Passed
Push — 1.11.x ( cf84be...f885fc )
by Julito
13:50
created

api_is_in_group()   A

Complexity

Conditions 6
Paths 8

Size

Total Lines 24
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
eloc 14
nc 8
nop 2
dl 0
loc 24
rs 9.2222
c 0
b 0
f 0
1
<?php
2
3
/* For licensing terms, see /license.txt */
4
5
use Chamilo\CoreBundle\Entity\SettingsCurrent;
6
use Chamilo\CourseBundle\Entity\CItemProperty;
7
use Chamilo\UserBundle\Entity\User;
8
use ChamiloSession as Session;
9
use PHPMailer\PHPMailer\PHPMailer;
10
use Symfony\Component\Finder\Finder;
11
12
/**
13
 * This is a code library for Chamilo.
14
 * It is included by default in every Chamilo file (through including the global.inc.php)
15
 * This library is in process of being transferred to src/Chamilo/CoreBundle/Component/Utils/ChamiloApi.
16
 * Whenever a function is transferred to the ChamiloApi class, the places where it is used should include
17
 * the "use Chamilo\CoreBundle\Component\Utils\ChamiloApi;" statement.
18
 */
19
20
// PHP version requirement.
21
define('REQUIRED_PHP_VERSION', '7.1');
22
define('REQUIRED_MIN_MEMORY_LIMIT', '128');
23
define('REQUIRED_MIN_UPLOAD_MAX_FILESIZE', '10');
24
define('REQUIRED_MIN_POST_MAX_SIZE', '10');
25
26
// USER STATUS CONSTANTS
27
/** global status of a user: student */
28
define('STUDENT', 5);
29
/** global status of a user: course manager */
30
define('COURSEMANAGER', 1);
31
/** global status of a user: session admin */
32
define('SESSIONADMIN', 3);
33
/** global status of a user: human ressource manager */
34
define('DRH', 4);
35
/** global status of a user: human ressource manager */
36
define('ANONYMOUS', 6);
37
/** global status of a user: low security, necessary for inserting data from
38
 * the teacher through HTMLPurifier */
39
define('COURSEMANAGERLOWSECURITY', 10);
40
// Soft user status
41
define('PLATFORM_ADMIN', 11);
42
define('SESSION_COURSE_COACH', 12);
43
define('SESSION_GENERAL_COACH', 13);
44
define('COURSE_STUDENT', 14); //student subscribed in a course
45
define('SESSION_STUDENT', 15); //student subscribed in a session course
46
define('COURSE_TUTOR', 16); // student is tutor of a course (NOT in session)
47
define('STUDENT_BOSS', 17); // student is boss
48
define('INVITEE', 20);
49
define('HRM_REQUEST', 21); //HRM has request for vinculation with user
50
51
// Table of status
52
$_status_list[COURSEMANAGER] = 'teacher'; // 1
53
$_status_list[SESSIONADMIN] = 'session_admin'; // 3
54
$_status_list[DRH] = 'drh'; // 4
55
$_status_list[STUDENT] = 'user'; // 5
56
$_status_list[ANONYMOUS] = 'anonymous'; // 6
57
$_status_list[INVITEE] = 'invited'; // 20
58
59
// COURSE VISIBILITY CONSTANTS
60
/** only visible for course admin */
61
define('COURSE_VISIBILITY_CLOSED', 0);
62
/** only visible for users registered in the course */
63
define('COURSE_VISIBILITY_REGISTERED', 1);
64
/** Open for all registered users on the platform */
65
define('COURSE_VISIBILITY_OPEN_PLATFORM', 2);
66
/** Open for the whole world */
67
define('COURSE_VISIBILITY_OPEN_WORLD', 3);
68
/** Invisible to all except admin */
69
define('COURSE_VISIBILITY_HIDDEN', 4);
70
71
define('COURSE_REQUEST_PENDING', 0);
72
define('COURSE_REQUEST_ACCEPTED', 1);
73
define('COURSE_REQUEST_REJECTED', 2);
74
define('DELETE_ACTION_ENABLED', false);
75
76
// EMAIL SENDING RECIPIENT CONSTANTS
77
define('SEND_EMAIL_EVERYONE', 1);
78
define('SEND_EMAIL_STUDENTS', 2);
79
define('SEND_EMAIL_TEACHERS', 3);
80
81
// SESSION VISIBILITY CONSTANTS
82
define('SESSION_VISIBLE_READ_ONLY', 1);
83
define('SESSION_VISIBLE', 2);
84
define('SESSION_INVISIBLE', 3); // not available
85
define('SESSION_AVAILABLE', 4);
86
87
define('SESSION_LINK_TARGET', '_self');
88
89
define('SUBSCRIBE_ALLOWED', 1);
90
define('SUBSCRIBE_NOT_ALLOWED', 0);
91
define('UNSUBSCRIBE_ALLOWED', 1);
92
define('UNSUBSCRIBE_NOT_ALLOWED', 0);
93
94
// SURVEY VISIBILITY CONSTANTS
95
define('SURVEY_VISIBLE_TUTOR', 0);
96
define('SURVEY_VISIBLE_TUTOR_STUDENT', 1);
97
define('SURVEY_VISIBLE_PUBLIC', 2);
98
99
// CONSTANTS defining all tools, using the english version
100
/* When you add a new tool you must add it into function api_get_tools_lists() too */
101
define('TOOL_DOCUMENT', 'document');
102
define('TOOL_LP_FINAL_ITEM', 'final_item');
103
define('TOOL_READOUT_TEXT', 'readout_text');
104
define('TOOL_THUMBNAIL', 'thumbnail');
105
define('TOOL_HOTPOTATOES', 'hotpotatoes');
106
define('TOOL_CALENDAR_EVENT', 'calendar_event');
107
define('TOOL_LINK', 'link');
108
define('TOOL_LINK_CATEGORY', 'link_category');
109
define('TOOL_COURSE_DESCRIPTION', 'course_description');
110
define('TOOL_SEARCH', 'search');
111
define('TOOL_LEARNPATH', 'learnpath');
112
define('TOOL_LEARNPATH_CATEGORY', 'learnpath_category');
113
define('TOOL_AGENDA', 'agenda');
114
define('TOOL_ANNOUNCEMENT', 'announcement');
115
define('TOOL_FORUM', 'forum');
116
define('TOOL_FORUM_CATEGORY', 'forum_category');
117
define('TOOL_FORUM_THREAD', 'forum_thread');
118
define('TOOL_FORUM_POST', 'forum_post');
119
define('TOOL_FORUM_ATTACH', 'forum_attachment');
120
define('TOOL_FORUM_THREAD_QUALIFY', 'forum_thread_qualify');
121
define('TOOL_THREAD', 'thread');
122
define('TOOL_POST', 'post');
123
define('TOOL_DROPBOX', 'dropbox');
124
define('TOOL_QUIZ', 'quiz');
125
define('TOOL_TEST_CATEGORY', 'test_category');
126
define('TOOL_USER', 'user');
127
define('TOOL_GROUP', 'group');
128
define('TOOL_BLOGS', 'blog_management');
129
define('TOOL_CHAT', 'chat');
130
define('TOOL_STUDENTPUBLICATION', 'student_publication');
131
define('TOOL_TRACKING', 'tracking');
132
define('TOOL_HOMEPAGE_LINK', 'homepage_link');
133
define('TOOL_COURSE_SETTING', 'course_setting');
134
define('TOOL_BACKUP', 'backup');
135
define('TOOL_COPY_COURSE_CONTENT', 'copy_course_content');
136
define('TOOL_RECYCLE_COURSE', 'recycle_course');
137
define('TOOL_COURSE_HOMEPAGE', 'course_homepage');
138
define('TOOL_COURSE_RIGHTS_OVERVIEW', 'course_rights');
139
define('TOOL_UPLOAD', 'file_upload');
140
define('TOOL_COURSE_MAINTENANCE', 'course_maintenance');
141
define('TOOL_SURVEY', 'survey');
142
define('TOOL_WIKI', 'wiki');
143
define('TOOL_GLOSSARY', 'glossary');
144
define('TOOL_GRADEBOOK', 'gradebook');
145
define('TOOL_NOTEBOOK', 'notebook');
146
define('TOOL_ATTENDANCE', 'attendance');
147
define('TOOL_COURSE_PROGRESS', 'course_progress');
148
define('TOOL_PORTFOLIO', 'portfolio');
149
define('TOOL_PLAGIARISM', 'compilatio');
150
define('TOOL_XAPI', 'xapi');
151
152
// CONSTANTS defining Chamilo interface sections
153
define('SECTION_CAMPUS', 'mycampus');
154
define('SECTION_COURSES', 'mycourses');
155
define('SECTION_CATALOG', 'catalog');
156
define('SECTION_MYPROFILE', 'myprofile');
157
define('SECTION_MYAGENDA', 'myagenda');
158
define('SECTION_COURSE_ADMIN', 'course_admin');
159
define('SECTION_PLATFORM_ADMIN', 'platform_admin');
160
define('SECTION_MYGRADEBOOK', 'mygradebook');
161
define('SECTION_TRACKING', 'session_my_space');
162
define('SECTION_SOCIAL', 'social-network');
163
define('SECTION_DASHBOARD', 'dashboard');
164
define('SECTION_REPORTS', 'reports');
165
define('SECTION_GLOBAL', 'global');
166
define('SECTION_INCLUDE', 'include');
167
define('SECTION_CUSTOMPAGE', 'custompage');
168
169
// CONSTANT name for local authentication source
170
define('PLATFORM_AUTH_SOURCE', 'platform');
171
define('CAS_AUTH_SOURCE', 'cas');
172
define('LDAP_AUTH_SOURCE', 'extldap');
173
174
// CONSTANT defining the default HotPotatoes files directory
175
define('DIR_HOTPOTATOES', '/HotPotatoes_files');
176
177
// event logs types
178
define('LOG_COURSE_DELETE', 'course_deleted');
179
define('LOG_COURSE_CREATE', 'course_created');
180
define('LOG_COURSE_SETTINGS_CHANGED', 'course_settings_changed');
181
182
// @todo replace 'soc_gr' with social_group
183
define('LOG_GROUP_PORTAL_CREATED', 'soc_gr_created');
184
define('LOG_GROUP_PORTAL_UPDATED', 'soc_gr_updated');
185
define('LOG_GROUP_PORTAL_DELETED', 'soc_gr_deleted');
186
define('LOG_GROUP_PORTAL_USER_DELETE_ALL', 'soc_gr_delete_users');
187
188
define('LOG_GROUP_PORTAL_ID', 'soc_gr_portal_id');
189
define('LOG_GROUP_PORTAL_REL_USER_ARRAY', 'soc_gr_user_array');
190
191
define('LOG_GROUP_PORTAL_USER_SUBSCRIBED', 'soc_gr_u_subs');
192
define('LOG_GROUP_PORTAL_USER_UNSUBSCRIBED', 'soc_gr_u_unsubs');
193
define('LOG_GROUP_PORTAL_USER_UPDATE_ROLE', 'soc_gr_update_role');
194
195
define('LOG_USER_DELETE', 'user_deleted');
196
define('LOG_USER_CREATE', 'user_created');
197
define('LOG_USER_UPDATE', 'user_updated');
198
define('LOG_USER_PASSWORD_UPDATE', 'user_password_updated');
199
define('LOG_USER_ENABLE', 'user_enable');
200
define('LOG_USER_DISABLE', 'user_disable');
201
define('LOG_USER_ANONYMIZE', 'user_anonymized');
202
define('LOG_USER_FIELD_CREATE', 'user_field_created');
203
define('LOG_USER_FIELD_DELETE', 'user_field_deleted');
204
define('LOG_SESSION_CREATE', 'session_created');
205
define('LOG_SESSION_DELETE', 'session_deleted');
206
define('LOG_SESSION_ADD_USER_COURSE', 'session_add_user_course');
207
define('LOG_SESSION_DELETE_USER_COURSE', 'session_delete_user_course');
208
define('LOG_SESSION_ADD_USER', 'session_add_user');
209
define('LOG_SESSION_DELETE_USER', 'session_delete_user');
210
define('LOG_SESSION_ADD_COURSE', 'session_add_course');
211
define('LOG_SESSION_DELETE_COURSE', 'session_delete_course');
212
define('LOG_SESSION_CATEGORY_CREATE', 'session_cat_created'); //changed in 1.9.8
213
define('LOG_SESSION_CATEGORY_DELETE', 'session_cat_deleted'); //changed in 1.9.8
214
define('LOG_CONFIGURATION_SETTINGS_CHANGE', 'settings_changed');
215
define('LOG_PLATFORM_LANGUAGE_CHANGE', 'platform_lng_changed'); //changed in 1.9.8
216
define('LOG_SUBSCRIBE_USER_TO_COURSE', 'user_subscribed');
217
define('LOG_UNSUBSCRIBE_USER_FROM_COURSE', 'user_unsubscribed');
218
define('LOG_ATTEMPTED_FORCED_LOGIN', 'attempted_forced_login');
219
define('LOG_PLUGIN_CHANGE', 'plugin_changed');
220
define('LOG_HOMEPAGE_CHANGED', 'homepage_changed');
221
define('LOG_PROMOTION_CREATE', 'promotion_created');
222
define('LOG_PROMOTION_DELETE', 'promotion_deleted');
223
define('LOG_CAREER_CREATE', 'career_created');
224
define('LOG_CAREER_DELETE', 'career_deleted');
225
define('LOG_USER_PERSONAL_DOC_DELETED', 'user_doc_deleted');
226
define('LOG_WIKI_ACCESS', 'wiki_page_view');
227
// All results from an exercise
228
define('LOG_EXERCISE_RESULT_DELETE', 'exe_result_deleted');
229
// Logs only the one attempt
230
define('LOG_EXERCISE_ATTEMPT_DELETE', 'exe_attempt_deleted');
231
define('LOG_LP_ATTEMPT_DELETE', 'lp_attempt_deleted');
232
define('LOG_QUESTION_RESULT_DELETE', 'qst_attempt_deleted');
233
define('LOG_QUESTION_SCORE_UPDATE', 'score_attempt_updated');
234
235
define('LOG_MY_FOLDER_CREATE', 'my_folder_created');
236
define('LOG_MY_FOLDER_CHANGE', 'my_folder_changed');
237
define('LOG_MY_FOLDER_DELETE', 'my_folder_deleted');
238
define('LOG_MY_FOLDER_COPY', 'my_folder_copied');
239
define('LOG_MY_FOLDER_CUT', 'my_folder_cut');
240
define('LOG_MY_FOLDER_PASTE', 'my_folder_pasted');
241
define('LOG_MY_FOLDER_UPLOAD', 'my_folder_uploaded');
242
243
// Event logs data types (max 20 chars)
244
define('LOG_COURSE_CODE', 'course_code');
245
define('LOG_COURSE_ID', 'course_id');
246
define('LOG_USER_ID', 'user_id');
247
define('LOG_USER_OBJECT', 'user_object');
248
define('LOG_USER_FIELD_VARIABLE', 'user_field_variable');
249
define('LOG_SESSION_ID', 'session_id');
250
251
define('LOG_QUESTION_ID', 'question_id');
252
define('LOG_SESSION_CATEGORY_ID', 'session_category_id');
253
define('LOG_CONFIGURATION_SETTINGS_CATEGORY', 'settings_category');
254
define('LOG_CONFIGURATION_SETTINGS_VARIABLE', 'settings_variable');
255
define('LOG_PLATFORM_LANGUAGE', 'default_platform_language');
256
define('LOG_PLUGIN_UPLOAD', 'plugin_upload');
257
define('LOG_PLUGIN_ENABLE', 'plugin_enable');
258
define('LOG_PLUGIN_SETTINGS_CHANGE', 'plugin_settings_change');
259
define('LOG_CAREER_ID', 'career_id');
260
define('LOG_PROMOTION_ID', 'promotion_id');
261
define('LOG_GRADEBOOK_LOCKED', 'gradebook_locked');
262
define('LOG_GRADEBOOK_UNLOCKED', 'gradebook_unlocked');
263
define('LOG_GRADEBOOK_ID', 'gradebook_id');
264
define('LOG_WIKI_PAGE_ID', 'wiki_page_id');
265
define('LOG_EXERCISE_ID', 'exercise_id');
266
define('LOG_EXERCISE_AND_USER_ID', 'exercise_and_user_id');
267
define('LOG_LP_ID', 'lp_id');
268
define('LOG_EXERCISE_ATTEMPT_QUESTION_ID', 'exercise_a_q_id');
269
define('LOG_EXERCISE_ATTEMPT', 'exe_id');
270
271
define('LOG_WORK_DIR_DELETE', 'work_dir_delete');
272
define('LOG_WORK_FILE_DELETE', 'work_file_delete');
273
define('LOG_WORK_DATA', 'work_data_array');
274
275
define('LOG_MY_FOLDER_PATH', 'path');
276
define('LOG_MY_FOLDER_NEW_PATH', 'new_path');
277
278
define('LOG_TERM_CONDITION_ACCEPTED', 'term_condition_accepted');
279
define('LOG_USER_CONFIRMED_EMAIL', 'user_confirmed_email');
280
define('LOG_USER_REMOVED_LEGAL_ACCEPT', 'user_removed_legal_accept');
281
282
define('LOG_USER_DELETE_ACCOUNT_REQUEST', 'user_delete_account_request');
283
284
define('LOG_QUESTION_CREATED', 'question_created');
285
define('LOG_QUESTION_UPDATED', 'question_updated');
286
define('LOG_QUESTION_DELETED', 'question_deleted');
287
define('LOG_QUESTION_REMOVED_FROM_QUIZ', 'question_removed_from_quiz');
288
289
define('LOG_SURVEY_ID', 'survey_id');
290
define('LOG_SURVEY_CREATED', 'survey_created');
291
define('LOG_SURVEY_DELETED', 'survey_deleted');
292
define('LOG_SURVEY_CLEAN_RESULTS', 'survey_clean_results');
293
294
define('USERNAME_PURIFIER', '/[^0-9A-Za-z_\.-]/');
295
296
//used when login_is_email setting is true
297
define('USERNAME_PURIFIER_MAIL', '/[^0-9A-Za-z_\.@]/');
298
define('USERNAME_PURIFIER_SHALLOW', '/\s/');
299
300
// This constant is a result of Windows OS detection, it has a boolean value:
301
// true whether the server runs on Windows OS, false otherwise.
302
define('IS_WINDOWS_OS', api_is_windows_os());
303
304
// Checks for installed optional php-extensions.
305
// intl extension (from PECL), it is installed by default as of PHP 5.3.0.
306
define('INTL_INSTALLED', function_exists('intl_get_error_code'));
307
// iconv extension, for PHP5 on Windows it is installed by default.
308
define('ICONV_INSTALLED', function_exists('iconv'));
309
define('MBSTRING_INSTALLED', function_exists('mb_strlen')); // mbstring extension.
310
311
// Patterns for processing paths. Examples.
312
define('REPEATED_SLASHES_PURIFIER', '/\/{2,}/'); // $path = preg_replace(REPEATED_SLASHES_PURIFIER, '/', $path);
313
define('VALID_WEB_PATH', '/https?:\/\/[^\/]*(\/.*)?/i'); // $is_valid_path = preg_match(VALID_WEB_PATH, $path);
314
// $new_path = preg_replace(VALID_WEB_SERVER_BASE, $new_base, $path);
315
define('VALID_WEB_SERVER_BASE', '/https?:\/\/[^\/]*/i');
316
// Constants for api_get_path() and api_get_path_type(), etc. - registered path types.
317
// basic (leaf elements)
318
define('REL_CODE_PATH', 'REL_CODE_PATH');
319
define('REL_COURSE_PATH', 'REL_COURSE_PATH');
320
define('REL_HOME_PATH', 'REL_HOME_PATH');
321
322
// Constants for api_get_path() and api_get_path_type(), etc. - registered path types.
323
define('WEB_PATH', 'WEB_PATH');
324
define('WEB_APP_PATH', 'WEB_APP_PATH');
325
define('SYS_PATH', 'SYS_PATH');
326
define('SYS_APP_PATH', 'SYS_APP_PATH');
327
define('SYS_UPLOAD_PATH', 'SYS_UPLOAD_PATH');
328
define('WEB_UPLOAD_PATH', 'WEB_UPLOAD_PATH');
329
330
define('REL_PATH', 'REL_PATH');
331
define('WEB_COURSE_PATH', 'WEB_COURSE_PATH');
332
define('SYS_COURSE_PATH', 'SYS_COURSE_PATH');
333
define('WEB_CODE_PATH', 'WEB_CODE_PATH');
334
define('SYS_CODE_PATH', 'SYS_CODE_PATH');
335
define('SYS_LANG_PATH', 'SYS_LANG_PATH');
336
define('WEB_IMG_PATH', 'WEB_IMG_PATH');
337
define('WEB_CSS_PATH', 'WEB_CSS_PATH');
338
define('WEB_PUBLIC_PATH', 'WEB_PUBLIC_PATH');
339
define('SYS_CSS_PATH', 'SYS_CSS_PATH');
340
define('SYS_PLUGIN_PATH', 'SYS_PLUGIN_PATH');
341
define('WEB_PLUGIN_PATH', 'WEB_PLUGIN_PATH');
342
define('WEB_PLUGIN_ASSET_PATH', 'WEB_PLUGIN_ASSET_PATH');
343
define('SYS_ARCHIVE_PATH', 'SYS_ARCHIVE_PATH');
344
define('WEB_ARCHIVE_PATH', 'WEB_ARCHIVE_PATH');
345
define('SYS_INC_PATH', 'SYS_INC_PATH');
346
define('LIBRARY_PATH', 'LIBRARY_PATH');
347
define('CONFIGURATION_PATH', 'CONFIGURATION_PATH');
348
define('WEB_LIBRARY_PATH', 'WEB_LIBRARY_PATH');
349
define('WEB_LIBRARY_JS_PATH', 'WEB_LIBRARY_JS_PATH');
350
define('WEB_AJAX_PATH', 'WEB_AJAX_PATH');
351
define('SYS_TEST_PATH', 'SYS_TEST_PATH');
352
define('WEB_TEMPLATE_PATH', 'WEB_TEMPLATE_PATH');
353
define('SYS_TEMPLATE_PATH', 'SYS_TEMPLATE_PATH');
354
define('SYS_PUBLIC_PATH', 'SYS_PUBLIC_PATH');
355
define('SYS_HOME_PATH', 'SYS_HOME_PATH');
356
define('WEB_HOME_PATH', 'WEB_HOME_PATH');
357
define('WEB_FONTS_PATH', 'WEB_FONTS_PATH');
358
define('SYS_FONTS_PATH', 'SYS_FONTS_PATH');
359
360
define('SYS_DEFAULT_COURSE_DOCUMENT_PATH', 'SYS_DEFAULT_COURSE_DOCUMENT_PATH');
361
define('REL_DEFAULT_COURSE_DOCUMENT_PATH', 'REL_DEFAULT_COURSE_DOCUMENT_PATH');
362
define('WEB_DEFAULT_COURSE_DOCUMENT_PATH', 'WEB_DEFAULT_COURSE_DOCUMENT_PATH');
363
364
// Relations type with Course manager
365
define('COURSE_RELATION_TYPE_COURSE_MANAGER', 1);
366
define('SESSION_RELATION_TYPE_COURSE_MANAGER', 1);
367
368
// Relations type with Human resources manager
369
define('COURSE_RELATION_TYPE_RRHH', 1);
370
define('SESSION_RELATION_TYPE_RRHH', 1);
371
372
//User image sizes
373
define('USER_IMAGE_SIZE_ORIGINAL', 1);
374
define('USER_IMAGE_SIZE_BIG', 2);
375
define('USER_IMAGE_SIZE_MEDIUM', 3);
376
define('USER_IMAGE_SIZE_SMALL', 4);
377
378
// Relation type between users
379
define('USER_UNKNOWN', 0);
380
define('USER_RELATION_TYPE_UNKNOWN', 1);
381
define('USER_RELATION_TYPE_PARENT', 2); // should be deprecated is useless
382
define('USER_RELATION_TYPE_FRIEND', 3);
383
define('USER_RELATION_TYPE_GOODFRIEND', 4); // should be deprecated is useless
384
define('USER_RELATION_TYPE_ENEMY', 5); // should be deprecated is useless
385
define('USER_RELATION_TYPE_DELETED', 6);
386
define('USER_RELATION_TYPE_RRHH', 7);
387
define('USER_RELATION_TYPE_BOSS', 8);
388
define('USER_RELATION_TYPE_HRM_REQUEST', 9);
389
390
// Gradebook link constants
391
// Please do not change existing values, they are used in the database !
392
define('GRADEBOOK_ITEM_LIMIT', 1000);
393
394
define('LINK_EXERCISE', 1);
395
define('LINK_DROPBOX', 2);
396
define('LINK_STUDENTPUBLICATION', 3);
397
define('LINK_LEARNPATH', 4);
398
define('LINK_FORUM_THREAD', 5);
399
//define('LINK_WORK',6);
400
define('LINK_ATTENDANCE', 7);
401
define('LINK_SURVEY', 8);
402
define('LINK_HOTPOTATOES', 9);
403
define('LINK_PORTFOLIO', 10);
404
405
// Score display types constants
406
define('SCORE_DIV', 1); // X / Y
407
define('SCORE_PERCENT', 2); // XX %
408
define('SCORE_DIV_PERCENT', 3); // X / Y (XX %)
409
define('SCORE_AVERAGE', 4); // XX %
410
define('SCORE_DECIMAL', 5); // 0.50  (X/Y)
411
define('SCORE_BAR', 6); // Uses the Display::bar_progress function
412
define('SCORE_SIMPLE', 7); // X
413
define('SCORE_IGNORE_SPLIT', 8); //  ??
414
define('SCORE_DIV_PERCENT_WITH_CUSTOM', 9); // X / Y (XX %) - Good!
415
define('SCORE_CUSTOM', 10); // Good!
416
define('SCORE_DIV_SIMPLE_WITH_CUSTOM', 11); // X - Good!
417
define('SCORE_DIV_SIMPLE_WITH_CUSTOM_LETTERS', 12); // X - Good!
418
define('SCORE_ONLY_SCORE', 13); // X - Good!
419
define('SCORE_NUMERIC', 14);
420
421
define('SCORE_BOTH', 1);
422
define('SCORE_ONLY_DEFAULT', 2);
423
define('SCORE_ONLY_CUSTOM', 3);
424
425
// From display.lib.php
426
427
define('MAX_LENGTH_BREADCRUMB', 100);
428
define('ICON_SIZE_ATOM', 8);
429
define('ICON_SIZE_TINY', 16);
430
define('ICON_SIZE_SMALL', 22);
431
define('ICON_SIZE_MEDIUM', 32);
432
define('ICON_SIZE_LARGE', 48);
433
define('ICON_SIZE_BIG', 64);
434
define('ICON_SIZE_HUGE', 128);
435
define('SHOW_TEXT_NEAR_ICONS', false);
436
437
// Session catalog
438
define('CATALOG_COURSES', 0);
439
define('CATALOG_SESSIONS', 1);
440
define('CATALOG_COURSES_SESSIONS', 2);
441
442
// Hook type events, pre-process and post-process.
443
// All means to be executed for both hook event types
444
define('HOOK_EVENT_TYPE_PRE', 0);
445
define('HOOK_EVENT_TYPE_POST', 1);
446
define('HOOK_EVENT_TYPE_ALL', 10);
447
448
define('CAREER_STATUS_ACTIVE', 1);
449
define('CAREER_STATUS_INACTIVE', 0);
450
451
define('PROMOTION_STATUS_ACTIVE', 1);
452
define('PROMOTION_STATUS_INACTIVE', 0);
453
454
// Group permissions
455
define('GROUP_PERMISSION_OPEN', '1');
456
define('GROUP_PERMISSION_CLOSED', '2');
457
458
// Group user permissions
459
define('GROUP_USER_PERMISSION_ADMIN', '1'); // the admin of a group
460
define('GROUP_USER_PERMISSION_READER', '2'); // a normal user
461
define('GROUP_USER_PERMISSION_PENDING_INVITATION', '3'); // When an admin/moderator invites a user
462
define('GROUP_USER_PERMISSION_PENDING_INVITATION_SENT_BY_USER', '4'); // an user joins a group
463
define('GROUP_USER_PERMISSION_MODERATOR', '5'); // a moderator
464
define('GROUP_USER_PERMISSION_ANONYMOUS', '6'); // an anonymous user
465
define('GROUP_USER_PERMISSION_HRM', '7'); // a human resources manager
466
467
define('GROUP_IMAGE_SIZE_ORIGINAL', 1);
468
define('GROUP_IMAGE_SIZE_BIG', 2);
469
define('GROUP_IMAGE_SIZE_MEDIUM', 3);
470
define('GROUP_IMAGE_SIZE_SMALL', 4);
471
define('GROUP_TITLE_LENGTH', 50);
472
473
// Exercise
474
// @todo move into a class
475
define('ALL_ON_ONE_PAGE', 1);
476
define('ONE_PER_PAGE', 2);
477
478
define('EXERCISE_FEEDBACK_TYPE_END', 0); //Feedback 		 - show score and expected answers
479
define('EXERCISE_FEEDBACK_TYPE_DIRECT', 1); //DirectFeedback - Do not show score nor answers
480
define('EXERCISE_FEEDBACK_TYPE_EXAM', 2); // NoFeedback 	 - Show score only
481
define('EXERCISE_FEEDBACK_TYPE_POPUP', 3); // Popup BT#15827
482
483
define('RESULT_DISABLE_SHOW_SCORE_AND_EXPECTED_ANSWERS', 0); //show score and expected answers
484
define('RESULT_DISABLE_NO_SCORE_AND_EXPECTED_ANSWERS', 1); //Do not show score nor answers
485
define('RESULT_DISABLE_SHOW_SCORE_ONLY', 2); //Show score only
486
define('RESULT_DISABLE_SHOW_FINAL_SCORE_ONLY_WITH_CATEGORIES', 3); //Show final score only with categories
487
define('RESULT_DISABLE_SHOW_SCORE_ATTEMPT_SHOW_ANSWERS_LAST_ATTEMPT', 4);
488
define('RESULT_DISABLE_DONT_SHOW_SCORE_ONLY_IF_USER_FINISHES_ATTEMPTS_SHOW_ALWAYS_FEEDBACK', 5);
489
define('RESULT_DISABLE_RANKING', 6);
490
define('RESULT_DISABLE_SHOW_ONLY_IN_CORRECT_ANSWER', 7);
491
define('RESULT_DISABLE_SHOW_SCORE_AND_EXPECTED_ANSWERS_AND_RANKING', 8);
492
define('RESULT_DISABLE_RADAR', 9);
493
define('RESULT_DISABLE_SHOW_SCORE_ATTEMPT_SHOW_ANSWERS_LAST_ATTEMPT_NO_FEEDBACK', 10);
494
495
define('EXERCISE_MAX_NAME_SIZE', 80);
496
497
// Question types (edit next array as well when adding values)
498
// @todo move into a class
499
define('UNIQUE_ANSWER', 1);
500
define('MULTIPLE_ANSWER', 2);
501
define('FILL_IN_BLANKS', 3);
502
define('MATCHING', 4);
503
define('FREE_ANSWER', 5);
504
define('HOT_SPOT', 6);
505
define('HOT_SPOT_ORDER', 7);
506
define('HOT_SPOT_DELINEATION', 8);
507
define('MULTIPLE_ANSWER_COMBINATION', 9);
508
define('UNIQUE_ANSWER_NO_OPTION', 10);
509
define('MULTIPLE_ANSWER_TRUE_FALSE', 11);
510
define('MULTIPLE_ANSWER_COMBINATION_TRUE_FALSE', 12);
511
define('ORAL_EXPRESSION', 13);
512
define('GLOBAL_MULTIPLE_ANSWER', 14);
513
define('MEDIA_QUESTION', 15);
514
define('CALCULATED_ANSWER', 16);
515
define('UNIQUE_ANSWER_IMAGE', 17);
516
define('DRAGGABLE', 18);
517
define('MATCHING_DRAGGABLE', 19);
518
define('ANNOTATION', 20);
519
define('READING_COMPREHENSION', 21);
520
define('MULTIPLE_ANSWER_TRUE_FALSE_DEGREE_CERTAINTY', 22);
521
522
define('EXERCISE_CATEGORY_RANDOM_SHUFFLED', 1);
523
define('EXERCISE_CATEGORY_RANDOM_ORDERED', 2);
524
define('EXERCISE_CATEGORY_RANDOM_DISABLED', 0);
525
526
// Question selection type
527
define('EX_Q_SELECTION_ORDERED', 1);
528
define('EX_Q_SELECTION_RANDOM', 2);
529
define('EX_Q_SELECTION_CATEGORIES_ORDERED_QUESTIONS_ORDERED', 3);
530
define('EX_Q_SELECTION_CATEGORIES_RANDOM_QUESTIONS_ORDERED', 4);
531
define('EX_Q_SELECTION_CATEGORIES_ORDERED_QUESTIONS_RANDOM', 5);
532
define('EX_Q_SELECTION_CATEGORIES_RANDOM_QUESTIONS_RANDOM', 6);
533
define('EX_Q_SELECTION_CATEGORIES_RANDOM_QUESTIONS_ORDERED_NO_GROUPED', 7);
534
define('EX_Q_SELECTION_CATEGORIES_RANDOM_QUESTIONS_RANDOM_NO_GROUPED', 8);
535
define('EX_Q_SELECTION_CATEGORIES_ORDERED_BY_PARENT_QUESTIONS_ORDERED', 9);
536
define('EX_Q_SELECTION_CATEGORIES_ORDERED_BY_PARENT_QUESTIONS_RANDOM', 10);
537
538
// Used to save the skill_rel_item table
539
define('ITEM_TYPE_EXERCISE', 1);
540
define('ITEM_TYPE_HOTPOTATOES', 2);
541
define('ITEM_TYPE_LINK', 3);
542
define('ITEM_TYPE_LEARNPATH', 4);
543
define('ITEM_TYPE_GRADEBOOK', 5);
544
define('ITEM_TYPE_STUDENT_PUBLICATION', 6);
545
//define('ITEM_TYPE_FORUM', 7);
546
define('ITEM_TYPE_ATTENDANCE', 8);
547
define('ITEM_TYPE_SURVEY', 9);
548
define('ITEM_TYPE_FORUM_THREAD', 10);
549
define('ITEM_TYPE_PORTFOLIO', 11);
550
551
// one big string with all question types, for the validator in pear/HTML/QuickForm/Rule/QuestionType
552
define(
553
    'QUESTION_TYPES',
554
    UNIQUE_ANSWER.':'.
555
    MULTIPLE_ANSWER.':'.
556
    FILL_IN_BLANKS.':'.
557
    MATCHING.':'.
558
    FREE_ANSWER.':'.
559
    HOT_SPOT.':'.
560
    HOT_SPOT_ORDER.':'.
561
    HOT_SPOT_DELINEATION.':'.
562
    MULTIPLE_ANSWER_COMBINATION.':'.
563
    UNIQUE_ANSWER_NO_OPTION.':'.
564
    MULTIPLE_ANSWER_TRUE_FALSE.':'.
565
    MULTIPLE_ANSWER_COMBINATION_TRUE_FALSE.':'.
566
    ORAL_EXPRESSION.':'.
567
    GLOBAL_MULTIPLE_ANSWER.':'.
568
    MEDIA_QUESTION.':'.
569
    CALCULATED_ANSWER.':'.
570
    UNIQUE_ANSWER_IMAGE.':'.
571
    DRAGGABLE.':'.
572
    MATCHING_DRAGGABLE.':'.
573
    MULTIPLE_ANSWER_TRUE_FALSE_DEGREE_CERTAINTY.':'.
574
    ANNOTATION
575
);
576
577
//Some alias used in the QTI exports
578
define('MCUA', 1);
579
define('TF', 1);
580
define('MCMA', 2);
581
define('FIB', 3);
582
583
// Skills
584
define('SKILL_TYPE_REQUIREMENT', 'required');
585
define('SKILL_TYPE_ACQUIRED', 'acquired');
586
define('SKILL_TYPE_BOTH', 'both');
587
588
// Message
589
define('MESSAGE_STATUS_NEW', '0');
590
define('MESSAGE_STATUS_UNREAD', '1');
591
//2 ??
592
define('MESSAGE_STATUS_DELETED', '3');
593
define('MESSAGE_STATUS_OUTBOX', '4');
594
define('MESSAGE_STATUS_INVITATION_PENDING', '5');
595
define('MESSAGE_STATUS_INVITATION_ACCEPTED', '6');
596
define('MESSAGE_STATUS_INVITATION_DENIED', '7');
597
define('MESSAGE_STATUS_WALL', '8');
598
define('MESSAGE_STATUS_WALL_DELETE', '9');
599
define('MESSAGE_STATUS_WALL_POST', '10');
600
define('MESSAGE_STATUS_CONVERSATION', '11');
601
define('MESSAGE_STATUS_FORUM', '12');
602
define('MESSAGE_STATUS_PROMOTED', '13');
603
604
// Images
605
define('IMAGE_WALL_SMALL_SIZE', 200);
606
define('IMAGE_WALL_MEDIUM_SIZE', 500);
607
define('IMAGE_WALL_BIG_SIZE', 2000);
608
define('IMAGE_WALL_SMALL', 'small');
609
define('IMAGE_WALL_MEDIUM', 'medium');
610
define('IMAGE_WALL_BIG', 'big');
611
612
// Social PLUGIN PLACES
613
define('SOCIAL_LEFT_PLUGIN', 1);
614
define('SOCIAL_CENTER_PLUGIN', 2);
615
define('SOCIAL_RIGHT_PLUGIN', 3);
616
define('CUT_GROUP_NAME', 50);
617
618
/**
619
 * FormValidator Filter.
620
 */
621
define('NO_HTML', 1);
622
define('STUDENT_HTML', 2);
623
define('TEACHER_HTML', 3);
624
define('STUDENT_HTML_FULLPAGE', 4);
625
define('TEACHER_HTML_FULLPAGE', 5);
626
627
// Timeline
628
define('TIMELINE_STATUS_ACTIVE', '1');
629
define('TIMELINE_STATUS_INACTIVE', '2');
630
631
// Event email template class
632
define('EVENT_EMAIL_TEMPLATE_ACTIVE', 1);
633
define('EVENT_EMAIL_TEMPLATE_INACTIVE', 0);
634
635
// Course home
636
define('SHORTCUTS_HORIZONTAL', 0);
637
define('SHORTCUTS_VERTICAL', 1);
638
639
// Image class
640
define('IMAGE_PROCESSOR', 'gd'); // 'imagick' or 'gd' strings
641
642
// Course copy
643
define('FILE_SKIP', 1);
644
define('FILE_RENAME', 2);
645
define('FILE_OVERWRITE', 3);
646
define('UTF8_CONVERT', false); //false by default
647
648
define('DOCUMENT', 'file');
649
define('FOLDER', 'folder');
650
651
define('RESOURCE_ASSET', 'asset');
652
define('RESOURCE_DOCUMENT', 'document');
653
define('RESOURCE_GLOSSARY', 'glossary');
654
define('RESOURCE_EVENT', 'calendar_event');
655
define('RESOURCE_LINK', 'link');
656
define('RESOURCE_COURSEDESCRIPTION', 'course_description');
657
define('RESOURCE_LEARNPATH', 'learnpath');
658
define('RESOURCE_LEARNPATH_CATEGORY', 'learnpath_category');
659
define('RESOURCE_ANNOUNCEMENT', 'announcement');
660
define('RESOURCE_FORUM', 'forum');
661
define('RESOURCE_FORUMTOPIC', 'thread');
662
define('RESOURCE_FORUMPOST', 'post');
663
define('RESOURCE_QUIZ', 'quiz');
664
define('RESOURCE_TEST_CATEGORY', 'test_category');
665
define('RESOURCE_QUIZQUESTION', 'Exercise_Question');
666
define('RESOURCE_TOOL_INTRO', 'Tool introduction');
667
define('RESOURCE_LINKCATEGORY', 'Link_Category');
668
define('RESOURCE_FORUMCATEGORY', 'Forum_Category');
669
define('RESOURCE_SCORM', 'Scorm');
670
define('RESOURCE_SURVEY', 'survey');
671
define('RESOURCE_SURVEYQUESTION', 'survey_question');
672
define('RESOURCE_SURVEYINVITATION', 'survey_invitation');
673
define('RESOURCE_WIKI', 'wiki');
674
define('RESOURCE_THEMATIC', 'thematic');
675
define('RESOURCE_ATTENDANCE', 'attendance');
676
define('RESOURCE_WORK', 'work');
677
define('RESOURCE_SESSION_COURSE', 'session_course');
678
define('RESOURCE_GRADEBOOK', 'gradebook');
679
define('ADD_THEMATIC_PLAN', 6);
680
681
// Max online users to show per page (whoisonline)
682
define('MAX_ONLINE_USERS', 12);
683
684
// Number of characters maximum to show in preview of course blog posts
685
define('BLOG_MAX_PREVIEW_CHARS', 800);
686
// HTML string to replace with a 'Read more...' link
687
define('BLOG_PAGE_BREAK', '<div style="page-break-after: always"><span style="display: none;">&nbsp;</span></div>');
688
689
// Make sure the CHAMILO_LOAD_WYSIWYG constant is defined
690
// To remove CKeditor libs from HTML, set this constant to true before loading
691
if (!defined('CHAMILO_LOAD_WYSIWYG')) {
692
    define('CHAMILO_LOAD_WYSIWYG', true);
693
}
694
695
/* Constants for course home */
696
define('TOOL_PUBLIC', 'Public');
697
define('TOOL_PUBLIC_BUT_HIDDEN', 'PublicButHide');
698
define('TOOL_COURSE_ADMIN', 'courseAdmin');
699
define('TOOL_PLATFORM_ADMIN', 'platformAdmin');
700
define('TOOL_AUTHORING', 'toolauthoring');
701
define('TOOL_INTERACTION', 'toolinteraction');
702
define('TOOL_COURSE_PLUGIN', 'toolcourseplugin'); //all plugins that can be enabled in courses
703
define('TOOL_ADMIN', 'tooladmin');
704
define('TOOL_ADMIN_PLATFORM', 'tooladminplatform');
705
define('TOOL_DRH', 'tool_drh');
706
define('TOOL_STUDENT_VIEW', 'toolstudentview');
707
define('TOOL_ADMIN_VISIBLE', 'tooladminvisible');
708
709
/**
710
 * Inclusion of internationalization libraries.
711
 */
712
require_once __DIR__.'/internationalization.lib.php';
713
714
/**
715
 * Returns a path to a certain resource within the Chamilo area, specifyed through a parameter.
716
 * Also, this function provides conversion between path types, in this case the input path points inside the Chamilo area too.
717
 *
718
 * See $_configuration['course_folder'] in the configuration.php to alter the WEB_COURSE_PATH and SYS_COURSE_PATH parameters.
719
720
 *
721
 * @param string $path (optional)   A path which type is to be converted. Also, it may be a defined constant for a path.
722
 *                     This parameter has meaning when $type parameter has one of the following values: TO_WEB, TO_SYS, TO_REL. Otherwise it is ignored.
723
 *
724
 * @return string the requested path or the converted path
725
 *
726
 * Notes about the current behaviour model:
727
 * 1. Windows back-slashes are converted to slashes in the result.
728
 * 2. A semi-absolute web-path is detected by its leading slash. On Linux systems, absolute system paths start with
729
 * a slash too, so an additional check about presence of leading system server base is implemented. For example, the function is
730
 * able to distinguish type difference between /var/www/chamilo/courses/ (SYS) and /chamilo/courses/ (REL).
731
 * 3. The function api_get_path() returns only these three types of paths, which in some sense are absolute. The function has
732
 * no a mechanism for processing relative web/system paths, such as: lesson01.html, ./lesson01.html, ../css/my_styles.css.
733
 * It has not been identified as needed yet.
734
 * 4. Also, resolving the meta-symbols "." and ".." within paths has not been implemented, it is to be identified as needed.
735
 *
736
 * For examples go to: *
737
 * See main/admin/system_status.php?section=paths
738
 *
739
 * Vchamilo changes : allow using an alternate configuration
740
 * to get vchamilo  instance paths
741
 */
742
function api_get_path($path = '', $configuration = [])
743
{
744
    global $paths;
745
746
    // get proper configuration data if exists
747
    global $_configuration;
748
749
    $emptyConfigurationParam = false;
750
    if (empty($configuration)) {
751
        $configuration = (array) $_configuration;
752
        $emptyConfigurationParam = true;
753
    }
754
755
    $course_folder = 'courses/';
756
    static $root_web = '';
757
    $root_sys = null;
758
    if ($_configuration) {
759
        $root_sys = $_configuration['root_sys'];
760
    }
761
762
    // If no $root_web has been set so far *and* no custom config has been passed to the function
763
    // then re-use the previously-calculated (run-specific) $root_web and skip this complex calculation
764
    if (empty($root_web) || $emptyConfigurationParam === false || empty($configuration)) {
765
        // Resolve master hostname.
766
        if (!empty($configuration) && array_key_exists('root_web', $configuration)) {
767
            $root_web = $configuration['root_web'];
768
        } else {
769
            $root_web = '';
770
            // Try guess it from server.
771
            if (defined('SYSTEM_INSTALLATION') && SYSTEM_INSTALLATION) {
772
                if (($pos = strpos(($requested_page_rel = api_get_self()), 'main/install')) !== false) {
773
                    $root_rel = substr($requested_page_rel, 0, $pos);
774
                    // See http://www.mediawiki.org/wiki/Manual:$wgServer
775
                    $server_protocol = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') ? 'https' : 'http';
776
                    $server_name =
777
                        isset($_SERVER['SERVER_NAME']) ? $_SERVER['SERVER_NAME']
778
                            : (isset($_SERVER['HOSTNAME']) ? $_SERVER['HOSTNAME']
779
                            : (isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST']
780
                                : (isset($_SERVER['SERVER_ADDR']) ? $_SERVER['SERVER_ADDR']
781
                                    : 'localhost')));
782
                    if (isset($_SERVER['SERVER_PORT']) &&
783
                        !strpos($server_name, ':') &&
784
                        (($server_protocol == 'http' && $_SERVER['SERVER_PORT'] != 80) ||
785
                        ($server_protocol == 'https' && $_SERVER['SERVER_PORT'] != 443))
786
                    ) {
787
                        $server_name .= ":".$_SERVER['SERVER_PORT'];
788
                    }
789
                    $root_web = $server_protocol.'://'.$server_name.$root_rel;
790
                    $root_sys = str_replace('\\', '/', realpath(__DIR__.'/../../../')).'/';
791
                }
792
                // Here we give up, so we don't touch anything.
793
            }
794
        }
795
    }
796
797
    if (isset($configuration['multiple_access_urls']) &&
798
        $configuration['multiple_access_urls']
799
    ) {
800
        // To avoid that the api_get_access_url() function fails since global.inc.php also calls the api.lib.php.
801
        if (isset($configuration['access_url']) && !empty($configuration['access_url'])) {
802
            // We look into the DB the function api_get_access_url
803
            $urlInfo = api_get_access_url($configuration['access_url']);
804
            // Avoid default value
805
            $defaultValues = ['http://localhost/', 'https://localhost/'];
806
            if (!empty($urlInfo['url']) && !in_array($urlInfo['url'], $defaultValues)) {
807
                $root_web = $urlInfo['active'] == 1 ? $urlInfo['url'] : $configuration['root_web'];
808
            }
809
        }
810
    }
811
812
    $paths = [];
813
    // Initialise cache with default values.
814
    if (!array_key_exists($root_web, $paths)) {
815
        $paths[$root_web] = [
816
            WEB_PATH => '',
817
            SYS_PATH => '',
818
            REL_PATH => '',
819
            WEB_COURSE_PATH => '',
820
            SYS_COURSE_PATH => '',
821
            REL_COURSE_PATH => '',
822
            WEB_CODE_PATH => 'main/',
823
            SYS_CODE_PATH => 'main/',
824
            REL_CODE_PATH => '/main/',
825
            SYS_LANG_PATH => 'lang/',
826
            WEB_IMG_PATH => 'img/',
827
            WEB_CSS_PATH => 'web/css/',
828
            SYS_CSS_PATH => 'app/Resources/public/css/',
829
            SYS_PLUGIN_PATH => 'plugin/',
830
            WEB_PLUGIN_PATH => 'plugin/',
831
            WEB_PLUGIN_ASSET_PATH => 'public/plugins/',
832
            SYS_ARCHIVE_PATH => 'app/cache/',
833
            WEB_ARCHIVE_PATH => 'app/cache/',
834
            SYS_HOME_PATH => 'app/home/',
835
            WEB_HOME_PATH => 'app/home/',
836
            REL_HOME_PATH => 'app/home/',
837
            SYS_APP_PATH => 'app/',
838
            WEB_APP_PATH => 'app/',
839
            SYS_UPLOAD_PATH => 'app/upload/',
840
            SYS_INC_PATH => 'inc/',
841
            CONFIGURATION_PATH => 'app/config/',
842
            LIBRARY_PATH => 'inc/lib/',
843
            WEB_LIBRARY_PATH => 'inc/lib/',
844
            WEB_LIBRARY_JS_PATH => 'inc/lib/javascript/',
845
            WEB_AJAX_PATH => 'inc/ajax/',
846
            SYS_TEST_PATH => 'tests/',
847
            WEB_TEMPLATE_PATH => 'template/',
848
            SYS_TEMPLATE_PATH => 'template/',
849
            WEB_UPLOAD_PATH => 'app/upload/',
850
            WEB_PUBLIC_PATH => 'web/',
851
            SYS_PUBLIC_PATH => 'web/',
852
            WEB_FONTS_PATH => 'fonts/',
853
            SYS_FONTS_PATH => 'fonts/',
854
        ];
855
    }
856
857
    $isInitialized = [];
858
    $course_folder = isset($configuration['course_folder']) ? $configuration['course_folder'] : $course_folder;
859
    $root_rel = isset($configuration['url_append']) ? $configuration['url_append'] : '';
860
    if (!empty($root_rel)) {
861
        // Adds "/" to the root_rel
862
        $hasSlash = substr($configuration['url_append'], 0, 1);
863
        if ($hasSlash !== '/') {
864
            $root_rel = '/'.$root_rel;
865
        }
866
    }
867
868
    // Web server base and system server base.
869
    if (!array_key_exists($root_web, $isInitialized)) {
870
        // process absolute global roots
871
        if (!empty($configuration)) {
872
            $code_folder = 'main';
873
        } else {
874
            $code_folder = $paths[$root_web][REL_CODE_PATH];
875
        }
876
877
        // Support for the installation process.
878
        // Developers might use the function api_get_path() directly or indirectly (this is difficult to be traced), at the moment when
879
        // configuration has not been created yet. This is why this function should be upgraded to return correct results in this case.
880
881
        // Dealing with trailing slashes.
882
        $slashed_root_web = api_add_trailing_slash($root_web);
883
        $root_sys = api_add_trailing_slash($root_sys);
884
        $root_rel = api_add_trailing_slash($root_rel);
885
        $code_folder = api_add_trailing_slash($code_folder);
886
        $course_folder = api_add_trailing_slash($course_folder);
887
888
        // Initialization of a table that contains common-purpose paths.
889
        $paths[$root_web][REL_PATH] = $root_rel;
890
        $paths[$root_web][REL_COURSE_PATH] = $root_rel.$course_folder;
891
        $paths[$root_web][REL_CODE_PATH] = $root_rel.$code_folder;
892
        $paths[$root_web][REL_DEFAULT_COURSE_DOCUMENT_PATH] = $paths[$root_web][REL_PATH].'main/default_course_document/';
893
894
        $paths[$root_web][WEB_PATH] = $slashed_root_web;
895
        $paths[$root_web][WEB_CODE_PATH] = $paths[$root_web][WEB_PATH].$code_folder;
896
        $paths[$root_web][WEB_COURSE_PATH] = $paths[$root_web][WEB_PATH].$course_folder;
897
        $paths[$root_web][WEB_DEFAULT_COURSE_DOCUMENT_PATH] = $paths[$root_web][WEB_CODE_PATH].'default_course_document/';
898
        $paths[$root_web][WEB_APP_PATH] = $paths[$root_web][WEB_PATH].$paths[$root_web][WEB_APP_PATH];
899
        $paths[$root_web][WEB_PLUGIN_PATH] = $paths[$root_web][WEB_PATH].$paths[$root_web][WEB_PLUGIN_PATH];
900
        $paths[$root_web][WEB_PLUGIN_ASSET_PATH] = $paths[$root_web][WEB_PATH].$paths[$root_web][WEB_PLUGIN_ASSET_PATH];
901
        $paths[$root_web][WEB_ARCHIVE_PATH] = $paths[$root_web][WEB_PATH].$paths[$root_web][WEB_ARCHIVE_PATH];
902
903
        $paths[$root_web][WEB_CSS_PATH] = $paths[$root_web][WEB_PATH].$paths[$root_web][WEB_CSS_PATH];
904
        $paths[$root_web][WEB_IMG_PATH] = $paths[$root_web][WEB_CODE_PATH].$paths[$root_web][WEB_IMG_PATH];
905
        $paths[$root_web][WEB_LIBRARY_PATH] = $paths[$root_web][WEB_CODE_PATH].$paths[$root_web][WEB_LIBRARY_PATH];
906
        $paths[$root_web][WEB_LIBRARY_JS_PATH] = $paths[$root_web][WEB_CODE_PATH].$paths[$root_web][WEB_LIBRARY_JS_PATH];
907
        $paths[$root_web][WEB_AJAX_PATH] = $paths[$root_web][WEB_CODE_PATH].$paths[$root_web][WEB_AJAX_PATH];
908
        $paths[$root_web][WEB_FONTS_PATH] = $paths[$root_web][WEB_CODE_PATH].$paths[$root_web][WEB_FONTS_PATH];
909
        $paths[$root_web][WEB_TEMPLATE_PATH] = $paths[$root_web][WEB_CODE_PATH].$paths[$root_web][WEB_TEMPLATE_PATH];
910
        $paths[$root_web][WEB_UPLOAD_PATH] = $paths[$root_web][WEB_PATH].$paths[$root_web][WEB_UPLOAD_PATH];
911
        $paths[$root_web][WEB_PUBLIC_PATH] = $paths[$root_web][WEB_PATH].$paths[$root_web][WEB_PUBLIC_PATH];
912
        $paths[$root_web][WEB_HOME_PATH] = $paths[$root_web][WEB_PATH].$paths[$root_web][REL_HOME_PATH];
913
914
        $paths[$root_web][SYS_PATH] = $root_sys;
915
        $paths[$root_web][SYS_CODE_PATH] = $root_sys.$code_folder;
916
        $paths[$root_web][SYS_TEST_PATH] = $paths[$root_web][SYS_PATH].$paths[$root_web][SYS_TEST_PATH];
917
        $paths[$root_web][SYS_TEMPLATE_PATH] = $paths[$root_web][SYS_CODE_PATH].$paths[$root_web][SYS_TEMPLATE_PATH];
918
        $paths[$root_web][SYS_PUBLIC_PATH] = $paths[$root_web][SYS_PATH].$paths[$root_web][SYS_PUBLIC_PATH];
919
        $paths[$root_web][SYS_CSS_PATH] = $paths[$root_web][SYS_PATH].$paths[$root_web][SYS_CSS_PATH];
920
        $paths[$root_web][SYS_FONTS_PATH] = $paths[$root_web][SYS_CODE_PATH].$paths[$root_web][SYS_FONTS_PATH];
921
        $paths[$root_web][SYS_ARCHIVE_PATH] = $paths[$root_web][SYS_PATH].$paths[$root_web][SYS_ARCHIVE_PATH];
922
        $paths[$root_web][SYS_APP_PATH] = $paths[$root_web][SYS_PATH].$paths[$root_web][SYS_APP_PATH];
923
        $paths[$root_web][SYS_COURSE_PATH] = $paths[$root_web][SYS_APP_PATH].$course_folder;
924
        $paths[$root_web][SYS_UPLOAD_PATH] = $paths[$root_web][SYS_PATH].$paths[$root_web][SYS_UPLOAD_PATH];
925
        $paths[$root_web][SYS_LANG_PATH] = $paths[$root_web][SYS_CODE_PATH].$paths[$root_web][SYS_LANG_PATH];
926
        $paths[$root_web][SYS_HOME_PATH] = $paths[$root_web][SYS_PATH].$paths[$root_web][SYS_HOME_PATH];
927
        $paths[$root_web][SYS_PLUGIN_PATH] = $paths[$root_web][SYS_PATH].$paths[$root_web][SYS_PLUGIN_PATH];
928
        $paths[$root_web][SYS_INC_PATH] = $paths[$root_web][SYS_CODE_PATH].$paths[$root_web][SYS_INC_PATH];
929
930
        $paths[$root_web][LIBRARY_PATH] = $paths[$root_web][SYS_CODE_PATH].$paths[$root_web][LIBRARY_PATH];
931
        $paths[$root_web][CONFIGURATION_PATH] = $paths[$root_web][SYS_PATH].$paths[$root_web][CONFIGURATION_PATH];
932
933
        global $virtualChamilo;
934
        if (!empty($virtualChamilo)) {
935
            $paths[$root_web][SYS_ARCHIVE_PATH] = api_add_trailing_slash($virtualChamilo[SYS_ARCHIVE_PATH]);
936
            $paths[$root_web][SYS_HOME_PATH] = api_add_trailing_slash($virtualChamilo[SYS_HOME_PATH]);
937
            $paths[$root_web][SYS_COURSE_PATH] = api_add_trailing_slash($virtualChamilo[SYS_COURSE_PATH]);
938
            $paths[$root_web][SYS_UPLOAD_PATH] = api_add_trailing_slash($virtualChamilo[SYS_UPLOAD_PATH]);
939
940
            $paths[$root_web][WEB_HOME_PATH] = api_add_trailing_slash($virtualChamilo[WEB_HOME_PATH]);
941
            $paths[$root_web][WEB_UPLOAD_PATH] = api_add_trailing_slash($virtualChamilo[WEB_UPLOAD_PATH]);
942
            $paths[$root_web][WEB_ARCHIVE_PATH] = api_add_trailing_slash($virtualChamilo[WEB_ARCHIVE_PATH]);
943
            //$paths[$root_web][WEB_COURSE_PATH] = api_add_trailing_slash($virtualChamilo[WEB_COURSE_PATH]);
944
945
            // WEB_UPLOAD_PATH should be handle by apache htaccess in the vhost
946
947
            // RewriteEngine On
948
            // RewriteRule /app/upload/(.*)$ http://localhost/other/upload/my-chamilo111-net/$1 [QSA,L]
949
950
            //$paths[$root_web][WEB_UPLOAD_PATH] = api_add_trailing_slash($virtualChamilo[WEB_UPLOAD_PATH]);
951
            //$paths[$root_web][REL_PATH] = $virtualChamilo[REL_PATH];
952
            //$paths[$root_web][REL_COURSE_PATH] = $virtualChamilo[REL_COURSE_PATH];
953
        }
954
955
        $isInitialized[$root_web] = true;
956
    }
957
958
    $path = trim($path);
959
960
    // Retrieving a common-purpose path.
961
    if (isset($paths[$root_web][$path])) {
962
        return $paths[$root_web][$path];
963
    }
964
965
    // Second purification.
966
967
    // Replacing Windows back slashes.
968
    $path = str_replace('\\', '/', $path);
969
    // Query strings sometimes mighth wrongly appear in non-URLs.
970
    // Let us check remove them from all types of paths.
971
    if (($pos = strpos($path, '?')) !== false) {
972
        $path = substr($path, 0, $pos);
973
    }
974
975
    // Detection of the input path type. Conversion to semi-absolute type ( /chamilo/main/inc/.... ).
976
977
    if (preg_match(VALID_WEB_PATH, $path)) {
978
        // A special case: When a URL points to the document download script directly, without
979
        // mod-rewrite translation, we have to translate it into an "ordinary" web path.
980
        // For example:
981
        // http://localhost/chamilo/main/document/download.php?doc_url=/image.png&cDir=/
982
        // becomes
983
        // http://localhost/chamilo/courses/TEST/document/image.png
984
        // TEST is a course directory name, so called "system course code".
985
        if (strpos($path, 'download.php') !== false) { // Fast detection first.
986
            $path = urldecode($path);
987
            if (preg_match('/(.*)main\/document\/download.php\?doc_url=\/(.*)&cDir=\/(.*)?/', $path, $matches)) {
988
                $sys_course_code =
989
                    isset($_SESSION['_course']['sysCode'])  // User is inside a course?
990
                        ? $_SESSION['_course']['sysCode']   // Yes, then use course's directory name.
991
                        : '{SYS_COURSE_CODE}'; // No, then use a fake code, it may be processed later.
992
                $path = $matches[1].'courses/'.$sys_course_code.'/document/'.str_replace('//', '/', $matches[3].'/'.$matches[2]);
993
            }
994
        }
995
        // Replacement of the present web server base with a slash '/'.
996
        $path = preg_replace(VALID_WEB_SERVER_BASE, '/', $path);
997
    }
998
999
    // Path now is semi-absolute. It is convenient at this moment repeated slashes to be removed.
1000
    $path = preg_replace(REPEATED_SLASHES_PURIFIER, '/', $path);
1001
1002
    return $path;
1003
}
1004
1005
/**
1006
 * Gets a modified version of the path for the CDN, if defined in
1007
 * configuration.php.
1008
 *
1009
 * @param string $web_path The path of the resource without CDN
1010
 *
1011
 * @return string The path of the resource converted to CDN
1012
 *
1013
 * @author Yannick Warnier <[email protected]>
1014
 */
1015
function api_get_cdn_path($web_path)
1016
{
1017
    global $_configuration;
1018
    if (!empty($_configuration['cdn_enable'])) {
1019
        $web_root = api_get_path(WEB_PATH);
1020
        $ext = substr($web_path, strrpos($web_path, '.'));
1021
        if (isset($ext[2])) { // faster version of strlen to check if len>2
1022
            // Check for CDN definitions
1023
            if (!empty($ext)) {
1024
                foreach ($_configuration['cdn'] as $host => $exts) {
1025
                    if (in_array($ext, $exts)) {
1026
                        //Use host as defined in $_configuration['cdn'], without
1027
                        // trailing slash
1028
                        return str_replace($web_root, $host.'/', $web_path);
1029
                    }
1030
                }
1031
            }
1032
        }
1033
    }
1034
1035
    return $web_path;
1036
}
1037
1038
/**
1039
 * @return bool Return true if CAS authentification is activated
1040
 */
1041
function api_is_cas_activated()
1042
{
1043
    return api_get_setting('cas_activate') == "true";
1044
}
1045
1046
/**
1047
 * @return bool Return true if LDAP authentification is activated
1048
 */
1049
function api_is_ldap_activated()
1050
{
1051
    global $extAuthSource;
1052
1053
    return is_array($extAuthSource[LDAP_AUTH_SOURCE]);
1054
}
1055
1056
/**
1057
 * @return bool Return true if Facebook authentification is activated
1058
 */
1059
function api_is_facebook_auth_activated()
1060
{
1061
    global $_configuration;
1062
1063
    return isset($_configuration['facebook_auth']) && $_configuration['facebook_auth'] == 1;
1064
}
1065
1066
/**
1067
 * Adds to a given path a trailing slash if it is necessary (adds "/" character at the end of the string).
1068
 *
1069
 * @param string $path the input path
1070
 *
1071
 * @return string returns the modified path
1072
 */
1073
function api_add_trailing_slash($path)
1074
{
1075
    return substr($path, -1) == '/' ? $path : $path.'/';
1076
}
1077
1078
/**
1079
 * Removes from a given path the trailing slash if it is necessary (removes "/" character from the end of the string).
1080
 *
1081
 * @param string $path the input path
1082
 *
1083
 * @return string returns the modified path
1084
 */
1085
function api_remove_trailing_slash($path)
1086
{
1087
    return substr($path, -1) == '/' ? substr($path, 0, -1) : $path;
1088
}
1089
1090
/**
1091
 * Checks the RFC 3986 syntax of a given URL.
1092
 *
1093
 * @param string $url      the URL to be checked
1094
 * @param bool   $absolute whether the URL is absolute (beginning with a scheme such as "http:")
1095
 *
1096
 * @return string|false Returns the URL if it is valid, FALSE otherwise.
1097
 *                      This function is an adaptation from the function valid_url(), Drupal CMS.
1098
 *
1099
 * @see http://drupal.org
1100
 * Note: The built-in function filter_var($urs, FILTER_VALIDATE_URL) has a bug for some versions of PHP.
1101
 * @see http://bugs.php.net/51192
1102
 */
1103
function api_valid_url($url, $absolute = false)
1104
{
1105
    if ($absolute) {
1106
        if (preg_match("
1107
            /^                                                      # Start at the beginning of the text
1108
            (?:ftp|https?|feed):\/\/                                # Look for ftp, http, https or feed schemes
1109
            (?:                                                     # Userinfo (optional) which is typically
1110
                (?:(?:[\w\.\-\+!$&'\(\)*\+,;=]|%[0-9a-f]{2})+:)*    # a username or a username and password
1111
                (?:[\w\.\-\+%!$&'\(\)*\+,;=]|%[0-9a-f]{2})+@        # combination
1112
            )?
1113
            (?:
1114
                (?:[a-z0-9\-\.]|%[0-9a-f]{2})+                      # A domain name or a IPv4 address
1115
                |(?:\[(?:[0-9a-f]{0,4}:)*(?:[0-9a-f]{0,4})\])       # or a well formed IPv6 address
1116
            )
1117
            (?::[0-9]+)?                                            # Server port number (optional)
1118
            (?:[\/|\?]
1119
                (?:[\w#!:\.\?\+=&@$'~*,;\/\(\)\[\]\-]|%[0-9a-f]{2}) # The path and query (optional)
1120
            *)?
1121
            $/xi", $url)) {
1122
            return $url;
1123
        }
1124
1125
        return false;
1126
    } else {
1127
        return preg_match("/^(?:[\w#!:\.\?\+=&@$'~*,;\/\(\)\[\]\-]|%[0-9a-f]{2})+$/i", $url) ? $url : false;
1128
    }
1129
}
1130
1131
/**
1132
 * Checks whether a given string looks roughly like an email address.
1133
 *
1134
 * @param string $address the e-mail address to be checked
1135
 *
1136
 * @return mixed returns the e-mail if it is valid, FALSE otherwise
1137
 */
1138
function api_valid_email($address)
1139
{
1140
    return filter_var($address, FILTER_VALIDATE_EMAIL);
1141
}
1142
1143
/* PROTECTION FUNCTIONS
1144
   Use these functions to protect your scripts. */
1145
1146
/**
1147
 * Function used to protect a course script.
1148
 * The function blocks access when
1149
 * - there is no $_SESSION["_course"] defined; or
1150
 * - $is_allowed_in_course is set to false (this depends on the course
1151
 * visibility and user status).
1152
 *
1153
 * This is only the first proposal, test and improve!
1154
 *
1155
 * @param bool Option to print headers when displaying error message. Default: false
1156
 * @param bool whether session admins should be allowed or not
1157
 * @param bool $checkTool check if tool is available for users (user, group)
1158
 *
1159
 * @return bool True if the user has access to the current course or is out of a course context, false otherwise
1160
 *
1161
 * @todo replace global variable
1162
 *
1163
 * @author Roan Embrechts
1164
 */
1165
function api_protect_course_script($print_headers = false, $allow_session_admins = false, $checkTool = '')
1166
{
1167
    $course_info = api_get_course_info();
1168
    if (empty($course_info)) {
1169
        api_not_allowed($print_headers);
1170
1171
        return false;
1172
    }
1173
1174
    if (api_is_drh()) {
1175
        return true;
1176
    }
1177
1178
    // Session admin has access to course
1179
    $sessionAccess = api_get_configuration_value('session_admins_access_all_content');
1180
    if ($sessionAccess) {
1181
        $allow_session_admins = true;
1182
    }
1183
1184
    if (api_is_platform_admin($allow_session_admins)) {
1185
        return true;
1186
    }
1187
1188
    $isAllowedInCourse = api_is_allowed_in_course();
1189
    $is_visible = false;
1190
    if (isset($course_info) && isset($course_info['visibility'])) {
1191
        switch ($course_info['visibility']) {
1192
            default:
1193
            case COURSE_VISIBILITY_CLOSED:
1194
                // Completely closed: the course is only accessible to the teachers. - 0
1195
                if ($isAllowedInCourse && api_get_user_id() && !api_is_anonymous()) {
1196
                    $is_visible = true;
1197
                }
1198
                break;
1199
            case COURSE_VISIBILITY_REGISTERED:
1200
                // Private - access authorized to course members only - 1
1201
                if ($isAllowedInCourse && api_get_user_id() && !api_is_anonymous()) {
1202
                    $is_visible = true;
1203
                }
1204
                break;
1205
            case COURSE_VISIBILITY_OPEN_PLATFORM:
1206
                // Open - access allowed for users registered on the platform - 2
1207
                if ($isAllowedInCourse && api_get_user_id() && !api_is_anonymous()) {
1208
                    $is_visible = true;
1209
                }
1210
                break;
1211
            case COURSE_VISIBILITY_OPEN_WORLD:
1212
                //Open - access allowed for the whole world - 3
1213
                $is_visible = true;
1214
                break;
1215
            case COURSE_VISIBILITY_HIDDEN:
1216
                //Completely closed: the course is only accessible to the teachers. - 0
1217
                if (api_is_platform_admin()) {
1218
                    $is_visible = true;
1219
                }
1220
                break;
1221
        }
1222
1223
        // If password is set and user is not registered to the course then the course is not visible.
1224
        if (false == $isAllowedInCourse &&
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like you are loosely comparing two booleans. Considering using the strict comparison === instead.

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

Loading history...
1225
            isset($course_info['registration_code']) && !empty($course_info['registration_code'])
1226
        ) {
1227
            $is_visible = false;
1228
        }
1229
    }
1230
1231
    if (!empty($checkTool)) {
1232
        if (!api_is_allowed_to_edit(true, true, true)) {
1233
            $toolInfo = api_get_tool_information_by_name($checkTool);
1234
            if (!empty($toolInfo) && isset($toolInfo['visibility']) && $toolInfo['visibility'] == 0) {
1235
                api_not_allowed(true);
1236
1237
                return false;
1238
            }
1239
        }
1240
    }
1241
1242
    // Check session visibility
1243
    $session_id = api_get_session_id();
1244
1245
    if (!empty($session_id)) {
1246
        // $isAllowedInCourse was set in local.inc.php
1247
        if (!$isAllowedInCourse) {
1248
            $is_visible = false;
1249
        }
1250
    }
1251
1252
    if (!$is_visible) {
1253
        api_not_allowed($print_headers);
1254
1255
        return false;
1256
    }
1257
1258
    if ($is_visible && 'true' === api_get_plugin_setting('positioning', 'tool_enable')) {
1259
        $plugin = Positioning::create();
1260
        $block = $plugin->get('block_course_if_initial_exercise_not_attempted');
1261
        if ('true' === $block) {
1262
            $currentPath = $_SERVER['PHP_SELF'];
1263
            // Allowed only this course paths.
1264
            $paths = [
1265
                '/plugin/positioning/start.php',
1266
                '/plugin/positioning/start_student.php',
1267
                '/main/course_home/course_home.php',
1268
                '/main/exercise/overview.php',
1269
            ];
1270
1271
            if (!in_array($currentPath, $paths, true)) {
1272
                // Check if entering an exercise.
1273
                global $current_course_tool;
1274
                if ('quiz' !== $current_course_tool) {
1275
                    $initialData = $plugin->getInitialExercise($course_info['real_id'], $session_id);
1276
                    if ($initialData && isset($initialData['exercise_id'])) {
1277
                        $results = Event::getExerciseResultsByUser(
0 ignored issues
show
Bug introduced by
The method getExerciseResultsByUser() does not exist on Event. ( Ignorable by Annotation )

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

1277
                        /** @scrutinizer ignore-call */ 
1278
                        $results = Event::getExerciseResultsByUser(

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

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

Loading history...
1278
                            api_get_user_id(),
1279
                            $initialData['exercise_id'],
1280
                            $course_info['real_id'],
1281
                            $session_id
1282
                        );
1283
                        if (empty($results)) {
1284
                            api_not_allowed($print_headers);
1285
1286
                            return false;
1287
                        }
1288
                    }
1289
                }
1290
            }
1291
        }
1292
    }
1293
1294
    api_block_inactive_user();
1295
1296
    return true;
1297
}
1298
1299
/**
1300
 * Function used to protect an admin script.
1301
 *
1302
 * The function blocks access when the user has no platform admin rights
1303
 * with an error message printed on default output
1304
 *
1305
 * @param bool Whether to allow session admins as well
1306
 * @param bool Whether to allow HR directors as well
1307
 * @param string An optional message (already passed through get_lang)
1308
 *
1309
 * @return bool True if user is allowed, false otherwise.
1310
 *              The function also outputs an error message in case not allowed
1311
 *
1312
 * @author Roan Embrechts (original author)
1313
 */
1314
function api_protect_admin_script($allow_sessions_admins = false, $allow_drh = false, $message = null)
1315
{
1316
    if (!api_is_platform_admin($allow_sessions_admins, $allow_drh)) {
1317
        api_not_allowed(true, $message);
1318
1319
        return false;
1320
    }
1321
1322
    api_block_inactive_user();
1323
1324
    return true;
1325
}
1326
1327
/**
1328
 * Blocks inactive users with a currently active session from accessing more pages "live".
1329
 *
1330
 * @return bool Returns true if the feature is disabled or the user account is still enabled.
1331
 *              Returns false (and shows a message) if the feature is enabled *and* the user is disabled.
1332
 */
1333
function api_block_inactive_user()
1334
{
1335
    $data = true;
1336
    if (api_get_configuration_value('security_block_inactive_users_immediately') != 1) {
1337
        return $data;
1338
    }
1339
1340
    $userId = api_get_user_id();
1341
    $homeUrl = api_get_path(WEB_PATH);
1342
    if ($userId == 0) {
1343
        return $data;
1344
    }
1345
1346
    $sql = "SELECT active FROM ".Database::get_main_table(TABLE_MAIN_USER)."
1347
            WHERE id = $userId";
1348
1349
    $result = Database::query($sql);
1350
    if (Database::num_rows($result) > 0) {
1351
        $result_array = Database::fetch_array($result);
1352
        $data = (bool) $result_array['active'];
1353
    }
1354
    if ($data == false) {
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like you are loosely comparing two booleans. Considering using the strict comparison === instead.

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

Loading history...
1355
        $tpl = new Template(null, true, true, false, true, false, true, 0);
1356
        $tpl->assign('hide_login_link', 1);
1357
1358
        //api_not_allowed(true, get_lang('AccountInactive'));
1359
        // we were not in a course, return to home page
1360
        $msg = Display::return_message(
1361
            get_lang('AccountInactive'),
1362
            'error',
1363
            false
1364
        );
1365
1366
        $msg .= '<p class="text-center">
1367
                 <a class="btn btn-default" href="'.$homeUrl.'">'.get_lang('BackHome').'</a></p>';
1368
1369
        if (api_is_anonymous()) {
1370
            $form = api_get_not_allowed_login_form();
1371
            $msg .= '<div class="well">';
1372
            $msg .= $form->returnForm();
1373
            $msg .= '</div>';
1374
        }
1375
1376
        $tpl->assign('content', $msg);
1377
        $tpl->display_one_col_template();
1378
        exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

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

Loading history...
1379
    }
1380
1381
    return $data;
1382
}
1383
1384
/**
1385
 * Function used to protect a teacher script.
1386
 * The function blocks access when the user has no teacher rights.
1387
 *
1388
 * @return bool True if the current user can access the script, false otherwise
1389
 *
1390
 * @author Yoselyn Castillo
1391
 */
1392
function api_protect_teacher_script()
1393
{
1394
    if (!api_is_allowed_to_edit()) {
1395
        api_not_allowed(true);
1396
1397
        return false;
1398
    }
1399
1400
    return true;
1401
}
1402
1403
/**
1404
 * Function used to prevent anonymous users from accessing a script.
1405
 *
1406
 * @param bool|true $printHeaders
1407
 *
1408
 * @author Roan Embrechts
1409
 *
1410
 * @return bool
1411
 */
1412
function api_block_anonymous_users($printHeaders = true)
1413
{
1414
    $user = api_get_user_info();
1415
    if (!(isset($user['user_id']) && $user['user_id']) || api_is_anonymous($user['user_id'], true)) {
1416
        api_not_allowed($printHeaders);
1417
1418
        return false;
1419
    }
1420
    api_block_inactive_user();
1421
1422
    return true;
1423
}
1424
1425
/**
1426
 * Returns a rough evaluation of the browser's name and version based on very
1427
 * simple regexp.
1428
 *
1429
 * @return array with the navigator name and version ['name' => '...', 'version' => '...']
1430
 */
1431
function api_get_navigator()
1432
{
1433
    $navigator = 'Unknown';
1434
    $version = 0;
1435
1436
    if (!isset($_SERVER['HTTP_USER_AGENT'])) {
1437
        return ['name' => 'Unknown', 'version' => '0.0.0'];
1438
    }
1439
1440
    if (strpos($_SERVER['HTTP_USER_AGENT'], 'Opera') !== false) {
1441
        $navigator = 'Opera';
1442
        list(, $version) = explode('Opera', $_SERVER['HTTP_USER_AGENT']);
1443
    } elseif (strpos($_SERVER['HTTP_USER_AGENT'], 'Edge') !== false) {
1444
        $navigator = 'Edge';
1445
        list(, $version) = explode('Edge', $_SERVER['HTTP_USER_AGENT']);
1446
    } elseif (strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE') !== false) {
1447
        $navigator = 'Internet Explorer';
1448
        list(, $version) = explode('MSIE ', $_SERVER['HTTP_USER_AGENT']);
1449
    } elseif (strpos($_SERVER['HTTP_USER_AGENT'], 'Chrome') !== false) {
1450
        $navigator = 'Chrome';
1451
        list(, $version) = explode('Chrome', $_SERVER['HTTP_USER_AGENT']);
1452
    } elseif (stripos($_SERVER['HTTP_USER_AGENT'], 'Safari') !== false) {
1453
        $navigator = 'Safari';
1454
        if (stripos($_SERVER['HTTP_USER_AGENT'], 'Version/') !== false) {
1455
            // If this Safari does have the "Version/" string in its user agent
1456
            // then use that as a version indicator rather than what's after
1457
            // "Safari/" which is rather a "build number" or something
1458
            list(, $version) = explode('Version/', $_SERVER['HTTP_USER_AGENT']);
1459
        } else {
1460
            list(, $version) = explode('Safari/', $_SERVER['HTTP_USER_AGENT']);
1461
        }
1462
    } elseif (strpos($_SERVER['HTTP_USER_AGENT'], 'Firefox') !== false) {
1463
        $navigator = 'Firefox';
1464
        list(, $version) = explode('Firefox', $_SERVER['HTTP_USER_AGENT']);
1465
    } elseif (strpos($_SERVER['HTTP_USER_AGENT'], 'Netscape') !== false) {
1466
        $navigator = 'Netscape';
1467
        if (stripos($_SERVER['HTTP_USER_AGENT'], 'Netscape/') !== false) {
1468
            list(, $version) = explode('Netscape', $_SERVER['HTTP_USER_AGENT']);
1469
        } else {
1470
            list(, $version) = explode('Navigator', $_SERVER['HTTP_USER_AGENT']);
1471
        }
1472
    } elseif (strpos($_SERVER['HTTP_USER_AGENT'], 'Konqueror') !== false) {
1473
        $navigator = 'Konqueror';
1474
        list(, $version) = explode('Konqueror', $_SERVER['HTTP_USER_AGENT']);
1475
    } elseif (stripos($_SERVER['HTTP_USER_AGENT'], 'applewebkit') !== false) {
1476
        $navigator = 'AppleWebKit';
1477
        list(, $version) = explode('Version/', $_SERVER['HTTP_USER_AGENT']);
1478
    } elseif (strpos($_SERVER['HTTP_USER_AGENT'], 'Gecko') !== false) {
1479
        $navigator = 'Mozilla';
1480
        list(, $version) = explode('; rv:', $_SERVER['HTTP_USER_AGENT']);
1481
    }
1482
1483
    // Now cut extra stuff around (mostly *after*) the version number
1484
    $version = preg_replace('/^([\/\s])?([\d\.]+)?.*/', '\2', $version);
1485
1486
    if (strpos($version, '.') === false) {
1487
        $version = number_format(doubleval($version), 1);
1488
    }
1489
1490
    return ['name' => $navigator, 'version' => $version];
1491
}
1492
1493
/**
1494
 * @return true if user self registration is allowed, false otherwise
1495
 */
1496
function api_is_self_registration_allowed()
1497
{
1498
    return isset($GLOBALS['allowSelfReg']) ? $GLOBALS['allowSelfReg'] : false;
0 ignored issues
show
Bug Best Practice introduced by
The expression return IssetNode ? $GLOB...'allowSelfReg'] : false could also return false which is incompatible with the documented return type true. Did you maybe forget to handle an error condition?

If the returned type also contains false, it is an indicator that maybe an error condition leading to the specific return statement remains unhandled.

Loading history...
1499
}
1500
1501
/**
1502
 * This function returns the id of the user which is stored in the $_user array.
1503
 *
1504
 * example: The function can be used to check if a user is logged in
1505
 *          if (api_get_user_id())
1506
 *
1507
 * @return int the id of the current user, 0 if is empty
1508
 */
1509
function api_get_user_id()
1510
{
1511
    $userInfo = Session::read('_user');
1512
    if ($userInfo && isset($userInfo['user_id'])) {
1513
        return (int) $userInfo['user_id'];
1514
    }
1515
1516
    return 0;
1517
}
1518
1519
/**
1520
 * Gets the list of courses a specific user is subscribed to.
1521
 *
1522
 * @param int       User ID
1523
 * @param bool $fetch_session Whether to get session courses or not - NOT YET IMPLEMENTED
1524
 *
1525
 * @return array Array of courses in the form [0]=>('code'=>xxx,'db'=>xxx,'dir'=>xxx,'status'=>d)
1526
 *
1527
 * @deprecated use CourseManager::get_courses_list_by_user_id()
1528
 */
1529
function api_get_user_courses($userId, $fetch_session = true)
1530
{
1531
    // Get out if not integer
1532
    if ($userId != strval(intval($userId))) {
1533
        return [];
1534
    }
1535
1536
    $t_course = Database::get_main_table(TABLE_MAIN_COURSE);
1537
    $t_course_user = Database::get_main_table(TABLE_MAIN_COURSE_USER);
1538
1539
    $sql = "SELECT cc.id as real_id, cc.code code, cc.directory dir, cu.status status
1540
            FROM $t_course cc, $t_course_user cu
1541
            WHERE
1542
                cc.id = cu.c_id AND
1543
                cu.user_id = $userId AND
1544
                cu.relation_type <> ".COURSE_RELATION_TYPE_RRHH;
1545
    $result = Database::query($sql);
1546
    if ($result === false) {
1547
        return [];
1548
    }
1549
1550
    $courses = [];
1551
    while ($row = Database::fetch_array($result)) {
1552
        // we only need the database name of the course
1553
        $courses[] = $row;
1554
    }
1555
1556
    return $courses;
1557
}
1558
1559
/**
1560
 * Formats user information into a standard array
1561
 * This function should be only used inside api_get_user_info().
1562
 *
1563
 * @param array Non-standard user array
0 ignored issues
show
Documentation Bug introduced by
The doc comment Non-standard at position 0 could not be parsed: Unknown type name 'Non-standard' at position 0 in Non-standard.
Loading history...
1564
 * @param bool $add_password
1565
 * @param bool $loadAvatars  turn off to improve performance
1566
 *
1567
 * @return array Standard user array
1568
 */
1569
function _api_format_user($user, $add_password = false, $loadAvatars = true)
1570
{
1571
    $result = [];
1572
1573
    $result['firstname'] = null;
1574
    $result['lastname'] = null;
1575
1576
    if (isset($user['firstname']) && isset($user['lastname'])) { // with only lowercase
1577
        $result['firstname'] = $user['firstname'];
1578
        $result['lastname'] = $user['lastname'];
1579
    } elseif (isset($user['firstName']) && isset($user['lastName'])) { // with uppercase letters
1580
        $result['firstname'] = isset($user['firstName']) ? $user['firstName'] : null;
1581
        $result['lastname'] = isset($user['lastName']) ? $user['lastName'] : null;
1582
    }
1583
1584
    if (isset($user['email'])) {
1585
        $result['mail'] = isset($user['email']) ? $user['email'] : null;
1586
        $result['email'] = isset($user['email']) ? $user['email'] : null;
1587
    } else {
1588
        $result['mail'] = isset($user['mail']) ? $user['mail'] : null;
1589
        $result['email'] = isset($user['mail']) ? $user['mail'] : null;
1590
    }
1591
1592
    $result['complete_name'] = api_get_person_name($result['firstname'], $result['lastname']);
1593
    $result['complete_name_with_username'] = $result['complete_name'];
1594
1595
    if (!empty($user['username']) && !api_get_configuration_value('hide_username_with_complete_name')) {
1596
        $result['complete_name_with_username'] = $result['complete_name'].' ('.$user['username'].')';
1597
    }
1598
1599
    $showEmail = api_get_setting('show_email_addresses') === 'true';
1600
    if (!empty($user['email'])) {
1601
        $result['complete_name_with_email_forced'] = $result['complete_name'].' ('.$user['email'].')';
1602
        if ($showEmail) {
1603
            $result['complete_name_with_email'] = $result['complete_name'].' ('.$user['email'].')';
1604
        }
1605
    } else {
1606
        $result['complete_name_with_email'] = $result['complete_name'];
1607
        $result['complete_name_with_email_forced'] = $result['complete_name'];
1608
    }
1609
1610
    // Kept for historical reasons
1611
    $result['firstName'] = $result['firstname'];
1612
    $result['lastName'] = $result['lastname'];
1613
1614
    $attributes = [
1615
        'phone',
1616
        'address',
1617
        'picture_uri',
1618
        'official_code',
1619
        'status',
1620
        'active',
1621
        'auth_source',
1622
        'username',
1623
        'theme',
1624
        'language',
1625
        'creator_id',
1626
        'registration_date',
1627
        'hr_dept_id',
1628
        'expiration_date',
1629
        'last_login',
1630
        'user_is_online',
1631
    ];
1632
1633
    if (api_get_setting('extended_profile') === 'true') {
1634
        $attributes[] = 'competences';
1635
        $attributes[] = 'diplomas';
1636
        $attributes[] = 'teach';
1637
        $attributes[] = 'openarea';
1638
    }
1639
1640
    foreach ($attributes as $attribute) {
1641
        $result[$attribute] = isset($user[$attribute]) ? $user[$attribute] : null;
1642
    }
1643
1644
    $user_id = (int) $user['user_id'];
1645
    // Maintain the user_id index for backwards compatibility
1646
    $result['user_id'] = $result['id'] = $user_id;
1647
1648
    $hasCertificates = Certificate::getCertificateByUser($user_id);
1649
    $result['has_certificates'] = 0;
1650
    if (!empty($hasCertificates)) {
1651
        $result['has_certificates'] = 1;
1652
    }
1653
1654
    $result['icon_status'] = '';
1655
    $result['icon_status_medium'] = '';
1656
1657
    $result['is_admin'] = UserManager::is_admin($user_id);
1658
1659
    // Getting user avatar.
1660
    if ($loadAvatars) {
1661
        $result['avatar'] = '';
1662
        $result['avatar_no_query'] = '';
1663
        $result['avatar_small'] = '';
1664
        $result['avatar_medium'] = '';
1665
1666
        if (!isset($user['avatar'])) {
1667
            $originalFile = UserManager::getUserPicture(
1668
                $user_id,
1669
                USER_IMAGE_SIZE_ORIGINAL,
1670
                null,
1671
                $result
1672
            );
1673
            $result['avatar'] = $originalFile;
1674
            $avatarString = explode('?', $result['avatar']);
1675
            $result['avatar_no_query'] = reset($avatarString);
1676
        } else {
1677
            $result['avatar'] = $user['avatar'];
1678
            $avatarString = explode('?', $user['avatar']);
1679
            $result['avatar_no_query'] = reset($avatarString);
1680
        }
1681
1682
        if (!isset($user['avatar_small'])) {
1683
            $smallFile = UserManager::getUserPicture(
1684
                $user_id,
1685
                USER_IMAGE_SIZE_SMALL,
1686
                null,
1687
                $result
1688
            );
1689
            $result['avatar_small'] = $smallFile;
1690
        } else {
1691
            $result['avatar_small'] = $user['avatar_small'];
1692
        }
1693
1694
        if (!isset($user['avatar_medium'])) {
1695
            $mediumFile = UserManager::getUserPicture(
1696
                $user_id,
1697
                USER_IMAGE_SIZE_MEDIUM,
1698
                null,
1699
                $result
1700
            );
1701
            $result['avatar_medium'] = $mediumFile;
1702
        } else {
1703
            $result['avatar_medium'] = $user['avatar_medium'];
1704
        }
1705
1706
        $urlImg = api_get_path(WEB_IMG_PATH);
1707
        $iconStatus = '';
1708
        $iconStatusMedium = '';
1709
        $label = '';
1710
        switch ($result['status']) {
1711
            case STUDENT:
1712
                if ($result['has_certificates']) {
1713
                    $iconStatus = $urlImg.'icons/svg/identifier_graduated.svg';
1714
                    $label = get_lang('Graduated');
1715
                } else {
1716
                    $iconStatus = $urlImg.'icons/svg/identifier_student.svg';
1717
                    $label = get_lang('Student');
1718
                }
1719
                break;
1720
            case COURSEMANAGER:
1721
                if ($result['is_admin']) {
1722
                    $iconStatus = $urlImg.'icons/svg/identifier_admin.svg';
1723
                    $label = get_lang('Admin');
1724
                } else {
1725
                    $iconStatus = $urlImg.'icons/svg/identifier_teacher.svg';
1726
                    $label = get_lang('Teacher');
1727
                }
1728
                break;
1729
            case STUDENT_BOSS:
1730
                $iconStatus = $urlImg.'icons/svg/identifier_teacher.svg';
1731
                $label = get_lang('StudentBoss');
1732
                break;
1733
        }
1734
1735
        if (!empty($iconStatus)) {
1736
            $iconStatusMedium = '<img src="'.$iconStatus.'" width="32px" height="32px">';
1737
            $iconStatus = '<img src="'.$iconStatus.'" width="22px" height="22px">';
1738
        }
1739
1740
        $result['icon_status'] = $iconStatus;
1741
        $result['icon_status_label'] = $label;
1742
        $result['icon_status_medium'] = $iconStatusMedium;
1743
    }
1744
1745
    if (isset($user['user_is_online'])) {
1746
        $result['user_is_online'] = $user['user_is_online'] == true ? 1 : 0;
1747
    }
1748
    if (isset($user['user_is_online_in_chat'])) {
1749
        $result['user_is_online_in_chat'] = (int) $user['user_is_online_in_chat'];
1750
    }
1751
1752
    if ($add_password) {
1753
        $result['password'] = $user['password'];
1754
    }
1755
1756
    if (isset($result['profile_completed'])) {
1757
        $result['profile_completed'] = $user['profile_completed'];
1758
    }
1759
1760
    $result['profile_url'] = api_get_path(WEB_CODE_PATH).'social/profile.php?u='.$user_id;
1761
1762
    // Send message link
1763
    $sendMessage = api_get_path(WEB_AJAX_PATH).'user_manager.ajax.php?a=get_user_popup&user_id='.$user_id;
1764
    $result['complete_name_with_message_link'] = Display::url(
1765
        $result['complete_name_with_username'],
1766
        $sendMessage,
1767
        ['class' => 'ajax']
1768
    );
1769
1770
    if (isset($user['extra'])) {
1771
        $result['extra'] = $user['extra'];
1772
    }
1773
1774
    return $result;
1775
}
1776
1777
/**
1778
 * Finds all the information about a user.
1779
 * If no parameter is passed you find all the information about the current user.
1780
 *
1781
 * @param int  $user_id
1782
 * @param bool $checkIfUserOnline
1783
 * @param bool $showPassword
1784
 * @param bool $loadExtraData
1785
 * @param bool $loadOnlyVisibleExtraData Get the user extra fields that are visible
1786
 * @param bool $loadAvatars              turn off to improve performance and if avatars are not needed
1787
 * @param bool $updateCache              update apc cache if exists
1788
 *
1789
 * @return mixed $user_info user_id, lastname, firstname, username, email, etc or false on error
1790
 *
1791
 * @author Patrick Cool <[email protected]>
1792
 * @author Julio Montoya
1793
 *
1794
 * @version 21 September 2004
1795
 */
1796
function api_get_user_info(
1797
    $user_id = 0,
1798
    $checkIfUserOnline = false,
1799
    $showPassword = false,
1800
    $loadExtraData = false,
1801
    $loadOnlyVisibleExtraData = false,
1802
    $loadAvatars = true,
1803
    $updateCache = false
1804
) {
1805
    $apcVar = null;
1806
    $user = false;
1807
    $cacheAvailable = api_get_configuration_value('apc');
1808
1809
    if (empty($user_id)) {
1810
        $userFromSession = Session::read('_user');
1811
1812
        if (isset($userFromSession)) {
1813
            if ($cacheAvailable === true &&
1814
                (
1815
                    empty($userFromSession['is_anonymous']) &&
1816
                    (isset($userFromSession['status']) && $userFromSession['status'] != ANONYMOUS)
1817
                )
1818
            ) {
1819
                $apcVar = api_get_configuration_value('apc_prefix').'userinfo_'.$userFromSession['user_id'];
1820
                if (apcu_exists($apcVar)) {
1821
                    if ($updateCache) {
1822
                        apcu_store($apcVar, $userFromSession, 60);
1823
                    }
1824
                    $user = apcu_fetch($apcVar);
1825
                } else {
1826
                    $user = _api_format_user(
1827
                        $userFromSession,
1828
                        $showPassword,
1829
                        $loadAvatars
1830
                    );
1831
                    apcu_store($apcVar, $user, 60);
1832
                }
1833
            } else {
1834
                $user = _api_format_user(
1835
                    $userFromSession,
1836
                    $showPassword,
1837
                    $loadAvatars
1838
                );
1839
            }
1840
1841
            return $user;
1842
        }
1843
1844
        return false;
1845
    }
1846
1847
    // Make sure user_id is safe
1848
    $user_id = (int) $user_id;
1849
1850
    // Re-use user information if not stale and already stored in APCu
1851
    if ($cacheAvailable === true) {
1852
        $apcVar = api_get_configuration_value('apc_prefix').'userinfo_'.$user_id;
1853
        if (apcu_exists($apcVar) && $updateCache == false && $checkIfUserOnline == false) {
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like you are loosely comparing two booleans. Considering using the strict comparison === instead.

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

Loading history...
1854
            $user = apcu_fetch($apcVar);
1855
1856
            return $user;
1857
        }
1858
    }
1859
1860
    $sql = "SELECT * FROM ".Database::get_main_table(TABLE_MAIN_USER)."
1861
            WHERE id = $user_id";
1862
    $result = Database::query($sql);
1863
    if (Database::num_rows($result) > 0) {
1864
        $result_array = Database::fetch_array($result);
1865
        $result_array['user_is_online_in_chat'] = 0;
1866
        if ($checkIfUserOnline) {
1867
            $use_status_in_platform = user_is_online($user_id);
1868
            $result_array['user_is_online'] = $use_status_in_platform;
1869
            $user_online_in_chat = 0;
1870
            if ($use_status_in_platform) {
1871
                $user_status = UserManager::get_extra_user_data_by_field(
1872
                    $user_id,
1873
                    'user_chat_status',
1874
                    false,
1875
                    true
1876
                );
1877
                if ((int) $user_status['user_chat_status'] == 1) {
1878
                    $user_online_in_chat = 1;
1879
                }
1880
            }
1881
            $result_array['user_is_online_in_chat'] = $user_online_in_chat;
1882
        }
1883
1884
        if ($loadExtraData) {
1885
            $fieldValue = new ExtraFieldValue('user');
1886
            $result_array['extra'] = $fieldValue->getAllValuesForAnItem(
1887
                $user_id,
1888
                $loadOnlyVisibleExtraData
1889
            );
1890
        }
1891
        $user = _api_format_user($result_array, $showPassword, $loadAvatars);
1892
    }
1893
1894
    if ($cacheAvailable === true) {
1895
        apcu_store($apcVar, $user, 60);
1896
    }
1897
1898
    return $user;
1899
}
1900
1901
/**
1902
 * @param int $userId
1903
 *
1904
 * @return User
1905
 */
1906
function api_get_user_entity($userId)
1907
{
1908
    $userId = (int) $userId;
1909
    $repo = UserManager::getRepository();
1910
1911
    /** @var User $user */
1912
    $user = $repo->find($userId);
1913
1914
    return $user;
1915
}
1916
1917
/**
1918
 * Finds all the information about a user from username instead of user id.
1919
 *
1920
 * @param string $username
1921
 *
1922
 * @return mixed $user_info array user_id, lastname, firstname, username, email or false on error
1923
 *
1924
 * @author Yannick Warnier <[email protected]>
1925
 */
1926
function api_get_user_info_from_username($username)
1927
{
1928
    if (empty($username)) {
1929
        return false;
1930
    }
1931
    $username = trim($username);
1932
1933
    $sql = "SELECT * FROM ".Database::get_main_table(TABLE_MAIN_USER)."
1934
            WHERE username='".Database::escape_string($username)."'";
1935
    $result = Database::query($sql);
1936
    if (Database::num_rows($result) > 0) {
1937
        $resultArray = Database::fetch_array($result);
1938
1939
        return _api_format_user($resultArray);
1940
    }
1941
1942
    return false;
1943
}
1944
1945
/**
1946
 * Get first user with an email.
1947
 *
1948
 * @param string $email
1949
 *
1950
 * @return array|bool
1951
 */
1952
function api_get_user_info_from_email($email = '')
1953
{
1954
    if (empty($email)) {
1955
        return false;
1956
    }
1957
    $sql = "SELECT * FROM ".Database::get_main_table(TABLE_MAIN_USER)."
1958
            WHERE email ='".Database::escape_string($email)."' LIMIT 1";
1959
    $result = Database::query($sql);
1960
    if (Database::num_rows($result) > 0) {
1961
        $resultArray = Database::fetch_array($result);
1962
1963
        return _api_format_user($resultArray);
1964
    }
1965
1966
    return false;
1967
}
1968
1969
/**
1970
 * @return string
1971
 */
1972
function api_get_course_id()
1973
{
1974
    return Session::read('_cid', null);
1975
}
1976
1977
/**
1978
 * Returns the current course id (integer).
1979
 *
1980
 * @param string $code Optional course code
1981
 *
1982
 * @return int
1983
 */
1984
function api_get_course_int_id($code = null)
1985
{
1986
    if (!empty($code)) {
1987
        $code = Database::escape_string($code);
1988
        $row = Database::select(
1989
            'id',
1990
            Database::get_main_table(TABLE_MAIN_COURSE),
1991
            ['where' => ['code = ?' => [$code]]],
1992
            'first'
1993
        );
1994
1995
        if (is_array($row) && isset($row['id'])) {
1996
            return $row['id'];
1997
        } else {
1998
            return false;
1999
        }
2000
    }
2001
2002
    return Session::read('_real_cid', 0);
2003
}
2004
2005
/**
2006
 * Returns the current course directory.
2007
 *
2008
 * This function relies on api_get_course_info()
2009
 *
2010
 * @param string    The course code - optional (takes it from session if not given)
2011
 *
2012
 * @return string The directory where the course is located inside the Chamilo "courses" directory
2013
 *
2014
 * @author Yannick Warnier <[email protected]>
2015
 */
2016
function api_get_course_path($course_code = null)
2017
{
2018
    $info = !empty($course_code) ? api_get_course_info($course_code) : api_get_course_info();
2019
2020
    return $info['path'];
2021
}
2022
2023
/**
2024
 * Gets a course setting from the current course_setting table. Try always using integer values.
2025
 *
2026
 * @param string $settingName The name of the setting we want from the table
2027
 * @param array  $courseInfo
2028
 * @param bool   $force       force checking the value in the database
2029
 *
2030
 * @return mixed The value of that setting in that table. Return -1 if not found.
2031
 */
2032
function api_get_course_setting($settingName, $courseInfo = [], $force = false)
2033
{
2034
    if (empty($courseInfo)) {
2035
        $courseInfo = api_get_course_info();
2036
    }
2037
2038
    if (empty($courseInfo) || empty($settingName)) {
2039
        return -1;
2040
    }
2041
2042
    $courseId = isset($courseInfo['real_id']) && !empty($courseInfo['real_id']) ? $courseInfo['real_id'] : 0;
2043
2044
    if (empty($courseId)) {
2045
        return -1;
2046
    }
2047
2048
    static $courseSettingInfo = [];
2049
2050
    if ($force) {
2051
        $courseSettingInfo = [];
2052
    }
2053
2054
    if (!isset($courseSettingInfo[$courseId])) {
2055
        $table = Database::get_course_table(TABLE_COURSE_SETTING);
2056
        $settingName = Database::escape_string($settingName);
2057
2058
        $sql = "SELECT variable, value FROM $table
2059
                WHERE c_id = $courseId ";
2060
        $res = Database::query($sql);
2061
        if (Database::num_rows($res) > 0) {
2062
            $result = Database::store_result($res, 'ASSOC');
2063
            $courseSettingInfo[$courseId] = array_column($result, 'value', 'variable');
2064
2065
            if (isset($courseSettingInfo[$courseId]['email_alert_manager_on_new_quiz'])) {
2066
                $value = $courseSettingInfo[$courseId]['email_alert_manager_on_new_quiz'];
2067
                if (!is_null($value)) {
2068
                    $result = explode(',', $value);
2069
                    $courseSettingInfo[$courseId]['email_alert_manager_on_new_quiz'] = $result;
2070
                }
2071
            }
2072
        }
2073
    }
2074
2075
    if (isset($courseSettingInfo[$courseId]) && array_key_exists($settingName, $courseSettingInfo[$courseId])) {
2076
        return $courseSettingInfo[$courseId][$settingName];
2077
    }
2078
2079
    return -1;
2080
}
2081
2082
function api_get_course_plugin_setting($plugin, $settingName, $courseInfo = [])
2083
{
2084
    $value = api_get_course_setting($settingName, $courseInfo, true);
2085
2086
    if (-1 === $value) {
2087
        // Check global settings
2088
        $value = api_get_plugin_setting($plugin, $settingName);
2089
        if ($value === 'true') {
2090
            return 1;
2091
        }
2092
        if ($value === 'false') {
2093
            return 0;
2094
        }
2095
        if (null === $value) {
2096
            return -1;
2097
        }
2098
    }
2099
2100
    return $value;
2101
}
2102
2103
/**
2104
 * Gets an anonymous user ID.
2105
 *
2106
 * For some tools that need tracking, like the learnpath tool, it is necessary
2107
 * to have a usable user-id to enable some kind of tracking, even if not
2108
 * perfect. An anonymous ID is taken from the users table by looking for a
2109
 * status of "6" (anonymous).
2110
 *
2111
 * @return int User ID of the anonymous user, or O if no anonymous user found
2112
 */
2113
function api_get_anonymous_id()
2114
{
2115
    // Find if another anon is connected now
2116
    $table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_LOGIN);
2117
    $tableU = Database::get_main_table(TABLE_MAIN_USER);
2118
    $ip = Database::escape_string(api_get_real_ip());
2119
    $max = (int) api_get_configuration_value('max_anonymous_users');
2120
    if ($max >= 2) {
2121
        $sql = "SELECT * FROM $table as TEL
2122
                JOIN $tableU as U
2123
                ON U.user_id = TEL.login_user_id
2124
                WHERE TEL.user_ip = '$ip'
2125
                    AND U.status = ".ANONYMOUS."
2126
                    AND U.user_id != 2 ";
2127
2128
        $result = Database::query($sql);
2129
        if (empty(Database::num_rows($result))) {
2130
            $login = uniqid('anon_');
2131
            $anonList = UserManager::get_user_list(['status' => ANONYMOUS], ['registration_date ASC']);
2132
            if (count($anonList) >= $max) {
2133
                foreach ($anonList as $userToDelete) {
2134
                    UserManager::delete_user($userToDelete['user_id']);
2135
                    break;
2136
                }
2137
            }
2138
            // Return the user ID
2139
            return UserManager::create_user(
0 ignored issues
show
Bug Best Practice introduced by
The expression return UserManager::crea...lhost', $login, $login) could also return false which is incompatible with the documented return type integer. Did you maybe forget to handle an error condition?

If the returned type also contains false, it is an indicator that maybe an error condition leading to the specific return statement remains unhandled.

Loading history...
2140
                $login,
2141
                'anon',
2142
                ANONYMOUS,
2143
                ' anonymous@localhost',
2144
                $login,
2145
                $login
2146
            );
2147
        } else {
2148
            $row = Database::fetch_array($result, 'ASSOC');
2149
2150
            return $row['user_id'];
2151
        }
2152
    }
2153
2154
    $table = Database::get_main_table(TABLE_MAIN_USER);
2155
    $sql = "SELECT user_id
2156
            FROM $table
2157
            WHERE status = ".ANONYMOUS." ";
2158
    $res = Database::query($sql);
2159
    if (Database::num_rows($res) > 0) {
2160
        $row = Database::fetch_array($res, 'ASSOC');
2161
2162
        return $row['user_id'];
2163
    }
2164
2165
    // No anonymous user was found.
2166
    return 0;
2167
}
2168
2169
/**
2170
 * @param string $courseCode
2171
 * @param int    $sessionId
2172
 * @param int    $groupId
2173
 *
2174
 * @return string
2175
 */
2176
function api_get_cidreq_params($courseCode, $sessionId = 0, $groupId = 0)
2177
{
2178
    $courseCode = !empty($courseCode) ? htmlspecialchars($courseCode) : '';
2179
    $sessionId = !empty($sessionId) ? (int) $sessionId : 0;
2180
    $groupId = !empty($groupId) ? (int) $groupId : 0;
2181
2182
    $url = 'cidReq='.$courseCode;
2183
    $url .= '&id_session='.$sessionId;
2184
    $url .= '&gidReq='.$groupId;
2185
2186
    return $url;
2187
}
2188
2189
/**
2190
 * Returns the current course url part including session, group, and gradebook params.
2191
 *
2192
 * @param bool   $addSessionId
2193
 * @param bool   $addGroupId
2194
 * @param string $origin
2195
 *
2196
 * @return string Course & session references to add to a URL
2197
 */
2198
function api_get_cidreq($addSessionId = true, $addGroupId = true, $origin = '')
2199
{
2200
    $courseCode = api_get_course_id();
2201
    $url = empty($courseCode) ? '' : 'cidReq='.urlencode(htmlspecialchars($courseCode));
2202
    $origin = empty($origin) ? api_get_origin() : urlencode(Security::remove_XSS($origin));
2203
2204
    if ($addSessionId) {
2205
        if (!empty($url)) {
2206
            $url .= api_get_session_id() == 0 ? '&id_session=0' : '&id_session='.api_get_session_id();
2207
        }
2208
    }
2209
2210
    if ($addGroupId) {
2211
        if (!empty($url)) {
2212
            $url .= api_get_group_id() == 0 ? '&gidReq=0' : '&gidReq='.api_get_group_id();
2213
        }
2214
    }
2215
2216
    if (!empty($url)) {
2217
        $url .= '&gradebook='.intval(api_is_in_gradebook());
2218
        $url .= '&origin='.$origin;
2219
    }
2220
2221
    return $url;
2222
}
2223
2224
/**
2225
 * Get if we visited a gradebook page.
2226
 *
2227
 * @return bool
2228
 */
2229
function api_is_in_gradebook()
2230
{
2231
    return Session::read('in_gradebook', false);
2232
}
2233
2234
/**
2235
 * Set that we are in a page inside a gradebook.
2236
 */
2237
function api_set_in_gradebook()
2238
{
2239
    Session::write('in_gradebook', true);
2240
}
2241
2242
/**
2243
 * Remove gradebook session.
2244
 */
2245
function api_remove_in_gradebook()
2246
{
2247
    Session::erase('in_gradebook');
2248
}
2249
2250
/**
2251
 * Returns the current course info array see api_format_course_array()
2252
 * If the course_code is given, the returned array gives info about that
2253
 * particular course, if none given it gets the course info from the session.
2254
 *
2255
 * @param string $course_code
2256
 *
2257
 * @return array
2258
 */
2259
function api_get_course_info($course_code = null)
2260
{
2261
    if (!empty($course_code)) {
2262
        $course_code = Database::escape_string($course_code);
2263
        $courseId = api_get_course_int_id($course_code);
2264
2265
        if (empty($courseId)) {
2266
            return [];
2267
        }
2268
2269
        $course_table = Database::get_main_table(TABLE_MAIN_COURSE);
2270
        $course_cat_table = Database::get_main_table(TABLE_MAIN_CATEGORY);
2271
        $sql = "SELECT
2272
                    course.*,
2273
                    course_category.code faCode,
2274
                    course_category.name faName
2275
                FROM $course_table
2276
                LEFT JOIN $course_cat_table
2277
                ON course.category_code = course_category.code
2278
                WHERE course.id = $courseId";
2279
        $result = Database::query($sql);
2280
        $courseInfo = [];
2281
        if (Database::num_rows($result) > 0) {
2282
            $data = Database::fetch_array($result);
2283
            $courseInfo = api_format_course_array($data);
2284
        }
2285
2286
        return $courseInfo;
2287
    }
2288
2289
    global $_course;
2290
    if ($_course == '-1') {
2291
        $_course = [];
2292
    }
2293
2294
    return $_course;
2295
}
2296
2297
/**
2298
 * @param int $courseId
2299
 *
2300
 * @return \Chamilo\CoreBundle\Entity\Course
2301
 */
2302
function api_get_course_entity($courseId = 0)
2303
{
2304
    if (empty($courseId)) {
2305
        $courseId = api_get_course_int_id();
2306
    }
2307
2308
    return Database::getManager()->getRepository('ChamiloCoreBundle:Course')->find($courseId);
2309
}
2310
2311
function api_get_group_entity($id = 0)
2312
{
2313
    if (empty($id)) {
2314
        $id = api_get_group_id();
2315
    }
2316
2317
    return Database::getManager()->getRepository('ChamiloCourseBundle:CGroupInfo')->find($id);
2318
}
2319
2320
/**
2321
 * @param int $id
2322
 *
2323
 * @return \Chamilo\CoreBundle\Entity\Session
2324
 */
2325
function api_get_session_entity($id = 0)
2326
{
2327
    if (empty($id)) {
2328
        $id = api_get_session_id();
2329
    }
2330
2331
    return Database::getManager()->getRepository('ChamiloCoreBundle:Session')->find($id);
2332
}
2333
2334
/**
2335
 * Returns the current course info array.
2336
2337
 * Now if the course_code is given, the returned array gives info about that
2338
 * particular course, not specially the current one.
2339
 *
2340
 * @param int $id Numeric ID of the course
2341
 *
2342
 * @return array The course info as an array formatted by api_format_course_array, including category.name
2343
 */
2344
function api_get_course_info_by_id($id = null)
2345
{
2346
    if (!empty($id)) {
2347
        $id = (int) $id;
2348
        $course_table = Database::get_main_table(TABLE_MAIN_COURSE);
2349
        $course_cat_table = Database::get_main_table(TABLE_MAIN_CATEGORY);
2350
        $sql = "SELECT
2351
                    course.*,
2352
                    course_category.code faCode,
2353
                    course_category.name faName
2354
                FROM $course_table
2355
                LEFT JOIN $course_cat_table
2356
                ON course.category_code = course_category.code
2357
                WHERE course.id = $id";
2358
        $result = Database::query($sql);
2359
        $_course = [];
2360
        if (Database::num_rows($result) > 0) {
2361
            $row = Database::fetch_array($result);
2362
            $_course = api_format_course_array($row);
2363
        }
2364
2365
        return $_course;
2366
    }
2367
2368
    global $_course;
2369
    if ($_course == '-1') {
2370
        $_course = [];
2371
    }
2372
2373
    return $_course;
2374
}
2375
2376
/**
2377
 * Reformat the course array (output by api_get_course_info()) in order, mostly,
2378
 * to switch from 'code' to 'id' in the array. This is a legacy feature and is
2379
 * now possibly causing massive confusion as a new "id" field has been added to
2380
 * the course table in 1.9.0.
2381
 *
2382
 * @param $course_data
2383
 *
2384
 * @return array
2385
 *
2386
 * @todo eradicate the false "id"=code field of the $_course array and use the int id
2387
 */
2388
function api_format_course_array($course_data)
2389
{
2390
    if (empty($course_data)) {
2391
        return [];
2392
    }
2393
2394
    $_course = [];
2395
    $_course['id'] = $course_data['code'];
2396
    $_course['real_id'] = $course_data['id'];
2397
2398
    // Added
2399
    $_course['code'] = $course_data['code'];
2400
    $_course['name'] = $course_data['title'];
2401
    $_course['title'] = $course_data['title'];
2402
    $_course['official_code'] = $course_data['visual_code'];
2403
    $_course['visual_code'] = $course_data['visual_code'];
2404
    $_course['sysCode'] = $course_data['code'];
2405
    $_course['path'] = $course_data['directory']; // Use as key in path.
2406
    $_course['directory'] = $course_data['directory'];
2407
    $_course['creation_date'] = $course_data['creation_date'];
2408
    $_course['titular'] = $course_data['tutor_name'];
2409
    $_course['tutor_name'] = $course_data['tutor_name'];
2410
    $_course['language'] = $course_data['course_language'];
2411
    $_course['extLink']['url'] = $course_data['department_url'];
2412
    $_course['extLink']['name'] = $course_data['department_name'];
2413
    $_course['categoryCode'] = $course_data['faCode'];
2414
    $_course['category_code'] = $course_data['faCode'];
2415
    $_course['categoryName'] = $course_data['faName'];
2416
    $_course['visibility'] = $course_data['visibility'];
2417
    $_course['subscribe_allowed'] = $course_data['subscribe'];
2418
    $_course['subscribe'] = $course_data['subscribe'];
2419
    $_course['unsubscribe'] = $course_data['unsubscribe'];
2420
    $_course['course_language'] = $course_data['course_language'];
2421
    $_course['activate_legal'] = isset($course_data['activate_legal']) ? $course_data['activate_legal'] : false;
2422
    $_course['legal'] = $course_data['legal'];
2423
    $_course['show_score'] = $course_data['show_score']; //used in the work tool
2424
    $_course['department_name'] = $course_data['department_name'];
2425
    $_course['department_url'] = $course_data['department_url'];
2426
2427
    $courseSys = api_get_path(SYS_COURSE_PATH).$course_data['directory'];
2428
    $webCourseHome = api_get_path(WEB_COURSE_PATH).$course_data['directory'];
2429
2430
    // Course password
2431
    $_course['registration_code'] = !empty($course_data['registration_code']) ? sha1($course_data['registration_code']) : null;
2432
    $_course['disk_quota'] = $course_data['disk_quota'];
2433
    $_course['course_public_url'] = $webCourseHome.'/index.php';
2434
    $_course['course_sys_path'] = $courseSys.'/';
2435
2436
    if (array_key_exists('add_teachers_to_sessions_courses', $course_data)) {
2437
        $_course['add_teachers_to_sessions_courses'] = $course_data['add_teachers_to_sessions_courses'];
2438
    }
2439
2440
    // Course image
2441
    $_course['course_image_source'] = '';
2442
    if (file_exists($courseSys.'/course-pic85x85.png')) {
2443
        $url_image = $webCourseHome.'/course-pic85x85.png';
2444
        $_course['course_image_source'] = $courseSys.'/course-pic85x85.png';
2445
    } else {
2446
        $url_image = Display::return_icon(
2447
            'course.png',
2448
            null,
2449
            null,
2450
            ICON_SIZE_LARGE,
2451
            null,
2452
            true,
2453
            true
2454
        );
2455
    }
2456
    $_course['course_image'] = $url_image;
2457
2458
    // Course large image
2459
    $_course['course_image_large_source'] = '';
2460
    if (file_exists($courseSys.'/course-pic.png')) {
2461
        $url_image = $webCourseHome.'/course-pic.png';
2462
        $_course['course_image_large_source'] = $courseSys.'/course-pic.png';
2463
    } else {
2464
        $url_image = Display::return_icon(
2465
            'session_default.png',
2466
            null,
2467
            null,
2468
            null,
2469
            null,
2470
            true,
2471
            true
2472
        );
2473
    }
2474
2475
    $_course['course_image_large'] = $url_image;
2476
2477
    return $_course;
2478
}
2479
2480
/**
2481
 * Returns a difficult to guess password.
2482
 *
2483
 * @param int $length the length of the password
2484
 *
2485
 * @return string the generated password
2486
 */
2487
function api_generate_password($length = 8)
2488
{
2489
    if ($length < 2) {
2490
        $length = 2;
2491
    }
2492
2493
    $charactersLowerCase = 'abcdefghijkmnopqrstuvwxyz';
2494
    $charactersUpperCase = 'ABCDEFGHJKLMNPQRSTUVWXYZ';
2495
    $minNumbers = 2;
2496
    $length = $length - $minNumbers;
2497
    $minLowerCase = round($length / 2);
2498
    $minUpperCase = $length - $minLowerCase;
2499
2500
    $password = '';
2501
    $passwordRequirements = api_get_configuration_value('password_requirements');
2502
2503
    $factory = new RandomLib\Factory();
2504
    $generator = $factory->getGenerator(new SecurityLib\Strength(SecurityLib\Strength::MEDIUM));
2505
2506
    if (!empty($passwordRequirements)) {
2507
        $length = $passwordRequirements['min']['length'];
2508
        $minNumbers = $passwordRequirements['min']['numeric'];
2509
        $minLowerCase = $passwordRequirements['min']['lowercase'];
2510
        $minUpperCase = $passwordRequirements['min']['uppercase'];
2511
2512
        $rest = $length - $minNumbers - $minLowerCase - $minUpperCase;
2513
        // Add the rest to fill the length requirement
2514
        if ($rest > 0) {
2515
            $password .= $generator->generateString($rest, $charactersLowerCase.$charactersUpperCase);
2516
        }
2517
    }
2518
2519
    // Min digits default 2
2520
    for ($i = 0; $i < $minNumbers; $i++) {
2521
        $password .= $generator->generateInt(2, 9);
2522
    }
2523
2524
    // Min lowercase
2525
    $password .= $generator->generateString($minLowerCase, $charactersLowerCase);
2526
2527
    // Min uppercase
2528
    $password .= $generator->generateString($minUpperCase, $charactersUpperCase);
2529
    $password = str_shuffle($password);
2530
2531
    return $password;
2532
}
2533
2534
/**
2535
 * Checks a password to see wether it is OK to use.
2536
 *
2537
 * @param string $password
2538
 *
2539
 * @return bool if the password is acceptable, false otherwise
2540
 *              Notes about what a password "OK to use" is:
2541
 *              1. The password should be at least 5 characters long.
2542
 *              2. Only English letters (uppercase or lowercase, it doesn't matter) and digits are allowed.
2543
 *              3. The password should contain at least 3 letters.
2544
 *              4. It should contain at least 2 digits.
2545
 *              Settings will change if the configuration value is set: password_requirements
2546
 */
2547
function api_check_password($password)
2548
{
2549
    $passwordRequirements = Security::getPasswordRequirements();
2550
2551
    $minLength = $passwordRequirements['min']['length'];
2552
    $minNumbers = $passwordRequirements['min']['numeric'];
2553
    // Optional
2554
    $minLowerCase = $passwordRequirements['min']['lowercase'];
2555
    $minUpperCase = $passwordRequirements['min']['uppercase'];
2556
2557
    $minLetters = $minLowerCase + $minUpperCase;
2558
    $passwordLength = api_strlen($password);
2559
2560
    $conditions = [
2561
        'min_length' => $passwordLength >= $minLength,
2562
    ];
2563
2564
    $digits = 0;
2565
    $lowerCase = 0;
2566
    $upperCase = 0;
2567
2568
    for ($i = 0; $i < $passwordLength; $i++) {
2569
        $currentCharacterCode = api_ord(api_substr($password, $i, 1));
2570
        if ($currentCharacterCode >= 65 && $currentCharacterCode <= 90) {
2571
            $upperCase++;
2572
        }
2573
2574
        if ($currentCharacterCode >= 97 && $currentCharacterCode <= 122) {
2575
            $lowerCase++;
2576
        }
2577
        if ($currentCharacterCode >= 48 && $currentCharacterCode <= 57) {
2578
            $digits++;
2579
        }
2580
    }
2581
2582
    // Min number of digits
2583
    $conditions['min_numeric'] = $digits >= $minNumbers;
2584
2585
    if (!empty($minUpperCase)) {
2586
        // Uppercase
2587
        $conditions['min_uppercase'] = $upperCase >= $minUpperCase;
2588
    }
2589
2590
    if (!empty($minLowerCase)) {
2591
        // Lowercase
2592
        $conditions['min_lowercase'] = $upperCase >= $minLowerCase;
2593
    }
2594
2595
    // Min letters
2596
    $letters = $upperCase + $lowerCase;
2597
    $conditions['min_letters'] = $letters >= $minLetters;
2598
2599
    $isPasswordOk = true;
2600
    foreach ($conditions as $condition) {
2601
        if ($condition === false) {
2602
            $isPasswordOk = false;
2603
            break;
2604
        }
2605
    }
2606
2607
    if ($isPasswordOk === false) {
2608
        $output = get_lang('NewPasswordRequirementsNotMatched').'<br />';
2609
        $output .= Security::getPasswordRequirementsToString($conditions);
2610
2611
        Display::addFlash(Display::return_message($output, 'warning', false));
2612
    }
2613
2614
    return $isPasswordOk;
2615
}
2616
2617
/**
2618
 * Clears the user ID from the session if it was the anonymous user. Generally
2619
 * used on out-of-tools pages to remove a user ID that could otherwise be used
2620
 * in the wrong context.
2621
 * This function is to be used in conjunction with the api_set_anonymous()
2622
 * function to simulate the user existence in case of an anonymous visit.
2623
 *
2624
 * @param bool      database check switch - passed to api_is_anonymous()
2625
 *
2626
 * @return bool true if succesfully unregistered, false if not anonymous
2627
 */
2628
function api_clear_anonymous($db_check = false)
2629
{
2630
    global $_user;
2631
    if (isset($_user['user_id']) && api_is_anonymous($_user['user_id'], $db_check)) {
2632
        unset($_user['user_id']);
2633
        Session::erase('_uid');
2634
2635
        return true;
2636
    }
2637
2638
    return false;
2639
}
2640
2641
/**
2642
 * Returns the status string corresponding to the status code.
2643
 *
2644
 * @author Noel Dieschburg
2645
 *
2646
 * @param int $status_code The integer status code (usually in the form of a constant)
2647
 *
2648
 * @return string
2649
 */
2650
function get_status_from_code($status_code)
2651
{
2652
    switch ($status_code) {
2653
        case STUDENT:
2654
            return get_lang('Student', '');
2655
        case COURSEMANAGER:
2656
            return get_lang('Teacher', '');
2657
        case SESSIONADMIN:
2658
            return get_lang('SessionsAdmin', '');
2659
        case DRH:
2660
            return get_lang('Drh', '');
2661
        case ANONYMOUS:
2662
            return get_lang('Anonymous', '');
2663
        case PLATFORM_ADMIN:
2664
            return get_lang('Administrator', '');
2665
        case SESSION_COURSE_COACH:
2666
            return get_lang('SessionCourseCoach', '');
2667
        case SESSION_GENERAL_COACH:
2668
            return get_lang('SessionGeneralCoach', '');
2669
        case COURSE_TUTOR:
2670
            return get_lang('CourseAssistant', '');
2671
        case STUDENT_BOSS:
2672
            return get_lang('StudentBoss', '');
2673
        case INVITEE:
2674
            return get_lang('Invitee', '');
2675
    }
2676
2677
    return '';
2678
}
2679
2680
/**
2681
 * Sets the current user as anonymous if it hasn't been identified yet. This
2682
 * function should be used inside a tool only. The function api_clear_anonymous()
2683
 * acts in the opposite direction by clearing the anonymous user's data every
2684
 * time we get on a course homepage or on a neutral page (index, admin, my space).
2685
 *
2686
 * @return bool true if set user as anonymous, false if user was already logged in or anonymous id could not be found
2687
 */
2688
function api_set_anonymous()
2689
{
2690
    global $_user;
2691
2692
    if (!empty($_user['user_id'])) {
2693
        return false;
2694
    }
2695
2696
    $user_id = api_get_anonymous_id();
2697
    if ($user_id == 0) {
2698
        return false;
2699
    }
2700
2701
    if (isset($_user['is_anonymous'])) {
2702
        return false;
2703
    }
2704
2705
    Session::erase('_user');
2706
    $_user['user_id'] = $user_id;
2707
    $_user['is_anonymous'] = true;
2708
    $GLOBALS['_user'] = $_user;
2709
    Session::write('_user', $_user);
2710
2711
    return true;
2712
}
2713
2714
/**
2715
 * Gets the current Chamilo (not PHP/cookie) session ID.
2716
 *
2717
 * @return int O if no active session, the session ID otherwise
2718
 */
2719
function api_get_session_id()
2720
{
2721
    return (int) Session::read('id_session', 0);
2722
}
2723
2724
/**
2725
 * Gets the current Chamilo (not social network) group ID.
2726
 *
2727
 * @return int O if no active group, the group id otherwise
2728
 */
2729
function api_get_group_id()
2730
{
2731
    return (int) Session::read('_gid', 0);
2732
}
2733
2734
/**
2735
 * Gets the current or given session name.
2736
 *
2737
 * @param   int     Session ID (optional)
2738
 *
2739
 * @return string The session name, or null if not found
2740
 */
2741
function api_get_session_name($session_id = 0)
2742
{
2743
    if (empty($session_id)) {
2744
        $session_id = api_get_session_id();
2745
        if (empty($session_id)) {
2746
            return null;
2747
        }
2748
    }
2749
    $t = Database::get_main_table(TABLE_MAIN_SESSION);
2750
    $s = "SELECT name FROM $t WHERE id = ".(int) $session_id;
2751
    $r = Database::query($s);
2752
    $c = Database::num_rows($r);
2753
    if ($c > 0) {
2754
        //technically, there can be only one, but anyway we take the first
2755
        $rec = Database::fetch_array($r);
2756
2757
        return $rec['name'];
2758
    }
2759
2760
    return null;
2761
}
2762
2763
/**
2764
 * Gets the session info by id.
2765
 *
2766
 * @param int $id Session ID
2767
 *
2768
 * @return array information of the session
2769
 */
2770
function api_get_session_info($id)
2771
{
2772
    return SessionManager::fetch($id);
2773
}
2774
2775
/**
2776
 * Gets the session visibility by session id.
2777
 *
2778
 * @param int  $session_id
2779
 * @param int  $courseId
2780
 * @param bool $ignore_visibility_for_admins
2781
 *
2782
 * @return int
2783
 *             0 = session still available,
2784
 *             SESSION_VISIBLE_READ_ONLY = 1,
2785
 *             SESSION_VISIBLE = 2,
2786
 *             SESSION_INVISIBLE = 3
2787
 */
2788
function api_get_session_visibility(
2789
    $session_id,
2790
    $courseId = null,
2791
    $ignore_visibility_for_admins = true
2792
) {
2793
    if (api_is_platform_admin()) {
2794
        if ($ignore_visibility_for_admins) {
2795
            return SESSION_AVAILABLE;
2796
        }
2797
    }
2798
2799
    $now = time();
2800
    if (empty($session_id)) {
2801
        return 0; // Means that the session is still available.
2802
    }
2803
2804
    $session_id = (int) $session_id;
2805
    $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
2806
2807
    $result = Database::query("SELECT * FROM $tbl_session WHERE id = $session_id");
2808
2809
    if (Database::num_rows($result) <= 0) {
2810
        return SESSION_INVISIBLE;
2811
    }
2812
2813
    $row = Database::fetch_array($result, 'ASSOC');
2814
    $visibility = $row['visibility'];
2815
2816
    // I don't care the session visibility.
2817
    if (empty($row['access_start_date']) && empty($row['access_end_date'])) {
2818
        // Session duration per student.
2819
        if (isset($row['duration']) && !empty($row['duration'])) {
2820
            $duration = $row['duration'] * 24 * 60 * 60;
2821
            $courseAccess = CourseManager::getFirstCourseAccessPerSessionAndUser($session_id, api_get_user_id());
2822
2823
            // If there is a session duration but there is no previous
2824
            // access by the user, then the session is still available
2825
            if (0 == count($courseAccess)) {
2826
                return SESSION_AVAILABLE;
2827
            }
2828
2829
            $currentTime = time();
2830
            $firstAccess = isset($courseAccess['login_course_date'])
2831
                ? api_strtotime($courseAccess['login_course_date'], 'UTC')
2832
                : 0;
2833
            $userDurationData = SessionManager::getUserSession(
2834
                api_get_user_id(),
2835
                $session_id
2836
            );
2837
            $userDuration = isset($userDurationData['duration'])
2838
                ? (intval($userDurationData['duration']) * 24 * 60 * 60)
2839
                : 0;
2840
2841
            $totalDuration = $firstAccess + $duration + $userDuration;
2842
2843
            return $totalDuration > $currentTime ? SESSION_AVAILABLE : SESSION_VISIBLE_READ_ONLY;
2844
        }
2845
2846
        return SESSION_AVAILABLE;
2847
    }
2848
2849
    // If start date was set.
2850
    if (!empty($row['access_start_date'])) {
2851
        $visibility = $now > api_strtotime($row['access_start_date'], 'UTC') ? SESSION_AVAILABLE : SESSION_INVISIBLE;
2852
    }
2853
2854
    // If the end date was set.
2855
    if (!empty($row['access_end_date'])) {
2856
        // Only if date_start said that it was ok
2857
        if ($visibility === SESSION_AVAILABLE) {
2858
            $visibility = $now < api_strtotime($row['access_end_date'], 'UTC')
2859
                ? SESSION_AVAILABLE // Date still available
2860
                : $row['visibility']; // Session ends
2861
        }
2862
    }
2863
2864
    // If I'm a coach the visibility can change in my favor depending in the coach dates.
2865
    $isCoach = api_is_coach($session_id, $courseId);
2866
2867
    if ($isCoach) {
2868
        // Test start date.
2869
        if (!empty($row['coach_access_start_date'])) {
2870
            $start = api_strtotime($row['coach_access_start_date'], 'UTC');
2871
            $visibility = $start < $now ? SESSION_AVAILABLE : SESSION_INVISIBLE;
2872
        }
2873
2874
        // Test end date.
2875
        if (!empty($row['coach_access_end_date'])) {
2876
            if ($visibility === SESSION_AVAILABLE) {
2877
                $endDateCoach = api_strtotime($row['coach_access_end_date'], 'UTC');
2878
                $visibility = $endDateCoach >= $now ? SESSION_AVAILABLE : $row['visibility'];
2879
            }
2880
        }
2881
    }
2882
2883
    return $visibility;
2884
}
2885
2886
/**
2887
 * This function returns a (star) session icon if the session is not null and
2888
 * the user is not a student.
2889
 *
2890
 * @param int $sessionId
2891
 * @param int $statusId  User status id - if 5 (student), will return empty
2892
 *
2893
 * @return string Session icon
2894
 */
2895
function api_get_session_image($sessionId, $statusId)
2896
{
2897
    $sessionId = (int) $sessionId;
2898
    $image = '';
2899
    if ($statusId != STUDENT) {
2900
        // Check whether is not a student
2901
        if ($sessionId > 0) {
2902
            $image = '&nbsp;&nbsp;'.Display::return_icon(
2903
                'star.png',
2904
                get_lang('SessionSpecificResource'),
2905
                ['align' => 'absmiddle'],
2906
                ICON_SIZE_SMALL
2907
            );
2908
        }
2909
    }
2910
2911
    return $image;
2912
}
2913
2914
/**
2915
 * This function add an additional condition according to the session of the course.
2916
 *
2917
 * @param int    $session_id        session id
2918
 * @param bool   $and               optional, true if more than one condition false if the only condition in the query
2919
 * @param bool   $with_base_content optional, true to accept content with session=0 as well,
2920
 *                                  false for strict session condition
2921
 * @param string $session_field
2922
 *
2923
 * @return string condition of the session
2924
 */
2925
function api_get_session_condition(
2926
    $session_id,
2927
    $and = true,
2928
    $with_base_content = false,
2929
    $session_field = 'session_id'
2930
) {
2931
    $session_id = (int) $session_id;
2932
2933
    if (empty($session_field)) {
2934
        $session_field = 'session_id';
2935
    }
2936
    // Condition to show resources by session
2937
    $condition_add = $and ? ' AND ' : ' WHERE ';
2938
2939
    if ($with_base_content) {
2940
        $condition_session = $condition_add." ( $session_field = $session_id OR $session_field = 0 OR $session_field IS NULL) ";
2941
    } else {
2942
        if (empty($session_id)) {
2943
            $condition_session = $condition_add." ($session_field = $session_id OR $session_field IS NULL)";
2944
        } else {
2945
            $condition_session = $condition_add." $session_field = $session_id ";
2946
        }
2947
    }
2948
2949
    return $condition_session;
2950
}
2951
2952
/**
2953
 * Returns the value of a setting from the web-adjustable admin config settings.
2954
 *
2955
 * WARNING true/false are stored as string, so when comparing you need to check e.g.
2956
 * if (api_get_setting('show_navigation_menu') == 'true') //CORRECT
2957
 * instead of
2958
 * if (api_get_setting('show_navigation_menu') == true) //INCORRECT
2959
 *
2960
 * @param string $variable The variable name
2961
 * @param string $key      The subkey (sub-variable) if any. Defaults to NULL
2962
 *
2963
 * @return string
2964
 *
2965
 * @author René Haentjens
2966
 * @author Bart Mollet
2967
 */
2968
function api_get_setting($variable, $key = null)
2969
{
2970
    global $_setting;
2971
    if ($variable == 'header_extra_content') {
2972
        $filename = api_get_home_path().'header_extra_content.txt';
2973
        if (file_exists($filename)) {
2974
            $value = file_get_contents($filename);
2975
2976
            return $value;
2977
        } else {
2978
            return '';
2979
        }
2980
    }
2981
    if ($variable == 'footer_extra_content') {
2982
        $filename = api_get_home_path().'footer_extra_content.txt';
2983
        if (file_exists($filename)) {
2984
            $value = file_get_contents($filename);
2985
2986
            return $value;
2987
        } else {
2988
            return '';
2989
        }
2990
    }
2991
    $value = null;
2992
    if (is_null($key)) {
2993
        $value = ((isset($_setting[$variable]) && $_setting[$variable] != '') ? $_setting[$variable] : null);
2994
    } else {
2995
        if (isset($_setting[$variable][$key])) {
2996
            $value = $_setting[$variable][$key];
2997
        }
2998
    }
2999
3000
    return $value;
3001
}
3002
3003
/**
3004
 * @param string $plugin
3005
 * @param string $variable
3006
 *
3007
 * @return string
3008
 */
3009
function api_get_plugin_setting($plugin, $variable)
3010
{
3011
    $variableName = $plugin.'_'.$variable;
3012
    $result = api_get_setting($variableName);
3013
3014
    if (isset($result[$plugin])) {
3015
        $value = $result[$plugin];
3016
        $unSerialized = UnserializeApi::unserialize('not_allowed_classes', $value, true);
3017
3018
        if (false !== $unSerialized) {
3019
            $value = $unSerialized;
3020
        }
3021
3022
        return $value;
3023
    }
3024
3025
    return null;
3026
}
3027
3028
/**
3029
 * Returns the value of a setting from the web-adjustable admin config settings.
3030
 */
3031
function api_get_settings_params($params)
3032
{
3033
    $table = Database::get_main_table(TABLE_MAIN_SETTINGS_CURRENT);
3034
3035
    return Database::select('*', $table, ['where' => $params]);
3036
}
3037
3038
/**
3039
 * @param array $params example: [id = ? => '1']
3040
 *
3041
 * @return array
3042
 */
3043
function api_get_settings_params_simple($params)
3044
{
3045
    $table = Database::get_main_table(TABLE_MAIN_SETTINGS_CURRENT);
3046
3047
    return Database::select('*', $table, ['where' => $params], 'one');
3048
}
3049
3050
/**
3051
 * Returns the value of a setting from the web-adjustable admin config settings.
3052
 */
3053
function api_delete_settings_params($params)
3054
{
3055
    $table = Database::get_main_table(TABLE_MAIN_SETTINGS_CURRENT);
3056
    $result = Database::delete($table, $params);
3057
3058
    return $result;
3059
}
3060
3061
/**
3062
 * Returns an escaped version of $_SERVER['PHP_SELF'] to avoid XSS injection.
3063
 *
3064
 * @return string Escaped version of $_SERVER['PHP_SELF']
3065
 */
3066
function api_get_self()
3067
{
3068
    return htmlentities($_SERVER['PHP_SELF']);
3069
}
3070
3071
/* USER PERMISSIONS */
3072
3073
/**
3074
 * Checks whether current user is a platform administrator.
3075
 *
3076
 * @param bool $allowSessionAdmins Whether session admins should be considered admins or not
3077
 * @param bool $allowDrh           Whether HR directors should be considered admins or not
3078
 *
3079
 * @return bool true if the user has platform admin rights,
3080
 *              false otherwise
3081
 *
3082
 * @see usermanager::is_admin(user_id) for a user-id specific function
3083
 */
3084
function api_is_platform_admin($allowSessionAdmins = false, $allowDrh = false)
3085
{
3086
    $isAdmin = Session::read('is_platformAdmin');
3087
    if ($isAdmin) {
3088
        return true;
3089
    }
3090
    $user = api_get_user_info();
3091
3092
    return
3093
        isset($user['status']) &&
3094
        (
3095
            ($allowSessionAdmins && $user['status'] == SESSIONADMIN) ||
3096
            ($allowDrh && $user['status'] == DRH)
3097
        );
3098
}
3099
3100
/**
3101
 * Checks whether the user given as user id is in the admin table.
3102
 *
3103
 * @param int $user_id If none provided, will use current user
3104
 * @param int $url     URL ID. If provided, also check if the user is active on given URL
3105
 *
3106
 * @return bool True if the user is admin, false otherwise
3107
 */
3108
function api_is_platform_admin_by_id($user_id = null, $url = null)
3109
{
3110
    $user_id = (int) $user_id;
3111
    if (empty($user_id)) {
3112
        $user_id = api_get_user_id();
3113
    }
3114
    $admin_table = Database::get_main_table(TABLE_MAIN_ADMIN);
3115
    $sql = "SELECT * FROM $admin_table WHERE user_id = $user_id";
3116
    $res = Database::query($sql);
3117
    $is_admin = Database::num_rows($res) === 1;
3118
    if (!$is_admin || !isset($url)) {
3119
        return $is_admin;
3120
    }
3121
    // We get here only if $url is set
3122
    $url = (int) $url;
3123
    $url_user_table = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
3124
    $sql = "SELECT * FROM $url_user_table
3125
            WHERE access_url_id = $url AND user_id = $user_id";
3126
    $res = Database::query($sql);
3127
    $result = Database::num_rows($res) === 1;
3128
3129
    return $result;
3130
}
3131
3132
/**
3133
 * Returns the user's numeric status ID from the users table.
3134
 *
3135
 * @param int $user_id If none provided, will use current user
3136
 *
3137
 * @return int User's status (1 for teacher, 5 for student, etc)
3138
 */
3139
function api_get_user_status($user_id = null)
3140
{
3141
    $user_id = (int) $user_id;
3142
    if (empty($user_id)) {
3143
        $user_id = api_get_user_id();
3144
    }
3145
    $table = Database::get_main_table(TABLE_MAIN_USER);
3146
    $sql = "SELECT status FROM $table WHERE user_id = $user_id ";
3147
    $result = Database::query($sql);
3148
    $status = null;
3149
    if (Database::num_rows($result)) {
3150
        $row = Database::fetch_array($result);
3151
        $status = $row['status'];
3152
    }
3153
3154
    return $status;
3155
}
3156
3157
/**
3158
 * Checks whether current user is allowed to create courses.
3159
 *
3160
 * @return bool true if the user has course creation rights,
3161
 *              false otherwise
3162
 */
3163
function api_is_allowed_to_create_course()
3164
{
3165
    if (api_is_platform_admin()) {
3166
        return true;
3167
    }
3168
3169
    // Teachers can only create courses
3170
    if (api_is_teacher()) {
3171
        if (api_get_setting('allow_users_to_create_courses') === 'true') {
3172
            return true;
3173
        } else {
3174
            return false;
3175
        }
3176
    }
3177
3178
    return Session::read('is_allowedCreateCourse');
3179
}
3180
3181
/**
3182
 * Checks whether the current user is a course administrator.
3183
 *
3184
 * @return bool True if current user is a course administrator
3185
 */
3186
function api_is_course_admin()
3187
{
3188
    if (api_is_platform_admin()) {
3189
        return true;
3190
    }
3191
3192
    return Session::read('is_courseAdmin');
3193
}
3194
3195
/**
3196
 * Checks whether the current user is a course coach
3197
 * Based on the presence of user in session.id_coach (session general coach).
3198
 *
3199
 * @return bool True if current user is a course coach
3200
 */
3201
function api_is_session_general_coach()
3202
{
3203
    return Session::read('is_session_general_coach');
3204
}
3205
3206
/**
3207
 * Checks whether the current user is a course tutor
3208
 * Based on the presence of user in session_rel_course_rel_user.user_id with status = 2.
3209
 *
3210
 * @return bool True if current user is a course tutor
3211
 */
3212
function api_is_course_tutor()
3213
{
3214
    return Session::read('is_courseTutor');
3215
}
3216
3217
/**
3218
 * @param int $user_id
3219
 * @param int $courseId
3220
 * @param int $session_id
3221
 *
3222
 * @return bool
3223
 */
3224
function api_is_course_session_coach($user_id, $courseId, $session_id)
3225
{
3226
    $session_table = Database::get_main_table(TABLE_MAIN_SESSION);
3227
    $session_rel_course_rel_user_table = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
3228
3229
    $user_id = (int) $user_id;
3230
    $session_id = (int) $session_id;
3231
    $courseId = (int) $courseId;
3232
3233
    $sql = "SELECT DISTINCT session.id
3234
            FROM $session_table
3235
            INNER JOIN $session_rel_course_rel_user_table session_rc_ru
3236
            ON session.id = session_rc_ru.session_id
3237
            WHERE
3238
                session_rc_ru.user_id = '".$user_id."'  AND
3239
                session_rc_ru.c_id = '$courseId' AND
3240
                session_rc_ru.status = 2 AND
3241
                session_rc_ru.session_id = '$session_id'";
3242
    $result = Database::query($sql);
3243
3244
    return Database::num_rows($result) > 0;
3245
}
3246
3247
/**
3248
 * Checks whether the current user is a course or session coach.
3249
 *
3250
 * @param int $session_id
3251
 * @param int $courseId
3252
 * @param bool  Check whether we are in student view and, if we are, return false
3253
 *
3254
 * @return bool True if current user is a course or session coach
3255
 */
3256
function api_is_coach($session_id = 0, $courseId = null, $check_student_view = true)
3257
{
3258
    $userId = api_get_user_id();
3259
3260
    if (!empty($session_id)) {
3261
        $session_id = (int) $session_id;
3262
    } else {
3263
        $session_id = api_get_session_id();
3264
    }
3265
3266
    // The student preview was on
3267
    if ($check_student_view && api_is_student_view_active()) {
3268
        return false;
3269
    }
3270
3271
    if (!empty($courseId)) {
3272
        $courseId = (int) $courseId;
3273
    } else {
3274
        $courseId = api_get_course_int_id();
3275
    }
3276
3277
    $session_table = Database::get_main_table(TABLE_MAIN_SESSION);
3278
    $session_rel_course_rel_user_table = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
3279
    $sessionIsCoach = [];
3280
3281
    if (!empty($courseId)) {
3282
        $sql = "SELECT DISTINCT s.id, name, access_start_date, access_end_date
3283
                FROM $session_table s
3284
                INNER JOIN $session_rel_course_rel_user_table session_rc_ru
3285
                ON session_rc_ru.session_id = s.id AND session_rc_ru.user_id = '".$userId."'
3286
                WHERE
3287
                    session_rc_ru.c_id = '$courseId' AND
3288
                    session_rc_ru.status = 2 AND
3289
                    session_rc_ru.session_id = '$session_id'";
3290
        $result = Database::query($sql);
3291
        $sessionIsCoach = Database::store_result($result);
3292
    }
3293
3294
    if (!empty($session_id)) {
3295
        $sql = "SELECT DISTINCT id, name, access_start_date, access_end_date
3296
                FROM $session_table
3297
                WHERE session.id_coach = $userId AND id = $session_id
3298
                ORDER BY access_start_date, access_end_date, name";
3299
        $result = Database::query($sql);
3300
        if (!empty($sessionIsCoach)) {
3301
            $sessionIsCoach = array_merge(
3302
                $sessionIsCoach,
3303
                Database::store_result($result)
3304
            );
3305
        } else {
3306
            $sessionIsCoach = Database::store_result($result);
3307
        }
3308
    }
3309
3310
    return count($sessionIsCoach) > 0;
3311
}
3312
3313
/**
3314
 * Checks whether the current user is a session administrator.
3315
 *
3316
 * @return bool True if current user is a course administrator
3317
 */
3318
function api_is_session_admin()
3319
{
3320
    $user = api_get_user_info();
3321
3322
    return isset($user['status']) && $user['status'] == SESSIONADMIN;
3323
}
3324
3325
/**
3326
 * Checks whether the current user is a human resources manager.
3327
 *
3328
 * @return bool True if current user is a human resources manager
3329
 */
3330
function api_is_drh()
3331
{
3332
    $user = api_get_user_info();
3333
3334
    return isset($user['status']) && $user['status'] == DRH;
3335
}
3336
3337
/**
3338
 * Checks whether the current user is a student.
3339
 *
3340
 * @return bool True if current user is a human resources manager
3341
 */
3342
function api_is_student()
3343
{
3344
    $user = api_get_user_info();
3345
3346
    return isset($user['status']) && $user['status'] == STUDENT;
3347
}
3348
3349
/**
3350
 * Checks whether the current user has the status 'teacher'.
3351
 *
3352
 * @return bool True if current user is a human resources manager
3353
 */
3354
function api_is_teacher()
3355
{
3356
    $user = api_get_user_info();
3357
3358
    return isset($user['status']) && $user['status'] == COURSEMANAGER;
3359
}
3360
3361
/**
3362
 * Checks whether the current user is a invited user.
3363
 *
3364
 * @return bool
3365
 */
3366
function api_is_invitee()
3367
{
3368
    $user = api_get_user_info();
3369
3370
    return isset($user['status']) && $user['status'] == INVITEE;
3371
}
3372
3373
/**
3374
 * This function checks whether a session is assigned into a category.
3375
 *
3376
 * @param int       - session id
0 ignored issues
show
Documentation Bug introduced by
The doc comment - at position 0 could not be parsed: Unknown type name '-' at position 0 in -.
Loading history...
3377
 * @param string    - category name
3378
 *
3379
 * @return bool - true if is found, otherwise false
3380
 */
3381
function api_is_session_in_category($session_id, $category_name)
3382
{
3383
    $session_id = (int) $session_id;
3384
    $category_name = Database::escape_string($category_name);
3385
    $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
3386
    $tbl_session_category = Database::get_main_table(TABLE_MAIN_SESSION_CATEGORY);
3387
3388
    $sql = "SELECT 1
3389
            FROM $tbl_session
3390
            WHERE $session_id IN (
3391
                SELECT s.id FROM $tbl_session s, $tbl_session_category sc
3392
                WHERE
3393
                  s.session_category_id = sc.id AND
3394
                  sc.name LIKE '%$category_name'
3395
            )";
3396
    $rs = Database::query($sql);
3397
3398
    if (Database::num_rows($rs) > 0) {
3399
        return true;
3400
    } else {
3401
        return false;
3402
    }
3403
}
3404
3405
/**
3406
 * Displays the title of a tool.
3407
 * Normal use: parameter is a string:
3408
 * api_display_tool_title("My Tool").
3409
 *
3410
 * Optionally, there can be a subtitle below
3411
 * the normal title, and / or a supra title above the normal title.
3412
 *
3413
 * e.g. supra title:
3414
 * group
3415
 * GROUP PROPERTIES
3416
 *
3417
 * e.g. subtitle:
3418
 * AGENDA
3419
 * calender & events tool
3420
 *
3421
 * @author Hugues Peeters <[email protected]>
3422
 *
3423
 * @param mixed $title_element - it could either be a string or an array
3424
 *                             containing 'supraTitle', 'mainTitle',
3425
 *                             'subTitle'
3426
 */
3427
function api_display_tool_title($title_element)
3428
{
3429
    if (is_string($title_element)) {
3430
        $tit = $title_element;
3431
        unset($title_element);
3432
        $title_element = [];
3433
        $title_element['mainTitle'] = $tit;
3434
    }
3435
    echo '<h3>';
3436
    if (!empty($title_element['supraTitle'])) {
3437
        echo '<small>'.$title_element['supraTitle'].'</small><br />';
3438
    }
3439
    if (!empty($title_element['mainTitle'])) {
3440
        echo $title_element['mainTitle'];
3441
    }
3442
    if (!empty($title_element['subTitle'])) {
3443
        echo '<br /><small>'.$title_element['subTitle'].'</small>';
3444
    }
3445
    echo '</h3>';
3446
}
3447
3448
/**
3449
 * Displays options for switching between student view and course manager view.
3450
 *
3451
 * Changes in version 1.2 (Patrick Cool)
3452
 * Student view switch now behaves as a real switch. It maintains its current state until the state
3453
 * is changed explicitly
3454
 *
3455
 * Changes in version 1.1 (Patrick Cool)
3456
 * student view now works correctly in subfolders of the document tool
3457
 * student view works correctly in the new links tool
3458
 *
3459
 * Example code for using this in your tools:
3460
 * //if ($is_courseAdmin && api_get_setting('student_view_enabled') == 'true') {
3461
 * //   display_tool_view_option($isStudentView);
3462
 * //}
3463
 * //and in later sections, use api_is_allowed_to_edit()
3464
 *
3465
 * @author Roan Embrechts
3466
 * @author Patrick Cool
3467
 * @author Julio Montoya, changes added in Chamilo
3468
 *
3469
 * @version 1.2
3470
 *
3471
 * @todo rewrite code so it is easier to understand
3472
 */
3473
function api_display_tool_view_option()
3474
{
3475
    if (api_get_setting('student_view_enabled') != 'true') {
3476
        return '';
3477
    }
3478
3479
    $sourceurl = '';
3480
    $is_framed = false;
3481
    // Exceptions apply for all multi-frames pages
3482
    if (strpos($_SERVER['REQUEST_URI'], 'chat/chat_banner.php') !== false) {
3483
        // The chat is a multiframe bit that doesn't work too well with the student_view, so do not show the link
3484
        return '';
3485
    }
3486
3487
    // Uncomment to remove student view link from document view page
3488
    if (strpos($_SERVER['REQUEST_URI'], 'lp/lp_header.php') !== false) {
3489
        if (empty($_GET['lp_id'])) {
3490
            return '';
3491
        }
3492
        $sourceurl = substr($_SERVER['REQUEST_URI'], 0, strpos($_SERVER['REQUEST_URI'], '?'));
3493
        $sourceurl = str_replace(
3494
            'lp/lp_header.php',
3495
            'lp/lp_controller.php?'.api_get_cidreq().'&action=view&lp_id='.intval($_GET['lp_id']).'&isStudentView='.($_SESSION['studentview'] == 'studentview' ? 'false' : 'true'),
3496
            $sourceurl
3497
        );
3498
        //showinframes doesn't handle student view anyway...
3499
        //return '';
3500
        $is_framed = true;
3501
    }
3502
3503
    // Check whether the $_SERVER['REQUEST_URI'] contains already url parameters (thus a questionmark)
3504
    if (!$is_framed) {
3505
        if (strpos($_SERVER['REQUEST_URI'], '?') === false) {
3506
            $sourceurl = api_get_self().'?'.api_get_cidreq();
3507
        } else {
3508
            $sourceurl = $_SERVER['REQUEST_URI'];
3509
        }
3510
    }
3511
3512
    $output_string = '';
3513
    if (!empty($_SESSION['studentview'])) {
3514
        if ($_SESSION['studentview'] == 'studentview') {
3515
            // We have to remove the isStudentView=true from the $sourceurl
3516
            $sourceurl = str_replace('&isStudentView=true', '', $sourceurl);
3517
            $sourceurl = str_replace('&isStudentView=false', '', $sourceurl);
3518
            $output_string .= '<a class="btn btn-primary btn-sm" href="'.$sourceurl.'&isStudentView=false" target="_self">'.
3519
                Display::returnFontAwesomeIcon('eye').' '.get_lang('SwitchToTeacherView').'</a>';
3520
        } elseif ($_SESSION['studentview'] == 'teacherview') {
3521
            // Switching to teacherview
3522
            $sourceurl = str_replace('&isStudentView=true', '', $sourceurl);
3523
            $sourceurl = str_replace('&isStudentView=false', '', $sourceurl);
3524
            $output_string .= '<a class="btn btn-default btn-sm" href="'.$sourceurl.'&isStudentView=true" target="_self">'.
3525
                Display::returnFontAwesomeIcon('eye').' '.get_lang('SwitchToStudentView').'</a>';
3526
        }
3527
    } else {
3528
        $output_string .= '<a class="btn btn-default btn-sm" href="'.$sourceurl.'&isStudentView=true" target="_self">'.
3529
            Display::returnFontAwesomeIcon('eye').' '.get_lang('SwitchToStudentView').'</a>';
3530
    }
3531
    $output_string = Security::remove_XSS($output_string);
3532
    $html = Display::tag('div', $output_string, ['class' => 'view-options']);
3533
3534
    return $html;
3535
}
3536
3537
// TODO: This is for the permission section.
3538
/**
3539
 * Function that removes the need to directly use is_courseAdmin global in
3540
 * tool scripts. It returns true or false depending on the user's rights in
3541
 * this particular course.
3542
 * Optionally checking for tutor and coach roles here allows us to use the
3543
 * student_view feature altogether with these roles as well.
3544
 *
3545
 * @param bool  Whether to check if the user has the tutor role
3546
 * @param bool  Whether to check if the user has the coach role
3547
 * @param bool  Whether to check if the user has the session coach role
3548
 * @param bool  check the student view or not
3549
 *
3550
 * @author Roan Embrechts
3551
 * @author Patrick Cool
3552
 * @author Julio Montoya
3553
 *
3554
 * @version 1.1, February 2004
3555
 *
3556
 * @return bool true: the user has the rights to edit, false: he does not
3557
 */
3558
function api_is_allowed_to_edit(
3559
    $tutor = false,
3560
    $coach = false,
3561
    $session_coach = false,
3562
    $check_student_view = true
3563
) {
3564
    $allowSessionAdminEdit = api_get_configuration_value('session_admins_edit_courses_content') === true;
3565
3566
    // Admins can edit anything.
3567
    if (api_is_platform_admin($allowSessionAdminEdit)) {
3568
        //The student preview was on
3569
        if ($check_student_view && api_is_student_view_active()) {
3570
            return false;
3571
        }
3572
3573
        return true;
3574
    }
3575
3576
    $sessionId = api_get_session_id();
3577
3578
    if ($sessionId && api_get_configuration_value('session_courses_read_only_mode')) {
3579
        $efv = new ExtraFieldValue('course');
3580
        $lockExrafieldField = $efv->get_values_by_handler_and_field_variable(
3581
            api_get_course_int_id(),
3582
            'session_courses_read_only_mode'
3583
        );
3584
3585
        if (!empty($lockExrafieldField['value'])) {
3586
            return false;
3587
        }
3588
    }
3589
3590
    $is_allowed_coach_to_edit = api_is_coach(null, null, $check_student_view);
3591
    $session_visibility = api_get_session_visibility($sessionId);
3592
    $is_courseAdmin = api_is_course_admin();
3593
3594
    if (!$is_courseAdmin && $tutor) {
3595
        // If we also want to check if the user is a tutor...
3596
        $is_courseAdmin = $is_courseAdmin || api_is_course_tutor();
3597
    }
3598
3599
    if (!$is_courseAdmin && $coach) {
3600
        // If we also want to check if the user is a coach...';
3601
        // Check if session visibility is read only for coaches.
3602
        if ($session_visibility == SESSION_VISIBLE_READ_ONLY) {
3603
            $is_allowed_coach_to_edit = false;
3604
        }
3605
3606
        if (api_get_setting('allow_coach_to_edit_course_session') == 'true') {
3607
            // Check if coach is allowed to edit a course.
3608
            $is_courseAdmin = $is_courseAdmin || $is_allowed_coach_to_edit;
3609
        }
3610
    }
3611
3612
    if (!$is_courseAdmin && $session_coach) {
3613
        $is_courseAdmin = $is_courseAdmin || $is_allowed_coach_to_edit;
3614
    }
3615
3616
    // Check if the student_view is enabled, and if so, if it is activated.
3617
    if (api_get_setting('student_view_enabled') == 'true') {
3618
        if (!empty($sessionId)) {
3619
            // Check if session visibility is read only for coaches.
3620
            if ($session_visibility == SESSION_VISIBLE_READ_ONLY) {
3621
                $is_allowed_coach_to_edit = false;
3622
            }
3623
3624
            if (api_get_setting('allow_coach_to_edit_course_session') == 'true') {
3625
                // Check if coach is allowed to edit a course.
3626
                $is_allowed = $is_allowed_coach_to_edit;
3627
            } else {
3628
                $is_allowed = false;
3629
            }
3630
            if ($check_student_view) {
3631
                $is_allowed = $is_allowed && $_SESSION['studentview'] != 'studentview';
3632
            }
3633
        } else {
3634
            if ($check_student_view) {
3635
                $is_allowed = $is_courseAdmin && $_SESSION['studentview'] != 'studentview';
3636
            } else {
3637
                $is_allowed = $is_courseAdmin;
3638
            }
3639
        }
3640
3641
        return $is_allowed;
3642
    } else {
3643
        return $is_courseAdmin;
3644
    }
3645
}
3646
3647
/**
3648
 * Returns true if user is a course coach of at least one course in session.
3649
 *
3650
 * @param int $sessionId
3651
 *
3652
 * @return bool
3653
 */
3654
function api_is_coach_of_course_in_session($sessionId)
3655
{
3656
    if (api_is_platform_admin()) {
3657
        return true;
3658
    }
3659
3660
    $userId = api_get_user_id();
3661
    $courseList = UserManager::get_courses_list_by_session(
3662
        $userId,
3663
        $sessionId
3664
    );
3665
3666
    // Session visibility.
3667
    $visibility = api_get_session_visibility(
3668
        $sessionId,
3669
        null,
3670
        false
3671
    );
3672
3673
    if ($visibility != SESSION_VISIBLE && !empty($courseList)) {
3674
        // Course Coach session visibility.
3675
        $blockedCourseCount = 0;
3676
        $closedVisibilityList = [
3677
            COURSE_VISIBILITY_CLOSED,
3678
            COURSE_VISIBILITY_HIDDEN,
3679
        ];
3680
3681
        foreach ($courseList as $course) {
3682
            // Checking session visibility
3683
            $sessionCourseVisibility = api_get_session_visibility(
3684
                $sessionId,
3685
                $course['real_id']
3686
            );
3687
3688
            $courseIsVisible = !in_array(
3689
                $course['visibility'],
3690
                $closedVisibilityList
3691
            );
3692
            if ($courseIsVisible === false || $sessionCourseVisibility == SESSION_INVISIBLE) {
3693
                $blockedCourseCount++;
3694
            }
3695
        }
3696
3697
        // If all courses are blocked then no show in the list.
3698
        if ($blockedCourseCount === count($courseList)) {
3699
            $visibility = SESSION_INVISIBLE;
3700
        } else {
3701
            $visibility = SESSION_VISIBLE;
3702
        }
3703
    }
3704
3705
    switch ($visibility) {
3706
        case SESSION_VISIBLE_READ_ONLY:
3707
        case SESSION_VISIBLE:
3708
        case SESSION_AVAILABLE:
3709
            return true;
3710
            break;
0 ignored issues
show
Unused Code introduced by
break is not strictly necessary here and could be removed.

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

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

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

Loading history...
3711
        case SESSION_INVISIBLE:
3712
            return false;
3713
    }
3714
3715
    return false;
3716
}
3717
3718
/**
3719
 * Checks if a student can edit contents in a session depending
3720
 * on the session visibility.
3721
 *
3722
 * @param bool $tutor Whether to check if the user has the tutor role
3723
 * @param bool $coach Whether to check if the user has the coach role
3724
 *
3725
 * @return bool true: the user has the rights to edit, false: he does not
3726
 */
3727
function api_is_allowed_to_session_edit($tutor = false, $coach = false)
3728
{
3729
    if (api_is_allowed_to_edit($tutor, $coach)) {
3730
        // If I'm a teacher, I will return true in order to not affect the normal behaviour of Chamilo tools.
3731
        return true;
3732
    } else {
3733
        $sessionId = api_get_session_id();
3734
3735
        if (0 == $sessionId) {
3736
            // I'm not in a session so i will return true to not affect the normal behaviour of Chamilo tools.
3737
            return true;
3738
        } else {
3739
            // I'm in a session and I'm a student
3740
            // Get the session visibility
3741
            $session_visibility = api_get_session_visibility($sessionId);
3742
            // if 5 the session is still available
3743
            switch ($session_visibility) {
3744
                case SESSION_VISIBLE_READ_ONLY: // 1
3745
                    return false;
3746
                case SESSION_VISIBLE:           // 2
3747
                    return true;
3748
                case SESSION_INVISIBLE:         // 3
3749
                    return false;
3750
                case SESSION_AVAILABLE:         //5
3751
                    return true;
3752
            }
3753
        }
3754
    }
3755
3756
    return false;
3757
}
3758
3759
/**
3760
 * Checks whether the user is allowed in a specific tool for a specific action.
3761
 *
3762
 * @param string $tool   the tool we are checking if the user has a certain permission
3763
 * @param string $action the action we are checking (add, edit, delete, move, visibility)
3764
 *
3765
 * @return bool
3766
 *
3767
 * @author Patrick Cool <[email protected]>, Ghent University
3768
 * @author Julio Montoya
3769
 *
3770
 * @version 1.0
3771
 */
3772
function api_is_allowed($tool, $action, $task_id = 0)
3773
{
3774
    $_user = api_get_user_info();
3775
    $_course = api_get_course_info();
3776
3777
    if (api_is_course_admin()) {
3778
        return true;
3779
    }
3780
3781
    if (is_array($_course) and count($_course) > 0) {
3782
        require_once __DIR__.'/../../permissions/permissions_functions.inc.php';
3783
3784
        // Getting the permissions of this user.
3785
        if ($task_id == 0) {
3786
            $user_permissions = get_permissions('user', $_user['user_id']);
3787
            $_SESSION['total_permissions'][$_course['code']] = $user_permissions;
3788
        }
3789
3790
        // Getting the permissions of the task.
3791
        if ($task_id != 0) {
3792
            $task_permissions = get_permissions('task', $task_id);
3793
            $_SESSION['total_permissions'][$_course['code']] = $task_permissions;
3794
        }
3795
        //print_r($_SESSION['total_permissions']);
3796
3797
        // Getting the permissions of the groups of the user
3798
        //$groups_of_user = GroupManager::get_group_ids($_course['db_name'], $_user['user_id']);
3799
3800
        //foreach($groups_of_user as $group)
3801
        //   $this_group_permissions = get_permissions('group', $group);
3802
3803
        // Getting the permissions of the courseroles of the user
3804
        $user_courserole_permissions = get_roles_permissions('user', $_user['user_id']);
3805
3806
        // Getting the permissions of the platformroles of the user
3807
        //$user_platformrole_permissions = get_roles_permissions('user', $_user['user_id'], ', platform');
3808
3809
        // Getting the permissions of the roles of the groups of the user
3810
        //foreach($groups_of_user as $group)
3811
        //    $this_group_courserole_permissions = get_roles_permissions('group', $group);
3812
3813
        // Getting the permissions of the platformroles of the groups of the user
3814
        //foreach($groups_of_user as $group)
3815
        //    $this_group_platformrole_permissions = get_roles_permissions('group', $group, 'platform');
3816
    }
3817
3818
    // If the permissions are limited, we have to map the extended ones to the limited ones.
3819
    if (api_get_setting('permissions') == 'limited') {
3820
        if ($action == 'Visibility') {
3821
            $action = 'Edit';
3822
        }
3823
        if ($action == 'Move') {
3824
            $action = 'Edit';
3825
        }
3826
    }
3827
3828
    // The session that contains all the permissions already exists for this course
3829
    // so there is no need to requery everything.
3830
    //my_print_r($_SESSION['total_permissions'][$_course['code']][$tool]);
3831
    if (is_array($_SESSION['total_permissions'][$_course['code']][$tool])) {
3832
        if (in_array($action, $_SESSION['total_permissions'][$_course['code']][$tool])) {
3833
            return true;
3834
        } else {
3835
            return false;
3836
        }
3837
    }
3838
3839
    return false;
3840
}
3841
3842
/**
3843
 * Tells whether this user is an anonymous user.
3844
 *
3845
 * @param int  $user_id  User ID (optional, will take session ID if not provided)
3846
 * @param bool $db_check Whether to check in the database (true) or simply in
3847
 *                       the session (false) to see if the current user is the anonymous user
3848
 *
3849
 * @return bool true if this user is anonymous, false otherwise
3850
 */
3851
function api_is_anonymous($user_id = null, $db_check = false)
3852
{
3853
    if (!isset($user_id)) {
3854
        $user_id = api_get_user_id();
3855
    }
3856
3857
    if ($db_check) {
3858
        $info = api_get_user_info($user_id);
3859
        if (false === $info || $info['status'] == ANONYMOUS) {
3860
            return true;
3861
        }
3862
    }
3863
3864
    $_user = api_get_user_info();
3865
3866
    if (isset($_user['status']) && $_user['status'] == ANONYMOUS) {
3867
        //if ($_user['user_id'] == 0) {
3868
        // In some cases, api_set_anonymous doesn't seem to be triggered in local.inc.php. Make sure it is.
3869
        // Occurs in agenda for admin links - YW
3870
        global $use_anonymous;
3871
        if (isset($use_anonymous) && $use_anonymous) {
3872
            api_set_anonymous();
3873
        }
3874
3875
        return true;
3876
    }
3877
3878
    return (isset($_user['is_anonymous']) && $_user['is_anonymous'] === true) || $_user === false;
3879
}
3880
3881
/**
3882
 * Displays message "You are not allowed here..." and exits the entire script.
3883
 *
3884
 * @param bool   $print_headers Whether or not to print headers (default = false -> does not print them)
3885
 * @param string $message
3886
 * @param int    $responseCode
3887
 */
3888
function api_not_allowed(
3889
    $print_headers = false,
3890
    $message = null,
3891
    $responseCode = 0
3892
) {
3893
    if (api_get_setting('sso_authentication') === 'true') {
3894
        global $osso;
3895
        if ($osso) {
3896
            $osso->logout();
3897
        }
3898
    }
3899
    $home_url = api_get_path(WEB_PATH);
3900
    $user_id = api_get_user_id();
3901
    $course = api_get_course_id();
3902
3903
    global $this_section;
3904
3905
    if (CustomPages::enabled() && !isset($user_id)) {
3906
        if (empty($user_id)) {
3907
            // Why the CustomPages::enabled() need to be to set the request_uri
3908
            $_SESSION['request_uri'] = $_SERVER['REQUEST_URI'];
3909
        }
3910
        CustomPages::display(CustomPages::INDEX_UNLOGGED);
3911
    }
3912
3913
    $origin = api_get_origin();
3914
3915
    $msg = null;
3916
    if (isset($message)) {
3917
        $msg = $message;
3918
    } else {
3919
        $msg = Display::return_message(
3920
            get_lang('NotAllowedClickBack').'
3921
            <script>function goBack(){window.history.back();}</script>',
3922
            'error',
3923
            false
3924
        );
3925
        $msg .= '<p class="text-center">
3926
             <a onclick="goBack();" class="btn btn-default" href="'.$home_url.'">'.get_lang('GoBack').'</a>
3927
             </p>';
3928
    }
3929
3930
    $msg = Display::div($msg, ['align' => 'center']);
3931
3932
    $show_headers = 0;
3933
    if ($print_headers && $origin != 'learnpath') {
3934
        $show_headers = 1;
3935
    }
3936
3937
    $tpl = new Template(null, $show_headers, $show_headers, false, true, false, true, $responseCode);
3938
    $tpl->assign('hide_login_link', 1);
3939
    $tpl->assign('content', $msg);
3940
3941
    if (($user_id != 0 && !api_is_anonymous()) &&
3942
        (!isset($course) || $course == -1) &&
3943
        empty($_GET['cidReq'])
3944
    ) {
3945
        // if the access is not authorized and there is some login information
3946
        // but the cidReq is not found, assume we are missing course data and send the user
3947
        // to the user_portal
3948
        $tpl->display_one_col_template();
3949
        exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

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

Loading history...
3950
    }
3951
3952
    if (!empty($_SERVER['REQUEST_URI']) &&
3953
        (
3954
            !empty($_GET['cidReq']) ||
3955
            $this_section == SECTION_MYPROFILE ||
3956
            $this_section == SECTION_PLATFORM_ADMIN
3957
        )
3958
    ) {
3959
        $courseCode = api_get_course_id();
3960
        // Only display form and return to the previous URL if there was a course ID included
3961
        if ($user_id != 0 && !api_is_anonymous()) {
3962
            //if there is a user ID, then the user is not allowed but the session is still there. Say so and exit
3963
            $tpl->assign('content', $msg);
3964
            $tpl->display_one_col_template();
3965
            exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

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

Loading history...
3966
        }
3967
3968
        if (!is_null($courseCode)) {
3969
            api_set_firstpage_parameter($courseCode);
3970
        }
3971
3972
        // If the user has no user ID, then his session has expired
3973
        $form = api_get_not_allowed_login_form();
3974
3975
        // see same text in auth/gotocourse.php and main_api.lib.php function api_not_allowed (above)
3976
        $content = Display::return_message(get_lang('NotAllowed'), 'error', false);
3977
3978
        if (!empty($courseCode)) {
3979
            $content .= '<h4>'.get_lang('LoginToGoToThisCourse').'</h4>';
3980
        }
3981
3982
        if (api_is_cas_activated()) {
3983
            $content .= Display::return_message(sprintf(get_lang('YouHaveAnInstitutionalAccount'), api_get_setting("Institution")), '', false);
3984
            $content .= Display::div(
3985
                Template::displayCASLoginButton(),
3986
                ['align' => 'center']
3987
            );
3988
            $content .= Display::return_message(get_lang('YouDontHaveAnInstitutionAccount'));
3989
            $content .= "<p style='text-align:center'><a href='#' onclick='$(this).parent().next().toggle()'>".get_lang('LoginWithExternalAccount')."</a></p>";
3990
            $content .= "<div style='display:none;'>";
3991
        }
3992
        $content .= '<div class="well">';
3993
        $content .= $form->returnForm();
3994
        $content .= '</div>';
3995
        if (api_is_cas_activated()) {
3996
            $content .= "</div>";
3997
        }
3998
3999
        if (!empty($courseCode)) {
4000
            $content .= '<hr/><p style="text-align:center"><a href="'.$home_url.'">'.
4001
                get_lang('ReturnToCourseHomepage').'</a></p>';
4002
        } else {
4003
            $content .= '<hr/><p style="text-align:center"><a href="'.$home_url.'">'.
4004
                get_lang('BackHome').'</a></p>';
4005
        }
4006
4007
        $tpl->setLoginBodyClass();
4008
        $tpl->assign('content', $content);
4009
        $tpl->display_one_col_template();
4010
        exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

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

Loading history...
4011
    }
4012
4013
    if ($user_id != 0 && !api_is_anonymous()) {
4014
        $tpl->display_one_col_template();
4015
        exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

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

Loading history...
4016
    }
4017
4018
    $msg = null;
4019
    // The session is over and we were not in a course,
4020
    // or we try to get directly to a private course without being logged
4021
    $courseId = api_get_course_int_id();
4022
    if (!empty($courseId)) {
4023
        api_set_firstpage_parameter(api_get_course_id());
4024
        $tpl->setLoginBodyClass();
4025
4026
        // see same text in auth/gotocourse.php and main_api.lib.php function api_not_allowed (bellow)
4027
        $msg = Display::return_message(get_lang('NotAllowed'), 'error', false);
4028
        $msg .= '<h4>'.get_lang('LoginToGoToThisCourse').'</h4>';
4029
        $casEnabled = api_is_cas_activated();
4030
        if ($casEnabled) {
4031
            $msg .= Display::return_message(
4032
                sprintf(get_lang('YouHaveAnInstitutionalAccount'), api_get_setting("Institution")),
4033
                '',
4034
                false
4035
            );
4036
            $msg .= Display::div(
4037
                Template::displayCASLoginButton(),
4038
                ['align' => 'center']
4039
            );
4040
            $msg .= Display::return_message(get_lang('YouDontHaveAnInstitutionAccount'));
4041
            $msg .= "<p style='text-align:center'><a href='#' onclick='$(this).parent().next().toggle()'>".get_lang('LoginWithExternalAccount')."</a></p>";
4042
            $msg .= "<div style='display:none;'>";
4043
        }
4044
        $form = api_get_not_allowed_login_form();
4045
        $msg .= '<div class="well">';
4046
        $msg .= $form->returnForm();
4047
        $msg .= '</div>';
4048
        if ($casEnabled) {
4049
            $msg .= "</div>";
4050
        }
4051
    } else {
4052
        // we were not in a course, return to home page
4053
        $msg = Display::return_message(
4054
            get_lang('NotAllowed'),
4055
            'error',
4056
            false
4057
        );
4058
4059
        $msg .= '<p class="text-center">
4060
                 <a class="btn btn-default" href="'.$home_url.'">'.get_lang('BackHome').'</a>
4061
                 </p>';
4062
4063
        if (!empty($message)) {
4064
            $msg = $message;
4065
        }
4066
4067
        if (api_is_anonymous()) {
4068
            $form = api_get_not_allowed_login_form();
4069
            $msg .= '<div class="well">';
4070
            $msg .= $form->returnForm();
4071
            $msg .= '</div>';
4072
        }
4073
    }
4074
4075
    $tpl->assign('content', $msg);
4076
    $tpl->display_one_col_template();
4077
    exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

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

Loading history...
4078
}
4079
4080
/**
4081
 * @return FormValidator
4082
 */
4083
function api_get_not_allowed_login_form()
4084
{
4085
    $action = api_get_self().'?'.Security::remove_XSS($_SERVER['QUERY_STRING']);
4086
    $action = str_replace('&amp;', '&', $action);
4087
    Session::write('redirect_after_not_allow_page', $action);
4088
    $action .= '&redirect_after_not_allow_page=1';
4089
4090
    $form = new FormValidator(
4091
        'formLogin',
4092
        'post',
4093
        $action,
4094
        null,
4095
        ['class' => 'form-stacked']
4096
    );
4097
    $params = [
4098
        'placeholder' => get_lang('UserName'),
4099
        'class' => 'col-md-3',
4100
    ];
4101
    if (api_browser_support('autocapitalize')) {
4102
        $params['autocapitalize'] = 'none';
4103
    }
4104
4105
    $form->addElement(
4106
        'text',
4107
        'login',
4108
        null,
4109
        $params
4110
    );
4111
    $form->addElement(
4112
        'password',
4113
        'password',
4114
        null,
4115
        ['placeholder' => get_lang('Password'), 'class' => 'col-md-3']
4116
    ); //new
4117
    $form->addButtonNext(get_lang('LoginEnter'), 'submitAuth');
4118
4119
    return $form;
4120
}
4121
4122
/**
4123
 * Gets a UNIX timestamp from a database (MySQL) datetime format string.
4124
 *
4125
 * @param string $last_post_datetime standard output date in a sql query
4126
 *
4127
 * @return int timestamp
4128
 *
4129
 * @author Toon Van Hoecke <[email protected]>
4130
 *
4131
 * @version October 2003
4132
 * @desc convert sql date to unix timestamp
4133
 */
4134
function convert_sql_date($last_post_datetime)
4135
{
4136
    list($last_post_date, $last_post_time) = explode(' ', $last_post_datetime);
4137
    list($year, $month, $day) = explode('-', $last_post_date);
4138
    list($hour, $min, $sec) = explode(':', $last_post_time);
4139
4140
    return mktime((int) $hour, (int) $min, (int) $sec, (int) $month, (int) $day, (int) $year);
4141
}
4142
4143
/**
4144
 * Gets item visibility from the item_property table.
4145
 *
4146
 * Getting the visibility is done by getting the last updated visibility entry,
4147
 * using the largest session ID found if session 0 and another was found (meaning
4148
 * the only one that is actually from the session, in case there are results from
4149
 * session 0 *AND* session n).
4150
 *
4151
 * @param array  $_course  Course properties array (result of api_get_course_info())
4152
 * @param string $tool     Tool (learnpath, document, etc)
4153
 * @param int    $id       The item ID in the given tool
4154
 * @param int    $session  The session ID (optional)
4155
 * @param int    $user_id
4156
 * @param string $type
4157
 * @param string $group_id
4158
 *
4159
 * @return int -1 on error, 0 if invisible, 1 if visible
4160
 */
4161
function api_get_item_visibility(
4162
    $_course,
4163
    $tool,
4164
    $id,
4165
    $session = 0,
4166
    $user_id = null,
4167
    $type = null,
4168
    $group_id = null
4169
) {
4170
    if (!is_array($_course) || count($_course) == 0 || empty($tool) || empty($id)) {
4171
        return -1;
4172
    }
4173
4174
    $tool = Database::escape_string($tool);
4175
    $id = (int) $id;
4176
    $session = (int) $session;
4177
    $TABLE_ITEMPROPERTY = Database::get_course_table(TABLE_ITEM_PROPERTY);
4178
    $course_id = (int) $_course['real_id'];
4179
4180
    $userCondition = '';
4181
    if (!empty($user_id)) {
4182
        $user_id = (int) $user_id;
4183
        $userCondition = " AND to_user_id = $user_id ";
4184
    }
4185
4186
    $typeCondition = '';
4187
    if (!empty($type)) {
4188
        $type = Database::escape_string($type);
4189
        $typeCondition = " AND lastedit_type = '$type' ";
4190
    }
4191
4192
    $groupCondition = '';
4193
    if (!empty($group_id)) {
4194
        $group_id = (int) $group_id;
4195
        $groupCondition = " AND to_group_id = '$group_id' ";
4196
    }
4197
4198
    $sql = "SELECT visibility
4199
            FROM $TABLE_ITEMPROPERTY
4200
            WHERE
4201
                c_id = $course_id AND
4202
                tool = '$tool' AND
4203
                ref = $id AND
4204
                (session_id = $session OR session_id = 0 OR session_id IS NULL)
4205
                $userCondition $typeCondition $groupCondition
4206
            ORDER BY session_id DESC, lastedit_date DESC
4207
            LIMIT 1";
4208
4209
    $res = Database::query($sql);
4210
    if ($res === false || Database::num_rows($res) == 0) {
4211
        return -1;
4212
    }
4213
    $row = Database::fetch_array($res);
4214
4215
    return (int) $row['visibility'];
4216
}
4217
4218
/**
4219
 * Delete a row in the c_item_property table.
4220
 *
4221
 * @param array  $courseInfo
4222
 * @param string $tool
4223
 * @param int    $itemId
4224
 * @param int    $userId
4225
 * @param int    $groupId    group.iid
4226
 * @param int    $sessionId
4227
 *
4228
 * @return false|null
4229
 */
4230
function api_item_property_delete(
4231
    $courseInfo,
4232
    $tool,
4233
    $itemId,
4234
    $userId,
4235
    $groupId = 0,
4236
    $sessionId = 0
4237
) {
4238
    if (empty($courseInfo)) {
4239
        return false;
4240
    }
4241
4242
    $courseId = (int) $courseInfo['real_id'];
4243
4244
    if (empty($courseId) || empty($tool) || empty($itemId)) {
4245
        return false;
4246
    }
4247
4248
    $table = Database::get_course_table(TABLE_ITEM_PROPERTY);
4249
    $tool = Database::escape_string($tool);
4250
    $itemId = intval($itemId);
4251
    $userId = intval($userId);
4252
    $groupId = intval($groupId);
4253
    $sessionId = intval($sessionId);
4254
4255
    $groupCondition = " AND to_group_id = $groupId ";
4256
    if (empty($groupId)) {
4257
        $groupCondition = " AND (to_group_id is NULL OR to_group_id = 0) ";
4258
    }
4259
4260
    $userCondition = " AND to_user_id = $userId ";
4261
    if (empty($userId)) {
4262
        $userCondition = " AND (to_user_id is NULL OR to_user_id = 0) ";
4263
    }
4264
    $sessionCondition = api_get_session_condition($sessionId, true, false, 'session_id');
4265
    $sql = "DELETE FROM $table
4266
            WHERE
4267
                c_id = $courseId AND
4268
                tool  = '$tool' AND
4269
                ref = $itemId
4270
                $sessionCondition
4271
                $userCondition
4272
                $groupCondition
4273
            ";
4274
4275
    Database::query($sql);
4276
}
4277
4278
/**
4279
 * Updates or adds item properties to the Item_propetry table
4280
 * Tool and lastedit_type are language independant strings (langvars->get_lang!).
4281
 *
4282
 * @param array  $_course        array with course properties
4283
 * @param string $tool           tool id, linked to 'rubrique' of the course tool_list (Warning: language sensitive !!)
4284
 * @param int    $item_id        id of the item itself, linked to key of every tool ('id', ...)
4285
 * @param string $last_edit_type add or update action
4286
 *                               (1) message to be translated (in trad4all) : e.g. DocumentAdded, DocumentUpdated;
4287
 *                               (2) "delete"
4288
 *                               (3) "visible"
4289
 *                               (4) "invisible"
4290
 * @param int    $user_id        id of the editing/adding user
4291
 * @param array  $groupInfo      must include group.iid/group.od
4292
 * @param int    $to_user_id     id of the intended user (always has priority over $to_group_id !), only relevant for $type (1)
4293
 * @param string $start_visible  0000-00-00 00:00:00 format
4294
 * @param string $end_visible    0000-00-00 00:00:00 format
4295
 * @param int    $session_id     The session ID, if any, otherwise will default to 0
4296
 *
4297
 * @return bool false if update fails
4298
 *
4299
 * @author Toon Van Hoecke <[email protected]>, Ghent University
4300
 *
4301
 * @version January 2005
4302
 * @desc update the item_properties table (if entry not exists, insert) of the course
4303
 */
4304
function api_item_property_update(
4305
    $_course,
4306
    $tool,
4307
    $item_id,
4308
    $last_edit_type,
4309
    $user_id,
4310
    $groupInfo = [],
4311
    $to_user_id = null,
4312
    $start_visible = '',
4313
    $end_visible = '',
4314
    $session_id = 0
4315
) {
4316
    if (empty($_course)) {
4317
        return false;
4318
    }
4319
4320
    $course_id = $_course['real_id'];
4321
4322
    if (empty($course_id)) {
4323
        return false;
4324
    }
4325
4326
    $to_group_id = 0;
4327
    if (!empty($groupInfo) && isset($groupInfo['iid'])) {
4328
        $to_group_id = (int) $groupInfo['iid'];
4329
    }
4330
4331
    $em = Database::getManager();
4332
4333
    // Definition of variables.
4334
    $tool = Database::escape_string($tool);
4335
    $item_id = (int) $item_id;
4336
    $lastEditTypeNoFilter = $last_edit_type;
4337
    $last_edit_type = Database::escape_string($last_edit_type);
4338
    $user_id = (int) $user_id;
4339
4340
    $startVisible = "NULL";
4341
    if (!empty($start_visible)) {
4342
        $start_visible = Database::escape_string($start_visible);
4343
        $startVisible = "'$start_visible'";
4344
    }
4345
4346
    $endVisible = "NULL";
4347
    if (!empty($end_visible)) {
4348
        $end_visible = Database::escape_string($end_visible);
4349
        $endVisible = "'$end_visible'";
4350
    }
4351
4352
    $to_filter = '';
4353
    $time = api_get_utc_datetime();
4354
4355
    if (!empty($session_id)) {
4356
        $session_id = (int) $session_id;
4357
    } else {
4358
        $session_id = api_get_session_id();
4359
    }
4360
4361
    // Definition of tables.
4362
    $tableItemProperty = Database::get_course_table(TABLE_ITEM_PROPERTY);
4363
4364
    if ($to_user_id <= 0) {
4365
        $to_user_id = null; // No to_user_id set
4366
    }
4367
4368
    if (!is_null($to_user_id)) {
4369
        // $to_user_id has more priority than $to_group_id
4370
        $to_user_id = (int) $to_user_id;
4371
        $to_field = 'to_user_id';
4372
        $to_value = $to_user_id;
4373
    } else {
4374
        // $to_user_id is not set.
4375
        $to_field = 'to_group_id';
4376
        $to_value = $to_group_id;
4377
    }
4378
4379
    $toValueCondition = empty($to_value) ? 'NULL' : "'$to_value'";
4380
    // Set filters for $to_user_id and $to_group_id, with priority for $to_user_id
4381
    $condition_session = " AND session_id = $session_id ";
4382
    if (empty($session_id)) {
4383
        $condition_session = ' AND (session_id = 0 OR session_id IS NULL) ';
4384
    }
4385
4386
    $filter = " c_id = $course_id AND tool = '$tool' AND ref = $item_id $condition_session ";
4387
4388
    // Check whether $to_user_id and $to_group_id are passed in the function call.
4389
    // If both are not passed (both are null) then it is a message for everybody and $to_group_id should be 0 !
4390
    if (is_null($to_user_id) && is_null($to_group_id)) {
4391
        $to_group_id = 0;
4392
    }
4393
4394
    if (!is_null($to_user_id)) {
4395
        // Set filter to intended user.
4396
        $to_filter = " AND to_user_id = $to_user_id $condition_session";
4397
    } else {
4398
        // Set filter to intended group.
4399
        if (($to_group_id != 0) && $to_group_id == strval(intval($to_group_id))) {
4400
            $to_filter = " AND to_group_id = $to_group_id $condition_session";
4401
        }
4402
    }
4403
4404
    // Adding filter if set.
4405
    $filter .= $to_filter;
4406
4407
    // Update if possible
4408
    $set_type = '';
4409
4410
    switch ($lastEditTypeNoFilter) {
4411
        case 'delete':
4412
            // delete = make item only visible for the platform admin.
4413
            $visibility = '2';
4414
            if (!empty($session_id)) {
4415
                // Check whether session id already exist into item_properties for updating visibility or add it.
4416
                $sql = "SELECT session_id FROM $tableItemProperty
4417
                        WHERE
4418
                            c_id = $course_id AND
4419
                            tool = '$tool' AND
4420
                            ref = $item_id AND
4421
                            session_id = $session_id";
4422
                $rs = Database::query($sql);
4423
                if (Database::num_rows($rs) > 0) {
4424
                    $sql = "UPDATE $tableItemProperty
4425
                            SET lastedit_type       = '".str_replace('_', '', ucwords($tool))."Deleted',
4426
                                lastedit_date       = '$time',
4427
                                lastedit_user_id    = $user_id,
4428
                                visibility          = $visibility,
4429
                                session_id          = $session_id $set_type
4430
                            WHERE $filter";
4431
                    $result = Database::query($sql);
4432
                } else {
4433
                    $sql = "INSERT INTO $tableItemProperty (c_id, tool, ref, insert_date, insert_user_id, lastedit_date, lastedit_type, lastedit_user_id, $to_field, visibility, start_visible, end_visible, session_id)
4434
                            VALUES ($course_id, '$tool',$item_id, '$time', $user_id, '$time', '$last_edit_type',$user_id, $toValueCondition, $visibility, $startVisible, $endVisible, $session_id)";
4435
                    $result = Database::query($sql);
4436
                    $id = Database::insert_id();
4437
                    if ($id) {
4438
                        $sql = "UPDATE $tableItemProperty SET id = iid WHERE iid = $id";
4439
                        Database::query($sql);
4440
                    }
4441
                }
4442
            } else {
4443
                $sql = "UPDATE $tableItemProperty
4444
                        SET
4445
                            lastedit_type='".str_replace('_', '', ucwords($tool))."Deleted',
4446
                            lastedit_date='$time',
4447
                            lastedit_user_id = $user_id,
4448
                            visibility = $visibility $set_type
4449
                        WHERE $filter";
4450
                $result = Database::query($sql);
4451
            }
4452
            break;
4453
        case 'visible': // Change item to visible.
4454
            $visibility = '1';
4455
            if (!empty($session_id)) {
4456
                // Check whether session id already exist into item_properties for updating visibility or add it.
4457
                $sql = "SELECT session_id FROM $tableItemProperty
4458
                        WHERE
4459
                            c_id = $course_id AND
4460
                            tool = '$tool' AND
4461
                            ref = $item_id AND
4462
                            session_id = $session_id";
4463
                $rs = Database::query($sql);
4464
                if (Database::num_rows($rs) > 0) {
4465
                    $sql = "UPDATE $tableItemProperty
4466
                            SET
4467
                                lastedit_type='".str_replace('_', '', ucwords($tool))."Visible',
4468
                                lastedit_date='$time',
4469
                                lastedit_user_id = $user_id,
4470
                                visibility = $visibility,
4471
                                session_id = $session_id $set_type
4472
                            WHERE $filter";
4473
                    $result = Database::query($sql);
4474
                } else {
4475
                    $sql = "INSERT INTO $tableItemProperty (c_id, tool, ref, insert_date, insert_user_id, lastedit_date, lastedit_type, lastedit_user_id, $to_field, visibility, start_visible, end_visible, session_id)
4476
                            VALUES ($course_id, '$tool', $item_id, '$time', $user_id, '$time', '$last_edit_type', $user_id, $toValueCondition, $visibility, $startVisible, $endVisible, $session_id)";
4477
                    $result = Database::query($sql);
4478
                    $id = Database::insert_id();
4479
                    if ($id) {
4480
                        $sql = "UPDATE $tableItemProperty SET id = iid WHERE iid = $id";
4481
                        Database::query($sql);
4482
                    }
4483
                }
4484
            } else {
4485
                $sql = "UPDATE $tableItemProperty
4486
                        SET
4487
                            lastedit_type='".str_replace('_', '', ucwords($tool))."Visible',
4488
                            lastedit_date='$time',
4489
                            lastedit_user_id = $user_id,
4490
                            visibility = $visibility $set_type
4491
                        WHERE $filter";
4492
                $result = Database::query($sql);
4493
            }
4494
            break;
4495
        case 'invisible': // Change item to invisible.
4496
            $visibility = '0';
4497
            if (!empty($session_id)) {
4498
                // Check whether session id already exist into item_properties for updating visibility or add it
4499
                $sql = "SELECT session_id FROM $tableItemProperty
4500
                        WHERE
4501
                            c_id = $course_id AND
4502
                            tool = '$tool' AND
4503
                            ref = $item_id AND
4504
                            session_id = $session_id";
4505
                $rs = Database::query($sql);
4506
                if (Database::num_rows($rs) > 0) {
4507
                    $sql = "UPDATE $tableItemProperty
4508
                            SET
4509
                                lastedit_type = '".str_replace('_', '', ucwords($tool))."Invisible',
4510
                                lastedit_date = '$time',
4511
                                lastedit_user_id = $user_id,
4512
                                visibility = $visibility,
4513
                                session_id = $session_id $set_type
4514
                            WHERE $filter";
4515
                    $result = Database::query($sql);
4516
                } else {
4517
                    $sql = "INSERT INTO $tableItemProperty (c_id, tool, ref, insert_date, insert_user_id, lastedit_date, lastedit_type, lastedit_user_id,$to_field, visibility, start_visible, end_visible, session_id)
4518
                            VALUES ($course_id, '$tool', $item_id, '$time', $user_id, '$time', '$last_edit_type', $user_id, $toValueCondition, $visibility, $startVisible, $endVisible, $session_id)";
4519
                    $result = Database::query($sql);
4520
                    $id = Database::insert_id();
4521
                    if ($id) {
4522
                        $sql = "UPDATE $tableItemProperty SET id = iid WHERE iid = $id";
4523
                        Database::query($sql);
4524
                    }
4525
                }
4526
            } else {
4527
                $sql = "UPDATE $tableItemProperty
4528
                        SET
4529
                            lastedit_type = '".str_replace('_', '', ucwords($tool))."Invisible',
4530
                            lastedit_date = '$time',
4531
                            lastedit_user_id = $user_id,
4532
                            visibility = $visibility $set_type
4533
                        WHERE $filter";
4534
                $result = Database::query($sql);
4535
            }
4536
            break;
4537
        default: // The item will be added or updated.
4538
            $set_type = ", lastedit_type = '$last_edit_type' ";
4539
            $visibility = '1';
4540
            //$filter .= $to_filter; already added
4541
            $sql = "UPDATE $tableItemProperty
4542
                    SET
4543
                      lastedit_date = '$time',
4544
                      lastedit_user_id = $user_id $set_type
4545
                    WHERE $filter";
4546
            $result = Database::query($sql);
4547
    }
4548
4549
    // Insert if no entries are found (can only happen in case of $last_edit_type switch is 'default').
4550
    if ($result == false || Database::affected_rows($result) == 0) {
4551
        $objCourse = $em->find('ChamiloCoreBundle:Course', intval($course_id));
4552
        $objTime = new DateTime('now', new DateTimeZone('UTC'));
4553
        $objUser = api_get_user_entity($user_id);
4554
        if (empty($objUser)) {
4555
            // Use anonymous
4556
            $user_id = api_get_anonymous_id();
4557
            $objUser = api_get_user_entity($user_id);
4558
        }
4559
4560
        $objGroup = null;
4561
        if (!empty($to_group_id)) {
4562
            $objGroup = $em->find('ChamiloCourseBundle:CGroupInfo', $to_group_id);
4563
        }
4564
4565
        $objToUser = api_get_user_entity($to_user_id);
4566
        $objSession = $em->find('ChamiloCoreBundle:Session', intval($session_id));
4567
4568
        $startVisibleDate = !empty($start_visible) ? new DateTime($start_visible, new DateTimeZone('UTC')) : null;
4569
        $endVisibleDate = !empty($endVisibleDate) ? new DateTime($endVisibleDate, new DateTimeZone('UTC')) : null;
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $endVisibleDate seems to never exist and therefore empty should always be true.
Loading history...
4570
4571
        $cItemProperty = new CItemProperty($objCourse);
4572
        $cItemProperty
4573
            ->setTool($tool)
4574
            ->setRef($item_id)
4575
            ->setInsertDate($objTime)
4576
            ->setInsertUser($objUser)
4577
            ->setLasteditDate($objTime)
4578
            ->setLasteditType($last_edit_type)
4579
            ->setGroup($objGroup)
4580
            ->setToUser($objToUser)
4581
            ->setVisibility($visibility)
4582
            ->setStartVisible($startVisibleDate)
4583
            ->setEndVisible($endVisibleDate)
4584
            ->setSession($objSession);
4585
4586
        $em->persist($cItemProperty);
4587
        $em->flush();
4588
4589
        $id = $cItemProperty->getIid();
4590
4591
        if ($id) {
4592
            $cItemProperty->setId($id);
4593
            $em->merge($cItemProperty);
4594
            $em->flush();
4595
4596
            return false;
4597
        }
4598
    }
4599
4600
    return true;
4601
}
4602
4603
/**
4604
 * Gets item property by tool.
4605
 *
4606
 * @param string $tool        tool name, linked to 'rubrique' of the course tool_list (Warning: language sensitive !!)
4607
 * @param string $course_code
4608
 * @param int    $session_id
4609
 *
4610
 * @return array All fields from c_item_property (all rows found) or empty array
4611
 */
4612
function api_get_item_property_by_tool($tool, $course_code, $session_id = null)
4613
{
4614
    $course_info = api_get_course_info($course_code);
4615
    $tool = Database::escape_string($tool);
4616
4617
    // Definition of tables.
4618
    $item_property_table = Database::get_course_table(TABLE_ITEM_PROPERTY);
4619
    $session_id = (int) $session_id;
4620
    $session_condition = ' AND session_id = '.$session_id;
4621
    if (empty($session_id)) {
4622
        $session_condition = " AND (session_id = 0 OR session_id IS NULL) ";
4623
    }
4624
    $course_id = $course_info['real_id'];
4625
4626
    $sql = "SELECT * FROM $item_property_table
4627
            WHERE
4628
                c_id = $course_id AND
4629
                tool = '$tool'
4630
                $session_condition ";
4631
    $rs = Database::query($sql);
4632
    $list = [];
4633
    if (Database::num_rows($rs) > 0) {
4634
        while ($row = Database::fetch_array($rs, 'ASSOC')) {
4635
            $list[] = $row;
4636
        }
4637
    }
4638
4639
    return $list;
4640
}
4641
4642
/**
4643
 * Gets item property by tool and user.
4644
 *
4645
 * @param int $userId
4646
 * @param int $tool
4647
 * @param int $courseId
4648
 * @param int $session_id
4649
 *
4650
 * @return array
4651
 */
4652
function api_get_item_property_list_by_tool_by_user(
4653
    $userId,
4654
    $tool,
4655
    $courseId,
4656
    $session_id = 0
4657
) {
4658
    $userId = intval($userId);
4659
    $tool = Database::escape_string($tool);
4660
    $session_id = intval($session_id);
4661
    $courseId = intval($courseId);
4662
4663
    // Definition of tables.
4664
    $item_property_table = Database::get_course_table(TABLE_ITEM_PROPERTY);
4665
    $session_condition = ' AND session_id = '.$session_id;
4666
    if (empty($session_id)) {
4667
        $session_condition = " AND (session_id = 0 OR session_id IS NULL) ";
4668
    }
4669
    $sql = "SELECT * FROM $item_property_table
4670
            WHERE
4671
                insert_user_id = $userId AND
4672
                c_id = $courseId AND
4673
                tool = '$tool'
4674
                $session_condition ";
4675
4676
    $rs = Database::query($sql);
4677
    $list = [];
4678
    if (Database::num_rows($rs) > 0) {
4679
        while ($row = Database::fetch_array($rs, 'ASSOC')) {
4680
            $list[] = $row;
4681
        }
4682
    }
4683
4684
    return $list;
4685
}
4686
4687
/**
4688
 * Gets item property id from tool of a course.
4689
 *
4690
 * @param string $course_code course code
4691
 * @param string $tool        tool name, linked to 'rubrique' of the course tool_list (Warning: language sensitive !!)
4692
 * @param int    $ref         id of the item itself, linked to key of every tool ('id', ...), "*" = all items of the tool
4693
 * @param int    $sessionId   Session ID (optional)
4694
 *
4695
 * @return int
4696
 */
4697
function api_get_item_property_id($course_code, $tool, $ref, $sessionId = 0)
4698
{
4699
    $course_info = api_get_course_info($course_code);
4700
    $tool = Database::escape_string($tool);
4701
    $ref = (int) $ref;
4702
4703
    // Definition of tables.
4704
    $tableItemProperty = Database::get_course_table(TABLE_ITEM_PROPERTY);
4705
    $course_id = $course_info['real_id'];
4706
    $sessionId = (int) $sessionId;
4707
    $sessionCondition = " AND session_id = $sessionId ";
4708
    if (empty($sessionId)) {
4709
        $sessionCondition = ' AND (session_id = 0 OR session_id IS NULL) ';
4710
    }
4711
    $sql = "SELECT id FROM $tableItemProperty
4712
            WHERE
4713
                c_id = $course_id AND
4714
                tool = '$tool' AND
4715
                ref = $ref
4716
                $sessionCondition";
4717
    $rs = Database::query($sql);
4718
    $item_property_id = '';
4719
    if (Database::num_rows($rs) > 0) {
4720
        $row = Database::fetch_array($rs);
4721
        $item_property_id = $row['id'];
4722
    }
4723
4724
    return $item_property_id;
4725
}
4726
4727
/**
4728
 * Inserts a record in the track_e_item_property table (No update).
4729
 *
4730
 * @param string $tool
4731
 * @param int    $ref
4732
 * @param string $title
4733
 * @param string $content
4734
 * @param int    $progress
4735
 *
4736
 * @return bool|int
4737
 */
4738
function api_track_item_property_update($tool, $ref, $title, $content, $progress)
4739
{
4740
    $tbl_stats_item_property = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ITEM_PROPERTY);
4741
    $course_id = api_get_course_int_id(); //numeric
4742
    $course_code = api_get_course_id(); //alphanumeric
4743
    $item_property_id = api_get_item_property_id($course_code, $tool, $ref);
4744
    if (!empty($item_property_id)) {
4745
        $sql = "INSERT IGNORE INTO $tbl_stats_item_property SET
4746
                course_id           = '$course_id',
4747
                item_property_id    = '$item_property_id',
4748
                title               = '".Database::escape_string($title)."',
4749
                content             = '".Database::escape_string($content)."',
4750
                progress            = '".intval($progress)."',
4751
                lastedit_date       = '".api_get_utc_datetime()."',
4752
                lastedit_user_id    = '".api_get_user_id()."',
4753
                session_id          = '".api_get_session_id()."'";
4754
        $result = Database::query($sql);
4755
        $affected_rows = Database::affected_rows($result);
4756
4757
        return $affected_rows;
4758
    }
4759
4760
    return false;
4761
}
4762
4763
/**
4764
 * @param string $tool
4765
 * @param int    $ref
4766
 *
4767
 * @return array|resource
4768
 */
4769
function api_get_track_item_property_history($tool, $ref)
4770
{
4771
    $tbl_stats_item_property = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ITEM_PROPERTY);
4772
    $course_id = api_get_course_int_id(); //numeric
4773
    $course_code = api_get_course_id(); //alphanumeric
4774
    $item_property_id = api_get_item_property_id($course_code, $tool, $ref);
4775
    $sql = "SELECT * FROM $tbl_stats_item_property
4776
            WHERE item_property_id = $item_property_id AND course_id = $course_id
4777
            ORDER BY lastedit_date DESC";
4778
    $result = Database::query($sql);
4779
    if ($result === false or $result === null) {
4780
        $result = [];
4781
    } else {
4782
        $result = Database::store_result($result, 'ASSOC');
4783
    }
4784
4785
    return $result;
4786
}
4787
4788
/**
4789
 * Gets item property data from tool of a course id.
4790
 *
4791
 * @param int    $course_id
4792
 * @param string $tool       tool name, linked to 'rubrique' of the course tool_list (Warning: language sensitive !!)
4793
 * @param int    $ref        id of the item itself, linked to key of every tool ('id', ...), "*" = all items of the tool
4794
 * @param int    $session_id
4795
 * @param int    $groupId
4796
 *
4797
 * @return array with all fields from c_item_property, empty array if not found or false if course could not be found
4798
 */
4799
function api_get_item_property_info($course_id, $tool, $ref, $session_id = 0, $groupId = 0)
4800
{
4801
    $courseInfo = api_get_course_info_by_id($course_id);
4802
4803
    if (empty($courseInfo)) {
4804
        return false;
4805
    }
4806
4807
    $tool = Database::escape_string($tool);
4808
    $course_id = $courseInfo['real_id'];
4809
    $ref = (int) $ref;
4810
    $session_id = (int) $session_id;
4811
4812
    $sessionCondition = " session_id = $session_id";
4813
    if (empty($session_id)) {
4814
        $sessionCondition = ' (session_id = 0 OR session_id IS NULL) ';
4815
    }
4816
4817
    // Definition of tables.
4818
    $table = Database::get_course_table(TABLE_ITEM_PROPERTY);
4819
4820
    $sql = "SELECT * FROM $table
4821
            WHERE
4822
                c_id = $course_id AND
4823
                tool = '$tool' AND
4824
                ref = $ref AND
4825
                $sessionCondition ";
4826
4827
    if (!empty($groupId)) {
4828
        $groupId = (int) $groupId;
4829
        $sql .= " AND to_group_id = $groupId ";
4830
    }
4831
4832
    $rs = Database::query($sql);
4833
    $row = [];
4834
    if (Database::num_rows($rs) > 0) {
4835
        $row = Database::fetch_array($rs, 'ASSOC');
4836
    }
4837
4838
    return $row;
4839
}
4840
4841
/**
4842
 * Displays a combo box so the user can select his/her preferred language.
4843
 *
4844
 * @param string The desired name= value for the select
4845
 * @param bool Whether we use the JQuery Chozen library or not
4846
 * (in some cases, like the indexing language picker, it can alter the presentation)
4847
 *
4848
 * @return string
4849
 */
4850
function api_get_languages_combo($name = 'language')
4851
{
4852
    $ret = '';
4853
    $platformLanguage = api_get_setting('platformLanguage');
4854
4855
    // Retrieve a complete list of all the languages.
4856
    $language_list = api_get_languages();
4857
4858
    if (count($language_list['name']) < 2) {
4859
        return $ret;
4860
    }
4861
4862
    // The the current language of the user so that his/her language occurs as selected in the dropdown menu.
4863
    if (isset($_SESSION['user_language_choice'])) {
4864
        $default = $_SESSION['user_language_choice'];
4865
    } else {
4866
        $default = $platformLanguage;
4867
    }
4868
4869
    $languages = $language_list['name'];
4870
    $folder = $language_list['folder'];
4871
4872
    $ret .= '<select name="'.$name.'" id="language_chosen" class="selectpicker form-control">';
4873
    foreach ($languages as $key => $value) {
4874
        if ($folder[$key] == $default) {
4875
            $selected = ' selected="selected"';
4876
        } else {
4877
            $selected = '';
4878
        }
4879
        $ret .= sprintf('<option value=%s" %s>%s</option>', $folder[$key], $selected, $value);
4880
    }
4881
    $ret .= '</select>';
4882
4883
    return $ret;
4884
}
4885
4886
/**
4887
 * Displays a form (drop down menu) so the user can select his/her preferred language.
4888
 * The form works with or without javascript.
4889
 *
4890
 * @param  bool Hide form if only one language available (defaults to false = show the box anyway)
4891
 * @param bool $showAsButton
4892
 *
4893
 * @return string|null Display the box directly
4894
 */
4895
function api_display_language_form($hide_if_no_choice = false, $showAsButton = false)
4896
{
4897
    // Retrieve a complete list of all the languages.
4898
    $language_list = api_get_languages();
4899
    if (count($language_list['name']) <= 1 && $hide_if_no_choice) {
4900
        return null; //don't show any form
4901
    }
4902
4903
    // The the current language of the user so that his/her language occurs as selected in the dropdown menu.
4904
    if (isset($_SESSION['user_language_choice'])) {
4905
        $user_selected_language = $_SESSION['user_language_choice'];
4906
    }
4907
    if (empty($user_selected_language)) {
4908
        $user_selected_language = api_get_setting('platformLanguage');
4909
    }
4910
4911
    $currentLanguageId = api_get_language_id($user_selected_language);
4912
    $currentLanguageInfo = api_get_language_info($currentLanguageId);
4913
4914
    $countryCode = languageCodeToCountryIsoCodeForFlags($currentLanguageInfo['isocode']);
4915
    $url = api_get_self();
4916
    if ($showAsButton) {
4917
        $html = '<div class="btn-group">
4918
              <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown">
4919
                <span class="flag-icon flag-icon-'.$countryCode.'"></span>
4920
                '.$currentLanguageInfo['original_name'].'
4921
                <span class="caret">
4922
                </span>
4923
              </button>';
4924
    } else {
4925
        $html = '
4926
            <a href="'.$url.'" class="dropdown-toggle" data-toggle="dropdown" role="button">
4927
                <span class="flag-icon flag-icon-'.$countryCode.'"></span>
4928
                '.$currentLanguageInfo['original_name'].'
4929
                <span class="caret"></span>
4930
            </a>
4931
            ';
4932
    }
4933
4934
    $html .= '<ul class="dropdown-menu" role="menu">';
4935
    foreach ($language_list['all'] as $key => $data) {
4936
        $urlLink = $url.'?language='.$data['english_name'];
4937
        $html .= '<li><a href="'.$urlLink.'"><span class="flag-icon flag-icon-'.languageCodeToCountryIsoCodeForFlags($data['isocode']).'"></span> '.$data['original_name'].'</a></li>';
4938
    }
4939
    $html .= '</ul>';
4940
4941
    if ($showAsButton) {
4942
        $html .= '</div>';
4943
    }
4944
4945
    return $html;
4946
}
4947
4948
/**
4949
 * Return a country code based on a language in order to show a country flag.
4950
 * Note: Showing a "language" flag is arguably a bad idea, as several countries
4951
 * share languages and the right flag cannot be shown for all of them.
4952
 *
4953
 * @param string $languageIsoCode
4954
 *
4955
 * @return string
4956
 */
4957
function languageCodeToCountryIsoCodeForFlags($languageIsoCode)
4958
{
4959
    $allow = api_get_configuration_value('language_flags_by_country');
4960
4961
    // @todo save in DB
4962
    switch ($languageIsoCode) {
4963
        case 'ar':
4964
            $country = 'ae';
4965
            break;
4966
        case 'bs':
4967
            $country = 'ba';
4968
            break;
4969
        case 'ca':
4970
            $country = 'es';
4971
            if ($allow) {
4972
                $country = 'catalan';
4973
            }
4974
            break;
4975
        case 'cs':
4976
            $country = 'cz';
4977
            break;
4978
        case 'da':
4979
            $country = 'dk';
4980
            break;
4981
        case 'el':
4982
            $country = 'ae';
4983
            break;
4984
        case 'en':
4985
            $country = 'gb';
4986
            break;
4987
        case 'eu': // Euskera
4988
            $country = 'es';
4989
            if ($allow) {
4990
                $country = 'basque';
4991
            }
4992
            break;
4993
        case 'gl': // galego
4994
            $country = 'es';
4995
            if ($allow) {
4996
                $country = 'galician';
4997
            }
4998
            break;
4999
        case 'he':
5000
            $country = 'il';
5001
            break;
5002
        case 'ja':
5003
            $country = 'jp';
5004
            break;
5005
        case 'ka':
5006
            $country = 'ge';
5007
            break;
5008
        case 'ko':
5009
            $country = 'kr';
5010
            break;
5011
        case 'ms':
5012
            $country = 'my';
5013
            break;
5014
        case 'pt-BR':
5015
            $country = 'br';
5016
            break;
5017
        case 'qu':
5018
            $country = 'pe';
5019
            break;
5020
        case 'sl':
5021
            $country = 'si';
5022
            break;
5023
        case 'sv':
5024
            $country = 'se';
5025
            break;
5026
        case 'uk': // Ukraine
5027
            $country = 'ua';
5028
            break;
5029
        case 'zh-TW':
5030
        case 'zh':
5031
            $country = 'cn';
5032
            break;
5033
        default:
5034
            $country = $languageIsoCode;
5035
            break;
5036
    }
5037
    $country = strtolower($country);
5038
5039
    return $country;
5040
}
5041
5042
/**
5043
 * Returns a list of all the languages that are made available by the admin.
5044
 *
5045
 * @return array An array with all languages. Structure of the array is
5046
 *               array['name'] = An array with the name of every language
5047
 *               array['folder'] = An array with the corresponding names of the language-folders in the filesystem
5048
 */
5049
function api_get_languages()
5050
{
5051
    $tbl_language = Database::get_main_table(TABLE_MAIN_LANGUAGE);
5052
    $sql = "SELECT * FROM $tbl_language WHERE available='1'
5053
            ORDER BY original_name ASC";
5054
    $result = Database::query($sql);
5055
    $language_list = [];
5056
    while ($row = Database::fetch_array($result)) {
5057
        $language_list['name'][] = $row['original_name'];
5058
        $language_list['folder'][] = $row['dokeos_folder'];
5059
        $language_list['all'][] = $row;
5060
    }
5061
5062
    return $language_list;
5063
}
5064
5065
/**
5066
 * Returns a list of all the languages that are made available by the admin.
5067
 *
5068
 * @return array
5069
 */
5070
function api_get_languages_to_array()
5071
{
5072
    $tbl_language = Database::get_main_table(TABLE_MAIN_LANGUAGE);
5073
    $sql = "SELECT * FROM $tbl_language
5074
            WHERE available='1' ORDER BY original_name ASC";
5075
    $result = Database::query($sql);
5076
    $languages = [];
5077
    while ($row = Database::fetch_array($result)) {
5078
        $languages[$row['dokeos_folder']] = $row['original_name'];
5079
    }
5080
5081
    return $languages;
5082
}
5083
5084
/**
5085
 * Returns the id (the database id) of a language.
5086
 *
5087
 * @param   string  language name (the corresponding name of the language-folder in the filesystem)
5088
 *
5089
 * @return int id of the language
5090
 */
5091
function api_get_language_id($language)
5092
{
5093
    if (empty($language)) {
5094
        return null;
5095
    }
5096
5097
    static $staticResult;
5098
5099
    if (isset($staticResult[$language])) {
5100
        return $staticResult[$language];
5101
    } else {
5102
        $table = Database::get_main_table(TABLE_MAIN_LANGUAGE);
5103
        $language = Database::escape_string($language);
5104
        $sql = "SELECT id FROM $table
5105
                WHERE dokeos_folder = '$language' LIMIT 1";
5106
        $result = Database::query($sql);
5107
        $row = Database::fetch_array($result);
5108
5109
        $staticResult[$language] = $row['id'];
5110
5111
        return $row['id'];
5112
    }
5113
}
5114
5115
/**
5116
 * Gets language of the requested type for the current user. Types are :
5117
 * user_profil_lang : profile language of current user
5118
 * user_select_lang : language selected by user at login
5119
 * course_lang : language of the current course
5120
 * platform_lang : default platform language.
5121
 *
5122
 * @param string $lang_type
5123
 *
5124
 * @return string
5125
 */
5126
function api_get_language_from_type($lang_type)
5127
{
5128
    $return = false;
5129
    switch ($lang_type) {
5130
        case 'platform_lang':
5131
            $temp_lang = api_get_setting('platformLanguage');
5132
            if (!empty($temp_lang)) {
5133
                $return = $temp_lang;
5134
            }
5135
            break;
5136
        case 'user_profil_lang':
5137
            $_user = api_get_user_info();
5138
            if (isset($_user['language']) && !empty($_user['language'])) {
5139
                $return = $_user['language'];
5140
            }
5141
            break;
5142
        case 'user_selected_lang':
5143
            if (isset($_SESSION['user_language_choice']) && !empty($_SESSION['user_language_choice'])) {
5144
                $return = $_SESSION['user_language_choice'];
5145
            }
5146
            break;
5147
        case 'course_lang':
5148
            global $_course;
5149
            $cidReq = null;
5150
            if (empty($_course)) {
5151
                // Code modified because the local.inc.php file it's declarated after this work
5152
                // causing the function api_get_course_info() returns a null value
5153
                $cidReq = isset($_GET["cidReq"]) ? Database::escape_string($_GET["cidReq"]) : null;
5154
                $cDir = (!empty($_GET['cDir']) ? $_GET['cDir'] : null);
5155
                if (empty($cidReq) && !empty($cDir)) {
5156
                    $c = CourseManager::getCourseCodeFromDirectory($cDir);
5157
                    if ($c) {
5158
                        $cidReq = $c;
5159
                    }
5160
                }
5161
            }
5162
            $_course = api_get_course_info($cidReq);
5163
            if (isset($_course['language']) && !empty($_course['language'])) {
5164
                $return = $_course['language'];
5165
                $showCourseInUserLanguage = api_get_course_setting('show_course_in_user_language');
5166
                if ($showCourseInUserLanguage == 1) {
5167
                    $userInfo = api_get_user_info();
5168
                    if (isset($userInfo['language'])) {
5169
                        $return = $userInfo['language'];
5170
                    }
5171
                }
5172
            }
5173
            break;
5174
        default:
5175
            $return = false;
5176
            break;
5177
    }
5178
5179
    return $return;
5180
}
5181
5182
/**
5183
 * Get the language information by its id.
5184
 *
5185
 * @param int $languageId
5186
 *
5187
 * @throws Exception
5188
 *
5189
 * @return array
5190
 */
5191
function api_get_language_info($languageId)
5192
{
5193
    if (empty($languageId)) {
5194
        return [];
5195
    }
5196
5197
    $language = Database::getManager()
5198
        ->find('ChamiloCoreBundle:Language', $languageId);
5199
5200
    if (!$language) {
5201
        return [];
5202
    }
5203
5204
    return [
5205
        'id' => $language->getId(),
5206
        'original_name' => $language->getOriginalName(),
5207
        'english_name' => $language->getEnglishName(),
5208
        'isocode' => $language->getIsocode(),
5209
        'dokeos_folder' => $language->getDokeosFolder(),
5210
        'available' => $language->getAvailable(),
5211
        'parent_id' => $language->getParent() ? $language->getParent()->getId() : null,
5212
    ];
5213
}
5214
5215
/**
5216
 * Returns the name of the visual (CSS) theme to be applied on the current page.
5217
 * The returned name depends on the platform, course or user -wide settings.
5218
 *
5219
 * @return string The visual theme's name, it is the name of a folder inside web/css/themes
5220
 */
5221
function api_get_visual_theme()
5222
{
5223
    static $visual_theme;
5224
5225
    // If call from CLI it should be reload.
5226
    if ('cli' === PHP_SAPI) {
5227
        $visual_theme = null;
5228
    }
5229
5230
    if (!isset($visual_theme)) {
5231
        $cacheAvailable = api_get_configuration_value('apc');
5232
        $userThemeAvailable = api_get_setting('user_selected_theme') == 'true';
5233
        $courseThemeAvailable = api_get_setting('allow_course_theme') == 'true';
5234
        // only use a shared cache if no user-based or course-based theme is allowed
5235
        $useCache = ($cacheAvailable && !$userThemeAvailable && !$courseThemeAvailable);
5236
        $apcVar = '';
5237
        if ($useCache) {
5238
            $apcVar = api_get_configuration_value('apc_prefix').'my_campus_visual_theme';
5239
            if (apcu_exists($apcVar)) {
5240
                return apcu_fetch($apcVar);
5241
            }
5242
        }
5243
5244
        $accessUrlId = api_get_current_access_url_id();
5245
        if ('cli' === PHP_SAPI) {
5246
            $accessUrlId = api_get_configuration_value('access_url');
5247
        }
5248
5249
        // Get style directly from DB
5250
        $styleFromDatabase = api_get_settings_params_simple(
5251
            [
5252
                'variable = ? AND access_url = ?' => [
5253
                    'stylesheets',
5254
                    $accessUrlId,
5255
                ],
5256
            ]
5257
        );
5258
        if ($styleFromDatabase) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $styleFromDatabase of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

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

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

Loading history...
5259
            $platform_theme = $styleFromDatabase['selected_value'];
5260
        } else {
5261
            $platform_theme = api_get_setting('stylesheets');
5262
        }
5263
5264
        // Platform's theme.
5265
        $visual_theme = $platform_theme;
5266
        if ($userThemeAvailable) {
5267
            $user_info = api_get_user_info();
5268
            if (isset($user_info['theme'])) {
5269
                $user_theme = $user_info['theme'];
5270
5271
                if (!empty($user_theme)) {
5272
                    $visual_theme = $user_theme;
5273
                    // User's theme.
5274
                }
5275
            }
5276
        }
5277
5278
        $course_id = api_get_course_id();
5279
        if (!empty($course_id)) {
5280
            if ($courseThemeAvailable) {
5281
                $course_theme = api_get_course_setting('course_theme', api_get_course_info());
5282
5283
                if (!empty($course_theme) && $course_theme != -1) {
5284
                    if (!empty($course_theme)) {
5285
                        // Course's theme.
5286
                        $visual_theme = $course_theme;
5287
                    }
5288
                }
5289
5290
                $allow_lp_theme = api_get_course_setting('allow_learning_path_theme');
5291
                if ($allow_lp_theme == 1) {
5292
                    global $lp_theme_css, $lp_theme_config;
5293
                    // These variables come from the file lp_controller.php.
5294
                    if (!$lp_theme_config) {
5295
                        if (!empty($lp_theme_css)) {
5296
                            // LP's theme.
5297
                            $visual_theme = $lp_theme_css;
5298
                        }
5299
                    }
5300
                }
5301
            }
5302
        }
5303
5304
        if (empty($visual_theme)) {
5305
            $visual_theme = 'chamilo';
5306
        }
5307
5308
        global $lp_theme_log;
5309
        if ($lp_theme_log) {
5310
            $visual_theme = $platform_theme;
5311
        }
5312
        if ($useCache) {
5313
            apcu_store($apcVar, $visual_theme, 120);
5314
        }
5315
    }
5316
5317
    return $visual_theme;
5318
}
5319
5320
/**
5321
 * Returns a list of CSS themes currently available in the CSS folder
5322
 * The folder must have a default.css file.
5323
 *
5324
 * @param bool $getOnlyThemeFromVirtualInstance Used by the vchamilo plugin
5325
 *
5326
 * @return array list of themes directories from the css folder
5327
 *               Note: Directory names (names of themes) in the file system should contain ASCII-characters only
5328
 */
5329
function api_get_themes($getOnlyThemeFromVirtualInstance = false)
5330
{
5331
    // This configuration value is set by the vchamilo plugin
5332
    $virtualTheme = api_get_configuration_value('virtual_css_theme_folder');
5333
5334
    $readCssFolder = function ($dir) use ($virtualTheme) {
5335
        $finder = new Finder();
5336
        $themes = $finder->directories()->in($dir)->depth(0)->sortByName();
5337
        $list = [];
5338
        /** @var Symfony\Component\Finder\SplFileInfo $theme */
5339
        foreach ($themes as $theme) {
5340
            $folder = $theme->getFilename();
5341
            // A theme folder is consider if there's a default.css file
5342
            if (!file_exists($theme->getPathname().'/default.css')) {
5343
                continue;
5344
            }
5345
            $name = ucwords(str_replace('_', ' ', $folder));
5346
            if ($folder == $virtualTheme) {
5347
                continue;
5348
            }
5349
            $list[$folder] = $name;
5350
        }
5351
5352
        return $list;
5353
    };
5354
5355
    $dir = api_get_path(SYS_CSS_PATH).'themes/';
5356
    $list = $readCssFolder($dir);
5357
5358
    if (!empty($virtualTheme)) {
5359
        $newList = $readCssFolder($dir.'/'.$virtualTheme);
5360
        if ($getOnlyThemeFromVirtualInstance) {
5361
            return $newList;
5362
        }
5363
        $list = $list + $newList;
5364
        asort($list);
5365
    }
5366
5367
    return $list;
5368
}
5369
5370
/**
5371
 * Find the largest sort value in a given user_course_category
5372
 * This function is used when we are moving a course to a different category
5373
 * and also when a user subscribes to courses (the new course is added at the end of the main category.
5374
 *
5375
 * @author Patrick Cool <[email protected]>, Ghent University
5376
 *
5377
 * @param int $user_course_category the id of the user_course_category
5378
 * @param int $user_id
5379
 *
5380
 * @return int the value of the highest sort of the user_course_category
5381
 */
5382
function api_max_sort_value($user_course_category, $user_id)
5383
{
5384
    $tbl_course_user = Database::get_main_table(TABLE_MAIN_COURSE_USER);
5385
    $sql = "SELECT max(sort) as max_sort FROM $tbl_course_user
5386
            WHERE
5387
                user_id='".intval($user_id)."' AND
5388
                relation_type<>".COURSE_RELATION_TYPE_RRHH." AND
5389
                user_course_cat='".intval($user_course_category)."'";
5390
    $result_max = Database::query($sql);
5391
    if (Database::num_rows($result_max) == 1) {
5392
        $row_max = Database::fetch_array($result_max);
5393
5394
        return $row_max['max_sort'];
5395
    }
5396
5397
    return 0;
5398
}
5399
5400
/**
5401
 * Transforms a number of seconds in hh:mm:ss format.
5402
 *
5403
 * @author Julian Prud'homme
5404
 *
5405
 * @param int    $seconds      number of seconds
5406
 * @param string $space
5407
 * @param bool   $showSeconds
5408
 * @param bool   $roundMinutes
5409
 *
5410
 * @return string the formatted time
5411
 */
5412
function api_time_to_hms($seconds, $space = ':', $showSeconds = true, $roundMinutes = false)
5413
{
5414
    // $seconds = -1 means that we have wrong data in the db.
5415
    if ($seconds == -1) {
5416
        return
5417
            get_lang('Unknown').
5418
            Display::return_icon(
5419
                'info2.gif',
5420
                get_lang('WrongDatasForTimeSpentOnThePlatform'),
5421
                ['align' => 'absmiddle', 'hspace' => '3px']
5422
            );
5423
    }
5424
5425
    // How many hours ?
5426
    $hours = floor($seconds / 3600);
5427
5428
    // How many minutes ?
5429
    $min = floor(($seconds - ($hours * 3600)) / 60);
5430
5431
    if ($roundMinutes) {
5432
        if ($min >= 45) {
5433
            $min = 45;
5434
        }
5435
5436
        if ($min >= 30 && $min <= 44) {
5437
            $min = 30;
5438
        }
5439
5440
        if ($min >= 15 && $min <= 29) {
5441
            $min = 15;
5442
        }
5443
5444
        if ($min >= 0 && $min <= 14) {
5445
            $min = 0;
5446
        }
5447
    }
5448
5449
    // How many seconds
5450
    $sec = floor($seconds - ($hours * 3600) - ($min * 60));
5451
5452
    if ($hours < 10) {
5453
        $hours = "0$hours";
5454
    }
5455
5456
    if ($sec < 10) {
5457
        $sec = "0$sec";
5458
    }
5459
5460
    if ($min < 10) {
5461
        $min = "0$min";
5462
    }
5463
5464
    $seconds = '';
5465
    if ($showSeconds) {
5466
        $seconds = $space.$sec;
5467
    }
5468
5469
    return $hours.$space.$min.$seconds;
5470
}
5471
5472
/* FILE SYSTEM RELATED FUNCTIONS */
5473
5474
/**
5475
 * Returns the permissions to be assigned to every newly created directory by the web-server.
5476
 * The return value is based on the platform administrator's setting
5477
 * "Administration > Configuration settings > Security > Permissions for new directories".
5478
 *
5479
 * @return int returns the permissions in the format "Owner-Group-Others, Read-Write-Execute", as an integer value
5480
 */
5481
function api_get_permissions_for_new_directories()
5482
{
5483
    static $permissions;
5484
    if (!isset($permissions)) {
5485
        $permissions = trim(api_get_setting('permissions_for_new_directories'));
5486
        // The default value 0777 is according to that in the platform administration panel after fresh system installation.
5487
        $permissions = octdec(!empty($permissions) ? $permissions : '0777');
5488
    }
5489
5490
    return $permissions;
5491
}
5492
5493
/**
5494
 * Returns the permissions to be assigned to every newly created directory by the web-server.
5495
 * The return value is based on the platform administrator's setting
5496
 * "Administration > Configuration settings > Security > Permissions for new files".
5497
 *
5498
 * @return int returns the permissions in the format
5499
 *             "Owner-Group-Others, Read-Write-Execute", as an integer value
5500
 */
5501
function api_get_permissions_for_new_files()
5502
{
5503
    static $permissions;
5504
    if (!isset($permissions)) {
5505
        $permissions = trim(api_get_setting('permissions_for_new_files'));
5506
        // The default value 0666 is according to that in the platform
5507
        // administration panel after fresh system installation.
5508
        $permissions = octdec(!empty($permissions) ? $permissions : '0666');
5509
    }
5510
5511
    return $permissions;
5512
}
5513
5514
/**
5515
 * Deletes a file, or a folder and its contents.
5516
 *
5517
 * @author      Aidan Lister <[email protected]>
5518
 *
5519
 * @version     1.0.3
5520
 *
5521
 * @param string $dirname Directory to delete
5522
 * @param       bool     Deletes only the content or not
5523
 * @param bool $strict if one folder/file fails stop the loop
5524
 *
5525
 * @return bool Returns TRUE on success, FALSE on failure
5526
 *
5527
 * @see http://aidanlister.com/2004/04/recursively-deleting-a-folder-in-php/
5528
 *
5529
 * @author      Yannick Warnier, adaptation for the Chamilo LMS, April, 2008
5530
 * @author      Ivan Tcholakov, a sanity check about Directory class creation has been added, September, 2009
5531
 */
5532
function rmdirr($dirname, $delete_only_content_in_folder = false, $strict = false)
5533
{
5534
    $res = true;
5535
    // A sanity check.
5536
    if (!file_exists($dirname)) {
5537
        return false;
5538
    }
5539
    $php_errormsg = '';
5540
    // Simple delete for a file.
5541
    if (is_file($dirname) || is_link($dirname)) {
5542
        $res = unlink($dirname);
5543
        if ($res === false) {
5544
            error_log(__FILE__.' line '.__LINE__.': '.((bool) ini_get('track_errors') ? $php_errormsg : 'Error not recorded because track_errors is off in your php.ini'), 0);
5545
        }
5546
5547
        return $res;
5548
    }
5549
5550
    // Loop through the folder.
5551
    $dir = dir($dirname);
5552
    // A sanity check.
5553
    $is_object_dir = is_object($dir);
5554
    if ($is_object_dir) {
5555
        while (false !== $entry = $dir->read()) {
5556
            // Skip pointers.
5557
            if ($entry == '.' || $entry == '..') {
5558
                continue;
5559
            }
5560
5561
            // Recurse.
5562
            if ($strict) {
5563
                $result = rmdirr("$dirname/$entry");
5564
                if ($result == false) {
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like you are loosely comparing two booleans. Considering using the strict comparison === instead.

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

Loading history...
5565
                    $res = false;
5566
                    break;
5567
                }
5568
            } else {
5569
                rmdirr("$dirname/$entry");
5570
            }
5571
        }
5572
    }
5573
5574
    // Clean up.
5575
    if ($is_object_dir) {
5576
        $dir->close();
5577
    }
5578
5579
    if ($delete_only_content_in_folder == false) {
5580
        $res = rmdir($dirname);
5581
        if ($res === false) {
5582
            error_log(__FILE__.' line '.__LINE__.': '.((bool) ini_get('track_errors') ? $php_errormsg : 'error not recorded because track_errors is off in your php.ini'), 0);
5583
        }
5584
    }
5585
5586
    return $res;
5587
}
5588
5589
// TODO: This function is to be simplified. File access modes to be implemented.
5590
/**
5591
 * function adapted from a php.net comment
5592
 * copy recursively a folder.
5593
 *
5594
 * @param string $source       the source folder
5595
 * @param string $dest         the dest folder
5596
 * @param array  $exclude      an array of excluded file_name (without extension)
5597
 * @param array  $copied_files the returned array of copied files
5598
 */
5599
function copyr($source, $dest, $exclude = [], $copied_files = [])
5600
{
5601
    if (empty($dest)) {
5602
        return false;
5603
    }
5604
    // Simple copy for a file
5605
    if (is_file($source)) {
5606
        $path_info = pathinfo($source);
5607
        if (!in_array($path_info['filename'], $exclude)) {
5608
            copy($source, $dest);
5609
        }
5610
5611
        return true;
5612
    } elseif (!is_dir($source)) {
5613
        //then source is not a dir nor a file, return
5614
        return false;
5615
    }
5616
5617
    // Make destination directory.
5618
    if (!is_dir($dest)) {
5619
        mkdir($dest, api_get_permissions_for_new_directories());
5620
    }
5621
5622
    // Loop through the folder.
5623
    $dir = dir($source);
5624
    while (false !== $entry = $dir->read()) {
5625
        // Skip pointers
5626
        if ($entry == '.' || $entry == '..') {
5627
            continue;
5628
        }
5629
5630
        // Deep copy directories.
5631
        if ($dest !== "$source/$entry") {
5632
            $files = copyr("$source/$entry", "$dest/$entry", $exclude, $copied_files);
5633
        }
5634
    }
5635
    // Clean up.
5636
    $dir->close();
5637
5638
    return true;
5639
}
5640
5641
/**
5642
 * @param string $pathname
5643
 * @param string $base_path_document
5644
 * @param int    $session_id
5645
 * @param array
5646
 * @param string
5647
 *
5648
 * @return mixed True if directory already exists, false if a file already exists at
5649
 *               the destination and null if everything goes according to plan
5650
 *@todo: Using DIRECTORY_SEPARATOR is not recommended, this is an obsolete approach.
5651
 * Documentation header to be added here.
5652
 */
5653
function copy_folder_course_session(
5654
    $pathname,
5655
    $base_path_document,
5656
    $session_id,
5657
    $course_info,
5658
    $document,
5659
    $source_course_id,
5660
    $originalFolderNameList = [],
5661
    $originalBaseName = ''
5662
) {
5663
    // Check whether directory already exists.
5664
    if (empty($pathname) || is_dir($pathname)) {
5665
        return true;
5666
    }
5667
5668
    // Ensure that a file with the same name does not already exist.
5669
    if (is_file($pathname)) {
5670
        trigger_error('copy_folder_course_session(): File exists', E_USER_WARNING);
5671
5672
        return false;
5673
    }
5674
5675
    //error_log('checking:');
5676
    //error_log(str_replace($base_path_document.DIRECTORY_SEPARATOR, '', $pathname));
5677
    $baseNoDocument = str_replace('document', '', $originalBaseName);
5678
    $folderTitles = explode('/', $baseNoDocument);
5679
    $folderTitles = array_filter($folderTitles);
5680
5681
    //error_log($baseNoDocument);error_log(print_r($folderTitles, 1));
5682
5683
    $table = Database::get_course_table(TABLE_DOCUMENT);
5684
    $session_id = (int) $session_id;
5685
    $source_course_id = (int) $source_course_id;
5686
    $course_id = $course_info['real_id'];
5687
    $folders = explode(DIRECTORY_SEPARATOR, str_replace($base_path_document.DIRECTORY_SEPARATOR, '', $pathname));
5688
    $new_pathname = $base_path_document;
5689
5690
    $path = '';
5691
    foreach ($folders as $index => $folder) {
5692
        $new_pathname .= DIRECTORY_SEPARATOR.$folder;
5693
        $path .= DIRECTORY_SEPARATOR.$folder;
5694
5695
        if (!file_exists($new_pathname)) {
5696
            $path = Database::escape_string($path);
5697
            //error_log("path: $path");
5698
            $sql = "SELECT * FROM $table
5699
                    WHERE
5700
                        c_id = $source_course_id AND
5701
                        path = '$path' AND
5702
                        filetype = 'folder' AND
5703
                        session_id = '$session_id'";
5704
            $rs1 = Database::query($sql);
5705
            $num_rows = Database::num_rows($rs1);
5706
5707
            if (0 == $num_rows) {
5708
                mkdir($new_pathname, api_get_permissions_for_new_directories());
5709
                $title = basename($new_pathname);
5710
5711
                if (isset($folderTitles[$index + 1])) {
5712
                    $checkPath = $folderTitles[$index + 1];
5713
                    //error_log("check $checkPath");
5714
                    if (isset($originalFolderNameList[$checkPath])) {
5715
                        $title = $originalFolderNameList[$checkPath];
5716
                        //error_log('use this name: '.$title);
5717
                    }
5718
                }
5719
5720
                // Insert new folder with destination session_id.
5721
                $params = [
5722
                    'c_id' => $course_id,
5723
                    'path' => $path,
5724
                    'comment' => $document->comment,
5725
                    'title' => $title,
5726
                    'filetype' => 'folder',
5727
                    'size' => '0',
5728
                    'session_id' => $session_id,
5729
                ];
5730
5731
                //error_log("old $folder"); error_log("Add doc $title in $path");
5732
                $document_id = Database::insert($table, $params);
5733
                if ($document_id) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $document_id of type false|integer is loosely compared to true; this is ambiguous if the integer can be 0. You might want to explicitly use !== false instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
5734
                    $sql = "UPDATE $table SET id = iid WHERE iid = $document_id";
5735
                    Database::query($sql);
5736
5737
                    api_item_property_update(
5738
                        $course_info,
5739
                        TOOL_DOCUMENT,
5740
                        $document_id,
5741
                        'FolderCreated',
5742
                        api_get_user_id(),
5743
                        0,
5744
                        0,
5745
                        null,
5746
                        null,
5747
                        $session_id
5748
                    );
5749
                }
5750
            }
5751
        }
5752
    }
5753
}
5754
5755
// TODO: chmodr() is a better name. Some corrections are needed. Documentation header to be added here.
5756
/**
5757
 * @param string $path
5758
 */
5759
function api_chmod_R($path, $filemode)
5760
{
5761
    if (!is_dir($path)) {
5762
        return chmod($path, $filemode);
5763
    }
5764
5765
    $handler = opendir($path);
5766
    while ($file = readdir($handler)) {
5767
        if ($file != '.' && $file != '..') {
5768
            $fullpath = "$path/$file";
5769
            if (!is_dir($fullpath)) {
5770
                if (!chmod($fullpath, $filemode)) {
5771
                    return false;
5772
                }
5773
            } else {
5774
                if (!api_chmod_R($fullpath, $filemode)) {
5775
                    return false;
5776
                }
5777
            }
5778
        }
5779
    }
5780
5781
    closedir($handler);
5782
5783
    return chmod($path, $filemode);
5784
}
5785
5786
// TODO: Where the following function has been copy/pased from? There is no information about author and license. Style, coding conventions...
5787
/**
5788
 * Parse info file format. (e.g: file.info).
5789
 *
5790
 * Files should use an ini-like format to specify values.
5791
 * White-space generally doesn't matter, except inside values.
5792
 * e.g.
5793
 *
5794
 * @verbatim
5795
 *   key = value
5796
 *   key = "value"
5797
 *   key = 'value'
5798
 *   key = "multi-line
5799
 *
5800
 *   value"
5801
 *   key = 'multi-line
5802
 *
5803
 *   value'
5804
 *   key
5805
 *   =
5806
 *   'value'
5807
 * @endverbatim
5808
 *
5809
 * Arrays are created using a GET-like syntax:
5810
 *
5811
 * @verbatim
5812
 *   key[] = "numeric array"
5813
 *   key[index] = "associative array"
5814
 *   key[index][] = "nested numeric array"
5815
 *   key[index][index] = "nested associative array"
5816
 * @endverbatim
5817
 *
5818
 * PHP constants are substituted in, but only when used as the entire value:
5819
 *
5820
 * Comments should start with a semi-colon at the beginning of a line.
5821
 *
5822
 * This function is NOT for placing arbitrary module-specific settings. Use
5823
 * variable_get() and variable_set() for that.
5824
 *
5825
 * Information stored in the module.info file:
5826
 * - name: The real name of the module for display purposes.
5827
 * - description: A brief description of the module.
5828
 * - dependencies: An array of shortnames of other modules this module depends on.
5829
 * - package: The name of the package of modules this module belongs to.
5830
 *
5831
 * Example of .info file:
5832
 * <code>
5833
 * @verbatim
5834
 *   name = Forum
5835
 *   description = Enables threaded discussions about general topics.
5836
 *   dependencies[] = taxonomy
5837
 *   dependencies[] = comment
5838
 *   package = Core - optional
5839
 *   version = VERSION
5840
 * @endverbatim
5841
 * </code>
5842
 *
5843
 * @param string $filename
5844
 *                         The file we are parsing. Accepts file with relative or absolute path.
5845
 *
5846
 * @return
5847
 *   The info array
5848
 */
5849
function api_parse_info_file($filename)
5850
{
5851
    $info = [];
5852
5853
    if (!file_exists($filename)) {
5854
        return $info;
5855
    }
5856
5857
    $data = file_get_contents($filename);
5858
    if (preg_match_all('
5859
        @^\s*                           # Start at the beginning of a line, ignoring leading whitespace
5860
        ((?:
5861
          [^=;\[\]]|                    # Key names cannot contain equal signs, semi-colons or square brackets,
5862
          \[[^\[\]]*\]                  # unless they are balanced and not nested
5863
        )+?)
5864
        \s*=\s*                         # Key/value pairs are separated by equal signs (ignoring white-space)
5865
        (?:
5866
          ("(?:[^"]|(?<=\\\\)")*")|     # Double-quoted string, which may contain slash-escaped quotes/slashes
5867
          (\'(?:[^\']|(?<=\\\\)\')*\')| # Single-quoted string, which may contain slash-escaped quotes/slashes
5868
          ([^\r\n]*?)                   # Non-quoted string
5869
        )\s*$                           # Stop at the next end of a line, ignoring trailing whitespace
5870
        @msx', $data, $matches, PREG_SET_ORDER)) {
5871
        $key = $value1 = $value2 = $value3 = '';
5872
        foreach ($matches as $match) {
5873
            // Fetch the key and value string.
5874
            $i = 0;
5875
            foreach (['key', 'value1', 'value2', 'value3'] as $var) {
5876
                $$var = isset($match[++$i]) ? $match[$i] : '';
5877
            }
5878
            $value = stripslashes(substr($value1, 1, -1)).stripslashes(substr($value2, 1, -1)).$value3;
5879
5880
            // Parse array syntax.
5881
            $keys = preg_split('/\]?\[/', rtrim($key, ']'));
5882
            $last = array_pop($keys);
5883
            $parent = &$info;
5884
5885
            // Create nested arrays.
5886
            foreach ($keys as $key) {
5887
                if ($key == '') {
5888
                    $key = count($parent);
5889
                }
5890
                if (!isset($parent[$key]) || !is_array($parent[$key])) {
5891
                    $parent[$key] = [];
5892
                }
5893
                $parent = &$parent[$key];
5894
            }
5895
5896
            // Handle PHP constants.
5897
            if (defined($value)) {
5898
                $value = constant($value);
5899
            }
5900
5901
            // Insert actual value.
5902
            if ($last == '') {
5903
                $last = count($parent);
5904
            }
5905
            $parent[$last] = $value;
5906
        }
5907
    }
5908
5909
    return $info;
5910
}
5911
5912
/**
5913
 * Gets Chamilo version from the configuration files.
5914
 *
5915
 * @return string A string of type "1.8.4", or an empty string if the version could not be found
5916
 */
5917
function api_get_version()
5918
{
5919
    return (string) api_get_configuration_value('system_version');
5920
}
5921
5922
/**
5923
 * Gets the software name (the name/brand of the Chamilo-based customized system).
5924
 *
5925
 * @return string
5926
 */
5927
function api_get_software_name()
5928
{
5929
    $name = api_get_configuration_value('software_name');
5930
    if (!empty($name)) {
5931
        return $name;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $name also could return the type boolean which is incompatible with the documented return type string.
Loading history...
5932
    } else {
5933
        return 'Chamilo';
5934
    }
5935
}
5936
5937
/**
5938
 * Checks whether status given in parameter exists in the platform.
5939
 *
5940
 * @param mixed the status (can be either int either string)
5941
 *
5942
 * @return bool if the status exists, else returns false
5943
 */
5944
function api_status_exists($status_asked)
5945
{
5946
    global $_status_list;
5947
5948
    return in_array($status_asked, $_status_list) ? true : isset($_status_list[$status_asked]);
5949
}
5950
5951
/**
5952
 * Checks whether status given in parameter exists in the platform. The function
5953
 * returns the status ID or false if it does not exist, but given the fact there
5954
 * is no "0" status, the return value can be checked against
5955
 * if(api_status_key()) to know if it exists.
5956
 *
5957
 * @param   mixed   The status (can be either int or string)
5958
 *
5959
 * @return mixed Status ID if exists, false otherwise
5960
 */
5961
function api_status_key($status)
5962
{
5963
    global $_status_list;
5964
5965
    return isset($_status_list[$status]) ? $status : array_search($status, $_status_list);
5966
}
5967
5968
/**
5969
 * Gets the status langvars list.
5970
 *
5971
 * @return string[] the list of status with their translations
5972
 */
5973
function api_get_status_langvars()
5974
{
5975
    return [
5976
        COURSEMANAGER => get_lang('Teacher', ''),
5977
        SESSIONADMIN => get_lang('SessionsAdmin', ''),
5978
        DRH => get_lang('Drh', ''),
5979
        STUDENT => get_lang('Student', ''),
5980
        ANONYMOUS => get_lang('Anonymous', ''),
5981
        STUDENT_BOSS => get_lang('RoleStudentBoss', ''),
5982
        INVITEE => get_lang('Invited'),
5983
    ];
5984
}
5985
5986
/**
5987
 * The function that retrieves all the possible settings for a certain config setting.
5988
 *
5989
 * @author Patrick Cool <[email protected]>, Ghent University
5990
 */
5991
function api_get_settings_options($var)
5992
{
5993
    $table_settings_options = Database::get_main_table(TABLE_MAIN_SETTINGS_OPTIONS);
5994
    $var = Database::escape_string($var);
5995
    $sql = "SELECT * FROM $table_settings_options
5996
            WHERE variable = '$var'
5997
            ORDER BY id";
5998
    $result = Database::query($sql);
5999
    $settings_options_array = [];
6000
    while ($row = Database::fetch_array($result, 'ASSOC')) {
6001
        $settings_options_array[] = $row;
6002
    }
6003
6004
    return $settings_options_array;
6005
}
6006
6007
/**
6008
 * @param array $params
6009
 */
6010
function api_set_setting_option($params)
6011
{
6012
    $table = Database::get_main_table(TABLE_MAIN_SETTINGS_OPTIONS);
6013
    if (empty($params['id'])) {
6014
        Database::insert($table, $params);
6015
    } else {
6016
        Database::update($table, $params, ['id = ? ' => $params['id']]);
6017
    }
6018
}
6019
6020
/**
6021
 * @param array $params
6022
 */
6023
function api_set_setting_simple($params)
6024
{
6025
    $table = Database::get_main_table(TABLE_MAIN_SETTINGS_CURRENT);
6026
    $url_id = api_get_current_access_url_id();
6027
6028
    if (empty($params['id'])) {
6029
        $params['access_url'] = $url_id;
6030
        Database::insert($table, $params);
6031
    } else {
6032
        Database::update($table, $params, ['id = ? ' => [$params['id']]]);
6033
    }
6034
}
6035
6036
/**
6037
 * @param int $id
6038
 */
6039
function api_delete_setting_option($id)
6040
{
6041
    $table = Database::get_main_table(TABLE_MAIN_SETTINGS_OPTIONS);
6042
    if (!empty($id)) {
6043
        Database::delete($table, ['id = ? ' => $id]);
6044
    }
6045
}
6046
6047
/**
6048
 * Sets a platform configuration setting to a given value.
6049
 *
6050
 * @param string    The variable we want to update
6051
 * @param string    The value we want to record
6052
 * @param string    The sub-variable if any (in most cases, this will remain null)
6053
 * @param string    The category if any (in most cases, this will remain null)
6054
 * @param int       The access_url for which this parameter is valid
6055
 * @param string $cat
6056
 *
6057
 * @return bool|null
6058
 */
6059
function api_set_setting($var, $value, $subvar = null, $cat = null, $access_url = 1)
6060
{
6061
    if (empty($var)) {
6062
        return false;
6063
    }
6064
    $t_settings = Database::get_main_table(TABLE_MAIN_SETTINGS_CURRENT);
6065
    $var = Database::escape_string($var);
6066
    $value = Database::escape_string($value);
6067
    $access_url = (int) $access_url;
6068
    if (empty($access_url)) {
6069
        $access_url = 1;
6070
    }
6071
    $select = "SELECT id FROM $t_settings WHERE variable = '$var' ";
6072
    if (!empty($subvar)) {
6073
        $subvar = Database::escape_string($subvar);
6074
        $select .= " AND subkey = '$subvar'";
6075
    }
6076
    if (!empty($cat)) {
6077
        $cat = Database::escape_string($cat);
6078
        $select .= " AND category = '$cat'";
6079
    }
6080
    if ($access_url > 1) {
6081
        $select .= " AND access_url = $access_url";
6082
    } else {
6083
        $select .= " AND access_url = 1 ";
6084
    }
6085
6086
    $res = Database::query($select);
6087
    if (Database::num_rows($res) > 0) {
6088
        // Found item for this access_url.
6089
        $row = Database::fetch_array($res);
6090
        $sql = "UPDATE $t_settings SET selected_value = '$value'
6091
                WHERE id = ".$row['id'];
6092
        Database::query($sql);
6093
    } else {
6094
        // Item not found for this access_url, we have to check if it exist with access_url = 1
6095
        $select = "SELECT * FROM $t_settings
6096
                   WHERE variable = '$var' AND access_url = 1 ";
6097
        // Just in case
6098
        if ($access_url == 1) {
6099
            if (!empty($subvar)) {
6100
                $select .= " AND subkey = '$subvar'";
6101
            }
6102
            if (!empty($cat)) {
6103
                $select .= " AND category = '$cat'";
6104
            }
6105
            $res = Database::query($select);
6106
            if (Database::num_rows($res) > 0) {
6107
                // We have a setting for access_url 1, but none for the current one, so create one.
6108
                $row = Database::fetch_array($res);
6109
                $insert = "INSERT INTO $t_settings (variable, subkey, type,category, selected_value, title, comment, scope, subkeytext, access_url)
6110
                        VALUES
6111
                        ('".$row['variable']."',".(!empty($row['subkey']) ? "'".$row['subkey']."'" : "NULL").",".
6112
                        "'".$row['type']."','".$row['category']."',".
6113
                        "'$value','".$row['title']."',".
6114
                        "".(!empty($row['comment']) ? "'".$row['comment']."'" : "NULL").",".(!empty($row['scope']) ? "'".$row['scope']."'" : "NULL").",".
6115
                        "".(!empty($row['subkeytext']) ? "'".$row['subkeytext']."'" : "NULL").",$access_url)";
6116
                Database::query($insert);
6117
            } else {
6118
                // Such a setting does not exist.
6119
                //error_log(__FILE__.':'.__LINE__.': Attempting to update setting '.$var.' ('.$subvar.') which does not exist at all', 0);
6120
            }
6121
        } else {
6122
            // Other access url.
6123
            if (!empty($subvar)) {
6124
                $select .= " AND subkey = '$subvar'";
6125
            }
6126
            if (!empty($cat)) {
6127
                $select .= " AND category = '$cat'";
6128
            }
6129
            $res = Database::query($select);
6130
6131
            if (Database::num_rows($res) > 0) {
6132
                // We have a setting for access_url 1, but none for the current one, so create one.
6133
                $row = Database::fetch_array($res);
6134
                if ($row['access_url_changeable'] == 1) {
6135
                    $insert = "INSERT INTO $t_settings (variable,subkey, type,category, selected_value,title, comment,scope, subkeytext,access_url, access_url_changeable) VALUES
6136
                            ('".$row['variable']."',".
6137
                            (!empty($row['subkey']) ? "'".$row['subkey']."'" : "NULL").",".
6138
                            "'".$row['type']."','".$row['category']."',".
6139
                            "'$value','".$row['title']."',".
6140
                            "".(!empty($row['comment']) ? "'".$row['comment']."'" : "NULL").",".
6141
                            (!empty($row['scope']) ? "'".$row['scope']."'" : "NULL").",".
6142
                            "".(!empty($row['subkeytext']) ? "'".$row['subkeytext']."'" : "NULL").",$access_url,".$row['access_url_changeable'].")";
6143
                    Database::query($insert);
6144
                }
6145
            } else { // Such a setting does not exist.
6146
                //error_log(__FILE__.':'.__LINE__.': Attempting to update setting '.$var.' ('.$subvar.') which does not exist at all. The access_url is: '.$access_url.' ',0);
6147
            }
6148
        }
6149
    }
6150
}
6151
6152
/**
6153
 * Sets a whole category of settings to one specific value.
6154
 *
6155
 * @param string    Category
6156
 * @param string    Value
6157
 * @param int       Access URL. Optional. Defaults to 1
6158
 * @param array     Optional array of filters on field type
6159
 * @param string $category
6160
 * @param string $value
6161
 *
6162
 * @return bool
6163
 */
6164
function api_set_settings_category($category, $value = null, $access_url = 1, $fieldtype = [])
6165
{
6166
    if (empty($category)) {
6167
        return false;
6168
    }
6169
    $category = Database::escape_string($category);
6170
    $t_s = Database::get_main_table(TABLE_MAIN_SETTINGS_CURRENT);
6171
    $access_url = (int) $access_url;
6172
    if (empty($access_url)) {
6173
        $access_url = 1;
6174
    }
6175
    if (isset($value)) {
6176
        $value = Database::escape_string($value);
6177
        $sql = "UPDATE $t_s SET selected_value = '$value'
6178
                WHERE category = '$category' AND access_url = $access_url";
6179
        if (is_array($fieldtype) && count($fieldtype) > 0) {
6180
            $sql .= " AND ( ";
6181
            $i = 0;
6182
            foreach ($fieldtype as $type) {
6183
                if ($i > 0) {
6184
                    $sql .= ' OR ';
6185
                }
6186
                $type = Database::escape_string($type);
6187
                $sql .= " type='".$type."' ";
6188
                $i++;
6189
            }
6190
            $sql .= ")";
6191
        }
6192
        $res = Database::query($sql);
6193
6194
        return $res !== false;
6195
    } else {
6196
        $sql = "UPDATE $t_s SET selected_value = NULL
6197
                WHERE category = '$category' AND access_url = $access_url";
6198
        if (is_array($fieldtype) && count($fieldtype) > 0) {
6199
            $sql .= " AND ( ";
6200
            $i = 0;
6201
            foreach ($fieldtype as $type) {
6202
                if ($i > 0) {
6203
                    $sql .= ' OR ';
6204
                }
6205
                $type = Database::escape_string($type);
6206
                $sql .= " type='".$type."' ";
6207
                $i++;
6208
            }
6209
            $sql .= ")";
6210
        }
6211
        $res = Database::query($sql);
6212
6213
        return $res !== false;
6214
    }
6215
}
6216
6217
/**
6218
 * Gets all available access urls in an array (as in the database).
6219
 *
6220
 * @return array An array of database records
6221
 */
6222
function api_get_access_urls($from = 0, $to = 1000000, $order = 'url', $direction = 'ASC')
6223
{
6224
    $table = Database::get_main_table(TABLE_MAIN_ACCESS_URL);
6225
    $from = (int) $from;
6226
    $to = (int) $to;
6227
    $order = Database::escape_string($order);
6228
    $direction = Database::escape_string($direction);
6229
    $direction = !in_array(strtolower(trim($direction)), ['asc', 'desc']) ? 'asc' : $direction;
6230
6231
    $sql = "SELECT id, url, description, active, created_by, tms
6232
            FROM $table
6233
            ORDER BY `$order` $direction
6234
            LIMIT $to OFFSET $from";
6235
    $res = Database::query($sql);
6236
6237
    return Database::store_result($res);
6238
}
6239
6240
/**
6241
 * Gets the access url info in an array.
6242
 *
6243
 * @param int  $id            Id of the access url
6244
 * @param bool $returnDefault Set to false if you want the real URL if URL 1 is still 'http://localhost/'
6245
 *
6246
 * @return array All the info (url, description, active, created_by, tms)
6247
 *               from the access_url table
6248
 *
6249
 * @author Julio Montoya
6250
 */
6251
function api_get_access_url($id, $returnDefault = true)
6252
{
6253
    static $staticResult;
6254
    $id = (int) $id;
6255
6256
    if (isset($staticResult[$id])) {
6257
        $result = $staticResult[$id];
6258
    } else {
6259
        // Calling the Database:: library dont work this is handmade.
6260
        $table_access_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL);
6261
        $sql = "SELECT url, description, active, created_by, tms
6262
                FROM $table_access_url WHERE id = '$id' ";
6263
        $res = Database::query($sql);
6264
        $result = @Database::fetch_array($res);
6265
        $staticResult[$id] = $result;
6266
    }
6267
6268
    // If the result url is 'http://localhost/' (the default) and the root_web
6269
    // (=current url) is different, and the $id is = 1 (which might mean
6270
    // api_get_current_access_url_id() returned 1 by default), then return the
6271
    // root_web setting instead of the current URL
6272
    // This is provided as an option to avoid breaking the storage of URL-specific
6273
    // homepages in home/localhost/
6274
    if ($id === 1 && $returnDefault === false) {
6275
        $currentUrl = api_get_current_access_url_id();
6276
        // only do this if we are on the main URL (=1), otherwise we could get
6277
        // information on another URL instead of the one asked as parameter
6278
        if ($currentUrl === 1) {
6279
            $rootWeb = api_get_path(WEB_PATH);
6280
            $default = 'http://localhost/';
6281
            if ($result['url'] === $default && $rootWeb != $default) {
6282
                $result['url'] = $rootWeb;
6283
            }
6284
        }
6285
    }
6286
6287
    return $result;
6288
}
6289
6290
/**
6291
 * Gets all the current settings for a specific access url.
6292
 *
6293
 * @param string    The category, if any, that we want to get
6294
 * @param string    Whether we want a simple list (display a category) or
6295
 * a grouped list (group by variable as in settings.php default). Values: 'list' or 'group'
6296
 * @param int       Access URL's ID. Optional. Uses 1 by default, which is the unique URL
6297
 *
6298
 * @return array Array of database results for the current settings of the current access URL
6299
 */
6300
function &api_get_settings($cat = null, $ordering = 'list', $access_url = 1, $url_changeable = 0)
6301
{
6302
    $table = Database::get_main_table(TABLE_MAIN_SETTINGS_CURRENT);
6303
    $access_url = (int) $access_url;
6304
    $where_condition = '';
6305
    if ($url_changeable == 1) {
6306
        $where_condition = " AND access_url_changeable= '1' ";
6307
    }
6308
    if (empty($access_url) || $access_url == -1) {
6309
        $access_url = 1;
6310
    }
6311
    $sql = "SELECT * FROM $table
6312
            WHERE access_url = $access_url  $where_condition ";
6313
6314
    if (!empty($cat)) {
6315
        $cat = Database::escape_string($cat);
6316
        $sql .= " AND category='$cat' ";
6317
    }
6318
    if ($ordering == 'group') {
6319
        $sql .= " ORDER BY id ASC";
6320
    } else {
6321
        $sql .= " ORDER BY 1,2 ASC";
6322
    }
6323
    $result = Database::query($sql);
6324
    if ($result === null) {
6325
        return [];
6326
    }
6327
    $result = Database::store_result($result, 'ASSOC');
6328
6329
    return $result;
6330
}
6331
6332
/**
6333
 * @param string $value       The value we want to record
6334
 * @param string $variable    The variable name we want to insert
6335
 * @param string $subKey      The subkey for the variable we want to insert
6336
 * @param string $type        The type for the variable we want to insert
6337
 * @param string $category    The category for the variable we want to insert
6338
 * @param string $title       The title
6339
 * @param string $comment     The comment
6340
 * @param string $scope       The scope
6341
 * @param string $subKeyText  The subkey text
6342
 * @param int    $accessUrlId The access_url for which this parameter is valid
6343
 * @param int    $visibility  The changeability of this setting for non-master urls
6344
 *
6345
 * @return int The setting ID
6346
 */
6347
function api_add_setting(
6348
    $value,
6349
    $variable,
6350
    $subKey = '',
6351
    $type = 'textfield',
6352
    $category = '',
6353
    $title = '',
6354
    $comment = '',
6355
    $scope = '',
6356
    $subKeyText = '',
6357
    $accessUrlId = 1,
6358
    $visibility = 0
6359
) {
6360
    $em = Database::getManager();
6361
    $settingRepo = $em->getRepository('ChamiloCoreBundle:SettingsCurrent');
6362
    $accessUrlId = (int) $accessUrlId ?: 1;
6363
6364
    if (is_array($value)) {
6365
        $value = serialize($value);
6366
    } else {
6367
        $value = trim($value);
6368
    }
6369
6370
    $criteria = ['variable' => $variable, 'accessUrl' => $accessUrlId];
6371
6372
    if (!empty($subKey)) {
6373
        $criteria['subkey'] = $subKey;
6374
    }
6375
6376
    // Check if this variable doesn't exist already
6377
    /** @var SettingsCurrent $setting */
6378
    $setting = $settingRepo->findOneBy($criteria);
6379
6380
    if ($setting) {
0 ignored issues
show
introduced by
$setting is of type Chamilo\CoreBundle\Entity\SettingsCurrent, thus it always evaluated to true.
Loading history...
6381
        $setting->setSelectedValue($value);
6382
6383
        $em->persist($setting);
6384
        $em->flush();
6385
6386
        return $setting->getId();
6387
    }
6388
6389
    // Item not found for this access_url, we have to check if the whole thing is missing
6390
    // (in which case we ignore the insert) or if there *is* a record but just for access_url = 1
6391
    $setting = new SettingsCurrent();
6392
    $setting
6393
        ->setVariable($variable)
6394
        ->setSelectedValue($value)
6395
        ->setType($type)
6396
        ->setCategory($category)
6397
        ->setSubkey($subKey)
6398
        ->setTitle($title)
6399
        ->setComment($comment)
6400
        ->setScope($scope)
6401
        ->setSubkeytext($subKeyText)
6402
        ->setAccessUrl($accessUrlId)
6403
        ->setAccessUrlChangeable($visibility);
6404
6405
    $em->persist($setting);
6406
    $em->flush();
6407
6408
    return $setting->getId();
6409
}
6410
6411
/**
6412
 * Checks wether a user can or can't view the contents of a course.
6413
 *
6414
 * @deprecated use CourseManager::is_user_subscribed_in_course
6415
 *
6416
 * @param int $userid User id or NULL to get it from $_SESSION
6417
 * @param int $cid    course id to check whether the user is allowed
6418
 *
6419
 * @return bool
6420
 */
6421
function api_is_course_visible_for_user($userid = null, $cid = null)
6422
{
6423
    if ($userid === null) {
6424
        $userid = api_get_user_id();
6425
    }
6426
    if (empty($userid) || strval(intval($userid)) != $userid) {
6427
        if (api_is_anonymous()) {
6428
            $userid = api_get_anonymous_id();
6429
        } else {
6430
            return false;
6431
        }
6432
    }
6433
    $cid = Database::escape_string($cid);
6434
6435
    $courseInfo = api_get_course_info($cid);
6436
    $courseId = $courseInfo['real_id'];
6437
    $is_platformAdmin = api_is_platform_admin();
6438
6439
    $course_table = Database::get_main_table(TABLE_MAIN_COURSE);
6440
    $course_cat_table = Database::get_main_table(TABLE_MAIN_CATEGORY);
6441
6442
    $sql = "SELECT
6443
                $course_table.category_code,
6444
                $course_table.visibility,
6445
                $course_table.code,
6446
                $course_cat_table.code
6447
            FROM $course_table
6448
            LEFT JOIN $course_cat_table
6449
                ON $course_table.category_code = $course_cat_table.code
6450
            WHERE
6451
                $course_table.code = '$cid'
6452
            LIMIT 1";
6453
6454
    $result = Database::query($sql);
6455
6456
    if (Database::num_rows($result) > 0) {
6457
        $visibility = Database::fetch_array($result);
6458
        $visibility = $visibility['visibility'];
6459
    } else {
6460
        $visibility = 0;
6461
    }
6462
    // Shortcut permissions in case the visibility is "open to the world".
6463
    if ($visibility === COURSE_VISIBILITY_OPEN_WORLD) {
6464
        return true;
6465
    }
6466
6467
    $tbl_course_user = Database::get_main_table(TABLE_MAIN_COURSE_USER);
6468
6469
    $sql = "SELECT
6470
                is_tutor, status
6471
            FROM $tbl_course_user
6472
            WHERE
6473
                user_id  = '$userid' AND
6474
                relation_type <> '".COURSE_RELATION_TYPE_RRHH."' AND
6475
                c_id = $courseId
6476
            LIMIT 1";
6477
6478
    $result = Database::query($sql);
6479
6480
    if (Database::num_rows($result) > 0) {
6481
        // This user has got a recorded state for this course.
6482
        $cuData = Database::fetch_array($result);
6483
        $is_courseMember = true;
6484
        $is_courseAdmin = ($cuData['status'] == 1);
6485
    }
6486
6487
    if (!$is_courseAdmin) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $is_courseAdmin does not seem to be defined for all execution paths leading up to this point.
Loading history...
6488
        // This user has no status related to this course.
6489
        // Is it the session coach or the session admin?
6490
        $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
6491
        $tbl_session_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
6492
        $tbl_session_course_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
6493
6494
        $sql = "SELECT
6495
                    session.id_coach, session_admin_id, session.id
6496
                FROM
6497
                    $tbl_session as session
6498
                INNER JOIN $tbl_session_course
6499
                    ON session_rel_course.session_id = session.id
6500
                    AND session_rel_course.c_id = '$courseId'
6501
                LIMIT 1";
6502
6503
        $result = Database::query($sql);
6504
        $row = Database::store_result($result);
6505
6506
        if ($row[0]['id_coach'] == $userid) {
6507
            $is_courseMember = true;
6508
            $is_courseAdmin = false;
6509
        } elseif ($row[0]['session_admin_id'] == $userid) {
6510
            $is_courseMember = false;
6511
            $is_courseAdmin = false;
6512
        } else {
6513
            // Check if the current user is the course coach.
6514
            $sql = "SELECT 1
6515
                    FROM $tbl_session_course
6516
                    WHERE session_rel_course.c_id = '$courseId'
6517
                    AND session_rel_course.id_coach = '$userid'
6518
                    LIMIT 1";
6519
6520
            $result = Database::query($sql);
6521
6522
            //if ($row = Database::fetch_array($result)) {
6523
            if (Database::num_rows($result) > 0) {
6524
                $is_courseMember = true;
6525
                $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
6526
6527
                $sql = "SELECT status FROM $tbl_user
6528
                        WHERE user_id = $userid
6529
                        LIMIT 1";
6530
6531
                $result = Database::query($sql);
6532
6533
                if (Database::result($result, 0, 0) == 1) {
6534
                    $is_courseAdmin = true;
6535
                } else {
6536
                    $is_courseAdmin = false;
6537
                }
6538
            } else {
6539
                // Check if the user is a student is this session.
6540
                $sql = "SELECT  id
6541
                        FROM $tbl_session_course_user
6542
                        WHERE
6543
                            user_id  = '$userid' AND
6544
                            c_id = '$courseId'
6545
                        LIMIT 1";
6546
6547
                if (Database::num_rows($result) > 0) {
6548
                    // This user haa got a recorded state for this course.
6549
                    while ($row = Database::fetch_array($result)) {
6550
                        $is_courseMember = true;
6551
                        $is_courseAdmin = false;
6552
                    }
6553
                }
6554
            }
6555
        }
6556
    }
6557
6558
    switch ($visibility) {
6559
        case COURSE_VISIBILITY_OPEN_WORLD:
6560
            return true;
6561
        case COURSE_VISIBILITY_OPEN_PLATFORM:
6562
            return isset($userid);
6563
        case COURSE_VISIBILITY_REGISTERED:
6564
        case COURSE_VISIBILITY_CLOSED:
6565
            return $is_platformAdmin || $is_courseMember || $is_courseAdmin;
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $is_courseMember does not seem to be defined for all execution paths leading up to this point.
Loading history...
6566
        case COURSE_VISIBILITY_HIDDEN:
6567
            return $is_platformAdmin;
6568
    }
6569
6570
    return false;
6571
}
6572
6573
/**
6574
 * Returns whether an element (forum, message, survey ...) belongs to a session or not.
6575
 *
6576
 * @param string the tool of the element
6577
 * @param int the element id in database
6578
 * @param int the session_id to compare with element session id
6579
 *
6580
 * @return bool true if the element is in the session, false else
6581
 */
6582
function api_is_element_in_the_session($tool, $element_id, $session_id = null)
6583
{
6584
    if (is_null($session_id)) {
6585
        $session_id = api_get_session_id();
6586
    }
6587
6588
    $element_id = (int) $element_id;
6589
6590
    if (empty($element_id)) {
6591
        return false;
6592
    }
6593
6594
    // Get information to build query depending of the tool.
6595
    switch ($tool) {
6596
        case TOOL_SURVEY:
6597
            $table_tool = Database::get_course_table(TABLE_SURVEY);
6598
            $key_field = 'survey_id';
6599
            break;
6600
        case TOOL_ANNOUNCEMENT:
6601
            $table_tool = Database::get_course_table(TABLE_ANNOUNCEMENT);
6602
            $key_field = 'id';
6603
            break;
6604
        case TOOL_AGENDA:
6605
            $table_tool = Database::get_course_table(TABLE_AGENDA);
6606
            $key_field = 'id';
6607
            break;
6608
        case TOOL_GROUP:
6609
            $table_tool = Database::get_course_table(TABLE_GROUP);
6610
            $key_field = 'id';
6611
            break;
6612
        default:
6613
            return false;
6614
    }
6615
    $course_id = api_get_course_int_id();
6616
6617
    $sql = "SELECT session_id FROM $table_tool
6618
            WHERE c_id = $course_id AND $key_field =  ".$element_id;
6619
    $rs = Database::query($sql);
6620
    if ($element_session_id = Database::result($rs, 0, 0)) {
6621
        if ($element_session_id == intval($session_id)) {
6622
            // The element belongs to the session.
6623
            return true;
6624
        }
6625
    }
6626
6627
    return false;
6628
}
6629
6630
/**
6631
 * Replaces "forbidden" characters in a filename string.
6632
 *
6633
 * @param string $filename
6634
 * @param bool   $treat_spaces_as_hyphens
6635
 *
6636
 * @return string
6637
 */
6638
function api_replace_dangerous_char($filename, $treat_spaces_as_hyphens = true)
6639
{
6640
    // Some non-properly encoded file names can cause the whole file to be
6641
    // skipped when uploaded. Avoid this by detecting the encoding and
6642
    // converting to UTF-8, setting the source as ASCII (a reasonably
6643
    // limited characters set) if nothing could be found (BT#
6644
    $encoding = api_detect_encoding($filename);
6645
    if (empty($encoding)) {
6646
        $encoding = 'ASCII';
6647
        if (!api_is_valid_ascii($filename)) {
6648
            // try iconv and try non standard ASCII a.k.a CP437
6649
            // see BT#15022
6650
            if (function_exists('iconv')) {
6651
                $result = iconv('CP437', 'UTF-8', $filename);
6652
                if (api_is_valid_utf8($result)) {
6653
                    $filename = $result;
6654
                    $encoding = 'UTF-8';
6655
                }
6656
            }
6657
        }
6658
    }
6659
6660
    $filename = api_to_system_encoding($filename, $encoding);
6661
6662
    $url = URLify::filter(
6663
        $filename,
6664
        250,
6665
        '',
6666
        true,
6667
        false,
6668
        false,
6669
        false,
6670
        $treat_spaces_as_hyphens
6671
    );
6672
6673
    // Replace multiple dots at the end.
6674
    $regex = "/\.+$/";
6675
    $url = preg_replace($regex, '', $url);
6676
6677
    return $url;
6678
}
6679
6680
/**
6681
 * Fixes the $_SERVER['REQUEST_URI'] that is empty in IIS6.
6682
 *
6683
 * @author Ivan Tcholakov, 28-JUN-2006.
6684
 */
6685
function api_request_uri()
6686
{
6687
    if (!empty($_SERVER['REQUEST_URI'])) {
6688
        return $_SERVER['REQUEST_URI'];
6689
    }
6690
    $uri = $_SERVER['SCRIPT_NAME'];
6691
    if (!empty($_SERVER['QUERY_STRING'])) {
6692
        $uri .= '?'.$_SERVER['QUERY_STRING'];
6693
    }
6694
    $_SERVER['REQUEST_URI'] = $uri;
6695
6696
    return $uri;
6697
}
6698
6699
/**
6700
 * Gets the current access_url id of the Chamilo Platform.
6701
 *
6702
 * @return int access_url_id of the current Chamilo Installation or 1 if multiple_access_urls is not enabled
6703
 *
6704
 * @author Julio Montoya <[email protected]>
6705
 */
6706
function api_get_current_access_url_id()
6707
{
6708
    if ('cli' === PHP_SAPI) {
6709
        $accessUrlId = api_get_configuration_value('access_url');
6710
        if (!empty($accessUrlId)) {
6711
            return $accessUrlId;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $accessUrlId also could return the type boolean which is incompatible with the documented return type integer.
Loading history...
6712
        }
6713
    }
6714
6715
    static $id;
6716
    if (!empty($id)) {
6717
        return (int) $id;
6718
    }
6719
6720
    if (!api_get_multiple_access_url()) {
6721
        // If the feature is not enabled, assume 1 and return before querying
6722
        // the database
6723
        return 1;
6724
    }
6725
6726
    $table = Database::get_main_table(TABLE_MAIN_ACCESS_URL);
6727
    $path = Database::escape_string(api_get_path(WEB_PATH));
6728
    $sql = "SELECT id FROM $table WHERE url = '".$path."'";
6729
    $result = Database::query($sql);
6730
    if (Database::num_rows($result) > 0) {
6731
        $id = Database::result($result, 0, 0);
6732
        if ($id === false) {
6733
            return -1;
6734
        }
6735
6736
        return (int) $id;
6737
    }
6738
6739
    $id = 1;
6740
6741
    //if the url in WEB_PATH was not found, it can only mean that there is
6742
    // either a configuration problem or the first URL has not been defined yet
6743
    // (by default it is http://localhost/). Thus the more sensible thing we can
6744
    // do is return 1 (the main URL) as the user cannot hack this value anyway
6745
    return 1;
6746
}
6747
6748
/**
6749
 * Gets the registered urls from a given user id.
6750
 *
6751
 * @param int $user_id
6752
 *
6753
 * @return array
6754
 *
6755
 * @author Julio Montoya <[email protected]>
6756
 */
6757
function api_get_access_url_from_user($user_id)
6758
{
6759
    $user_id = (int) $user_id;
6760
    $table_url_rel_user = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
6761
    $table_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL);
6762
    $sql = "SELECT access_url_id
6763
            FROM $table_url_rel_user url_rel_user
6764
            INNER JOIN $table_url u
6765
            ON (url_rel_user.access_url_id = u.id)
6766
            WHERE user_id = ".intval($user_id);
6767
    $result = Database::query($sql);
6768
    $list = [];
6769
    while ($row = Database::fetch_array($result, 'ASSOC')) {
6770
        $list[] = $row['access_url_id'];
6771
    }
6772
6773
    return $list;
6774
}
6775
6776
/**
6777
 * Gets the status of a user in a course.
6778
 *
6779
 * @param int $user_id
6780
 * @param int $courseId
6781
 *
6782
 * @return int user status
6783
 */
6784
function api_get_status_of_user_in_course($user_id, $courseId)
6785
{
6786
    $tbl_rel_course_user = Database::get_main_table(TABLE_MAIN_COURSE_USER);
6787
    if (!empty($user_id) && !empty($courseId)) {
6788
        $user_id = intval($user_id);
6789
        $courseId = intval($courseId);
6790
        $sql = 'SELECT status
6791
                FROM '.$tbl_rel_course_user.'
6792
                WHERE user_id='.$user_id.' AND c_id = '.$courseId;
6793
        $result = Database::query($sql);
6794
        $row_status = Database::fetch_array($result, 'ASSOC');
6795
6796
        return $row_status['status'];
6797
    } else {
6798
        return 0;
6799
    }
6800
}
6801
6802
/**
6803
 * Checks whether the curent user is in a group or not.
6804
 *
6805
 * @param string        The group id - optional (takes it from session if not given)
6806
 * @param string        The course code - optional (no additional check by course if course code is not given)
6807
 *
6808
 * @return bool
6809
 *
6810
 * @author Ivan Tcholakov
6811
 */
6812
function api_is_in_group($groupIdParam = null, $courseCodeParam = null)
6813
{
6814
    if (!empty($courseCodeParam)) {
6815
        $courseCode = api_get_course_id();
6816
        if (!empty($courseCode)) {
6817
            if ($courseCodeParam != $courseCode) {
6818
                return false;
6819
            }
6820
        } else {
6821
            return false;
6822
        }
6823
    }
6824
6825
    $groupId = api_get_group_id();
6826
6827
    if (!empty($groupId)) {
6828
        if (!empty($groupIdParam)) {
6829
            return $groupIdParam == $groupId;
6830
        } else {
6831
            return true;
6832
        }
6833
    }
6834
6835
    return false;
6836
}
6837
6838
/**
6839
 * Checks whether a secret key is valid.
6840
 *
6841
 * @param string $original_key_secret - secret key from (webservice) client
6842
 * @param string $security_key        - security key from Chamilo
6843
 *
6844
 * @return bool - true if secret key is valid, false otherwise
6845
 */
6846
function api_is_valid_secret_key($original_key_secret, $security_key)
6847
{
6848
    if (empty($original_key_secret) || empty($security_key)) {
6849
        return false;
6850
    }
6851
6852
    return (string) $original_key_secret === sha1($security_key);
6853
}
6854
6855
/**
6856
 * Checks whether a user is into course.
6857
 *
6858
 * @param int $course_id - the course id
6859
 * @param int $user_id   - the user id
6860
 *
6861
 * @return bool
6862
 */
6863
function api_is_user_of_course($course_id, $user_id)
6864
{
6865
    $tbl_course_rel_user = Database::get_main_table(TABLE_MAIN_COURSE_USER);
6866
    $sql = 'SELECT user_id FROM '.$tbl_course_rel_user.'
6867
            WHERE
6868
                c_id ="'.intval($course_id).'" AND
6869
                user_id = "'.intval($user_id).'" AND
6870
                relation_type <> '.COURSE_RELATION_TYPE_RRHH.' ';
6871
    $result = Database::query($sql);
6872
6873
    return Database::num_rows($result) == 1;
6874
}
6875
6876
/**
6877
 * Checks whether the server's operating system is Windows (TM).
6878
 *
6879
 * @return bool - true if the operating system is Windows, false otherwise
6880
 */
6881
function api_is_windows_os()
6882
{
6883
    if (function_exists('php_uname')) {
6884
        // php_uname() exists as of PHP 4.0.2, according to the documentation.
6885
        // We expect that this function will always work for Chamilo 1.8.x.
6886
        $os = php_uname();
6887
    }
6888
    // The following methods are not needed, but let them stay, just in case.
6889
    elseif (isset($_ENV['OS'])) {
6890
        // Sometimes $_ENV['OS'] may not be present (bugs?)
6891
        $os = $_ENV['OS'];
6892
    } elseif (defined('PHP_OS')) {
6893
        // PHP_OS means on which OS PHP was compiled, this is why
6894
        // using PHP_OS is the last choice for detection.
6895
        $os = PHP_OS;
6896
    } else {
6897
        return false;
6898
    }
6899
6900
    return strtolower(substr((string) $os, 0, 3)) == 'win';
6901
}
6902
6903
/**
6904
 * This function informs whether the sent request is XMLHttpRequest.
6905
 */
6906
function api_is_xml_http_request()
6907
{
6908
    return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';
6909
}
6910
6911
/**
6912
 * This wrapper function has been implemented for avoiding some known problems about the function getimagesize().
6913
 *
6914
 * @see http://php.net/manual/en/function.getimagesize.php
6915
 * @see http://www.dokeos.com/forum/viewtopic.php?t=12345
6916
 * @see http://www.dokeos.com/forum/viewtopic.php?t=16355
6917
 *
6918
 * @return int
6919
 */
6920
function api_getimagesize($path)
6921
{
6922
    $image = new Image($path);
6923
6924
    return $image->get_image_size();
6925
}
6926
6927
/**
6928
 * This function resizes an image, with preserving its proportions (or aspect ratio).
6929
 *
6930
 * @author Ivan Tcholakov, MAY-2009.
6931
 *
6932
 * @param int $image         System path or URL of the image
6933
 * @param int $target_width  Targeted width
6934
 * @param int $target_height Targeted height
6935
 *
6936
 * @return array Calculated new width and height
6937
 */
6938
function api_resize_image($image, $target_width, $target_height)
6939
{
6940
    $image_properties = api_getimagesize($image);
6941
6942
    return api_calculate_image_size(
6943
        $image_properties['width'],
6944
        $image_properties['height'],
6945
        $target_width,
6946
        $target_height
6947
    );
6948
}
6949
6950
/**
6951
 * This function calculates new image size, with preserving image's proportions (or aspect ratio).
6952
 *
6953
 * @author Ivan Tcholakov, MAY-2009.
6954
 * @author The initial idea has been taken from code by Patrick Cool, MAY-2004.
6955
 *
6956
 * @param int $image_width   Initial width
6957
 * @param int $image_height  Initial height
6958
 * @param int $target_width  Targeted width
6959
 * @param int $target_height Targeted height
6960
 *
6961
 * @return array Calculated new width and height
6962
 */
6963
function api_calculate_image_size(
6964
    $image_width,
6965
    $image_height,
6966
    $target_width,
6967
    $target_height
6968
) {
6969
    // Only maths is here.
6970
    $result = ['width' => $image_width, 'height' => $image_height];
6971
    if ($image_width <= 0 || $image_height <= 0) {
6972
        return $result;
6973
    }
6974
    $resize_factor_width = $target_width / $image_width;
6975
    $resize_factor_height = $target_height / $image_height;
6976
    $delta_width = $target_width - $image_width * $resize_factor_height;
6977
    $delta_height = $target_height - $image_height * $resize_factor_width;
6978
    if ($delta_width > $delta_height) {
6979
        $result['width'] = ceil($image_width * $resize_factor_height);
6980
        $result['height'] = ceil($image_height * $resize_factor_height);
6981
    } elseif ($delta_width < $delta_height) {
6982
        $result['width'] = ceil($image_width * $resize_factor_width);
6983
        $result['height'] = ceil($image_height * $resize_factor_width);
6984
    } else {
6985
        $result['width'] = ceil($target_width);
6986
        $result['height'] = ceil($target_height);
6987
    }
6988
6989
    return $result;
6990
}
6991
6992
/**
6993
 * Returns a list of Chamilo's tools or
6994
 * checks whether a given identificator is a valid Chamilo's tool.
6995
 *
6996
 * @author Isaac flores paz
6997
 *
6998
 * @param string The tool name to filter
6999
 *
7000
 * @return mixed Filtered string or array
7001
 */
7002
function api_get_tools_lists($my_tool = null)
7003
{
7004
    $tools_list = [
7005
        TOOL_DOCUMENT,
7006
        TOOL_THUMBNAIL,
7007
        TOOL_HOTPOTATOES,
7008
        TOOL_CALENDAR_EVENT,
7009
        TOOL_LINK,
7010
        TOOL_COURSE_DESCRIPTION,
7011
        TOOL_SEARCH,
7012
        TOOL_LEARNPATH,
7013
        TOOL_ANNOUNCEMENT,
7014
        TOOL_FORUM,
7015
        TOOL_THREAD,
7016
        TOOL_POST,
7017
        TOOL_DROPBOX,
7018
        TOOL_QUIZ,
7019
        TOOL_USER,
7020
        TOOL_GROUP,
7021
        TOOL_BLOGS,
7022
        TOOL_CHAT,
7023
        TOOL_STUDENTPUBLICATION,
7024
        TOOL_TRACKING,
7025
        TOOL_HOMEPAGE_LINK,
7026
        TOOL_COURSE_SETTING,
7027
        TOOL_BACKUP,
7028
        TOOL_COPY_COURSE_CONTENT,
7029
        TOOL_RECYCLE_COURSE,
7030
        TOOL_COURSE_HOMEPAGE,
7031
        TOOL_COURSE_RIGHTS_OVERVIEW,
7032
        TOOL_UPLOAD,
7033
        TOOL_COURSE_MAINTENANCE,
7034
        TOOL_SURVEY,
7035
        TOOL_WIKI,
7036
        TOOL_GLOSSARY,
7037
        TOOL_GRADEBOOK,
7038
        TOOL_NOTEBOOK,
7039
        TOOL_ATTENDANCE,
7040
        TOOL_COURSE_PROGRESS,
7041
    ];
7042
    if (empty($my_tool)) {
7043
        return $tools_list;
7044
    }
7045
7046
    return in_array($my_tool, $tools_list) ? $my_tool : '';
7047
}
7048
7049
/**
7050
 * Checks whether we already approved the last version term and condition.
7051
 *
7052
 * @param int user id
7053
 *
7054
 * @return bool true if we pass false otherwise
7055
 */
7056
function api_check_term_condition($userId)
7057
{
7058
    if (api_get_setting('allow_terms_conditions') === 'true') {
7059
        // Check if exists terms and conditions
7060
        if (LegalManager::count() == 0) {
7061
            return true;
7062
        }
7063
7064
        $extraFieldValue = new ExtraFieldValue('user');
7065
        $data = $extraFieldValue->get_values_by_handler_and_field_variable(
7066
            $userId,
7067
            'legal_accept'
7068
        );
7069
7070
        if (!empty($data) && isset($data['value']) && !empty($data['value'])) {
7071
            $result = $data['value'];
7072
            $user_conditions = explode(':', $result);
7073
            $version = $user_conditions[0];
7074
            $langId = $user_conditions[1];
7075
            $realVersion = LegalManager::get_last_version($langId);
7076
7077
            return $version >= $realVersion;
7078
        }
7079
7080
        return false;
7081
    }
7082
7083
    return false;
7084
}
7085
7086
/**
7087
 * Gets all information of a tool into course.
7088
 *
7089
 * @param int The tool id
7090
 *
7091
 * @return array
7092
 */
7093
function api_get_tool_information_by_name($name)
7094
{
7095
    $t_tool = Database::get_course_table(TABLE_TOOL_LIST);
7096
    $course_id = api_get_course_int_id();
7097
    $sql = "SELECT * FROM $t_tool
7098
            WHERE c_id = $course_id  AND name = '".Database::escape_string($name)."' ";
7099
    $rs = Database::query($sql);
7100
7101
    return Database::fetch_array($rs, 'ASSOC');
7102
}
7103
7104
/**
7105
 * Function used to protect a "global" admin script.
7106
 * The function blocks access when the user has no global platform admin rights.
7107
 * Global admins are the admins that are registered in the main.admin table
7108
 * AND the users who have access to the "principal" portal.
7109
 * That means that there is a record in the main.access_url_rel_user table
7110
 * with his user id and the access_url_id=1.
7111
 *
7112
 * @author Julio Montoya
7113
 *
7114
 * @param int $user_id
7115
 *
7116
 * @return bool
7117
 */
7118
function api_is_global_platform_admin($user_id = null)
7119
{
7120
    $user_id = (int) $user_id;
7121
    if (empty($user_id)) {
7122
        $user_id = api_get_user_id();
7123
    }
7124
    if (api_is_platform_admin_by_id($user_id)) {
7125
        $urlList = api_get_access_url_from_user($user_id);
7126
        // The admin is registered in the first "main" site with access_url_id = 1
7127
        if (in_array(1, $urlList)) {
7128
            return true;
7129
        } else {
7130
            return false;
7131
        }
7132
    }
7133
7134
    return false;
7135
}
7136
7137
/**
7138
 * @param int  $admin_id_to_check
7139
 * @param int  $my_user_id
7140
 * @param bool $allow_session_admin
7141
 *
7142
 * @return bool
7143
 */
7144
function api_global_admin_can_edit_admin(
7145
    $admin_id_to_check,
7146
    $my_user_id = null,
7147
    $allow_session_admin = false
7148
) {
7149
    if (empty($my_user_id)) {
7150
        $my_user_id = api_get_user_id();
7151
    }
7152
7153
    $iam_a_global_admin = api_is_global_platform_admin($my_user_id);
7154
    $user_is_global_admin = api_is_global_platform_admin($admin_id_to_check);
7155
7156
    if ($iam_a_global_admin) {
7157
        // Global admin can edit everything
7158
        return true;
7159
    } else {
7160
        // If i'm a simple admin
7161
        $is_platform_admin = api_is_platform_admin_by_id($my_user_id);
7162
7163
        if ($allow_session_admin) {
7164
            $is_platform_admin = api_is_platform_admin_by_id($my_user_id) || (api_get_user_status($my_user_id) == SESSIONADMIN);
7165
        }
7166
7167
        if ($is_platform_admin) {
7168
            if ($user_is_global_admin) {
7169
                return false;
7170
            } else {
7171
                return true;
7172
            }
7173
        } else {
7174
            return false;
7175
        }
7176
    }
7177
}
7178
7179
/**
7180
 * @param int  $admin_id_to_check
7181
 * @param int  $my_user_id
7182
 * @param bool $allow_session_admin
7183
 *
7184
 * @return bool|null
7185
 */
7186
function api_protect_super_admin($admin_id_to_check, $my_user_id = null, $allow_session_admin = false)
7187
{
7188
    if (api_global_admin_can_edit_admin($admin_id_to_check, $my_user_id, $allow_session_admin)) {
7189
        return true;
7190
    } else {
7191
        api_not_allowed();
7192
    }
7193
}
7194
7195
/**
7196
 * Function used to protect a global admin script.
7197
 * The function blocks access when the user has no global platform admin rights.
7198
 * See also the api_is_global_platform_admin() function wich defines who's a "global" admin.
7199
 *
7200
 * @author Julio Montoya
7201
 */
7202
function api_protect_global_admin_script()
7203
{
7204
    if (!api_is_global_platform_admin()) {
7205
        api_not_allowed();
7206
7207
        return false;
7208
    }
7209
7210
    return true;
7211
}
7212
7213
/**
7214
 * Get active template.
7215
 *
7216
 * @param string    theme type (optional: default)
7217
 * @param string    path absolute(abs) or relative(rel) (optional:rel)
7218
 *
7219
 * @return string actived template path
7220
 */
7221
function api_get_template($path_type = 'rel')
7222
{
7223
    $path_types = ['rel', 'abs'];
7224
    $template_path = '';
7225
    if (in_array($path_type, $path_types)) {
7226
        if ($path_type == 'rel') {
7227
            $template_path = api_get_path(SYS_TEMPLATE_PATH);
7228
        } else {
7229
            $template_path = api_get_path(WEB_TEMPLATE_PATH);
7230
        }
7231
    }
7232
    $actived_theme = 'default';
7233
    if (api_get_setting('active_template')) {
7234
        $actived_theme = api_get_setting('active_template');
7235
    }
7236
    $actived_theme_path = $template_path.$actived_theme.DIRECTORY_SEPARATOR;
7237
7238
    return $actived_theme_path;
7239
}
7240
7241
/**
7242
 * Check browser support for specific file types or features
7243
 * This function checks if the user's browser supports a file format or given
7244
 * feature, or returns the current browser and major version when
7245
 * $format=check_browser. Only a limited number of formats and features are
7246
 * checked by this method. Make sure you check its definition first.
7247
 *
7248
 * @param string $format Can be a file format (extension like svg, webm, ...) or a feature (like autocapitalize, ...)
7249
 *
7250
 * @return bool or return text array if $format=check_browser
7251
 *
7252
 * @author Juan Carlos Raña Trabado
7253
 */
7254
function api_browser_support($format = '')
7255
{
7256
    $browser = new Browser();
7257
    $current_browser = $browser->getBrowser();
7258
    $a_versiontemp = explode('.', $browser->getVersion());
7259
    $current_majorver = $a_versiontemp[0];
7260
7261
    static $result;
7262
7263
    if (isset($result[$format])) {
7264
        return $result[$format];
7265
    }
7266
7267
    // Native svg support
7268
    if ($format == 'svg') {
7269
        if (($current_browser == 'Internet Explorer' && $current_majorver >= 9) ||
7270
            ($current_browser == 'Firefox' && $current_majorver > 1) ||
7271
            ($current_browser == 'Safari' && $current_majorver >= 4) ||
7272
            ($current_browser == 'Chrome' && $current_majorver >= 1) ||
7273
            ($current_browser == 'Opera' && $current_majorver >= 9)
7274
        ) {
7275
            $result[$format] = true;
7276
7277
            return true;
7278
        } else {
7279
            $result[$format] = false;
7280
7281
            return false;
7282
        }
7283
    } elseif ($format == 'pdf') {
7284
        // native pdf support
7285
        if (($current_browser == 'Chrome' && $current_majorver >= 6) ||
7286
            ('Firefox' === $current_browser && $current_majorver >= 15)
7287
        ) {
7288
            $result[$format] = true;
7289
7290
            return true;
7291
        } else {
7292
            $result[$format] = false;
7293
7294
            return false;
7295
        }
7296
    } elseif ($format == 'tif' || $format == 'tiff') {
7297
        //native tif support
7298
        if ($current_browser == 'Safari' && $current_majorver >= 5) {
7299
            $result[$format] = true;
7300
7301
            return true;
7302
        } else {
7303
            $result[$format] = false;
7304
7305
            return false;
7306
        }
7307
    } elseif ($format == 'ogg' || $format == 'ogx' || $format == 'ogv' || $format == 'oga') {
7308
        //native ogg, ogv,oga support
7309
        if (($current_browser == 'Firefox' && $current_majorver >= 3) ||
7310
            ($current_browser == 'Chrome' && $current_majorver >= 3) ||
7311
            ($current_browser == 'Opera' && $current_majorver >= 9)) {
7312
            $result[$format] = true;
7313
7314
            return true;
7315
        } else {
7316
            $result[$format] = false;
7317
7318
            return false;
7319
        }
7320
    } elseif ($format == 'mpg' || $format == 'mpeg') {
7321
        //native mpg support
7322
        if (($current_browser == 'Safari' && $current_majorver >= 5)) {
7323
            $result[$format] = true;
7324
7325
            return true;
7326
        } else {
7327
            $result[$format] = false;
7328
7329
            return false;
7330
        }
7331
    } elseif ($format == 'mp4') {
7332
        //native mp4 support (TODO: Android, iPhone)
7333
        if ($current_browser == 'Android' || $current_browser == 'iPhone') {
7334
            $result[$format] = true;
7335
7336
            return true;
7337
        } else {
7338
            $result[$format] = false;
7339
7340
            return false;
7341
        }
7342
    } elseif ($format == 'mov') {
7343
        //native mov support( TODO:check iPhone)
7344
        if ($current_browser == 'Safari' && $current_majorver >= 5 || $current_browser == 'iPhone') {
0 ignored issues
show
introduced by
Consider adding parentheses for clarity. Current Interpretation: ($current_browser == 'Sa...ent_browser == 'iPhone', Probably Intended Meaning: $current_browser == 'Saf...nt_browser == 'iPhone')
Loading history...
7345
            $result[$format] = true;
7346
7347
            return true;
7348
        } else {
7349
            $result[$format] = false;
7350
7351
            return false;
7352
        }
7353
    } elseif ($format == 'avi') {
7354
        //native avi support
7355
        if ($current_browser == 'Safari' && $current_majorver >= 5) {
7356
            $result[$format] = true;
7357
7358
            return true;
7359
        } else {
7360
            $result[$format] = false;
7361
7362
            return false;
7363
        }
7364
    } elseif ($format == 'wmv') {
7365
        //native wmv support
7366
        if ($current_browser == 'Firefox' && $current_majorver >= 4) {
7367
            $result[$format] = true;
7368
7369
            return true;
7370
        } else {
7371
            $result[$format] = false;
7372
7373
            return false;
7374
        }
7375
    } elseif ($format == 'webm') {
7376
        //native webm support (TODO:check IE9, Chrome9, Android)
7377
        if (($current_browser == 'Firefox' && $current_majorver >= 4) ||
7378
            ($current_browser == 'Opera' && $current_majorver >= 9) ||
7379
            ($current_browser == 'Internet Explorer' && $current_majorver >= 9) ||
7380
            ($current_browser == 'Chrome' && $current_majorver >= 9) ||
7381
            $current_browser == 'Android'
7382
        ) {
7383
            $result[$format] = true;
7384
7385
            return true;
7386
        } else {
7387
            $result[$format] = false;
7388
7389
            return false;
7390
        }
7391
    } elseif ($format == 'wav') {
7392
        //native wav support (only some codecs !)
7393
        if (($current_browser == 'Firefox' && $current_majorver >= 4) ||
7394
            ($current_browser == 'Safari' && $current_majorver >= 5) ||
7395
            ($current_browser == 'Opera' && $current_majorver >= 9) ||
7396
            ($current_browser == 'Internet Explorer' && $current_majorver >= 9) ||
7397
            ($current_browser == 'Chrome' && $current_majorver > 9) ||
7398
            $current_browser == 'Android' ||
7399
            $current_browser == 'iPhone'
7400
        ) {
7401
            $result[$format] = true;
7402
7403
            return true;
7404
        } else {
7405
            $result[$format] = false;
7406
7407
            return false;
7408
        }
7409
    } elseif ($format == 'mid' || $format == 'kar') {
7410
        //native midi support (TODO:check Android)
7411
        if ($current_browser == 'Opera' && $current_majorver >= 9 || $current_browser == 'Android') {
0 ignored issues
show
introduced by
Consider adding parentheses for clarity. Current Interpretation: ($current_browser == 'Op...nt_browser == 'Android', Probably Intended Meaning: $current_browser == 'Ope...t_browser == 'Android')
Loading history...
7412
            $result[$format] = true;
7413
7414
            return true;
7415
        } else {
7416
            $result[$format] = false;
7417
7418
            return false;
7419
        }
7420
    } elseif ($format == 'wma') {
7421
        //native wma support
7422
        if ($current_browser == 'Firefox' && $current_majorver >= 4) {
7423
            $result[$format] = true;
7424
7425
            return true;
7426
        } else {
7427
            $result[$format] = false;
7428
7429
            return false;
7430
        }
7431
    } elseif ($format == 'au') {
7432
        //native au support
7433
        if ($current_browser == 'Safari' && $current_majorver >= 5) {
7434
            $result[$format] = true;
7435
7436
            return true;
7437
        } else {
7438
            $result[$format] = false;
7439
7440
            return false;
7441
        }
7442
    } elseif ($format == 'mp3') {
7443
        //native mp3 support (TODO:check Android, iPhone)
7444
        if (($current_browser == 'Safari' && $current_majorver >= 5) ||
7445
            ($current_browser == 'Chrome' && $current_majorver >= 6) ||
7446
            ($current_browser == 'Internet Explorer' && $current_majorver >= 9) ||
7447
            $current_browser == 'Android' ||
7448
            $current_browser == 'iPhone' ||
7449
            $current_browser == 'Firefox'
7450
        ) {
7451
            $result[$format] = true;
7452
7453
            return true;
7454
        } else {
7455
            $result[$format] = false;
7456
7457
            return false;
7458
        }
7459
    } elseif ($format == 'autocapitalize') {
7460
        // Help avoiding showing the autocapitalize option if the browser doesn't
7461
        // support it: this attribute is against the HTML5 standard
7462
        if ($current_browser == 'Safari' || $current_browser == 'iPhone') {
7463
            return true;
7464
        } else {
7465
            return false;
7466
        }
7467
    } elseif ($format == "check_browser") {
7468
        $array_check_browser = [$current_browser, $current_majorver];
7469
7470
        return $array_check_browser;
7471
    } else {
7472
        $result[$format] = false;
7473
7474
        return false;
7475
    }
7476
}
7477
7478
/**
7479
 * This function checks if exist path and file browscap.ini
7480
 * In order for this to work, your browscap configuration setting in php.ini
7481
 * must point to the correct location of the browscap.ini file on your system
7482
 * http://php.net/manual/en/function.get-browser.php.
7483
 *
7484
 * @return bool
7485
 *
7486
 * @author Juan Carlos Raña Trabado
7487
 */
7488
function api_check_browscap()
7489
{
7490
    $setting = ini_get('browscap');
7491
    if ($setting) {
7492
        $browser = get_browser($_SERVER['HTTP_USER_AGENT'], true);
7493
        if (strpos($setting, 'browscap.ini') && !empty($browser)) {
7494
            return true;
7495
        }
7496
    }
7497
7498
    return false;
7499
}
7500
7501
/**
7502
 * Returns the <script> HTML tag.
7503
 */
7504
function api_get_js($file)
7505
{
7506
    return '<script src="'.api_get_path(WEB_LIBRARY_PATH).'javascript/'.$file.'"></script>'."\n";
7507
}
7508
7509
/**
7510
 * Returns the <script> HTML tag.
7511
 *
7512
 * @return string
7513
 */
7514
function api_get_asset($file)
7515
{
7516
    return '<script src="'.api_get_path(WEB_PUBLIC_PATH).'assets/'.$file.'"></script>'."\n";
7517
}
7518
7519
/**
7520
 * Returns the <script> HTML tag.
7521
 *
7522
 * @param string $file
7523
 * @param string $media
7524
 *
7525
 * @return string
7526
 */
7527
function api_get_css_asset($file, $media = 'screen')
7528
{
7529
    return '<link href="'.api_get_path(WEB_PUBLIC_PATH).'assets/'.$file.'" rel="stylesheet" media="'.$media.'" type="text/css" />'."\n";
7530
}
7531
7532
/**
7533
 * Returns the <link> HTML tag.
7534
 *
7535
 * @param string $file
7536
 * @param string $media
7537
 */
7538
function api_get_css($file, $media = 'screen')
7539
{
7540
    return '<link href="'.$file.'" rel="stylesheet" media="'.$media.'" type="text/css" />'."\n";
7541
}
7542
7543
/**
7544
 * Returns the js header to include the jquery library.
7545
 */
7546
function api_get_jquery_js()
7547
{
7548
    return api_get_asset('jquery/dist/jquery.min.js');
7549
}
7550
7551
/**
7552
 * Returns the jquery path.
7553
 *
7554
 * @return string
7555
 */
7556
function api_get_jquery_web_path()
7557
{
7558
    return api_get_path(WEB_PUBLIC_PATH).'assets/jquery/dist/jquery.min.js';
7559
}
7560
7561
/**
7562
 * @return string
7563
 */
7564
function api_get_jquery_ui_js_web_path()
7565
{
7566
    return api_get_path(WEB_PUBLIC_PATH).'assets/jquery-ui/jquery-ui.min.js';
7567
}
7568
7569
/**
7570
 * @return string
7571
 */
7572
function api_get_jquery_ui_css_web_path()
7573
{
7574
    return api_get_path(WEB_PUBLIC_PATH).'assets/jquery-ui/themes/smoothness/jquery-ui.min.css';
7575
}
7576
7577
/**
7578
 * Returns the jquery-ui library js headers.
7579
 *
7580
 * @param   bool    add the jqgrid library
7581
 *
7582
 * @return string html tags
7583
 */
7584
function api_get_jquery_ui_js($include_jqgrid = false)
7585
{
7586
    $libraries = [];
7587
    if ($include_jqgrid) {
7588
        $libraries[] = 'jqgrid';
7589
    }
7590
7591
    return api_get_jquery_libraries_js($libraries);
7592
}
7593
7594
function api_get_jqgrid_js()
7595
{
7596
    return api_get_jquery_libraries_js(['jqgrid']);
7597
}
7598
7599
/**
7600
 * Returns the jquery library js and css headers.
7601
 *
7602
 * @param   array   list of jquery libraries supported jquery-ui, jqgrid
7603
 * @param   bool    add the jquery library
7604
 *
7605
 * @return string html tags
7606
 */
7607
function api_get_jquery_libraries_js($libraries)
7608
{
7609
    $js = '';
7610
    $js_path = api_get_path(WEB_LIBRARY_PATH).'javascript/';
7611
7612
    //jqgrid js and css
7613
    if (in_array('jqgrid', $libraries)) {
7614
        $languaje = 'en';
7615
        $platform_isocode = strtolower(api_get_language_isocode());
7616
7617
        //languages supported by jqgrid see files in main/inc/lib/javascript/jqgrid/js/i18n
7618
        $jqgrid_langs = [
7619
            'bg', 'bg1251', 'cat', 'cn', 'cs', 'da', 'de', 'el', 'en', 'es', 'fa', 'fi', 'fr', 'gl', 'he', 'hu', 'is', 'it', 'ja', 'nl', 'no', 'pl', 'pt-br', 'pt', 'ro', 'ru', 'sk', 'sr', 'sv', 'tr', 'ua',
7620
        ];
7621
7622
        if (in_array($platform_isocode, $jqgrid_langs)) {
7623
            $languaje = $platform_isocode;
7624
        }
7625
        //$js .= '<link rel="stylesheet" href="'.$js_path.'jqgrid/css/ui.jqgrid.css" type="text/css">';
7626
        $js .= api_get_css($js_path.'jqgrid/css/ui.jqgrid.css');
7627
        $js .= api_get_js('jqgrid/js/i18n/grid.locale-'.$languaje.'.js');
7628
        $js .= api_get_js('jqgrid/js/jquery.jqGrid.min.js');
7629
    }
7630
7631
    //Document multiple upload funcionality
7632
    if (in_array('jquery-upload', $libraries)) {
7633
        $js .= api_get_asset('blueimp-load-image/js/load-image.all.min.js');
7634
        $js .= api_get_asset('blueimp-canvas-to-blob/js/canvas-to-blob.min.js');
7635
        $js .= api_get_asset('jquery-file-upload/js/jquery.iframe-transport.js');
7636
        $js .= api_get_asset('jquery-file-upload/js/jquery.fileupload.js');
7637
        $js .= api_get_asset('jquery-file-upload/js/jquery.fileupload-process.js');
7638
        $js .= api_get_asset('jquery-file-upload/js/jquery.fileupload-image.js');
7639
        $js .= api_get_asset('jquery-file-upload/js/jquery.fileupload-audio.js');
7640
        $js .= api_get_asset('jquery-file-upload/js/jquery.fileupload-video.js');
7641
        $js .= api_get_asset('jquery-file-upload/js/jquery.fileupload-validate.js');
7642
7643
        $js .= api_get_css(api_get_path(WEB_PUBLIC_PATH).'assets/jquery-file-upload/css/jquery.fileupload.css');
7644
        $js .= api_get_css(api_get_path(WEB_PUBLIC_PATH).'assets/jquery-file-upload/css/jquery.fileupload-ui.css');
7645
    }
7646
7647
    // jquery datepicker
7648
    if (in_array('datepicker', $libraries)) {
7649
        $languaje = 'en-GB';
7650
        $platform_isocode = strtolower(api_get_language_isocode());
7651
7652
        // languages supported by jqgrid see files in main/inc/lib/javascript/jqgrid/js/i18n
7653
        $datapicker_langs = [
7654
            'af', 'ar', 'ar-DZ', 'az', 'bg', 'bs', 'ca', 'cs', 'cy-GB', 'da', 'de', 'el', 'en-AU', 'en-GB', 'en-NZ', 'eo', 'es', 'et', 'eu', 'fa', 'fi', 'fo', 'fr', 'fr-CH', 'gl', 'he', 'hi', 'hr', 'hu', 'hy', 'id', 'is', 'it', 'ja', 'ka', 'kk', 'km', 'ko', 'lb', 'lt', 'lv', 'mk', 'ml', 'ms', 'nl', 'nl-BE', 'no', 'pl', 'pt', 'pt-BR', 'rm', 'ro', 'ru', 'sk', 'sl', 'sq', 'sr', 'sr-SR', 'sv', 'ta', 'th', 'tj', 'tr', 'uk', 'vi', 'zh-CN', 'zh-HK', 'zh-TW',
7655
        ];
7656
        if (in_array($platform_isocode, $datapicker_langs)) {
7657
            $languaje = $platform_isocode;
7658
        }
7659
7660
        $js .= api_get_js('jquery-ui/jquery-ui-i18n.min.js');
7661
        $script = '<script>
7662
        $(function(){
7663
            $.datepicker.setDefaults($.datepicker.regional["'.$languaje.'"]);
7664
            $.datepicker.regional["local"] = $.datepicker.regional["'.$languaje.'"];
7665
        });
7666
        </script>
7667
        ';
7668
        $js .= $script;
7669
    }
7670
7671
    return $js;
7672
}
7673
7674
/**
7675
 * Returns the URL to the course or session, removing the complexity of the URL
7676
 * building piece by piece.
7677
 *
7678
 * This function relies on api_get_course_info()
7679
 *
7680
 * @param string $courseCode The course code - optional (takes it from context if not given)
7681
 * @param int    $sessionId  The session ID  - optional (takes it from context if not given)
7682
 * @param int    $groupId    The group ID - optional (takes it from context if not given)
7683
 *
7684
 * @return string The URL to a course, a session, or empty string if nothing works e.g. https://localhost/courses/ABC/index.php?session_id=3&gidReq=1
7685
 *
7686
 * @author  Julio Montoya <[email protected]>
7687
 */
7688
function api_get_course_url($courseCode = null, $sessionId = null, $groupId = null)
7689
{
7690
    $courseDirectory = '';
7691
    $url = '';
7692
    // If courseCode not set, get context or []
7693
    if (empty($courseCode)) {
7694
        $courseInfo = api_get_course_info();
7695
    } else {
7696
        $courseInfo = api_get_course_info($courseCode);
7697
    }
7698
7699
    // If course defined, get directory, otherwise keep empty string
7700
    if (!empty($courseInfo['directory'])) {
7701
        $courseDirectory = $courseInfo['directory'];
7702
    }
7703
7704
    // If sessionId not set, get context or 0
7705
    if (empty($sessionId)) {
7706
        $sessionId = api_get_session_id();
7707
    }
7708
7709
    // If groupId not set, get context or 0
7710
    if (empty($groupId)) {
7711
        $groupId = api_get_group_id();
7712
    }
7713
7714
    // Build the URL
7715
    if (!empty($courseDirectory)) {
7716
        // directory not empty, so we do have a course
7717
        $url = api_get_path(WEB_COURSE_PATH).$courseDirectory.'/index.php?id_session='.$sessionId.'&gidReq='.$groupId;
7718
    } elseif (!empty($sessionId) && api_get_configuration_value('remove_session_url') !== true) {
7719
        // if the course was unset and the session was set, send directly to the session
7720
        $url = api_get_path(WEB_CODE_PATH).'session/index.php?session_id='.$sessionId;
7721
    }
7722
    // if not valid combination was found, return an empty string
7723
    return $url;
7724
}
7725
7726
/**
7727
 * Check if the current portal has the $_configuration['multiple_access_urls'] parameter on.
7728
 *
7729
 * @return bool true if multi site is enabled
7730
 */
7731
function api_get_multiple_access_url()
7732
{
7733
    global $_configuration;
7734
    if (isset($_configuration['multiple_access_urls']) && $_configuration['multiple_access_urls']) {
7735
        return true;
7736
    }
7737
7738
    return false;
7739
}
7740
7741
/**
7742
 * Just a synonym for api_get_multiple_access_url().
7743
 *
7744
 * @return bool
7745
 */
7746
function api_is_multiple_url_enabled()
7747
{
7748
    return api_get_multiple_access_url();
7749
}
7750
7751
/**
7752
 * Returns a md5 unique id.
7753
 *
7754
 * @todo add more parameters
7755
 */
7756
function api_get_unique_id()
7757
{
7758
    $id = md5(time().uniqid().api_get_user_id().api_get_course_id().api_get_session_id());
7759
7760
    return $id;
7761
}
7762
7763
/**
7764
 * Get home path.
7765
 *
7766
 * @return string
7767
 */
7768
function api_get_home_path()
7769
{
7770
    // FIX : Start the routing determination from central path definition
7771
    $home = api_get_path(SYS_HOME_PATH);
7772
    if (api_get_multiple_access_url()) {
7773
        $access_url_id = api_get_current_access_url_id();
7774
        $url_info = api_get_access_url($access_url_id);
7775
        $url = api_remove_trailing_slash(preg_replace('/https?:\/\//i', '', $url_info['url']));
7776
        $clean_url = api_replace_dangerous_char($url);
7777
        $clean_url = str_replace('/', '-', $clean_url);
7778
        $clean_url .= '/';
7779
        if ($clean_url != 'localhost/') {
7780
            // means that the multiple URL was not well configured we don't rename the $home variable
7781
            return "{$home}{$clean_url}";
7782
        }
7783
    }
7784
7785
    return $home;
7786
}
7787
7788
/**
7789
 * @param int Course id
7790
 * @param int tool id: TOOL_QUIZ, TOOL_FORUM, TOOL_STUDENTPUBLICATION, TOOL_LEARNPATH
7791
 * @param int the item id (tool id, exercise id, lp id)
7792
 *
7793
 * @return bool
7794
 */
7795
function api_resource_is_locked_by_gradebook($item_id, $link_type, $course_code = null)
7796
{
7797
    if (api_is_platform_admin()) {
7798
        return false;
7799
    }
7800
    if (api_get_setting('gradebook_locking_enabled') == 'true') {
7801
        if (empty($course_code)) {
7802
            $course_code = api_get_course_id();
7803
        }
7804
        $table = Database::get_main_table(TABLE_MAIN_GRADEBOOK_LINK);
7805
        $item_id = intval($item_id);
7806
        $link_type = intval($link_type);
7807
        $course_code = Database::escape_string($course_code);
7808
        $sql = "SELECT locked FROM $table
7809
                WHERE locked = 1 AND ref_id = $item_id AND type = $link_type AND course_code = '$course_code' ";
7810
        $result = Database::query($sql);
7811
        if (Database::num_rows($result)) {
7812
            return true;
7813
        }
7814
    }
7815
7816
    return false;
7817
}
7818
7819
/**
7820
 * Blocks a page if the item was added in a gradebook.
7821
 *
7822
 * @param int       exercise id, work id, thread id,
7823
 * @param int       LINK_EXERCISE, LINK_STUDENTPUBLICATION, LINK_LEARNPATH LINK_FORUM_THREAD, LINK_ATTENDANCE
7824
 * see gradebook/lib/be/linkfactory
7825
 * @param string    course code
7826
 *
7827
 * @return false|null
7828
 */
7829
function api_block_course_item_locked_by_gradebook($item_id, $link_type, $course_code = null)
7830
{
7831
    if (api_is_platform_admin()) {
7832
        return false;
7833
    }
7834
7835
    if (api_resource_is_locked_by_gradebook($item_id, $link_type, $course_code)) {
7836
        $message = Display::return_message(get_lang('ResourceLockedByGradebook'), 'warning');
7837
        api_not_allowed(true, $message);
7838
    }
7839
}
7840
7841
/**
7842
 * Checks the PHP version installed is enough to run Chamilo.
7843
 *
7844
 * @param string Include path (used to load the error page)
7845
 */
7846
function api_check_php_version($my_inc_path = null)
7847
{
7848
    if (!function_exists('version_compare') || version_compare(phpversion(), REQUIRED_PHP_VERSION, '<')) {
7849
        $global_error_code = 1;
7850
        // Incorrect PHP version
7851
        $global_page = $my_inc_path.'global_error_message.inc.php';
7852
        if (file_exists($global_page)) {
7853
            require $global_page;
7854
        }
7855
        exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

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

Loading history...
7856
    }
7857
}
7858
7859
/**
7860
 * Checks whether the Archive directory is present and writeable. If not,
7861
 * prints a warning message.
7862
 */
7863
function api_check_archive_dir()
7864
{
7865
    if (is_dir(api_get_path(SYS_ARCHIVE_PATH)) && !is_writable(api_get_path(SYS_ARCHIVE_PATH))) {
7866
        $message = Display::return_message(get_lang('ArchivesDirectoryNotWriteableContactAdmin'), 'warning');
7867
        api_not_allowed(true, $message);
7868
    }
7869
}
7870
7871
/**
7872
 * Returns an array of global configuration settings which should be ignored
7873
 * when printing the configuration settings screens.
7874
 *
7875
 * @return array Array of strings, each identifying one of the excluded settings
7876
 */
7877
function api_get_locked_settings()
7878
{
7879
    return [
7880
        'server_type',
7881
        'permanently_remove_deleted_files',
7882
        'account_valid_duration',
7883
        'service_ppt2lp',
7884
        'wcag_anysurfer_public_pages',
7885
        'upload_extensions_list_type',
7886
        'upload_extensions_blacklist',
7887
        'upload_extensions_whitelist',
7888
        'upload_extensions_skip',
7889
        'upload_extensions_replace_by',
7890
        'hide_dltt_markup',
7891
        'split_users_upload_directory',
7892
        'permissions_for_new_directories',
7893
        'permissions_for_new_files',
7894
        'platform_charset',
7895
        'ldap_description',
7896
        'cas_activate',
7897
        'cas_server',
7898
        'cas_server_uri',
7899
        'cas_port',
7900
        'cas_protocol',
7901
        'cas_add_user_activate',
7902
        'update_user_info_cas_with_ldap',
7903
        'languagePriority1',
7904
        'languagePriority2',
7905
        'languagePriority3',
7906
        'languagePriority4',
7907
        'login_is_email',
7908
        'chamilo_database_version',
7909
    ];
7910
}
7911
7912
/**
7913
 * Checks if the user is corrently logged in. Returns the user ID if he is, or
7914
 * false if he isn't. If the user ID is given and is an integer, then the same
7915
 * ID is simply returned.
7916
 *
7917
 * @param  int User ID
7918
 *
7919
 * @return bool Integer User ID is logged in, or false otherwise
7920
 */
7921
function api_user_is_login($user_id = null)
7922
{
7923
    $user_id = empty($user_id) ? api_get_user_id() : (int) $user_id;
7924
7925
    return $user_id && !api_is_anonymous();
7926
}
7927
7928
/**
7929
 * Guess the real ip for register in the database, even in reverse proxy cases.
7930
 * To be recognized, the IP has to be found in either $_SERVER['REMOTE_ADDR'] or
7931
 * in $_SERVER['HTTP_X_FORWARDED_FOR'], which is in common use with rproxies.
7932
 * Note: the result of this function is not SQL-safe. Please escape it before
7933
 * inserting in a database.
7934
 *
7935
 * @return string the user's real ip (unsafe - escape it before inserting to db)
7936
 *
7937
 * @author Jorge Frisancho Jibaja <[email protected]>, USIL - Some changes to allow the use of real IP using reverse proxy
7938
 *
7939
 * @version CEV CHANGE 24APR2012
7940
 */
7941
function api_get_real_ip()
7942
{
7943
    $ip = trim($_SERVER['REMOTE_ADDR']);
7944
    if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
7945
        if (preg_match('/,/', $_SERVER['HTTP_X_FORWARDED_FOR'])) {
7946
            @list($ip1, $ip2) = @explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
7947
        } else {
7948
            $ip1 = $_SERVER['HTTP_X_FORWARDED_FOR'];
7949
        }
7950
        $ip = trim($ip1);
7951
    }
7952
7953
    return $ip;
7954
}
7955
7956
/**
7957
 * Checks whether an IP is included inside an IP range.
7958
 *
7959
 * @param string IP address
7960
 * @param string IP range
7961
 * @param string $ip
7962
 *
7963
 * @return bool True if IP is in the range, false otherwise
7964
 *
7965
 * @author claudiu at cnixs dot com  on http://www.php.net/manual/fr/ref.network.php#55230
7966
 * @author Yannick Warnier for improvements and managment of multiple ranges
7967
 *
7968
 * @todo check for IPv6 support
7969
 */
7970
function api_check_ip_in_range($ip, $range)
7971
{
7972
    if (empty($ip) or empty($range)) {
7973
        return false;
7974
    }
7975
    $ip_ip = ip2long($ip);
7976
    // divide range param into array of elements
7977
    if (strpos($range, ',') !== false) {
7978
        $ranges = explode(',', $range);
7979
    } else {
7980
        $ranges = [$range];
7981
    }
7982
    foreach ($ranges as $range) {
0 ignored issues
show
introduced by
$range is overwriting one of the parameters of this function.
Loading history...
7983
        $range = trim($range);
7984
        if (empty($range)) {
7985
            continue;
7986
        }
7987
        if (strpos($range, '/') === false) {
7988
            if (strcmp($ip, $range) === 0) {
7989
                return true; // there is a direct IP match, return OK
7990
            }
7991
            continue; //otherwise, get to the next range
7992
        }
7993
        // the range contains a "/", so analyse completely
7994
        list($net, $mask) = explode("/", $range);
7995
7996
        $ip_net = ip2long($net);
7997
        // mask binary magic
7998
        $ip_mask = ~((1 << (32 - $mask)) - 1);
7999
8000
        $ip_ip_net = $ip_ip & $ip_mask;
8001
        if ($ip_ip_net == $ip_net) {
8002
            return true;
8003
        }
8004
    }
8005
8006
    return false;
8007
}
8008
8009
function api_check_user_access_to_legal($courseInfo)
8010
{
8011
    if (empty($courseInfo)) {
8012
        return false;
8013
    }
8014
8015
    $visibility = (int) $courseInfo['visibility'];
8016
    $visibilityList = [COURSE_VISIBILITY_OPEN_WORLD, COURSE_VISIBILITY_OPEN_PLATFORM];
8017
8018
    return
8019
        in_array($visibility, $visibilityList) ||
8020
        api_is_drh() ||
8021
        (COURSE_VISIBILITY_REGISTERED === $visibility && 1 === (int) $courseInfo['subscribe']);
8022
}
8023
8024
/**
8025
 * Checks if the global chat is enabled or not.
8026
 *
8027
 * @return bool
8028
 */
8029
function api_is_global_chat_enabled()
8030
{
8031
    return
8032
        !api_is_anonymous() &&
8033
        api_get_setting('allow_global_chat') === 'true' &&
8034
        api_get_setting('allow_social_tool') === 'true';
8035
}
8036
8037
/**
8038
 * @todo Fix tool_visible_by_default_at_creation labels
8039
 *
8040
 * @param int   $item_id
8041
 * @param int   $tool_id
8042
 * @param int   $group_id   id
8043
 * @param array $courseInfo
8044
 * @param int   $sessionId
8045
 * @param int   $userId
8046
 */
8047
function api_set_default_visibility(
8048
    $item_id,
8049
    $tool_id,
8050
    $group_id = 0,
8051
    $courseInfo = [],
8052
    $sessionId = 0,
8053
    $userId = 0
8054
) {
8055
    $courseInfo = empty($courseInfo) ? api_get_course_info() : $courseInfo;
8056
    $courseId = $courseInfo['real_id'];
8057
    $courseCode = $courseInfo['code'];
8058
    $sessionId = empty($sessionId) ? api_get_session_id() : $sessionId;
8059
    $userId = empty($userId) ? api_get_user_id() : $userId;
8060
8061
    // if group is null force group_id = 0, this force is needed to create a LP folder with group = 0
8062
    if (is_null($group_id)) {
8063
        $group_id = 0;
8064
    } else {
8065
        $group_id = empty($group_id) ? api_get_group_id() : $group_id;
8066
    }
8067
8068
    $groupInfo = [];
8069
    if (!empty($group_id)) {
8070
        $groupInfo = GroupManager::get_group_properties($group_id);
8071
    }
8072
    $original_tool_id = $tool_id;
8073
8074
    switch ($tool_id) {
8075
        case TOOL_LINK:
8076
        case TOOL_LINK_CATEGORY:
8077
            $tool_id = 'links';
8078
            break;
8079
        case TOOL_DOCUMENT:
8080
            $tool_id = 'documents';
8081
            break;
8082
        case TOOL_LEARNPATH:
8083
            $tool_id = 'learning';
8084
            break;
8085
        case TOOL_ANNOUNCEMENT:
8086
            $tool_id = 'announcements';
8087
            break;
8088
        case TOOL_FORUM:
8089
        case TOOL_FORUM_CATEGORY:
8090
        case TOOL_FORUM_THREAD:
8091
            $tool_id = 'forums';
8092
            break;
8093
        case TOOL_QUIZ:
8094
            $tool_id = 'quiz';
8095
            break;
8096
    }
8097
    $setting = api_get_setting('tool_visible_by_default_at_creation');
8098
8099
    if (isset($setting[$tool_id])) {
8100
        $visibility = 'invisible';
8101
        if ($setting[$tool_id] == 'true') {
8102
            $visibility = 'visible';
8103
        }
8104
8105
        // Read the portal and course default visibility
8106
        if ($tool_id === 'documents') {
8107
            $visibility = DocumentManager::getDocumentDefaultVisibility($courseInfo);
8108
        }
8109
8110
        api_item_property_update(
8111
            $courseInfo,
8112
            $original_tool_id,
8113
            $item_id,
8114
            $visibility,
8115
            $userId,
8116
            $groupInfo,
8117
            null,
8118
            null,
8119
            null,
8120
            $sessionId
8121
        );
8122
8123
        // Fixes default visibility for tests
8124
        switch ($original_tool_id) {
8125
            case TOOL_QUIZ:
8126
                if (empty($sessionId)) {
8127
                    $objExerciseTmp = new Exercise($courseId);
8128
                    $objExerciseTmp->read($item_id);
8129
                    if ($visibility == 'visible') {
8130
                        $objExerciseTmp->enable();
8131
                        $objExerciseTmp->save();
8132
                    } else {
8133
                        $objExerciseTmp->disable();
8134
                        $objExerciseTmp->save();
8135
                    }
8136
                }
8137
                break;
8138
        }
8139
    }
8140
}
8141
8142
/**
8143
 * @return string
8144
 */
8145
function api_get_security_key()
8146
{
8147
    return api_get_configuration_value('security_key');
0 ignored issues
show
Bug Best Practice introduced by
The expression return api_get_configura...n_value('security_key') also could return the type boolean which is incompatible with the documented return type string.
Loading history...
8148
}
8149
8150
/**
8151
 * @param int $user_id
8152
 * @param int $courseId
8153
 * @param int $session_id
8154
 *
8155
 * @return array
8156
 */
8157
function api_detect_user_roles($user_id, $courseId, $session_id = 0)
8158
{
8159
    $user_roles = [];
8160
    $courseInfo = api_get_course_info_by_id($courseId);
8161
    $course_code = $courseInfo['code'];
8162
8163
    $url_id = api_get_current_access_url_id();
8164
    if (api_is_platform_admin_by_id($user_id, $url_id)) {
8165
        $user_roles[] = PLATFORM_ADMIN;
8166
    }
8167
8168
    /*if (api_is_drh()) {
8169
        $user_roles[] = DRH;
8170
    }*/
8171
8172
    if (!empty($session_id)) {
8173
        if (SessionManager::user_is_general_coach($user_id, $session_id)) {
8174
            $user_roles[] = SESSION_GENERAL_COACH;
8175
        }
8176
    }
8177
8178
    if (!empty($course_code)) {
8179
        if (empty($session_id)) {
8180
            if (CourseManager::is_course_teacher($user_id, $course_code)) {
8181
                $user_roles[] = COURSEMANAGER;
8182
            }
8183
            if (CourseManager::get_tutor_in_course_status($user_id, $courseInfo['real_id'])) {
8184
                $user_roles[] = COURSE_TUTOR;
8185
            }
8186
8187
            if (CourseManager::is_user_subscribed_in_course($user_id, $course_code)) {
8188
                $user_roles[] = COURSE_STUDENT;
8189
            }
8190
        } else {
8191
            $user_status_in_session = SessionManager::get_user_status_in_course_session(
8192
                $user_id,
8193
                $courseId,
8194
                $session_id
8195
            );
8196
8197
            if (!empty($user_status_in_session)) {
8198
                if ($user_status_in_session == 0) {
8199
                    $user_roles[] = SESSION_STUDENT;
8200
                }
8201
                if ($user_status_in_session == 2) {
8202
                    $user_roles[] = SESSION_COURSE_COACH;
8203
                }
8204
            }
8205
8206
            /*if (api_is_course_session_coach($user_id, $course_code, $session_id)) {
8207
               $user_roles[] = SESSION_COURSE_COACH;
8208
            }*/
8209
        }
8210
    }
8211
8212
    return $user_roles;
8213
}
8214
8215
/**
8216
 * @param int $courseId
8217
 * @param int $session_id
8218
 *
8219
 * @return bool
8220
 */
8221
function api_coach_can_edit_view_results($courseId = null, $session_id = null)
8222
{
8223
    if (api_is_platform_admin()) {
8224
        return true;
8225
    }
8226
8227
    $user_id = api_get_user_id();
8228
8229
    if (empty($courseId)) {
8230
        $courseId = api_get_course_int_id();
8231
    }
8232
8233
    if (empty($session_id)) {
8234
        $session_id = api_get_session_id();
8235
    }
8236
8237
    $roles = api_detect_user_roles($user_id, $courseId, $session_id);
8238
8239
    if (in_array(SESSION_COURSE_COACH, $roles)) {
8240
        //return api_get_setting('session_tutor_reports_visibility') == 'true';
8241
        return true;
8242
    } else {
8243
        if (in_array(COURSEMANAGER, $roles)) {
8244
            return true;
8245
        }
8246
8247
        return false;
8248
    }
8249
}
8250
8251
/**
8252
 * @param string $file
8253
 *
8254
 * @return string
8255
 */
8256
function api_get_js_simple($file)
8257
{
8258
    return '<script src="'.$file.'"></script>'."\n";
8259
}
8260
8261
function api_set_settings_and_plugins()
8262
{
8263
    global $_configuration;
8264
    $_setting = [];
8265
    $_plugins = [];
8266
8267
    // access_url == 1 is the default chamilo location
8268
    $settings_by_access_list = [];
8269
    $access_url_id = api_get_current_access_url_id();
8270
    if ($access_url_id != 1) {
8271
        $url_info = api_get_access_url($_configuration['access_url']);
8272
        if ($url_info['active'] == 1) {
8273
            $settings_by_access = &api_get_settings(null, 'list', $_configuration['access_url'], 1);
8274
            foreach ($settings_by_access as &$row) {
8275
                if (empty($row['variable'])) {
8276
                    $row['variable'] = 0;
8277
                }
8278
                if (empty($row['subkey'])) {
8279
                    $row['subkey'] = 0;
8280
                }
8281
                if (empty($row['category'])) {
8282
                    $row['category'] = 0;
8283
                }
8284
                $settings_by_access_list[$row['variable']][$row['subkey']][$row['category']] = $row;
8285
            }
8286
        }
8287
    }
8288
8289
    $result = api_get_settings(null, 'list', 1);
8290
8291
    foreach ($result as &$row) {
8292
        if ($access_url_id != 1) {
8293
            if ($url_info['active'] == 1) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $url_info does not seem to be defined for all execution paths leading up to this point.
Loading history...
8294
                $var = empty($row['variable']) ? 0 : $row['variable'];
8295
                $subkey = empty($row['subkey']) ? 0 : $row['subkey'];
8296
                $category = empty($row['category']) ? 0 : $row['category'];
8297
            }
8298
8299
            if ($row['access_url_changeable'] == 1 && $url_info['active'] == 1) {
8300
                if (isset($settings_by_access_list[$var]) &&
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $var does not seem to be defined for all execution paths leading up to this point.
Loading history...
8301
                    $settings_by_access_list[$var][$subkey][$category]['selected_value'] != '') {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $category does not seem to be defined for all execution paths leading up to this point.
Loading history...
Comprehensibility Best Practice introduced by
The variable $subkey does not seem to be defined for all execution paths leading up to this point.
Loading history...
8302
                    if ($row['subkey'] == null) {
8303
                        $_setting[$row['variable']] = $settings_by_access_list[$var][$subkey][$category]['selected_value'];
8304
                    } else {
8305
                        $_setting[$row['variable']][$row['subkey']] = $settings_by_access_list[$var][$subkey][$category]['selected_value'];
8306
                    }
8307
                } else {
8308
                    if ($row['subkey'] == null) {
8309
                        $_setting[$row['variable']] = $row['selected_value'];
8310
                    } else {
8311
                        $_setting[$row['variable']][$row['subkey']] = $row['selected_value'];
8312
                    }
8313
                }
8314
            } else {
8315
                if ($row['subkey'] == null) {
8316
                    $_setting[$row['variable']] = $row['selected_value'];
8317
                } else {
8318
                    $_setting[$row['variable']][$row['subkey']] = $row['selected_value'];
8319
                }
8320
            }
8321
        } else {
8322
            if ($row['subkey'] == null) {
8323
                $_setting[$row['variable']] = $row['selected_value'];
8324
            } else {
8325
                $_setting[$row['variable']][$row['subkey']] = $row['selected_value'];
8326
            }
8327
        }
8328
    }
8329
8330
    $result = api_get_settings('Plugins', 'list', $access_url_id);
8331
    $_plugins = [];
8332
    foreach ($result as &$row) {
8333
        $key = &$row['variable'];
8334
        if (is_string($_setting[$key])) {
8335
            $_setting[$key] = [];
8336
        }
8337
        $_setting[$key][] = $row['selected_value'];
8338
        $_plugins[$key][] = $row['selected_value'];
8339
    }
8340
8341
    $_SESSION['_setting'] = $_setting;
8342
    $_SESSION['_plugins'] = $_plugins;
8343
}
8344
8345
/**
8346
 * Modify default memory_limit and max_execution_time limits
8347
 * Needed when processing long tasks.
8348
 */
8349
function api_set_more_memory_and_time_limits()
8350
{
8351
    if (function_exists('ini_set')) {
8352
        api_set_memory_limit('2048M');
8353
        ini_set('max_execution_time', 3600);
8354
    }
8355
}
8356
8357
/**
8358
 * Tries to set memory limit, if authorized and new limit is higher than current.
8359
 *
8360
 * @param string $mem New memory limit
8361
 *
8362
 * @return bool True on success, false on failure or current is higher than suggested
8363
 * @assert (null) === false
8364
 * @assert (-1) === false
8365
 * @assert (0) === true
8366
 * @assert ('1G') === true
8367
 */
8368
function api_set_memory_limit($mem)
8369
{
8370
    //if ini_set() not available, this function is useless
8371
    if (!function_exists('ini_set') || is_null($mem) || $mem == -1) {
8372
        return false;
8373
    }
8374
8375
    $memory_limit = ini_get('memory_limit');
8376
    if (api_get_bytes_memory_limit($mem) > api_get_bytes_memory_limit($memory_limit)) {
8377
        ini_set('memory_limit', $mem);
8378
8379
        return true;
8380
    }
8381
8382
    return false;
8383
}
8384
8385
/**
8386
 * Gets memory limit in bytes.
8387
 *
8388
 * @param string The memory size (128M, 1G, 1000K, etc)
8389
 *
8390
 * @return int
8391
 * @assert (null) === false
8392
 * @assert ('1t')  === 1099511627776
8393
 * @assert ('1g')  === 1073741824
8394
 * @assert ('1m')  === 1048576
8395
 * @assert ('100k') === 102400
8396
 */
8397
function api_get_bytes_memory_limit($mem)
8398
{
8399
    $size = strtolower(substr($mem, -1));
8400
8401
    switch ($size) {
8402
        case 't':
8403
            $mem = intval(substr($mem, -1)) * 1024 * 1024 * 1024 * 1024;
8404
            break;
8405
        case 'g':
8406
            $mem = intval(substr($mem, 0, -1)) * 1024 * 1024 * 1024;
8407
            break;
8408
        case 'm':
8409
            $mem = intval(substr($mem, 0, -1)) * 1024 * 1024;
8410
            break;
8411
        case 'k':
8412
            $mem = intval(substr($mem, 0, -1)) * 1024;
8413
            break;
8414
        default:
8415
            // we assume it's integer only
8416
            $mem = intval($mem);
8417
            break;
8418
    }
8419
8420
    return $mem;
8421
}
8422
8423
/**
8424
 * Finds all the information about a user from username instead of user id.
8425
 *
8426
 * @param string $officialCode
8427
 *
8428
 * @return array $user_info user_id, lastname, firstname, username, email, ...
8429
 *
8430
 * @author Yannick Warnier <[email protected]>
8431
 */
8432
function api_get_user_info_from_official_code($officialCode)
8433
{
8434
    if (empty($officialCode)) {
8435
        return false;
8436
    }
8437
    $sql = "SELECT * FROM ".Database::get_main_table(TABLE_MAIN_USER)."
8438
            WHERE official_code ='".Database::escape_string($officialCode)."'";
8439
    $result = Database::query($sql);
8440
    if (Database::num_rows($result) > 0) {
8441
        $result_array = Database::fetch_array($result);
8442
8443
        return _api_format_user($result_array);
8444
    }
8445
8446
    return false;
8447
}
8448
8449
/**
8450
 * @param string $usernameInputId
8451
 * @param string $passwordInputId
8452
 *
8453
 * @return string|null
8454
 */
8455
function api_get_password_checker_js($usernameInputId, $passwordInputId)
8456
{
8457
    $checkPass = api_get_setting('allow_strength_pass_checker');
8458
    $useStrengthPassChecker = $checkPass === 'true';
8459
8460
    if ($useStrengthPassChecker === false) {
8461
        return null;
8462
    }
8463
8464
    $translations = [
8465
        'wordLength' => get_lang('PasswordIsTooShort'),
8466
        'wordNotEmail' => get_lang('YourPasswordCannotBeTheSameAsYourEmail'),
8467
        'wordSimilarToUsername' => get_lang('YourPasswordCannotContainYourUsername'),
8468
        'wordTwoCharacterClasses' => get_lang('WordTwoCharacterClasses'),
8469
        'wordRepetitions' => get_lang('TooManyRepetitions'),
8470
        'wordSequences' => get_lang('YourPasswordContainsSequences'),
8471
        'errorList' => get_lang('ErrorsFound'),
8472
        'veryWeak' => get_lang('PasswordVeryWeak'),
8473
        'weak' => get_lang('PasswordWeak'),
8474
        'normal' => get_lang('PasswordNormal'),
8475
        'medium' => get_lang('PasswordMedium'),
8476
        'strong' => get_lang('PasswordStrong'),
8477
        'veryStrong' => get_lang('PasswordVeryStrong'),
8478
    ];
8479
8480
    $js = api_get_asset('pwstrength-bootstrap/dist/pwstrength-bootstrap.min.js');
8481
    $js .= "<script>
8482
    var errorMessages = {
8483
        password_to_short : \"".get_lang('PasswordIsTooShort')."\",
8484
        same_as_username : \"".get_lang('YourPasswordCannotBeTheSameAsYourUsername')."\"
8485
    };
8486
8487
    $(function() {
8488
        var lang = ".json_encode($translations).";
8489
        var options = {
8490
            common: {
8491
                onLoad: function () {
8492
                    //$('#messages').text('Start typing password');
8493
8494
                    var inputGroup = $('".$passwordInputId."').parents('.input-group');
8495
8496
                    if (inputGroup.length > 0) {
8497
                        inputGroup.find('.progress').insertAfter(inputGroup);
8498
                    }
8499
                }
8500
            },
8501
            ui: {
8502
                showVerdictsInsideProgressBar: true
8503
            },
8504
            onKeyUp: function (evt) {
8505
                $(evt.target).pwstrength('outputErrorList');
8506
            },
8507
            errorMessages : errorMessages,
8508
            viewports: {
8509
                progress: '#password_progress',
8510
                verdict: '#password-verdict',
8511
                errors: '#password-errors'
8512
            },
8513
            usernameField: '$usernameInputId'
8514
        };
8515
        options.i18n = {
8516
            t: function (key) {
8517
                var result = lang[key];
8518
                return result === key ? '' : result; // This assumes you return the
8519
            }
8520
        };
8521
        $('".$passwordInputId."').pwstrength(options);
8522
    });
8523
    </script>";
8524
8525
    return $js;
8526
}
8527
8528
/**
8529
 * create an user extra field called 'captcha_blocked_until_date'.
8530
 *
8531
 * @param string $username
8532
 *
8533
 * @return bool
8534
 */
8535
function api_block_account_captcha($username)
8536
{
8537
    $userInfo = api_get_user_info_from_username($username);
8538
    if (empty($userInfo)) {
8539
        return false;
8540
    }
8541
    $minutesToBlock = api_get_setting('captcha_time_to_block');
8542
    $time = time() + $minutesToBlock * 60;
8543
    UserManager::update_extra_field_value(
8544
        $userInfo['user_id'],
8545
        'captcha_blocked_until_date',
8546
        api_get_utc_datetime($time)
8547
    );
8548
8549
    return true;
8550
}
8551
8552
/**
8553
 * @param string $username
8554
 *
8555
 * @return bool
8556
 */
8557
function api_clean_account_captcha($username)
8558
{
8559
    $userInfo = api_get_user_info_from_username($username);
8560
    if (empty($userInfo)) {
8561
        return false;
8562
    }
8563
    Session::erase('loginFailedCount');
8564
    UserManager::update_extra_field_value(
8565
        $userInfo['user_id'],
8566
        'captcha_blocked_until_date',
8567
        null
8568
    );
8569
8570
    return true;
8571
}
8572
8573
/**
8574
 * @param string $username
8575
 *
8576
 * @return bool
8577
 */
8578
function api_get_user_blocked_by_captcha($username)
8579
{
8580
    $userInfo = api_get_user_info_from_username($username);
8581
    if (empty($userInfo)) {
8582
        return false;
8583
    }
8584
    $data = UserManager::get_extra_user_data_by_field(
8585
        $userInfo['user_id'],
8586
        'captcha_blocked_until_date'
8587
    );
8588
    if (isset($data) && isset($data['captcha_blocked_until_date'])) {
8589
        return $data['captcha_blocked_until_date'];
8590
    }
8591
8592
    return false;
8593
}
8594
8595
/**
8596
 * Remove tags from HTML anf return the $in_number_char first non-HTML char
8597
 * Postfix the text with "..." if it has been truncated.
8598
 *
8599
 * @param string $text
8600
 * @param int    $number
8601
 *
8602
 * @return string
8603
 *
8604
 * @author hubert borderiou
8605
 */
8606
function api_get_short_text_from_html($text, $number)
8607
{
8608
    // Delete script and style tags
8609
    $text = preg_replace('/(<(script|style)\b[^>]*>).*?(<\/\2>)/is', "$1$3", $text);
8610
    $text = api_html_entity_decode($text);
8611
    $out_res = api_remove_tags_with_space($text, false);
8612
    $postfix = "...";
8613
    if (strlen($out_res) > $number) {
8614
        $out_res = substr($out_res, 0, $number).$postfix;
8615
    }
8616
8617
    return $out_res;
8618
}
8619
8620
/**
8621
 * Replace tags with a space in a text.
8622
 * If $in_double_quote_replace, replace " with '' (for HTML attribute purpose, for exemple).
8623
 *
8624
 * @return string
8625
 *
8626
 * @author hubert borderiou
8627
 */
8628
function api_remove_tags_with_space($in_html, $in_double_quote_replace = true)
8629
{
8630
    $out_res = $in_html;
8631
    if ($in_double_quote_replace) {
8632
        $out_res = str_replace('"', "''", $out_res);
8633
    }
8634
    // avoid text stuck together when tags are removed, adding a space after >
8635
    $out_res = str_replace(">", "> ", $out_res);
8636
    $out_res = strip_tags($out_res);
8637
8638
    return $out_res;
8639
}
8640
8641
/**
8642
 * If true, the drh can access all content (courses, users) inside a session.
8643
 *
8644
 * @return bool
8645
 */
8646
function api_drh_can_access_all_session_content()
8647
{
8648
    return api_get_setting('drh_can_access_all_session_content') === 'true';
8649
}
8650
8651
/**
8652
 * @param string $tool
8653
 * @param string $setting
8654
 * @param int    $defaultValue
8655
 *
8656
 * @return string
8657
 */
8658
function api_get_default_tool_setting($tool, $setting, $defaultValue)
8659
{
8660
    global $_configuration;
8661
    if (isset($_configuration[$tool]) &&
8662
        isset($_configuration[$tool]['default_settings']) &&
8663
        isset($_configuration[$tool]['default_settings'][$setting])
8664
    ) {
8665
        return $_configuration[$tool]['default_settings'][$setting];
8666
    }
8667
8668
    return $defaultValue;
8669
}
8670
8671
/**
8672
 * Checks if user can login as another user.
8673
 *
8674
 * @param int $loginAsUserId the user id to log in
8675
 * @param int $userId        my user id
8676
 *
8677
 * @return bool
8678
 */
8679
function api_can_login_as($loginAsUserId, $userId = null)
8680
{
8681
    if (empty($userId)) {
8682
        $userId = api_get_user_id();
8683
    }
8684
    if ($loginAsUserId == $userId) {
8685
        return false;
8686
    }
8687
8688
    if (empty($loginAsUserId)) {
8689
        return false;
8690
    }
8691
8692
    if ($loginAsUserId != strval(intval($loginAsUserId))) {
8693
        return false;
8694
    }
8695
8696
    // Check if the user to login is an admin
8697
    if (api_is_platform_admin_by_id($loginAsUserId)) {
8698
        // Only super admins can login to admin accounts
8699
        if (!api_global_admin_can_edit_admin($loginAsUserId)) {
8700
            return false;
8701
        }
8702
    }
8703
8704
    $userInfo = api_get_user_info($loginAsUserId);
8705
    $isDrh = function () use ($loginAsUserId) {
8706
        if (api_is_drh()) {
8707
            if (api_drh_can_access_all_session_content()) {
8708
                $users = SessionManager::getAllUsersFromCoursesFromAllSessionFromStatus(
8709
                    'drh_all',
8710
                    api_get_user_id()
8711
                );
8712
                $userList = [];
8713
                if (is_array($users)) {
8714
                    foreach ($users as $user) {
8715
                        $userList[] = $user['user_id'];
8716
                    }
8717
                }
8718
                if (in_array($loginAsUserId, $userList)) {
8719
                    return true;
8720
                }
8721
            } else {
8722
                if (api_is_drh() &&
8723
                    UserManager::is_user_followed_by_drh($loginAsUserId, api_get_user_id())
8724
                ) {
8725
                    return true;
8726
                }
8727
            }
8728
        }
8729
8730
        return false;
8731
    };
8732
8733
    $loginAsStatusForSessionAdmins = [STUDENT];
8734
8735
    if (api_get_configuration_value('allow_session_admin_login_as_teacher')) {
8736
        $loginAsStatusForSessionAdmins[] = COURSEMANAGER;
8737
    }
8738
8739
    return api_is_platform_admin() ||
8740
        (api_is_session_admin() && in_array($userInfo['status'], $loginAsStatusForSessionAdmins)) ||
8741
        $isDrh();
8742
}
8743
8744
/**
8745
 * @return bool
8746
 */
8747
function api_is_allowed_in_course()
8748
{
8749
    if (api_is_platform_admin()) {
8750
        return true;
8751
    }
8752
8753
    return Session::read('is_allowed_in_course');
8754
}
8755
8756
function api_set_cookie($name, $value, $expires = 0)
8757
{
8758
    $expires = (int) $expires;
8759
    setcookie($name, $value, $expires, '', '', api_is_https(), true);
8760
}
8761
8762
/**
8763
 * Set the cookie to go directly to the course code $in_firstpage
8764
 * after login.
8765
 *
8766
 * @param string $value is the course code of the course to go
8767
 */
8768
function api_set_firstpage_parameter($value)
8769
{
8770
    api_set_cookie('GotoCourse', $value);
8771
}
8772
8773
/**
8774
 * Delete the cookie to go directly to the course code $in_firstpage
8775
 * after login.
8776
 */
8777
function api_delete_firstpage_parameter()
8778
{
8779
    api_set_cookie('GotoCourse', '', time() - 3600);
8780
}
8781
8782
/**
8783
 * @return bool if course_code for direct course access after login is set
8784
 */
8785
function exist_firstpage_parameter()
8786
{
8787
    return isset($_COOKIE['GotoCourse']) && $_COOKIE['GotoCourse'] != '';
8788
}
8789
8790
/**
8791
 * @return string return the course_code of the course where user login
8792
 */
8793
function api_get_firstpage_parameter()
8794
{
8795
    return $_COOKIE['GotoCourse'];
8796
}
8797
8798
/**
8799
 * Return true on https install.
8800
 *
8801
 * @return bool
8802
 */
8803
function api_is_https()
8804
{
8805
    if (!empty($_SERVER['HTTP_X_FORWARDED_PROTO']) &&
0 ignored issues
show
introduced by
Consider adding parentheses for clarity. Current Interpretation: (! empty($_SERVER['HTTP_...ttps_forwarded_proto']), Probably Intended Meaning: ! empty($_SERVER['HTTP_X...tps_forwarded_proto']))
Loading history...
8806
        $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https' || !empty($_configuration['force_https_forwarded_proto'])
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $_configuration seems to never exist and therefore empty should always be true.
Loading history...
8807
    ) {
8808
        $isSecured = true;
8809
    } else {
8810
        if (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') {
8811
            $isSecured = true;
8812
        } else {
8813
            $isSecured = false;
8814
            // last chance
8815
            if (!empty($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] == 443) {
8816
                $isSecured = true;
8817
            }
8818
        }
8819
    }
8820
8821
    return $isSecured;
8822
}
8823
8824
/**
8825
 * Return protocol (http or https).
8826
 *
8827
 * @return string
8828
 */
8829
function api_get_protocol()
8830
{
8831
    return api_is_https() ? 'https' : 'http';
8832
}
8833
8834
/**
8835
 * Return a string where " are replaced with 2 '
8836
 * It is useful when you pass a PHP variable in a Javascript browser dialog
8837
 * e.g. : alert("<?php get_lang('Message') ?>");
8838
 * and message contains character ".
8839
 *
8840
 * @param string $in_text
8841
 *
8842
 * @return string
8843
 */
8844
function convert_double_quote_to_single($in_text)
8845
{
8846
    return api_preg_replace('/"/', "''", $in_text);
8847
}
8848
8849
/**
8850
 * Get origin.
8851
 *
8852
 * @param string
8853
 *
8854
 * @return string
8855
 */
8856
function api_get_origin()
8857
{
8858
    return isset($_REQUEST['origin']) ? urlencode(Security::remove_XSS(urlencode($_REQUEST['origin']))) : '';
8859
}
8860
8861
/**
8862
 * Warns an user that the portal reach certain limit.
8863
 *
8864
 * @param string $limitName
8865
 */
8866
function api_warn_hosting_contact($limitName)
8867
{
8868
    $hostingParams = api_get_configuration_value(1);
8869
    $email = null;
8870
8871
    if (!empty($hostingParams)) {
8872
        if (isset($hostingParams['hosting_contact_mail'])) {
8873
            $email = $hostingParams['hosting_contact_mail'];
8874
        }
8875
    }
8876
8877
    if (!empty($email)) {
8878
        $subject = get_lang('HostingWarningReached');
8879
        $body = get_lang('PortalName').': '.api_get_path(WEB_PATH)." \n ";
8880
        $body .= get_lang('PortalLimitType').': '.$limitName." \n ";
8881
        if (isset($hostingParams[$limitName])) {
8882
            $body .= get_lang('Value').': '.$hostingParams[$limitName];
8883
        }
8884
        api_mail_html(null, $email, $subject, $body);
8885
    }
8886
}
8887
8888
/**
8889
 * Gets value of a variable from app/config/configuration.php
8890
 * Variables that are not set in the configuration.php file but set elsewhere:
8891
 * - virtual_css_theme_folder (vchamilo plugin)
8892
 * - access_url (global.inc.php)
8893
 * - apc/apc_prefix (global.inc.php).
8894
 *
8895
 * @param string $variable
8896
 *
8897
 * @return bool|mixed
8898
 */
8899
function api_get_configuration_value($variable)
8900
{
8901
    global $_configuration;
8902
    // Check the current url id, id = 1 by default
8903
    $urlId = isset($_configuration['access_url']) ? (int) $_configuration['access_url'] : 1;
8904
8905
    $variable = trim($variable);
8906
8907
    // Check if variable exists
8908
    if (isset($_configuration[$variable])) {
8909
        if (is_array($_configuration[$variable])) {
8910
            // Check if it exists for the sub portal
8911
            if (array_key_exists($urlId, $_configuration[$variable])) {
8912
                return $_configuration[$variable][$urlId];
8913
            } else {
8914
                // Try to found element with id = 1 (master portal)
8915
                if (array_key_exists(1, $_configuration[$variable])) {
8916
                    return $_configuration[$variable][1];
8917
                }
8918
            }
8919
        }
8920
8921
        return $_configuration[$variable];
8922
    }
8923
8924
    return false;
8925
}
8926
8927
/**
8928
 * Retreives and returns a value in a hierarchical configuration array
8929
 * api_get_configuration_sub_value('a/b/c') returns api_get_configuration_value('a')['b']['c'].
8930
 *
8931
 * @param string $path      the successive array keys, separated by the separator
8932
 * @param mixed  $default   value to be returned if not found, null by default
8933
 * @param string $separator '/' by default
8934
 * @param array  $array     the active configuration array by default
8935
 *
8936
 * @return mixed the found value or $default
8937
 */
8938
function api_get_configuration_sub_value($path, $default = null, $separator = '/', $array = null)
8939
{
8940
    $pos = strpos($path, $separator);
8941
    if (false === $pos) {
8942
        if (is_null($array)) {
8943
            return api_get_configuration_value($path);
8944
        }
8945
        if (is_array($array) && array_key_exists($path, $array)) {
8946
            return $array[$path];
8947
        }
8948
8949
        return $default;
8950
    }
8951
    $key = substr($path, 0, $pos);
8952
    if (is_null($array)) {
8953
        $newArray = api_get_configuration_value($key);
8954
    } elseif (is_array($array) && array_key_exists($key, $array)) {
8955
        $newArray = $array[$key];
8956
    } else {
8957
        return $default;
8958
    }
8959
    if (is_array($newArray)) {
8960
        $newPath = substr($path, $pos + 1);
8961
8962
        return api_get_configuration_sub_value($newPath, $default, $separator, $newArray);
8963
    }
8964
8965
    return $default;
8966
}
8967
8968
/**
8969
 * Retrieves and returns a value in a hierarchical configuration array
8970
 * api_array_sub_value($array, 'a/b/c') returns $array['a']['b']['c'].
8971
 *
8972
 * @param array  $array     the recursive array that contains the value to be returned (or not)
8973
 * @param string $path      the successive array keys, separated by the separator
8974
 * @param mixed  $default   the value to be returned if not found
8975
 * @param string $separator the separator substring
8976
 *
8977
 * @return mixed the found value or $default
8978
 */
8979
function api_array_sub_value($array, $path, $default = null, $separator = '/')
8980
{
8981
    $pos = strpos($path, $separator);
8982
    if (false === $pos) {
8983
        if (is_array($array) && array_key_exists($path, $array)) {
8984
            return $array[$path];
8985
        }
8986
8987
        return $default;
8988
    }
8989
    $key = substr($path, 0, $pos);
8990
    if (is_array($array) && array_key_exists($key, $array)) {
8991
        $newArray = $array[$key];
8992
    } else {
8993
        return $default;
8994
    }
8995
    if (is_array($newArray)) {
8996
        $newPath = substr($path, $pos + 1);
8997
8998
        return api_array_sub_value($newArray, $newPath, $default);
8999
    }
9000
9001
    return $default;
9002
}
9003
9004
/**
9005
 * Returns supported image extensions in the portal.
9006
 *
9007
 * @param bool $supportVectors Whether vector images should also be accepted or not
9008
 *
9009
 * @return array Supported image extensions in the portal
9010
 */
9011
function api_get_supported_image_extensions($supportVectors = true)
9012
{
9013
    // jpg can also be called jpeg, jpe, jfif and jif. See https://en.wikipedia.org/wiki/JPEG#JPEG_filename_extensions
9014
    $supportedImageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'jpe', 'jfif', 'jif'];
9015
    if ($supportVectors) {
9016
        array_push($supportedImageExtensions, 'svg');
9017
    }
9018
    if (version_compare(PHP_VERSION, '5.5.0', '>=')) {
9019
        array_push($supportedImageExtensions, 'webp');
9020
    }
9021
9022
    return $supportedImageExtensions;
9023
}
9024
9025
/**
9026
 * This setting changes the registration status for the campus.
9027
 *
9028
 * @author Patrick Cool <[email protected]>, Ghent University
9029
 *
9030
 * @version August 2006
9031
 *
9032
 * @param bool $listCampus Whether we authorize
9033
 *
9034
 * @todo the $_settings should be reloaded here. => write api function for this and use this in global.inc.php also.
9035
 */
9036
function api_register_campus($listCampus = true)
9037
{
9038
    $tbl_settings = Database::get_main_table(TABLE_MAIN_SETTINGS_CURRENT);
9039
9040
    $sql = "UPDATE $tbl_settings SET selected_value='true' WHERE variable='registered'";
9041
    Database::query($sql);
9042
9043
    if (!$listCampus) {
9044
        $sql = "UPDATE $tbl_settings SET selected_value='true' WHERE variable='donotlistcampus'";
9045
        Database::query($sql);
9046
    }
9047
}
9048
9049
/**
9050
 * Checks whether current user is a student boss.
9051
 *
9052
 * @global array $_user
9053
 *
9054
 * @return bool
9055
 */
9056
function api_is_student_boss()
9057
{
9058
    $_user = api_get_user_info();
9059
9060
    return isset($_user['status']) && $_user['status'] == STUDENT_BOSS;
9061
}
9062
9063
/**
9064
 * Check whether the user type should be exclude.
9065
 * Such as invited or anonymous users.
9066
 *
9067
 * @param bool $checkDB Optional. Whether check the user status
9068
 * @param int  $userId  Options. The user id
9069
 *
9070
 * @return bool
9071
 */
9072
function api_is_excluded_user_type($checkDB = false, $userId = 0)
9073
{
9074
    if ($checkDB) {
9075
        $userId = empty($userId) ? api_get_user_id() : (int) $userId;
9076
9077
        if ($userId == 0) {
9078
            return true;
9079
        }
9080
9081
        $userInfo = api_get_user_info($userId);
9082
9083
        switch ($userInfo['status']) {
9084
            case INVITEE:
9085
            case ANONYMOUS:
9086
                return true;
9087
            default:
9088
                return false;
9089
        }
9090
    }
9091
9092
    $isInvited = api_is_invitee();
9093
    $isAnonymous = api_is_anonymous();
9094
9095
    if ($isInvited || $isAnonymous) {
9096
        return true;
9097
    }
9098
9099
    return false;
9100
}
9101
9102
/**
9103
 * Get the user status to ignore in reports.
9104
 *
9105
 * @param string $format Optional. The result type (array or string)
9106
 *
9107
 * @return array|string
9108
 */
9109
function api_get_users_status_ignored_in_reports($format = 'array')
9110
{
9111
    $excludedTypes = [
9112
        INVITEE,
9113
        ANONYMOUS,
9114
    ];
9115
9116
    if ($format == 'string') {
9117
        return implode(', ', $excludedTypes);
9118
    }
9119
9120
    return $excludedTypes;
9121
}
9122
9123
/**
9124
 * Set the Site Use Cookie Warning for 1 year.
9125
 */
9126
function api_set_site_use_cookie_warning_cookie()
9127
{
9128
    api_set_cookie('ChamiloUsesCookies', 'ok', time() + 31556926);
9129
}
9130
9131
/**
9132
 * Return true if the Site Use Cookie Warning Cookie warning exists.
9133
 *
9134
 * @return bool
9135
 */
9136
function api_site_use_cookie_warning_cookie_exist()
9137
{
9138
    return isset($_COOKIE['ChamiloUsesCookies']);
9139
}
9140
9141
/**
9142
 * Given a number of seconds, format the time to show hours, minutes and seconds.
9143
 *
9144
 * @param int    $time         The time in seconds
9145
 * @param string $originFormat Optional. PHP o JS
9146
 *
9147
 * @return string (00h00'00")
9148
 */
9149
function api_format_time($time, $originFormat = 'php')
9150
{
9151
    $h = get_lang('h');
9152
    $hours = $time / 3600;
9153
    $mins = ($time % 3600) / 60;
9154
    $secs = ($time % 60);
9155
9156
    if ($time < 0) {
9157
        $hours = 0;
9158
        $mins = 0;
9159
        $secs = 0;
9160
    }
9161
9162
    if ($originFormat == 'js') {
9163
        $formattedTime = trim(sprintf("%02d : %02d : %02d", $hours, $mins, $secs));
9164
    } else {
9165
        $formattedTime = trim(sprintf("%02d$h%02d'%02d\"", $hours, $mins, $secs));
9166
    }
9167
9168
    return $formattedTime;
9169
}
9170
9171
/**
9172
 * Create a new empty directory with index.html file.
9173
 *
9174
 * @param string $name            The new directory name
9175
 * @param string $parentDirectory Directory parent directory name
9176
 *
9177
 * @return bool Return true if the directory was create. Otherwise return false
9178
 */
9179
function api_create_protected_dir($name, $parentDirectory)
9180
{
9181
    $isCreated = false;
9182
9183
    if (!is_writable($parentDirectory)) {
9184
        return false;
9185
    }
9186
9187
    $fullPath = $parentDirectory.api_replace_dangerous_char($name);
9188
9189
    if (mkdir($fullPath, api_get_permissions_for_new_directories(), true)) {
9190
        $fp = fopen($fullPath.'/index.html', 'w');
9191
9192
        if ($fp) {
0 ignored issues
show
introduced by
$fp is of type resource, thus it always evaluated to false.
Loading history...
9193
            if (fwrite($fp, '<html><head><title></title></head><body></body></html>')) {
9194
                $isCreated = true;
9195
            }
9196
        }
9197
9198
        fclose($fp);
9199
    }
9200
9201
    return $isCreated;
9202
}
9203
9204
/**
9205
 * Sends an HTML email using the phpmailer class (and multipart/alternative to downgrade gracefully)
9206
 * Sender name and email can be specified, if not specified
9207
 * name and email of the platform admin are used.
9208
 *
9209
 * @author Bert Vanderkimpen ICT&O UGent
9210
 * @author Yannick Warnier <[email protected]>
9211
 *
9212
 * @param string    name of recipient
9213
 * @param string    email of recipient
9214
 * @param string    email subject
9215
 * @param string    email body
9216
 * @param string    sender name
9217
 * @param string    sender e-mail
9218
 * @param array  $extra_headers        in form $headers = array($name => $value) to allow parsing
9219
 * @param array  $data_file            (path and filename)
9220
 * @param bool   $embedded_image       True for attaching a embedded file inside content html (optional)
9221
 * @param array  $additionalParameters
9222
 * @param string $sendErrorTo          If there's an error while sending the email, $sendErrorTo will receive a notification
9223
 *
9224
 * @return int true if mail was sent
9225
 *
9226
 * @see             PHPMailer.php
9227
 */
9228
function api_mail_html(
9229
    $recipient_name,
9230
    $recipient_email,
9231
    $subject,
9232
    $message,
9233
    $senderName = '',
9234
    $senderEmail = '',
9235
    $extra_headers = [],
9236
    $data_file = [],
9237
    $embedded_image = false,
9238
    $additionalParameters = [],
9239
    $sendErrorTo = ''
9240
) {
9241
    global $platform_email;
9242
9243
    if (true === api_get_configuration_value('disable_send_mail')) {
9244
        return true;
9245
    }
9246
9247
    $mail = new PHPMailer();
9248
    $mail->Mailer = $platform_email['SMTP_MAILER'];
9249
    $mail->Host = $platform_email['SMTP_HOST'];
9250
    $mail->Port = $platform_email['SMTP_PORT'];
9251
    $mail->CharSet = isset($platform_email['SMTP_CHARSET']) ? $platform_email['SMTP_CHARSET'] : 'UTF-8';
9252
    // Stay far below SMTP protocol 980 chars limit.
9253
    $mail->WordWrap = 200;
9254
    $mail->SMTPOptions = $platform_email['SMTPOptions'] ?? [];
9255
9256
    if ($platform_email['SMTP_AUTH']) {
9257
        $mail->SMTPAuth = 1;
9258
        $mail->Username = $platform_email['SMTP_USER'];
9259
        $mail->Password = $platform_email['SMTP_PASS'];
9260
        if (isset($platform_email['SMTP_SECURE'])) {
9261
            $mail->SMTPSecure = $platform_email['SMTP_SECURE'];
9262
        }
9263
    }
9264
    $mail->SMTPDebug = isset($platform_email['SMTP_DEBUG']) ? $platform_email['SMTP_DEBUG'] : 0;
9265
9266
    // 5 = low, 1 = high
9267
    $mail->Priority = 3;
9268
    $mail->SMTPKeepAlive = true;
9269
9270
    api_set_noreply_and_from_address_to_mailer(
9271
        $mail,
9272
        ['name' => $senderName, 'email' => $senderEmail],
9273
        !empty($extra_headers['reply_to']) ? $extra_headers['reply_to'] : []
9274
    );
9275
9276
    if (!empty($sendErrorTo) && PHPMailer::ValidateAddress($sendErrorTo)) {
9277
        $mail->AddCustomHeader('Errors-To', $sendErrorTo);
9278
    }
9279
9280
    unset($extra_headers['reply_to']);
9281
9282
    $mail->Subject = $subject;
9283
    $mail->AltBody = strip_tags(
9284
        str_replace('<br />', "\n", api_html_entity_decode($message))
9285
    );
9286
9287
    $list = api_get_configuration_value('send_all_emails_to');
9288
    if (!empty($list) && isset($list['emails'])) {
9289
        foreach ($list['emails'] as $email) {
9290
            $mail->AddAddress($email);
9291
        }
9292
    }
9293
9294
    // Send embedded image.
9295
    if ($embedded_image) {
9296
        // Get all images html inside content.
9297
        preg_match_all("/<img\s+.*?src=[\"\']?([^\"\' >]*)[\"\']?[^>]*>/i", $message, $m);
9298
        // Prepare new tag images.
9299
        $new_images_html = [];
9300
        $i = 1;
9301
        if (!empty($m[1])) {
9302
            foreach ($m[1] as $image_path) {
9303
                $real_path = realpath($image_path);
9304
                $filename = basename($image_path);
9305
                $image_cid = $filename.'_'.$i;
9306
                $encoding = 'base64';
9307
                $image_type = mime_content_type($real_path);
9308
                $mail->AddEmbeddedImage(
9309
                    $real_path,
9310
                    $image_cid,
9311
                    $filename,
9312
                    $encoding,
9313
                    $image_type
9314
                );
9315
                $new_images_html[] = '<img src="cid:'.$image_cid.'" />';
9316
                $i++;
9317
            }
9318
        }
9319
9320
        // Replace origin image for new embedded image html.
9321
        $x = 0;
9322
        if (!empty($m[0])) {
9323
            foreach ($m[0] as $orig_img) {
9324
                $message = str_replace($orig_img, $new_images_html[$x], $message);
9325
                $x++;
9326
            }
9327
        }
9328
    }
9329
9330
    $mailView = new Template(null, false, false, false, false, false, false);
9331
9332
    $noReply = api_get_setting('noreply_email_address');
9333
    if (!empty($noReply)) {
9334
        $message .= '<br />'.get_lang('ThisIsAutomaticEmailNoReply');
9335
    }
9336
    $mailView->assign('content', $message);
9337
9338
    if (isset($additionalParameters['link'])) {
9339
        $mailView->assign('link', $additionalParameters['link']);
9340
    }
9341
    $mailView->assign('mail_header_style', api_get_configuration_value('mail_header_style'));
9342
    $mailView->assign('mail_content_style', api_get_configuration_value('mail_content_style'));
9343
    $layout = $mailView->get_template('mail/mail.tpl');
9344
    $mail->Body = $mailView->fetch($layout);
9345
9346
    // Attachment.
9347
    if (!empty($data_file)) {
9348
        foreach ($data_file as $file_attach) {
9349
            if (!empty($file_attach['path']) && !empty($file_attach['filename'])) {
9350
                $mail->AddAttachment($file_attach['path'], $file_attach['filename']);
9351
            }
9352
        }
9353
    }
9354
9355
    // Only valid addresses are accepted.
9356
    if (is_array($recipient_email)) {
9357
        foreach ($recipient_email as $dest) {
9358
            if (api_valid_email($dest)) {
9359
                $mail->AddAddress($dest, $recipient_name);
9360
            }
9361
        }
9362
    } else {
9363
        if (api_valid_email($recipient_email)) {
9364
            $mail->AddAddress($recipient_email, $recipient_name);
9365
        } else {
9366
            return 0;
9367
        }
9368
    }
9369
9370
    if (is_array($extra_headers) && count($extra_headers) > 0) {
9371
        foreach ($extra_headers as $key => $value) {
9372
            switch (strtolower($key)) {
9373
                case 'encoding':
9374
                case 'content-transfer-encoding':
9375
                    $mail->Encoding = $value;
9376
                    break;
9377
                case 'charset':
9378
                    $mail->CharSet = $value;
9379
                    break;
9380
                case 'contenttype':
9381
                case 'content-type':
9382
                    $mail->ContentType = $value;
9383
                    break;
9384
                default:
9385
                    $mail->AddCustomHeader($key, $value);
9386
                    break;
9387
            }
9388
        }
9389
    } else {
9390
        if (!empty($extra_headers)) {
9391
            $mail->AddCustomHeader($extra_headers);
9392
        }
9393
    }
9394
9395
    // WordWrap the html body (phpMailer only fixes AltBody) FS#2988
9396
    $mail->Body = $mail->WrapText($mail->Body, $mail->WordWrap);
9397
9398
    if (!empty($platform_email['DKIM']) &&
9399
        !empty($platform_email['DKIM_SELECTOR']) &&
9400
        !empty($platform_email['DKIM_DOMAIN']) &&
9401
        (!empty($platform_email['DKIM_PRIVATE_KEY_STRING']) || !empty($platform_email['DKIM_PRIVATE_KEY']))) {
9402
        $mail->DKIM_selector = $platform_email['DKIM_SELECTOR'];
9403
        $mail->DKIM_domain = $platform_email['DKIM_DOMAIN'];
9404
        if (!empty($platform_email['SMTP_UNIQUE_SENDER'])) {
9405
            $mail->DKIM_identity = $platform_email['SMTP_FROM_EMAIL'];
9406
        }
9407
        $mail->DKIM_private_string = $platform_email['DKIM_PRIVATE_KEY_STRING'];
9408
        $mail->DKIM_private = $platform_email['DKIM_PRIVATE_KEY'];
9409
    }
9410
9411
    // Send the mail message.
9412
    $sent = $mail->Send();
9413
    if (!$sent) {
9414
        error_log('ERROR: mail not sent to '.$recipient_name.' ('.$recipient_email.') because of '.$mail->ErrorInfo.'<br />');
9415
    }
9416
9417
    if ($mail->SMTPDebug > 1) {
9418
        error_log(
9419
            "Mail debug:: ".
9420
            "Protocol: ".$mail->Mailer.' :: '.
9421
            "Host/Port: ".$mail->Host.':'.$mail->Port.' :: '.
9422
            "Authent/Open: ".($mail->SMTPAuth ? 'Authent' : 'Open').' :: '.
9423
            ($mail->SMTPAuth ? "  User/Pass: ".$mail->Username.':'.$mail->Password : '').' :: '.
9424
            "Sender: ".$mail->Sender.
9425
            "Recipient email: ".$recipient_email.
9426
            "Subject: ".$subject
9427
        );
9428
    }
9429
9430
    if (!$sent) {
9431
        return 0;
9432
    }
9433
9434
    if (!empty($additionalParameters)) {
9435
        $plugin = new AppPlugin();
9436
        $smsPlugin = $plugin->getSMSPluginLibrary();
9437
        if ($smsPlugin) {
0 ignored issues
show
introduced by
$smsPlugin is of type SmsPluginLibraryInterface, thus it always evaluated to true.
Loading history...
9438
            $smsPlugin->send($additionalParameters);
9439
        }
9440
    }
9441
9442
    // Clear all the addresses.
9443
    $mail->ClearAddresses();
9444
9445
    // Clear all attachments
9446
    $mail->ClearAttachments();
9447
9448
    return 1;
9449
}
9450
9451
/**
9452
 * Checks access to a course group.
9453
 *
9454
 * @param string $tool       Possible values: GroupManager::GROUP_TOOL_*
9455
 * @param bool   $showHeader
9456
 */
9457
function api_protect_course_group($tool, $showHeader = true)
9458
{
9459
    $groupId = api_get_group_id();
9460
    if (!empty($groupId)) {
9461
        if (api_is_platform_admin()) {
9462
            return true;
9463
        }
9464
9465
        if (api_is_allowed_to_edit(false, true, true)) {
9466
            return true;
9467
        }
9468
9469
        $userId = api_get_user_id();
9470
        $sessionId = api_get_session_id();
9471
        if (!empty($sessionId)) {
9472
            if (api_is_coach($sessionId, api_get_course_int_id())) {
9473
                return true;
9474
            }
9475
9476
            if (api_is_drh()) {
9477
                if (SessionManager::isUserSubscribedAsHRM($sessionId, $userId)) {
9478
                    return true;
9479
                }
9480
            }
9481
        }
9482
9483
        $groupInfo = GroupManager::get_group_properties($groupId);
9484
9485
        // Group doesn't exists
9486
        if (empty($groupInfo)) {
9487
            api_not_allowed($showHeader);
9488
        }
9489
9490
        // Check group access
9491
        $allow = GroupManager::user_has_access(
9492
            $userId,
9493
            $groupInfo['iid'],
9494
            $tool
9495
        );
9496
9497
        if (!$allow) {
9498
            api_not_allowed($showHeader);
9499
        }
9500
    }
9501
9502
    return false;
9503
}
9504
9505
/**
9506
 * Check if a date is in a date range.
9507
 *
9508
 * @param datetime $startDate
9509
 * @param datetime $endDate
9510
 * @param datetime $currentDate
9511
 *
9512
 * @return bool true if date is in rage, false otherwise
9513
 */
9514
function api_is_date_in_date_range($startDate, $endDate, $currentDate = null)
9515
{
9516
    $startDate = strtotime(api_get_local_time($startDate));
9517
    $endDate = strtotime(api_get_local_time($endDate));
9518
    $currentDate = strtotime(api_get_local_time($currentDate));
9519
9520
    if ($currentDate >= $startDate && $currentDate <= $endDate) {
9521
        return true;
9522
    }
9523
9524
    return false;
9525
}
9526
9527
/**
9528
 * Eliminate the duplicates of a multidimensional array by sending the key.
9529
 *
9530
 * @param array $array multidimensional array
9531
 * @param int   $key   key to find to compare
9532
 *
9533
 * @return array
9534
 */
9535
function api_unique_multidim_array($array, $key)
9536
{
9537
    $temp_array = [];
9538
    $i = 0;
9539
    $key_array = [];
9540
9541
    foreach ($array as $val) {
9542
        if (!in_array($val[$key], $key_array)) {
9543
            $key_array[$i] = $val[$key];
9544
            $temp_array[$i] = $val;
9545
        }
9546
        $i++;
9547
    }
9548
9549
    return $temp_array;
9550
}
9551
9552
/**
9553
 * Limit the access to Session Admins when the limit_session_admin_role
9554
 * configuration variable is set to true.
9555
 */
9556
function api_protect_limit_for_session_admin()
9557
{
9558
    $limitAdmin = api_get_setting('limit_session_admin_role');
9559
    if (api_is_session_admin() && $limitAdmin === 'true') {
9560
        api_not_allowed(true);
9561
    }
9562
}
9563
9564
/**
9565
 * Limits that a session admin has access to list users.
9566
 * When limit_session_admin_list_users configuration variable is set to true.
9567
 */
9568
function api_protect_session_admin_list_users()
9569
{
9570
    $limitAdmin = api_get_configuration_value('limit_session_admin_list_users');
9571
9572
    if (api_is_session_admin() && true === $limitAdmin) {
9573
        api_not_allowed(true);
9574
    }
9575
}
9576
9577
/**
9578
 * @return bool
9579
 */
9580
function api_is_student_view_active()
9581
{
9582
    $studentView = Session::read('studentview');
9583
9584
    return $studentView == 'studentview';
9585
}
9586
9587
/**
9588
 * Adds a file inside the upload/$type/id.
9589
 *
9590
 * @param string $type
9591
 * @param array  $file
9592
 * @param int    $itemId
9593
 * @param string $cropParameters
9594
 *
9595
 * @return array|bool
9596
 */
9597
function api_upload_file($type, $file, $itemId, $cropParameters = '')
9598
{
9599
    $upload = process_uploaded_file($file);
9600
    if ($upload) {
9601
        $name = api_replace_dangerous_char($file['name']);
9602
9603
        // No "dangerous" files
9604
        $name = disable_dangerous_file($name);
9605
9606
        $pathId = '/'.substr((string) $itemId, 0, 1).'/'.$itemId.'/';
9607
        $path = api_get_path(SYS_UPLOAD_PATH).$type.$pathId;
9608
9609
        if (!is_dir($path)) {
9610
            mkdir($path, api_get_permissions_for_new_directories(), true);
9611
        }
9612
9613
        $pathToSave = $path.$name;
9614
        $result = moveUploadedFile($file, $pathToSave);
9615
9616
        if ($result) {
9617
            if (!empty($cropParameters)) {
9618
                $image = new Image($pathToSave);
9619
                $image->crop($cropParameters);
9620
            }
9621
9622
            return ['path_to_save' => $pathId.$name];
9623
        }
9624
    }
9625
9626
    return false;
9627
}
9628
9629
/**
9630
 * @param string $type
9631
 * @param int    $itemId
9632
 * @param string $file
9633
 *
9634
 * @return bool
9635
 */
9636
function api_get_uploaded_web_url($type, $itemId, $file)
9637
{
9638
    return api_get_uploaded_file($type, $itemId, $file, true);
9639
}
9640
9641
/**
9642
 * @param string $type
9643
 * @param int    $itemId
9644
 * @param string $file
9645
 * @param bool   $getUrl
9646
 *
9647
 * @return bool
9648
 */
9649
function api_get_uploaded_file($type, $itemId, $file, $getUrl = false)
9650
{
9651
    $itemId = (int) $itemId;
9652
    $pathId = '/'.substr((string) $itemId, 0, 1).'/'.$itemId.'/';
9653
    $path = api_get_path(SYS_UPLOAD_PATH).$type.$pathId;
9654
    $file = basename($file);
9655
    $file = $path.'/'.$file;
9656
    if (Security::check_abs_path($file, $path) && is_file($file) && file_exists($file)) {
9657
        if ($getUrl) {
9658
            return str_replace(api_get_path(SYS_UPLOAD_PATH), api_get_path(WEB_UPLOAD_PATH), $file);
9659
        }
9660
9661
        return $file;
9662
    }
9663
9664
    return false;
9665
}
9666
9667
/**
9668
 * @param string $type
9669
 * @param int    $itemId
9670
 * @param string $file
9671
 * @param string $title
9672
 */
9673
function api_download_uploaded_file($type, $itemId, $file, $title = '')
9674
{
9675
    $file = api_get_uploaded_file($type, $itemId, $file);
9676
    if ($file) {
9677
        if (Security::check_abs_path($file, api_get_path(SYS_UPLOAD_PATH).$type)) {
9678
            DocumentManager::file_send_for_download($file, true, $title);
9679
            exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

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

Loading history...
9680
        }
9681
    }
9682
    api_not_allowed(true);
9683
}
9684
9685
/**
9686
 * @param string $type
9687
 * @param string $file
9688
 */
9689
function api_remove_uploaded_file($type, $file)
9690
{
9691
    $typePath = api_get_path(SYS_UPLOAD_PATH).$type;
9692
    $path = $typePath.'/'.$file;
9693
    if (Security::check_abs_path($path, $typePath) && file_exists($path) && is_file($path)) {
9694
        unlink($path);
9695
    }
9696
}
9697
9698
/**
9699
 * @param string $type
9700
 * @param int    $itemId
9701
 * @param string $file
9702
 *
9703
 * @return bool
9704
 */
9705
function api_remove_uploaded_file_by_id($type, $itemId, $file)
9706
{
9707
    $file = api_get_uploaded_file($type, $itemId, $file, false);
9708
    $typePath = api_get_path(SYS_UPLOAD_PATH).$type;
9709
    if (Security::check_abs_path($file, $typePath) && file_exists($file) && is_file($file)) {
9710
        unlink($file);
9711
9712
        return true;
9713
    }
9714
9715
    return false;
9716
}
9717
9718
/**
9719
 * Converts string value to float value.
9720
 *
9721
 * 3.141516 => 3.141516
9722
 * 3,141516 => 3.141516
9723
 *
9724
 * @todo WIP
9725
 *
9726
 * @param string $number
9727
 *
9728
 * @return float
9729
 */
9730
function api_float_val($number)
9731
{
9732
    $number = (float) str_replace(',', '.', trim($number));
9733
9734
    return $number;
9735
}
9736
9737
/**
9738
 * Converts float values
9739
 * Example if $decimals = 2.
9740
 *
9741
 * 3.141516 => 3.14
9742
 * 3,141516 => 3,14
9743
 *
9744
 * @param string $number            number in iso code
9745
 * @param int    $decimals
9746
 * @param string $decimalSeparator
9747
 * @param string $thousandSeparator
9748
 *
9749
 * @return bool|string
9750
 */
9751
function api_number_format($number, $decimals = 0, $decimalSeparator = '.', $thousandSeparator = ',')
9752
{
9753
    $number = api_float_val($number);
9754
9755
    return number_format($number, $decimals, $decimalSeparator, $thousandSeparator);
9756
}
9757
9758
/**
9759
 * Set location url with a exit break by default.
9760
 *
9761
 * @param string $url
9762
 * @param bool   $exit
9763
 */
9764
function api_location($url, $exit = true)
9765
{
9766
    header('Location: '.$url);
9767
9768
    if ($exit) {
9769
        exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

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

Loading history...
9770
    }
9771
}
9772
9773
/**
9774
 * @return string
9775
 */
9776
function api_get_web_url()
9777
{
9778
    if (api_get_setting('server_type') === 'test') {
9779
        return api_get_path(WEB_PATH).'web/app_dev.php/';
9780
    } else {
9781
        return api_get_path(WEB_PATH).'web/';
9782
    }
9783
}
9784
9785
/**
9786
 * @param string $from
9787
 * @param string $to
9788
 *
9789
 * @return string
9790
 */
9791
function api_get_relative_path($from, $to)
9792
{
9793
    // some compatibility fixes for Windows paths
9794
    $from = is_dir($from) ? rtrim($from, '\/').'/' : $from;
9795
    $to = is_dir($to) ? rtrim($to, '\/').'/' : $to;
9796
    $from = str_replace('\\', '/', $from);
9797
    $to = str_replace('\\', '/', $to);
9798
9799
    $from = explode('/', $from);
9800
    $to = explode('/', $to);
9801
    $relPath = $to;
9802
9803
    foreach ($from as $depth => $dir) {
9804
        // find first non-matching dir
9805
        if ($dir === $to[$depth]) {
9806
            // ignore this directory
9807
            array_shift($relPath);
9808
        } else {
9809
            // get number of remaining dirs to $from
9810
            $remaining = count($from) - $depth;
9811
            if ($remaining > 1) {
9812
                // add traversals up to first matching dir
9813
                $padLength = (count($relPath) + $remaining - 1) * -1;
9814
                $relPath = array_pad($relPath, $padLength, '..');
9815
                break;
9816
            } else {
9817
                $relPath[0] = './'.$relPath[0];
9818
            }
9819
        }
9820
    }
9821
9822
    return implode('/', $relPath);
9823
}
9824
9825
/**
9826
 * Unserialize content using Brummann\Polyfill\Unserialize.
9827
 *
9828
 * @param string $type
9829
 * @param string $serialized
9830
 *
9831
 * @return mixed
9832
 */
9833
function api_unserialize_content($type, $serialized, $ignoreErrors = false)
9834
{
9835
    switch ($type) {
9836
        case 'career':
9837
        case 'sequence_graph':
9838
            $allowedClasses = [Graph::class, VerticesMap::class, Vertices::class, Edges::class];
9839
            break;
9840
        case 'lp':
9841
            $allowedClasses = [
9842
                learnpath::class,
9843
                learnpathItem::class,
9844
                aicc::class,
9845
                aiccBlock::class,
9846
                aiccItem::class,
9847
                aiccObjective::class,
9848
                aiccResource::class,
9849
                scorm::class,
9850
                scormItem::class,
9851
                scormMetadata::class,
9852
                scormOrganization::class,
9853
                scormResource::class,
9854
                Link::class,
9855
                LpItem::class,
9856
            ];
9857
            break;
9858
        case 'course':
9859
            $allowedClasses = [
9860
                Course::class,
9861
                Announcement::class,
9862
                Attendance::class,
9863
                CalendarEvent::class,
9864
                CourseCopyLearnpath::class,
9865
                CourseCopyTestCategory::class,
9866
                CourseDescription::class,
9867
                CourseSession::class,
9868
                Document::class,
9869
                Forum::class,
9870
                ForumCategory::class,
9871
                ForumPost::class,
9872
                ForumTopic::class,
9873
                Glossary::class,
9874
                GradeBookBackup::class,
9875
                Link::class,
9876
                LinkCategory::class,
9877
                Quiz::class,
9878
                QuizQuestion::class,
9879
                QuizQuestionOption::class,
9880
                ScormDocument::class,
9881
                Survey::class,
9882
                SurveyInvitation::class,
9883
                SurveyQuestion::class,
9884
                Thematic::class,
9885
                ToolIntro::class,
9886
                Wiki::class,
9887
                Work::class,
9888
                stdClass::class,
9889
            ];
9890
            break;
9891
        case 'not_allowed_classes':
9892
        default:
9893
            $allowedClasses = false;
9894
    }
9895
9896
    if ($ignoreErrors) {
9897
        return @Unserialize::unserialize(
9898
            $serialized,
9899
            ['allowed_classes' => $allowedClasses]
9900
        );
9901
    }
9902
9903
    return Unserialize::unserialize(
9904
        $serialized,
9905
        ['allowed_classes' => $allowedClasses]
9906
    );
9907
}
9908
9909
/**
9910
 * Set the From and ReplyTo properties to PHPMailer instance.
9911
 *
9912
 * @throws \PHPMailer\PHPMailer\Exception
9913
 */
9914
function api_set_noreply_and_from_address_to_mailer(PHPMailer $mailer, array $sender, array $replyToAddress = [])
9915
{
9916
    $platformEmail = $GLOBALS['platform_email'];
9917
9918
    $noReplyAddress = api_get_setting('noreply_email_address');
9919
    $avoidReplyToAddress = false;
9920
9921
    if (!empty($noReplyAddress)) {
9922
        $avoidReplyToAddress = api_get_configuration_value('mail_no_reply_avoid_reply_to');
9923
    }
9924
9925
    $notification = new Notification();
9926
    // If the parameter is set don't use the admin.
9927
    $senderName = !empty($sender['name']) ? $sender['name'] : $notification->getDefaultPlatformSenderName();
9928
    $senderEmail = !empty($sender['email']) ? $sender['email'] : $notification->getDefaultPlatformSenderEmail();
9929
9930
    // Send errors to the platform admin
9931
    $adminEmail = api_get_setting('emailAdministrator');
9932
    if (PHPMailer::ValidateAddress($adminEmail)) {
9933
        $mailer->AddCustomHeader('Errors-To: '.$adminEmail);
9934
    }
9935
9936
    // Reply to first
9937
    if (!$avoidReplyToAddress) {
9938
        if (
9939
            !empty($replyToAddress) &&
9940
            PHPMailer::ValidateAddress($replyToAddress['mail'])
9941
        ) {
9942
            $mailer->AddReplyTo($replyToAddress['mail'], $replyToAddress['name']);
9943
            //$mailer->Sender = $replyToAddress['mail'];
9944
        }
9945
    }
9946
9947
    //If the SMTP configuration only accept one sender
9948
    if (
9949
        isset($platformEmail['SMTP_UNIQUE_SENDER']) &&
9950
        $platformEmail['SMTP_UNIQUE_SENDER']
9951
    ) {
9952
        $senderName = $notification->getDefaultPlatformSenderName();
9953
        $senderEmail = $notification->getDefaultPlatformSenderEmail();
9954
9955
        if (PHPMailer::ValidateAddress($senderEmail)) {
9956
            //force-set Sender to $senderEmail, otherwise SetFrom only does it if it is currently empty
9957
            $mailer->Sender = $senderEmail;
9958
        }
9959
    }
9960
9961
    $mailer->SetFrom($senderEmail, $senderName, !$avoidReplyToAddress);
9962
}
9963
9964
/**
9965
 * @param string $template
9966
 *
9967
 * @return string
9968
 */
9969
function api_find_template($template)
9970
{
9971
    return Template::findTemplateFilePath($template);
9972
}
9973
9974
/**
9975
 * Returns an array of languages (English names like "english", "french", etc)
9976
 * to ISO 639-1 codes (fr, es, etc) for use (for example) to show flags
9977
 * Note: 'english' is returned as 'gb'.
9978
 *
9979
 * @return array
9980
 */
9981
function api_get_language_list_for_flag()
9982
{
9983
    $table = Database::get_main_table(TABLE_MAIN_LANGUAGE);
9984
    $sql = "SELECT english_name, isocode FROM $table
9985
            ORDER BY original_name ASC";
9986
    static $languages = [];
9987
    if (empty($languages)) {
9988
        $result = Database::query($sql);
9989
        while ($row = Database::fetch_array($result)) {
9990
            $languages[$row['english_name']] = $row['isocode'];
9991
        }
9992
        $languages['english'] = 'gb';
9993
    }
9994
9995
    return $languages;
9996
}
9997
9998
/**
9999
 * Generate the Javascript required for the on-page translation of
10000
 * multi-language strings.
10001
 *
10002
 * @throws Exception
10003
 *
10004
 * @return string
10005
 */
10006
function api_get_language_translate_html()
10007
{
10008
    $translate = api_get_configuration_value('translate_html');
10009
10010
    if (!$translate) {
10011
        return '';
10012
    }
10013
10014
    $languageList = api_get_languages();
10015
    $hideAll = '';
10016
    foreach ($languageList['all'] as $language) {
10017
        $hideAll .= '
10018
        $("span:lang('.$language['isocode'].')").filter(
10019
            function(e, val) {
10020
                // Only find the spans if they have set the lang
10021
                if ($(this).attr("lang") == null) {
10022
                    return false;
10023
                }
10024
10025
                // Ignore ckeditor classes
10026
                return !this.className.match(/cke(.*)/);
10027
        }).hide();'."\n";
10028
    }
10029
10030
    $userInfo = api_get_user_info();
10031
    $languageId = 0;
10032
    if (!empty($userInfo['language'])) {
10033
        $languageId = api_get_language_id($userInfo['language']);
10034
    } elseif (!empty($_GET['language'])) {
10035
        $languageId = api_get_language_id($_GET['language']);
10036
    }
10037
    $languageInfo = api_get_language_info($languageId);
10038
    $isoCode = 'en';
10039
10040
    if (!empty($languageInfo)) {
10041
        $isoCode = $languageInfo['isocode'];
10042
    }
10043
10044
    return '
10045
            $(function() {
10046
                '.$hideAll.'
10047
                var defaultLanguageFromUser = "'.$isoCode.'";
10048
10049
                $("span:lang('.$isoCode.')").filter(
10050
                    function() {
10051
                        // Ignore ckeditor classes
10052
                        return !this.className.match(/cke(.*)/);
10053
                }).show();
10054
10055
                var defaultLanguage = "";
10056
                var langFromUserFound = false;
10057
10058
                $(this).find("span").filter(
10059
                    function() {
10060
                        // Ignore ckeditor classes
10061
                        return !this.className.match(/cke(.*)/);
10062
                }).each(function() {
10063
                    defaultLanguage = $(this).attr("lang");
10064
                    if (defaultLanguage) {
10065
                        $(this).before().next("br").remove();
10066
                        if (defaultLanguageFromUser == defaultLanguage) {
10067
                            langFromUserFound = true;
10068
                        }
10069
                    }
10070
                });
10071
10072
                // Show default language
10073
                if (langFromUserFound == false && defaultLanguage) {
10074
                    $("span:lang("+defaultLanguage+")").filter(
10075
                    function() {
10076
                            // Ignore ckeditor classes
10077
                            return !this.className.match(/cke(.*)/);
10078
                    }).show();
10079
                }
10080
            });
10081
    ';
10082
}
10083
10084
/**
10085
 * Filter a multi-language HTML string (for the multi-language HTML
10086
 * feature) into the given language (strip the rest).
10087
 *
10088
 * @param string $htmlString The HTML string to "translate". Usually <p><span lang="en">Some string</span></p><p><span lang="fr">Une chaîne</span></p>
10089
 * @param string $language   The language in which we want to get the
10090
 *
10091
 * @throws Exception
10092
 *
10093
 * @return string The filtered string in the given language, or the full string if no translated string was identified
10094
 */
10095
function api_get_filtered_multilingual_HTML_string($htmlString, $language = null)
10096
{
10097
    if (api_get_configuration_value('translate_html') != true) {
10098
        return $htmlString;
10099
    }
10100
    $userInfo = api_get_user_info();
10101
    $languageId = 0;
10102
    if (!empty($language)) {
10103
        $languageId = api_get_language_id($language);
10104
    } elseif (!empty($userInfo['language'])) {
10105
        $languageId = api_get_language_id($userInfo['language']);
10106
    }
10107
    $languageInfo = api_get_language_info($languageId);
10108
    $isoCode = 'en';
10109
10110
    if (!empty($languageInfo)) {
10111
        $isoCode = $languageInfo['isocode'];
10112
    }
10113
10114
    // Split HTML in the separate language strings
10115
    // Note: some strings might look like <p><span ..>...</span></p> but others might be like combine 2 <span> in 1 <p>
10116
    if (!preg_match('/<span.*?lang="(\w\w)">/is', $htmlString)) {
10117
        return $htmlString;
10118
    }
10119
    $matches = [];
10120
    preg_match_all('/<span.*?lang="(\w\w)">(.*?)<\/span>/is', $htmlString, $matches);
10121
    if (!empty($matches)) {
10122
        // matches[0] are the full string
10123
        // matches[1] are the languages
10124
        // matches[2] are the strings
10125
        foreach ($matches[1] as $id => $match) {
10126
            if ($match == $isoCode) {
10127
                return $matches[2][$id];
10128
            }
10129
        }
10130
        // Could find the pattern but could not find our language. Return the first language found.
10131
        return $matches[2][0];
10132
    }
10133
    // Could not find pattern. Just return the whole string. We shouldn't get here.
10134
    return $htmlString;
10135
}
10136
10137
/**
10138
 * Get the print.css file for current theme.
10139
 * Only the file path or the file contents when $getFileContents is true.
10140
 */
10141
function api_get_print_css(bool $getFileContents = true, bool $useWebPath = false): string
10142
{
10143
    $sysCssPath = api_get_path(SYS_CSS_PATH);
10144
    $cssFile = $sysCssPath.'themes/'.api_get_visual_theme().'/print.css';
10145
10146
    if (!file_exists($cssFile)) {
10147
        $cssFile = $sysCssPath.'print.css';
10148
    }
10149
10150
    if ($getFileContents) {
10151
        return file_get_contents($cssFile);
10152
    }
10153
10154
    if ($useWebPath) {
10155
        return str_replace($sysCssPath, api_get_path(WEB_CSS_PATH), $cssFile);
10156
    }
10157
10158
    return $cssFile;
10159
}
10160