Passed
Pull Request — master (#6650)
by
unknown
08:10
created

Display::getFlash()   C

Complexity

Conditions 12
Paths 66

Size

Total Lines 38
Code Lines 27

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 12
eloc 27
nc 66
nop 0
dl 0
loc 38
rs 6.9666
c 0
b 0
f 0

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
/* For licensing terms, see /license.txt */
4
5
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...
6
use Chamilo\CoreBundle\Entity\ExtraFieldValues;
7
use Chamilo\CoreBundle\Enums\ActionIcon;
8
use Chamilo\CoreBundle\Enums\ObjectIcon;
9
use Chamilo\CoreBundle\Enums\StateIcon;
10
use Chamilo\CoreBundle\Enums\ToolIcon;
11
use Chamilo\CoreBundle\Framework\Container;
12
use Chamilo\CoreBundle\Helpers\ThemeHelper;
13
use ChamiloSession as Session;
14
use Symfony\Component\HttpFoundation\Response;
15
16
/**
17
 * Class Display
18
 * Contains several public functions dealing with the display of
19
 * table data, messages, help topics, ...
20
 *
21
 * Include/require it in your code to use its public functionality.
22
 * There are also several display public functions in the main api library.
23
 *
24
 * All public functions static public functions inside a class called Display,
25
 * so you use them like this: e.g.
26
 * Display::return_message($message)
27
 */
28
class Display
29
{
30
    /** @var Template */
31
    public static $global_template;
32
    public static $preview_style = null;
33
    public static $legacyTemplate;
34
35
    public function __construct()
36
    {
37
    }
38
39
    /**
40
     * @return array
41
     */
42
    public static function toolList()
43
    {
44
        return [
45
            'group',
46
            'work',
47
            'glossary',
48
            'forum',
49
            'course_description',
50
            'gradebook',
51
            'attendance',
52
            'course_progress',
53
            'notebook',
54
        ];
55
    }
56
57
    /**
58
     * Displays the page header.
59
     *
60
     * @param string The name of the page (will be showed in the page title)
61
     * @param string Optional help file name
62
     * @param string $page_header
63
     */
64
    public static function display_header(
65
        $tool_name = '',
66
        $help = null,
67
        $page_header = null
68
    ) {
69
        global $interbreadcrumb;
70
        $interbreadcrumb[] = ['url' => '#', 'name' => $tool_name];
71
72
        ob_start();
73
74
        return true;
75
    }
76
77
    /**
78
     * Displays the reduced page header (without banner).
79
     */
80
    public static function display_reduced_header()
81
    {
82
        ob_start();
83
        self::$legacyTemplate = '@ChamiloCore/Layout/no_layout.html.twig';
84
85
        return true;
86
    }
87
88
    /**
89
     * Display no header.
90
     */
91
    public static function display_no_header()
92
    {
93
        global $tool_name, $show_learnpath;
94
        self::$global_template = new Template(
95
            $tool_name,
96
            false,
97
            false,
98
            $show_learnpath
99
        );
100
    }
101
102
    /**
103
     * Display the page footer.
104
     */
105
    public static function display_footer()
106
    {
107
        $contents = ob_get_contents();
108
        if (ob_get_length()) {
109
            ob_end_clean();
110
        }
111
        $tpl = '@ChamiloCore/Layout/layout_one_col.html.twig';
112
        if (!empty(self::$legacyTemplate)) {
113
            $tpl = self::$legacyTemplate;
114
        }
115
        $response = new Response();
116
        $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...
117
        global $interbreadcrumb, $htmlHeadXtra;
118
119
        $courseInfo = api_get_course_info();
120
        if (!empty($courseInfo)) {
121
            $url = $courseInfo['course_public_url'];
122
            $sessionId = api_get_session_id();
123
            if (!empty($sessionId)) {
124
                $url .= '?sid='.$sessionId;
125
            }
126
127
            if (!empty($interbreadcrumb)) {
128
                array_unshift(
129
                    $interbreadcrumb,
130
                    ['name' => $courseInfo['title'], 'url' => $url]
131
                );
132
            }
133
        }
134
135
        if (empty($interbreadcrumb)) {
136
            $interbreadcrumb = [];
137
        } else {
138
            $interbreadcrumb = array_filter(
139
                $interbreadcrumb,
140
                function ($item) {
141
                    return isset($item['name']) && !empty($item['name']);
142
                }
143
            );
144
        }
145
146
        $params['legacy_javascript'] = $htmlHeadXtra;
147
        $params['legacy_breadcrumb'] = json_encode(array_values($interbreadcrumb));
148
149
        Template::setVueParams($params);
150
        $content = Container::getTwig()->render($tpl, $params);
151
        $response->setContent($content);
152
        $response->send();
153
        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...
154
    }
155
156
    /**
157
     * Display the page footer.
158
     */
159
    public static function display_reduced_footer()
160
    {
161
        return self::display_footer();
0 ignored issues
show
Bug introduced by
Are you sure the usage of self::display_footer() targeting Display::display_footer() 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...
162
    }
163
164
    /**
165
     * Displays the tool introduction of a tool.
166
     *
167
     * @author Patrick Cool <[email protected]>, Ghent University
168
     *
169
     * @param string $tool          these are the constants that are used for indicating the tools
170
     * @param array  $editor_config Optional configuration settings for the online editor.
171
     *                              return: $tool return a string array list with the "define" in main_api.lib
172
     *
173
     * @return string html code for adding an introduction
174
     */
175
    public static function display_introduction_section(
176
        $tool,
177
        $editor_config = null
178
    ) {
179
        // @todo replace introduction section with a vue page.
180
        return;
181
    }
182
183
    /**
184
     * @param string $tool
185
     * @param array  $editor_config
186
     */
187
    public static function return_introduction_section(
188
        $tool,
189
        $editor_config = null
190
    ) {
191
    }
192
193
    /**
194
     * Displays a table.
195
     *
196
     * @param array  $header          Titles for the table header
197
     *                                each item in this array can contain 3 values
198
     *                                - 1st element: the column title
199
     *                                - 2nd element: true or false (column sortable?)
200
     *                                - 3th element: additional attributes for
201
     *                                th-tag (eg for column-width)
202
     *                                - 4the element: additional attributes for the td-tags
203
     * @param array  $content         2D-array with the tables content
204
     * @param array  $sorting_options Keys are:
205
     *                                'column' = The column to use as sort-key
206
     *                                'direction' = SORT_ASC or SORT_DESC
207
     * @param array  $paging_options  Keys are:
208
     *                                'per_page_default' = items per page when switching from
209
     *                                full-    list to per-page-view
210
     *                                'per_page' = number of items to show per page
211
     *                                'page_nr' = The page to display
212
     * @param array  $query_vars      Additional variables to add in the query-string
213
     * @param array  $form_actions
214
     * @param string $style           The style that the table will show. You can set 'table' or 'grid'
215
     * @param string $tableName
216
     * @param string $tableId
217
     *
218
     * @author [email protected]
219
     */
220
    public static function display_sortable_table(
221
        $header,
222
        $content,
223
        $sorting_options = [],
224
        $paging_options = [],
225
        $query_vars = null,
226
        $form_actions = [],
227
        $style = 'table',
228
        $tableName = 'tablename',
229
        $tableId = ''
230
    ) {
231
        $column = $sorting_options['column'] ?? 0;
232
        $default_items_per_page = $paging_options['per_page'] ?? 20;
233
        $table = new SortableTableFromArray($content, $column, $default_items_per_page, $tableName, null, $tableId);
234
        if (is_array($query_vars)) {
235
            $table->set_additional_parameters($query_vars);
236
        }
237
        if ('table' === $style) {
238
            if (is_array($header) && count($header) > 0) {
239
                foreach ($header as $index => $header_item) {
240
                    $table->set_header(
241
                        $index,
242
                        isset($header_item[0]) ? $header_item[0] : null,
243
                        isset($header_item[1]) ? $header_item[1] : null,
244
                        isset($header_item[2]) ? $header_item[2] : null,
245
                        isset($header_item[3]) ? $header_item[3] : null
246
                    );
247
                }
248
            }
249
            $table->set_form_actions($form_actions);
250
            $table->display();
251
        } else {
252
            $table->display_grid();
253
        }
254
    }
255
256
    /**
257
     * Returns an HTML table with sortable column (through complete page refresh).
258
     *
259
     * @param array  $header
260
     * @param array  $content         Array of row arrays
261
     * @param array  $sorting_options
262
     * @param array  $paging_options
263
     * @param array  $query_vars
264
     * @param array  $form_actions
265
     * @param string $style
266
     *
267
     * @return string HTML string for array
268
     */
269
    public static function return_sortable_table(
270
        $header,
271
        $content,
272
        $sorting_options = [],
273
        $paging_options = [],
274
        $query_vars = null,
275
        $form_actions = [],
276
        $style = 'table'
277
    ) {
278
        ob_start();
279
        self::display_sortable_table(
280
            $header,
281
            $content,
282
            $sorting_options,
283
            $paging_options,
284
            $query_vars,
285
            $form_actions,
286
            $style
287
        );
288
        $content = ob_get_contents();
289
        ob_end_clean();
290
291
        return $content;
292
    }
293
294
    /**
295
     * Shows a nice grid.
296
     *
297
     * @param string grid name (important to create css)
298
     * @param array header content
299
     * @param array array with the information to show
300
     * @param array $paging_options Keys are:
301
     *                              'per_page_default' = items per page when switching from
302
     *                              full-    list to per-page-view
303
     *                              'per_page' = number of items to show per page
304
     *                              'page_nr' = The page to display
305
     *                              'hide_navigation' =  true to hide the navigation
306
     * @param array $query_vars     Additional variables to add in the query-string
307
     * @param mixed An array with bool values to know which columns show.
308
     * i.e: $visibility_options= array(true, false) we will only show the first column
309
     *                Can be also only a bool value. TRUE: show all columns, FALSE: show nothing
310
     */
311
    public static function display_sortable_grid(
312
        $name,
313
        $header,
314
        $content,
315
        $paging_options = [],
316
        $query_vars = null,
317
        $form_actions = [],
318
        $visibility_options = true,
319
        $sort_data = true,
320
        $grid_class = []
321
    ) {
322
        echo self::return_sortable_grid(
323
            $name,
324
            $header,
325
            $content,
326
            $paging_options,
327
            $query_vars,
328
            $form_actions,
329
            $visibility_options,
330
            $sort_data,
331
            $grid_class
332
        );
333
    }
334
335
    /**
336
     * Gets a nice grid in html string.
337
     *
338
     * @param string grid name (important to create css)
339
     * @param array header content
340
     * @param array array with the information to show
341
     * @param array $paging_options Keys are:
342
     *                              'per_page_default' = items per page when switching from
343
     *                              full-    list to per-page-view
344
     *                              'per_page' = number of items to show per page
345
     *                              'page_nr' = The page to display
346
     *                              'hide_navigation' =  true to hide the navigation
347
     * @param array $query_vars     Additional variables to add in the query-string
348
     * @param mixed An array with bool values to know which columns show. i.e:
349
     *  $visibility_options= array(true, false) we will only show the first column
350
     *    Can be also only a bool value. TRUE: show all columns, FALSE: show nothing
351
     * @param bool  true for sorting data or false otherwise
352
     * @param array grid classes
353
     *
354
     * @return string html grid
355
     */
356
    public static function return_sortable_grid(
357
        $name,
358
        $header,
359
        $content,
360
        $paging_options = [],
361
        $query_vars = null,
362
        $form_actions = [],
363
        $visibility_options = true,
364
        $sort_data = true,
365
        $grid_class = [],
366
        $elementCount = 0
367
    ) {
368
        $column = 0;
369
        $default_items_per_page = $paging_options['per_page'] ?? 20;
370
        $table = new SortableTableFromArray($content, $column, $default_items_per_page, $name);
371
        $table->total_number_of_items = (int) $elementCount;
372
        if (is_array($query_vars)) {
373
            $table->set_additional_parameters($query_vars);
374
        }
375
376
        return $table->display_simple_grid(
377
            $visibility_options,
378
            $paging_options['hide_navigation'],
379
            $default_items_per_page,
380
            $sort_data,
381
            $grid_class
382
        );
383
    }
384
385
    /**
386
     * Displays a table with a special configuration.
387
     *
388
     * @param array $header          Titles for the table header
389
     *                               each item in this array can contain 3 values
390
     *                               - 1st element: the column title
391
     *                               - 2nd element: true or false (column sortable?)
392
     *                               - 3th element: additional attributes for th-tag (eg for column-width)
393
     *                               - 4the element: additional attributes for the td-tags
394
     * @param array $content         2D-array with the tables content
395
     * @param array $sorting_options Keys are:
396
     *                               'column' = The column to use as sort-key
397
     *                               'direction' = SORT_ASC or SORT_DESC
398
     * @param array $paging_options  Keys are:
399
     *                               'per_page_default' = items per page when switching from full list to per-page-view
400
     *                               'per_page' = number of items to show per page
401
     *                               'page_nr' = The page to display
402
     * @param array $query_vars      Additional variables to add in the query-string
403
     * @param array $column_show     Array of binaries 1= show columns 0. hide a column
404
     * @param array $column_order    An array of integers that let us decide how the columns are going to be sort.
405
     *                               i.e:  $column_order=array('1''4','3','4'); The 2nd column will be order like the 4th column
406
     * @param array $form_actions    Set optional forms actions
407
     *
408
     * @author Julio Montoya
409
     */
410
    public static function display_sortable_config_table(
411
        $table_name,
412
        $header,
413
        $content,
414
        $sorting_options = [],
415
        $paging_options = [],
416
        $query_vars = null,
417
        $column_show = [],
418
        $column_order = [],
419
        $form_actions = []
420
    ) {
421
        $column = isset($sorting_options['column']) ? $sorting_options['column'] : 0;
422
        $default_items_per_page = isset($paging_options['per_page']) ? $paging_options['per_page'] : 20;
423
424
        $table = new SortableTableFromArrayConfig(
425
            $content,
426
            $column,
427
            $default_items_per_page,
428
            $table_name,
429
            $column_show,
430
            $column_order
431
        );
432
433
        if (is_array($query_vars)) {
434
            $table->set_additional_parameters($query_vars);
435
        }
436
        // Show or hide the columns header
437
        if (is_array($column_show)) {
438
            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...
439
                if (!empty($column_show[$i])) {
440
                    $val0 = isset($header[$i][0]) ? $header[$i][0] : null;
441
                    $val1 = isset($header[$i][1]) ? $header[$i][1] : null;
442
                    $val2 = isset($header[$i][2]) ? $header[$i][2] : null;
443
                    $val3 = isset($header[$i][3]) ? $header[$i][3] : null;
444
                    $table->set_header($i, $val0, $val1, $val2, $val3);
445
                }
446
            }
447
        }
448
        $table->set_form_actions($form_actions);
449
        $table->display();
450
    }
451
452
    /**
453
     * Returns a div html string with.
454
     *
455
     * @param string $message
456
     * @param string $type    Example: confirm, normal, warning, error
457
     * @param bool $filter  Whether to XSS-filter or not
458
     *
459
     * @return string Message wrapped into an HTML div
460
     */
461
    public static function return_message(string $message, string $type = 'normal', bool $filter = true): string
462
    {
463
        if (empty($message)) {
464
            return '';
465
        }
466
467
        if ($filter) {
468
            $message = api_htmlentities(
469
                $message,
470
                ENT_QUOTES
471
            );
472
        }
473
474
        $class = '';
475
        switch ($type) {
476
            case 'warning':
477
                $class .= 'alert alert-warning';
478
                break;
479
            case 'error':
480
                $class .= 'alert alert-danger';
481
                break;
482
            case 'confirmation':
483
            case 'confirm':
484
            case 'success':
485
                $class .= 'alert alert-success';
486
                break;
487
            case 'normal':
488
            case 'info':
489
            default:
490
                $class .= 'alert alert-info';
491
        }
492
493
        return self::div($message, ['class' => $class]);
494
    }
495
496
    /**
497
     * Returns an encrypted mailto hyperlink.
498
     *
499
     * @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...
500
     * @param string  clickable text
501
     * @param string  optional, class from stylesheet
502
     * @param bool $addExtraContent
503
     *
504
     * @return string encrypted mailto hyperlink
505
     */
506
    public static function encrypted_mailto_link(
507
        $email,
508
        $clickable_text = null,
509
        $style_class = '',
510
        $addExtraContent = false
511
    ) {
512
        if (is_null($clickable_text)) {
513
            $clickable_text = $email;
514
        }
515
516
        // "mailto:" already present?
517
        if ('mailto:' !== substr($email, 0, 7)) {
518
            $email = 'mailto:'.$email;
519
        }
520
521
        // Class (stylesheet) defined?
522
        if ('' !== $style_class) {
523
            $style_class = ' class="'.$style_class.'"';
524
        }
525
526
        // Encrypt email
527
        $hmail = '';
528
        for ($i = 0; $i < strlen($email); $i++) {
529
            $hmail .= '&#'.ord($email[$i]).';';
530
        }
531
532
        $value = ('true' === api_get_setting('profile.add_user_course_information_in_mailto'));
533
534
        if ($value) {
535
            if ('false' === api_get_setting('allow_email_editor')) {
536
                $hmail .= '?';
537
            }
538
539
            if (!api_is_anonymous()) {
540
                $hmail .= '&subject='.Security::remove_XSS(api_get_setting('siteName'));
541
            }
542
            if ($addExtraContent) {
543
                $content = '';
544
                if (!api_is_anonymous()) {
545
                    $userInfo = api_get_user_info();
546
                    $content .= get_lang('User').': '.$userInfo['complete_name']."\n";
547
548
                    $courseInfo = api_get_course_info();
549
                    if (!empty($courseInfo)) {
550
                        $content .= get_lang('Course').': ';
551
                        $content .= $courseInfo['name'];
552
                        $sessionInfo = api_get_session_info(api_get_session_id());
553
                        if (!empty($sessionInfo)) {
554
                            $content .= ' '.$sessionInfo['name'].' <br />';
555
                        }
556
                    }
557
                }
558
                $hmail .= '&body='.rawurlencode($content);
559
            }
560
        }
561
562
        $hclickable_text = '';
563
        // Encrypt clickable text if @ is present
564
        if (strpos($clickable_text, '@')) {
565
            for ($i = 0; $i < strlen($clickable_text); $i++) {
566
                $hclickable_text .= '&#'.ord($clickable_text[$i]).';';
567
            }
568
        } else {
569
            $hclickable_text = @htmlspecialchars(
570
                $clickable_text,
571
                ENT_QUOTES,
572
                api_get_system_encoding()
573
            );
574
        }
575
        // Return encrypted mailto hyperlink
576
        return '<a href="'.$hmail.'"'.$style_class.' class="clickable_email_link">'.$hclickable_text.'</a>';
577
    }
578
579
    /**
580
     * Prints an <option>-list with all letters (A-Z).
581
     *
582
     * @todo This is English language specific implementation.
583
     * It should be adapted for the other languages.
584
     *
585
     * @return string
586
     */
587
    public static function get_alphabet_options($selectedLetter = '')
588
    {
589
        $result = '';
590
        for ($i = 65; $i <= 90; $i++) {
591
            $letter = chr($i);
592
            $result .= '<option value="'.$letter.'"';
593
            if ($selectedLetter == $letter) {
594
                $result .= ' selected="selected"';
595
            }
596
            $result .= '>'.$letter.'</option>';
597
        }
598
599
        return $result;
600
    }
601
602
    /**
603
     * Get the options withing a select box within the given values.
604
     *
605
     * @param int   Min value
606
     * @param int   Max value
607
     * @param int   Default value
608
     *
609
     * @return string HTML select options
610
     */
611
    public static function get_numeric_options($min, $max, $selected_num = 0)
612
    {
613
        $result = '';
614
        for ($i = $min; $i <= $max; $i++) {
615
            $result .= '<option value="'.$i.'"';
616
            if (is_int($selected_num)) {
617
                if ($selected_num == $i) {
618
                    $result .= ' selected="selected"';
619
                }
620
            }
621
            $result .= '>'.$i.'</option>';
622
        }
623
624
        return $result;
625
    }
626
627
    /**
628
     * Gets the path of an icon.
629
     *
630
     * @param string $icon
631
     * @param int    $size
632
     *
633
     * @return string
634
     */
635
    public static function returnIconPath($icon, $size = ICON_SIZE_SMALL)
636
    {
637
        return self::return_icon($icon, null, null, $size, null, true, false);
638
    }
639
640
    /**
641
     * This public function returns the htmlcode for an icon.
642
     *
643
     * @param string   The filename of the file (in the main/img/ folder
644
     * @param string   The alt text (probably a language variable)
645
     * @param array    Additional attributes (for instance height, width, onclick, ...)
646
     * @param int  The wanted width of the icon (to be looked for in the corresponding img/icons/ folder)
647
     *
648
     * @return string An HTML string of the right <img> tag
649
     *
650
     * @author Patrick Cool <[email protected]>, Ghent University 2006
651
     * @author Julio Montoya 2010 Function improved, adding image constants
652
     * @author Yannick Warnier 2011 Added size handler
653
     *
654
     * @version Feb 2011
655
     */
656
    public static function return_icon(
657
        string $image,
658
        ?string $alt_text = '',
659
        ?array $additional_attributes = [],
660
        ?int $size = ICON_SIZE_SMALL,
661
        ?bool $show_text = true,
662
        ?bool $return_only_path = false,
663
        ?bool $loadThemeIcon = true
664
    ) {
665
        $code_path = api_get_path(SYS_PUBLIC_PATH);
666
        $w_code_path = api_get_path(WEB_PUBLIC_PATH);
667
        // The following path is checked to see if the file exist. It's
668
        // important to use the public path (i.e. web/css/) rather than the
669
        // internal path (/app/Resource/public/css/) because the path used
670
        // in the end must be the public path
671
        $alternateCssPath = api_get_path(SYS_PUBLIC_PATH).'css/';
672
        $alternateWebCssPath = api_get_path(WEB_PUBLIC_PATH).'css/';
673
674
        // Avoid issues with illegal string offset for legacy calls to this
675
        // method with an empty string rather than null or an empty array
676
        if (empty($additional_attributes)) {
677
            $additional_attributes = [];
678
        }
679
680
        $image = trim($image);
681
682
        if (isset($size)) {
683
            $size = (int) $size;
684
        } else {
685
            $size = ICON_SIZE_SMALL;
686
        }
687
688
        $size_extra = $size.'/';
689
        $icon = $w_code_path.'img/'.$image;
690
        $theme = 'themes/chamilo/icons/';
691
692
        if ($loadThemeIcon) {
693
            // @todo with chamilo 2 code
694
            $theme = 'themes/'.api_get_visual_theme().'/icons/';
695
            if (is_file($alternateCssPath.$theme.$image)) {
696
                $icon = $alternateWebCssPath.$theme.$image;
697
            }
698
            // Checking the theme icons folder example: var/themes/chamilo/icons/XXX
699
            if (is_file($alternateCssPath.$theme.$size_extra.$image)) {
700
                $icon = $alternateWebCssPath.$theme.$size_extra.$image;
701
            } elseif (is_file($code_path.'img/icons/'.$size_extra.$image)) {
702
                //Checking the main/img/icons/XXX/ folder
703
                $icon = $w_code_path.'img/icons/'.$size_extra.$image;
704
            }
705
        } else {
706
            if (is_file($code_path.'img/icons/'.$size_extra.$image)) {
707
                // Checking the main/img/icons/XXX/ folder
708
                $icon = $w_code_path.'img/icons/'.$size_extra.$image;
709
            }
710
        }
711
712
        // Special code to enable SVG - refs #7359 - Needs more work
713
        // The code below does something else to "test out" SVG: for each icon,
714
        // it checks if there is an SVG version. If so, it uses it.
715
        // When moving this to production, the return_icon() calls should
716
        // ask for the SVG version directly
717
        $svgIcons = api_get_setting('icons_mode_svg');
718
        if ('true' == $svgIcons && false == $return_only_path) {
719
            $svgImage = substr($image, 0, -3).'svg';
720
            if (is_file($code_path.$theme.'svg/'.$svgImage)) {
721
                $icon = $w_code_path.$theme.'svg/'.$svgImage;
722
            } elseif (is_file($code_path.'img/icons/svg/'.$svgImage)) {
723
                $icon = $w_code_path.'img/icons/svg/'.$svgImage;
724
            }
725
726
            if (empty($additional_attributes['height'])) {
727
                $additional_attributes['height'] = $size;
728
            }
729
            if (empty($additional_attributes['width'])) {
730
                $additional_attributes['width'] = $size;
731
            }
732
        }
733
734
        if ($return_only_path) {
735
            return $icon;
736
        }
737
738
        $img = self::img($icon, $alt_text, $additional_attributes);
739
        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...
740
            if ($show_text) {
741
                $img = "$img $alt_text";
742
            }
743
        }
744
745
        return $img;
746
    }
