Passed
Push — 1.10.x ( c1f149...c762b4 )
by
unknown
83:20 queued 31:10
created

Display::set_header()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %
Metric Value
dl 0
loc 5
rs 9.4285
cc 1
eloc 3
nc 1
nop 0
1
<?php
2
/* For licensing terms, see /license.txt */
3
4
use ChamiloSession as Session;
5
6
/**
7
 * Class Display
8
 * Contains several public functions dealing with the display of
9
 * table data, messages, help topics, ...
10
 *
11
 * Include/require it in your code to use its public functionality.
12
 * There are also several display public functions in the main api library.
13
 *
14
 * All public functions static public functions inside a class called Display,
15
 * so you use them like this: e.g.
16
 * Display::display_normal_message($message)
17
 *
18
 * @package chamilo.library
19
 *
20
 */
21
class Display
22
{
23
    /** @var Template */
24
    public static $global_template;
25
    public static $preview_style = null;
26
27
    /**
28
     * Constructor
29
     */
30
    public function __construct()
31
    {
32
    }
33
34
    /**
35
     * @return array
36
     */
37
    public static function toolList()
38
    {
39
        return array(
40
            'group',
41
            'work',
42
            'glossary',
43
            'forum',
44
            'course_description',
45
            'gradebook',
46
            'attendance',
47
            'course_progress',
48
            'notebook'
49
        );
50
    }
51
52
     /**
53
     * Displays the page header
54
     * @param string The name of the page (will be showed in the page title)
55
     * @param string Optional help file name
56
     * @param string $page_header
57
     */
58
    public static function display_header($tool_name ='', $help = null, $page_header = null)
59
    {
60
        $origin = api_get_origin();
61
        $showHeader = true;
62
        if (isset($origin) && $origin == 'learnpath') {
63
            $showHeader = false;
64
        }
65
66
        self::$global_template = new Template($tool_name, $showHeader, $showHeader);
67
68
        // Fixing tools with any help it takes xxx part of main/xxx/index.php
69
        if (empty($help)) {
70
            $currentURL = api_get_self();
71
            preg_match('/main\/([^*\/]+)/', $currentURL, $matches);
72
            $toolList = self::toolList();
73
            if (!empty($matches)) {
74
                foreach ($matches as $match) {
75
                    if (in_array($match, $toolList)) {
76
                        $help = explode('_', $match);
77
                        $help = array_map('ucfirst', $help);
78
                        $help = implode('', $help);
79
                        break;
80
                    }
81
                }
82
            }
83
        }
84
85
        self::$global_template->setHelp($help);
86
87
        if (!empty(self::$preview_style)) {
88
            self::$global_template->preview_theme = self::$preview_style;
89
            self::$global_template->setCssFiles();
90
            self::$global_template->set_js_files();
91
            self::$global_template->setCssCustomFiles();
92
        }
93
        if (!empty($page_header)) {
94
            self::$global_template->assign('header', $page_header);
95
        }
96
97
        echo self::$global_template->show_header_template();
98
    }
99
100
    /**
101
     * Displays the reduced page header (without banner)
102
     */
103
    public static function display_reduced_header()
104
    {
105
        global $show_learnpath, $tool_name;
106
        self::$global_template = new Template($tool_name, false, false, $show_learnpath);
107
        echo self::$global_template->show_header_template();
108
    }
109
110
    /**
111
     * Display no header
112
     */
113
    public static function display_no_header()
114
    {
115
        global $tool_name, $show_learnpath;
116
        $disable_js_and_css_files = true;
117
        self::$global_template = new Template($tool_name, false, false, $show_learnpath);
118
    }
119
120
    /**
121
     * Displays the reduced page header (without banner)
122
     */
123
    public static function set_header()
124
    {
125
        global $show_learnpath, $tool_name;
126
        self::$global_template = new Template($tool_name, false, false, $show_learnpath);
127
    }
128
129
    /**
130
     * Display the page footer
131
     */
132
    public static function display_footer()
133
    {
134
        echo self::$global_template->show_footer_template();
135
    }
136
137
    /**
138
     * Display the page footer
139
     */
140
    public static function display_reduced_footer()
141
    {
142
        echo self::$global_template->show_footer_js_template();
143
    }
144
145
    public static function page()
146
    {
147
        return new Page();
148
    }
149
150
    /**
151
     * Displays the tool introduction of a tool.
152
     *
153
     * @author Patrick Cool <[email protected]>, Ghent University
154
     * @param string $tool These are the constants that are used for indicating the tools.
155
     * @param array $editor_config Optional configuration settings for the online editor.
156
     * return: $tool return a string array list with the "define" in main_api.lib
157
     * @return html code for adding an introduction
158
     */
159
    public static function display_introduction_section($tool, $editor_config = null)
160
    {
161
        echo self::return_introduction_section($tool, $editor_config);
162
    }
163
164
    /**
165
     * @param string $tool
166
     * @param array $editor_config
167
     * @return null
168
     */
169
    public static function return_introduction_section($tool, $editor_config = null)
170
    {
171
        $is_allowed_to_edit = api_is_allowed_to_edit();
172
        $moduleId = $tool;
173
        if (api_get_setting('enable_tool_introduction') == 'true' || $tool == TOOL_COURSE_HOMEPAGE) {
174
            $introduction_section = null;
175
            require api_get_path(INCLUDE_PATH).'introductionSection.inc.php';
176
            return $introduction_section;
177
        }
178
    }
179
180
    /**
181
     *	Displays a localised html file
182
     *	tries to show the file "$full_file_name"."_".$language_interface.".html"
183
     *	and if this does not exist, shows the file "$full_file_name".".html"
184
     *	warning this public function defines a global
185
     *	@param $full_file_name, the (path) name of the file, without .html
186
     *	@return return a string with the path
187
     */
188
    public static function display_localised_html_file($full_file_name)
189
    {
190
        global $language_interface;
191
        $localised_file_name = $full_file_name.'_'.$language_interface.'.html';
192
        $default_file_name = $full_file_name.'.html';
193
        if (file_exists($localised_file_name)) {
194
            include $localised_file_name;
195
        } else {
196
            include $default_file_name;
197
        }
198
    }
199
200
    /**
201
     * Displays a table
202
     * @param array $header Titles for the table header
203
     * 						each item in this array can contain 3 values
204
     * 						- 1st element: the column title
205
     * 						- 2nd element: true or false (column sortable?)
206
     * 						- 3th element: additional attributes for
207
     *  						th-tag (eg for column-width)
208
     * 						- 4the element: additional attributes for the td-tags
209
     * @param array $content 2D-array with the tables content
210
     * @param array $sorting_options Keys are:
211
     * 					'column' = The column to use as sort-key
212
     * 					'direction' = SORT_ASC or SORT_DESC
213
     * @param array $paging_options Keys are:
214
     * 					'per_page_default' = items per page when switching from
215
     * 										 full-	list to per-page-view
216
     * 					'per_page' = number of items to show per page
217
     * 					'page_nr' = The page to display
218
     * @param array $query_vars Additional variables to add in the query-string
219
     * @param string The style that the table will show. You can set 'table' or 'grid'
220
     * @author [email protected]
221
     */
222
    public static function display_sortable_table(
223
        $header,
224
        $content,
225
        $sorting_options = array(),
226
        $paging_options = array(),
227
        $query_vars = null,
228
        $form_actions = array(),
229
        $style = 'table'
230
    ) {
231
        global $origin;
232
        $column = isset($sorting_options['column']) ? $sorting_options['column'] : 0;
233
        $default_items_per_page = isset($paging_options['per_page']) ? $paging_options['per_page'] : 20;
234
        $table = new SortableTableFromArray($content, $column, $default_items_per_page);
235
        if (is_array($query_vars)) {
236
            $table->set_additional_parameters($query_vars);
237
        }
238
        if ($style == 'table') {
239
            if (is_array($header) && count($header) > 0) {
240
                foreach ($header as $index => $header_item) {
241
                    $table->set_header(
242
                        $index,
243
                        isset($header_item[0]) ? $header_item[0] : null,
244
                        isset($header_item[1]) ? $header_item[1] : null,
245
                        isset($header_item[2]) ? $header_item[2] : null,
246
                        isset($header_item[3]) ? $header_item[3] : null
247
                    );
248
                }
249
            }
250
            $table->set_form_actions($form_actions);
251
            $table->display();
252
        } else {
253
            $table->display_grid();
254
        }
255
    }
256
257
    public static function return_sortable_table(
258
        $header,
259
        $content,
260
        $sorting_options = array(),
261
        $paging_options = array(),
262
        $query_vars = null,
263
        $form_actions = array(),
264
        $style = 'table'
265
    ) {
266
        ob_start();
267
        self::display_sortable_table(
268
            $header,
269
            $content,
270
            $sorting_options,
271
            $paging_options,
272
            $query_vars,
273
            $form_actions,
274
            $style
275
        );
276
        $content = ob_get_contents();
277
        ob_end_clean();
278
        return $content;
279
    }
280
281
    /**
282
     * Shows a nice grid
283
     * @param string grid name (important to create css)
284
     * @param array header content
285
     * @param array array with the information to show
286
     * @param array $paging_options Keys are:
287
     * 					'per_page_default' = items per page when switching from
288
     * 										 full-	list to per-page-view
289
     * 					'per_page' = number of items to show per page
290
     * 					'page_nr' = The page to display
291
     * 					'hide_navigation' =  true to hide the navigation
292
     * @param array $query_vars Additional variables to add in the query-string
293
     * @param array $form actions Additional variables to add in the query-string
0 ignored issues
show
Bug introduced by
There is no parameter named $form. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
294
     * @param mixed An array with bool values to know which columns show.
295
     * i.e: $visibility_options= array(true, false) we will only show the first column
296
     * 				Can be also only a bool value. TRUE: show all columns, FALSE: show nothing
297
     */
298
    public static function display_sortable_grid(
299
        $name,
300
        $header,
301
        $content,
302
        $paging_options = array(),
303
        $query_vars = null,
304
        $form_actions = array(),
305
        $visibility_options = true,
306
        $sort_data = true,
307
        $grid_class = array()
308
    ) {
309
        echo self::return_sortable_grid(
310
            $name,
311
            $header,
312
            $content,
313
            $paging_options,
314
            $query_vars,
315
            $form_actions,
316
            $visibility_options,
317
            $sort_data,
318
            $grid_class
319
        );
320
    }
321
322
    /**
323
     * Gets a nice grid in html string
324
     * @param string grid name (important to create css)
325
     * @param array header content
326
     * @param array array with the information to show
327
     * @param array $paging_options Keys are:
328
     * 					'per_page_default' = items per page when switching from
329
     * 										 full-	list to per-page-view
330
     * 					'per_page' = number of items to show per page
331
     * 					'page_nr' = The page to display
332
     * 					'hide_navigation' =  true to hide the navigation
333
     * @param array $query_vars Additional variables to add in the query-string
334
     * @param array $form actions Additional variables to add in the query-string
0 ignored issues
show
Bug introduced by
There is no parameter named $form. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
335
     * @param mixed An array with bool values to know which columns show. i.e:
336
     *  $visibility_options= array(true, false) we will only show the first column
337
     * 	Can be also only a bool value. TRUE: show all columns, FALSE: show nothing
338
     * @param bool  true for sorting data or false otherwise
339
     * @param array grid classes
340
     * @return 	string   html grid
341
     */
342
    public static function return_sortable_grid(
343
        $name,
344
        $header,
345
        $content,
346
        $paging_options = array(),
347
        $query_vars = null,
348
        $form_actions = array(),
349
        $visibility_options = true,
350
        $sort_data = true,
351
        $grid_class = array(),
352
        $elementCount = 0
353
    ) {
354
        $column =  0;
355
        $default_items_per_page = isset($paging_options['per_page']) ? $paging_options['per_page'] : 20;
356
357
        $table = new SortableTableFromArray($content, $column, $default_items_per_page, $name);
358
        $table->total_number_of_items = intval($elementCount);
359
        if (is_array($query_vars)) {
360
            $table->set_additional_parameters($query_vars);
361
        }
362
363
        return $table->display_simple_grid(
364
            $visibility_options,
365
            $paging_options['hide_navigation'],
366
            $default_items_per_page,
367
            $sort_data,
368
            $grid_class
369
        );
370
    }
371
372
    /**
373
     * Displays a table with a special configuration
374
     * @param array $header Titles for the table header
375
     * 						each item in this array can contain 3 values
376
     * 						- 1st element: the column title
377
     * 						- 2nd element: true or false (column sortable?)
378
     * 						- 3th element: additional attributes for
379
     *  						th-tag (eg for column-width)
380
     * 						- 4the element: additional attributes for the td-tags
381
     * @param array $content 2D-array with the tables content
382
     * @param array $sorting_options Keys are:
383
     * 					'column' = The column to use as sort-key
384
     * 					'direction' = SORT_ASC or SORT_DESC
385
     * @param array $paging_options Keys are:
386
     * 					'per_page_default' = items per page when switching from
387
     * 										 full-	list to per-page-view
388
     * 					'per_page' = number of items to show per page
389
     * 					'page_nr' = The page to display
390
     * @param array $query_vars Additional variables to add in the query-string
391
     * @param array $column_show Array of binaries 1= show columns 0. hide a column
392
     * @param array $column_order An array of integers that let us decide how the columns are going to be sort.
393
     * 						      i.e:  $column_order=array('1''4','3','4'); The 2nd column will be order like the 4th column
394
     * @param array $form_actions Set optional forms actions
395
     *
396
     * @author Julio Montoya
397
     */
398
    public static function display_sortable_config_table(
399
        $table_name,
400
        $header,
401
        $content,
402
        $sorting_options = array(),
403
        $paging_options = array(),
404
        $query_vars = null,
405
        $column_show = array(),
406
        $column_order = array(),
407
        $form_actions = array()
408
    ) {
409
        $column = isset($sorting_options['column']) ? $sorting_options['column'] : 0;
410
        $default_items_per_page = isset($paging_options['per_page']) ? $paging_options['per_page'] : 20;
411
412
        $table = new SortableTableFromArrayConfig(
413
            $content,
414
            $column,
415
            $default_items_per_page,
416
            $table_name,
417
            $column_show,
418
            $column_order
419
        );
420
421
        if (is_array($query_vars)) {
422
            $table->set_additional_parameters($query_vars);
423
        }
424
        // Show or hide the columns header
425
        if (is_array($column_show)) {
426
            for ($i = 0; $i < count($column_show); $i++) {
427
                if (!empty($column_show[$i])) {
428
                    $val0 = isset($header[$i][0]) ? $header[$i][0] : null;
429
                    $val1 = isset($header[$i][1]) ? $header[$i][1] : null;
430
                    $val2 = isset($header[$i][2]) ? $header[$i][2] : null;
431
                    $val3 = isset($header[$i][3]) ? $header[$i][3] : null;
432
                    $table->set_header($i, $val0, $val1, $val2, $val3);
433
                }
434
            }
435
        }
436
        $table->set_form_actions($form_actions);
437
        $table->display();
438
    }
439
440
    /**
441
     * Displays a normal message. It is recommended to use this public function
442
     * to display any normal information messages.
443
     * @param string $message
444
     * @param bool	$filter (true) or not (false)
445
     * @param bool $returnValue
446
     *
447
     * @return void
448
     */
449 View Code Duplication
    public static function display_normal_message($message, $filter = true, $returnValue = false)
450
    {
451
    	$message = self::return_message($message, 'normal', $filter);
452
        if ($returnValue) {
453
            return $message;
454
        } else {
455
            echo $message;
456
        }
457
    }
458
459
    /**
460
     * Displays an warning message. Use this if you want to draw attention to something
461
     * This can also be used for instance with the hint in the exercises
462
     *
463
     */
464 View Code Duplication
    public static function display_warning_message($message, $filter = true, $returnValue = false)
465
    {
466
        $message = self::return_message($message, 'warning', $filter);
467
        if ($returnValue) {
468
            return $message;
469
        } else {
470
            echo $message;
471
        }
472
    }
473
474
    /**
475
     * Displays an confirmation message. Use this if something has been done successfully
476
     * @param bool	Filter (true) or not (false)
477
     * @return void
478
     */
479 View Code Duplication
    public static function display_confirmation_message ($message, $filter = true, $returnValue = false)
480
    {
481
        $message = self::return_message($message, 'confirm', $filter);
482
        if ($returnValue) {
483
            return $message;
484
        } else {
485
            echo $message;
486
        }
487
    }
488
489
    /**
490
     * Displays an error message. It is recommended to use this public function if an error occurs
491
     * @param string $message - include any additional html
492
     *                          tags if you need them
493
     * @param bool	Filter (true) or not (false)
494
     * @return void
495
     */
496 View Code Duplication
    public static function display_error_message ($message, $filter = true, $returnValue = false)
497
    {
498
        $message = self::return_message($message, 'error', $filter);
499
        if ($returnValue) {
500
            return $message;
501
        } else {
502
            echo $message;
503
        }
504
    }
505
506
    /**
507
     * @param string $message
508
     * @param string $type
509
     * @param bool $filter
510
     */
511
    public static function return_message_and_translate($message, $type='normal', $filter = true)
512
    {
513
        $message = get_lang($message);
514
        echo self::return_message($message, $type, $filter);
515
    }
516
517
    /**
518
     * Returns a div html string with
519
     * @param   string  The message
520
     * @param   string  The message type (confirm,normal,warning,error)
521
     * @param   bool    Whether to XSS-filter or not
522
     * @return  string  Message wrapped into an HTML div
523
     */
524
    public static function return_message($message, $type = 'normal', $filter = true)
525
    {
526
        if (empty($message)) {
527
            return '';
528
        }
529
530
        if ($filter) {
531
        	$message = api_htmlentities($message, ENT_QUOTES, api_is_xml_http_request() ? 'UTF-8' : api_get_system_encoding());
532
        }
533
534
        $class = "";
535
        switch($type) {
536
            case 'warning':
537
               $class .= 'alert alert-warning';
538
               break;
539
            case 'error':
540
               $class .= 'alert alert-danger';
541
               break;
542
            case 'confirmation':
543
            case 'confirm':
544
            case 'success':
545
                $class .= 'alert alert-success';
546
               break;
547
            case 'normal':
548
            default:
549
                $class .= 'alert alert-info';
550
        }
551
552
        return self::div($message, array('class'=> $class));
553
    }
554
555
    /**
556
     * Returns an encrypted mailto hyperlink
557
     *
558
     * @param string  e-mail
559
     * @param string  clickable text
560
     * @param string  optional, class from stylesheet
561
     * @return string encrypted mailto hyperlink
562
     */
563
    public static function encrypted_mailto_link ($email, $clickable_text = null, $style_class = '')
564
    {
565
        if (is_null($clickable_text)) {
566
            $clickable_text = $email;
567
        }
568
        // "mailto:" already present?
569
        if (substr($email, 0, 7) != 'mailto:') {
570
            $email = 'mailto:'.$email;
571
        }
572
        // Class (stylesheet) defined?
573
        if ($style_class != '') {
574
            $style_class = ' class="'.$style_class.'"';
575
        }
576
        // Encrypt email
577
        $hmail = '';
578 View Code Duplication
        for ($i = 0; $i < strlen($email); $i ++) {
579
            $hmail .= '&#'.ord($email {
580
            $i }).';';
581
        }
582
        $hclickable_text = null;
583
        // Encrypt clickable text if @ is present
584
        if (strpos($clickable_text, '@')) {
585
            for ($i = 0; $i < strlen($clickable_text); $i ++) {
586
                $hclickable_text .= '&#'.ord($clickable_text {
587
                $i }).';';
588
            }
589
        } else {
590
            $hclickable_text = @htmlspecialchars($clickable_text, ENT_QUOTES, api_get_system_encoding());
591
        }
592
        // Return encrypted mailto hyperlink
593
        return '<a href="'.$hmail.'"'.$style_class.' class="clickable_email_link">'.$hclickable_text.'</a>';
594
    }
595
596
    /**
597
     * Returns an mailto icon hyperlink
598
     *
599
     * @param string  e-mail
600
     * @param string  icon source file from the icon lib
601
     * @param integer  icon size from icon lib
602
     * @param string  optional, class from stylesheet
603
     * @return string encrypted mailto hyperlink
604
     */
605
    public static function icon_mailto_link($email, $icon_file = "mail.png", $icon_size = 22, $style_class = '')
606
    {
607
        // "mailto:" already present?
608
        if (substr($email, 0, 7) != 'mailto:') {
609
            $email = 'mailto:'.$email;
610
        }
611
        // Class (stylesheet) defined?
612
        if ($style_class != '') {
613
            $style_class = ' class="'.$style_class.'"';
614
        }
615
        // Encrypt email
616
        $hmail = '';
617 View Code Duplication
        for ($i = 0; $i < strlen($email); $i ++) {
618
            $hmail .= '&#'.ord($email {
619
            $i }).';';
620
        }
621
        // icon html code
622
        $icon_html_source = self::return_icon($icon_file, $hmail, '', $icon_size);
623
        // Return encrypted mailto hyperlink
624
625
        return '<a href="'.$hmail.'"'.$style_class.' class="clickable_email_link">'.$icon_html_source.'</a>';
626
    }
627
628
    /**
629
     *	Creates a hyperlink to the platform homepage.
630
     *	@param string $name, the visible name of the hyperlink, default is sitename
0 ignored issues
show
Bug introduced by
There is no parameter named $name,. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
631
     *	@return string with html code for hyperlink
632
     */
633
    public static function get_platform_home_link_html($name = '')
634
    {
635
        if ($name == '') {
636
            $name = api_get_setting('siteName');
637
        }
638
        return '<a href="'.api_get_path(WEB_PATH).'index.php">'.$name.'</a>';
639
    }
640
641
    /**
642
     * Prints an <option>-list with all letters (A-Z).
643
     * @param char $selected_letter The letter that should be selected
644
     * @todo This is English language specific implementation.
645
     * It should be adapted for the other languages.
646
     */
647 View Code Duplication
    public static function get_alphabet_options($selected_letter = '')
648
    {
649
        $result = '';
650
        for ($i = 65; $i <= 90; $i ++) {
651
            $letter = chr($i);
652
            $result .= '<option value="'.$letter.'"';
653
            if ($selected_letter == $letter) {
654
                $result .= ' selected="selected"';
655
            }
656
            $result .= '>'.$letter.'</option>';
657
        }
658
        return $result;
659
    }
660
661
    /**
662
     * Get the options withing a select box within the given values
663
     * @param int   Min value
664
     * @param int   Max value
665
     * @param int   Default value
666
     * @return string HTML select options
667
     */
668 View Code Duplication
    public static function get_numeric_options($min, $max, $selected_num = 0)
669
    {
670
        $result = '';
671
        for ($i = $min; $i <= $max; $i ++) {
672
            $result .= '<option value="'.$i.'"';
673
            if (is_int($selected_num))
674
                if ($selected_num == $i) {
675
                    $result .= ' selected="selected"';
676
                }
677
            $result .= '>'.$i.'</option>';
678
        }
679
        return $result;
680
    }
681
682
    /**
683
     * This public function displays an icon
684
     * @param string   The filename of the file (in the main/img/ folder
685
     * @param string   The alt text (probably a language variable)
686
     * @param array    additional attributes (for instance height, width, onclick, ...)
687
     * @param integer  The wanted width of the icon (to be looked for in the corresponding img/icons/ folder)
688
     * @return void
689
    */
690
    public static function display_icon(
691
        $image,
692
        $alt_text = '',
693
        $additional_attributes = array(),
694
        $size = null
695
    ) {
696
        echo self::return_icon($image, $alt_text, $additional_attributes, $size);
697
    }
698
699
    /**
700
     * Gets the path of an icon
701
     * 
702
     * @param string $icon
703
     * @return string
704
     */
705
    public static function returnIconPath($icon)
706
    {
707
        return Display::return_icon($icon, null, null, null, null, true, false);
708
    }
709
710
    /**
711
     * This public function returns the htmlcode for an icon
712
     *
713
     * @param string   The filename of the file (in the main/img/ folder
714
     * @param string   The alt text (probably a language variable)
715
     * @param array    Additional attributes (for instance height, width, onclick, ...)
716
     * @param integer  The wanted width of the icon (to be looked for in the corresponding img/icons/ folder)
717
     * @return string  An HTML string of the right <img> tag
718
     *
719
     * @author Patrick Cool <[email protected]>, Ghent University 2006
720
     * @author Julio Montoya 2010 Function improved, adding image constants
721
     * @author Yannick Warnier 2011 Added size handler
722
     * @version Feb 2011
723
    */
724
    public static function return_icon(
725
        $image,
726
        $alt_text = '',
727
        $additional_attributes = array(),
728
        $size = ICON_SIZE_SMALL,
729
        $show_text = true,
730
        $return_only_path = false,
731
        $loadThemeIcon = true
732
    ) {
733
        $code_path = api_get_path(SYS_CODE_PATH);
734
        $w_code_path = api_get_path(WEB_CODE_PATH);
735
        $alternateCssPath = api_get_path(SYS_CSS_PATH);
736
        $alternateWebCssPath = api_get_path(WEB_CSS_PATH);
737
738
        $image = trim($image);
739
        $size_extra = '';
740
741
        if (isset($size)) {
742
            $size = intval($size);
743
            $size_extra = $size . '/';
744
        } else {
745
            $size = ICON_SIZE_SMALL;
746
        }
747
748
        // Checking the img/ folder
749
        $icon = $w_code_path.'img/'.$image;
750
751
        $theme = 'themes/chamilo/icons/';
752
753
        if ($loadThemeIcon) {
754
            $theme = 'themes/' . api_get_visual_theme() . '/icons/';
755
            // Checking the theme icons folder example: app/Resources/public/css/themes/chamilo/icons/XXX
756
            if (is_file($alternateCssPath.$theme.$size_extra.$image)) {
757
                $icon = $alternateWebCssPath.$theme.$size_extra.$image;
758
            } elseif (is_file($code_path.'img/icons/'.$size_extra.$image)) {
759
                //Checking the main/img/icons/XXX/ folder
760
                $icon = $w_code_path.'img/icons/'.$size_extra.$image;
761
            }
762
        }
763
764
        // Special code to enable SVG - refs #7359 - Needs more work
765
        // The code below does something else to "test out" SVG: for each icon,
766
        // it checks if there is an SVG version. If so, it uses it.
767
        // When moving this to production, the return_icon() calls should
768
        // ask for the SVG version directly
769
        $testServer = api_get_setting('server_type');
770
        if ($testServer == 'test' && $return_only_path == false) {
771
            $svgImage = substr($image, 0, -3) . 'svg';
772
            if (is_file($code_path . $theme . 'svg/' . $svgImage)) {
773
                $icon = $w_code_path . $theme . 'svg/' . $svgImage;
774
            } elseif (is_file($code_path . 'img/icons/svg/' . $svgImage)) {
775
                $icon = $w_code_path . 'img/icons/svg/' . $svgImage;
776
            }
777
778
            if (empty($additional_attributes['height'])) {
779
                $additional_attributes['height'] = $size;
780
            }
781
            if (empty($additional_attributes['width'])) {
782
                $additional_attributes['width'] = $size;
783
            }
784
        }
785
786
        $icon = api_get_cdn_path($icon);
787
788
        if ($return_only_path) {
789
            return $icon;
790
791
        }
792
793
        $img = self::img($icon, $alt_text, $additional_attributes);
794
        if (SHOW_TEXT_NEAR_ICONS == true and !empty($alt_text)) {
795
            if ($show_text) {
796
                $img = "$img $alt_text";
797
            }
798
        }
799
800
        return $img;
801
    }
802
803
    /**
804
     * Returns the htmlcode for an image
805
     *
806
     * @param string $image_path the filename of the file (in the main/img/ folder
807
     * @param string $alt_text the alt text (probably a language variable)
808
     * @param array  $additional_attributes (for instance height, width, onclick, ...)
809
     * @param boolean $filterPath Optional. Whether filter the image path. Default is true
810
     * @author Julio Montoya 2010
811
     */
812
    public static function img($image_path, $alt_text = '', $additional_attributes = array(), $filterPath = true)
813
    {
814
        // Sanitizing the parameter $image_path
815
        if ($filterPath) {
816
            $image_path = Security::filter_img_path($image_path);
817
        }
818
819
        // alt text = the image name if there is none provided (for XHTML compliance)
820
        if ($alt_text == '') {
821
            $alt_text = basename($image_path);
822
        }
823
824
        $additional_attributes['src'] = $image_path;
825
826
        if (empty($additional_attributes['alt'])) {
827
            $additional_attributes['alt'] = $alt_text;
828
        }
829
        if (empty($additional_attributes['title'])) {
830
            $additional_attributes['title'] = $alt_text;
831
        }
832
833
        return self::tag('img', '', $additional_attributes);
834
    }
835
836
    /**
837
     * Returns the htmlcode for a tag (h3, h1, div, a, button), etc
838
     *
839
     * @param string $tag the tag name
840
     * @param string $content the tag's content
841
     * @param array $additional_attributes (for instance height, width, onclick, ...)
842
     * @author Julio Montoya 2010
843
     */
844
    public static function tag($tag, $content, $additional_attributes = array())
845
    {
846
        $attribute_list = '';
847
        // Managing the additional attributes
848
        if (!empty($additional_attributes) && is_array($additional_attributes)) {
849
            $attribute_list = '';
850
            foreach ($additional_attributes as $key => & $value) {
851
                $attribute_list .= $key.'="'.$value.'" ';
852
            }
853
        }
854
        //some tags don't have this </XXX>
855
        if (in_array($tag, array('img','input','br'))) {
856
            $return_value = '<'.$tag.' '.$attribute_list.' />';
857
        } else {
858
            $return_value = '<'.$tag.' '.$attribute_list.' > '.$content.'</'.$tag.'>';
859
        }
860
        return $return_value;
861
    }
862
863
    /**
864
     * Creates a URL anchor
865
     * @param string $name
866
     * @param string $url
867
     * @param array $attributes
868
     *
869
     * @return string
870
     */
871
    public static function url($name, $url, $attributes = array())
872
    {
873
        if (!empty($url)) {
874
            $url = preg_replace('#&amp;#', '&', $url);
875
            $url = htmlspecialchars($url, ENT_QUOTES, 'UTF-8');
876
            $attributes['href'] = $url;
877
        }
878
        return self::tag('a', $name, $attributes);
879
    }
880
881
    /**
882
     * Creates a div tag
883
     *
884
     * @param string $content
885
     * @param array $attributes
886
     * @return string
887
     */
888
    public static function div($content, $attributes = array())
889
    {
890
        return self::tag('div', $content, $attributes);
891
    }
892
893
    /**
894
     * Creates a span tag
895
     */
896
    public static function span($content, $attributes = array())
897
    {
898
        return self::tag('span', $content, $attributes);
899
    }
900
901
    /**
902
     * Displays an HTML input tag
903
     *
904
     */
905
    public static function input($type, $name, $value, $attributes = array())
906
    {
907
         if (isset($type)) {
908
             $attributes['type']= $type;
909
         }
910
         if (isset($name)) {
911
             $attributes['name']= $name;
912
         }
913
         if (isset($value)) {
914
             $attributes['value']= $value;
915
        }
916
        return self::tag('input', '', $attributes);
917
    }
918
919
    /**
920
     * @param $name
921
     * @param $value
922
     * @param array $attributes
923
     * @return string
924
     */
925
    public static function button($name, $value, $attributes = array())
926
    {
927
    	if (!empty($name)) {
928
            $attributes['name'] = $name;
929
    	}
930
    	return self::tag('button', $value, $attributes);
931
    }
932
933
    /**
934
     * Displays an HTML select tag
935
     *
936
     */
937
    public static function select(
938
        $name,
939
        $values,
940
        $default = -1,
941
        $extra_attributes = array(),
942
        $show_blank_item = true,
943
        $blank_item_text = null
944
    ) {
945
        $html = '';
946
        $extra = '';
947
        $default_id = 'id="' . $name . '" ';
948
        foreach ($extra_attributes as $key => $parameter) {
949
            if ($key == 'id') {
950
                $default_id = '';
951
            }
952
            $extra .= $key . '="' . $parameter . '" ';
953
        }
954
        $html .= '<select name="' . $name . '" ' . $default_id . ' ' . $extra . '>';
955
956
        if ($show_blank_item) {
957
            if (empty($blank_item_text)) {
958
                $blank_item_text = get_lang('Select');
959
            } else {
960
                $blank_item_text = Security::remove_XSS($blank_item_text);
961
            }
962
            $html .= self::tag('option', '-- ' . $blank_item_text . ' --', array('value' => '-1'));
963
        }
964
        if ($values) {
965
            foreach ($values as $key => $value) {
966
                if (is_array($value) && isset($value['name'])) {
967
                    $value = $value['name'];
968
                }
969
                $html .= '<option value="' . $key . '"';
970
971
                if (is_array($default)) {
972
                    foreach ($default as $item) {
973
                        if ($item == $key) {
974
                            $html .= ' selected="selected"';
975
                            break;
976
                        }
977
                    }
978
                } else {
979
                    if ($default == $key) {
980
                        $html .= ' selected="selected"';
981
                    }
982
                }
983
984
                $html .= '>' . $value . '</option>';
985
            }
986
        }
987
        $html .= '</select>';
988
        return $html;
989
    }
990
991
    /**
992
     * Creates a tab menu
993
     * Requirements: declare the jquery, jquery-ui libraries + the jquery-ui.css
994
     * in the $htmlHeadXtra variable before the display_header
995
     * Add this script
996
     * @example
997
             * <script>
998
                    $(function() {
999
                        $( "#tabs" ).tabs();
1000
                    });
1001
                </script>
1002
     * @param   array   list of the tab titles
1003
     * @param   array   content that will be showed
1004
     * @param   string  the id of the container of the tab in the example "tabs"
1005
     * @param   array   attributes for the ul
1006
     *
1007
     */
1008
    public static function tabs($header_list, $content_list, $id = 'tabs', $attributes = array(), $ul_attributes = array())
1009
    {
1010
        if (empty($header_list) || count($header_list) == 0 ) {
1011
            return '';
1012
        }
1013
1014
        $lis = '';
1015
        $i = 1;
1016
        foreach ($header_list as $item) {
1017
            $active = '';
1018
            if ($i == 1) {
1019
                $active = ' active';
1020
            }
1021
            $item = self::tag('a', $item, array('href'=>'#'.$id.'-'.$i, 'role'=> 'tab'));
1022
            $ul_attributes['data-toggle'] = 'tab';
1023
            $ul_attributes['role'] = 'presentation';
1024
            $ul_attributes['class'] = $active;
1025
            $lis .= self::tag('li', $item, $ul_attributes);
1026
            $i++;
1027
        }
1028
        $ul = self::tag('ul', $lis, ['class' => 'nav nav-tabs', 'role'=> 'tablist']);
1029
1030
        $i = 1;
1031
        $divs = '';
1032
        foreach ($content_list as $content) {
1033
            $active = '';
1034
            if ($i == 1) {
1035
                $active = ' active';
1036
            }
1037
            $divs .= self::tag('div', $content, array('id'=> $id.'-'.$i, 'class' => 'tab-pane '.$active, 'role' => 'tabpanel'));
1038
            $i++;
1039
        }
1040
1041
        $attributes['id'] = $id;
1042
        $attributes['role'] = 'tabpanel';
1043
        $attributes['class'] = 'tab-wrapper';
1044
1045
        $main_div = self::tag('div', $ul.self::tag('div', $divs, ['class' => 'tab-content']), $attributes);
1046
1047
        return $main_div ;
1048
    }
1049
1050
    /**
1051
     * @param $headers
1052
     * @param null $selected
1053
     *
1054
     * @return string
1055
     */
1056
    public static function tabsOnlyLink($headers, $selected = null)
1057
    {
1058
         $id = uniqid();
1059
         $i = 1;
1060
         $lis = null;
1061
         foreach ($headers as $item) {
1062
            $class = null;
1063
            if ($i == $selected) {
1064
                $class = 'active';
1065
            }
1066
             $item = self::tag(
1067
                 'a',
1068
                 $item['content'],
1069
                 array('id' => $id.'-'.$i, 'href' => $item['url'])
1070
             );
1071
             $lis .= self::tag('li', $item, array('class' => $class));
1072
            $i++;
1073
        }
1074
        return self::tag('ul', $lis, array('class' => 'nav nav-tabs tabs-margin'));
1075
    }
1076
1077
    /**
1078
     * In order to display a grid using jqgrid you have to:
1079
     * @example
1080
     * After your Display::display_header function you have to add the nex javascript code:     *
1081
     * <script>
1082
     *   echo Display::grid_js('my_grid_name', $url,$columns, $column_model, $extra_params,array());
1083
     *   // for more information of this function check the grid_js() function
1084
     * </script>
1085
     * //Then you have to call the grid_html
1086
     * echo Display::grid_html('my_grid_name');
1087
     * As you can see both function use the same "my_grid_name" this is very important otherwise nothing will work
1088
     *
1089
     * @param   string  the div id, this value must be the same with the first parameter of Display::grid_js()
1090
     * @return  string  html
1091
     *
1092
     */
1093
    public static function grid_html($div_id)
1094
    {
1095
        $table  = self::tag('table','', array('id' => $div_id));
1096
        $table .= self::tag('div','', array('id' => $div_id.'_pager'));
1097
        return $table;
1098
    }
1099
1100
    /**
1101
     * @param string $label
1102
     * @param string $form_item
1103
     * @return string
1104
     */
1105
    public static function form_row($label, $form_item)
1106
    {
1107
        $label = self::span($label, array('class' =>'control-label'));
1108
        $form_item = self::div($form_item, array('class' =>'controls'));
1109
        return self::div($label.$form_item, array('class'=>'control-group'));
1110
    }
1111
1112
    /**
1113
     * This is a wrapper to use the jqgrid in Chamilo.
1114
     * For the other jqgrid options visit http://www.trirand.com/jqgridwiki/doku.php?id=wiki:options
1115
     * This function need to be in the ready jquery function
1116
     * example --> $(function() { <?php echo Display::grid_js('grid' ...); ?> }
1117
     * In order to work this function needs the Display::grid_html function with the same div id
1118
     *
1119
     * @param   string  $div_id div id
1120
     * @param   string  $url url where the jqgrid will ask for data (if datatype = json)
1121
     * @param   array   $column_names Visible columns (you should use get_lang). An array in which we place the names of the columns.
1122
     * 					This is the text that appears in the head of the grid (Header layer).
1123
     * 					Example: colname   {name:'date',     index:'date',   width:120, align:'right'},
1124
     * @param   array   $column_model the column model :  Array which describes the parameters of the columns.This is the most important part of the grid.
1125
     * 					For a full description of all valid values see colModel API. See the url above.
1126
     * @param   array   $extra_params extra parameters
1127
     * @param   array   $data data that will be loaded
1128
     * @param	string	$formatter A string that will be appended to the JSON returned
1129
     * @param	bool	$fixed_width not implemented yet
1130
     * @return  string  the js code
1131
     *
1132
     */
1133
    public static function grid_js(
1134
        $div_id,
1135
        $url,
1136
        $column_names,
1137
        $column_model,
1138
        $extra_params,
1139
        $data = array(),
1140
        $formatter = '',
1141
        $fixed_width = false
1142
    ) {
1143
        $obj = new stdClass();
1144
        $obj->first = 'first';
1145
1146
        if (!empty($url)) {
1147
            $obj->url = $url;
1148
        }
1149
1150
        //This line should only be used/modified in case of having characters
1151
        // encoding problems - see #6159
1152
        //$column_names = array_map("utf8_encode", $column_names);
1153
1154
        $obj->colNames      = $column_names;
1155
        $obj->colModel      = $column_model;
1156
        $obj->pager         = '#'.$div_id.'_pager';
1157
        $obj->datatype  = 'json';
1158
        $obj->viewrecords = 'true';
1159
1160
        $all_value = 10000000;
1161
1162
        // Default row quantity
1163
        if (!isset($extra_params['rowList'])) {
1164
            $extra_params['rowList'] = array(20, 50, 100, 500, 1000, $all_value);
1165
        }
1166
1167
        $json = '';
1168
        if (!empty($extra_params['datatype'])) {
1169
            $obj->datatype = $extra_params['datatype'];
1170
        }
1171
1172
        // Row even odd style.
1173
        $obj->altRows = true;
1174
        if (!empty($extra_params['altRows'])) {
1175
            $obj->altRows = $extra_params['altRows'];
1176
        }
1177
1178
        if (!empty($extra_params['sortname'])) {
1179
            $obj->sortname = $extra_params['sortname'];
1180
        }
1181
1182
        if (!empty($extra_params['sortorder'])) {
1183
            $obj->sortorder = $extra_params['sortorder'];
1184
        }
1185
1186
        if (!empty($extra_params['rowList'])) {
1187
            $obj->rowList = $extra_params['rowList'];
1188
        }
1189
        //Sets how many records we want to view in the grid
1190
        $obj->rowNum = 20;
1191
        if (!empty($extra_params['rowNum'])) {
1192
            $obj->rowNum = $extra_params['rowNum'];
1193
        }
1194
1195
        if (!empty($extra_params['viewrecords'])) {
1196
            $obj->viewrecords = $extra_params['viewrecords'];
1197
        }
1198
1199
        $beforeSelectRow = null;
1200
        if (isset($extra_params['beforeSelectRow'])) {
1201
            $beforeSelectRow = "beforeSelectRow: ".$extra_params['beforeSelectRow'].", ";
1202
            unset($extra_params['beforeSelectRow']);
1203
        }
1204
1205
        // Adding extra params
1206
        if (!empty($extra_params)) {
1207
            foreach ($extra_params as $key => $element) {
1208
                // the groupHeaders key gets a special treatment
1209
                if ($key != 'groupHeaders') {
1210
                    $obj->$key = $element;
1211
                }
1212
            }
1213
        }
1214
1215
        // Adding static data.
1216
        if (!empty($data)) {
1217
            $data_var = $div_id.'_data';
1218
            $json.=' var '.$data_var.' = '.json_encode($data).';';
1219
            $obj->data = $data_var;
1220
            $obj->datatype = 'local';
1221
            $json.="\n";
1222
        }
1223
1224
        $obj->end = 'end';
1225
1226
        $json_encode = json_encode($obj);
1227
1228
        if (!empty($data)) {
1229
            //Converts the "data":"js_variable" to "data":js_variable,
1230
            // otherwise it will not work
1231
            $json_encode = str_replace('"data":"'.$data_var.'"', '"data":'.$data_var.'', $json_encode);
1232
        }
1233
1234
        // Fixing true/false js values that doesn't need the ""
1235
        $json_encode = str_replace(':"true"',':true',$json_encode);
1236
        // wrap_cell is not a valid jqgrid attributes is a hack to wrap a text
1237
        $json_encode = str_replace('"wrap_cell":true', 'cellattr : function(rowId, value, rowObject, colModel, arrData) { return \'class = "jqgrid_whitespace"\'; }', $json_encode);
1238
        $json_encode = str_replace(':"false"',':false',$json_encode);
1239
        $json_encode = str_replace('"formatter":"action_formatter"', 'formatter:action_formatter', $json_encode);
1240
        $json_encode = str_replace(array('{"first":"first",','"end":"end"}'), '', $json_encode);
1241
1242
        // Creating the jqgrid element.
1243
        $json .= '$("#'.$div_id.'").jqGrid({';
1244
        //$json .= $beforeSelectRow;
1245
1246
        $json .= $json_encode;
1247
1248
        $json .= '});';
1249
1250
        // Grouping headers option
1251
        if (isset($extra_params['groupHeaders'])) {
1252
            $groups = '';
1253
            foreach ($extra_params['groupHeaders'] as $group) {
1254
                //{ "startColumnName" : "courses", "numberOfColumns" : 1, "titleText" : "Order Info" },
1255
                $groups .= '{ "startColumnName" : "' . $group['startColumnName'] . '", "numberOfColumns" : ' . $group['numberOfColumns'] . ', "titleText" : "' . $group['titleText']  . '" },';
1256
1257
            }
1258
            $json .= '$("#'.$div_id.'").jqGrid("setGroupHeaders", {
1259
                "useColSpanStyle" : false,
1260
                "groupHeaders"    : [
1261
                    ' . $groups . '
1262
                ]
1263
            });';
1264
        }