747
748
    /**
749
     * Returns the htmlcode for an image.
750
     *
751
     * @param string $image_path            the filename of the file (in the main/img/ folder
752
     * @param string $alt_text              the alt text (probably a language variable)
753
     * @param array  $additional_attributes (for instance height, width, onclick, ...)
754
     * @param bool   $filterPath            Optional. Whether filter the image path. Default is true
755
     *
756
     * @return string
757
     *
758
     * @author Julio Montoya 2010
759
     */
760
    public static function img(
761
        $image_path,
762
        $alt_text = '',
763
        $additional_attributes = null,
764
        $filterPath = true
765
    ) {
766
        if (empty($image_path)) {
767
            return '';
768
        }
769
        // Sanitizing the parameter $image_path
770
        if ($filterPath) {
771
            $image_path = Security::filter_img_path($image_path);
772
        }
773
774
        // alt text = the image name if there is none provided (for XHTML compliance)
775
        if ('' == $alt_text) {
776
            $alt_text = basename($image_path);
777
        }
778
779
        if (empty($additional_attributes)) {
780
            $additional_attributes = [];
781
        }
782
783
        $additional_attributes['src'] = $image_path;
784
785
        if (empty($additional_attributes['alt'])) {
786
            $additional_attributes['alt'] = $alt_text;
787
        }
788
        if (empty($additional_attributes['title'])) {
789
            $additional_attributes['title'] = $alt_text;
790
        }
791
792
        return self::tag('img', '', $additional_attributes);
793
    }