1265
1266
        $all_text = addslashes(get_lang('All'));
1267
        $json .= '$("'.$obj->pager.' option[value='.$all_value.']").text("'.$all_text.'");';
1268
        $json.= "\n";
1269
        // Adding edit/delete icons.
1270
        $json.= $formatter;
1271
1272
        return $json;
1273
    }
1274
1275
    /**
1276
     * @param array $headers
1277
     * @param array $rows
1278
     * @param array $attributes
1279
     * @return string
1280
     */
1281
    public static function table($headers, $rows, $attributes = array())
1282
    {
1283
    	if (empty($attributes)) {
1284
    		$attributes['class'] = 'data_table';
1285
        }
1286
        $table = new HTML_Table($attributes);
1287
        $row = 0;
1288
        $column = 0;
1289
1290
        // Course headers
1291
        if (!empty($headers)) {
1292
	        foreach ($headers as $item) {
1293
	            $table->setHeaderContents($row, $column, $item);
1294
	            $column++;
1295
	        }
1296
	        $row = 1;
1297
	        $column = 0;
1298
        }
1299
1300
        if (!empty($rows)) {
1301
	        foreach($rows as $content) {
1302
	            $table->setCellContents($row, $column, $content);
1303
                $row++;
1304
            }
1305
        }
1306
        return $table->toHtml();
1307
    }
1308
1309
    /**
1310
     * Returns the "what's new" icon notifications
1311
     *
1312
     * The general logic of this function is to track the last time the user
1313
     * entered the course and compare to what has changed inside this course
1314
     * since then, based on the item_property table inside this course. Note that,
1315
     * if the user never entered the course before, he will not see notification
1316
     * icons. This function takes session ID into account (if any) and only shows
1317
     * the corresponding notifications.
1318
     * @param array     Course information array, containing at least elements 'db' and 'k'
1319
     * @return string   The HTML link to be shown next to the course
1320
     */
1321
    public static function show_notification($course_info)
1322
    {
1323
        if (empty($course_info)) {
1324
            return '';
1325
        }
1326
1327
        $t_track_e_access = Database::get_main_table(TABLE_STATISTIC_TRACK_E_LASTACCESS);
1328
        $course_tool_table = Database::get_course_table(TABLE_TOOL_LIST);
1329
        $tool_edit_table = Database::get_course_table(TABLE_ITEM_PROPERTY);
1330
        $course_code = Database::escape_string($course_info['code']);
1331
1332
        $user_id = api_get_user_id();
1333
        $course_id = intval($course_info['real_id']);
1334
        $sessionId = intval($course_info['id_session']);
1335
1336
        // Get the user's last access dates to all tools of this course
1337
        $sql = "SELECT *
1338
                FROM $t_track_e_access
1339
                WHERE
1340
                    c_id = $course_id AND
1341
                    access_user_id = '$user_id' AND
1342
                    access_session_id ='".$sessionId."'";
1343
        $resLastTrackInCourse = Database::query($sql);
1344
1345
        $oldestTrackDate = $oldestTrackDateOrig = '3000-01-01 00:00:00';
1346
        while ($lastTrackInCourse = Database::fetch_array($resLastTrackInCourse)) {
1347
            $lastTrackInCourseDate[$lastTrackInCourse['access_tool']] = $lastTrackInCourse['access_date'];
1348
            if ($oldestTrackDate > $lastTrackInCourse['access_date']) {
1349
                $oldestTrackDate = $lastTrackInCourse['access_date'];
1350
            }
1351
        }
1352
1353
        if ($oldestTrackDate == $oldestTrackDateOrig) {
1354
            //if there was no connexion to the course ever, then take the
1355
            // course creation date as a reference
1356
            $oldestTrackDate = $course_info['creation_date'];
1357
        }
1358
1359
        $sessionCondition = api_get_session_condition(
1360
            $sessionId,
1361
            true,
1362
            false,
1363
            'tet.session_id'
1364
        );
1365
1366
        // Get the last edits of all tools of this course.
1367
        $sql = "SELECT
1368
                    tet.*,
1369
                    tet.lastedit_date last_date,
1370
                    tet.tool tool,
1371
                    tet.ref ref,
1372
                    tet.lastedit_type type,
1373
                    tet.to_group_id group_id,
1374
                    ctt.image image,
1375
                    ctt.link link
1376
                FROM $tool_edit_table tet
1377
                INNER JOIN $course_tool_table ctt
1378
                ON tet.c_id = ctt.c_id
1379
                WHERE
1380
                    tet.c_id = $course_id AND
1381
                    tet.lastedit_date > '$oldestTrackDate' ".
1382
                    // Special hack for work tool, which is called student_publication in c_tool and work in c_item_property :-/ BT#7104
1383
                    " AND (ctt.name = tet.tool OR (ctt.name = 'student_publication' AND tet.tool = 'work'))
1384
                    AND ctt.visibility = '1'
1385
                    AND tet.lastedit_user_id != $user_id $sessionCondition
1386
                 ORDER BY tet.lastedit_date";
1387
1388
        $res = Database::query($sql);
1389
        // Get the group_id's with user membership.
1390
        $group_ids = GroupManager :: get_group_ids($course_info['real_id'], $user_id);
1391
        $group_ids[] = 0; //add group 'everyone'
1392
        $notifications = array();
1393
        // Filter all last edits of all tools of the course
1394
        while ($res && ($item_property = Database::fetch_array($res, 'ASSOC'))) {
1395
1396
            // First thing to check is if the user never entered the tool
1397
            // or if his last visit was earlier than the last modification.
1398
            if ((!isset($lastTrackInCourseDate[$item_property['tool']])
1399
                 || $lastTrackInCourseDate[$item_property['tool']] < $item_property['lastedit_date'])
1400
                // Drop the tool elements that are part of a group that the
1401
                // user is not part of.
1402
                && ((in_array($item_property['to_group_id'], $group_ids)
1403
                // Drop the dropbox, notebook and chat tools (we don't care)
1404
                && (
1405
                        //$item_property['tool'] != TOOL_DROPBOX &&
1406
                        $item_property['tool'] != TOOL_NOTEBOOK &&
1407
                        $item_property['tool'] != TOOL_CHAT)
1408
                   )
1409
                )
1410
                // Take only what's visible or "invisible but where the user is a teacher" or where the visibility is unset.
1411
                && ($item_property['visibility'] == '1'
1412
                    || ($course_info['status'] == '1' && $item_property['visibility'] == '0')
1413
                    || !isset($item_property['visibility']))
1414
            ) {
1415
                // Also drop announcements and events that are not for the user or his group.
1416
                if ((
1417
                        $item_property['tool'] == TOOL_ANNOUNCEMENT ||
1418
                        $item_property['tool'] == TOOL_CALENDAR_EVENT
1419
                    ) &&
1420
                    (
1421
                        ($item_property['to_user_id'] != $user_id) &&
1422
                        (!isset($item_property['to_group_id']) || !in_array($item_property['to_group_id'], $group_ids)))
1423
                ) {
1424
                   continue;
1425
                }
1426
1427
                // If it's a survey, make sure the user's invited. Otherwise drop it.
1428
                if ($item_property['tool'] == TOOL_SURVEY) {
1429
                    $survey_info = SurveyManager::get_survey($item_property['ref'], 0, $course_code);
1430
                    if (!empty($survey_info)) {
1431
                        $invited_users = SurveyUtil::get_invited_users(
1432
                            $survey_info['code'],
1433
                            $course_code
1434
                        );
1435
                        if (!in_array($user_id, $invited_users['course_users'])) {
1436
                            continue;
1437
                        }
1438
                    }
1439
                }
1440
1441
                // If it's a learning path, ensure it is currently visible to the user
1442
                if ($item_property['tool'] == TOOL_LEARNPATH) {
1443
                    if (!learnpath::is_lp_visible_for_student($item_property['ref'], $user_id, $course_code)) {
1444
                        continue;
1445
                    }
1446
                }
1447
1448
                if ($item_property['tool'] == TOOL_DROPBOX) {
1449
                    $item_property['link'] = 'dropbox/dropbox_download.php?id='.$item_property['ref'];
1450
                }
1451
1452
                if ($item_property['tool'] == 'work' &&
1453
                    $item_property['type'] == 'DirectoryCreated'
1454
                ) {
1455
                    $item_property['lastedit_type'] = 'WorkAdded';
1456
                }
1457
                $notifications[$item_property['tool']] = $item_property;
1458
            }
1459
        }
1460
1461
        // Show all tool icons where there is something new.
1462
        $return = '&nbsp;';
1463
        foreach($notifications as $notification) {
1464
            $lastDate = date('d/m/Y H:i', convert_sql_date($notification['lastedit_date']));
1465
            $type = $notification['lastedit_type'];
1466
            $label = get_lang('TitleNotification').": ".get_lang($type)." ($lastDate)";
1467
1468
            if (strpos($notification['link'], '?') === false) {
1469
                $notification['link'] = $notification['link'].'?notification=1';
1470
            } else {
1471
                $notification['link'] = $notification['link'].'&notification=1';
1472
            }
1473
            $return .= Display::url(
1474
                Display::return_icon($notification['image'], $label),
1475
                api_get_path(WEB_CODE_PATH).
1476
                $notification['link'].'&cidReq='.$course_code.
1477
                '&ref='.$notification['ref'].
1478
                '&gidReq='.$notification['to_group_id'].
1479
                '&id_session='.$sessionId
1480
            ).'&nbsp;';
1481
        }
1482
1483
        return $return;
1484
    }