794
795
    /**
796
     * Returns the htmlcode for a tag (h3, h1, div, a, button), etc.
797
     *
798
     * @param string $tag                   the tag name
799
     * @param string $content               the tag's content
800
     * @param array  $additional_attributes (for instance height, width, onclick, ...)
801
     *
802
     * @return string
803
     *
804
     * @author Julio Montoya 2010
805
     */
806
    public static function tag($tag, $content, $additional_attributes = [])
807
    {
808
        $attribute_list = '';
809
        // Managing the additional attributes
810
        if (!empty($additional_attributes) && is_array($additional_attributes)) {
811
            $attribute_list = '';
812
            foreach ($additional_attributes as $key => &$value) {
813
                $attribute_list .= $key.'="'.$value.'" ';
814
            }
815
        }
816
        //some tags don't have this </XXX>
817
        if (in_array($tag, ['img', 'input', 'br'])) {
818
            $return_value = '<'.$tag.' '.$attribute_list.' />';
819
        } else {
820
            $return_value = '<'.$tag.' '.$attribute_list.' >'.$content.'</'.$tag.'>';
821
        }
822
823
        return $return_value;
824
    }
825
826
    /**
827
     * Creates a URL anchor.
828
     *
829
     * @param string $name
830
     * @param string $url
831
     * @param array  $attributes
832
     *
833
     * @return string
834
     */
835
    public static function url($name, $url, $attributes = [])
836
    {
837
        if (!empty($url)) {
838
            $url = preg_replace('#&amp;#', '&', $url);
839
            $url = htmlspecialchars($url, ENT_QUOTES, 'UTF-8');
840
            $attributes['href'] = $url;
841
        }
842
843
        return self::tag('a', $name, $attributes);
844
    }
845
846
    /**
847
     * Creates a div tag.
848
     *
849
     * @param string $content
850
     * @param array  $attributes
851
     *
852
     * @return string
853
     */
854
    public static function div($content, $attributes = [])
855
    {
856
        return self::tag('div', $content, $attributes);
857
    }
858
859
    /**
860
     * Creates a span tag.
861
     */
862
    public static function span($content, $attributes = [])
863
    {
864
        return self::tag('span', $content, $attributes);
865
    }
866
867
    /**
868
     * Displays an HTML input tag.
869
     */
870
    public static function input($type, $name, $value, $attributes = [])
871
    {
872
        if (isset($type)) {
873
            $attributes['type'] = $type;
874
        }
875
        if (isset($name)) {
876
            $attributes['name'] = $name;
877
        }
878
        if (isset($value)) {
879
            $attributes['value'] = $value;
880
        }
881
882
        if ('text' === $type) {
883
            $attributes['class'] = isset($attributes['class'])
884
                ? $attributes['class'].' p-inputtext p-component '
885
                : 'p-inputtext p-component ';
886
        }
887
888
        return self::tag('input', '', $attributes);
889
    }
890
891
    /**
892
     * Displays an HTML select tag.
893
     */
894
    public static function select(
895
        string $name,
896
        array $values,
897
        mixed $default = -1,
898
        array $extra_attributes = [],
899
        bool $show_blank_item = true,
900
        string $blank_item_text = ''
901
    ): string {
902
        $html = '';
903
        $extra = '';
904
        $default_id = 'id="'.$name.'" ';
905
        $extra_attributes = array_merge(
906
            ['class' => 'p-select p-component p-inputwrapper p-inputwrapper-filled'],
907
            $extra_attributes
908
        );
909
        foreach ($extra_attributes as $key => $parameter) {
910
            if ('id' == $key) {
911
                $default_id = '';
912
            }
913
            $extra .= $key.'="'.$parameter.'" ';
914
        }
915
        $html .= '<select name="'.$name.'" '.$default_id.' '.$extra.'>';
916
917
        if ($show_blank_item) {
918
            if (empty($blank_item_text)) {
919
                $blank_item_text = get_lang('Select');
920
            } else {
921
                $blank_item_text = Security::remove_XSS($blank_item_text);
922
            }
923
            $html .= self::tag(
924
                'option',
925
                '-- '.$blank_item_text.' --',
926
                ['value' => '-1']
927
            );
928
        }
929
        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...
930
            foreach ($values as $key => $value) {
931
                if (is_array($value) && isset($value['name'])) {
932
                    $value = $value['name'];
933
                }
934
                $html .= '<option value="'.$key.'"';
935
936
                if (is_array($default)) {
937
                    foreach ($default as $item) {
938
                        if ($item == $key) {
939
                            $html .= ' selected="selected"';
940
                            break;
941
                        }
942
                    }
943
                } else {
944
                    if ($default == $key) {
945
                        $html .= ' selected="selected"';
946
                    }
947
                }
948
949
                $html .= '>'.$value.'</option>';
950
            }
951
        }
952
        $html .= '</select>';
953
954
        return $html;
955
    }
956
957
    /**
958
     * @param $name
959
     * @param $value
960
     * @param array $attributes
961
     *
962
     * @return string
963
     */
964
    public static function button($name, $value, $attributes = [])
965
    {
966
        if (!empty($name)) {
967
            $attributes['name'] = $name;
968
        }
969
970
        return self::tag('button', $value, $attributes);
971
    }
972
973
    /**
974
     * Creates a tab menu
975
     * Requirements: declare the jquery, jquery-ui libraries + the jquery-ui.css
976
     * in the $htmlHeadXtra variable before the display_header
977
     * Add this script.
978
     *
979
     * @param array  $headers       list of the tab titles
980
     * @param array  $items
981
     * @param string $id            id of the container of the tab in the example "tabs"
982
     * @param array  $attributes    for the ul
983
     * @param array  $ul_attributes
984
     * @param string $selected
985
     *
986
     * @return string
987
     */
988
    public static function tabs(
989
        $headers,
990
        $items,
991
        $id = 'tabs',
992
        $attributes = [],
993
        $ul_attributes = [],
994
        $selected = ''
995
    ) {
996
        if (empty($headers) || 0 === count($headers)) {
997
            return '';
998
        }
999
1000
        $lis = '';
1001
        $i = 1;
1002
        foreach ($headers as $item) {
1003
            $active = '';
1004
            if (1 == $i) {
1005
                $active = ' active';
1006
            }
1007
1008
            if (!empty($selected)) {
1009
                $active = '';
1010
                if ($selected == $i) {
1011
                    $active = ' active';
1012
                }
1013
            }
1014
1015
            $item = self::tag(
1016
                'a',
1017
                $item,
1018
                [
1019
                    //'href' => '#'.$id.'-'.$i,
1020
                    'href' => 'javascript:void(0)',
1021
                    'class' => 'nav-item nav-link '.$active,
1022
                    '@click' => "openTab =  $i",
1023
                    'id' => $id.$i.'-tab',
1024
                    'data-toggle' => 'tab',
1025
                    'role' => 'tab',
1026
                    'aria-controls' => $id.'-'.$i,
1027
                    'aria-selected' => $selected,
1028
                ]
1029
            );
1030
            $lis .= $item;
1031
            $i++;
1032
        }
1033
1034
        $ul = self::tag(
1035
            'nav',
1036
            $lis,
1037
            [
1038
                'id' => 'nav_'.$id,
1039
                'class' => 'nav nav-tabs',
1040
                'role' => 'tablist',
1041
            ]
1042
        );
1043
1044
        $i = 1;
1045
        $divs = '';
1046
        foreach ($items as $content) {
1047
            $active = '';
1048
            if (1 == $i) {
1049
                $active = ' show active';
1050
            }
1051
1052
            if (!empty($selected)) {
1053
                $active = '';
1054
                if ($selected == $i) {
1055
                    $active = ' show active';
1056
                }
1057
            }
1058
1059
            $divs .= self::tag(
1060
                'div',
1061
                $content,
1062
                [
1063
                    'id' => $id.'-'.$i,
1064
                    'x-show' => "openTab === $i",
1065
                    //'class' => 'tab-pane fade '.$active,
1066
                    //'role' => 'tabpanel',
1067
                    //'aria-labelledby' => $id.$i.'-tab',
1068
                ]
1069
            );
1070
            $i++;
1071
        }
1072
1073
        $attributes['id'] = ''.$id;
1074
        if (empty($attributes['class'])) {
1075
            $attributes['class'] = '';
1076
        }
1077
        $attributes['class'] .= ' tab_wrapper ';
1078
        $attributes['x-data'] = ' { openTab: 1 } ';
1079
1080
        return self::tag(
1081
            'div',
1082
            $ul.
1083
            $divs,
1084
            $attributes
1085
        );
1086
    }
1087
1088
    /**
1089
     * @param $headers
1090
     * @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...
1091
     *
1092
     * @return string
1093
     */
1094
    public static function tabsOnlyLink($headers, $selected = null, string $tabList = '')
1095
    {
1096
        $id = uniqid('tabs_');
1097
        $list = '';
1098
1099
        if ('integer' === gettype($selected)) {
1100
            $selected -= 1;
1101
        }
1102
1103
        foreach ($headers as $key => $item) {
1104
            $class = null;
1105
            if ($key == $selected) {
1106
                $class = 'active';
1107
            }
1108
            $item = self::tag(
1109
                'a',
1110
                $item['content'],
1111
                [
1112
                    'id' => $id.'-'.$key,
1113
                    'href' => $item['url'],
1114
                    'class' => 'nav-link '.$class,
1115
                ]
1116
            );
1117
            $list .= '<li class="nav-item">'.$item.'</li>';
1118
        }
1119
1120
        return self::div(
1121
            self::tag(
1122
                'ul',
1123
                $list,
1124
                ['class' => 'nav nav-tabs']
1125
            ),
1126
            ['class' => "ul-tablist $tabList"]
1127
        );
1128
    }
1129
1130
    /**
1131
     * In order to display a grid using jqgrid you have to:.
1132
     *
1133
     * @example
1134
     * After your Display::display_header function you have to add the nex javascript code:
1135
     * <script>
1136
     *   echo Display::grid_js('my_grid_name', $url,$columns, $column_model, $extra_params,[]);
1137
     *   // for more information of this function check the grid_js() function
1138
     * </script>
1139
     * //Then you have to call the grid_html
1140
     * echo Display::grid_html('my_grid_name');
1141
     * As you can see both function use the same "my_grid_name" this is very important otherwise nothing will work
1142
     *
1143
     * @param   string  the div id, this value must be the same with the first parameter of Display::grid_js()
1144
     *
1145
     * @return string html
1146
     */
1147
    public static function grid_html($div_id)
1148
    {
1149
        $table = self::tag('table', '', ['id' => $div_id]);
1150
        $table .= self::tag('div', '', ['id' => $div_id.'_pager']);
1151
1152
        return $table;
1153
    }
1154
1155
    /**
1156
     * This is a wrapper to use the jqgrid in Chamilo.
1157
     * For the other jqgrid options visit http://www.trirand.com/jqgridwiki/doku.php?id=wiki:options
1158
     * This function need to be in the ready jquery function
1159
     * example --> $(function() { <?php echo Display::grid_js('grid' ...); ?> }
1160
     * In order to work this function needs the Display::grid_html function with the same div id.
1161
     *
1162
     * @param string $div_id       div id
1163
     * @param string $url          url where the jqgrid will ask for data (if datatype = json)
1164
     * @param array  $column_names Visible columns (you should use get_lang).
1165
     *                             An array in which we place the names of the columns.
1166
     *                             This is the text that appears in the head of the grid (Header layer).
1167
     *                             Example: colname   {name:'date',     index:'date',   width:120, align:'right'},
1168
     * @param array  $column_model the column model :  Array which describes the parameters of the columns.
1169
     *                             This is the most important part of the grid.
1170
     *                             For a full description of all valid values see colModel API. See the url above.
1171
     * @param array  $extra_params extra parameters
1172
     * @param array  $data         data that will be loaded
1173
     * @param string $formatter    A string that will be appended to the JSON returned
1174
     * @param bool   $fixed_width  not implemented yet
1175
     *
1176
     * @return string the js code
1177
     */
1178
    public static function grid_js(
1179
        $div_id,
1180
        $url,
1181
        $column_names,
1182
        $column_model,
1183
        $extra_params,
1184
        $data = [],
1185
        $formatter = '',
1186
        $fixed_width = false
1187
    ) {
1188
        $obj = new stdClass();
1189
        $obj->first = 'first';
1190
1191
        if (!empty($url)) {
1192
            $obj->url = $url;
1193
        }
1194
1195
        // Needed it in order to render the links/html in the grid
1196
        foreach ($column_model as &$columnModel) {
1197
            if (!isset($columnModel['formatter'])) {
1198
                $columnModel['formatter'] = '';
1199
            }
1200
        }
1201
1202
        //This line should only be used/modified in case of having characters
1203
        // encoding problems - see #6159
1204
        //$column_names = array_map("utf8_encode", $column_names);
1205
        $obj->colNames = $column_names;
1206
        $obj->colModel = $column_model;
1207
        $obj->pager = '#'.$div_id.'_pager';
1208
        $obj->datatype = 'json';
1209
        $obj->viewrecords = 'true';
1210
        $obj->guiStyle = 'bootstrap4';
1211
        $obj->iconSet = 'materialDesignIcons';
1212
        $all_value = 10000000;
1213
1214
        // Sets how many records we want to view in the grid
1215
        $obj->rowNum = 20;
1216
1217
        // Default row quantity
1218
        if (!isset($extra_params['rowList'])) {
1219
            $defaultRowList = [20, 50, 100, 500, 1000, $all_value];
1220
            $rowList = api_get_setting('platform.table_row_list', true);
1221
            if (is_array($rowList) && isset($rowList['options']) && is_array($rowList['options'])) {
1222
                $rowList = $rowList['options'];
1223
                $rowList[] = $all_value;
1224
            } else {
1225
                $rowList = $defaultRowList;
1226
            }
1227
            $extra_params['rowList'] = $rowList;
1228
        }
1229
1230
        $defaultRow = (int) api_get_setting('platform.table_default_row');
1231
        if ($defaultRow > 0) {
1232
            $obj->rowNum = $defaultRow;
1233
        }
1234
1235
        $json = '';
1236
        if (!empty($extra_params['datatype'])) {
1237
            $obj->datatype = $extra_params['datatype'];
1238
        }
1239
1240
        // Row even odd style.
1241
        $obj->altRows = true;
1242
        if (!empty($extra_params['altRows'])) {
1243
            $obj->altRows = $extra_params['altRows'];
1244
        }
1245
1246
        if (!empty($extra_params['sortname'])) {
1247
            $obj->sortname = $extra_params['sortname'];
1248
        }
1249
1250
        if (!empty($extra_params['sortorder'])) {
1251
            $obj->sortorder = $extra_params['sortorder'];
1252
        }
1253
1254
        if (!empty($extra_params['rowList'])) {
1255
            $obj->rowList = $extra_params['rowList'];
1256
        }
1257
1258
        if (!empty($extra_params['rowNum'])) {
1259
            $obj->rowNum = $extra_params['rowNum'];
1260
        } else {
1261
            // Try to load max rows from Session
1262
            $urlInfo = parse_url($url);
1263
            if (isset($urlInfo['query'])) {
1264
                parse_str($urlInfo['query'], $query);
1265
                if (isset($query['a'])) {
1266
                    $action = $query['a'];
1267
                    // This value is set in model.ajax.php
1268
                    $savedRows = Session::read('max_rows_'.$action);
1269
                    if (!empty($savedRows)) {
1270
                        $obj->rowNum = $savedRows;
1271
                    }
1272
                }
1273
            }
1274
        }
1275
1276
        if (!empty($extra_params['viewrecords'])) {
1277
            $obj->viewrecords = $extra_params['viewrecords'];
1278
        }
1279
1280
        $beforeSelectRow = null;
1281
        if (isset($extra_params['beforeSelectRow'])) {
1282
            $beforeSelectRow = 'beforeSelectRow: '.$extra_params['beforeSelectRow'].', ';
1283
            unset($extra_params['beforeSelectRow']);
1284
        }
1285
1286
        $beforeProcessing = '';
1287
        if (isset($extra_params['beforeProcessing'])) {
1288
            $beforeProcessing = 'beforeProcessing : function() { '.$extra_params['beforeProcessing'].' },';
1289
            unset($extra_params['beforeProcessing']);
1290
        }
1291
1292
        $beforeRequest = '';
1293
        if (isset($extra_params['beforeRequest'])) {
1294
            $beforeRequest = 'beforeRequest : function() { '.$extra_params['beforeRequest'].' },';
1295
            unset($extra_params['beforeRequest']);
1296
        }
1297
1298
        $gridComplete = '';
1299
        if (isset($extra_params['gridComplete'])) {
1300
            $gridComplete = 'gridComplete : function() { '.$extra_params['gridComplete'].' },';
1301
            unset($extra_params['gridComplete']);
1302
        }
1303
1304
        // Adding extra params
1305
        if (!empty($extra_params)) {
1306
            foreach ($extra_params as $key => $element) {
1307
                // the groupHeaders key gets a special treatment
1308
                if ('groupHeaders' != $key) {
1309
                    $obj->$key = $element;
1310
                }
1311
            }
1312
        }
1313
1314
        // Adding static data.
1315
        if (!empty($data)) {
1316
            $data_var = $div_id.'_data';
1317
            $json .= ' var '.$data_var.' = '.json_encode($data).';';
1318
            $obj->data = $data_var;
1319
            $obj->datatype = 'local';
1320
            $json .= "\n";
1321
        }
1322
1323
        $obj->end = 'end';
1324
1325
        $json_encode = json_encode($obj);
1326
1327
        if (!empty($data)) {
1328
            //Converts the "data":"js_variable" to "data":js_variable,
1329
            // otherwise it will not work
1330
            $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...
1331
        }
1332
1333
        // Fixing true/false js values that doesn't need the ""
1334
        $json_encode = str_replace(':"true"', ':true', $json_encode);
1335
        // wrap_cell is not a valid jqgrid attributes is a hack to wrap a text
1336
        $json_encode = str_replace('"wrap_cell":true', 'cellattr : function(rowId, value, rowObject, colModel, arrData) { return \'class = "jqgrid_whitespace"\'; }', $json_encode);
1337
        $json_encode = str_replace(':"false"', ':false', $json_encode);
1338
        $json_encode = str_replace('"formatter":"action_formatter"', 'formatter:action_formatter', $json_encode);
1339
        $json_encode = str_replace('"formatter":"extra_formatter"', 'formatter:extra_formatter', $json_encode);
1340
        $json_encode = str_replace(['{"first":"first",', '"end":"end"}'], '', $json_encode);
1341
1342
        if (('true' === api_get_setting('document.allow_compilatio_tool')) &&
1343
            (false !== strpos($_SERVER['REQUEST_URI'], 'work/work.php') ||
1344
             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...
1345
            )
1346
        ) {
1347
            $json_encode = str_replace('"function () { compilatioInit() }"',
1348
                'function () { compilatioInit() }',
1349
                $json_encode
1350
            );
1351
        }
1352
        // Creating the jqgrid element.
1353
        $json .= '$("#'.$div_id.'").jqGrid({';
1354
        $json .= "autowidth: true,";
1355
        //$json .= $beforeSelectRow;
1356
        $json .= $gridComplete;
1357
        $json .= $beforeProcessing;
1358
        $json .= $beforeRequest;
1359
        $json .= $json_encode;
1360
        $json .= '});';
1361
1362
        // Grouping headers option
1363
        if (isset($extra_params['groupHeaders'])) {
1364
            $groups = '';
1365
            foreach ($extra_params['groupHeaders'] as $group) {
1366
                //{ "startColumnName" : "courses", "numberOfColumns" : 1, "titleText" : "Order Info" },
1367
                $groups .= '{ "startColumnName" : "'.$group['startColumnName'].'", "numberOfColumns" : '.$group['numberOfColumns'].', "titleText" : "'.$group['titleText'].'" },';
1368
            }
1369
            $json .= '$("#'.$div_id.'").jqGrid("setGroupHeaders", {
1370
                "useColSpanStyle" : false,
1371
                "groupHeaders"    : [
1372
                    '.$groups.'
1373
                ]
1374
            });';
1375
        }
1376
1377
        $all_text = addslashes(get_lang('All'));
1378
        $json .= '$("'.$obj->pager.' option[value='.$all_value.']").text("'.$all_text.'");';
1379
        $json .= "\n";
1380
        // Adding edit/delete icons.
1381
        $json .= $formatter;
1382
1383
        return $json;
1384
    }
1385
1386
    /**
1387
     * @param array $headers
1388
     * @param array $rows
1389
     * @param array $attributes
1390
     *
1391
     * @return string
1392
     */
1393
    public static function table($headers, $rows, $attributes = [])
1394
    {
1395
        if (empty($attributes)) {
1396
            $attributes['class'] = 'data_table';
1397
        }
1398
        $table = new HTML_Table($attributes);
1399
        $row = 0;
1400
        $column = 0;
1401
1402
        // Course headers
1403
        if (!empty($headers)) {
1404
            foreach ($headers as $item) {
1405
                $table->setHeaderContents($row, $column, $item);
1406
                $column++;
1407
            }
1408
            $row = 1;
1409
            $column = 0;
1410
        }
1411
1412
        if (!empty($rows)) {
1413
            foreach ($rows as $content) {
1414
                $table->setCellContents($row, $column, $content);
1415
                $row++;
1416
            }
1417
        }
1418
1419
        return $table->toHtml();
1420
    }
1421
1422
    /**
1423
     * Get the session box details as an array.
1424
     *
1425
     * @todo check session visibility.
1426
     *
1427
     * @param int $session_id
1428
     *
1429
     * @return array Empty array or session array
1430
     *               ['title'=>'...','category'=>'','dates'=>'...','coach'=>'...','active'=>true/false,'session_category_id'=>int]
1431
     */
1432
    public static function getSessionTitleBox($session_id)