1485
1486
    /**
1487
     * Get the session box details as an array
1488
     * @param int       Session ID
1489
     * @return array    Empty array or session array
1490
     * ['title'=>'...','category'=>'','dates'=>'...','coach'=>'...','active'=>true/false,'session_category_id'=>int]
1491
     */
1492
    public static function get_session_title_box($session_id)
1493
    {
1494
        global $nosession;
1495
1496
        if (!$nosession) {
1497
            global $now, $date_start, $date_end;
1498
        }
1499
1500
        $output = array();
1501
        if (!$nosession) {
1502
            $main_user_table        = Database :: get_main_table(TABLE_MAIN_USER);
1503
            $tbl_session            = Database :: get_main_table(TABLE_MAIN_SESSION);
1504
            $active = false;
1505
            // Request for the name of the general coach
1506
            $sql ='SELECT tu.lastname, tu.firstname, ts.*
1507
                    FROM '.$tbl_session.' ts
1508
                    LEFT JOIN '.$main_user_table .' tu
1509
                    ON ts.id_coach = tu.user_id
1510
                    WHERE ts.id = '.intval($session_id);
1511
            $rs = Database::query($sql);
1512
            $session_info = Database::store_result($rs, 'ASSOC');
1513
            $session_info = $session_info[0];
1514
1515
            $session = array();
1516
            $session['title'] = $session_info['name'];
1517
            $session['coach'] = '';
1518
            $session['dates'] =  '';
1519
1520
            if (
1521
                (
1522
                    $session_info['access_end_date'] == '0000-00-00' &&
1523
                    $session_info['access_start_date'] == '0000-00-00'
1524
                ) ||
1525
                (
1526
                    empty($session_info['access_end_date']) && empty($session_info['access_start_date'])
1527
                )
1528
            ) {
1529 View Code Duplication
                if (api_get_setting('show_session_coach') === 'true') {
1530
                    $session['coach'] = get_lang('GeneralCoach').': '.api_get_person_name($session_info['firstname'], $session_info['lastname']);
1531
                }
1532
                if (isset($session_info['duration']) && !empty($session_info['duration'])) {
1533
                    $userDurationData = SessionManager::getUserSession(
1534
                            api_get_user_id(),
1535
                            $session_id
1536
                    );
1537
                    $userDuration = 0;
1538
                    if (isset($userDurationData['duration'])) {
1539
                        $userDuration = intval($userDurationData['duration']);
1540
                    }
1541
                    $totalDuration = $session_info['duration'] + $userDuration;
1542
1543
                    $daysLeft = SessionManager::getDayLeftInSession(
1544
                        $session_id,
1545
                        api_get_user_id(),
1546
                        $totalDuration
1547
                    );
1548
                    $session['duration'] = sprintf(get_lang('SessionDurationXDaysLeft'), $daysLeft);
1549
                }
1550
                $active = true;
1551
            } else {
1552
                $start = $stop = false;
1553
                $start_buffer = $stop_buffer = '';
1554 View Code Duplication
                if ($session_info['access_start_date'] == '0000-00-00' || empty($session_info['access_start_date'])) {
1555
                    $session_info['access_start_date'] = '';
1556
                } else {
1557
                    $start = true;
1558
                    $start_buffer = $session_info['access_start_date'];
1559
                    $session_info['access_start_date'] = $session_info['access_start_date'];
1560
                }
1561 View Code Duplication
                if ($session_info['access_end_date'] == '0000-00-00' || empty($session_info['access_end_date'])) {
1562
                    $session_info['access_end_date'] = '';
1563
                } else {
1564
                    $stop = true;
1565
                    $stop_buffer = $session_info['access_end_date'];
1566
                    $session_info['access_end_date'] = $session_info['access_end_date'];
1567
                }
1568
                if ($start && $stop) {
1569
                    $session['dates'] = Display::tag(
1570
                        'em',
1571
                        sprintf(
1572
                            get_lang('FromDateXToDateY'),
1573
                            api_format_date($start_buffer),
1574
                            api_format_date($stop_buffer)
1575
                        )
1576
                    );
1577
                } else {
1578
                    $start_buffer = $stop_buffer = null;
1579
1580
                    if (!empty($session_info['access_start_date'])) {
1581
                        $start_buffer = sprintf(
1582
                            get_lang('FromDateX'),
1583
                            api_format_date($session_info['access_start_date'])
1584
                        );
1585
                    }
1586
1587
                    if (!empty($session_info['access_end_date'])) {
1588
                        $stop_buffer = sprintf(
1589
                            get_lang('UntilDateX'),
1590
                            api_format_date($session_info['access_end_date'])
1591
                        );
1592
                    }
1593
1594
                    $session['dates'] = Display::tag(
1595
                        'em',
1596
                        "$start_buffer $stop_buffer"
1597
                    );
1598
                }
1599
1600 View Code Duplication
                if ( api_get_setting('show_session_coach') === 'true' ) {
1601
                    $session['coach'] = get_lang('GeneralCoach') . ': ' . api_get_person_name(
1602
                        $session_info['firstname'],
1603
                        $session_info['lastname']
1604
                    );
1605
                }
1606
                $active = ($date_start <= $now && $date_end >= $now);
1607
            }
1608
            $session['active'] = $active;
1609
            $session['session_category_id'] = $session_info['session_category_id'];
1610
1611
            $session['description'] = $session_info['description'];
1612
            $session['show_description'] = $session_info['show_description'];
1613
1614
            $entityManager = Database::getManager();
1615
            $fieldValuesRepo = $entityManager->getRepository('ChamiloCoreBundle:ExtraFieldValues');
1616
            $extraFieldValues = $fieldValuesRepo->getVisibleValues(
1617
                Chamilo\CoreBundle\Entity\ExtraField::SESSION_FIELD_TYPE,
1618
                $session_id
1619
            );
1620
1621
            $session['extra_fields'] = [];
1622
1623
            foreach ($extraFieldValues as $value) {
1624
                $session['extra_fields'][] = [
1625
                    'field' => [
1626
                        'variable' => $value->getField()->getVariable(),
1627
                        'display_text' => $value->getField()->getDisplayText()
1628
                    ],
1629
                    'value' => $value->getValue()
1630
                ];
1631
            }
1632
1633
            $output = $session;
1634
        }
1635
        return $output;
1636
    }