1433
    {
1434
        $session_info = api_get_session_info($session_id);
1435
        $generalCoachesNames = implode(
1436
            ' - ',
1437
            SessionManager::getGeneralCoachesNamesForSession($session_id)
1438
        );
1439
1440
        $session = [];
1441
        $session['category_id'] = $session_info['session_category_id'];
1442
        $session['title'] = $session_info['name'];
1443
        $session['dates'] = '';
1444
        $session['coach'] = '';
1445
        if ('true' === api_get_setting('show_session_coach') && $generalCoachesNames) {
1446
            $session['coach'] = get_lang('General coach').': '.$generalCoachesNames;
1447
        }
1448
        $active = false;
1449
        if (('0000-00-00 00:00:00' === $session_info['access_end_date'] &&
1450
            '0000-00-00 00:00:00' === $session_info['access_start_date']) ||
1451
            (empty($session_info['access_end_date']) && empty($session_info['access_start_date']))
1452
        ) {
1453
            if (isset($session_info['duration']) && !empty($session_info['duration'])) {
1454
                $daysLeft = SessionManager::getDayLeftInSession($session_info, api_get_user_id());
1455
                $session['duration'] = $daysLeft >= 0
1456
                    ? sprintf(get_lang('This session has a maximum duration. Only %s days to go.'), $daysLeft)
1457
                    : get_lang('You are already registered but your allowed access time has expired.');
1458
            }
1459
            $active = true;
1460
        } else {
1461
            $dates = SessionManager::parseSessionDates($session_info, true);
1462
            $session['dates'] = $dates['access'];
1463
            //$active = $date_start <= $now && $date_end >= $now;
1464
        }
1465
        $session['active'] = $active;
1466
        $session['session_category_id'] = $session_info['session_category_id'];
1467
        $session['visibility'] = $session_info['visibility'];
1468
        $session['num_users'] = $session_info['nbr_users'];
1469
        $session['num_courses'] = $session_info['nbr_courses'];
1470
        $session['description'] = $session_info['description'];
1471
        $session['show_description'] = $session_info['show_description'];
1472
        //$session['image'] = SessionManager::getSessionImage($session_info['id']);
1473
        $session['url'] = api_get_path(WEB_CODE_PATH).'session/index.php?session_id='.$session_info['id'];
1474
1475
        $entityManager = Database::getManager();
1476
        $fieldValuesRepo = $entityManager->getRepository(ExtraFieldValues::class);
1477
        $extraFieldValues = $fieldValuesRepo->getVisibleValues(
1478
            ExtraField::SESSION_FIELD_TYPE,
1479
            $session_id
1480
        );
1481
1482
        $session['extra_fields'] = [];
1483
        /** @var ExtraFieldValues $value */
1484
        foreach ($extraFieldValues as $value) {
1485
            if (empty($value)) {
1486
                continue;
1487
            }
1488
            $session['extra_fields'][] = [
1489
                'field' => [
1490
                    'variable' => $value->getField()->getVariable(),
1491
                    'display_text' => $value->getField()->getDisplayText(),
1492
                ],
1493
                'value' => $value->getFieldValue(),
1494
            ];
1495
        }
1496
1497
        return $session;
1498
    }
1499
1500
    /**
1501
     * Return the five star HTML.
1502
     *
1503
     * @param string $id              of the rating ul element
1504
     * @param string $url             that will be added (for jquery see hot_courses.tpl)
1505
     * @param array  $point_info      point info array see function CourseManager::get_course_ranking()
1506
     * @param bool   $add_div_wrapper add a div wrapper
1507
     *
1508
     * @return string
1509
     */
1510
    public static function return_rating_system(
1511
        $id,
1512
        $url,
1513
        $point_info = [],
1514
        $add_div_wrapper = true
1515
    ) {
1516
        $number_of_users_who_voted = isset($point_info['users_who_voted']) ? $point_info['users_who_voted'] : null;
1517
        $percentage = isset($point_info['point_average']) ? $point_info['point_average'] : 0;
1518
1519
        if (!empty($percentage)) {
1520
            $percentage = $percentage * 125 / 100;
1521
        }
1522
        $accesses = isset($point_info['accesses']) ? $point_info['accesses'] : 0;
1523
        $star_label = sprintf(get_lang('%s stars out of 5'), $point_info['point_average_star']);
1524
1525
        $html = '<section class="rating-widget">';
1526
        $html .= '<div class="rating-stars"><ul id="stars">';
1527
        $html .= '<li class="star" data-link="'.$url.'&amp;star=1" title="Poor" data-value="1"><i class="fa fa-star fa-fw"></i></li>
1528
                 <li class="star" data-link="'.$url.'&amp;star=2" title="Fair" data-value="2"><i class="fa fa-star fa-fw"></i></li>
1529
                 <li class="star" data-link="'.$url.'&amp;star=3" title="Good" data-value="3"><i class="fa fa-star fa-fw"></i></li>
1530
                 <li class="star" data-link="'.$url.'&amp;star=4" title="Excellent" data-value="4"><i class="fa fa-star fa-fw"></i></li>
1531
                 <li class="star" data-link="'.$url.'&amp;star=5" title="WOW!!!" data-value="5"><i class="fa fa-star fa-fw"></i></li>
1532
        ';
1533
        $html .= '</ul></div>';
1534
        $html .= '</section>';
1535
        $labels = [];
1536
1537
        $labels[] = 1 == $number_of_users_who_voted ? $number_of_users_who_voted.' '.get_lang('Vote') : $number_of_users_who_voted.' '.get_lang('Votes');
1538
        $labels[] = 1 == $accesses ? $accesses.' '.get_lang('Visit') : $accesses.' '.get_lang('Visits');
1539
        $labels[] = $point_info['user_vote'] ? get_lang('Your vote').' ['.$point_info['user_vote'].']' : get_lang('Your vote').' [?] ';
1540
1541
        if (!$add_div_wrapper && api_is_anonymous()) {
1542
            $labels[] = self::tag('span', get_lang('Login to vote'), ['class' => 'error']);
1543
        }
1544
1545
        $html .= self::div(implode(' | ', $labels), ['id' => 'vote_label_'.$id, 'class' => 'vote_label_info']);
1546
        $html .= ' '.self::span(' ', ['id' => 'vote_label2_'.$id]);
1547
1548
        if ($add_div_wrapper) {
1549
            $html = self::div($html, ['id' => 'rating_wrapper_'.$id]);
1550
        }
1551
1552
        return $html;
1553
    }
1554
1555
    /**
1556
     * @param string $title
1557
     * @param string $second_title
1558
     * @param string $size
1559
     * @param bool   $filter
1560
     *
1561
     * @return string
1562
     */
1563
    public static function page_header($title, $second_title = null, $size = 'h2', $filter = true)
1564
    {
1565
        if ($filter) {
1566
            $title = Security::remove_XSS($title);
1567
        }
1568
1569
        if (!empty($second_title)) {
1570
            if ($filter) {
1571
                $second_title = Security::remove_XSS($second_title);
1572
            }
1573
            $title .= "<small> $second_title</small>";
1574
        }
1575
1576
        return '<div class="page-header section-header"><'.$size.' class="section-header__title">'.$title.'</'.$size.'></div>';
1577
    }
1578
1579
    public static function page_header_and_translate($title, $second_title = null)
1580
    {
1581
        $title = get_lang($title);
1582
1583
        return self::page_header($title, $second_title);
1584
    }
1585
1586
    public static function page_subheader($title, $second_title = null, $size = 'h3', $attributes = [])
1587
    {
1588
        if (!empty($second_title)) {
1589
            $second_title = Security::remove_XSS($second_title);
1590
            $title .= "<small> $second_title<small>";
1591
        }
1592
        $subTitle = self::tag($size, Security::remove_XSS($title), $attributes);
1593
1594
        return $subTitle;
1595
    }
1596
1597
    public static function page_subheader2($title, $second_title = null)
1598
    {
1599
        return self::page_header($title, $second_title, 'h4');
1600
    }
1601
1602
    public static function page_subheader3($title, $second_title = null)
1603
    {
1604
        return self::page_header($title, $second_title, 'h5');
1605
    }
1606
1607
    public static function description(array $list): string
1608
    {
1609
        $html = '';
1610
        if (!empty($list)) {
1611
            $html = '<dl class="dl-horizontal">';
1612
            foreach ($list as $item) {
1613
                $html .= '<dt>'.$item['title'].'</dt>';
1614
                $html .= '<dd>'.$item['content'].'</dd>';
1615
            }
1616
            $html .= '</dl>';
1617
        }
1618
1619
        return $html;
1620
    }
1621
1622
    /**
1623
     * @param int    $percentage      int value between 0 and 100
1624
     * @param bool   $show_percentage
1625
     * @param string $extra_info
1626
     * @param string $class           danger/success/infowarning
1627
     *
1628
     * @return string
1629
     */
1630
    public static function bar_progress($percentage, $show_percentage = true, $extra_info = '', $class = '')
1631
    {
1632
        $percentage = (int) $percentage;
1633
        $class = empty($class) ? '' : "progress-bar-$class";
1634
1635
        $div = '<div class="progress">
1636
                <div
1637
                    class="progress-bar progress-bar-striped '.$class.'"
1638
                    role="progressbar"
1639
                    aria-valuenow="'.$percentage.'"
1640
                    aria-valuemin="0"
1641
                    aria-valuemax="100"
1642
                    style="width: '.$percentage.'%;"
1643
                >';
1644
        if ($show_percentage) {
1645
            $div .= $percentage.'%';
1646
        } else {
1647
            if (!empty($extra_info)) {
1648
                $div .= $extra_info;
1649
            }
1650
        }
1651
        $div .= '</div></div>';
1652
1653
        return $div;
1654
    }
1655
1656
    /**
1657
     * @param array $badge_list
1658
     *
1659
     * @return string
1660
     */
1661
    public static function badgeGroup($list)
1662
    {
1663
        $html = '<div class="badge-group">';
1664
        foreach ($list as $badge) {
1665
            $html .= $badge;
1666
        }
1667
        $html .= '</div>';
1668
1669
        return $html;
1670
    }
1671
1672
    /**
1673
     * Return an HTML span element with the badge class and an additional bg-$type class
1674
     */
1675
    public static function label(string $content, string $type = 'default'): string
1676
    {
1677
        $html = '';
1678
        if (!empty($content)) {
1679
            $class = match ($type) {
1680
                'success' => 'success',
1681
                'warning' => 'warning',
1682
                'important', 'danger', 'error' => 'error',
1683
                'info' => 'info',
1684
                'primary' => 'primary',
1685
                default => 'secondary',
1686
            };
1687
1688
            $html = '<span class="badge badge--'.$class.'">';
1689
            $html .= $content;
1690
            $html .= '</span>';
1691
        }
1692
1693
        return $html;
1694
    }
1695
1696
    public static function actions(array $items): string
1697
    {
1698
        if (empty($items)) {
1699
            return '';
1700
        }
1701
1702
        $links = '';
1703
        foreach ($items as $value) {
1704
            $attributes = $value['url_attributes'] ?? [];
1705
            $links .= self::url($value['content'], $value['url'], $attributes);
1706
        }
1707
1708
        return self::toolbarAction(uniqid('toolbar', false), [$links]);
1709
    }
1710
1711
    /**
1712
     * Prints a tooltip.
1713
     *
1714
     * @param string $text
1715
     * @param string $tip
1716
     *
1717
     * @return string
1718
     */
1719
    public static function tip($text, $tip)
1720
    {
1721
        if (empty($tip)) {
1722
            return $text;
1723
        }
1724
1725
        return self::span(
1726
            $text,
1727
            ['class' => 'boot-tooltip', 'title' => strip_tags($tip)]
1728
        );
1729
    }
1730
1731
    /**
1732
     * @param array $buttons
1733
     *
1734
     * @return string
1735
     */
1736
    public static function groupButton($buttons)
1737
    {
1738
        $html = '<div class="btn-group" role="group">';
1739
        foreach ($buttons as $button) {
1740
            $html .= $button;
1741
        }
1742
        $html .= '</div>';
1743
1744
        return $html;
1745
    }
1746
1747
    /**
1748
     * @todo use twig
1749
     *
1750
     * @param string $title
1751
     * @param array  $elements
1752
     * @param bool   $alignToRight
1753
     *
1754
     * @return string
1755
     */
1756
    public static function groupButtonWithDropDown($title, $elements, $alignToRight = false)
1757
    {
1758
        $id = uniqid('dropdown', false);
1759
        $html = '
1760
        <div class="dropdown inline-block relative">
1761
            <button
1762
                id="'.$id.'"
1763
                type="button"
1764
                class="inline-flex justify-center w-full rounded-md border border-gray-300 shadow-sm px-4 py-2 bg-white text-sm font-medium text-gray-700 hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-offset-gray-100 focus:ring-indigo-500"
1765
                aria-expanded="false"
1766
                aria-haspopup="true"
1767
                onclick="document.querySelector(\'#'.$id.'_menu\').classList.toggle(\'hidden\')"
1768
            >
1769
              '.$title.'
1770
              <svg class="-mr-1 ml-2 h-5 w-5" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor" aria-hidden="true">
1771
                <path fill-rule="evenodd" d="M5.293 7.293a1 1 0 011.414 0L10 10.586l3.293-3.293a1 1 0 111.414 1.414l-4 4a1 1 0 01-1.414 0l-4-4a1 1 0 010-1.414z" clip-rule="evenodd" />
1772
              </svg>
1773
            </button>
1774
            <div
1775
                id="'.$id.'_menu"
1776
                class=" dropdown-menu hidden origin-top-right absolute right-0 mt-2 w-56 rounded-md shadow-lg bg-white ring-1 ring-black ring-opacity-5 focus:outline-none"
1777
                role="menu"
1778
                aria-orientation="vertical"
1779
                aria-labelledby="menu-button"
1780
                tabindex="-1"
1781
            >
1782
            <div class="py-1" role="none">';
1783
        foreach ($elements as $item) {
1784
            $html .= self::url(
1785
                    $item['title'],
1786
                    $item['href'],
1787
                    [
1788
                        'class' => 'text-gray-700 block px-4 py-2 text-sm',
1789
                        'role' => 'menuitem',
1790
                        'onclick' => $item['onclick'] ?? '',
1791
                        'data-action' => $item['data-action'] ?? '',
1792
                        'data-confirm' => $item['data-confirm'] ?? '',
1793
                    ]
1794
                );
1795
        }
1796
        $html .= '
1797
            </div>
1798
            </div>
1799
            </div>
1800
        ';
1801
1802
        return $html;
1803
    }
1804
1805
    /**
1806
     * @param string $file
1807
     * @param array  $params
1808
     *
1809
     * @return string|null
1810
     */
1811
    public static function getMediaPlayer($file, $params = [])
1812
    {
1813
        $fileInfo = pathinfo($file);
1814
1815
        $autoplay = isset($params['autoplay']) && 'true' === $params['autoplay'] ? 'autoplay' : '';
1816
        $id = isset($params['id']) ? $params['id'] : $fileInfo['basename'];
1817
        $width = isset($params['width']) ? 'width="'.$params['width'].'"' : null;
1818
        $class = isset($params['class']) ? ' class="'.$params['class'].'"' : null;
1819
1820
        switch ($fileInfo['extension']) {
1821
            case 'mp3':
1822
            case 'webm':
1823
                $html = '<audio id="'.$id.'" '.$class.' controls '.$autoplay.' '.$width.' src="'.$params['url'].'" >';
1824
                $html .= '<object width="'.$width.'" height="50" type="application/x-shockwave-flash" data="'.api_get_path(WEB_LIBRARY_PATH).'javascript/mediaelement/flashmediaelement.swf">
1825
                            <param name="movie" value="'.api_get_path(WEB_LIBRARY_PATH).'javascript/mediaelement/flashmediaelement.swf" />
1826
                            <param name="flashvars" value="controls=true&file='.$params['url'].'" />
1827
                          </object>';
1828
                $html .= '</audio>';
1829
1830
                return $html;
1831
                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...
1832
            case 'wav':
1833
            case 'ogg':
1834
                $html = '<audio width="300px" controls id="'.$id.'" '.$autoplay.' src="'.$params['url'].'" >';
1835
1836
                return $html;
1837
                break;
1838
        }
1839
1840
        return null;
1841
    }
1842
1843
    /**
1844
     * @param int    $nextValue
1845
     * @param array  $list
1846
     * @param int    $current
1847
     * @param int    $fixedValue
1848
     * @param array  $conditions
1849
     * @param string $link
1850
     * @param bool   $isMedia
1851
     * @param bool   $addHeaders
1852
     * @param array  $linkAttributes
1853
     *
1854
     * @return string
1855
     */
1856
    public static function progressPaginationBar(
1857
        $nextValue,
1858
        $list,
1859
        $current,
1860
        $fixedValue = null,
1861
        $conditions = [],
1862
        $link = null,
1863
        $isMedia = false,
1864
        $addHeaders = true,
1865
        $linkAttributes = []
1866
    ) {
1867
        if ($addHeaders) {
1868
            $pagination_size = 'pagination-mini';
1869
            $html = '<div class="exercise_pagination pagination '.$pagination_size.'"><ul>';
1870
        } else {
1871
            $html = null;
1872
        }
1873
        $affectAllItems = false;
1874
        if ($isMedia && isset($fixedValue) && ($nextValue + 1 == $current)) {
1875
            $affectAllItems = true;
1876
        }
1877
        $localCounter = 0;
1878
        foreach ($list as $itemId) {
1879
            $isCurrent = false;
1880
            if ($affectAllItems) {
1881
                $isCurrent = true;
1882
            } else {
1883
                if (!$isMedia) {
1884
                    $isCurrent = $current == ($localCounter + $nextValue + 1) ? true : false;
1885
                }
1886
            }
1887
            $html .= self::parsePaginationItem(
1888
                $itemId,
1889
                $isCurrent,
1890
                $conditions,
1891
                $link,
1892
                $nextValue,
1893
                $isMedia,
1894
                $localCounter,
1895
                $fixedValue,
1896
                $linkAttributes
1897
            );
1898
            $localCounter++;
1899
        }
1900
        if ($addHeaders) {
1901
            $html .= '</ul></div>';
1902
        }
1903
1904
        return $html;
1905
    }
1906
1907
    /**
1908
     * @param int    $itemId
1909
     * @param bool   $isCurrent
1910
     * @param array  $conditions
1911
     * @param string $link
1912
     * @param int    $nextValue
1913
     * @param bool   $isMedia
1914
     * @param int    $localCounter
1915
     * @param int    $fixedValue
1916
     * @param array  $linkAttributes
1917
     *
1918
     * @return string
1919
     */
1920
    public static function parsePaginationItem(
1921
        $itemId,
1922
        $isCurrent,
1923
        $conditions,
1924
        $link,
1925
        $nextValue = 0,
1926
        $isMedia = false,
1927
        $localCounter = null,
1928
        $fixedValue = null,
1929
        $linkAttributes = []
1930
    ) {
1931
        $defaultClass = 'before';
1932
        $class = $defaultClass;
1933
        foreach ($conditions as $condition) {
1934
            $array = isset($condition['items']) ? $condition['items'] : [];
1935
            $class_to_applied = $condition['class'];
1936
            $type = isset($condition['type']) ? $condition['type'] : 'positive';
1937
            $mode = isset($condition['mode']) ? $condition['mode'] : 'add';
1938
            switch ($type) {
1939
                case 'positive':
1940
                    if (in_array($itemId, $array)) {
1941
                        if ('overwrite' == $mode) {
1942
                            $class = " $defaultClass $class_to_applied";
1943
                        } else {
1944
                            $class .= " $class_to_applied";
1945
                        }
1946
                    }
1947
                    break;
1948
                case 'negative':
1949
                    if (!in_array($itemId, $array)) {
1950
                        if ('overwrite' == $mode) {
1951
                            $class = " $defaultClass $class_to_applied";
1952
                        } else {
1953
                            $class .= " $class_to_applied";
1954
                        }
1955
                    }
1956
                    break;
1957
            }
1958
        }
1959
        if ($isCurrent) {
1960
            $class = 'before current';
1961
        }
1962
        if ($isMedia && $isCurrent) {
1963
            $class = 'before current';
1964
        }
1965
        if (empty($link)) {
1966
            $link_to_show = '#';
1967
        } else {
1968
            $link_to_show = $link.($nextValue + $localCounter);
1969
        }
1970
        $label = $nextValue + $localCounter + 1;
1971
        if ($isMedia) {
1972
            $label = ($fixedValue + 1).' '.chr(97 + $localCounter);
1973
            $link_to_show = $link.$fixedValue.'#questionanchor'.$itemId;
1974
        }
1975
        $link = self::url($label.' ', $link_to_show, $linkAttributes);
1976
1977
        return '<li class = "'.$class.'">'.$link.'</li>';
1978
    }
1979
1980
    /**
1981
     * @param int $current
1982
     * @param int $total
1983
     *
1984
     * @return string
1985
     */
1986
    public static function paginationIndicator($current, $total)
1987
    {
1988
        $html = null;
1989
        if (!empty($current) && !empty($total)) {
1990
            $label = sprintf(get_lang('%s of %s'), $current, $total);
1991
            $html = self::url($label, '#', ['class' => 'btn disabled']);
1992
        }
1993
1994
        return $html;
1995
    }
1996
1997
    /**
1998
     * @param $url
1999
     * @param $currentPage
2000
     * @param $pagesCount
2001
     * @param $totalItems
2002
     *
2003
     * @return string
2004
     */
2005
    public static function getPagination($url, $currentPage, $pagesCount, $totalItems)
2006
    {
2007
        $pagination = '';
2008
        if ($totalItems > 1 && $pagesCount > 1) {
2009
            $pagination .= '<ul class="pagination">';
2010
            for ($i = 0; $i < $pagesCount; $i++) {
2011
                $newPage = $i + 1;
2012
                if ($currentPage == $newPage) {
2013
                    $pagination .= '<li class="active"><a href="'.$url.'&page='.$newPage.'">'.$newPage.'</a></li>';
2014
                } else {
2015
                    $pagination .= '<li><a href="'.$url.'&page='.$newPage.'">'.$newPage.'</a></li>';
2016
                }
2017
            }
2018
            $pagination .= '</ul>';
2019
        }
2020
2021
        return $pagination;
2022
    }
2023
2024
    /**
2025
     * Adds a legacy message in the queue.
2026
     *
2027
     * @param string $message
2028
     */
2029
    public static function addFlash($message)
2030
    {
2031
        // Detect type of message.
2032
        $parts = preg_match('/alert-([a-z]*)/', $message, $matches);
2033
        $type = 'primary';
2034
        if ($parts && isset($matches[1]) && $matches[1]) {
2035
            $type = $matches[1];
2036
        }
2037
        // Detect legacy content of message.
2038
        $result = preg_match('/<div(.*?)\>(.*?)\<\/div>/s', $message, $matches);
2039
        if ($result && isset($matches[2])) {
2040
            Container::getSession()->getFlashBag()->add($type, $matches[2]);
2041
        }
2042
    }
2043
2044
    /**
2045
     * Get the profile edition link for a user.
2046
     *
2047
     * @param int  $userId  The user id
2048
     * @param bool $asAdmin Optional. Whether get the URL for the platform admin
2049
     *
2050
     * @return string The link
2051
     */
2052
    public static function getProfileEditionLink($userId, $asAdmin = false)
2053
    {
2054
        $editProfileUrl = api_get_path(WEB_CODE_PATH).'auth/profile.php';
2055
        if ($asAdmin) {
2056
            $editProfileUrl = api_get_path(WEB_CODE_PATH)."admin/user_edit.php?user_id=".intval($userId);
2057
        }
2058
2059
        return $editProfileUrl;
2060
    }
2061
2062
    /**
2063
     * Get the vCard for a user.
2064
     *
2065
     * @param int $userId The user id
2066
     *
2067
     * @return string *.*vcf file
2068
     */
2069
    public static function getVCardUserLink($userId)
2070
    {
2071
        return api_get_path(WEB_PATH).'main/social/vcard_export.php?userId='.intval($userId);
2072
    }
2073
2074
    /**
2075
     * @param string $content
2076
     * @param string $title
2077
     * @param string $footer
2078
     * @param string $type        primary|success|info|warning|danger
2079
     * @param string $extra
2080
     * @param string $id
2081
     * @param string $customColor
2082
     * @param string $rightAction
2083
     *
2084
     * @return string
2085
     */