1637
1638
    /**
1639
     * Return the five star HTML
1640
     *
1641
     * @param  string  id of the rating ul element
1642
     * @param  string  url that will be added (for jquery see hot_courses.tpl)
1643
	 * @param	string	point info array see function CourseManager::get_course_ranking()
1644
	 * @param	bool	add a div wrapper
1645
	 * @todo	use     templates
1646
     **/
1647
    public static function return_rating_system($id, $url, $point_info = array(), $add_div_wrapper = true)
1648
    {
1649
		$number_of_users_who_voted = isset($point_info['users_who_voted']) ? $point_info['users_who_voted'] : null;
1650
		$percentage = isset($point_info['point_average']) ? $point_info['point_average'] : 0;
1651
1652
		if (!empty($percentage)) {
1653
            $percentage = $percentage*125/100;
1654
        }
1655
		$accesses =  isset($point_info['accesses']) ? $point_info['accesses'] : 0;
1656
1657
		$star_label = sprintf(get_lang('XStarsOutOf5'), $point_info['point_average_star']);
1658
1659
        $html = '<ul id="'.$id.'" class="star-rating">
1660
					<li class="current-rating" style="width:'.$percentage.'px;"></li>
1661
					<li><a href="javascript:void(0);" data-link="'.$url.'&amp;star=1" title="'.$star_label.'" class="one-star">1</a></li>
1662
					<li><a href="javascript:void(0);" data-link="'.$url.'&amp;star=2" title="'.$star_label.'" class="two-stars">2</a></li>
1663
					<li><a href="javascript:void(0);" data-link="'.$url.'&amp;star=3" title="'.$star_label.'" class="three-stars">3</a></li>
1664
					<li><a href="javascript:void(0);" data-link="'.$url.'&amp;star=4" title="'.$star_label.'" class="four-stars">4</a></li>
1665
					<li><a href="javascript:void(0);" data-link="'.$url.'&amp;star=5" title="'.$star_label.'" class="five-stars">5</a></li>
1666
				</ul>';
1667
1668
		$labels = array();
1669
1670
		$labels[]= $number_of_users_who_voted == 1 ? $number_of_users_who_voted.' '.get_lang('Vote') : $number_of_users_who_voted.' '.get_lang('Votes');
1671
		$labels[]= $accesses == 1 ? $accesses.' '.get_lang('Visit') : $accesses.' '.get_lang('Visits');
1672
		if (!empty($number_of_users_who_voted)) {
1673
			$labels[]= get_lang('Average').' '.$point_info['point_average_star'].'/5';
1674
		}
1675
1676
		$labels[]= $point_info['user_vote']  ? get_lang('YourVote').' ['.$point_info['user_vote'].']' : get_lang('YourVote'). ' [?] ';
1677
1678
		if (!$add_div_wrapper && api_is_anonymous()) {
1679
			$labels[]= Display::tag('span', get_lang('LoginToVote'), array('class' => 'error'));
1680
		}
1681
1682
        $html .= Display::div(implode(' | ', $labels) , array('id' =>  'vote_label_'.$id, 'class' => 'vote_label_info'));
1683
        $html .= ' '.Display::span(' ', array('id' =>  'vote_label2_'.$id));
1684
1685
        if ($add_div_wrapper) {
1686
			$html = Display::div($html, array('id' => 'rating_wrapper_'.$id));
1687
		}
1688
1689
        return $html;
1690
    }
1691
1692
    public static function return_default_table_class()
1693
    {
1694
        return 'table table-bordered';
1695
    }
1696
1697
    /**
1698
     * @param string $title
1699
     * @param string $second_title
1700
     * @param string $size
1701
     * @param bool $filter
1702
     * @return string
1703
     */
1704
    public static function page_header($title, $second_title = null, $size = 'h2', $filter = true)
1705
    {
1706
        if ($filter) {
1707
            $title = Security::remove_XSS($title);
1708
        }
1709
1710
        if (!empty($second_title)) {
1711
            if ($filter) {
1712
                $second_title = Security::remove_XSS($second_title);
1713
            }
1714
            $title .= "<small> $second_title<small>";
1715
        }
1716
        return '<div class="page-header"><'.$size.'>'.$title.'</'.$size.'></div>';
1717
    }
1718
1719
    public static function page_header_and_translate($title, $second_title = null)
1720
    {
1721
        $title = get_lang($title);
1722
        return self::page_header($title, $second_title);
1723
    }
1724
1725
     public static function page_subheader_and_translate($title, $second_title = null)
1726
     {
1727
        $title = get_lang($title);
1728
        return self::page_subheader($title, $second_title);
1729
    }
1730
1731
    public static function page_subheader($title, $second_title = null, $size = 'h3')