2086
    public static function panel(
2087
        $content,
2088
        $title = '',
2089
        $footer = '',
2090
        $type = 'default',
2091
        $extra = '',
2092
        $id = '',
2093
        $customColor = '',
2094
        $rightAction = ''
2095
    ) {
2096
        $headerStyle = '';
2097
        if (!empty($customColor)) {
2098
            $headerStyle = 'style = "color: white; background-color: '.$customColor.'" ';
2099
        }
2100
2101
        $footer = !empty($footer) ? '<p class="card-text"><small class="text-muted">'.$footer.'</small></p>' : '';
2102
        $typeList = ['primary', 'success', 'info', 'warning', 'danger'];
2103
        $style = !in_array($type, $typeList) ? 'default' : $type;
2104
2105
        if (!empty($id)) {
2106
            $id = " id='$id'";
2107
        }
2108
        $cardBody = $title.' '.self::contentPanel($content).' '.$footer;
2109
2110
        return "
2111
            <div $id class=card>
2112
                <div class='flex justify-between items-center py-2'>
2113
                    <div class='relative mt-1 flex'>
2114
                        $title
2115
                    </div>
2116
                    <div>
2117
                        $rightAction
2118
                    </div>
2119
                </div>
2120
2121
                $content
2122
                $footer
2123
            </div>"
2124
        ;
2125
    }
2126
2127
    /**
2128
     * @param string $content
2129
     */
2130
    public static function contentPanel($content): string
2131
    {
2132
        if (empty($content)) {
2133
            return '';
2134
        }
2135
2136
        return '<div class="card-text">'.$content.'</div>';
2137
    }
2138
2139
    /**
2140
     * Get the button HTML with an Awesome Font icon.
2141
     *
2142
     * @param string $text        The button content
2143
     * @param string $url         The url to button
2144
     * @param string $icon        The Awesome Font class for icon
2145
     * @param string $type        Optional. The button Bootstrap class. Default 'default' class
2146
     * @param array  $attributes  The additional attributes
2147
     * @param bool   $includeText
2148
     *
2149
     * @return string The button HTML
2150
     */
2151
    public static function toolbarButton(
2152
        $text,
2153
        $url,
2154
        $icon = 'check',
2155
        $type = null,
2156
        array $attributes = [],
2157
        $includeText = true
2158
    ) {
2159
        $buttonClass = "btn btn--secondary-outline";
2160
        if (!empty($type)) {
2161
            $buttonClass = "btn btn--$type";
2162
        }
2163
        //$icon = self::tag('i', null, ['class' => "fa fa-$icon fa-fw", 'aria-hidden' => 'true']);
2164
        $icon = self::getMdiIcon($icon);
2165
        $attributes['class'] = isset($attributes['class']) ? "$buttonClass {$attributes['class']}" : $buttonClass;
2166
        $attributes['title'] = $attributes['title'] ?? $text;
2167
2168
        if (!$includeText) {
2169
            $text = '<span class="sr-only">'.$text.'</span>';
2170
        }
2171
2172
        return self::url("$icon $text", $url, $attributes);
2173
    }
2174
2175
    /**
2176
     * Generate an HTML "p-toolbar" div element with the given id attribute.
2177
     * @param string $id The HTML div's "id" attribute to set
2178
     * @param array  $contentList Array of left-center-right elements for the toolbar. If only 2 elements are defined, this becomes left-right (no center)
2179
     * @return string HTML div for the toolbar
2180
     */
2181
    public static function toolbarAction(string $id, array $contentList): string
2182
    {
2183
        $contentListPurged = array_filter($contentList);
2184
2185
        if (empty($contentListPurged)) {
2186
            return '';
2187
        }
2188
2189
        $count = count($contentList);
2190
2191
        $start = $contentList[0];
2192
        $center = '';
2193
        $end = '';
2194
2195
        if (2 === $count) {
2196
            $end = $contentList[1];
2197
        } elseif (3 === $count) {
2198
            $center = $contentList[1];
2199
            $end = $contentList[2];
2200
        }
2201
2202
2203
        return '<div id="'.$id.'" class="toolbar-action p-toolbar p-component flex items-center justify-between flex-wrap" role="toolbar">
2204
                <div class="p-toolbar-group-start p-toolbar-group-left">'.$start.'</div>
2205
                <div class="p-toolbar-group-center">'.$center.'</div>
2206
                <div class="p-toolbar-group-end p-toolbar-group-right">'.$end.'</div>
2207
            </div>
2208
        ';
2209
    }
2210
2211
    /**
2212
     * @param array  $content
2213
     * @param array  $colsWidth Optional. Columns width
2214
     *
2215
     * @return string
2216
     */
2217
    public static function toolbarGradeAction($content, $colsWidth = [])
2218
    {
2219
        $col = count($content);
2220
2221
        if (!$colsWidth) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $colsWidth 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...
2222
            $width = 8 / $col;
2223
            array_walk($content, function () use ($width, &$colsWidth) {
2224
                $colsWidth[] = $width;
2225
            });
2226
        }
2227
2228
        $html = '<div id="grade" class="p-toolbar p-component flex items-center justify-between flex-wrap" role="toolbar">';
2229
        for ($i = 0; $i < $col; $i++) {
2230
            $class = 'col-sm-'.$colsWidth[$i];
2231
            if ($col > 1) {
2232
                if ($i > 0 && $i < count($content) - 1) {
2233
                    $class .= ' text-center';
2234
                } elseif ($i === count($content) - 1) {
2235
                    $class .= ' text-right';
2236
                }
2237
            }
2238
            $html .= '<div class="'.$class.'">'.$content[$i].'</div>';
2239
        }
2240
        $html .= '</div>';
2241
2242
        return $html;
2243
    }
2244
2245
    /**
2246
     * The auto-translated title version of getMdiIconSimple()
2247
     * Shortcut method to getMdiIcon, to be used from Twig (see ChamiloExtension.php)
2248
     * using acceptable default values
2249
     * @param string $name The icon name or a string representing the icon in our *Icon Enums
2250
     * @param int|null $size The icon size
2251
     * @param string|null $additionalClass Additional CSS class to add to the icon
2252
     * @param string|null $title A title for the icon
2253
     * @return string
2254
     * @throws InvalidArgumentException
2255
     * @throws ReflectionException
2256
     */
2257
    public static function getMdiIconTranslate(
2258
        string $name,
2259
        ?int $size = ICON_SIZE_SMALL,
2260
        ?string $additionalClass = 'ch-tool-icon',
2261
        ?string $title = null
2262
    ): string
2263
    {
2264
        if (!empty($title)) {
2265
            $title = get_lang($title);
2266
        }
2267
2268
        return self::getMdiIconSimple($name, $size, $additionalClass, $title);
2269
    }
2270
    /**
2271
     * Shortcut method to getMdiIcon, to be used from Twig (see ChamiloExtension.php)
2272
     * using acceptable default values
2273
     * @param string $name The icon name or a string representing the icon in our *Icon Enums
2274
     * @param int|null $size The icon size
2275
     * @param string|null $additionalClass Additional CSS class to add to the icon
2276
     * @param string|null $title A title for the icon
2277
     * @return string
2278
     * @throws InvalidArgumentException
2279
     * @throws ReflectionException
2280
     */
2281
    public static function getMdiIconSimple(
2282
        string $name,
2283
        ?int $size = ICON_SIZE_SMALL,
2284
        ?string $additionalClass = 'ch-tool-icon',
2285
        ?string $title = null
2286
    ): string
2287
    {
2288
        // If the string contains '::', we assume it is a reference to one of the icon Enum classes in src/CoreBundle/Enums/
2289
        $matches = [];
2290
        if (preg_match('/(\w*)::(\w*)/', $name, $matches)) {
2291
            if (count($matches) != 3) {
2292
                throw new InvalidArgumentException('Invalid enum case string format. Expected format is "EnumClass::CASE".');
2293
            }
2294
            $enum = $matches[1];
2295
            $case = $matches[2];
2296
            if (!class_exists('Chamilo\CoreBundle\Enums\\'.$enum)) {
2297
                throw new InvalidArgumentException("Class {$enum} does not exist.");
2298
            }
2299
            $reflection = new ReflectionEnum('Chamilo\CoreBundle\Enums\\'.$enum);
2300
            // Check if the case exists in the Enum class
2301
            if (!$reflection->hasCase($case)) {
2302
                throw new InvalidArgumentException("Case {$case} does not exist in enum class {$enum}.");
2303
            }
2304
            // Get the Enum case
2305
            /* @var ReflectionEnumUnitCase $enumUnitCaseObject */
2306
            $enumUnitCaseObject = $reflection->getCase($case);
2307
            $enumValue = $enumUnitCaseObject->getValue();
2308
            $name = $enumValue->value;
2309
2310
        }
2311
2312
        return self::getMdiIcon($name, $additionalClass, null, $size, $title);
2313
    }
2314
2315
    /**
2316
     * Get a full HTML <i> tag for an icon from the Material Design Icons set
2317
     * @param string|ActionIcon|ToolIcon|ObjectIcon|StateIcon $name
2318
     * @param string|null                                     $additionalClass
2319
     * @param string|null                                     $style
2320
     * @param int|null                                        $pixelSize
2321
     * @param string|null                                     $title
2322
     * @param array|null                                      $additionalAttributes
2323
     * @return string
2324
     */
2325
    public static function getMdiIcon(string|ActionIcon|ToolIcon|ObjectIcon|StateIcon $name, string $additionalClass = null, string $style = null, int $pixelSize = null, string $title = null, array $additionalAttributes = null): string
2326
    {
2327
        $sizeString = '';
2328
        if (!empty($pixelSize)) {
2329
            $sizeString = 'font-size: '.$pixelSize.'px; width: '.$pixelSize.'px; height: '.$pixelSize.'px; ';
2330
        }
2331
        if (empty($style)) {
2332
            $style = '';
2333
        }
2334
2335
        $additionalAttributes['class'] = 'mdi mdi-';
2336
2337
        if ($name instanceof ActionIcon
2338
            || $name instanceof ToolIcon
2339
            || $name instanceof ObjectIcon
2340
            || $name instanceof StateIcon
2341
        ) {
2342
            $additionalAttributes['class'] .= $name->value;
2343
        } else {
2344
            $additionalAttributes['class'] .= $name;
2345
        }
2346
2347
        $additionalAttributes['class'] .= " $additionalClass";
2348
        $additionalAttributes['style'] = $sizeString.$style;
2349
        $additionalAttributes['aria-hidden'] = 'true';
2350
2351
        if (!empty($title)) {
2352
            $additionalAttributes['title'] = htmlentities($title);
2353
        }
2354
2355
        return self::tag(
2356
            'i',
2357
            '',
2358
            $additionalAttributes
2359
        );
2360
    }
2361
2362
    /**
2363
     * Get a HTML code for a icon by Font Awesome.
2364
     *
2365
     * @param string     $name            The icon name. Example: "mail-reply"
2366
     * @param int|string $size            Optional. The size for the icon. (Example: lg, 2, 3, 4, 5)
2367
     * @param bool       $fixWidth        Optional. Whether add the fw class
2368
     * @param string     $additionalClass Optional. Additional class
2369
     *
2370
     * @return string
2371
     * @deprecated Use getMdiIcon() instead
2372
     */
2373
    public static function returnFontAwesomeIcon(
2374
        $name,
2375
        $size = '',
2376
        $fixWidth = false,
2377
        $additionalClass = ''
2378
    ) {
2379
        $className = "mdi mdi-$name";
2380
2381
        if ($fixWidth) {
2382
            $className .= ' fa-fw';
2383
        }
2384
2385
        switch ($size) {
2386
            case 'xs':
2387
            case 'sm':
2388
            case 'lg':
2389
                $className .= " fa-{$size}";
2390
                break;
2391
            case 2:
2392
            case 3:
2393
            case 4:
2394
            case 5:
2395
                $className .= " fa-{$size}x";
2396
                break;
2397
        }
2398
2399
        if (!empty($additionalClass)) {
2400
            $className .= " $additionalClass";
2401
        }
2402
2403
        $icon = self::tag('em', null, ['class' => $className]);
2404
2405
        return "$icon ";
2406
    }