1732
    {
1733
        if (!empty($second_title)) {
1734
            $second_title = Security::remove_XSS($second_title);
1735
            $title .= "<small> $second_title<small>";
1736
        }
1737
        return '<'.$size.'>'.Security::remove_XSS($title).'</'.$size.'>';
1738
    }
1739
1740
    public static function page_subheader2($title, $second_title = null)
1741
    {
1742
        return self::page_header($title, $second_title, 'h4');
1743
    }
1744
1745
    public static function page_subheader3($title, $second_title = null)
1746
    {
1747
        return self::page_header($title, $second_title, 'h5');
1748
    }
1749
1750
    /**
1751
     * @param array $list
1752
     * @return null|string
1753
     */
1754
    public static function description($list)
1755
    {
1756
        $html = null;
1757
        if (!empty($list)) {
1758
            $html = '<dl class="dl-horizontal">';
1759
            foreach ($list as $item) {
1760
                $html .= '<dt>' . $item['title'] . '</dt>';
1761
                $html .= '<dd>' . $item['content'] . '</dd>';
1762
            }
1763
            $html .= '</dl>';
1764
        }
1765
        return $html;
1766
    }
1767
1768
    /**
1769
     * @param $percentage
1770
     * @param bool $show_percentage
1771
     * @param null $extra_info
1772
     * @return string
1773
     */
1774
    public static function bar_progress($percentage, $show_percentage = true, $extra_info = null)
1775
    {
1776
        $percentage = intval($percentage);
1777
        $div = '<div class="progress">
1778
                <div
1779
                    class="progress-bar progress-bar-striped"
1780
                    role="progressbar"
1781
                    aria-valuenow="'.$percentage.'"
1782
                    aria-valuemin="0"
1783
                    aria-valuemax="100"
1784
                    style="width: '.$percentage.'%;"
1785
                >';
1786
        if ($show_percentage) {
1787
            $div .= $percentage.'%';
1788
        } else {
1789
            if (!empty($extra_info)) {
1790
                $div .= $extra_info;
1791
            }
1792
        }
1793
        $div .= '</div>';
1794
1795
        return $div;
1796
    }
1797
1798
    /**
1799
     * @param string $count
1800
     * @param string $type
1801
     * @return null|string
1802
     */
1803
    public static function badge($count, $type ="warning")
1804
    {
1805
        $class = '';
1806
1807
        switch ($type) {
1808
            case 'success':
1809
                $class = 'badge-success';
1810
                break;
1811
            case 'warning':
1812
                $class = 'badge-warning';
1813
                break;
1814
            case 'important':
1815
                $class = 'badge-important';
1816
                break;
1817
            case 'info':
1818
                $class = 'badge-info';
1819
                break;
1820
            case 'inverse':
1821
                $class = 'badge-inverse';
1822
                break;
1823
        }
1824
1825
        if (!empty($count)) {
1826
            return ' <span class="badge '.$class.'">'.$count.'</span>';
1827
        }
1828
        return null;
1829
    }
1830
1831
    /**
1832
     * @param array $badge_list
1833
     * @return string
1834
     */
1835
    public static function badge_group($badge_list)
1836
    {
1837
        $html = '<div class="badge-group">';
1838
        foreach ($badge_list as $badge) {
1839
            $html .= $badge;
1840
        }
1841
        $html .= '</div>';
1842
        return $html;
1843
    }
1844
1845
    /**
1846
     * @param string $content
1847
     * @param string $type
1848
     * @return string
1849
     */
1850
    public static function label($content, $type = 'default')
1851
    {
1852
        switch ($type) {
1853
            case 'success':
1854
                $class = 'label-success';
1855
                break;
1856
            case 'warning':
1857
                $class = 'label-warning';
1858
                break;
1859
            case 'important':
1860
                //no break
1861
            case 'danger':
1862
                $class = 'label-danger';
1863
                break;
1864
            case 'info':
1865
                $class = 'label-info';
1866
                break;
1867
            case 'primary':
1868
                $class = 'label-primary';
1869
                break;
1870
            default:
1871
                $class = 'label-default';
1872
                break;
1873
        }
1874
1875
        $html = '';
1876
        if (!empty($content)) {
1877
            $html = '<span class="label '.$class.'">';
1878
            $html .= $content;
1879
            $html .='</span>';
1880
        }
1881
1882
        return $html;
1883
    }
1884
1885
    /**
1886
     * @param array $items
1887
     * @return null|string
1888
     */
1889
    public static function actions($items, $class = 'new_actions')
1890
    {
1891
        $html = null;
1892
        if (!empty($items)) {
1893
            $html = '<div class="'.$class.'"><ul class="nav nav-pills">';
1894
            foreach ($items as $value) {
1895
                $class = null;
1896
                if (isset($value['active']) && $value['active']) {
1897
                    $class = 'class ="active"';
1898
                }
1899
1900
                if (basename($_SERVER['REQUEST_URI']) == basename($value['url']) ) {
1901
                    $class = 'class ="active"';
1902
                }
1903
                $html .= "<li $class >";
1904
                $attributes = isset($value['url_attributes']) ? $value['url_attributes'] : array();
1905
                $html .= self::url($value['content'], $value['url'], $attributes);
1906
                $html .= '</li>';
1907
            }
1908
            $html .= '</ul></div>';
1909
        }
1910
        return $html;
1911
    }
1912
1913
    /**
1914
     * Prints a tooltip
1915
     * @param string $text
1916
     * @param string $tip
1917
     *
1918
     * @return string
1919
     */
1920
    public static function tip($text, $tip)
1921
    {
1922
        if (empty($tip)) {
1923
            return $text;
1924
        }
1925
        return self::span($text, array('class' => 'boot-tooltip', 'title' => strip_tags($tip)));
1926
    }
1927
1928
    /**
1929
     * @param array $items
1930
     * @param string $type
1931
     * @param null $id
1932
     * @return null|string
1933
     */
1934
    public static function generate_accordion($items, $type = 'jquery', $id = null)
1935
    {
1936
        $html = null;
1937
        if (!empty($items)) {
1938
            if (empty($id)) {
1939
                $id = api_get_unique_id();
1940
            }
1941
            if ($type == 'jquery') {
1942
                $html = '<div class="accordion_jquery" id="'.$id.'">'; //using jquery
1943
            } else {
1944
                $html = '<div class="accordion" id="'.$id.'">'; //using bootstrap
1945
            }
1946
1947
            $count = 1;
1948
            foreach ($items as $item) {
1949
                $html .= '<div class="accordion-my-group">';
1950
                $html .= '<div class="accordion-heading">
1951
                            <a class="accordion-toggle" data-toggle="collapse" data-parent="#'.$id.'" href="#collapse'.$count.'">
1952
                            '.$item['title'].'
1953
                            </a>
1954
                          </div>';
1955
1956
                $html .= '<div id="collapse'.$count.'" class="accordion-body">';
1957
                $html .= '<div class="accordion-my-inner">
1958
                            '.$item['content'].'
1959
                            </div>
1960
                          </div>';
1961
            }
1962
            $html .= '</div>';
1963
        }
1964
1965
        return $html;
1966
    }
1967
1968
    /**
1969
     * @todo use twig
1970
     */
1971
    public static function group_button($title, $elements)
1972
    {
1973
        $html = '<div class="btn-group">
1974
                <button class="btn btn-default dropdown-toggle" data-toggle="dropdown">
1975
                '.$title.'
1976
                <span class="caret"></span></button>
1977
                <ul class="dropdown-menu">';
1978
        foreach ($elements as $item) {
1979
            $html .= Display::tag('li', Display::url($item['title'], $item['href']));
1980
        }
1981
        $html .= '</ul>
1982
            </div>';
1983
        return $html;
1984
    }
1985
1986
    /**
1987
     * @param string $file
1988
     * @param array $params
1989
     * @return null|string
1990
     */
1991
    public static function getMediaPlayer($file, $params = array())
1992
    {
1993
        $fileInfo = pathinfo($file);
1994
1995
        switch ($fileInfo['extension']) {
1996
            case 'wav':
1997
                if (isset($params['url'])) {
1998
                    $url = DocumentManager::generateAudioTempFile(basename($file), $file);
1999
                    return DocumentManager::readNanogongFile($url);
2000
                }
2001
                break;
2002
            case 'mp3':
2003
            case 'webm':
2004
                $autoplay = null;
2005
                if (isset($params['autoplay']) && $params['autoplay'] == 'true') {
2006
                    $autoplay = 'autoplay';
2007
                }
2008
                $width = isset($params['width']) ? 'width="'.$params['width'].'"' : null;
2009
                $id = isset($params['id']) ? $params['id'] : $fileInfo['basename'];
2010
                $class = isset($params['class']) ? ' class="'.$params['class'].'"' : null;
2011
2012
                $html = '<audio id="'.$id.'" '.$class.' controls '.$autoplay.' '.$width.' src="'.$params['url'].'" >';
2013
                $html .= '<object width="'.$width.'" height="50" type="application/x-shockwave-flash" data="'.api_get_path(WEB_LIBRARY_PATH).'javascript/mediaelement/flashmediaelement.swf">
2014
                            <param name="movie" value="'.api_get_path(WEB_LIBRARY_PATH).'javascript/mediaelement/flashmediaelement.swf" />
2015
                            <param name="flashvars" value="controls=true&file='.$params['url'].'" />
2016
                          </object>';
2017
                $html .= '</audio>';
2018
2019
                return $html;
2020
                break;
2021
        }
2022
2023
        return null;
2024
    }
2025
2026
    /**
2027
     * Adds a message in the queue
2028
     * @param string $message
2029
     */
2030
    public static function addFlash($message)
2031
    {
2032
        $messages = Session::read('flash_messages');
2033
        if (empty($messages)) {
2034
            $messages[] = $message;
2035
        } else {
2036
            array_push($messages, $message);
2037
        }
2038
        Session::write('flash_messages', $messages);
2039
    }
2040
2041
    /**
2042
     * @return string
2043
     */
2044
    public static function getFlashToString()
2045
    {
2046
        $messages = Session::read('flash_messages');
2047
        $messageToString = '';
2048
        if (!empty($messages)) {
2049
            foreach ($messages as $message) {
2050
                $messageToString .= $message;
2051
            }
2052
        }
2053
2054
        return $messageToString;
2055
    }
2056
2057
    /**
2058
     * Shows the message from the session
2059
     */
2060
    public static function showFlash()
2061
    {
2062
        echo self::getFlashToString();
2063
    }
2064
2065
    /**
2066
     * Destroys the message session
2067
     */
2068
    public static function cleanFlashMessages()
2069
    {
2070
        Session::erase('flash_messages');
2071
    }
2072
2073
    /**
2074
     * Get the profile edition link for a user
2075
     * @param int $userId The user id
2076
     * @param boolean $asAdmin Optional. Whether get the URL for the platform admin
2077
     * @return string The link
2078
     */
2079
    public static function getProfileEditionLink($userId, $asAdmin = false)
2080
    {
2081
        $editProfileUrl = api_get_path(WEB_CODE_PATH).'auth/profile.php';
2082
2083
        if ($asAdmin) {
2084
            $editProfileUrl = api_get_path(WEB_CODE_PATH)."admin/user_edit.php?user_id=".intval($userId);
2085
        }
2086
2087
        if (api_get_setting('sso_authentication') === 'true') {
2088
            $subSSOClass = api_get_setting('sso_authentication_subclass');
2089
2090
            $objSSO = null;
2091
2092 View Code Duplication
            if (!empty($subSSOClass)) {
2093
                require_once api_get_path(SYS_CODE_PATH)."auth/sso/sso.$subSSOClass.class.php";
2094
                $subSSOClass = 'sso'.$subSSOClass;
2095
                $objSSO = new $subSSOClass();
2096
            } else {
2097
                $objSSO = new sso();
2098
            }
2099
2100
            $editProfileUrl = $objSSO->generateProfileEditingURL(
2101
                $userId,
2102
                $asAdmin
2103
            );
2104
        }
2105
2106
        return $editProfileUrl;
2107
    }
2108
2109
    /**
2110
     * Get the vCard for a user
2111
     * @param int $userId The user id
2112
     * @return string *.*vcf file
2113
     */
2114
    public static function getVCardUserLink($userId)
2115
    {
2116
        $vCardUrl = api_get_path(WEB_PATH).'main/social/vcard_export.php?userId='.intval($userId);;
2117
2118
        return $vCardUrl;
2119
    }
2120
2121
    /**
2122
     * @param string $content
2123
     * @param string $title
2124
     * @param string $footer
2125
     * @param string $style primary|success|info|warning|danger
2126
     * @param string $extra
2127
     *
2128
     * @return string
2129
     */
2130
    public static function panel($content, $title = '', $footer = '', $style = '', $extra = '')
2131
    {
2132
        $title = !empty($title) ? '<div class="panel-heading"><h3 class="panel-title">'.$title.'</h3>'.$extra.'</div>' : '';
2133
        $footer = !empty($footer) ? '<div class="panel-footer ">'.$footer.'</div>' : '';
2134
        $styles = ['primary','success','info','warning','danger'];
2135
        $style = !in_array($style, $styles) ? 'default' : $style;
2136
2137
        return '
2138
            <div class="panel panel-'.$style.'">
2139
                '.$title.'
2140
                '.self::contentPanel($content).'
2141
                '.$footer.'
2142
            </div>'
2143
        ;
2144
    }
2145
2146
    /**
2147
     * @param string $content
2148
     * @return string
2149
     */
2150
    public static function contentPanel($content)
2151
    {
2152
        return '<div class="panel-body">
2153
                '.$content.'
2154
                </div>';
2155
    }
2156
2157
    /**
2158
     * Get the button HTML with an Awesome Font icon
2159
     * @param string $text The button content
2160
     * @param string $url The url to button
2161
     * @param string $icon The Awesome Font class for icon
2162
     * @param string $type Optional. The button Bootstrap class. Default 'default' class
2163
     * @param array $attributes The additional attributes
2164
     * @return string The button HTML
2165
     */
2166
    public static function toolbarButton(
2167
        $text,
2168
        $url,
2169
        $icon = 'check',
2170
        $type = 'default',
2171
        array $attributes = [],
2172
        $includeText = true
2173
    ) {
2174
        $buttonClass = "btn btn-$type";
2175
        $icon = self::tag('i', null, ['class' => "fa fa-$icon fa-fw", 'aria-hidden' => 'true']);
2176
        $attributes['class'] = isset($attributes['class']) ? "$buttonClass {$attributes['class']}" : $buttonClass;
2177
2178
        if (!$includeText) {
2179
            $text = '<span class="sr-only">' . $text . '</span>';
2180
        }
2181
2182
        return self::url("$icon $text", $url, $attributes);
2183
    }
2184
2185
    /**
2186
     * @param int $id
2187
     * @param array $content
2188
     * @param int $col
2189
     * @param bool|true $right
2190
     * @return string
2191
     */
2192
    public static function toolbarAction($id, $content = array(), $col = 2, $right = true)
2193
    {
2194
        $columns = 12/$col;
2195
        $html = '';
2196
        $html .= '<div id="' . $id . '" class="actions">';
2197
        $html .= '<div class="row">';
2198
        if ($col > 4) {
2199
            $html = '<div class="alert alert-warning" role="alert">Action toolbar design does not work when exceeding four columns - check Display::toolbarAction()</div>';
2200
        } else {
2201
            for ( $i = 0; $i < $col; $i++ ) {
2202
                $html .= '<div class="col-md-' . $columns . '">';
2203
                if ( $col == 2 && $i == 1 ) {
2204
                    if ($right === true) {
2205
                        $html .= '<div class="pull-right">';
2206
                        $html .= (isset($content[$i])?$content[$i]:'');
2207
                        $html .= '</div>';
2208
                    } else {
2209
                        $html .= $content[$i];
2210
                    }
2211
                } else {
2212
                    $html .= $content[$i];
2213
                }
2214
                $html .= '</div>';
2215
            }
2216
        }
2217
        $html .= '</div>';
2218
        $html .= '</div>';
2219
2220
        return $html;
2221
    }
2222
2223
    /**
2224
     * Get a HTML code for a icon by Font Awesome
2225
     * @param string $name The icon name
2226
     * @param boolean $fixWidth Optional. Whether add the fw class
2227
     * @param int|string $size Optional. The size for the icon.
2228
     * @param string $additionalClass Optional. Additional class
2229
     *
2230
     * @return string
2231
     */
2232
    public static function returnFontAwesomeIcon(
2233
        $name,
2234
        $fixWidth = false,
2235
        $size = null,
2236
        $additionalClass = null
2237
    ) {
2238
        $className = "fa fa-$name";
2239
2240
        if ($fixWidth) {
2241
            $className .= ' fa-fw';
2242
        }
2243
2244
        switch ($size) {
2245
            case 'lg':
2246
                $className .= ' fa-lg';
2247
                break;
2248
            case 2:
2249
                //no break
2250
            case 3:
2251
                //no break
2252
            case 4:
2253
                //no break
2254
            case 5:
2255
                $className .= " fa-{$size}x";
2256
                break;
2257
        }
2258
2259
        if (!empty($additionalClass)) {
2260
            $className .= " $additionalClass";
2261
        }
2262
2263
        $icon = self::tag('em', null, ['class' => $className]);
2264
2265
        return "$icon ";
2266
    }
2267
2268
    /**
2269
     * @param string $title
2270
     * @param string $content
2271
     * @param null $id
2272
     * @param array $params
2273
     * @param null $idAccordion
2274
     * @param null $idCollapse
2275
     * @param bool|true $open
2276
     * @param bool|false $fullClickable
2277
     * @return null|string
2278
     */
2279
    public static function panelCollapse(
2280
        $title,
2281
        $content,
2282
        $id = null,
2283
        $params = array(),
2284
        $idAccordion = null,
2285
        $idCollapse = null,
2286
        $open = true,
2287
        $fullClickable = false
2288
    ) {
2289
        if (!empty($idAccordion)) {
2290
            $headerClass = '';
2291
            $headerClass .= $fullClickable ? 'center-block ' : '';
2292
            $headerClass .= $open ? '' : 'collapsed';
2293
            $contentClass = 'panel-collapse collapse ';
2294
            $contentClass .= $open ? 'in' : '';
2295
            $ariaExpanded = $open ? 'true' : 'false';
2296
2297
            $html = <<<HTML
2298
                <div class="panel-group" id="$idAccordion" role="tablist" aria-multiselectable="true">
2299
                    <div class="panel panel-default" id="$id">
2300
                        <div class="panel-heading" role="tab">
2301
                            <h4 class="panel-title">
2302
                                <a class="$headerClass" role="button" data-toggle="collapse" data-parent="#$idAccordion" href="#$idCollapse" aria-expanded="$ariaExpanded" aria-controls="$idCollapse">$title</a>
2303
                            </h4>
2304
                        </div>
2305
                        <div id="$idCollapse" class="$contentClass" role="tabpanel">
2306
                            <div class="panel-body">$content</div>
2307
                        </div>
2308
                    </div>
2309
                </div>
2310
HTML;
2311 View Code Duplication
        } else {
2312
            if (!empty($id)) {
2313
                $params['id'] = $id;
2314
            }
2315
            $params['class'] = 'panel panel-default';
2316
            $html = null;
2317
            if (!empty($title)) {
2318
                $html .= '<div class="panel-heading">'.$title.'</div>' . PHP_EOL;
2319
            }
2320
            $html.= '<div class="panel-body">'.$content.'</div>' . PHP_EOL;
2321
            $html = Display::div($html, $params);
2322
        }
2323
        return $html;
2324
    }
2325
}
2326