2407
2408
    public static function returnPrimeIcon(
2409
        $name,
2410
        $size = '',
2411
        $fixWidth = false,
2412
        $additionalClass = ''
2413
    ) {
2414
        $className = "pi pi-$name";
2415
2416
        if ($fixWidth) {
2417
            $className .= ' pi-fw';
2418
        }
2419
2420
        if ($size) {
2421
            $className .= " pi-$size";
2422
        }
2423
2424
        if (!empty($additionalClass)) {
2425
            $className .= " $additionalClass";
2426
        }
2427
2428
        $icon = self::tag('i', null, ['class' => $className]);
2429
2430
        return "$icon ";
2431
    }
2432
2433
    /**
2434
     * @param string     $title
2435
     * @param string     $content
2436
     * @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...
2437
     * @param array      $params
2438
     * @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...
2439
     * @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...
2440
     * @param bool|true  $open
2441
     * @param bool|false $fullClickable
2442
     *
2443
     * @return string
2444
     *
2445
     * @todo rework function to easy use
2446
     */
2447
    public static function panelCollapse(
2448
        $title,
2449
        $content,
2450
        $id = null,
2451
        $params = [],
2452
        $idAccordion = null,
2453
        $idCollapse = null,
2454
        $open = true,
2455
        $fullClickable = false
2456
    ) {
2457
        $javascript = '';
2458
        if (!empty($idAccordion)) {
2459
            $javascript = '
2460
        <script>
2461
            document.addEventListener("DOMContentLoaded", function() {
2462
                const buttons = document.querySelectorAll("#card_'.$idAccordion.' a");
2463
                const menus = document.querySelectorAll("#collapse_'.$idAccordion.'");
2464
                buttons.forEach((button, index) => {
2465
                    button.addEventListener("click", function() {
2466
                        menus.forEach((menu, menuIndex) => {
2467
                            if (index === menuIndex) {
2468
                                button.setAttribute("aria-expanded", "true" === button.getAttribute("aria-expanded") ? "false" : "true")
2469
                                button.classList.toggle("mdi-chevron-down")
2470
                                button.classList.toggle("mdi-chevron-up")
2471
                                menu.classList.toggle("active");
2472
                            } else {
2473
                                menu.classList.remove("active");
2474
                            }
2475
                        });
2476
                    });
2477
                });
2478
            });
2479
        </script>';
2480
            $html = '
2481
        <div class="display-panel-collapse mb-2">
2482
            <div class="display-panel-collapse__header" id="card_'.$idAccordion.'">
2483
                <a role="button"
2484
                    class="mdi mdi-chevron-down"
2485
                    data-toggle="collapse"
2486
                    data-target="#collapse_'.$idAccordion.'"
2487
                    aria-expanded="'.(($open) ? 'true' : 'false').'"
2488
                    aria-controls="collapse_'.$idAccordion.'"
2489
                >
2490
                    '.$title.'
2491
                </a>
2492
            </div>
2493
            <div
2494
                id="collapse_'.$idAccordion.'"
2495
                class="display-panel-collapse__collapsible '.(($open) ? 'active' : '').'"
2496
            >
2497
                <div id="collapse_contant_'.$idAccordion.'">';
2498
2499
            $html .= $content;
2500
            $html .= '</div></div></div>';
2501
2502
        } else {
2503
            if (!empty($id)) {
2504
                $params['id'] = $id;
2505
            }
2506
            $params['class'] = 'v-card bg-white mx-2';
2507
            $html = '';
2508
            if (!empty($title)) {
2509
                $html .= '<div class="v-card-header text-h5 my-2">'.$title.'</div>'.PHP_EOL;
2510
            }
2511
            $html .= '<div class="v-card-text">'.$content.'</div>'.PHP_EOL;
2512
            $html = self::div($html, $params);
2513
        }
2514
2515
        return $javascript.$html;
2516
    }
2517
2518
    /**
2519
     * Returns the string "1 day ago" with a link showing the exact date time.
2520
     *
2521
     * @param string|DateTime $dateTime in UTC or a DateTime in UTC
2522
     *
2523
     * @throws Exception
2524
     *
2525
     * @return string
2526
     */
2527
    public static function dateToStringAgoAndLongDate(string|DateTime $dateTime): string
2528
    {
2529
        if (empty($dateTime) || '0000-00-00 00:00:00' === $dateTime) {
2530
            return '';
2531
        }
2532
2533
        if (is_string($dateTime)) {
2534
            $dateTime = new \DateTime($dateTime, new \DateTimeZone('UTC'));
2535
        }
2536
2537
        return self::tip(
2538
            date_to_str_ago($dateTime),
2539
            api_convert_and_format_date($dateTime, DATE_TIME_FORMAT_LONG)
2540
        );
2541
    }
2542
2543
    /**
2544
     * @param array  $userInfo
2545
     * @param string $status
2546
     * @param string $toolbar
2547
     *
2548
     * @return string
2549
     */
2550
    public static function getUserCard($userInfo, $status = '', $toolbar = '')
2551
    {
2552
        if (empty($userInfo)) {
2553
            return '';
2554
        }
2555
2556
        if (!empty($status)) {
2557
            $status = '<div class="items-user-status">'.$status.'</div>';
2558
        }
2559
2560
        if (!empty($toolbar)) {
2561
            $toolbar = '<div class="btn-group pull-right">'.$toolbar.'</div>';
2562
        }
2563
2564
        return '<div id="user_card_'.$userInfo['id'].'" class="card d-flex flex-row">
2565
                    <img src="'.$userInfo['avatar'].'" class="rounded" />
2566
                    <h3 class="card-title">'.$userInfo['complete_name'].'</h3>
2567
                    <div class="card-body">
2568
                       <div class="card-title">
2569
                       '.$status.'
2570
                       '.$toolbar.'
2571
                       </div>
2572
                    </div>
2573
                    <hr />
2574
              </div>';
2575
    }
2576
2577
    /**
2578
     * @param string $fileName
2579
     * @param string $fileUrl
2580
     *
2581
     * @return string
2582
     */
2583
    public static function fileHtmlGuesser($fileName, $fileUrl)
2584
    {
2585
        $data = pathinfo($fileName);
2586
2587
        //$content = self::url($data['basename'], $fileUrl);
2588
        $content = '';
2589
        switch ($data['extension']) {
2590
            case 'webm':
2591
            case 'mp4':
2592
            case 'ogg':
2593
                $content = '<video style="width: 400px; height:100%;" src="'.$fileUrl.'"></video>';
2594
                // Allows video to play when loading during an ajax call
2595
                $content .= "<script>jQuery('video:not(.skip), audio:not(.skip)').mediaelementplayer();</script>";
2596
                break;
2597
            case 'jpg':
2598
            case 'jpeg':
2599
            case 'gif':
2600
            case 'png':
2601
                $content = '<img class="img-responsive" src="'.$fileUrl.'" />';
2602
                break;
2603
            default:
2604
                //$html = self::url($data['basename'], $fileUrl);
2605
                break;
2606
        }
2607
        //$html = self::url($content, $fileUrl, ['ajax']);
2608
2609
        return $content;
2610
    }
2611
2612
    /**
2613
     * @param string $image
2614
     * @param int    $size
2615
     *
2616
     * @return string
2617
     */
2618
    public static function get_icon_path($image, $size = ICON_SIZE_SMALL)
2619
    {
2620
        return self::return_icon($image, '', [], $size, false, true);
2621
    }
2622
2623
    /**
2624
     * @param $id
2625
     *
2626
     * @return array|mixed
2627
     */
2628
    public static function randomColor($id)
2629
    {
2630
        static $colors = [];
2631
2632
        if (!empty($colors[$id])) {
2633
            return $colors[$id];
2634
        } else {
2635
            $color = substr(md5(time() * $id), 0, 6);
2636
            $c1 = hexdec(substr($color, 0, 2));
2637
            $c2 = hexdec(substr($color, 2, 2));
2638
            $c3 = hexdec(substr($color, 4, 2));
2639
            $luminosity = $c1 + $c2 + $c3;
2640
2641
            $type = '#000000';
2642
            if ($luminosity < (255 + 255 + 255) / 2) {
2643
                $type = '#FFFFFF';
2644
            }
2645
2646
            $result = [
2647
                'color' => '#'.$color,
2648
                'luminosity' => $type,
2649
            ];
2650
            $colors[$id] = $result;
2651
2652
            return $result; // example: #fc443a
2653
        }
2654
    }
2655
2656
    public static function noDataView(string $title, string $icon, string $buttonTitle, string $url): string
2657
    {
2658
        $content = '<div id="no-data-view">';
2659
        $content .= '<h3>'.$title.'</h3>';
2660
        $content .= $icon;
2661
        $content .= '<div class="controls">';
2662
        $content .= self::url(
2663
            '<em class="fa fa-plus"></em> '.$buttonTitle,
2664
            $url,
2665
            ['class' => 'btn btn--primary']
2666
        );
2667
        $content .= '</div>';
2668
        $content .= '</div>';
2669
2670
        return $content;
2671
    }
2672
2673
    public static function prose(string $contents): string
2674
    {
2675
        return "
2676
    <div class='w-full my-8'>
2677
      <div class='prose prose-blue max-w-none px-6 py-4 bg-white rounded-lg shadow'>
2678
        $contents
2679
      </div>
2680
    </div>
2681
    ";
2682
    }
2683
2684
    public static function getFrameReadyBlock(
2685
        string $frameName,
2686
        string $itemType = '',
2687
        string $jsConditionalFunction = 'function () { return false; }'
2688
    ): string {
2689
2690
        if (in_array($itemType, ['link', 'sco', 'xapi', 'quiz', 'h5p', 'forum'])) {
2691
            return false;
0 ignored issues
show
Bug Best Practice introduced by
The expression return false returns the type false which is incompatible with the type-hinted return string.
Loading history...
2692
        }
2693
2694
        $themeHelper = Container::$container->get(ThemeHelper::class);
0 ignored issues
show
Bug introduced by
The method get() does not exist on null. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

2694
        /** @scrutinizer ignore-call */ 
2695
        $themeHelper = Container::$container->get(ThemeHelper::class);

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
2695
2696
        $themeColorsUrl = $themeHelper->getThemeAssetUrl('colors.css');
2697
2698
        $colorThemeItem = $themeColorsUrl
2699
            ? '{ type: "stylesheet", src: "'.$themeColorsUrl.'" },'
2700
            : '';
2701
2702
        return '$.frameReady(function() {},
2703
            "'.$frameName.'",
2704
            [
2705
                { type: "script", src: "/build/runtime.js" },
2706
                { type: "script", src: "/build/legacy_framereadyloader.js" },
2707
                { type: "stylesheet", src: "/build/legacy_framereadyloader.css" },
2708
                '.$colorThemeItem.'
2709
            ],
2710
            '.$jsConditionalFunction
2711
            .');';
2712
    }
2713
2714
    /**
2715
     * Renders and consumes messages stored with Display::addFlash().
2716
     * Returns HTML ready to inject into the view (alert-*).
2717
     *
2718
     * @return html string with all Flash messages (or '' if none)
2719
     */
2720
    public static function getFlash(): string
2721
    {
2722
        $html = '';
2723
2724
        try {
2725
            $flashBag = Container::getSession()->getFlashBag();
2726
            $all = $flashBag->all();
2727
2728
            foreach ($all as $type => $messages) {
2729
                switch ($type) {
2730
                    case 'success':
2731
                        $displayType = 'success';
2732
                        break;
2733
                    case 'warning':
2734
                        $displayType = 'warning';
2735
                        break;
2736
                    case 'danger':
2737
                    case 'error':
2738
                        $displayType = 'error';
2739
                        break;
2740
                    case 'info':
2741
                    case 'primary':
2742
                    default:
2743
                        $displayType = 'info';
2744
                        break;
2745
                }
2746
2747
                foreach ((array) $messages as $msg) {
2748
                    if (is_string($msg) && $msg !== '') {
2749
                        $html .= self::return_message($msg, $displayType, false);
2750
                    }
2751
                }
2752
            }
2753
        } catch (\Throwable $e) {
2754
            error_log('Display::getFlash error: '.$e->getMessage());
2755
        }
2756
2757
        return $html;
2758
    }
2759
}
2760