Passed
Pull Request — master (#5790)
by Angel Fernando Quiroz
25:02 queued 17:19
created

api_get_setting()   C

Complexity

Conditions 16
Paths 14

Size

Total Lines 60
Code Lines 37

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 16
eloc 37
c 2
b 0
f 0
nc 14
nop 3
dl 0
loc 60
rs 5.5666

How to fix   Long Method    Complexity   

Long Method

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

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

Commonly applied refactorings include:

1
<?php
2
3
/* For licensing terms, see /license.txt */
4
5
use Chamilo\CoreBundle\Entity\AccessUrl;
6
use Chamilo\CoreBundle\Entity\Course;
7
use Chamilo\CoreBundle\Entity\Language;
8
use Chamilo\CoreBundle\Entity\Session as SessionEntity;
9
use Chamilo\CoreBundle\Entity\SettingsCurrent;
10
use Chamilo\CoreBundle\Entity\User;
11
use Chamilo\CoreBundle\Entity\UserCourseCategory;
12
use Chamilo\CoreBundle\Exception\NotAllowedException;
13
use Chamilo\CoreBundle\Framework\Container;
14
use Chamilo\CoreBundle\ServiceHelper\AccessUrlHelper;
15
use Chamilo\CoreBundle\ServiceHelper\MailHelper;
16
use Chamilo\CoreBundle\ServiceHelper\PermissionServiceHelper;
17
use Chamilo\CoreBundle\ServiceHelper\ThemeHelper;
18
use Chamilo\CourseBundle\Entity\CGroup;
19
use Chamilo\CourseBundle\Entity\CLp;
20
use ChamiloSession as Session;
21
use Symfony\Bridge\Twig\Mime\TemplatedEmail;
22
use Symfony\Component\Finder\Finder;
23
use Symfony\Component\Mime\Address;
24
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
25
use Symfony\Component\Security\Core\User\UserInterface;
26
use Symfony\Component\Validator\Constraints as Assert;
27
use Symfony\Component\Yaml\Yaml;
28
use ZipStream\Option\Archive;
29
use ZipStream\ZipStream;
30
use Chamilo\CoreBundle\Component\Utils\ActionIcon;
31
use Chamilo\CoreBundle\Component\Utils\ObjectIcon;
32
33
/**
34
 * This is a code library for Chamilo.
35
 * It is included by default in every Chamilo file (through including the global.inc.php)
36
 * This library is in process of being transferred to src/Chamilo/CoreBundle/Component/Utils/ChamiloApi.
37
 * Whenever a function is transferred to the ChamiloApi class, the places where it is used should include
38
 * the "use Chamilo\CoreBundle\Component\Utils\ChamiloApi;" statement.
39
 */
40
41
// PHP version requirement.
42
define('REQUIRED_PHP_VERSION', '8.2');
43
define('REQUIRED_MIN_MEMORY_LIMIT', '128');
44
define('REQUIRED_MIN_UPLOAD_MAX_FILESIZE', '10');
45
define('REQUIRED_MIN_POST_MAX_SIZE', '10');
46
47
// USER STATUS CONSTANTS
48
/** global status of a user: student */
49
define('STUDENT', 5);
50
/** global status of a user: course manager */
51
define('COURSEMANAGER', 1);
52
/** global status of a user: session admin */
53
define('SESSIONADMIN', 3);
54
/** global status of a user: human resources manager */
55
define('DRH', 4);
56
/** global status of a user: anonymous visitor */
57
define('ANONYMOUS', 6);
58
/** global status of a user: low security, necessary for inserting data from
59
 * the teacher through HTMLPurifier */
60
define('COURSEMANAGERLOWSECURITY', 10);
61
// Soft user status
62
define('PLATFORM_ADMIN', 11);
63
define('SESSION_COURSE_COACH', 12);
64
define('SESSION_GENERAL_COACH', 13);
65
define('COURSE_STUDENT', 14); //student subscribed in a course
66
define('SESSION_STUDENT', 15); //student subscribed in a session course
67
define('COURSE_TUTOR', 16); // student is tutor of a course (NOT in session)
68
define('STUDENT_BOSS', 17); // student is boss
69
define('INVITEE', 20);
70
define('HRM_REQUEST', 21); //HRM has request for vinculation with user
71
72
// COURSE VISIBILITY CONSTANTS
73
/** only visible for course admin */
74
define('COURSE_VISIBILITY_CLOSED', 0);
75
/** only visible for users registered in the course */
76
define('COURSE_VISIBILITY_REGISTERED', 1);
77
/** Open for all registered users on the platform */
78
define('COURSE_VISIBILITY_OPEN_PLATFORM', 2);
79
/** Open for the whole world */
80
define('COURSE_VISIBILITY_OPEN_WORLD', 3);
81
/** Invisible to all except admin */
82
define('COURSE_VISIBILITY_HIDDEN', 4);
83
84
define('COURSE_REQUEST_PENDING', 0);
85
define('COURSE_REQUEST_ACCEPTED', 1);
86
define('COURSE_REQUEST_REJECTED', 2);
87
define('DELETE_ACTION_ENABLED', false);
88
89
// EMAIL SENDING RECIPIENT CONSTANTS
90
define('SEND_EMAIL_EVERYONE', 1);
91
define('SEND_EMAIL_STUDENTS', 2);
92
define('SEND_EMAIL_TEACHERS', 3);
93
94
// SESSION VISIBILITY CONSTANTS
95
define('SESSION_VISIBLE_READ_ONLY', 1);
96
define('SESSION_VISIBLE', 2);
97
define('SESSION_INVISIBLE', 3); // not available
98
define('SESSION_AVAILABLE', 4);
99
100
define('SESSION_LINK_TARGET', '_self');
101
102
define('SUBSCRIBE_ALLOWED', 1);
103
define('SUBSCRIBE_NOT_ALLOWED', 0);
104
define('UNSUBSCRIBE_ALLOWED', 1);
105
define('UNSUBSCRIBE_NOT_ALLOWED', 0);
106
107
// SURVEY VISIBILITY CONSTANTS
108
define('SURVEY_VISIBLE_TUTOR', 0);
109
define('SURVEY_VISIBLE_TUTOR_STUDENT', 1);
110
define('SURVEY_VISIBLE_PUBLIC', 2);
111
112
// CONSTANTS defining all tools, using the english version
113
/* When you add a new tool you must add it into function api_get_tools_lists() too */
114
define('TOOL_DOCUMENT', 'document');
115
define('TOOL_LP_FINAL_ITEM', 'final_item');
116
define('TOOL_READOUT_TEXT', 'readout_text');
117
define('TOOL_THUMBNAIL', 'thumbnail');
118
define('TOOL_HOTPOTATOES', 'hotpotatoes');
119
define('TOOL_CALENDAR_EVENT', 'calendar_event');
120
define('TOOL_LINK', 'link');
121
define('TOOL_LINK_CATEGORY', 'link_category');
122
define('TOOL_COURSE_DESCRIPTION', 'course_description');
123
define('TOOL_SEARCH', 'search');
124
define('TOOL_LEARNPATH', 'learnpath');
125
define('TOOL_LEARNPATH_CATEGORY', 'learnpath_category');
126
define('TOOL_AGENDA', 'agenda');
127
define('TOOL_ANNOUNCEMENT', 'announcement');
128
define('TOOL_FORUM', 'forum');
129
define('TOOL_FORUM_CATEGORY', 'forum_category');
130
define('TOOL_FORUM_THREAD', 'forum_thread');
131
define('TOOL_FORUM_POST', 'forum_post');
132
define('TOOL_FORUM_ATTACH', 'forum_attachment');
133
define('TOOL_FORUM_THREAD_QUALIFY', 'forum_thread_qualify');
134
define('TOOL_THREAD', 'thread');
135
define('TOOL_POST', 'post');
136
define('TOOL_DROPBOX', 'dropbox');
137
define('TOOL_QUIZ', 'quiz');
138
define('TOOL_TEST_CATEGORY', 'test_category');
139
define('TOOL_USER', 'user');
140
define('TOOL_GROUP', 'group');
141
define('TOOL_BLOGS', 'blog_management');
142
define('TOOL_CHAT', 'chat');
143
define('TOOL_STUDENTPUBLICATION', 'student_publication');
144
define('TOOL_TRACKING', 'tracking');
145
define('TOOL_HOMEPAGE_LINK', 'homepage_link');
146
define('TOOL_COURSE_SETTING', 'course_setting');
147
define('TOOL_BACKUP', 'backup');
148
define('TOOL_COPY_COURSE_CONTENT', 'copy_course_content');
149
define('TOOL_RECYCLE_COURSE', 'recycle_course');
150
define('TOOL_COURSE_HOMEPAGE', 'course_homepage');
151
define('TOOL_COURSE_RIGHTS_OVERVIEW', 'course_rights');
152
define('TOOL_UPLOAD', 'file_upload');
153
define('TOOL_COURSE_MAINTENANCE', 'course_maintenance');
154
define('TOOL_SURVEY', 'survey');
155
//define('TOOL_WIKI', 'wiki');
156
define('TOOL_GLOSSARY', 'glossary');
157
define('TOOL_GRADEBOOK', 'gradebook');
158
define('TOOL_NOTEBOOK', 'notebook');
159
define('TOOL_ATTENDANCE', 'attendance');
160
define('TOOL_COURSE_PROGRESS', 'course_progress');
161
define('TOOL_PORTFOLIO', 'portfolio');
162
define('TOOL_PLAGIARISM', 'compilatio');
163
define('TOOL_XAPI', 'xapi');
164
165
// CONSTANTS defining Chamilo interface sections
166
define('SECTION_CAMPUS', 'mycampus');
167
define('SECTION_COURSES', 'mycourses');
168
define('SECTION_CATALOG', 'catalog');
169
define('SECTION_MYPROFILE', 'myprofile');
170
define('SECTION_MYAGENDA', 'myagenda');
171
define('SECTION_COURSE_ADMIN', 'course_admin');
172
define('SECTION_PLATFORM_ADMIN', 'platform_admin');
173
define('SECTION_MYGRADEBOOK', 'mygradebook');
174
define('SECTION_TRACKING', 'session_my_space');
175
define('SECTION_SOCIAL', 'social-network');
176
define('SECTION_DASHBOARD', 'dashboard');
177
define('SECTION_REPORTS', 'reports');
178
define('SECTION_GLOBAL', 'global');
179
define('SECTION_INCLUDE', 'include');
180
define('SECTION_CUSTOMPAGE', 'custompage');
181
182
// CONSTANT name for local authentication source
183
define('PLATFORM_AUTH_SOURCE', 'platform');
184
define('CAS_AUTH_SOURCE', 'cas');
185
define('LDAP_AUTH_SOURCE', 'extldap');
186
187
// event logs types
188
define('LOG_COURSE_DELETE', 'course_deleted');
189
define('LOG_COURSE_CREATE', 'course_created');
190
define('LOG_COURSE_SETTINGS_CHANGED', 'course_settings_changed');
191
192
// @todo replace 'soc_gr' with social_group
193
define('LOG_GROUP_PORTAL_CREATED', 'soc_gr_created');
194
define('LOG_GROUP_PORTAL_UPDATED', 'soc_gr_updated');
195
define('LOG_GROUP_PORTAL_DELETED', 'soc_gr_deleted');
196
define('LOG_GROUP_PORTAL_USER_DELETE_ALL', 'soc_gr_delete_users');
197
198
define('LOG_GROUP_PORTAL_ID', 'soc_gr_portal_id');
199
define('LOG_GROUP_PORTAL_REL_USER_ARRAY', 'soc_gr_user_array');
200
201
define('LOG_GROUP_PORTAL_USER_SUBSCRIBED', 'soc_gr_u_subs');
202
define('LOG_GROUP_PORTAL_USER_UNSUBSCRIBED', 'soc_gr_u_unsubs');
203
define('LOG_GROUP_PORTAL_USER_UPDATE_ROLE', 'soc_gr_update_role');
204
205
define('LOG_MESSAGE_DATA', 'message_data');
206
define('LOG_MESSAGE_DELETE', 'msg_deleted');
207
208
define('LOG_USER_DELETE', 'user_deleted');
209
define('LOG_USER_PREDELETE', 'user_predeleted');
210
define('LOG_USER_CREATE', 'user_created');
211
define('LOG_USER_UPDATE', 'user_updated');
212
define('LOG_USER_PASSWORD_UPDATE', 'user_password_updated');
213
define('LOG_USER_ENABLE', 'user_enable');
214
define('LOG_USER_DISABLE', 'user_disable');
215
define('LOG_USER_ANONYMIZE', 'user_anonymized');
216
define('LOG_USER_FIELD_CREATE', 'user_field_created');
217
define('LOG_USER_FIELD_DELETE', 'user_field_deleted');
218
define('LOG_SESSION_CREATE', 'session_created');
219
define('LOG_SESSION_DELETE', 'session_deleted');
220
define('LOG_SESSION_ADD_USER_COURSE', 'session_add_user_course');
221
define('LOG_SESSION_DELETE_USER_COURSE', 'session_delete_user_course');
222
define('LOG_SESSION_ADD_USER', 'session_add_user');
223
define('LOG_SESSION_DELETE_USER', 'session_delete_user');
224
define('LOG_SESSION_ADD_COURSE', 'session_add_course');
225
define('LOG_SESSION_DELETE_COURSE', 'session_delete_course');
226
define('LOG_SESSION_CATEGORY_CREATE', 'session_cat_created'); //changed in 1.9.8
227
define('LOG_SESSION_CATEGORY_DELETE', 'session_cat_deleted'); //changed in 1.9.8
228
define('LOG_CONFIGURATION_SETTINGS_CHANGE', 'settings_changed');
229
define('LOG_PLATFORM_LANGUAGE_CHANGE', 'platform_lng_changed'); //changed in 1.9.8
230
define('LOG_SUBSCRIBE_USER_TO_COURSE', 'user_subscribed');
231
define('LOG_UNSUBSCRIBE_USER_FROM_COURSE', 'user_unsubscribed');
232
define('LOG_ATTEMPTED_FORCED_LOGIN', 'attempted_forced_login');
233
define('LOG_PLUGIN_CHANGE', 'plugin_changed');
234
define('LOG_HOMEPAGE_CHANGED', 'homepage_changed');
235
define('LOG_PROMOTION_CREATE', 'promotion_created');
236
define('LOG_PROMOTION_DELETE', 'promotion_deleted');
237
define('LOG_CAREER_CREATE', 'career_created');
238
define('LOG_CAREER_DELETE', 'career_deleted');
239
define('LOG_USER_PERSONAL_DOC_DELETED', 'user_doc_deleted');
240
//define('LOG_WIKI_ACCESS', 'wiki_page_view');
241
// All results from an exercise
242
define('LOG_EXERCISE_RESULT_DELETE', 'exe_result_deleted');
243
// Logs only the one attempt
244
define('LOG_EXERCISE_ATTEMPT_DELETE', 'exe_attempt_deleted');
245
define('LOG_LP_ATTEMPT_DELETE', 'lp_attempt_deleted');
246
define('LOG_QUESTION_RESULT_DELETE', 'qst_attempt_deleted');
247
define('LOG_QUESTION_SCORE_UPDATE', 'score_attempt_updated');
248
249
define('LOG_MY_FOLDER_CREATE', 'my_folder_created');
250
define('LOG_MY_FOLDER_CHANGE', 'my_folder_changed');
251
define('LOG_MY_FOLDER_DELETE', 'my_folder_deleted');
252
define('LOG_MY_FOLDER_COPY', 'my_folder_copied');
253
define('LOG_MY_FOLDER_CUT', 'my_folder_cut');
254
define('LOG_MY_FOLDER_PASTE', 'my_folder_pasted');
255
define('LOG_MY_FOLDER_UPLOAD', 'my_folder_uploaded');
256
257
// Event logs data types (max 20 chars)
258
define('LOG_COURSE_CODE', 'course_code');
259
define('LOG_COURSE_ID', 'course_id');
260
define('LOG_USER_ID', 'user_id');
261
define('LOG_USER_OBJECT', 'user_object');
262
define('LOG_USER_FIELD_VARIABLE', 'user_field_variable');
263
define('LOG_SESSION_ID', 'session_id');
264
265
define('LOG_QUESTION_ID', 'question_id');
266
define('LOG_SESSION_CATEGORY_ID', 'session_category_id');
267
define('LOG_CONFIGURATION_SETTINGS_CATEGORY', 'settings_category');
268
define('LOG_CONFIGURATION_SETTINGS_VARIABLE', 'settings_variable');
269
define('LOG_PLATFORM_LANGUAGE', 'default_platform_language');
270
define('LOG_PLUGIN_UPLOAD', 'plugin_upload');
271
define('LOG_PLUGIN_ENABLE', 'plugin_enable');
272
define('LOG_PLUGIN_SETTINGS_CHANGE', 'plugin_settings_change');
273
define('LOG_CAREER_ID', 'career_id');
274
define('LOG_PROMOTION_ID', 'promotion_id');
275
define('LOG_GRADEBOOK_LOCKED', 'gradebook_locked');
276
define('LOG_GRADEBOOK_UNLOCKED', 'gradebook_unlocked');
277
define('LOG_GRADEBOOK_ID', 'gradebook_id');
278
//define('LOG_WIKI_PAGE_ID', 'wiki_page_id');
279
define('LOG_EXERCISE_ID', 'exercise_id');
280
define('LOG_EXERCISE_AND_USER_ID', 'exercise_and_user_id');
281
define('LOG_LP_ID', 'lp_id');
282
define('LOG_EXERCISE_ATTEMPT_QUESTION_ID', 'exercise_a_q_id');
283
define('LOG_EXERCISE_ATTEMPT', 'exe_id');
284
285
define('LOG_WORK_DIR_DELETE', 'work_dir_delete');
286
define('LOG_WORK_FILE_DELETE', 'work_file_delete');
287
define('LOG_WORK_DATA', 'work_data_array');
288
289
define('LOG_MY_FOLDER_PATH', 'path');
290
define('LOG_MY_FOLDER_NEW_PATH', 'new_path');
291
292
define('LOG_TERM_CONDITION_ACCEPTED', 'term_condition_accepted');
293
define('LOG_USER_CONFIRMED_EMAIL', 'user_confirmed_email');
294
define('LOG_USER_REMOVED_LEGAL_ACCEPT', 'user_removed_legal_accept');
295
296
define('LOG_USER_DELETE_ACCOUNT_REQUEST', 'user_delete_account_request');
297
298
define('LOG_QUESTION_CREATED', 'question_created');
299
define('LOG_QUESTION_UPDATED', 'question_updated');
300
define('LOG_QUESTION_DELETED', 'question_deleted');
301
define('LOG_QUESTION_REMOVED_FROM_QUIZ', 'question_removed_from_quiz');
302
303
define('LOG_SURVEY_ID', 'survey_id');
304
define('LOG_SURVEY_CREATED', 'survey_created');
305
define('LOG_SURVEY_DELETED', 'survey_deleted');
306
define('LOG_SURVEY_CLEAN_RESULTS', 'survey_clean_results');
307
define('USERNAME_PURIFIER', '/[^0-9A-Za-z_\.@\$-]/');
308
309
//used when login_is_email setting is true
310
define('USERNAME_PURIFIER_MAIL', '/[^0-9A-Za-z_\.@]/');
311
define('USERNAME_PURIFIER_SHALLOW', '/\s/');
312
313
// This constant is a result of Windows OS detection, it has a boolean value:
314
// true whether the server runs on Windows OS, false otherwise.
315
define('IS_WINDOWS_OS', api_is_windows_os());
316
317
// Patterns for processing paths. Examples.
318
define('REPEATED_SLASHES_PURIFIER', '/\/{2,}/'); // $path = preg_replace(REPEATED_SLASHES_PURIFIER, '/', $path);
319
define('VALID_WEB_PATH', '/https?:\/\/[^\/]*(\/.*)?/i'); // $is_valid_path = preg_match(VALID_WEB_PATH, $path);
320
// $new_path = preg_replace(VALID_WEB_SERVER_BASE, $new_base, $path);
321
define('VALID_WEB_SERVER_BASE', '/https?:\/\/[^\/]*/i');
322
// Constants for api_get_path() and api_get_path_type(), etc. - registered path types.
323
// basic (leaf elements)
324
define('REL_CODE_PATH', 'REL_CODE_PATH');
325
define('REL_COURSE_PATH', 'REL_COURSE_PATH');
326
define('REL_HOME_PATH', 'REL_HOME_PATH');
327
328
// Constants for api_get_path() and api_get_path_type(), etc. - registered path types.
329
define('WEB_PATH', 'WEB_PATH');
330
define('SYS_PATH', 'SYS_PATH');
331
define('SYMFONY_SYS_PATH', 'SYMFONY_SYS_PATH');
332
333
define('REL_PATH', 'REL_PATH');
334
define('WEB_COURSE_PATH', 'WEB_COURSE_PATH');
335
define('WEB_CODE_PATH', 'WEB_CODE_PATH');
336
define('SYS_CODE_PATH', 'SYS_CODE_PATH');
337
define('SYS_LANG_PATH', 'SYS_LANG_PATH');
338
define('WEB_IMG_PATH', 'WEB_IMG_PATH');
339
define('WEB_CSS_PATH', 'WEB_CSS_PATH');
340
define('WEB_PUBLIC_PATH', 'WEB_PUBLIC_PATH');
341
define('SYS_CSS_PATH', 'SYS_CSS_PATH');
342
define('SYS_PLUGIN_PATH', 'SYS_PLUGIN_PATH');
343
define('WEB_PLUGIN_PATH', 'WEB_PLUGIN_PATH');
344
define('WEB_PLUGIN_ASSET_PATH', 'WEB_PLUGIN_ASSET_PATH');
345
define('SYS_ARCHIVE_PATH', 'SYS_ARCHIVE_PATH');
346
define('WEB_ARCHIVE_PATH', 'WEB_ARCHIVE_PATH');
347
define('LIBRARY_PATH', 'LIBRARY_PATH');
348
define('CONFIGURATION_PATH', 'CONFIGURATION_PATH');
349
define('WEB_LIBRARY_PATH', 'WEB_LIBRARY_PATH');
350
define('WEB_LIBRARY_JS_PATH', 'WEB_LIBRARY_JS_PATH');
351
define('WEB_AJAX_PATH', 'WEB_AJAX_PATH');
352
define('SYS_TEST_PATH', 'SYS_TEST_PATH');
353
define('SYS_TEMPLATE_PATH', 'SYS_TEMPLATE_PATH');
354
define('SYS_PUBLIC_PATH', 'SYS_PUBLIC_PATH');
355
define('SYS_FONTS_PATH', 'SYS_FONTS_PATH');
356
357
// Relations type with Course manager
358
define('COURSE_RELATION_TYPE_COURSE_MANAGER', 1);
359
360
// Relations type with Human resources manager
361
define('COURSE_RELATION_TYPE_RRHH', 1);
362
363
// User image sizes
364
define('USER_IMAGE_SIZE_ORIGINAL', 1);
365
define('USER_IMAGE_SIZE_BIG', 2);
366
define('USER_IMAGE_SIZE_MEDIUM', 3);
367
define('USER_IMAGE_SIZE_SMALL', 4);
368
369
// Gradebook link constants
370
// Please do not change existing values, they are used in the database !
371
define('GRADEBOOK_ITEM_LIMIT', 1000);
372
373
define('LINK_EXERCISE', 1);
374
define('LINK_DROPBOX', 2);
375
define('LINK_STUDENTPUBLICATION', 3);
376
define('LINK_LEARNPATH', 4);
377
define('LINK_FORUM_THREAD', 5);
378
//define('LINK_WORK',6);
379
define('LINK_ATTENDANCE', 7);
380
define('LINK_SURVEY', 8);
381
define('LINK_HOTPOTATOES', 9);
382
define('LINK_PORTFOLIO', 10);
383
384
// Score display types constants
385
define('SCORE_DIV', 1); // X / Y
386
define('SCORE_PERCENT', 2); // XX %
387
define('SCORE_DIV_PERCENT', 3); // X / Y (XX %)
388
define('SCORE_AVERAGE', 4); // XX %
389
define('SCORE_DECIMAL', 5); // 0.50  (X/Y)
390
define('SCORE_BAR', 6); // Uses the Display::bar_progress function
391
define('SCORE_SIMPLE', 7); // X
392
define('SCORE_IGNORE_SPLIT', 8); //  ??
393
define('SCORE_DIV_PERCENT_WITH_CUSTOM', 9); // X / Y (XX %) - Good!
394
define('SCORE_CUSTOM', 10); // Good!
395
define('SCORE_DIV_SIMPLE_WITH_CUSTOM', 11); // X - Good!
396
define('SCORE_DIV_SIMPLE_WITH_CUSTOM_LETTERS', 12); // X - Good!
397
define('SCORE_ONLY_SCORE', 13); // X - Good!
398
define('SCORE_NUMERIC', 14);
399
400
define('SCORE_BOTH', 1);
401
define('SCORE_ONLY_DEFAULT', 2);
402
define('SCORE_ONLY_CUSTOM', 3);
403
404
// From display.lib.php
405
406
define('MAX_LENGTH_BREADCRUMB', 100);
407
define('ICON_SIZE_ATOM', 8);
408
define('ICON_SIZE_TINY', 16);
409
define('ICON_SIZE_SMALL', 22);
410
define('ICON_SIZE_MEDIUM', 32);
411
define('ICON_SIZE_LARGE', 48);
412
define('ICON_SIZE_BIG', 64);
413
define('ICON_SIZE_HUGE', 128);
414
define('SHOW_TEXT_NEAR_ICONS', false);
415
416
// Session catalog
417
define('CATALOG_COURSES', 0);
418
define('CATALOG_SESSIONS', 1);
419
define('CATALOG_COURSES_SESSIONS', 2);
420
421
// Hook type events, pre-process and post-process.
422
// All means to be executed for both hook event types
423
define('HOOK_EVENT_TYPE_PRE', 0);
424
define('HOOK_EVENT_TYPE_POST', 1);
425
define('HOOK_EVENT_TYPE_ALL', 10);
426
427
// Group permissions
428
define('GROUP_PERMISSION_OPEN', '1');
429
define('GROUP_PERMISSION_CLOSED', '2');
430
431
// Group user permissions
432
define('GROUP_USER_PERMISSION_ADMIN', 1); // the admin of a group
433
define('GROUP_USER_PERMISSION_READER', 2); // a normal user
434
define('GROUP_USER_PERMISSION_PENDING_INVITATION', 3); // When an admin/moderator invites a user
435
define('GROUP_USER_PERMISSION_PENDING_INVITATION_SENT_BY_USER', 4); // an user joins a group
436
define('GROUP_USER_PERMISSION_MODERATOR', 5); // a moderator
437
define('GROUP_USER_PERMISSION_ANONYMOUS', 6); // an anonymous user
438
define('GROUP_USER_PERMISSION_HRM', 7); // a human resources manager
439
440
define('GROUP_IMAGE_SIZE_ORIGINAL', 1);
441
define('GROUP_IMAGE_SIZE_BIG', 2);
442
define('GROUP_IMAGE_SIZE_MEDIUM', 3);
443
define('GROUP_IMAGE_SIZE_SMALL', 4);
444
define('GROUP_TITLE_LENGTH', 50);
445
446
// Exercise
447
// @todo move into a class
448
define('ALL_ON_ONE_PAGE', 1);
449
define('ONE_PER_PAGE', 2);
450
451
define('EXERCISE_FEEDBACK_TYPE_END', 0); //Feedback 		 - show score and expected answers
452
define('EXERCISE_FEEDBACK_TYPE_DIRECT', 1); //DirectFeedback - Do not show score nor answers
453
define('EXERCISE_FEEDBACK_TYPE_EXAM', 2); // NoFeedback 	 - Show score only
454
define('EXERCISE_FEEDBACK_TYPE_POPUP', 3); // Popup BT#15827
455
456
define('RESULT_DISABLE_SHOW_SCORE_AND_EXPECTED_ANSWERS', 0); //show score and expected answers
457
define('RESULT_DISABLE_NO_SCORE_AND_EXPECTED_ANSWERS', 1); //Do not show score nor answers
458
define('RESULT_DISABLE_SHOW_SCORE_ONLY', 2); //Show score only
459
define('RESULT_DISABLE_SHOW_FINAL_SCORE_ONLY_WITH_CATEGORIES', 3); //Show final score only with categories
460
define('RESULT_DISABLE_SHOW_SCORE_ATTEMPT_SHOW_ANSWERS_LAST_ATTEMPT', 4);
461
define('RESULT_DISABLE_DONT_SHOW_SCORE_ONLY_IF_USER_FINISHES_ATTEMPTS_SHOW_ALWAYS_FEEDBACK', 5);
462
define('RESULT_DISABLE_RANKING', 6);
463
define('RESULT_DISABLE_SHOW_ONLY_IN_CORRECT_ANSWER', 7);
464
define('RESULT_DISABLE_SHOW_SCORE_AND_EXPECTED_ANSWERS_AND_RANKING', 8);
465
define('RESULT_DISABLE_RADAR', 9);
466
define('RESULT_DISABLE_SHOW_SCORE_ATTEMPT_SHOW_ANSWERS_LAST_ATTEMPT_NO_FEEDBACK', 10);
467
468
define('EXERCISE_MAX_NAME_SIZE', 80);
469
470
// Question types (edit next array as well when adding values)
471
// @todo move into a class
472
define('UNIQUE_ANSWER', 1);
473
define('MULTIPLE_ANSWER', 2);
474
define('FILL_IN_BLANKS', 3);
475
define('MATCHING', 4);
476
define('FREE_ANSWER', 5);
477
define('HOT_SPOT', 6);
478
define('HOT_SPOT_ORDER', 7);
479
define('HOT_SPOT_DELINEATION', 8);
480
define('MULTIPLE_ANSWER_COMBINATION', 9);
481
define('UNIQUE_ANSWER_NO_OPTION', 10);
482
define('MULTIPLE_ANSWER_TRUE_FALSE', 11);
483
define('MULTIPLE_ANSWER_COMBINATION_TRUE_FALSE', 12);
484
define('ORAL_EXPRESSION', 13);
485
define('GLOBAL_MULTIPLE_ANSWER', 14);
486
define('MEDIA_QUESTION', 15);
487
define('CALCULATED_ANSWER', 16);
488
define('UNIQUE_ANSWER_IMAGE', 17);
489
define('DRAGGABLE', 18);
490
define('MATCHING_DRAGGABLE', 19);
491
define('ANNOTATION', 20);
492
define('READING_COMPREHENSION', 21);
493
define('MULTIPLE_ANSWER_TRUE_FALSE_DEGREE_CERTAINTY', 22);
494
495
define('EXERCISE_CATEGORY_RANDOM_SHUFFLED', 1);
496
define('EXERCISE_CATEGORY_RANDOM_ORDERED', 2);
497
define('EXERCISE_CATEGORY_RANDOM_DISABLED', 0);
498
499
// Question selection type
500
define('EX_Q_SELECTION_ORDERED', 1);
501
define('EX_Q_SELECTION_RANDOM', 2);
502
define('EX_Q_SELECTION_CATEGORIES_ORDERED_QUESTIONS_ORDERED', 3);
503
define('EX_Q_SELECTION_CATEGORIES_RANDOM_QUESTIONS_ORDERED', 4);
504
define('EX_Q_SELECTION_CATEGORIES_ORDERED_QUESTIONS_RANDOM', 5);
505
define('EX_Q_SELECTION_CATEGORIES_RANDOM_QUESTIONS_RANDOM', 6);
506
define('EX_Q_SELECTION_CATEGORIES_RANDOM_QUESTIONS_ORDERED_NO_GROUPED', 7);
507
define('EX_Q_SELECTION_CATEGORIES_RANDOM_QUESTIONS_RANDOM_NO_GROUPED', 8);
508
define('EX_Q_SELECTION_CATEGORIES_ORDERED_BY_PARENT_QUESTIONS_ORDERED', 9);
509
define('EX_Q_SELECTION_CATEGORIES_ORDERED_BY_PARENT_QUESTIONS_RANDOM', 10);
510
511
// Used to save the skill_rel_item table
512
define('ITEM_TYPE_EXERCISE', 1);
513
define('ITEM_TYPE_HOTPOTATOES', 2);
514
define('ITEM_TYPE_LINK', 3);
515
define('ITEM_TYPE_LEARNPATH', 4);
516
define('ITEM_TYPE_GRADEBOOK', 5);
517
define('ITEM_TYPE_STUDENT_PUBLICATION', 6);
518
//define('ITEM_TYPE_FORUM', 7);
519
define('ITEM_TYPE_ATTENDANCE', 8);
520
define('ITEM_TYPE_SURVEY', 9);
521
define('ITEM_TYPE_FORUM_THREAD', 10);
522
define('ITEM_TYPE_PORTFOLIO', 11);
523
524
// Course description blocks.
525
define('ADD_BLOCK', 8);
526
527
// one big string with all question types, for the validator in pear/HTML/QuickForm/Rule/QuestionType
528
define(
529
    'QUESTION_TYPES',
530
    UNIQUE_ANSWER.':'.
531
    MULTIPLE_ANSWER.':'.
532
    FILL_IN_BLANKS.':'.
533
    MATCHING.':'.
534
    FREE_ANSWER.':'.
535
    HOT_SPOT.':'.
536
    HOT_SPOT_ORDER.':'.
537
    HOT_SPOT_DELINEATION.':'.
538
    MULTIPLE_ANSWER_COMBINATION.':'.
539
    UNIQUE_ANSWER_NO_OPTION.':'.
540
    MULTIPLE_ANSWER_TRUE_FALSE.':'.
541
    MULTIPLE_ANSWER_COMBINATION_TRUE_FALSE.':'.
542
    ORAL_EXPRESSION.':'.
543
    GLOBAL_MULTIPLE_ANSWER.':'.
544
    MEDIA_QUESTION.':'.
545
    CALCULATED_ANSWER.':'.
546
    UNIQUE_ANSWER_IMAGE.':'.
547
    DRAGGABLE.':'.
548
    MATCHING_DRAGGABLE.':'.
549
    MULTIPLE_ANSWER_TRUE_FALSE_DEGREE_CERTAINTY.':'.
550
    ANNOTATION
551
);
552
553
//Some alias used in the QTI exports
554
define('MCUA', 1);
555
define('TF', 1);
556
define('MCMA', 2);
557
define('FIB', 3);
558
559
// Message
560
define('MESSAGE_STATUS_INVITATION_PENDING', 5);
561
define('MESSAGE_STATUS_INVITATION_ACCEPTED', 6);
562
define('MESSAGE_STATUS_INVITATION_DENIED', 7);
563
define('MESSAGE_STATUS_WALL', 8);
564
565
define('MESSAGE_STATUS_WALL_DELETE', 9);
566
define('MESSAGE_STATUS_WALL_POST', 10);
567
568
define('MESSAGE_STATUS_FORUM', 12);
569
define('MESSAGE_STATUS_PROMOTED', 13);
570
571
// Images
572
define('IMAGE_WALL_SMALL_SIZE', 200);
573
define('IMAGE_WALL_MEDIUM_SIZE', 500);
574
define('IMAGE_WALL_BIG_SIZE', 2000);
575
define('IMAGE_WALL_SMALL', 'small');
576
define('IMAGE_WALL_MEDIUM', 'medium');
577
define('IMAGE_WALL_BIG', 'big');
578
579
// Social PLUGIN PLACES
580
define('SOCIAL_LEFT_PLUGIN', 1);
581
define('SOCIAL_CENTER_PLUGIN', 2);
582
define('SOCIAL_RIGHT_PLUGIN', 3);
583
define('CUT_GROUP_NAME', 50);
584
585
/**
586
 * FormValidator Filter.
587
 */
588
define('NO_HTML', 1);
589
define('STUDENT_HTML', 2);
590
define('TEACHER_HTML', 3);
591
define('STUDENT_HTML_FULLPAGE', 4);
592
define('TEACHER_HTML_FULLPAGE', 5);
593
594
// Timeline
595
define('TIMELINE_STATUS_ACTIVE', '1');
596
define('TIMELINE_STATUS_INACTIVE', '2');
597
598
// Event email template class
599
define('EVENT_EMAIL_TEMPLATE_ACTIVE', 1);
600
define('EVENT_EMAIL_TEMPLATE_INACTIVE', 0);
601
602
// Course home
603
define('SHORTCUTS_HORIZONTAL', 0);
604
define('SHORTCUTS_VERTICAL', 1);
605
606
// Course copy
607
define('FILE_SKIP', 1);
608
define('FILE_RENAME', 2);
609
define('FILE_OVERWRITE', 3);
610
define('UTF8_CONVERT', false); //false by default
611
612
define('DOCUMENT', 'file');
613
define('FOLDER', 'folder');
614
615
define('RESOURCE_ASSET', 'asset');
616
define('RESOURCE_DOCUMENT', 'document');
617
define('RESOURCE_GLOSSARY', 'glossary');
618
define('RESOURCE_EVENT', 'calendar_event');
619
define('RESOURCE_LINK', 'link');
620
define('RESOURCE_COURSEDESCRIPTION', 'course_description');
621
define('RESOURCE_LEARNPATH', 'learnpath');
622
define('RESOURCE_LEARNPATH_CATEGORY', 'learnpath_category');
623
define('RESOURCE_ANNOUNCEMENT', 'announcement');
624
define('RESOURCE_FORUM', 'forum');
625
define('RESOURCE_FORUMTOPIC', 'thread');
626
define('RESOURCE_FORUMPOST', 'post');
627
define('RESOURCE_QUIZ', 'quiz');
628
define('RESOURCE_TEST_CATEGORY', 'test_category');
629
define('RESOURCE_QUIZQUESTION', 'Exercise_Question');
630
define('RESOURCE_TOOL_INTRO', 'Tool introduction');
631
define('RESOURCE_LINKCATEGORY', 'Link_Category');
632
define('RESOURCE_FORUMCATEGORY', 'Forum_Category');
633
define('RESOURCE_SCORM', 'Scorm');
634
define('RESOURCE_SURVEY', 'survey');
635
define('RESOURCE_SURVEYQUESTION', 'survey_question');
636
define('RESOURCE_SURVEYINVITATION', 'survey_invitation');
637
//define('RESOURCE_WIKI', 'wiki');
638
define('RESOURCE_THEMATIC', 'thematic');
639
define('RESOURCE_ATTENDANCE', 'attendance');
640
define('RESOURCE_WORK', 'work');
641
define('RESOURCE_SESSION_COURSE', 'session_course');
642
define('RESOURCE_GRADEBOOK', 'gradebook');
643
define('ADD_THEMATIC_PLAN', 6);
644
645
// Max online users to show per page (whoisonline)
646
define('MAX_ONLINE_USERS', 12);
647
648
define('TOOL_AUTHORING', 'toolauthoring');
649
define('TOOL_INTERACTION', 'toolinteraction');
650
define('TOOL_COURSE_PLUGIN', 'toolcourseplugin'); //all plugins that can be enabled in courses
651
define('TOOL_ADMIN', 'tooladmin');
652
define('TOOL_ADMIN_PLATFORM', 'tooladminplatform');
653
define('TOOL_DRH', 'tool_drh');
654
define('TOOL_STUDENT_VIEW', 'toolstudentview');
655
define('TOOL_ADMIN_VISIBLE', 'tooladminvisible');
656
657
// Search settings (from main/inc/lib/search/IndexableChunk.class.php )
658
// some constants to avoid serialize string keys on serialized data array
659
define('SE_COURSE_ID', 0);
660
define('SE_TOOL_ID', 1);
661
define('SE_DATA', 2);
662
define('SE_USER', 3);
663
664
// in some cases we need top differenciate xapian documents of the same tool
665
define('SE_DOCTYPE_EXERCISE_EXERCISE', 0);
666
define('SE_DOCTYPE_EXERCISE_QUESTION', 1);
667
668
// xapian prefixes
669
define('XAPIAN_PREFIX_COURSEID', 'C');
670
define('XAPIAN_PREFIX_TOOLID', 'O');
671
672
// User active field constants
673
define('USER_ACTIVE', 1);
674
define('USER_INACTIVE', 0);
675
define('USER_INACTIVE_AUTOMATIC', -1);
676
define('USER_SOFT_DELETED', -2);
677
678
/**
679
 * Returns a path to a certain resource within Chamilo.
680
 *
681
 * @param string $path A path which type is to be converted. Also, it may be a defined constant for a path.
682
 *
683
 * @return string the requested path or the converted path
684
 *
685
 * Notes about the current behaviour model:
686
 * 1. Windows back-slashes are converted to slashes in the result.
687
 * 2. A semi-absolute web-path is detected by its leading slash. On Linux systems, absolute system paths start with
688
 * a slash too, so an additional check about presence of leading system server base is implemented. For example, the function is
689
 * able to distinguish type difference between /var/www/chamilo/courses/ (SYS) and /chamilo/courses/ (REL).
690
 * 3. The function api_get_path() returns only these three types of paths, which in some sense are absolute. The function has
691
 * no a mechanism for processing relative web/system paths, such as: lesson01.html, ./lesson01.html, ../css/my_styles.css.
692
 * It has not been identified as needed yet.
693
 * 4. Also, resolving the meta-symbols "." and ".." within paths has not been implemented, it is to be identified as needed.
694
 *
695
 * Vchamilo changes : allow using an alternate configuration
696
 * to get vchamilo  instance paths
697
 */
698
function api_get_path($path = '', $configuration = [])
699
{
700
    global $paths;
701
702
    // get proper configuration data if exists
703
    global $_configuration;
704
705
    $emptyConfigurationParam = false;
706
    if (empty($configuration)) {
707
        $configuration = (array) $_configuration;
708
        $emptyConfigurationParam = true;
709
    }
710
711
    $root_sys = Container::getProjectDir();
712
    $root_web = '';
713
    if (isset(Container::$container)) {
714
        $root_web = Container::$container->get('router')->generate(
715
            'index',
716
            [],
717
            UrlGeneratorInterface::ABSOLUTE_URL
718
        );
719
    }
720
721
    /*if (api_get_multiple_access_url()) {
722
        // To avoid that the api_get_access_url() function fails since global.inc.php also calls the main_api.lib.php
723
        if (isset($configuration['access_url']) && !empty($configuration['access_url'])) {
724
            // We look into the DB the function api_get_access_url
725
            $urlInfo = api_get_access_url($configuration['access_url']);
726
            // Avoid default value
727
            $defaultValues = ['http://localhost/', 'https://localhost/'];
728
            if (!empty($urlInfo['url']) && !in_array($urlInfo['url'], $defaultValues)) {
729
                $root_web = 1 == $urlInfo['active'] ? $urlInfo['url'] : $configuration['root_web'];
730
            }
731
        }
732
    }*/
733
734
    $paths = [
735
        WEB_PATH => $root_web,
736
        SYMFONY_SYS_PATH => $root_sys,
737
        SYS_PATH => $root_sys.'public/',
738
        REL_PATH => '',
739
        CONFIGURATION_PATH => 'app/config/',
740
        LIBRARY_PATH => $root_sys.'public/main/inc/lib/',
741
742
        REL_COURSE_PATH => '',
743
        REL_CODE_PATH => '/main/',
744
745
        SYS_CODE_PATH => $root_sys.'public/main/',
746
        SYS_CSS_PATH => $root_sys.'public/build/css/',
747
        SYS_PLUGIN_PATH => $root_sys.'public/plugin/',
748
        SYS_ARCHIVE_PATH => $root_sys.'var/cache/',
749
        SYS_TEST_PATH => $root_sys.'tests/',
750
        SYS_TEMPLATE_PATH => $root_sys.'public/main/template/',
751
        SYS_PUBLIC_PATH => $root_sys.'public/',
752
        SYS_FONTS_PATH => $root_sys.'public/fonts/',
753
754
        WEB_CODE_PATH => $root_web.'main/',
755
        WEB_PLUGIN_ASSET_PATH => $root_web.'plugins/',
756
        WEB_COURSE_PATH => $root_web.'course/',
757
        WEB_IMG_PATH => $root_web.'img/',
758
        WEB_CSS_PATH => $root_web.'build/css/',
759
        WEB_AJAX_PATH => $root_web.'main/inc/ajax/',
760
        WEB_LIBRARY_PATH => $root_web.'main/inc/lib/',
761
        WEB_LIBRARY_JS_PATH => $root_web.'main/inc/lib/javascript/',
762
        WEB_PLUGIN_PATH => $root_web.'plugin/',
763
        WEB_PUBLIC_PATH => $root_web,
764
    ];
765
766
    $root_rel = '';
767
768
    global $virtualChamilo;
769
    if (!empty($virtualChamilo)) {
770
        $paths[SYS_ARCHIVE_PATH] = api_add_trailing_slash($virtualChamilo[SYS_ARCHIVE_PATH]);
771
        //$paths[SYS_UPLOAD_PATH] = api_add_trailing_slash($virtualChamilo[SYS_UPLOAD_PATH]);
772
        //$paths[$root_web][WEB_UPLOAD_PATH] = api_add_trailing_slash($virtualChamilo[WEB_UPLOAD_PATH]);
773
        $paths[WEB_ARCHIVE_PATH] = api_add_trailing_slash($virtualChamilo[WEB_ARCHIVE_PATH]);
774
        //$paths[$root_web][WEB_COURSE_PATH] = api_add_trailing_slash($virtualChamilo[WEB_COURSE_PATH]);
775
776
        // WEB_UPLOAD_PATH should be handle by apache htaccess in the vhost
777
778
        // RewriteEngine On
779
        // RewriteRule /app/upload/(.*)$ http://localhost/other/upload/my-chamilo111-net/$1 [QSA,L]
780
781
        //$paths[$root_web][WEB_UPLOAD_PATH] = api_add_trailing_slash($virtualChamilo[WEB_UPLOAD_PATH]);
782
        //$paths[$root_web][REL_PATH] = $virtualChamilo[REL_PATH];
783
        //$paths[$root_web][REL_COURSE_PATH] = $virtualChamilo[REL_COURSE_PATH];
784
    }
785
786
    $path = trim($path);
787
788
    // Retrieving a common-purpose path.
789
    if (isset($paths[$path])) {
790
        return $paths[$path];
791
    }
792
793
    return false;
794
}
795
796
/**
797
 * Adds to a given path a trailing slash if it is necessary (adds "/" character at the end of the string).
798
 *
799
 * @param string $path the input path
800
 *
801
 * @return string returns the modified path
802
 */
803
function api_add_trailing_slash($path)
804
{
805
    return '/' === substr($path, -1) ? $path : $path.'/';
806
}
807
808
/**
809
 * Removes from a given path the trailing slash if it is necessary (removes "/" character from the end of the string).
810
 *
811
 * @param string $path the input path
812
 *
813
 * @return string returns the modified path
814
 */
815
function api_remove_trailing_slash($path)
816
{
817
    return '/' === substr($path, -1) ? substr($path, 0, -1) : $path;
818
}
819
820
/**
821
 * Checks the RFC 3986 syntax of a given URL.
822
 *
823
 * @param string $url      the URL to be checked
824
 * @param bool   $absolute whether the URL is absolute (beginning with a scheme such as "http:")
825
 *
826
 * @return string|false Returns the URL if it is valid, FALSE otherwise.
827
 *                      This function is an adaptation from the function valid_url(), Drupal CMS.
828
 *
829
 * @see http://drupal.org
830
 * Note: The built-in function filter_var($urs, FILTER_VALIDATE_URL) has a bug for some versions of PHP.
831
 * @see http://bugs.php.net/51192
832
 */
833
function api_valid_url($url, $absolute = false)
834
{
835
    if ($absolute) {
836
        if (preg_match("
837
            /^                                                      # Start at the beginning of the text
838
            (?:ftp|https?|feed):\/\/                                # Look for ftp, http, https or feed schemes
839
            (?:                                                     # Userinfo (optional) which is typically
840
                (?:(?:[\w\.\-\+!$&'\(\)*\+,;=]|%[0-9a-f]{2})+:)*    # a username or a username and password
841
                (?:[\w\.\-\+%!$&'\(\)*\+,;=]|%[0-9a-f]{2})+@        # combination
842
            )?
843
            (?:
844
                (?:[a-z0-9\-\.]|%[0-9a-f]{2})+                      # A domain name or a IPv4 address
845
                |(?:\[(?:[0-9a-f]{0,4}:)*(?:[0-9a-f]{0,4})\])       # or a well formed IPv6 address
846
            )
847
            (?::[0-9]+)?                                            # Server port number (optional)
848
            (?:[\/|\?]
849
                (?:[\w#!:\.\?\+=&@$'~*,;\/\(\)\[\]\-]|%[0-9a-f]{2}) # The path and query (optional)
850
            *)?
851
            $/xi", $url)) {
852
            return $url;
853
        }
854
855
        return false;
856
    } else {
857
        return preg_match("/^(?:[\w#!:\.\?\+=&@$'~*,;\/\(\)\[\]\-]|%[0-9a-f]{2})+$/i", $url) ? $url : false;
858
    }
859
}
860
861
/**
862
 * Checks whether a given string looks roughly like an email address.
863
 *
864
 * @param string $address the e-mail address to be checked
865
 *
866
 * @return mixed returns the e-mail if it is valid, FALSE otherwise
867
 */
868
function api_valid_email($address)
869
{
870
    return filter_var($address, FILTER_VALIDATE_EMAIL);
871
}
872
873
/**
874
 * Function used to protect a course script.
875
 * The function blocks access when
876
 * - there is no $_SESSION["_course"] defined; or
877
 * - $is_allowed_in_course is set to false (this depends on the course
878
 * visibility and user status).
879
 *
880
 * This is only the first proposal, test and improve!
881
 *
882
 * @param bool Option to print headers when displaying error message. Default: false
883
 * @param bool whether session admins should be allowed or not
884
 * @param string $checkTool check if tool is available for users (user, group)
885
 *
886
 * @return bool True if the user has access to the current course or is out of a course context, false otherwise
887
 *
888
 * @todo replace global variable
889
 *
890
 * @author Roan Embrechts
891
 */
892
function api_protect_course_script($print_headers = false, $allow_session_admins = false, string $checkTool = '', $cid = null): bool
893
{
894
    $course_info = api_get_course_info();
895
    if (empty($course_info) && isset($_REQUEST['cid'])) {
896
        $course_info = api_get_course_info_by_id((int) $_REQUEST['cid']);
897
    }
898
899
    if (isset($cid)) {
900
        $course_info = api_get_course_info_by_id($cid);
901
    }
902
903
    if (empty($course_info)) {
904
        api_not_allowed($print_headers);
905
906
        return false;
907
    }
908
909
    if (api_is_drh()) {
910
        return true;
911
    }
912
913
    // Session admin has access to course
914
    $sessionAccess = ('true' === api_get_setting('session.session_admins_access_all_content'));
915
    if ($sessionAccess) {
916
        $allow_session_admins = true;
917
    }
918
919
    if (api_is_platform_admin($allow_session_admins)) {
920
        return true;
921
    }
922
923
    $isAllowedInCourse = api_is_allowed_in_course();
924
    $is_visible = false;
925
    if (isset($course_info) && isset($course_info['visibility'])) {
926
        switch ($course_info['visibility']) {
927
            default:
928
            case Course::CLOSED:
929
                // Completely closed: the course is only accessible to the teachers. - 0
930
                if ($isAllowedInCourse && api_get_user_id() && !api_is_anonymous()) {
931
                    $is_visible = true;
932
                }
933
                break;
934
            case Course::REGISTERED:
935
                // Private - access authorized to course members only - 1
936
                if ($isAllowedInCourse && api_get_user_id() && !api_is_anonymous()) {
937
                    $is_visible = true;
938
                }
939
                break;
940
            case Course::OPEN_PLATFORM:
941
                // Open - access allowed for users registered on the platform - 2
942
                if ($isAllowedInCourse && api_get_user_id() && !api_is_anonymous()) {
943
                    $is_visible = true;
944
                }
945
                break;
946
            case Course::OPEN_WORLD:
947
                //Open - access allowed for the whole world - 3
948
                $is_visible = true;
949
                break;
950
            case Course::HIDDEN:
951
                //Completely closed: the course is only accessible to the teachers. - 0
952
                if (api_is_platform_admin()) {
953
                    $is_visible = true;
954
                }
955
                break;
956
        }
957
958
        //If password is set and user is not registered to the course then the course is not visible
959
        if (false === $isAllowedInCourse &&
960
            isset($course_info['registration_code']) &&
961
            !empty($course_info['registration_code'])
962
        ) {
963
            $is_visible = false;
964
        }
965
    }
966
967
    if (!empty($checkTool)) {
968
        if (!api_is_allowed_to_edit(true, true, true)) {
969
            $toolInfo = api_get_tool_information_by_name($checkTool);
970
            if (!empty($toolInfo) && isset($toolInfo['visibility']) && 0 == $toolInfo['visibility']) {
971
                api_not_allowed(true);
972
973
                return false;
974
            }
975
        }
976
    }
977
978
    // Check session visibility
979
    $session_id = api_get_session_id();
980
981
    if (!empty($session_id)) {
982
        // $isAllowedInCourse was set in local.inc.php
983
        if (!$isAllowedInCourse) {
984
            $is_visible = false;
985
        }
986
        // Check if course is inside session.
987
        if (!SessionManager::relation_session_course_exist($session_id, $course_info['real_id'])) {
988
            $is_visible = false;
989
        }
990
    }
991
992
    if (!$is_visible) {
993
        api_not_allowed($print_headers);
994
995
        return false;
996
    }
997
998
    if ($is_visible && 'true' === api_get_plugin_setting('positioning', 'tool_enable')) {
999
        $plugin = Positioning::create();
1000
        $block = $plugin->get('block_course_if_initial_exercise_not_attempted');
1001
        if ('true' === $block) {
1002
            $currentPath = $_SERVER['PHP_SELF'];
1003
            // Allowed only this course paths.
1004
            $paths = [
1005
                '/plugin/positioning/start.php',
1006
                '/plugin/positioning/start_student.php',
1007
                '/main/course_home/course_home.php',
1008
                '/main/exercise/overview.php',
1009
            ];
1010
1011
            if (!in_array($currentPath, $paths, true)) {
1012
                // Check if entering an exercise.
1013
                // @todo remove global $current_course_tool
1014
                /*global $current_course_tool;
1015
                if ('quiz' !== $current_course_tool) {
1016
                    $initialData = $plugin->getInitialExercise($course_info['real_id'], $session_id);
1017
                    if ($initialData && isset($initialData['exercise_id'])) {
1018
                        $results = Event::getExerciseResultsByUser(
1019
                            api_get_user_id(),
1020
                            $initialData['exercise_id'],
1021
                            $course_info['real_id'],
1022
                            $session_id
1023
                        );
1024
                        if (empty($results)) {
1025
                            api_not_allowed($print_headers);
1026
1027
                            return false;
1028
                        }
1029
                    }
1030
                }*/
1031
            }
1032
        }
1033
    }
1034
1035
    api_block_inactive_user();
1036
1037
    return true;
1038
}
1039
1040
/**
1041
 * Function used to protect an admin script.
1042
 *
1043
 * The function blocks access when the user has no platform admin rights
1044
 * with an error message printed on default output
1045
 *
1046
 * @param bool Whether to allow session admins as well
1047
 * @param bool Whether to allow HR directors as well
1048
 * @param string An optional message (already passed through get_lang)
1049
 *
1050
 * @return bool True if user is allowed, false otherwise.
1051
 *              The function also outputs an error message in case not allowed
1052
 *
1053
 * @author Roan Embrechts (original author)
1054
 */
1055
function api_protect_admin_script($allow_sessions_admins = false, $allow_drh = false, $message = null)
1056
{
1057
    if (!api_is_platform_admin($allow_sessions_admins, $allow_drh)) {
1058
        api_not_allowed(true, $message);
1059
1060
        return false;
1061
    }
1062
    api_block_inactive_user();
1063
1064
    return true;
1065
}
1066
1067
/**
1068
 * Blocks inactive users with a currently active session from accessing more pages "live".
1069
 *
1070
 * @return bool Returns true if the feature is disabled or the user account is still enabled.
1071
 *              Returns false (and shows a message) if the feature is enabled *and* the user is disabled.
1072
 */
1073
function api_block_inactive_user()
1074
{
1075
    $data = true;
1076
    if ('true' !== api_get_setting('security.security_block_inactive_users_immediately')) {
1077
        return $data;
1078
    }
1079
1080
    $userId = api_get_user_id();
1081
    $homeUrl = api_get_path(WEB_PATH);
1082
    if (0 == $userId) {
1083
        return $data;
1084
    }
1085
1086
    $sql = "SELECT active FROM ".Database::get_main_table(TABLE_MAIN_USER)."
1087
            WHERE id = $userId";
1088
1089
    $result = Database::query($sql);
1090
    if (Database::num_rows($result) > 0) {
1091
        $result_array = Database::fetch_array($result);
1092
        $data = (bool) $result_array['active'];
1093
    }
1094
    if (false == $data) {
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...
1095
        $tpl = new Template(null, true, true, false, true, false, true, 0);
1096
        $tpl->assign('hide_login_link', 1);
1097
1098
        //api_not_allowed(true, get_lang('Account inactive'));
1099
        // we were not in a course, return to home page
1100
        $msg = Display::return_message(
1101
            get_lang('Account inactive'),
1102
            'error',
1103
            false
1104
        );
1105
1106
        $msg .= '<p class="text-center">
1107
                 <a class="btn btn--plain" href="'.$homeUrl.'">'.get_lang('Back to Home Page.').'</a></p>';
1108
1109
        $tpl->assign('content', $msg);
1110
        $tpl->display_one_col_template();
1111
        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...
1112
    }
1113
1114
    return $data;
1115
}
1116
1117
/**
1118
 * Function used to protect a teacher script.
1119
 * The function blocks access when the user has no teacher rights.
1120
 *
1121
 * @return bool True if the current user can access the script, false otherwise
1122
 *
1123
 * @author Yoselyn Castillo
1124
 */
1125
function api_protect_teacher_script()
1126
{
1127
    if (!api_is_allowed_to_edit()) {
1128
        api_not_allowed(true);
1129
1130
        return false;
1131
    }
1132
1133
    return true;
1134
}
1135
1136
/**
1137
 * Function used to prevent anonymous users from accessing a script.
1138
 *
1139
 * @param bool $printHeaders
1140
 *
1141
 * @return bool
1142
 */
1143
function api_block_anonymous_users($printHeaders = true)
1144
{
1145
    $isAuth = Container::getAuthorizationChecker()->isGranted('IS_AUTHENTICATED');
1146
1147
    if (false === $isAuth) {
1148
        api_not_allowed($printHeaders);
1149
1150
        return false;
1151
    }
1152
1153
    api_block_inactive_user();
1154
1155
    return true;
1156
}
1157
1158
/**
1159
 * Returns a rough evaluation of the browser's name and version based on very
1160
 * simple regexp.
1161
 *
1162
 * @return array with the navigator name and version ['name' => '...', 'version' => '...']
1163
 */
1164
function api_get_navigator()
1165
{
1166
    $navigator = 'Unknown';
1167
    $version = 0;
1168
1169
    if (!isset($_SERVER['HTTP_USER_AGENT'])) {
1170
        return ['name' => 'Unknown', 'version' => '0.0.0'];
1171
    }
1172
1173
    if (false !== strpos($_SERVER['HTTP_USER_AGENT'], 'Opera')) {
1174
        $navigator = 'Opera';
1175
        [, $version] = explode('Opera', $_SERVER['HTTP_USER_AGENT']);
1176
    } elseif (false !== strpos($_SERVER['HTTP_USER_AGENT'], 'Edge')) {
1177
        $navigator = 'Edge';
1178
        [, $version] = explode('Edge', $_SERVER['HTTP_USER_AGENT']);
1179
    } elseif (false !== strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE')) {
1180
        $navigator = 'Internet Explorer';
1181
        [, $version] = explode('MSIE ', $_SERVER['HTTP_USER_AGENT']);
1182
    } elseif (false !== strpos($_SERVER['HTTP_USER_AGENT'], 'Chrome')) {
1183
        $navigator = 'Chrome';
1184
        [, $version] = explode('Chrome', $_SERVER['HTTP_USER_AGENT']);
1185
    } elseif (false !== stripos($_SERVER['HTTP_USER_AGENT'], 'Safari')) {
1186
        $navigator = 'Safari';
1187
        if (false !== stripos($_SERVER['HTTP_USER_AGENT'], 'Version/')) {
1188
            // If this Safari does have the "Version/" string in its user agent
1189
            // then use that as a version indicator rather than what's after
1190
            // "Safari/" which is rather a "build number" or something
1191
            [, $version] = explode('Version/', $_SERVER['HTTP_USER_AGENT']);
1192
        } else {
1193
            [, $version] = explode('Safari/', $_SERVER['HTTP_USER_AGENT']);
1194
        }
1195
    } elseif (false !== strpos($_SERVER['HTTP_USER_AGENT'], 'Firefox')) {
1196
        $navigator = 'Firefox';
1197
        [, $version] = explode('Firefox', $_SERVER['HTTP_USER_AGENT']);
1198
    } elseif (false !== strpos($_SERVER['HTTP_USER_AGENT'], 'Netscape')) {
1199
        $navigator = 'Netscape';
1200
        if (false !== stripos($_SERVER['HTTP_USER_AGENT'], 'Netscape/')) {
1201
            [, $version] = explode('Netscape', $_SERVER['HTTP_USER_AGENT']);
1202
        } else {
1203
            [, $version] = explode('Navigator', $_SERVER['HTTP_USER_AGENT']);
1204
        }
1205
    } elseif (false !== strpos($_SERVER['HTTP_USER_AGENT'], 'Konqueror')) {
1206
        $navigator = 'Konqueror';
1207
        [, $version] = explode('Konqueror', $_SERVER['HTTP_USER_AGENT']);
1208
    } elseif (false !== stripos($_SERVER['HTTP_USER_AGENT'], 'applewebkit')) {
1209
        $navigator = 'AppleWebKit';
1210
        [, $version] = explode('Version/', $_SERVER['HTTP_USER_AGENT']);
1211
    } elseif (false !== strpos($_SERVER['HTTP_USER_AGENT'], 'Gecko')) {
1212
        $navigator = 'Mozilla';
1213
        [, $version] = explode('; rv:', $_SERVER['HTTP_USER_AGENT']);
1214
    }
1215
1216
    // Now cut extra stuff around (mostly *after*) the version number
1217
    $version = preg_replace('/^([\/\s])?([\d\.]+)?.*/', '\2', $version);
1218
1219
    if (false === strpos($version, '.')) {
1220
        $version = number_format(doubleval($version), 1);
1221
    }
1222
1223
    return ['name' => $navigator, 'version' => $version];
1224
}
1225
1226
/**
1227
 * This function returns the id of the user which is stored in the $_user array.
1228
 *
1229
 * example: The function can be used to check if a user is logged in
1230
 *          if (api_get_user_id())
1231
 *
1232
 * @return int the id of the current user, 0 if is empty
1233
 */
1234
function api_get_user_id()
1235
{
1236
    $userInfo = Session::read('_user');
1237
    if ($userInfo && isset($userInfo['user_id'])) {
1238
        return (int) $userInfo['user_id'];
1239
    }
1240
1241
    return 0;
1242
}
1243
1244
/**
1245
 * Formats user information into a standard array
1246
 * This function should be only used inside api_get_user_info().
1247
 *
1248
 * @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...
1249
 * @param bool $add_password
1250
 * @param bool $loadAvatars  turn off to improve performance
1251
 *
1252
 * @return array Standard user array
1253
 */
1254
function _api_format_user($user, $add_password = false, $loadAvatars = true)
1255
{
1256
    $result = [];
1257
1258
    if (!isset($user['id'])) {
1259
        return [];
1260
    }
1261
1262
    $result['firstname'] = null;
1263
    $result['lastname'] = null;
1264
1265
    if (isset($user['firstname']) && isset($user['lastname'])) {
1266
        // with only lowercase
1267
        $result['firstname'] = $user['firstname'];
1268
        $result['lastname'] = $user['lastname'];
1269
    } elseif (isset($user['firstName']) && isset($user['lastName'])) {
1270
        // with uppercase letters
1271
        $result['firstname'] = isset($user['firstName']) ? $user['firstName'] : null;
1272
        $result['lastname'] = isset($user['lastName']) ? $user['lastName'] : null;
1273
    }
1274
1275
    if (isset($user['email'])) {
1276
        $result['mail'] = isset($user['email']) ? $user['email'] : null;
1277
        $result['email'] = isset($user['email']) ? $user['email'] : null;
1278
    } else {
1279
        $result['mail'] = isset($user['mail']) ? $user['mail'] : null;
1280
        $result['email'] = isset($user['mail']) ? $user['mail'] : null;
1281
    }
1282
1283
    $result['complete_name'] = api_get_person_name($result['firstname'], $result['lastname']);
1284
    $result['complete_name_with_username'] = $result['complete_name'];
1285
1286
    if (!empty($user['username']) && 'false' === api_get_setting('profile.hide_username_with_complete_name')) {
1287
        $result['complete_name_with_username'] = $result['complete_name'].' ('.$user['username'].')';
1288
    }
1289
1290
    $showEmail = 'true' === api_get_setting('show_email_addresses');
1291
    if (!empty($user['email'])) {
1292
        $result['complete_name_with_email_forced'] = $result['complete_name'].' ('.$user['email'].')';
1293
        if ($showEmail) {
1294
            $result['complete_name_with_email'] = $result['complete_name'].' ('.$user['email'].')';
1295
        }
1296
    } else {
1297
        $result['complete_name_with_email'] = $result['complete_name'];
1298
        $result['complete_name_with_email_forced'] = $result['complete_name'];
1299
    }
1300
1301
    // Kept for historical reasons
1302
    $result['firstName'] = $result['firstname'];
1303
    $result['lastName'] = $result['lastname'];
1304
1305
    $attributes = [
1306
        'phone',
1307
        'address',
1308
        'picture_uri',
1309
        'official_code',
1310
        'status',
1311
        'active',
1312
        'auth_source',
1313
        'username',
1314
        'theme',
1315
        'language',
1316
        'locale',
1317
        'creator_id',
1318
        'registration_date',
1319
        'hr_dept_id',
1320
        'expiration_date',
1321
        'last_login',
1322
        'user_is_online',
1323
        'profile_completed',
1324
    ];
1325
1326
    if ('true' === api_get_setting('extended_profile')) {
1327
        $attributes[] = 'competences';
1328
        $attributes[] = 'diplomas';
1329
        $attributes[] = 'teach';
1330
        $attributes[] = 'openarea';
1331
    }
1332
1333
    foreach ($attributes as $attribute) {
1334
        $result[$attribute] = $user[$attribute] ?? null;
1335
    }
1336
1337
    $user_id = (int) $user['id'];
1338
    // Maintain the user_id index for backwards compatibility
1339
    $result['user_id'] = $result['id'] = $user_id;
1340
1341
    $hasCertificates = Certificate::getCertificateByUser($user_id);
1342
    $result['has_certificates'] = 0;
1343
    if (!empty($hasCertificates)) {
1344
        $result['has_certificates'] = 1;
1345
    }
1346
1347
    $result['icon_status'] = '';
1348
    $result['icon_status_medium'] = '';
1349
    $result['is_admin'] = UserManager::is_admin($user_id);
1350
1351
    // Getting user avatar.
1352
    if ($loadAvatars) {
1353
        $result['avatar'] = '';
1354
        $result['avatar_no_query'] = '';
1355
        $result['avatar_small'] = '';
1356
        $result['avatar_medium'] = '';
1357
1358
        if (empty($user['avatar'])) {
1359
            $originalFile = UserManager::getUserPicture(
1360
                $user_id,
1361
                USER_IMAGE_SIZE_ORIGINAL,
1362
                null,
1363
                $result
1364
            );
1365
            $result['avatar'] = $originalFile;
1366
            $avatarString = explode('?', $result['avatar']);
1367
            $result['avatar_no_query'] = reset($avatarString);
1368
        } else {
1369
            $result['avatar'] = $user['avatar'];
1370
            $avatarString = explode('?', $user['avatar']);
1371
            $result['avatar_no_query'] = reset($avatarString);
1372
        }
1373
1374
        if (!isset($user['avatar_small'])) {
1375
            $smallFile = UserManager::getUserPicture(
1376
                $user_id,
1377
                USER_IMAGE_SIZE_SMALL,
1378
                null,
1379
                $result
1380
            );
1381
            $result['avatar_small'] = $smallFile;
1382
        } else {
1383
            $result['avatar_small'] = $user['avatar_small'];
1384
        }
1385
1386
        if (!isset($user['avatar_medium'])) {
1387
            $mediumFile = UserManager::getUserPicture(
1388
                $user_id,
1389
                USER_IMAGE_SIZE_MEDIUM,
1390
                null,
1391
                $result
1392
            );
1393
            $result['avatar_medium'] = $mediumFile;
1394
        } else {
1395
            $result['avatar_medium'] = $user['avatar_medium'];
1396
        }
1397
1398
        $urlImg = api_get_path(WEB_IMG_PATH);
1399
        $iconStatus = '';
1400
        $iconStatusMedium = '';
1401
        $label = '';
1402
1403
        switch ($result['status']) {
1404
            case STUDENT:
1405
                if ($result['has_certificates']) {
1406
                    $iconStatus = $urlImg.'icons/svg/identifier_graduated.svg';
1407
                    $label = get_lang('Graduated');
1408
                } else {
1409
                    $iconStatus = $urlImg.'icons/svg/identifier_student.svg';
1410
                    $label = get_lang('Student');
1411
                }
1412
                break;
1413
            case COURSEMANAGER:
1414
                if ($result['is_admin']) {
1415
                    $iconStatus = $urlImg.'icons/svg/identifier_admin.svg';
1416
                    $label = get_lang('Admin');
1417
                } else {
1418
                    $iconStatus = $urlImg.'icons/svg/identifier_teacher.svg';
1419
                    $label = get_lang('Teacher');
1420
                }
1421
                break;
1422
            case STUDENT_BOSS:
1423
                $iconStatus = $urlImg.'icons/svg/identifier_teacher.svg';
1424
                $label = get_lang('StudentBoss');
1425
                break;
1426
        }
1427
1428
        if (!empty($iconStatus)) {
1429
            $iconStatusMedium = '<img src="'.$iconStatus.'" width="32px" height="32px">';
1430
            $iconStatus = '<img src="'.$iconStatus.'" width="22px" height="22px">';
1431
        }
1432
1433
        $result['icon_status'] = $iconStatus;
1434
        $result['icon_status_label'] = $label;
1435
        $result['icon_status_medium'] = $iconStatusMedium;
1436
    }
1437
1438
    if (isset($user['user_is_online'])) {
1439
        $result['user_is_online'] = true == $user['user_is_online'] ? 1 : 0;
1440
    }
1441
    if (isset($user['user_is_online_in_chat'])) {
1442
        $result['user_is_online_in_chat'] = (int) $user['user_is_online_in_chat'];
1443
    }
1444
1445
    if ($add_password) {
1446
        $result['password'] = $user['password'];
1447
    }
1448
1449
    if (isset($result['profile_completed'])) {
1450
        $result['profile_completed'] = $user['profile_completed'];
1451
    }
1452
1453
    $result['profile_url'] = api_get_path(WEB_CODE_PATH).'social/profile.php?u='.$user_id;
1454
1455
    // Send message link
1456
    $sendMessage = api_get_path(WEB_AJAX_PATH).'user_manager.ajax.php?a=get_user_popup&user_id='.$user_id;
1457
    $result['complete_name_with_message_link'] = Display::url(
1458
        $result['complete_name_with_username'],
1459
        $sendMessage,
1460
        ['class' => 'ajax']
1461
    );
1462
1463
    if (isset($user['extra'])) {
1464
        $result['extra'] = $user['extra'];
1465
    }
1466
1467
    return $result;
1468
}
1469
1470
/**
1471
 * Finds all the information about a user.
1472
 * If no parameter is passed you find all the information about the current user.
1473
 *
1474
 * @param int  $user_id
1475
 * @param bool $checkIfUserOnline
1476
 * @param bool $showPassword
1477
 * @param bool $loadExtraData
1478
 * @param bool $loadOnlyVisibleExtraData Get the user extra fields that are visible
1479
 * @param bool $loadAvatars              turn off to improve performance and if avatars are not needed
1480
 * @param bool $updateCache              update apc cache if exists
1481
 *
1482
 * @return mixed $user_info user_id, lastname, firstname, username, email, etc or false on error
1483
 *
1484
 * @author Patrick Cool <[email protected]>
1485
 * @author Julio Montoya
1486
 *
1487
 * @version 21 September 2004
1488
 */
1489
function api_get_user_info(
1490
    $user_id = 0,
1491
    $checkIfUserOnline = false,
1492
    $showPassword = false,
1493
    $loadExtraData = false,
1494
    $loadOnlyVisibleExtraData = false,
1495
    $loadAvatars = true,
1496
    $updateCache = false
1497
) {
1498
    // Make sure user_id is safe
1499
    $user_id = (int) $user_id;
1500
    $user = false;
1501
    if (empty($user_id)) {
1502
        $userFromSession = Session::read('_user');
1503
        if (isset($userFromSession) && !empty($userFromSession)) {
1504
            return $userFromSession;
1505
            /*
1506
            return _api_format_user(
1507
                $userFromSession,
1508
                $showPassword,
1509
                $loadAvatars
1510
            );*/
1511
        }
1512
1513
        return false;
1514
    }
1515
1516
    $sql = "SELECT * FROM ".Database::get_main_table(TABLE_MAIN_USER)."
1517
            WHERE id = $user_id";
1518
    $result = Database::query($sql);
1519
    if (Database::num_rows($result) > 0) {
1520
        $result_array = Database::fetch_array($result);
1521
        $result_array['user_is_online_in_chat'] = 0;
1522
        if ($checkIfUserOnline) {
1523
            $use_status_in_platform = user_is_online($user_id);
1524
            $result_array['user_is_online'] = $use_status_in_platform;
1525
            $user_online_in_chat = 0;
1526
            if ($use_status_in_platform) {
1527
                $user_status = UserManager::get_extra_user_data_by_field(
1528
                    $user_id,
1529
                    'user_chat_status',
1530
                    false,
1531
                    true
1532
                );
1533
                if (1 == (int) $user_status['user_chat_status']) {
1534
                    $user_online_in_chat = 1;
1535
                }
1536
            }
1537
            $result_array['user_is_online_in_chat'] = $user_online_in_chat;
1538
        }
1539
1540
        if ($loadExtraData) {
1541
            $fieldValue = new ExtraFieldValue('user');
1542
            $result_array['extra'] = $fieldValue->getAllValuesForAnItem(
1543
                $user_id,
1544
                $loadOnlyVisibleExtraData
1545
            );
1546
        }
1547
        $user = _api_format_user($result_array, $showPassword, $loadAvatars);
1548
    }
1549
1550
    return $user;
1551
}
1552
1553
function api_get_user_info_from_entity(
1554
    User $user,
1555
    $checkIfUserOnline = false,
1556
    $showPassword = false,
1557
    $loadExtraData = false,
1558
    $loadOnlyVisibleExtraData = false,
1559
    $loadAvatars = true,
1560
    $loadCertificate = false
1561
) {
1562
    if (!$user instanceof UserInterface) {
1563
        return false;
1564
    }
1565
1566
    // Make sure user_id is safe
1567
    $user_id = (int) $user->getId();
1568
1569
    if (empty($user_id)) {
1570
        $userFromSession = Session::read('_user');
1571
1572
        if (isset($userFromSession) && !empty($userFromSession)) {
1573
            return $userFromSession;
1574
        }
1575
1576
        return false;
1577
    }
1578
1579
    $result = [];
1580
    $result['user_is_online_in_chat'] = 0;
1581
    if ($checkIfUserOnline) {
1582
        $use_status_in_platform = user_is_online($user_id);
1583
        $result['user_is_online'] = $use_status_in_platform;
1584
        $user_online_in_chat = 0;
1585
        if ($use_status_in_platform) {
1586
            $user_status = UserManager::get_extra_user_data_by_field(
1587
                $user_id,
1588
                'user_chat_status',
1589
                false,
1590
                true
1591
            );
1592
            if (1 == (int) $user_status['user_chat_status']) {
1593
                $user_online_in_chat = 1;
1594
            }
1595
        }
1596
        $result['user_is_online_in_chat'] = $user_online_in_chat;
1597
    }
1598
1599
    if ($loadExtraData) {
1600
        $fieldValue = new ExtraFieldValue('user');
1601
        $result['extra'] = $fieldValue->getAllValuesForAnItem(
1602
            $user_id,
1603
            $loadOnlyVisibleExtraData
1604
        );
1605
    }
1606
1607
    $result['username'] = $user->getUsername();
1608
    $result['status'] = $user->getStatus();
1609
    $result['firstname'] = $user->getFirstname();
1610
    $result['lastname'] = $user->getLastname();
1611
    $result['email'] = $result['mail'] = $user->getEmail();
1612
    $result['complete_name'] = api_get_person_name($result['firstname'], $result['lastname']);
1613
    $result['complete_name_with_username'] = $result['complete_name'];
1614
1615
    if (!empty($result['username']) && 'false' === api_get_setting('profile.hide_username_with_complete_name')) {
1616
        $result['complete_name_with_username'] = $result['complete_name'].' ('.$result['username'].')';
1617
    }
1618
1619
    $showEmail = 'true' === api_get_setting('show_email_addresses');
1620
    if (!empty($result['email'])) {
1621
        $result['complete_name_with_email_forced'] = $result['complete_name'].' ('.$result['email'].')';
1622
        if ($showEmail) {
1623
            $result['complete_name_with_email'] = $result['complete_name'].' ('.$result['email'].')';
1624
        }
1625
    } else {
1626
        $result['complete_name_with_email'] = $result['complete_name'];
1627
        $result['complete_name_with_email_forced'] = $result['complete_name'];
1628
    }
1629
1630
    // Kept for historical reasons
1631
    $result['firstName'] = $result['firstname'];
1632
    $result['lastName'] = $result['lastname'];
1633
1634
    $attributes = [
1635
        'picture_uri',
1636
        'last_login',
1637
        'user_is_online',
1638
    ];
1639
1640
    $result['phone'] = $user->getPhone();
1641
    $result['address'] = $user->getAddress();
1642
    $result['official_code'] = $user->getOfficialCode();
1643
    $result['active'] = $user->isActive();
1644
    $result['auth_source'] = $user->getAuthSource();
1645
    $result['language'] = $user->getLocale();
1646
    $result['creator_id'] = $user->getCreatorId();
1647
    $result['registration_date'] = $user->getRegistrationDate()->format('Y-m-d H:i:s');
1648
    $result['hr_dept_id'] = $user->getHrDeptId();
1649
    $result['expiration_date'] = '';
1650
    if ($user->getExpirationDate()) {
1651
        $result['expiration_date'] = $user->getExpirationDate()->format('Y-m-d H:i:s');
1652
    }
1653
1654
    $result['last_login'] = null;
1655
    if ($user->getLastLogin()) {
1656
        $result['last_login'] = $user->getLastLogin()->format('Y-m-d H:i:s');
1657
    }
1658
1659
    $result['competences'] = $user->getCompetences();
1660
    $result['diplomas'] = $user->getDiplomas();
1661
    $result['teach'] = $user->getTeach();
1662
    $result['openarea'] = $user->getOpenarea();
1663
    $user_id = (int) $user->getId();
1664
1665
    // Maintain the user_id index for backwards compatibility
1666
    $result['user_id'] = $result['id'] = $user_id;
1667
1668
    if ($loadCertificate) {
1669
        $hasCertificates = Certificate::getCertificateByUser($user_id);
1670
        $result['has_certificates'] = 0;
1671
        if (!empty($hasCertificates)) {
1672
            $result['has_certificates'] = 1;
1673
        }
1674
    }
1675
1676
    $result['icon_status'] = '';
1677
    $result['icon_status_medium'] = '';
1678
    $result['is_admin'] = UserManager::is_admin($user_id);
1679
1680
    // Getting user avatar.
1681
    if ($loadAvatars) {
1682
        $result['avatar'] = '';
1683
        $result['avatar_no_query'] = '';
1684
        $result['avatar_small'] = '';
1685
        $result['avatar_medium'] = '';
1686
        $urlImg = '/';
1687
        $iconStatus = '';
1688
        $iconStatusMedium = '';
1689
1690
        switch ($user->getStatus()) {
1691
            case STUDENT:
1692
                if (isset($result['has_certificates']) && $result['has_certificates']) {
1693
                    $iconStatus = $urlImg.'icons/svg/identifier_graduated.svg';
1694
                } else {
1695
                    $iconStatus = $urlImg.'icons/svg/identifier_student.svg';
1696
                }
1697
                break;
1698
            case COURSEMANAGER:
1699
                if ($result['is_admin']) {
1700
                    $iconStatus = $urlImg.'icons/svg/identifier_admin.svg';
1701
                } else {
1702
                    $iconStatus = $urlImg.'icons/svg/identifier_teacher.svg';
1703
                }
1704
                break;
1705
            case STUDENT_BOSS:
1706
                $iconStatus = $urlImg.'icons/svg/identifier_teacher.svg';
1707
                break;
1708
        }
1709
1710
        if (!empty($iconStatus)) {
1711
            $iconStatusMedium = '<img src="'.$iconStatus.'" width="32px" height="32px">';
1712
            $iconStatus = '<img src="'.$iconStatus.'" width="22px" height="22px">';
1713
        }
1714
1715
        $result['icon_status'] = $iconStatus;
1716
        $result['icon_status_medium'] = $iconStatusMedium;
1717
    }
1718
1719
    if (isset($result['user_is_online'])) {
1720
        $result['user_is_online'] = true == $result['user_is_online'] ? 1 : 0;
1721
    }
1722
    if (isset($result['user_is_online_in_chat'])) {
1723
        $result['user_is_online_in_chat'] = $result['user_is_online_in_chat'];
1724
    }
1725
1726
    $result['password'] = '';
1727
    if ($showPassword) {
1728
        $result['password'] = $user->getPassword();
1729
    }
1730
1731
    if (isset($result['profile_completed'])) {
1732
        $result['profile_completed'] = $result['profile_completed'];
1733
    }
1734
1735
    $result['profile_url'] = api_get_path(WEB_CODE_PATH).'social/profile.php?u='.$user_id;
1736
1737
    // Send message link
1738
    $sendMessage = api_get_path(WEB_AJAX_PATH).'user_manager.ajax.php?a=get_user_popup&user_id='.$user_id;
1739
    $result['complete_name_with_message_link'] = Display::url(
1740
        $result['complete_name_with_username'],
1741
        $sendMessage,
1742
        ['class' => 'ajax']
1743
    );
1744
1745
    if (isset($result['extra'])) {
1746
        $result['extra'] = $result['extra'];
1747
    }
1748
1749
    return $result;
1750
}
1751
1752
function api_get_lp_entity(int $id): ?CLp
1753
{
1754
    return Database::getManager()->getRepository(CLp::class)->find($id);
1755
}
1756
1757
function api_get_user_entity(int $userId = 0): ?User
1758
{
1759
    $userId = $userId ?: api_get_user_id();
1760
    $repo = Container::getUserRepository();
1761
1762
    return $repo->find($userId);
1763
}
1764
1765
function api_get_current_user(): ?User
1766
{
1767
    $isLoggedIn = Container::getAuthorizationChecker()->isGranted('IS_AUTHENTICATED_REMEMBERED');
1768
    if (false === $isLoggedIn) {
1769
        return null;
1770
    }
1771
1772
    $token = Container::getTokenStorage()->getToken();
1773
1774
    if (null !== $token) {
1775
        return $token->getUser();
1776
    }
1777
1778
    return null;
1779
}
1780
1781
/**
1782
 * Finds all the information about a user from username instead of user id.
1783
 *
1784
 * @param string $username
1785
 *
1786
 * @return mixed $user_info array user_id, lastname, firstname, username, email or false on error
1787
 *
1788
 * @author Yannick Warnier <[email protected]>
1789
 */
1790
function api_get_user_info_from_username($username)
1791
{
1792
    if (empty($username)) {
1793
        return false;
1794
    }
1795
    $username = trim($username);
1796
1797
    $sql = "SELECT * FROM ".Database::get_main_table(TABLE_MAIN_USER)."
1798
            WHERE username='".Database::escape_string($username)."'";
1799
    $result = Database::query($sql);
1800
    if (Database::num_rows($result) > 0) {
1801
        $resultArray = Database::fetch_array($result);
1802
1803
        return _api_format_user($resultArray);
1804
    }
1805
1806
    return false;
1807
}
1808
1809
/**
1810
 * Get first user with an email.
1811
 *
1812
 * @param string $email
1813
 *
1814
 * @return array|bool
1815
 */
1816
function api_get_user_info_from_email($email = '')
1817
{
1818
    if (empty($email)) {
1819
        return false;
1820
    }
1821
    $sql = "SELECT * FROM ".Database::get_main_table(TABLE_MAIN_USER)."
1822
            WHERE email ='".Database::escape_string($email)."' LIMIT 1";
1823
    $result = Database::query($sql);
1824
    if (Database::num_rows($result) > 0) {
1825
        $resultArray = Database::fetch_array($result);
1826
1827
        return _api_format_user($resultArray);
1828
    }
1829
1830
    return false;
1831
}
1832
1833
/**
1834
 * @return string
1835
 */
1836
function api_get_course_id()
1837
{
1838
    return Session::read('_cid', null);
1839
}
1840
1841
/**
1842
 * Returns the current course id (integer).
1843
 *
1844
 * @param ?string $code Optional course code
1845
 *
1846
 * @return int
1847
 */
1848
function api_get_course_int_id(?string $code = null): int
1849
{
1850
    if (!empty($code)) {
1851
        $code = Database::escape_string($code);
1852
        $row = Database::select(
1853
            'id',
1854
            Database::get_main_table(TABLE_MAIN_COURSE),
1855
            ['where' => ['code = ?' => [$code]]],
1856
            'first'
1857
        );
1858
1859
        if (is_array($row) && isset($row['id'])) {
1860
            return $row['id'];
1861
        } else {
1862
            return 0;
1863
        }
1864
    }
1865
1866
    $cid = Session::read('_real_cid', 0);
1867
    if (empty($cid) && isset($_REQUEST['cid'])) {
1868
        $cid = (int) $_REQUEST['cid'];
1869
    }
1870
1871
    return $cid;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $cid could return the type null which is incompatible with the type-hinted return integer. Consider adding an additional type-check to rule them out.
Loading history...
1872
}
1873
1874
/**
1875
 * Gets a course setting from the current course_setting table. Try always using integer values.
1876
 *
1877
 * @param string       $settingName The name of the setting we want from the table
1878
 * @param Course|array $courseInfo
1879
 * @param bool         $force       force checking the value in the database
1880
 *
1881
 * @return mixed The value of that setting in that table. Return -1 if not found.
1882
 */
1883
function api_get_course_setting($settingName, $courseInfo = null, $force = false)
1884
{
1885
    if (empty($courseInfo)) {
1886
        $courseInfo = api_get_course_info();
1887
    }
1888
1889
    if (empty($courseInfo) || empty($settingName)) {
1890
        return -1;
1891
    }
1892
1893
    if ($courseInfo instanceof Course) {
1894
        $courseId = $courseInfo->getId();
1895
    } else {
1896
        $courseId = isset($courseInfo['real_id']) && !empty($courseInfo['real_id']) ? $courseInfo['real_id'] : 0;
1897
    }
1898
1899
    if (empty($courseId)) {
1900
        return -1;
1901
    }
1902
1903
    static $courseSettingInfo = [];
1904
1905
    if ($force) {
1906
        $courseSettingInfo = [];
1907
    }
1908
1909
    if (!isset($courseSettingInfo[$courseId])) {
1910
        $table = Database::get_course_table(TABLE_COURSE_SETTING);
1911
        $settingName = Database::escape_string($settingName);
1912
1913
        $sql = "SELECT variable, value FROM $table
1914
                WHERE c_id = $courseId ";
1915
        $res = Database::query($sql);
1916
        if (Database::num_rows($res) > 0) {
1917
            $result = Database::store_result($res, 'ASSOC');
1918
            $courseSettingInfo[$courseId] = array_column($result, 'value', 'variable');
1919
1920
            if (isset($courseSettingInfo[$courseId]['email_alert_manager_on_new_quiz'])) {
1921
                $value = $courseSettingInfo[$courseId]['email_alert_manager_on_new_quiz'];
1922
                if (!is_null($value)) {
1923
                    $result = explode(',', $value);
1924
                    $courseSettingInfo[$courseId]['email_alert_manager_on_new_quiz'] = $result;
1925
                }
1926
            }
1927
        }
1928
    }
1929
1930
    if (isset($courseSettingInfo[$courseId]) && isset($courseSettingInfo[$courseId][$settingName])) {
1931
        return $courseSettingInfo[$courseId][$settingName];
1932
    }
1933
1934
    return -1;
1935
}
1936
1937
function api_get_course_plugin_setting($plugin, $settingName, $courseInfo = [])
1938
{
1939
    $value = api_get_course_setting($settingName, $courseInfo, true);
1940
1941
    if (-1 === $value) {
1942
        // Check global settings
1943
        $value = api_get_plugin_setting($plugin, $settingName);
1944
        if ('true' === $value) {
1945
            return 1;
1946
        }
1947
        if ('false' === $value) {
1948
            return 0;
1949
        }
1950
        if (null === $value) {
1951
            return -1;
1952
        }
1953
    }
1954
1955
    return $value;
1956
}
1957
1958
/**
1959
 * Gets an anonymous user ID.
1960
 *
1961
 * For some tools that need tracking, like the learnpath tool, it is necessary
1962
 * to have a usable user-id to enable some kind of tracking, even if not
1963
 * perfect. An anonymous ID is taken from the users table by looking for a
1964
 * status of "6" (anonymous).
1965
 *
1966
 * @return int User ID of the anonymous user, or O if no anonymous user found
1967
 */
1968
function api_get_anonymous_id()
1969
{
1970
    // Find if another anon is connected now
1971
    $table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_LOGIN);
1972
    $tableU = Database::get_main_table(TABLE_MAIN_USER);
1973
    $ip = Database::escape_string(api_get_real_ip());
1974
    $max = (int) api_get_setting('admin.max_anonymous_users');
1975
    if ($max >= 2) {
1976
        $sql = "SELECT * FROM $table as TEL
1977
                JOIN $tableU as U
1978
                ON U.id = TEL.login_user_id
1979
                WHERE TEL.user_ip = '$ip'
1980
                    AND U.status = ".ANONYMOUS."
1981
                    AND U.id != 2 ";
1982
1983
        $result = Database::query($sql);
1984
        if (empty(Database::num_rows($result))) {
1985
            $login = uniqid('anon_');
1986
            $anonList = UserManager::get_user_list(['status' => ANONYMOUS], ['registration_date ASC']);
1987
            if (count($anonList) >= $max) {
1988
                foreach ($anonList as $userToDelete) {
1989
                    UserManager::delete_user($userToDelete['user_id']);
1990
                    break;
1991
                }
1992
            }
1993
1994
            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...
1995
                $login,
1996
                'anon',
1997
                ANONYMOUS,
1998
                ' anonymous@localhost',
1999
                $login,
2000
                $login
2001
            );
2002
        } else {
2003
            $row = Database::fetch_assoc($result);
2004
2005
            return $row['id'];
2006
        }
2007
    }
2008
2009
    $table = Database::get_main_table(TABLE_MAIN_USER);
2010
    $sql = "SELECT id
2011
            FROM $table
2012
            WHERE status = ".ANONYMOUS." ";
2013
    $res = Database::query($sql);
2014
    if (Database::num_rows($res) > 0) {
2015
        $row = Database::fetch_assoc($res);
2016
2017
        return $row['id'];
2018
    }
2019
2020
    // No anonymous user was found.
2021
    return 0;
2022
}
2023
2024
/**
2025
 * @param int $courseId
2026
 * @param int $sessionId
2027
 * @param int $groupId
2028
 *
2029
 * @return string
2030
 */
2031
function api_get_cidreq_params($courseId, $sessionId = 0, $groupId = 0)
2032
{
2033
    $courseId = !empty($courseId) ? (int) $courseId : 0;
2034
    $sessionId = !empty($sessionId) ? (int) $sessionId : 0;
2035
    $groupId = !empty($groupId) ? (int) $groupId : 0;
2036
2037
    $url = 'cid='.$courseId;
2038
    $url .= '&sid='.$sessionId;
2039
    $url .= '&gid='.$groupId;
2040
2041
    return $url;
2042
}
2043
2044
/**
2045
 * Returns the current course url part including session, group, and gradebook params.
2046
 *
2047
 * @param bool   $addSessionId
2048
 * @param bool   $addGroupId
2049
 * @param string $origin
2050
 *
2051
 * @return string Course & session references to add to a URL
2052
 */
2053
function api_get_cidreq($addSessionId = true, $addGroupId = true, $origin = '')
2054
{
2055
    $courseId = api_get_course_int_id();
2056
    if (0 === $courseId && isset($_REQUEST['cid'])) {
2057
        $courseId = (int) $_REQUEST['cid'];
2058
    }
2059
    $url = empty($courseId) ? '' : 'cid='.$courseId;
2060
    $origin = empty($origin) ? api_get_origin() : Security::remove_XSS($origin);
2061
2062
    if ($addSessionId) {
2063
        if (!empty($url)) {
2064
            $sessionId = api_get_session_id();
2065
            if (0 === $sessionId && isset($_REQUEST['sid'])) {
2066
                $sessionId = (int) $_REQUEST['sid'];
2067
            }
2068
            $url .= 0 === $sessionId ? '&sid=0' : '&sid='.$sessionId;
2069
        }
2070
    }
2071
2072
    if ($addGroupId) {
2073
        if (!empty($url)) {
2074
            $url .= 0 == api_get_group_id() ? '&gid=0' : '&gid='.api_get_group_id();
2075
        }
2076
    }
2077
2078
    if (!empty($url)) {
2079
        $url .= '&gradebook='.(int) api_is_in_gradebook();
2080
        if (false !== $origin) {
2081
            $url .= '&origin=' . $origin;
0 ignored issues
show
Bug introduced by
Are you sure $origin of type array|string can be used in concatenation? ( Ignorable by Annotation )

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

2081
            $url .= '&origin=' . /** @scrutinizer ignore-type */ $origin;
Loading history...
2082
        }
2083
    }
2084
2085
    return $url;
2086
}
2087
2088
/**
2089
 * Get if we visited a gradebook page.
2090
 *
2091
 * @return bool
2092
 */
2093
function api_is_in_gradebook()
2094
{
2095
    return Session::read('in_gradebook', false);
2096
}
2097
2098
/**
2099
 * Set that we are in a page inside a gradebook.
2100
 */
2101
function api_set_in_gradebook()
2102
{
2103
    Session::write('in_gradebook', true);
2104
}
2105
2106
/**
2107
 * Remove gradebook session.
2108
 */
2109
function api_remove_in_gradebook()
2110
{
2111
    Session::erase('in_gradebook');
2112
}
2113
2114
/**
2115
 * Returns the current course info array see api_format_course_array()
2116
 * If the course_code is given, the returned array gives info about that
2117
 * particular course, if none given it gets the course info from the session.
2118
 *
2119
 * @param string $courseCode
2120
 *
2121
 * @return array
2122
 */
2123
function api_get_course_info($courseCode = null)
2124
{
2125
    if (!empty($courseCode)) {
2126
        $course = Container::getCourseRepository()->findOneByCode($courseCode);
2127
2128
        return api_format_course_array($course);
2129
    }
2130
2131
    $course = Session::read('_course');
2132
    if ('-1' == $course) {
2133
        $course = [];
2134
    }
2135
2136
    if (empty($course) && isset($_REQUEST['cid'])) {
2137
        $course = api_get_course_info_by_id((int) $_REQUEST['cid']);
2138
    }
2139
2140
    return $course;
2141
}
2142
2143
/**
2144
 * @param int $courseId
2145
 */
2146
function api_get_course_entity($courseId = 0): ?Course
2147
{
2148
    if (empty($courseId)) {
2149
        $courseId = api_get_course_int_id();
2150
    }
2151
2152
    if (empty($courseId)) {
2153
        return null;
2154
    }
2155
2156
    return Container::getCourseRepository()->find($courseId);
2157
}
2158
2159
/**
2160
 * @param int $id
2161
 */
2162
function api_get_session_entity($id = 0): ?SessionEntity
2163
{
2164
    if (empty($id)) {
2165
        $id = api_get_session_id();
2166
    }
2167
2168
    if (empty($id)) {
2169
        return null;
2170
    }
2171
2172
    return Container::getSessionRepository()->find($id);
2173
}
2174
2175
/**
2176
 * @param int $id
2177
 */
2178
function api_get_group_entity($id = 0): ?CGroup
2179
{
2180
    if (empty($id)) {
2181
        $id = api_get_group_id();
2182
    }
2183
2184
    return Container::getGroupRepository()->find($id);
2185
}
2186
2187
/**
2188
 * @param int $id
2189
 */
2190
function api_get_url_entity($id = 0): ?AccessUrl
2191
{
2192
    if (empty($id)) {
2193
        $id = api_get_current_access_url_id();
2194
    }
2195
2196
    return Container::getAccessUrlRepository()->find($id);
2197
}
2198
2199
/**
2200
 * Returns the current course info array.
2201
2202
 * Now if the course_code is given, the returned array gives info about that
2203
 * particular course, not specially the current one.
2204
 *
2205
 * @param int $id Numeric ID of the course
2206
 *
2207
 * @return array The course info as an array formatted by api_format_course_array, including category.title
2208
 */
2209
function api_get_course_info_by_id(?int $id = 0)
2210
{
2211
    if (empty($id)) {
2212
        $course = Session::read('_course', []);
2213
2214
        return $course;
2215
    }
2216
2217
    $course = Container::getCourseRepository()->find($id);
2218
    if (empty($course)) {
2219
        return [];
2220
    }
2221
2222
    return api_format_course_array($course);
2223
}
2224
2225
/**
2226
 * Reformat the course array (output by api_get_course_info()) in order, mostly,
2227
 * to switch from 'code' to 'id' in the array.
2228
 *
2229
 * @return array
2230
 *
2231
 * @todo eradicate the false "id"=code field of the $_course array and use the int id
2232
 */
2233
function api_format_course_array(Course $course = null)
2234
{
2235
    if (empty($course)) {
2236
        return [];
2237
    }
2238
2239
    $courseData = [];
2240
    $courseData['id'] = $courseData['real_id'] = $course->getId();
2241
2242
    // Added
2243
    $courseData['code'] = $courseData['sysCode'] = $course->getCode();
2244
    $courseData['name'] = $courseData['title'] = $course->getTitle(); // 'name' only used for backwards compatibility - should be removed in the long run
2245
    $courseData['official_code'] = $courseData['visual_code'] = $course->getVisualCode();
2246
    $courseData['creation_date'] = $course->getCreationDate()->format('Y-m-d H:i:s');
2247
    $courseData['titular'] = $course->getTutorName();
2248
    $courseData['language'] = $courseData['course_language'] = $course->getCourseLanguage();
2249
    $courseData['extLink']['url'] = $courseData['department_url'] = $course->getDepartmentUrl();
2250
    $courseData['extLink']['name'] = $courseData['department_name'] = $course->getDepartmentName();
2251
2252
    $courseData['visibility'] = $course->getVisibility();
2253
    $courseData['subscribe_allowed'] = $courseData['subscribe'] = $course->getSubscribe();
2254
    $courseData['unsubscribe'] = $course->getUnsubscribe();
2255
    $courseData['activate_legal'] = $course->getActivateLegal();
2256
    $courseData['legal'] = $course->getLegal();
2257
    $courseData['show_score'] = $course->getShowScore(); //used in the work tool
2258
    $courseData['video_url'] = $course->getVideoUrl();
2259
    $courseData['sticky'] = (int) $course->isSticky();
2260
2261
    $coursePath = '/course/';
2262
    $webCourseHome = $coursePath.$courseData['real_id'].'/home';
2263
2264
    // Course password
2265
    $courseData['registration_code'] = $course->getRegistrationCode();
2266
    $courseData['disk_quota'] = $course->getDiskQuota();
2267
    $courseData['course_public_url'] = $webCourseHome;
2268
    $courseData['about_url'] = $coursePath.$courseData['real_id'].'/about';
2269
    $courseData['add_teachers_to_sessions_courses'] = $course->isAddTeachersToSessionsCourses();
2270
2271
    $image = Display::getMdiIcon(
2272
        ObjectIcon::COURSE,
2273
        'ch-tool-icon',
2274
        null,
2275
        ICON_SIZE_BIG
2276
    );
2277
2278
    $illustration = Container::getIllustrationRepository()->getIllustrationUrl($course);
2279
    if (!empty($illustration)) {
2280
        $image = $illustration;
2281
    }
2282
2283
    $courseData['course_image'] = $image.'?filter=course_picture_small';
2284
    $courseData['course_image_large'] = $image.'?filter=course_picture_medium';
2285
2286
    if ('true' === api_get_setting('course.show_course_duration') && null !== $course->getDuration()) {
2287
        $courseData['duration'] = $course->getDuration();
2288
    }
2289
2290
    return $courseData;
2291
}
2292
2293
/**
2294
 * Returns a difficult to guess password.
2295
 */
2296
function api_generate_password(int $length = 8, $useRequirements = true): string
2297
{
2298
    if ($length < 2) {
2299
        $length = 2;
2300
    }
2301
2302
    $charactersLowerCase = 'abcdefghijkmnopqrstuvwxyz';
2303
    $charactersUpperCase = 'ABCDEFGHJKLMNPQRSTUVWXYZ';
2304
    $charactersSpecials = '!@#$%^&*()_+-=[]{}|;:,.<>?';
2305
    $minNumbers = 2;
2306
    $length = $length - $minNumbers;
2307
    $minLowerCase = round($length / 2);
2308
    $minUpperCase = $length - $minLowerCase;
2309
    $minSpecials = 1; // Default minimum special characters
2310
2311
    $password = '';
2312
    $passwordRequirements = $useRequirements ? Security::getPasswordRequirements() : [];
2313
2314
    $factory = new RandomLib\Factory();
2315
    $generator = $factory->getGenerator(new SecurityLib\Strength(SecurityLib\Strength::MEDIUM));
2316
2317
    if (!empty($passwordRequirements)) {
2318
        $length = $passwordRequirements['min']['length'];
2319
        $minNumbers = $passwordRequirements['min']['numeric'];
2320
        $minLowerCase = $passwordRequirements['min']['lowercase'];
2321
        $minUpperCase = $passwordRequirements['min']['uppercase'];
2322
        $minSpecials = $passwordRequirements['min']['specials'];
2323
2324
        $rest = $length - $minNumbers - $minLowerCase - $minUpperCase - $minSpecials;
2325
        // Add the rest to fill the length requirement
2326
        if ($rest > 0) {
2327
            $password .= $generator->generateString($rest, $charactersLowerCase.$charactersUpperCase);
2328
        }
2329
    }
2330
2331
    // Min digits default 2
2332
    for ($i = 0; $i < $minNumbers; $i++) {
2333
        $password .= $generator->generateInt(2, 9);
2334
    }
2335
2336
    // Min lowercase
2337
    $password .= $generator->generateString($minLowerCase, $charactersLowerCase);
2338
2339
    // Min uppercase
2340
    $password .= $generator->generateString($minUpperCase, $charactersUpperCase);
2341
2342
    // Min special characters
2343
    $password .= $generator->generateString($minSpecials, $charactersSpecials);
2344
2345
    // Shuffle the password to ensure randomness
2346
    $password = str_shuffle($password);
2347
2348
    return $password;
2349
}
2350
2351
/**
2352
 * Checks a password to see wether it is OK to use.
2353
 *
2354
 * @param string $password
2355
 *
2356
 * @return bool if the password is acceptable, false otherwise
2357
 *              Notes about what a password "OK to use" is:
2358
 *              1. The password should be at least 5 characters long.
2359
 *              2. Only English letters (uppercase or lowercase, it doesn't matter) and digits are allowed.
2360
 *              3. The password should contain at least 3 letters.
2361
 *              4. It should contain at least 2 digits.
2362
 *              Settings will change if the configuration value is set: password_requirements
2363
 */
2364
function api_check_password($password)
2365
{
2366
    $passwordRequirements = Security::getPasswordRequirements();
2367
2368
    $minLength = $passwordRequirements['min']['length'];
2369
    $minNumbers = $passwordRequirements['min']['numeric'];
2370
    // Optional
2371
    $minLowerCase = $passwordRequirements['min']['lowercase'];
2372
    $minUpperCase = $passwordRequirements['min']['uppercase'];
2373
2374
    $minLetters = $minLowerCase + $minUpperCase;
2375
    $passwordLength = api_strlen($password);
2376
2377
    $conditions = [
2378
        'min_length' => $passwordLength >= $minLength,
2379
    ];
2380
2381
    $digits = 0;
2382
    $lowerCase = 0;
2383
    $upperCase = 0;
2384
2385
    for ($i = 0; $i < $passwordLength; $i++) {
2386
        $currentCharacterCode = api_ord(api_substr($password, $i, 1));
2387
        if ($currentCharacterCode >= 65 && $currentCharacterCode <= 90) {
2388
            $upperCase++;
2389
        }
2390
2391
        if ($currentCharacterCode >= 97 && $currentCharacterCode <= 122) {
2392
            $lowerCase++;
2393
        }
2394
        if ($currentCharacterCode >= 48 && $currentCharacterCode <= 57) {
2395
            $digits++;
2396
        }
2397
    }
2398
2399
    // Min number of digits
2400
    $conditions['min_numeric'] = $digits >= $minNumbers;
2401
2402
    if (!empty($minUpperCase)) {
2403
        // Uppercase
2404
        $conditions['min_uppercase'] = $upperCase >= $minUpperCase;
2405
    }
2406
2407
    if (!empty($minLowerCase)) {
2408
        // Lowercase
2409
        $conditions['min_lowercase'] = $upperCase >= $minLowerCase;
2410
    }
2411
2412
    // Min letters
2413
    $letters = $upperCase + $lowerCase;
2414
    $conditions['min_letters'] = $letters >= $minLetters;
2415
2416
    $isPasswordOk = true;
2417
    foreach ($conditions as $condition) {
2418
        if (false === $condition) {
2419
            $isPasswordOk = false;
2420
            break;
2421
        }
2422
    }
2423
2424
    if (false === $isPasswordOk) {
2425
        $output = get_lang('The new password does not match the minimum security requirements').'<br />';
2426
        $output .= Security::getPasswordRequirementsToString($conditions);
2427
2428
        Display::addFlash(Display::return_message($output, 'warning', false));
2429
    }
2430
2431
    return $isPasswordOk;
2432
}
2433
2434
/**
2435
 * Gets the current Chamilo (not PHP/cookie) session ID.
2436
 *
2437
 * @return int O if no active session, the session ID otherwise
2438
 */
2439
function api_get_session_id()
2440
{
2441
    return (int) Session::read('sid', 0);
2442
}
2443
2444
/**
2445
 * Gets the current Chamilo (not social network) group ID.
2446
 *
2447
 * @return int O if no active session, the session ID otherwise
2448
 */
2449
function api_get_group_id()
2450
{
2451
    return Session::read('gid', 0);
2452
}
2453
2454
/**
2455
 * Gets the current or given session name.
2456
 *
2457
 * @param   int     Session ID (optional)
2458
 *
2459
 * @return string The session name, or null if not found
2460
 */
2461
function api_get_session_name($session_id = 0)
2462
{
2463
    if (empty($session_id)) {
2464
        $session_id = api_get_session_id();
2465
        if (empty($session_id)) {
2466
            return null;
2467
        }
2468
    }
2469
    $t = Database::get_main_table(TABLE_MAIN_SESSION);
2470
    $s = "SELECT title FROM $t WHERE id = ".(int) $session_id;
2471
    $r = Database::query($s);
2472
    $c = Database::num_rows($r);
2473
    if ($c > 0) {
2474
        //technically, there can be only one, but anyway we take the first
2475
        $rec = Database::fetch_array($r);
2476
2477
        return $rec['title'];
2478
    }
2479
2480
    return null;
2481
}
2482
2483
/**
2484
 * Gets the session info by id.
2485
 *
2486
 * @param int $id Session ID
2487
 *
2488
 * @return array information of the session
2489
 */
2490
function api_get_session_info($id)
2491
{
2492
    return SessionManager::fetch($id);
2493
}
2494
2495
/**
2496
 * Gets the session visibility by session id.
2497
 *
2498
 * @param int  $session_id
2499
 * @param int  $courseId
2500
 * @param bool $ignore_visibility_for_admins
2501
 *
2502
 * @return int
2503
 *             0 = session still available,
2504
 *             SESSION_VISIBLE_READ_ONLY = 1,
2505
 *             SESSION_VISIBLE = 2,
2506
 *             SESSION_INVISIBLE = 3
2507
 */
2508
function api_get_session_visibility(
2509
    $session_id,
2510
    $courseId = null,
2511
    $ignore_visibility_for_admins = true,
2512
    $userId = 0
2513
) {
2514
    if (api_is_platform_admin()) {
2515
        if ($ignore_visibility_for_admins) {
2516
            return SESSION_AVAILABLE;
2517
        }
2518
    }
2519
    $userId = empty($userId) ? api_get_user_id() : (int) $userId;
2520
2521
    $now = time();
2522
    if (empty($session_id)) {
2523
        return 0; // Means that the session is still available.
2524
    }
2525
2526
    $session_id = (int) $session_id;
2527
    $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
2528
2529
    $result = Database::query("SELECT * FROM $tbl_session WHERE id = $session_id");
2530
2531
    if (Database::num_rows($result) <= 0) {
2532
        return SESSION_INVISIBLE;
2533
    }
2534
2535
    $row = Database::fetch_assoc($result);
2536
    $visibility = $row['visibility'];
2537
2538
    // I don't care the session visibility.
2539
    if (empty($row['access_start_date']) && empty($row['access_end_date'])) {
2540
        // Session duration per student.
2541
        if (isset($row['duration']) && !empty($row['duration'])) {
2542
            $duration = $row['duration'] * 24 * 60 * 60;
2543
            $courseAccess = CourseManager::getFirstCourseAccessPerSessionAndUser($session_id, $userId);
2544
2545
            // If there is a session duration but there is no previous
2546
            // access by the user, then the session is still available
2547
            if (0 == count($courseAccess)) {
2548
                return SESSION_AVAILABLE;
2549
            }
2550
2551
            $currentTime = time();
2552
            $firstAccess = isset($courseAccess['login_course_date'])
2553
                ? api_strtotime($courseAccess['login_course_date'], 'UTC')
2554
                : 0;
2555
            $userDurationData = SessionManager::getUserSession($userId, $session_id);
2556
            $userDuration = isset($userDurationData['duration'])
2557
                ? (intval($userDurationData['duration']) * 24 * 60 * 60)
2558
                : 0;
2559
2560
            $totalDuration = $firstAccess + $duration + $userDuration;
2561
2562
            return $totalDuration > $currentTime ? SESSION_AVAILABLE : SESSION_VISIBLE_READ_ONLY;
2563
        }
2564
2565
        return SESSION_AVAILABLE;
2566
    }
2567
2568
    // If start date was set.
2569
    if (!empty($row['access_start_date'])) {
2570
        $visibility = $now > api_strtotime($row['access_start_date'], 'UTC') ? SESSION_AVAILABLE : SESSION_INVISIBLE;
2571
    } else {
2572
        // If there's no start date, assume it's available until the end date
2573
        $visibility = SESSION_AVAILABLE;
2574
    }
2575
2576
    // If the end date was set.
2577
    if (!empty($row['access_end_date'])) {
2578
        // Only if date_start said that it was ok
2579
        if (SESSION_AVAILABLE === $visibility) {
2580
            $visibility = $now < api_strtotime($row['access_end_date'], 'UTC')
2581
                ? SESSION_AVAILABLE // Date still available
2582
                : $row['visibility']; // Session ends
2583
        }
2584
    }
2585
2586
    // If I'm a coach the visibility can change in my favor depending in the coach dates.
2587
    $isCoach = api_is_coach($session_id, $courseId);
2588
2589
    if ($isCoach) {
2590
        // Test start date.
2591
        if (!empty($row['coach_access_start_date'])) {
2592
            $start = api_strtotime($row['coach_access_start_date'], 'UTC');
2593
            $visibility = $start < $now ? SESSION_AVAILABLE : SESSION_INVISIBLE;
2594
        }
2595
2596
        // Test end date.
2597
        if (!empty($row['coach_access_end_date'])) {
2598
            if (SESSION_AVAILABLE === $visibility) {
2599
                $endDateCoach = api_strtotime($row['coach_access_end_date'], 'UTC');
2600
                $visibility = $endDateCoach >= $now ? SESSION_AVAILABLE : $row['visibility'];
2601
            }
2602
        }
2603
    }
2604
2605
    return $visibility;
2606
}
2607
2608
/**
2609
 * This function returns a (star) session icon if the session is not null and
2610
 * the user is not a student.
2611
 *
2612
 * @param int $sessionId
2613
 * @param int $statusId  User status id - if 5 (student), will return empty
2614
 *
2615
 * @return string Session icon
2616
 */
2617
function api_get_session_image($sessionId, User $user)
2618
{
2619
    $sessionId = (int) $sessionId;
2620
    $image = '';
2621
    if (!$user->hasRole('ROLE_STUDENT')) {
2622
        // Check whether is not a student
2623
        if ($sessionId > 0) {
2624
            $image = '&nbsp;&nbsp;'.Display::getMdiIcon(
2625
                ObjectIcon::STAR,
2626
                'ch-tool-icon',
2627
                'align:absmiddle;',
2628
                ICON_SIZE_SMALL,
2629
                get_lang('Session-specific resource')
2630
            );
2631
        }
2632
    }
2633
2634
    return $image;
2635
}
2636
2637
/**
2638
 * This function add an additional condition according to the session of the course.
2639
 *
2640
 * @param int    $session_id        session id
2641
 * @param bool   $and               optional, true if more than one condition false if the only condition in the query
2642
 * @param bool   $with_base_content optional, true to accept content with session=0 as well,
2643
 *                                  false for strict session condition
2644
 * @param string $session_field
2645
 *
2646
 * @return string condition of the session
2647
 */
2648
function api_get_session_condition(
2649
    $session_id,
2650
    $and = true,
2651
    $with_base_content = false,
2652
    $session_field = 'session_id'
2653
) {
2654
    $session_id = (int) $session_id;
2655
2656
    if (empty($session_field)) {
2657
        $session_field = 'session_id';
2658
    }
2659
    // Condition to show resources by session
2660
    $condition_add = $and ? ' AND ' : ' WHERE ';
2661
2662
    if ($with_base_content) {
2663
        $condition_session = $condition_add." ( $session_field = $session_id OR $session_field = 0 OR $session_field IS NULL) ";
2664
    } else {
2665
        if (empty($session_id)) {
2666
            $condition_session = $condition_add." ($session_field = $session_id OR $session_field IS NULL)";
2667
        } else {
2668
            $condition_session = $condition_add." $session_field = $session_id ";
2669
        }
2670
    }
2671
2672
    return $condition_session;
2673
}
2674
2675
/**
2676
 * Returns the value of a setting from the web-adjustable admin config settings.
2677
 *
2678
 * WARNING true/false are stored as string, so when comparing you need to check e.g.
2679
 * if (api_get_setting('show_navigation_menu') == 'true') //CORRECT
2680
 * instead of
2681
 * if (api_get_setting('show_navigation_menu') == true) //INCORRECT
2682
 *
2683
 * @param string $variable The variable name
2684
 *
2685
 * @return string|array
2686
 */
2687
function api_get_setting($variable, $isArray = false, $key = null)
2688
{
2689
    $settingsManager = Container::getSettingsManager();
2690
    if (empty($settingsManager)) {
2691
        return '';
2692
    }
2693
    $variable = trim($variable);
2694
2695
    switch ($variable) {
2696
        case 'server_type':
2697
            $test = ['dev', 'test'];
2698
            $environment = Container::getEnvironment();
2699
            if (in_array($environment, $test)) {
2700
                return 'test';
2701
            }
2702
2703
            return 'prod';
2704
        // deprecated settings
2705
        // no break
2706
        case 'openid_authentication':
2707
        case 'service_ppt2lp':
2708
        case 'formLogin_hide_unhide_label':
2709
            return false;
2710
            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...
2711
        case 'tool_visible_by_default_at_creation':
2712
            $values = $settingsManager->getSetting($variable);
2713
            $newResult = [];
2714
            foreach ($values as $parameter) {
2715
                $newResult[$parameter] = 'true';
2716
            }
2717
2718
            return $newResult;
2719
            break;
2720
        default:
2721
            $settingValue = $settingsManager->getSetting($variable, true);
2722
            if (is_string($settingValue) && $isArray && !empty($settingValue)) {
2723
                // Check if the value is a valid JSON string
2724
                $decodedValue = json_decode($settingValue, true);
2725
2726
                // If it's a valid JSON string and the result is an array, return it
2727
                if (is_array($decodedValue)) {
2728
                    return $decodedValue;
2729
                }
2730
2731
                // If it's not an array, continue with the normal flow
2732
                // Optional: If you need to evaluate the value using eval
2733
                $strArrayValue = rtrim($settingValue, ';');
2734
                $value = eval("return $strArrayValue;");
0 ignored issues
show
introduced by
The use of eval() is discouraged.
Loading history...
2735
                if (is_array($value)) {
2736
                    return $value;
2737
                }
2738
            }
2739
2740
            // If the value is not a JSON array or wasn't returned previously, continue with the normal flow
2741
            if (!empty($key) && isset($settingValue[$variable][$key])) {
2742
                return $settingValue[$variable][$key];
2743
            }
2744
2745
            return $settingValue;
2746
            break;
2747
    }
2748
}
2749
2750
/**
2751
 * @param string $variable
2752
 * @param string $option
2753
 *
2754
 * @return bool
2755
 */
2756
function api_get_setting_in_list($variable, $option)
2757
{
2758
    $value = api_get_setting($variable);
2759
2760
    return in_array($option, $value);
2761
}
2762
2763
/**
2764
 * @param string $plugin
2765
 * @param string $variable
2766
 *
2767
 * @return string
2768
 */
2769
function api_get_plugin_setting($plugin, $variable)
2770
{
2771
    $variableName = $plugin.'_'.$variable;
2772
    //$result = api_get_setting($variableName);
2773
    $params = [
2774
        'category = ? AND subkey = ? AND variable = ?' => [
2775
            'Plugins',
2776
            $plugin,
2777
            $variableName,
2778
        ],
2779
    ];
2780
    $table = Database::get_main_table(TABLE_MAIN_SETTINGS);
2781
    $result = Database::select(
2782
        'selected_value',
2783
        $table,
2784
        ['where' => $params],
2785
        'one'
2786
    );
2787
    if ($result) {
2788
        $value = $result['selected_value'];
2789
        $serializedValue = @unserialize($result['selected_value'], []);
2790
        if (false !== $serializedValue) {
2791
            $value = $serializedValue;
2792
        }
2793
2794
        return $value;
2795
    }
2796
2797
    return null;
2798
    /// Old code
2799
2800
    $variableName = $plugin.'_'.$variable;
0 ignored issues
show
Unused Code introduced by
$variableName = $plugin . '_' . $variable is not reachable.

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

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

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

    return false;
}

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

Loading history...
2801
    $result = api_get_setting($variableName);
2802
2803
    if (isset($result[$plugin])) {
2804
        $value = $result[$plugin];
2805
2806
        $unserialized = UnserializeApi::unserialize('not_allowed_classes', $value, true);
2807
2808
        if (false !== $unserialized) {
2809
            $value = $unserialized;
2810
        }
2811
2812
        return $value;
2813
    }
2814
2815
    return null;
2816
}
2817
2818
/**
2819
 * Returns the value of a setting from the web-adjustable admin config settings.
2820
 */
2821
function api_get_settings_params($params)
2822
{
2823
    $table = Database::get_main_table(TABLE_MAIN_SETTINGS);
2824
2825
    return Database::select('*', $table, ['where' => $params]);
2826
}
2827
2828
/**
2829
 * @param array $params example: [id = ? => '1']
2830
 *
2831
 * @return array
2832
 */
2833
function api_get_settings_params_simple($params)
2834
{
2835
    $table = Database::get_main_table(TABLE_MAIN_SETTINGS);
2836
2837
    return Database::select('*', $table, ['where' => $params], 'one');
0 ignored issues
show
Bug Best Practice introduced by
The expression return Database::select(...re' => $params), 'one') also could return the type integer which is incompatible with the documented return type array.
Loading history...
2838
}
2839
2840
/**
2841
 * Returns the value of a setting from the web-adjustable admin config settings.
2842
 */
2843
function api_delete_settings_params($params)
2844
{
2845
    $table = Database::get_main_table(TABLE_MAIN_SETTINGS);
2846
2847
    return Database::delete($table, $params);
2848
}
2849
2850
/**
2851
 * Returns an escaped version of $_SERVER['PHP_SELF'] to avoid XSS injection.
2852
 *
2853
 * @return string Escaped version of $_SERVER['PHP_SELF']
2854
 */
2855
function api_get_self()
2856
{
2857
    return htmlentities($_SERVER['PHP_SELF']);
2858
}
2859
2860
/**
2861
 * Checks whether current user is a platform administrator.
2862
 *
2863
 * @param bool $allowSessionAdmins Whether session admins should be considered admins or not
2864
 * @param bool $allowDrh           Whether HR directors should be considered admins or not
2865
 *
2866
 * @return bool true if the user has platform admin rights,
2867
 *              false otherwise
2868
 *
2869
 * @see usermanager::is_admin(user_id) for a user-id specific function
2870
 */
2871
function api_is_platform_admin($allowSessionAdmins = false, $allowDrh = false)
2872
{
2873
    $currentUser = api_get_current_user();
2874
2875
    if (null === $currentUser) {
2876
        return false;
2877
    }
2878
2879
    $isAdmin = $currentUser->hasRole('ROLE_ADMIN') || $currentUser->hasRole('ROLE_SUPER_ADMIN');
2880
2881
    if ($isAdmin) {
2882
        return true;
2883
    }
2884
2885
    if ($allowSessionAdmins && $currentUser->hasRole('ROLE_SESSION_MANAGER')) {
2886
        return true;
2887
    }
2888
2889
    if ($allowDrh && $currentUser->hasRole('ROLE_HR')) {
2890
        return true;
2891
    }
2892
2893
    return false;
2894
}
2895
2896
/**
2897
 * Checks whether the user given as user id is in the admin table.
2898
 *
2899
 * @param int $user_id If none provided, will use current user
2900
 * @param int $url     URL ID. If provided, also check if the user is active on given URL
2901
 *
2902
 * @return bool True if the user is admin, false otherwise
2903
 */
2904
function api_is_platform_admin_by_id($user_id = null, $url = null)
2905
{
2906
    $user_id = (int) $user_id;
2907
    if (empty($user_id)) {
2908
        $user_id = api_get_user_id();
2909
    }
2910
    $admin_table = Database::get_main_table(TABLE_MAIN_ADMIN);
2911
    $sql = "SELECT * FROM $admin_table WHERE user_id = $user_id";
2912
    $res = Database::query($sql);
2913
    $is_admin = 1 === Database::num_rows($res);
2914
    if (!$is_admin || !isset($url)) {
2915
        return $is_admin;
2916
    }
2917
    // We get here only if $url is set
2918
    $url = (int) $url;
2919
    $url_user_table = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
2920
    $sql = "SELECT * FROM $url_user_table
2921
            WHERE access_url_id = $url AND user_id = $user_id";
2922
    $res = Database::query($sql);
2923
2924
    return 1 === Database::num_rows($res);
2925
}
2926
2927
/**
2928
 * Checks whether current user is allowed to create courses.
2929
 *
2930
 * @return bool true if the user has course creation rights,
2931
 *              false otherwise
2932
 */
2933
function api_is_allowed_to_create_course()
2934
{
2935
    if (api_is_platform_admin()) {
2936
        return true;
2937
    }
2938
2939
    // Teachers can only create courses
2940
    if (api_is_teacher()) {
2941
        if ('true' === api_get_setting('allow_users_to_create_courses')) {
2942
            return true;
2943
        } else {
2944
            return false;
2945
        }
2946
    }
2947
2948
    return Session::read('is_allowedCreateCourse');
2949
}
2950
2951
/**
2952
 * Checks whether the current user is a course administrator.
2953
 *
2954
 * @return bool True if current user is a course administrator
2955
 */
2956
function api_is_course_admin()
2957
{
2958
    if (api_is_platform_admin()) {
2959
        return true;
2960
    }
2961
2962
    $user = api_get_current_user();
2963
    if ($user) {
2964
        if (
2965
            $user->hasRole('ROLE_CURRENT_COURSE_SESSION_TEACHER') ||
2966
            $user->hasRole('ROLE_CURRENT_COURSE_TEACHER')
2967
        ) {
2968
            return true;
2969
        }
2970
    }
2971
2972
    return false;
2973
}
2974
2975
/**
2976
 * Checks whether the current user is a course coach
2977
 * Based on the presence of user in session_rel_user.relation_type (as session general coach, value 3).
2978
 *
2979
 * @return bool True if current user is a course coach
2980
 */
2981
function api_is_session_general_coach()
2982
{
2983
    return Session::read('is_session_general_coach');
2984
}
2985
2986
/**
2987
 * Checks whether the current user is a course tutor
2988
 * Based on the presence of user in session_rel_course_rel_user.user_id with status = 2.
2989
 *
2990
 * @return bool True if current user is a course tutor
2991
 */
2992
function api_is_course_tutor()
2993
{
2994
    return Session::read('is_courseTutor');
2995
}
2996
2997
/**
2998
 * @param int $user_id
2999
 * @param int $courseId
3000
 * @param int $session_id
3001
 *
3002
 * @return bool
3003
 */
3004
function api_is_course_session_coach($user_id, $courseId, $session_id)
3005
{
3006
    $session_table = Database::get_main_table(TABLE_MAIN_SESSION);
3007
    $session_rel_course_rel_user_table = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
3008
3009
    $user_id = (int) $user_id;
3010
    $session_id = (int) $session_id;
3011
    $courseId = (int) $courseId;
3012
3013
    $sql = "SELECT DISTINCT session.id
3014
            FROM $session_table
3015
            INNER JOIN $session_rel_course_rel_user_table session_rc_ru
3016
            ON session.id = session_rc_ru.session_id
3017
            WHERE
3018
                session_rc_ru.user_id = '".$user_id."'  AND
3019
                session_rc_ru.c_id = '$courseId' AND
3020
                session_rc_ru.status = ".SessionEntity::COURSE_COACH." AND
3021
                session_rc_ru.session_id = '$session_id'";
3022
    $result = Database::query($sql);
3023
3024
    return Database::num_rows($result) > 0;
3025
}
3026
3027
/**
3028
 * Checks whether the current user is a course or session coach.
3029
 *
3030
 * @param int $session_id
3031
 * @param int $courseId
3032
 * @param bool  Check whether we are in student view and, if we are, return false
3033
 * @param int $userId
3034
 *
3035
 * @return bool True if current user is a course or session coach
3036
 */
3037
function api_is_coach($session_id = 0, $courseId = null, $check_student_view = true, $userId = 0)
3038
{
3039
    $userId = empty($userId) ? api_get_user_id() : (int) $userId;
3040
3041
    if (!empty($session_id)) {
3042
        $session_id = (int) $session_id;
3043
    } else {
3044
        $session_id = api_get_session_id();
3045
    }
3046
3047
    // The student preview was on
3048
    if ($check_student_view && api_is_student_view_active()) {
3049
        return false;
3050
    }
3051
3052
    if (!empty($courseId)) {
3053
        $courseId = (int) $courseId;
3054
    } else {
3055
        $courseId = api_get_course_int_id();
3056
    }
3057
3058
    $session_table = Database::get_main_table(TABLE_MAIN_SESSION);
3059
    $session_rel_course_rel_user_table = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
3060
    $tblSessionRelUser = Database::get_main_table(TABLE_MAIN_SESSION_USER);
3061
    $sessionIsCoach = [];
3062
3063
    if (!empty($courseId)) {
3064
        $sql = "SELECT DISTINCT s.id, title, access_start_date, access_end_date
3065
                FROM $session_table s
3066
                INNER JOIN $session_rel_course_rel_user_table session_rc_ru
3067
                ON session_rc_ru.session_id = s.id AND session_rc_ru.user_id = '".$userId."'
3068
                WHERE
3069
                    session_rc_ru.c_id = '$courseId' AND
3070
                    session_rc_ru.status =".SessionEntity::COURSE_COACH." AND
3071
                    session_rc_ru.session_id = '$session_id'";
3072
        $result = Database::query($sql);
3073
        $sessionIsCoach = Database::store_result($result);
3074
    }
3075
3076
    if (!empty($session_id)) {
3077
        $sql = "SELECT DISTINCT s.id
3078
                FROM $session_table AS s
3079
                INNER JOIN $tblSessionRelUser sru
3080
                ON s.id = sru.session_id
3081
                WHERE
3082
                    sru.user_id = $userId AND
3083
                    s.id = $session_id AND
3084
                    sru.relation_type = ".SessionEntity::GENERAL_COACH."
3085
                ORDER BY s.access_start_date, s.access_end_date, s.title";
3086
        $result = Database::query($sql);
3087
        if (!empty($sessionIsCoach)) {
3088
            $sessionIsCoach = array_merge(
3089
                $sessionIsCoach,
3090
                Database::store_result($result)
3091
            );
3092
        } else {
3093
            $sessionIsCoach = Database::store_result($result);
3094
        }
3095
    }
3096
3097
    return count($sessionIsCoach) > 0;
3098
}
3099
3100
function api_user_has_role(string $role, ?User $user = null): bool
3101
{
3102
    if (null === $user) {
3103
        $user = api_get_current_user();
3104
    }
3105
3106
    if (null === $user) {
3107
        return false;
3108
    }
3109
3110
    return $user->hasRole($role);
3111
}
3112
3113
function api_is_allowed_in_course(): bool
3114
{
3115
    if (api_is_platform_admin()) {
3116
        return true;
3117
    }
3118
3119
    $user = api_get_current_user();
3120
    if ($user instanceof User) {
3121
        if ($user->hasRole('ROLE_CURRENT_COURSE_SESSION_STUDENT') ||
3122
            $user->hasRole('ROLE_CURRENT_COURSE_SESSION_TEACHER') ||
3123
            $user->hasRole('ROLE_CURRENT_COURSE_STUDENT') ||
3124
            $user->hasRole('ROLE_CURRENT_COURSE_TEACHER')
3125
        ) {
3126
            return true;
3127
        }
3128
    }
3129
3130
    return false;
3131
}
3132
3133
/**
3134
 * Checks whether current user is a student boss.
3135
 */
3136
function api_is_student_boss(?User $user = null): bool
3137
{
3138
    return api_user_has_role('ROLE_STUDENT_BOSS', $user);
3139
}
3140
3141
/**
3142
 * Checks whether the current user is a session administrator.
3143
 *
3144
 * @return bool True if current user is a course administrator
3145
 */
3146
function api_is_session_admin(?User $user = null)
3147
{
3148
    return api_user_has_role('ROLE_SESSION_MANAGER', $user);
3149
}
3150
3151
/**
3152
 * Checks whether the current user is a human resources manager.
3153
 *
3154
 * @return bool True if current user is a human resources manager
3155
 */
3156
function api_is_drh()
3157
{
3158
    return api_user_has_role('ROLE_HR');
3159
}
3160
3161
/**
3162
 * Checks whether the current user is a student.
3163
 *
3164
 * @return bool True if current user is a human resources manager
3165
 */
3166
function api_is_student()
3167
{
3168
    return api_user_has_role('ROLE_STUDENT');
3169
}
3170
3171
/**
3172
 * Checks whether the current user has the status 'teacher'.
3173
 *
3174
 * @return bool True if current user is a human resources manager
3175
 */
3176
function api_is_teacher()
3177
{
3178
    return api_user_has_role('ROLE_TEACHER');
3179
}
3180
3181
/**
3182
 * Checks whether the current user is a invited user.
3183
 *
3184
 * @return bool
3185
 */
3186
function api_is_invitee()
3187
{
3188
    return api_user_has_role('ROLE_INVITEE');
3189
}
3190
3191
/**
3192
 * This function checks whether a session is assigned into a category.
3193
 *
3194
 * @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...
3195
 * @param string    - category name
3196
 *
3197
 * @return bool - true if is found, otherwise false
3198
 */
3199
function api_is_session_in_category($session_id, $category_name)
3200
{
3201
    $session_id = (int) $session_id;
3202
    $category_name = Database::escape_string($category_name);
3203
    $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
3204
    $tbl_session_category = Database::get_main_table(TABLE_MAIN_SESSION_CATEGORY);
3205
3206
    $sql = "SELECT 1
3207
            FROM $tbl_session
3208
            WHERE $session_id IN (
3209
                SELECT s.id FROM $tbl_session s, $tbl_session_category sc
3210
                WHERE
3211
                  s.session_category_id = sc.id AND
3212
                  sc.name LIKE '%$category_name'
3213
            )";
3214
    $rs = Database::query($sql);
3215
3216
    if (Database::num_rows($rs) > 0) {
3217
        return true;
3218
    }
3219
3220
    return false;
3221
}
3222
3223
/**
3224
 * Displays options for switching between student view and course manager view.
3225
 *
3226
 * Changes in version 1.2 (Patrick Cool)
3227
 * Student view switch now behaves as a real switch. It maintains its current state until the state
3228
 * is changed explicitly
3229
 *
3230
 * Changes in version 1.1 (Patrick Cool)
3231
 * student view now works correctly in subfolders of the document tool
3232
 * student view works correctly in the new links tool
3233
 *
3234
 * Example code for using this in your tools:
3235
 * //if ($is_courseAdmin && api_get_setting('student_view_enabled') == 'true') {
3236
 * //   display_tool_view_option($isStudentView);
3237
 * //}
3238
 * //and in later sections, use api_is_allowed_to_edit()
3239
 *
3240
 * @author Roan Embrechts
3241
 * @author Patrick Cool
3242
 * @author Julio Montoya, changes added in Chamilo
3243
 *
3244
 * @version 1.2
3245
 *
3246
 * @todo rewrite code so it is easier to understand
3247
 */
3248
function api_display_tool_view_option()
3249
{
3250
    if ('true' != api_get_setting('student_view_enabled')) {
3251
        return '';
3252
    }
3253
3254
    $sourceurl = '';
3255
    $is_framed = false;
3256
    // Exceptions apply for all multi-frames pages
3257
    if (false !== strpos($_SERVER['REQUEST_URI'], 'chat/chat_banner.php')) {
3258
        // The chat is a multiframe bit that doesn't work too well with the student_view, so do not show the link
3259
        return '';
3260
    }
3261
3262
    // Uncomment to remove student view link from document view page
3263
    if (false !== strpos($_SERVER['REQUEST_URI'], 'lp/lp_header.php')) {
3264
        if (empty($_GET['lp_id'])) {
3265
            return '';
3266
        }
3267
        $sourceurl = substr($_SERVER['REQUEST_URI'], 0, strpos($_SERVER['REQUEST_URI'], '?'));
3268
        $sourceurl = str_replace(
3269
            'lp/lp_header.php',
3270
            'lp/lp_controller.php?'.api_get_cidreq().'&action=view&lp_id='.intval($_GET['lp_id']).'&isStudentView='.('studentview' == $_SESSION['studentview'] ? 'false' : 'true'),
3271
            $sourceurl
3272
        );
3273
        //showinframes doesn't handle student view anyway...
3274
        //return '';
3275
        $is_framed = true;
3276
    }
3277
3278
    // Check whether the $_SERVER['REQUEST_URI'] contains already url parameters (thus a questionmark)
3279
    if (!$is_framed) {
3280
        if (false === strpos($_SERVER['REQUEST_URI'], '?')) {
3281
            $sourceurl = api_get_self().'?'.api_get_cidreq();
3282
        } else {
3283
            $sourceurl = $_SERVER['REQUEST_URI'];
3284
        }
3285
    }
3286
3287
    $output_string = '';
3288
    if (!empty($_SESSION['studentview'])) {
3289
        if ('studentview' == $_SESSION['studentview']) {
3290
            // We have to remove the isStudentView=true from the $sourceurl
3291
            $sourceurl = str_replace('&isStudentView=true', '', $sourceurl);
3292
            $sourceurl = str_replace('&isStudentView=false', '', $sourceurl);
3293
            $output_string .= '<a class="btn btn--primary btn-sm" href="'.$sourceurl.'&isStudentView=false" target="_self">'.
3294
                Display::getMdiIcon('eye').' '.get_lang('Switch to teacher view').'</a>';
3295
        } elseif ('teacherview' == $_SESSION['studentview']) {
3296
            // Switching to teacherview
3297
            $sourceurl = str_replace('&isStudentView=true', '', $sourceurl);
3298
            $sourceurl = str_replace('&isStudentView=false', '', $sourceurl);
3299
            $output_string .= '<a class="btn btn--plain btn-sm" href="'.$sourceurl.'&isStudentView=true" target="_self">'.
3300
                Display::getMdiIcon('eye').' '.get_lang('Switch to student view').'</a>';
3301
        }
3302
    } else {
3303
        $output_string .= '<a class="btn btn--plain btn-sm" href="'.$sourceurl.'&isStudentView=true" target="_self">'.
3304
            Display::getMdiIcon('eye').' '.get_lang('Switch to student view').'</a>';
3305
    }
3306
    $output_string = Security::remove_XSS($output_string);
3307
    $html = Display::tag('div', $output_string, ['class' => 'view-options']);
3308
3309
    return $html;
3310
}
3311
3312
/**
3313
 * Function that removes the need to directly use is_courseAdmin global in
3314
 * tool scripts. It returns true or false depending on the user's rights in
3315
 * this particular course.
3316
 * Optionally checking for tutor and coach roles here allows us to use the
3317
 * student_view feature altogether with these roles as well.
3318
 *
3319
 * @param bool  Whether to check if the user has the tutor role
3320
 * @param bool  Whether to check if the user has the coach role
3321
 * @param bool  Whether to check if the user has the session coach role
3322
 * @param bool  check the student view or not
3323
 *
3324
 * @author Roan Embrechts
3325
 * @author Patrick Cool
3326
 * @author Julio Montoya
3327
 *
3328
 * @version 1.1, February 2004
3329
 *
3330
 * @return bool true: the user has the rights to edit, false: he does not
3331
 */
3332
function api_is_allowed_to_edit(
3333
    $tutor = false,
3334
    $coach = false,
3335
    $session_coach = false,
3336
    $check_student_view = true
3337
) {
3338
    $allowSessionAdminEdit = 'true' === api_get_setting('session.session_admins_edit_courses_content');
3339
    // Admins can edit anything.
3340
    if (api_is_platform_admin($allowSessionAdminEdit)) {
3341
        //The student preview was on
3342
        if ($check_student_view && api_is_student_view_active()) {
3343
            return false;
3344
        }
3345
3346
        return true;
3347
    }
3348
3349
    $sessionId = api_get_session_id();
3350
3351
    if ($sessionId && 'true' === api_get_setting('session.session_courses_read_only_mode')) {
3352
        $efv = new ExtraFieldValue('course');
3353
        $lockExrafieldField = $efv->get_values_by_handler_and_field_variable(
3354
            api_get_course_int_id(),
3355
            'session_courses_read_only_mode'
3356
        );
3357
3358
        if (!empty($lockExrafieldField['value'])) {
3359
            return false;
3360
        }
3361
    }
3362
3363
    $is_allowed_coach_to_edit = api_is_coach(null, null, $check_student_view);
3364
    $session_visibility = api_get_session_visibility($sessionId);
3365
    $is_courseAdmin = api_is_course_admin();
3366
3367
    if (!$is_courseAdmin && $tutor) {
3368
        // If we also want to check if the user is a tutor...
3369
        $is_courseAdmin = $is_courseAdmin || api_is_course_tutor();
3370
    }
3371
3372
    if (!$is_courseAdmin && $coach) {
3373
        // If we also want to check if the user is a coach...';
3374
        // Check if session visibility is read only for coaches.
3375
        if (SESSION_VISIBLE_READ_ONLY == $session_visibility) {
3376
            $is_allowed_coach_to_edit = false;
3377
        }
3378
3379
        if ('true' === api_get_setting('allow_coach_to_edit_course_session')) {
3380
            // Check if coach is allowed to edit a course.
3381
            $is_courseAdmin = $is_courseAdmin || $is_allowed_coach_to_edit;
3382
        }
3383
    }
3384
3385
    if (!$is_courseAdmin && $session_coach) {
3386
        $is_courseAdmin = $is_courseAdmin || $is_allowed_coach_to_edit;
3387
    }
3388
3389
    // Check if the student_view is enabled, and if so, if it is activated.
3390
    if ('true' === api_get_setting('student_view_enabled')) {
3391
        $studentView = api_is_student_view_active();
3392
        if (!empty($sessionId)) {
3393
            // Check if session visibility is read only for coaches.
3394
            if (SESSION_VISIBLE_READ_ONLY == $session_visibility) {
3395
                $is_allowed_coach_to_edit = false;
3396
            }
3397
3398
            $is_allowed = false;
3399
            if ('true' === api_get_setting('allow_coach_to_edit_course_session')) {
3400
                // Check if coach is allowed to edit a course.
3401
                $is_allowed = $is_allowed_coach_to_edit;
3402
            }
3403
            if ($check_student_view) {
3404
                $is_allowed = $is_allowed && false === $studentView;
3405
            }
3406
        } else {
3407
            $is_allowed = $is_courseAdmin;
3408
            if ($check_student_view) {
3409
                $is_allowed = $is_courseAdmin && false === $studentView;
3410
            }
3411
        }
3412
3413
        return $is_allowed;
3414
    } else {
3415
        return $is_courseAdmin;
3416
    }
3417
}
3418
3419
/**
3420
 * Returns true if user is a course coach of at least one course in session.
3421
 *
3422
 * @param int $sessionId
3423
 *
3424
 * @return bool
3425
 */
3426
function api_is_coach_of_course_in_session($sessionId)
3427
{
3428
    if (api_is_platform_admin()) {
3429
        return true;
3430
    }
3431
3432
    $userId = api_get_user_id();
3433
    $courseList = UserManager::get_courses_list_by_session(
3434
        $userId,
3435
        $sessionId
3436
    );
3437
3438
    // Session visibility.
3439
    $visibility = api_get_session_visibility(
3440
        $sessionId,
3441
        null,
3442
        false
3443
    );
3444
3445
    if (SESSION_VISIBLE != $visibility && !empty($courseList)) {
3446
        // Course Coach session visibility.
3447
        $blockedCourseCount = 0;
3448
        $closedVisibilityList = [
3449
            COURSE_VISIBILITY_CLOSED,
3450
            COURSE_VISIBILITY_HIDDEN,
3451
        ];
3452
3453
        foreach ($courseList as $course) {
3454
            // Checking session visibility
3455
            $sessionCourseVisibility = api_get_session_visibility(
3456
                $sessionId,
3457
                $course['real_id']
3458
            );
3459
3460
            $courseIsVisible = !in_array(
3461
                $course['visibility'],
3462
                $closedVisibilityList
3463
            );
3464
            if (false === $courseIsVisible || SESSION_INVISIBLE == $sessionCourseVisibility) {
3465
                $blockedCourseCount++;
3466
            }
3467
        }
3468
3469
        // If all courses are blocked then no show in the list.
3470
        if ($blockedCourseCount === count($courseList)) {
3471
            $visibility = SESSION_INVISIBLE;
3472
        } else {
3473
            $visibility = SESSION_VISIBLE;
3474
        }
3475
    }
3476
3477
    switch ($visibility) {
3478
        case SESSION_VISIBLE_READ_ONLY:
3479
        case SESSION_VISIBLE:
3480
        case SESSION_AVAILABLE:
3481
            return true;
3482
            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...
3483
        case SESSION_INVISIBLE:
3484
            return false;
3485
    }
3486
3487
    return false;
3488
}
3489
3490
/**
3491
 * Checks if a student can edit contents in a session depending
3492
 * on the session visibility.
3493
 *
3494
 * @param bool $tutor Whether to check if the user has the tutor role
3495
 * @param bool $coach Whether to check if the user has the coach role
3496
 *
3497
 * @return bool true: the user has the rights to edit, false: he does not
3498
 */
3499
function api_is_allowed_to_session_edit($tutor = false, $coach = false)
3500
{
3501
    if (api_is_allowed_to_edit($tutor, $coach)) {
3502
        // If I'm a teacher, I will return true in order to not affect the normal behaviour of Chamilo tools.
3503
        return true;
3504
    } else {
3505
        $sessionId = api_get_session_id();
3506
3507
        if (0 == $sessionId) {
3508
            // I'm not in a session so i will return true to not affect the normal behaviour of Chamilo tools.
3509
            return true;
3510
        } else {
3511
            // I'm in a session and I'm a student
3512
            // Get the session visibility
3513
            $session_visibility = api_get_session_visibility($sessionId);
3514
            // if 5 the session is still available
3515
            switch ($session_visibility) {
3516
                case SESSION_VISIBLE_READ_ONLY: // 1
3517
                    return false;
3518
                case SESSION_VISIBLE:           // 2
3519
                    return true;
3520
                case SESSION_INVISIBLE:         // 3
3521
                    return false;
3522
                case SESSION_AVAILABLE:         //5
3523
                    return true;
3524
            }
3525
        }
3526
    }
3527
3528
    return false;
3529
}
3530
3531
/**
3532
 * Current user is anon?
3533
 *
3534
 * @return bool true if this user is anonymous, false otherwise
3535
 */
3536
function api_is_anonymous()
3537
{
3538
    return !Container::getAuthorizationChecker()->isGranted('IS_AUTHENTICATED');
3539
}
3540
3541
/**
3542
 * Displays message "You are not allowed here..." and exits the entire script.
3543
 *
3544
 * @param bool $print_headers Whether to print headers (default = false -> does not print them)
3545
 * @param string $message
3546
 * @param int $responseCode
3547
 *
3548
 * @throws Exception
3549
 */
3550
function api_not_allowed(
3551
    $print_headers = false,
3552
    $message = null,
3553
    $responseCode = 0
3554
): never {
3555
    throw new NotAllowedException($message ?: 'You are not allowed', null, $responseCode);
3556
}
3557
3558
/**
3559
 * @param string $languageIsoCode
3560
 *
3561
 * @return string
3562
 */
3563
function languageToCountryIsoCode($languageIsoCode)
3564
{
3565
    $allow = ('true' === api_get_setting('language.language_flags_by_country'));
3566
3567
    // @todo save in DB
3568
    switch ($languageIsoCode) {
3569
        case 'ar':
3570
            $country = 'ae';
3571
            break;
3572
        case 'bs':
3573
            $country = 'ba';
3574
            break;
3575
        case 'ca':
3576
            $country = 'es';
3577
            if ($allow) {
3578
                $country = 'catalan';
3579
            }
3580
            break;
3581
        case 'cs':
3582
            $country = 'cz';
3583
            break;
3584
        case 'da':
3585
            $country = 'dk';
3586
            break;
3587
        case 'el':
3588
            $country = 'ae';
3589
            break;
3590
        case 'en':
3591
            $country = 'gb';
3592
            break;
3593
        case 'eu': // Euskera
3594
            $country = 'es';
3595
            if ($allow) {
3596
                $country = 'basque';
3597
            }
3598
            break;
3599
        case 'gl': // galego
3600
            $country = 'es';
3601
            if ($allow) {
3602
                $country = 'galician';
3603
            }
3604
            break;
3605
        case 'he':
3606
            $country = 'il';
3607
            break;
3608
        case 'ja':
3609
            $country = 'jp';
3610
            break;
3611
        case 'ka':
3612
            $country = 'ge';
3613
            break;
3614
        case 'ko':
3615
            $country = 'kr';
3616
            break;
3617
        case 'ms':
3618
            $country = 'my';
3619
            break;
3620
        case 'pt-BR':
3621
            $country = 'br';
3622
            break;
3623
        case 'qu':
3624
            $country = 'pe';
3625
            break;
3626
        case 'sl':
3627
            $country = 'si';
3628
            break;
3629
        case 'sv':
3630
            $country = 'se';
3631
            break;
3632
        case 'uk': // Ukraine
3633
            $country = 'ua';
3634
            break;
3635
        case 'zh-TW':
3636
        case 'zh':
3637
            $country = 'cn';
3638
            break;
3639
        default:
3640
            $country = $languageIsoCode;
3641
            break;
3642
    }
3643
    $country = strtolower($country);
3644
3645
    return $country;
3646
}
3647
3648
/**
3649
 * Returns a list of all the languages that are made available by the admin.
3650
 *
3651
 * @return array An array with all languages. Structure of the array is
3652
 *               array['name'] = An array with the name of every language
3653
 *               array['folder'] = An array with the corresponding names of the language-folders in the filesystem
3654
 */
3655
function api_get_languages()
3656
{
3657
    $table = Database::get_main_table(TABLE_MAIN_LANGUAGE);
3658
    $sql = "SELECT * FROM $table WHERE available='1'
3659
            ORDER BY original_name ASC";
3660
    $result = Database::query($sql);
3661
    $languages = [];
3662
    while ($row = Database::fetch_assoc($result)) {
3663
        $languages[$row['isocode']] = $row['original_name'];
3664
    }
3665
3666
    return $languages;
3667
}
3668
3669
/**
3670
 * Returns the id (the database id) of a language.
3671
 *
3672
 * @param   string  language name (the corresponding name of the language-folder in the filesystem)
3673
 *
3674
 * @return int id of the language
3675
 */
3676
function api_get_language_id($language)
3677
{
3678
    $tbl_language = Database::get_main_table(TABLE_MAIN_LANGUAGE);
3679
    if (empty($language)) {
3680
        return null;
3681
    }
3682
3683
    // We check the language by iscocode
3684
    $langInfo = api_get_language_from_iso($language);
3685
    if (null !== $langInfo && !empty($langInfo->getId())) {
3686
        return $langInfo->getId();
3687
    }
3688
3689
    $language = Database::escape_string($language);
3690
    $sql = "SELECT id FROM $tbl_language
3691
            WHERE english_name = '$language' LIMIT 1";
3692
    $result = Database::query($sql);
3693
    $row = Database::fetch_array($result);
3694
3695
    return $row['id'];
3696
}
3697
3698
/**
3699
 * Get the language information by its id.
3700
 *
3701
 * @param int $languageId
3702
 *
3703
 * @throws Exception
3704
 *
3705
 * @return array
3706
 */
3707
function api_get_language_info($languageId)
3708
{
3709
    if (empty($languageId)) {
3710
        return [];
3711
    }
3712
3713
    $language = Database::getManager()->find(Language::class, $languageId);
3714
3715
    if (!$language) {
3716
        return [];
3717
    }
3718
3719
    return [
3720
        'id' => $language->getId(),
3721
        'original_name' => $language->getOriginalName(),
3722
        'english_name' => $language->getEnglishName(),
3723
        'isocode' => $language->getIsocode(),
3724
        'available' => $language->getAvailable(),
3725
        'parent_id' => $language->getParent() ? $language->getParent()->getId() : null,
3726
    ];
3727
}
3728
3729
/**
3730
 * @param string $code
3731
 *
3732
 * @return Language
3733
 */
3734
function api_get_language_from_iso($code)
3735
{
3736
    $em = Database::getManager();
3737
3738
    return $em->getRepository(Language::class)->findOneBy(['isocode' => $code]);
3739
}
3740
3741
/**
3742
 * Shortcut to ThemeHelper::getVisualTheme()
3743
 */
3744
function api_get_visual_theme(): string
3745
{
3746
    $themeHelper = Container::$container->get(ThemeHelper::class);
0 ignored issues
show
Bug introduced by
The method get() does not exist on null. ( Ignorable by Annotation )

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

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

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

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

Loading history...
3747
3748
    return $themeHelper->getVisualTheme();
3749
}
3750
3751
/**
3752
 * Returns a list of CSS themes currently available in the CSS folder
3753
 * The folder must have a default.css file.
3754
 *
3755
 * @param bool $getOnlyThemeFromVirtualInstance Used by the vchamilo plugin
3756
 *
3757
 * @return array list of themes directories from the css folder
3758
 *               Note: Directory names (names of themes) in the file system should contain ASCII-characters only
3759
 */
3760
function api_get_themes($getOnlyThemeFromVirtualInstance = false)
3761
{
3762
    // This configuration value is set by the vchamilo plugin
3763
    $virtualTheme = api_get_configuration_value('virtual_css_theme_folder');
3764
3765
    $readCssFolder = function ($dir) use ($virtualTheme) {
3766
        $finder = new Finder();
3767
        $themes = $finder->directories()->in($dir)->depth(0)->sortByName();
3768
        $list = [];
3769
        /** @var Symfony\Component\Finder\SplFileInfo $theme */
3770
        foreach ($themes as $theme) {
3771
            $folder = $theme->getFilename();
3772
            // A theme folder is consider if there's a default.css file
3773
            if (!file_exists($theme->getPathname().'/default.css')) {
3774
                continue;
3775
            }
3776
            $name = ucwords(str_replace('_', ' ', $folder));
3777
            if ($folder == $virtualTheme) {
3778
                continue;
3779
            }
3780
            $list[$folder] = $name;
3781
        }
3782
3783
        return $list;
3784
    };
3785
3786
    $dir = Container::getProjectDir().'var/themes/';
3787
    $list = $readCssFolder($dir);
3788
3789
    if (!empty($virtualTheme)) {
3790
        $newList = $readCssFolder($dir.'/'.$virtualTheme);
3791
        if ($getOnlyThemeFromVirtualInstance) {
3792
            return $newList;
3793
        }
3794
        $list = $list + $newList;
3795
        asort($list);
3796
    }
3797
3798
    return $list;
3799
}
3800
3801
/**
3802
 * Find the largest sort value in a given user_course_category
3803
 * This function is used when we are moving a course to a different category
3804
 * and also when a user subscribes to courses (the new course is added at the end of the main category.
3805
 *
3806
 * @param int $courseCategoryId the id of the user_course_category
3807
 * @param int $userId
3808
 *
3809
 * @return int the value of the highest sort of the user_course_category
3810
 */
3811
function api_max_sort_value($courseCategoryId, $userId)
3812
{
3813
    $user = api_get_user_entity($userId);
3814
    $userCourseCategory = Database::getManager()->getRepository(UserCourseCategory::class)->find($courseCategoryId);
3815
3816
    return null === $user ? 0 : $user->getMaxSortValue($userCourseCategory);
3817
}
3818
3819
/**
3820
 * Transforms a number of seconds in hh:mm:ss format.
3821
 *
3822
 * @author Julian Prud'homme
3823
 *
3824
 * @param int    $seconds      number of seconds
3825
 * @param string $space
3826
 * @param bool   $showSeconds
3827
 * @param bool   $roundMinutes
3828
 *
3829
 * @return string the formatted time
3830
 */
3831
function api_time_to_hms($seconds, $space = ':', $showSeconds = true, $roundMinutes = false)
3832
{
3833
    // $seconds = -1 means that we have wrong data in the db.
3834
    if (-1 == $seconds) {
3835
        return
3836
            get_lang('Unknown').
3837
            Display::getMdiIcon(
3838
                ActionIcon::INFORMATION,
3839
                'ch-tool-icon',
3840
                'align: absmiddle; hspace: 3px',
3841
                ICON_SIZE_SMALL,
3842
                get_lang('The datas about this user were registered when the calculation of time spent on the platform wasn\'t possible.')
3843
            );
3844
    }
3845
3846
    // How many hours ?
3847
    $hours = floor($seconds / 3600);
3848
3849
    // How many minutes ?
3850
    $min = floor(($seconds - ($hours * 3600)) / 60);
3851
3852
    if ($roundMinutes) {
3853
        if ($min >= 45) {
3854
            $min = 45;
3855
        }
3856
3857
        if ($min >= 30 && $min <= 44) {
3858
            $min = 30;
3859
        }
3860
3861
        if ($min >= 15 && $min <= 29) {
3862
            $min = 15;
3863
        }
3864
3865
        if ($min >= 0 && $min <= 14) {
3866
            $min = 0;
3867
        }
3868
    }
3869
3870
    // How many seconds
3871
    $sec = floor($seconds - ($hours * 3600) - ($min * 60));
3872
3873
    if ($hours < 10) {
3874
        $hours = "0$hours";
3875
    }
3876
3877
    if ($sec < 10) {
3878
        $sec = "0$sec";
3879
    }
3880
3881
    if ($min < 10) {
3882
        $min = "0$min";
3883
    }
3884
3885
    $seconds = '';
3886
    if ($showSeconds) {
3887
        $seconds = $space.$sec;
3888
    }
3889
3890
    return $hours.$space.$min.$seconds;
3891
}
3892
3893
/**
3894
 * Returns the permissions to be assigned to every newly created directory by the web-server.
3895
 * The return value is based on the platform administrator's setting
3896
 * "Administration > Configuration settings > Security > Permissions for new directories".
3897
 *
3898
 * @return int returns the permissions in the format "Owner-Group-Others, Read-Write-Execute", as an integer value
3899
 */
3900
function api_get_permissions_for_new_directories()
3901
{
3902
    static $permissions;
3903
    if (!isset($permissions)) {
3904
        $permissions = trim(api_get_setting('permissions_for_new_directories'));
3905
        // The default value 0777 is according to that in the platform administration panel after fresh system installation.
3906
        $permissions = octdec(!empty($permissions) ? $permissions : '0777');
3907
    }
3908
3909
    return $permissions;
3910
}
3911
3912
/**
3913
 * Returns the permissions to be assigned to every newly created directory by the web-server.
3914
 * The return value is based on the platform administrator's setting
3915
 * "Administration > Configuration settings > Security > Permissions for new files".
3916
 *
3917
 * @return int returns the permissions in the format
3918
 *             "Owner-Group-Others, Read-Write-Execute", as an integer value
3919
 */
3920
function api_get_permissions_for_new_files()
3921
{
3922
    static $permissions;
3923
    if (!isset($permissions)) {
3924
        $permissions = trim(api_get_setting('permissions_for_new_files'));
3925
        // The default value 0666 is according to that in the platform
3926
        // administration panel after fresh system installation.
3927
        $permissions = octdec(!empty($permissions) ? $permissions : '0666');
3928
    }
3929
3930
    return $permissions;
3931
}
3932
3933
/**
3934
 * Deletes a file, or a folder and its contents.
3935
 *
3936
 * @author      Aidan Lister <[email protected]>
3937
 *
3938
 * @version     1.0.3
3939
 *
3940
 * @param string $dirname Directory to delete
3941
 * @param       bool     Deletes only the content or not
3942
 * @param bool $strict if one folder/file fails stop the loop
3943
 *
3944
 * @return bool Returns TRUE on success, FALSE on failure
3945
 *
3946
 * @see http://aidanlister.com/2004/04/recursively-deleting-a-folder-in-php/
3947
 *
3948
 * @author      Yannick Warnier, adaptation for the Chamilo LMS, April, 2008
3949
 * @author      Ivan Tcholakov, a sanity check about Directory class creation has been added, September, 2009
3950
 */
3951
function rmdirr($dirname, $delete_only_content_in_folder = false, $strict = false)
3952
{
3953
    $res = true;
3954
    // A sanity check.
3955
    if (!file_exists($dirname)) {
3956
        return false;
3957
    }
3958
    $php_errormsg = '';
3959
    // Simple delete for a file.
3960
    if (is_file($dirname) || is_link($dirname)) {
3961
        $res = unlink($dirname);
3962
        if (false === $res) {
3963
            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);
3964
        }
3965
3966
        return $res;
3967
    }
3968
3969
    // Loop through the folder.
3970
    $dir = dir($dirname);
3971
    // A sanity check.
3972
    $is_object_dir = is_object($dir);
3973
    if ($is_object_dir) {
3974
        while (false !== $entry = $dir->read()) {
3975
            // Skip pointers.
3976
            if ('.' == $entry || '..' == $entry) {
3977
                continue;
3978
            }
3979
3980
            // Recurse.
3981
            if ($strict) {
3982
                $result = rmdirr("$dirname/$entry");
3983
                if (false == $result) {
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...
3984
                    $res = false;
3985
                    break;
3986
                }
3987
            } else {
3988
                rmdirr("$dirname/$entry");
3989
            }
3990
        }
3991
    }
3992
3993
    // Clean up.
3994
    if ($is_object_dir) {
3995
        $dir->close();
3996
    }
3997
3998
    if (false == $delete_only_content_in_folder) {
3999
        $res = rmdir($dirname);
4000
        if (false === $res) {
4001
            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);
4002
        }
4003
    }
4004
4005
    return $res;
4006
}
4007
4008
// TODO: This function is to be simplified. File access modes to be implemented.
4009
/**
4010
 * function adapted from a php.net comment
4011
 * copy recursively a folder.
4012
 *
4013
 * @param the source folder
4014
 * @param the dest folder
4015
 * @param an array of excluded file_name (without extension)
4016
 * @param copied_files the returned array of copied files
4017
 * @param string $source
4018
 * @param string $dest
4019
 */
4020
function copyr($source, $dest, $exclude = [], $copied_files = [])
4021
{
4022
    if (empty($dest)) {
4023
        return false;
4024
    }
4025
    // Simple copy for a file
4026
    if (is_file($source)) {
4027
        $path_info = pathinfo($source);
4028
        if (!in_array($path_info['filename'], $exclude)) {
4029
            copy($source, $dest);
4030
        }
4031
4032
        return true;
4033
    } elseif (!is_dir($source)) {
4034
        //then source is not a dir nor a file, return
4035
        return false;
4036
    }
4037
4038
    // Make destination directory.
4039
    if (!is_dir($dest)) {
4040
        mkdir($dest, api_get_permissions_for_new_directories());
4041
    }
4042
4043
    // Loop through the folder.
4044
    $dir = dir($source);
4045
    while (false !== $entry = $dir->read()) {
4046
        // Skip pointers
4047
        if ('.' == $entry || '..' == $entry) {
4048
            continue;
4049
        }
4050
4051
        // Deep copy directories.
4052
        if ($dest !== "$source/$entry") {
4053
            $files = copyr("$source/$entry", "$dest/$entry", $exclude, $copied_files);
4054
        }
4055
    }
4056
    // Clean up.
4057
    $dir->close();
4058
4059
    return true;
4060
}
4061
4062
/**
4063
 * @todo: Using DIRECTORY_SEPARATOR is not recommended, this is an obsolete approach.
4064
 * Documentation header to be added here.
4065
 *
4066
 * @param string $pathname
4067
 * @param string $base_path_document
4068
 * @param int    $session_id
4069
 *
4070
 * @return mixed True if directory already exists, false if a file already exists at
4071
 *               the destination and null if everything goes according to plan
4072
 */
4073
function copy_folder_course_session(
4074
    $pathname,
4075
    $base_path_document,
4076
    $session_id,
4077
    $course_info,
4078
    $document,
4079
    $source_course_id
4080
) {
4081
    $table = Database::get_course_table(TABLE_DOCUMENT);
4082
    $session_id = intval($session_id);
4083
    $source_course_id = intval($source_course_id);
4084
4085
    // Check whether directory already exists.
4086
    if (is_dir($pathname) || empty($pathname)) {
4087
        return true;
4088
    }
4089
4090
    // Ensure that a file with the same name does not already exist.
4091
    if (is_file($pathname)) {
4092
        trigger_error('copy_folder_course_session(): File exists', E_USER_WARNING);
4093
4094
        return false;
4095
    }
4096
4097
    $course_id = $course_info['real_id'];
4098
    $folders = explode(DIRECTORY_SEPARATOR, str_replace($base_path_document.DIRECTORY_SEPARATOR, '', $pathname));
4099
    $new_pathname = $base_path_document;
4100
    $path = '';
4101
4102
    foreach ($folders as $folder) {
4103
        $new_pathname .= DIRECTORY_SEPARATOR.$folder;
4104
        $path .= DIRECTORY_SEPARATOR.$folder;
4105
4106
        if (!file_exists($new_pathname)) {
4107
            $path = Database::escape_string($path);
4108
4109
            $sql = "SELECT * FROM $table
4110
                    WHERE
4111
                        c_id = $source_course_id AND
4112
                        path = '$path' AND
4113
                        filetype = 'folder' AND
4114
                        session_id = '$session_id'";
4115
            $rs1 = Database::query($sql);
4116
            $num_rows = Database::num_rows($rs1);
4117
4118
            if (0 == $num_rows) {
4119
                mkdir($new_pathname, api_get_permissions_for_new_directories());
4120
4121
                // Insert new folder with destination session_id.
4122
                $params = [
4123
                    'c_id' => $course_id,
4124
                    'path' => $path,
4125
                    'comment' => $document->comment,
4126
                    'title' => basename($new_pathname),
4127
                    'filetype' => 'folder',
4128
                    'size' => '0',
4129
                    'session_id' => $session_id,
4130
                ];
4131
                Database::insert($table, $params);
4132
            }
4133
        }
4134
    } // en foreach
4135
}
4136
4137
// TODO: chmodr() is a better name. Some corrections are needed. Documentation header to be added here.
4138
/**
4139
 * @param string $path
4140
 */
4141
function api_chmod_R($path, $filemode)
4142
{
4143
    if (!is_dir($path)) {
4144
        return chmod($path, $filemode);
4145
    }
4146
4147
    $handler = opendir($path);
4148
    while ($file = readdir($handler)) {
4149
        if ('.' != $file && '..' != $file) {
4150
            $fullpath = "$path/$file";
4151
            if (!is_dir($fullpath)) {
4152
                if (!chmod($fullpath, $filemode)) {
4153
                    return false;
4154
                }
4155
            } else {
4156
                if (!api_chmod_R($fullpath, $filemode)) {
4157
                    return false;
4158
                }
4159
            }
4160
        }
4161
    }
4162
4163
    closedir($handler);
4164
4165
    return chmod($path, $filemode);
4166
}
4167
4168
// TODO: Where the following function has been copy/pased from? There is no information about author and license. Style, coding conventions...
4169
/**
4170
 * Parse info file format. (e.g: file.info).
4171
 *
4172
 * Files should use an ini-like format to specify values.
4173
 * White-space generally doesn't matter, except inside values.
4174
 * e.g.
4175
 *
4176
 * @verbatim
4177
 *   key = value
4178
 *   key = "value"
4179
 *   key = 'value'
4180
 *   key = "multi-line
4181
 *
4182
 *   value"
4183
 *   key = 'multi-line
4184
 *
4185
 *   value'
4186
 *   key
4187
 *   =
4188
 *   'value'
4189
 * @endverbatim
4190
 *
4191
 * Arrays are created using a GET-like syntax:
4192
 *
4193
 * @verbatim
4194
 *   key[] = "numeric array"
4195
 *   key[index] = "associative array"
4196
 *   key[index][] = "nested numeric array"
4197
 *   key[index][index] = "nested associative array"
4198
 * @endverbatim
4199
 *
4200
 * PHP constants are substituted in, but only when used as the entire value:
4201
 *
4202
 * Comments should start with a semi-colon at the beginning of a line.
4203
 *
4204
 * This function is NOT for placing arbitrary module-specific settings. Use
4205
 * variable_get() and variable_set() for that.
4206
 *
4207
 * Information stored in the module.info file:
4208
 * - name: The real name of the module for display purposes.
4209
 * - description: A brief description of the module.
4210
 * - dependencies: An array of shortnames of other modules this module depends on.
4211
 * - package: The name of the package of modules this module belongs to.
4212
 *
4213
 * Example of .info file:
4214
 * <code>
4215
 * @verbatim
4216
 *   name = Forum
4217
 *   description = Enables threaded discussions about general topics.
4218
 *   dependencies[] = taxonomy
4219
 *   dependencies[] = comment
4220
 *   package = Core - optional
4221
 *   version = VERSION
4222
 * @endverbatim
4223
 * </code>
4224
 *
4225
 * @param string $filename
4226
 *                         The file we are parsing. Accepts file with relative or absolute path.
4227
 *
4228
 * @return
4229
 *   The info array
4230
 */
4231
function api_parse_info_file($filename)
4232
{
4233
    $info = [];
4234
4235
    if (!file_exists($filename)) {
4236
        return $info;
4237
    }
4238
4239
    $data = file_get_contents($filename);
4240
    if (preg_match_all('
4241
        @^\s*                           # Start at the beginning of a line, ignoring leading whitespace
4242
        ((?:
4243
          [^=;\[\]]|                    # Key names cannot contain equal signs, semi-colons or square brackets,
4244
          \[[^\[\]]*\]                  # unless they are balanced and not nested
4245
        )+?)
4246
        \s*=\s*                         # Key/value pairs are separated by equal signs (ignoring white-space)
4247
        (?:
4248
          ("(?:[^"]|(?<=\\\\)")*")|     # Double-quoted string, which may contain slash-escaped quotes/slashes
4249
          (\'(?:[^\']|(?<=\\\\)\')*\')| # Single-quoted string, which may contain slash-escaped quotes/slashes
4250
          ([^\r\n]*?)                   # Non-quoted string
4251
        )\s*$                           # Stop at the next end of a line, ignoring trailing whitespace
4252
        @msx', $data, $matches, PREG_SET_ORDER)) {
4253
        $key = $value1 = $value2 = $value3 = '';
4254
        foreach ($matches as $match) {
4255
            // Fetch the key and value string.
4256
            $i = 0;
4257
            foreach (['key', 'value1', 'value2', 'value3'] as $var) {
4258
                $$var = isset($match[++$i]) ? $match[$i] : '';
4259
            }
4260
            $value = stripslashes(substr($value1, 1, -1)).stripslashes(substr($value2, 1, -1)).$value3;
4261
4262
            // Parse array syntax.
4263
            $keys = preg_split('/\]?\[/', rtrim($key, ']'));
4264
            $last = array_pop($keys);
4265
            $parent = &$info;
4266
4267
            // Create nested arrays.
4268
            foreach ($keys as $key) {
4269
                if ('' == $key) {
4270
                    $key = count($parent);
4271
                }
4272
                if (!isset($parent[$key]) || !is_array($parent[$key])) {
4273
                    $parent[$key] = [];
4274
                }
4275
                $parent = &$parent[$key];
4276
            }
4277
4278
            // Handle PHP constants.
4279
            if (defined($value)) {
4280
                $value = constant($value);
4281
            }
4282
4283
            // Insert actual value.
4284
            if ('' == $last) {
4285
                $last = count($parent);
4286
            }
4287
            $parent[$last] = $value;
4288
        }
4289
    }
4290
4291
    return $info;
4292
}
4293
4294
/**
4295
 * Gets Chamilo version from the configuration files.
4296
 *
4297
 * @return string A string of type "1.8.4", or an empty string if the version could not be found
4298
 */
4299
function api_get_version()
4300
{
4301
    return (string) api_get_configuration_value('system_version');
4302
}
4303
4304
/**
4305
 * Gets the software name (the name/brand of the Chamilo-based customized system).
4306
 *
4307
 * @return string
4308
 */
4309
function api_get_software_name()
4310
{
4311
    $name = api_get_env_variable('SOFTWARE_NAME', 'Chamilo');
4312
    return $name;
4313
}
4314
4315
function api_get_status_list()
4316
{
4317
    $list = [];
4318
    // Table of status
4319
    $list[COURSEMANAGER] = 'teacher'; // 1
4320
    $list[SESSIONADMIN] = 'session_admin'; // 3
4321
    $list[DRH] = 'drh'; // 4
4322
    $list[STUDENT] = 'user'; // 5
4323
    $list[ANONYMOUS] = 'anonymous'; // 6
4324
    $list[INVITEE] = 'invited'; // 20
4325
4326
    return $list;
4327
}
4328
4329
/**
4330
 * Checks whether status given in parameter exists in the platform.
4331
 *
4332
 * @param mixed the status (can be either int either string)
4333
 *
4334
 * @return bool if the status exists, else returns false
4335
 */
4336
function api_status_exists($status_asked)
4337
{
4338
    $list = api_get_status_list();
4339
4340
    return in_array($status_asked, $list) ? true : isset($list[$status_asked]);
4341
}
4342
4343
/**
4344
 * Checks whether status given in parameter exists in the platform. The function
4345
 * returns the status ID or false if it does not exist, but given the fact there
4346
 * is no "0" status, the return value can be checked against
4347
 * if(api_status_key()) to know if it exists.
4348
 *
4349
 * @param   mixed   The status (can be either int or string)
4350
 *
4351
 * @return mixed Status ID if exists, false otherwise
4352
 */
4353
function api_status_key($status)
4354
{
4355
    $list = api_get_status_list();
4356
4357
    return isset($list[$status]) ? $status : array_search($status, $list);
4358
}
4359
4360
/**
4361
 * Gets the status langvars list.
4362
 *
4363
 * @return string[] the list of status with their translations
4364
 */
4365
function api_get_status_langvars()
4366
{
4367
    return [
4368
        COURSEMANAGER => get_lang('Teacher'),
4369
        SESSIONADMIN => get_lang('Sessions administrator'),
4370
        DRH => get_lang('Human Resources Manager'),
4371
        STUDENT => get_lang('Learner'),
4372
        ANONYMOUS => get_lang('Anonymous'),
4373
        STUDENT_BOSS => get_lang('Student boss'),
4374
        INVITEE => get_lang('Invited'),
4375
    ];
4376
}
4377
4378
/**
4379
 * The function that retrieves all the possible settings for a certain config setting.
4380
 *
4381
 * @author Patrick Cool <[email protected]>, Ghent University
4382
 */
4383
function api_get_settings_options($var)
4384
{
4385
    $table_settings_options = Database::get_main_table(TABLE_MAIN_SETTINGS_OPTIONS);
4386
    $var = Database::escape_string($var);
4387
    $sql = "SELECT * FROM $table_settings_options
4388
            WHERE variable = '$var'
4389
            ORDER BY id";
4390
    $result = Database::query($sql);
4391
    $settings_options_array = [];
4392
    while ($row = Database::fetch_assoc($result)) {
4393
        $settings_options_array[] = $row;
4394
    }
4395
4396
    return $settings_options_array;
4397
}
4398
4399
/**
4400
 * @param array $params
4401
 */
4402
function api_set_setting_option($params)
4403
{
4404
    $table = Database::get_main_table(TABLE_MAIN_SETTINGS_OPTIONS);
4405
    if (empty($params['id'])) {
4406
        Database::insert($table, $params);
4407
    } else {
4408
        Database::update($table, $params, ['id = ? ' => $params['id']]);
4409
    }
4410
}
4411
4412
/**
4413
 * @param array $params
4414
 */
4415
function api_set_setting_simple($params)
4416
{
4417
    $table = Database::get_main_table(TABLE_MAIN_SETTINGS);
4418
    $url_id = api_get_current_access_url_id();
4419
4420
    if (empty($params['id'])) {
4421
        $params['access_url'] = $url_id;
4422
        Database::insert($table, $params);
4423
    } else {
4424
        Database::update($table, $params, ['id = ? ' => [$params['id']]]);
4425
    }
4426
}
4427
4428
/**
4429
 * @param int $id
4430
 */
4431
function api_delete_setting_option($id)
4432
{
4433
    $table = Database::get_main_table(TABLE_MAIN_SETTINGS_OPTIONS);
4434
    if (!empty($id)) {
4435
        Database::delete($table, ['id = ? ' => $id]);
4436
    }
4437
}
4438
4439
/**
4440
 * Sets a platform configuration setting to a given value.
4441
 *
4442
 * @param string    The variable we want to update
4443
 * @param string    The value we want to record
4444
 * @param string    The sub-variable if any (in most cases, this will remain null)
4445
 * @param string    The category if any (in most cases, this will remain null)
4446
 * @param int       The access_url for which this parameter is valid
4447
 * @param string $cat
4448
 *
4449
 * @return bool|null
4450
 */
4451
function api_set_setting($var, $value, $subvar = null, $cat = null, $access_url = 1)
4452
{
4453
    if (empty($var)) {
4454
        return false;
4455
    }
4456
    $t_settings = Database::get_main_table(TABLE_MAIN_SETTINGS);
4457
    $var = Database::escape_string($var);
4458
    $value = Database::escape_string($value);
4459
    $access_url = (int) $access_url;
4460
    if (empty($access_url)) {
4461
        $access_url = 1;
4462
    }
4463
    $select = "SELECT id FROM $t_settings WHERE variable = '$var' ";
4464
    if (!empty($subvar)) {
4465
        $subvar = Database::escape_string($subvar);
4466
        $select .= " AND subkey = '$subvar'";
4467
    }
4468
    if (!empty($cat)) {
4469
        $cat = Database::escape_string($cat);
4470
        $select .= " AND category = '$cat'";
4471
    }
4472
    if ($access_url > 1) {
4473
        $select .= " AND access_url = $access_url";
4474
    } else {
4475
        $select .= " AND access_url = 1 ";
4476
    }
4477
4478
    $res = Database::query($select);
4479
    if (Database::num_rows($res) > 0) {
4480
        // Found item for this access_url.
4481
        $row = Database::fetch_array($res);
4482
        $sql = "UPDATE $t_settings SET selected_value = '$value'
4483
                WHERE id = ".$row['id'];
4484
        Database::query($sql);
4485
    } else {
4486
        // Item not found for this access_url, we have to check if it exist with access_url = 1
4487
        $select = "SELECT * FROM $t_settings
4488
                   WHERE variable = '$var' AND access_url = 1 ";
4489
        // Just in case
4490
        if (1 == $access_url) {
4491
            if (!empty($subvar)) {
4492
                $select .= " AND subkey = '$subvar'";
4493
            }
4494
            if (!empty($cat)) {
4495
                $select .= " AND category = '$cat'";
4496
            }
4497
            $res = Database::query($select);
4498
            if (Database::num_rows($res) > 0) {
4499
                // We have a setting for access_url 1, but none for the current one, so create one.
4500
                $row = Database::fetch_array($res);
4501
                $insert = "INSERT INTO $t_settings (variable, subkey, type,category, selected_value, title, comment, scope, subkeytext, access_url)
4502
                        VALUES
4503
                        ('".$row['variable']."',".(!empty($row['subkey']) ? "'".$row['subkey']."'" : "NULL").",".
4504
                    "'".$row['type']."','".$row['category']."',".
4505
                    "'$value','".$row['title']."',".
4506
                    "".(!empty($row['comment']) ? "'".$row['comment']."'" : "NULL").",".(!empty($row['scope']) ? "'".$row['scope']."'" : "NULL").",".
4507
                    "".(!empty($row['subkeytext']) ? "'".$row['subkeytext']."'" : "NULL").",$access_url)";
4508
                Database::query($insert);
4509
            } else {
4510
                // Such a setting does not exist.
4511
                //error_log(__FILE__.':'.__LINE__.': Attempting to update setting '.$var.' ('.$subvar.') which does not exist at all', 0);
4512
            }
4513
        } else {
4514
            // Other access url.
4515
            if (!empty($subvar)) {
4516
                $select .= " AND subkey = '$subvar'";
4517
            }
4518
            if (!empty($cat)) {
4519
                $select .= " AND category = '$cat'";
4520
            }
4521
            $res = Database::query($select);
4522
4523
            if (Database::num_rows($res) > 0) {
4524
                // We have a setting for access_url 1, but none for the current one, so create one.
4525
                $row = Database::fetch_array($res);
4526
                if (1 == $row['access_url_changeable']) {
4527
                    $insert = "INSERT INTO $t_settings (variable,subkey, type,category, selected_value,title, comment,scope, subkeytext,access_url, access_url_changeable) VALUES
4528
                            ('".$row['variable']."',".
4529
                        (!empty($row['subkey']) ? "'".$row['subkey']."'" : "NULL").",".
4530
                        "'".$row['type']."','".$row['category']."',".
4531
                        "'$value','".$row['title']."',".
4532
                        "".(!empty($row['comment']) ? "'".$row['comment']."'" : "NULL").",".
4533
                        (!empty($row['scope']) ? "'".$row['scope']."'" : "NULL").",".
4534
                        "".(!empty($row['subkeytext']) ? "'".$row['subkeytext']."'" : "NULL").",$access_url,".$row['access_url_changeable'].")";
4535
                    Database::query($insert);
4536
                }
4537
            } else { // Such a setting does not exist.
4538
                //error_log(__FILE__.':'.__LINE__.': Attempting to update setting '.$var.' ('.$subvar.') which does not exist at all. The access_url is: '.$access_url.' ',0);
4539
            }
4540
        }
4541
    }
4542
}
4543
4544
/**
4545
 * Sets a whole category of settings to one specific value.
4546
 *
4547
 * @param string    Category
4548
 * @param string    Value
4549
 * @param int       Access URL. Optional. Defaults to 1
4550
 * @param array     Optional array of filters on field type
4551
 * @param string $category
4552
 * @param string $value
4553
 *
4554
 * @return bool
4555
 */
4556
function api_set_settings_category($category, $value = null, $access_url = 1, $fieldtype = [])
4557
{
4558
    if (empty($category)) {
4559
        return false;
4560
    }
4561
    $category = Database::escape_string($category);
4562
    $t_s = Database::get_main_table(TABLE_MAIN_SETTINGS);
4563
    $access_url = (int) $access_url;
4564
    if (empty($access_url)) {
4565
        $access_url = 1;
4566
    }
4567
    if (isset($value)) {
4568
        $value = Database::escape_string($value);
4569
        $sql = "UPDATE $t_s SET selected_value = '$value'
4570
                WHERE category = '$category' AND access_url = $access_url";
4571
        if (is_array($fieldtype) && count($fieldtype) > 0) {
4572
            $sql .= " AND ( ";
4573
            $i = 0;
4574
            foreach ($fieldtype as $type) {
4575
                if ($i > 0) {
4576
                    $sql .= ' OR ';
4577
                }
4578
                $type = Database::escape_string($type);
4579
                $sql .= " type='".$type."' ";
4580
                $i++;
4581
            }
4582
            $sql .= ")";
4583
        }
4584
        $res = Database::query($sql);
4585
4586
        return false !== $res;
4587
    } else {
4588
        $sql = "UPDATE $t_s SET selected_value = NULL
4589
                WHERE category = '$category' AND access_url = $access_url";
4590
        if (is_array($fieldtype) && count($fieldtype) > 0) {
4591
            $sql .= " AND ( ";
4592
            $i = 0;
4593
            foreach ($fieldtype as $type) {
4594
                if ($i > 0) {
4595
                    $sql .= ' OR ';
4596
                }
4597
                $type = Database::escape_string($type);
4598
                $sql .= " type='".$type."' ";
4599
                $i++;
4600
            }
4601
            $sql .= ")";
4602
        }
4603
        $res = Database::query($sql);
4604
4605
        return false !== $res;
4606
    }
4607
}
4608
4609
/**
4610
 * Gets all available access urls in an array (as in the database).
4611
 *
4612
 * @return array An array of database records
4613
 */
4614
function api_get_access_urls($from = 0, $to = 1000000, $order = 'url', $direction = 'ASC')
4615
{
4616
    $table = Database::get_main_table(TABLE_MAIN_ACCESS_URL);
4617
    $from = (int) $from;
4618
    $to = (int) $to;
4619
    $order = Database::escape_string($order);
4620
    $direction = Database::escape_string($direction);
4621
    $direction = !in_array(strtolower(trim($direction)), ['asc', 'desc']) ? 'asc' : $direction;
4622
    $sql = "SELECT id, url, description, active, created_by, tms
4623
            FROM $table
4624
            ORDER BY `$order` $direction
4625
            LIMIT $to OFFSET $from";
4626
    $res = Database::query($sql);
4627
4628
    return Database::store_result($res);
4629
}
4630
4631
/**
4632
 * Gets the access url info in an array.
4633
 *
4634
 * @param int  $id            Id of the access url
4635
 * @param bool $returnDefault Set to false if you want the real URL if URL 1 is still 'http://localhost/'
4636
 *
4637
 * @return array All the info (url, description, active, created_by, tms)
4638
 *               from the access_url table
4639
 *
4640
 * @author Julio Montoya
4641
 */
4642
function api_get_access_url($id, $returnDefault = true)
4643
{
4644
    static $staticResult;
4645
    $id = (int) $id;
4646
4647
    if (isset($staticResult[$id])) {
4648
        $result = $staticResult[$id];
4649
    } else {
4650
        // Calling the Database:: library dont work this is handmade.
4651
        $table_access_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL);
4652
        $sql = "SELECT url, description, active, created_by, tms
4653
                FROM $table_access_url WHERE id = '$id' ";
4654
        $res = Database::query($sql);
4655
        $result = @Database::fetch_array($res);
4656
        $staticResult[$id] = $result;
4657
    }
4658
4659
    // If the result url is 'http://localhost/' (the default) and the root_web
4660
    // (=current url) is different, and the $id is = 1 (which might mean
4661
    // api_get_current_access_url_id() returned 1 by default), then return the
4662
    // root_web setting instead of the current URL
4663
    // This is provided as an option to avoid breaking the storage of URL-specific
4664
    // homepages in home/localhost/
4665
    if (1 === $id && false === $returnDefault) {
4666
        $currentUrl = api_get_current_access_url_id();
4667
        // only do this if we are on the main URL (=1), otherwise we could get
4668
        // information on another URL instead of the one asked as parameter
4669
        if (1 === $currentUrl) {
4670
            $rootWeb = api_get_path(WEB_PATH);
4671
            $default = AccessUrl::DEFAULT_ACCESS_URL;
4672
            if ($result['url'] === $default && $rootWeb != $default) {
4673
                $result['url'] = $rootWeb;
4674
            }
4675
        }
4676
    }
4677
4678
    return $result;
4679
}
4680
4681
/**
4682
 * Gets all the current settings for a specific access url.
4683
 *
4684
 * @param string    The category, if any, that we want to get
4685
 * @param string    Whether we want a simple list (display a category) or
4686
 * a grouped list (group by variable as in settings.php default). Values: 'list' or 'group'
4687
 * @param int       Access URL's ID. Optional. Uses 1 by default, which is the unique URL
4688
 *
4689
 * @return array Array of database results for the current settings of the current access URL
4690
 */
4691
function &api_get_settings($cat = null, $ordering = 'list', $access_url = 1, $url_changeable = 0)
4692
{
4693
    $table = Database::get_main_table(TABLE_MAIN_SETTINGS);
4694
    $access_url = (int) $access_url;
4695
    $where_condition = '';
4696
    if (1 == $url_changeable) {
4697
        $where_condition = " AND access_url_changeable= '1' ";
4698
    }
4699
    if (empty($access_url) || -1 == $access_url) {
4700
        $access_url = 1;
4701
    }
4702
    $sql = "SELECT * FROM $table
4703
            WHERE access_url = $access_url  $where_condition ";
4704
4705
    if (!empty($cat)) {
4706
        $cat = Database::escape_string($cat);
4707
        $sql .= " AND category='$cat' ";
4708
    }
4709
    if ('group' == $ordering) {
4710
        $sql .= " ORDER BY id ASC";
4711
    } else {
4712
        $sql .= " ORDER BY 1,2 ASC";
4713
    }
4714
    $result = Database::query($sql);
4715
    if (null === $result) {
4716
        $result = [];
4717
        return $result;
4718
    }
4719
    $result = Database::store_result($result, 'ASSOC');
4720
4721
    return $result;
4722
}
4723
4724
/**
4725
 * @param string $value       The value we want to record
4726
 * @param string $variable    The variable name we want to insert
4727
 * @param string $subKey      The subkey for the variable we want to insert
4728
 * @param string $type        The type for the variable we want to insert
4729
 * @param string $category    The category for the variable we want to insert
4730
 * @param string $title       The title
4731
 * @param string $comment     The comment
4732
 * @param string $scope       The scope
4733
 * @param string $subKeyText  The subkey text
4734
 * @param int    $accessUrlId The access_url for which this parameter is valid
4735
 * @param int    $visibility  The changeability of this setting for non-master urls
4736
 *
4737
 * @return int The setting ID
4738
 */
4739
function api_add_setting(
4740
    $value,
4741
    $variable,
4742
    $subKey = '',
4743
    $type = 'textfield',
4744
    $category = '',
4745
    $title = '',
4746
    $comment = '',
4747
    $scope = '',
4748
    $subKeyText = '',
4749
    $accessUrlId = 1,
4750
    $visibility = 0
4751
) {
4752
    $em = Database::getManager();
4753
4754
    $settingRepo = $em->getRepository(SettingsCurrent::class);
4755
    $accessUrlId = (int) $accessUrlId ?: 1;
4756
4757
    if (is_array($value)) {
4758
        $value = serialize($value);
4759
    } else {
4760
        $value = trim($value);
4761
    }
4762
4763
    $criteria = ['variable' => $variable, 'url' => $accessUrlId];
4764
4765
    if (!empty($subKey)) {
4766
        $criteria['subkey'] = $subKey;
4767
    }
4768
4769
    // Check if this variable doesn't exist already
4770
    /** @var SettingsCurrent $setting */
4771
    $setting = $settingRepo->findOneBy($criteria);
4772
4773
    if ($setting) {
0 ignored issues
show
introduced by
$setting is of type Chamilo\CoreBundle\Entity\SettingsCurrent, thus it always evaluated to true.
Loading history...
4774
        $setting->setSelectedValue($value);
4775
4776
        $em->persist($setting);
4777
        $em->flush();
4778
4779
        return $setting->getId();
4780
    }
4781
4782
    // Item not found for this access_url, we have to check if the whole thing is missing
4783
    // (in which case we ignore the insert) or if there *is* a record but just for access_url = 1
4784
    $setting = new SettingsCurrent();
4785
    $url = api_get_url_entity();
4786
4787
    $setting
4788
        ->setVariable($variable)
4789
        ->setSelectedValue($value)
4790
        ->setType($type)
4791
        ->setCategory($category)
4792
        ->setSubkey($subKey)
4793
        ->setTitle($title)
4794
        ->setComment($comment)
4795
        ->setScope($scope)
4796
        ->setSubkeytext($subKeyText)
4797
        ->setUrl(api_get_url_entity())
4798
        ->setAccessUrlChangeable($visibility);
4799
4800
    $em->persist($setting);
4801
    $em->flush();
4802
4803
    return $setting->getId();
4804
}
4805
4806
/**
4807
 * Checks wether a user can or can't view the contents of a course.
4808
 *
4809
 * @deprecated use CourseManager::is_user_subscribed_in_course
4810
 *
4811
 * @param int $userid User id or NULL to get it from $_SESSION
4812
 * @param int $cid    course id to check whether the user is allowed
4813
 *
4814
 * @return bool
4815
 */
4816
function api_is_course_visible_for_user($userid = null, $cid = null)
4817
{
4818
    if (null === $userid) {
4819
        $userid = api_get_user_id();
4820
    }
4821
    if (empty($userid) || strval(intval($userid)) != $userid) {
4822
        if (api_is_anonymous()) {
4823
            $userid = api_get_anonymous_id();
4824
        } else {
4825
            return false;
4826
        }
4827
    }
4828
    $cid = Database::escape_string($cid);
4829
4830
    $courseInfo = api_get_course_info($cid);
4831
    $courseId = $courseInfo['real_id'];
4832
    $is_platformAdmin = api_is_platform_admin();
4833
4834
    $course_table = Database::get_main_table(TABLE_MAIN_COURSE);
4835
    $course_cat_table = Database::get_main_table(TABLE_MAIN_CATEGORY);
4836
4837
    $sql = "SELECT
4838
                $course_cat_table.code AS category_code,
4839
                $course_table.visibility,
4840
                $course_table.code,
4841
                $course_cat_table.code
4842
            FROM $course_table
4843
            LEFT JOIN $course_cat_table
4844
                ON $course_table.category_id = $course_cat_table.id
4845
            WHERE
4846
                $course_table.code = '$cid'
4847
            LIMIT 1";
4848
4849
    $result = Database::query($sql);
4850
4851
    if (Database::num_rows($result) > 0) {
4852
        $visibility = Database::fetch_array($result);
4853
        $visibility = $visibility['visibility'];
4854
    } else {
4855
        $visibility = 0;
4856
    }
4857
    // Shortcut permissions in case the visibility is "open to the world".
4858
    if (COURSE_VISIBILITY_OPEN_WORLD === $visibility) {
4859
        return true;
4860
    }
4861
4862
    $tbl_course_user = Database::get_main_table(TABLE_MAIN_COURSE_USER);
4863
4864
    $sql = "SELECT
4865
                is_tutor, status
4866
            FROM $tbl_course_user
4867
            WHERE
4868
                user_id  = '$userid' AND
4869
                relation_type <> '".COURSE_RELATION_TYPE_RRHH."' AND
4870
                c_id = $courseId
4871
            LIMIT 1";
4872
4873
    $result = Database::query($sql);
4874
4875
    if (Database::num_rows($result) > 0) {
4876
        // This user has got a recorded state for this course.
4877
        $cuData = Database::fetch_array($result);
4878
        $is_courseMember = true;
4879
        $is_courseAdmin = (1 == $cuData['status']);
4880
    }
4881
4882
    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...
4883
        // This user has no status related to this course.
4884
        // Is it the session coach or the session admin?
4885
        $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
4886
        $tbl_session_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
4887
        $tblSessionRelUser = Database::get_main_table(TABLE_MAIN_SESSION_USER);
4888
        $tbl_session_course_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
4889
4890
        $sql = "SELECT sru_2.user_id AS session_admin_id, sru_1.user_id AS session_coach_id
4891
                FROM $tbl_session AS s
4892
                INNER JOIN $tblSessionRelUser sru_1
4893
                ON (sru_1.session_id = s.id AND sru_1.relation_type = ".SessionEntity::GENERAL_COACH.")
4894
                INNER JOIN $tblSessionRelUser sru_2
4895
                ON (sru_2.session_id = s.id AND sru_2.relation_type = ".SessionEntity::SESSION_ADMIN.")
4896
                INNER JOIN $tbl_session_course src
4897
                ON (src.session_id = s.id AND src.c_id = $courseId)";
4898
4899
        $result = Database::query($sql);
4900
        $row = Database::store_result($result);
4901
        $sessionAdminsId = array_column($row, 'session_admin_id');
4902
        $sessionCoachesId = array_column($row, 'session_coach_id');
4903
4904
        if (in_array($userid, $sessionCoachesId)) {
4905
            $is_courseMember = true;
4906
            $is_courseAdmin = false;
4907
        } elseif (in_array($userid, $sessionAdminsId)) {
4908
            $is_courseMember = false;
4909
            $is_courseAdmin = false;
4910
        } else {
4911
            // Check if the current user is the course coach.
4912
            $sql = "SELECT 1
4913
                    FROM $tbl_session_course
4914
                    WHERE session_rel_course.c_id = '$courseId'
4915
                    AND session_rel_course.id_coach = '$userid'
4916
                    LIMIT 1";
4917
4918
            $result = Database::query($sql);
4919
4920
            //if ($row = Database::fetch_array($result)) {
4921
            if (Database::num_rows($result) > 0) {
4922
                $is_courseMember = true;
4923
                $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
4924
4925
                $sql = "SELECT status FROM $tbl_user
4926
                        WHERE id = $userid
4927
                        LIMIT 1";
4928
4929
                $result = Database::query($sql);
4930
4931
                if (1 == Database::result($result, 0, 0)) {
4932
                    $is_courseAdmin = true;
4933
                } else {
4934
                    $is_courseAdmin = false;
4935
                }
4936
            } else {
4937
                // Check if the user is a student is this session.
4938
                $sql = "SELECT  id
4939
                        FROM $tbl_session_course_user
4940
                        WHERE
4941
                            user_id  = '$userid' AND
4942
                            c_id = '$courseId'
4943
                        LIMIT 1";
4944
4945
                if (Database::num_rows($result) > 0) {
4946
                    // This user haa got a recorded state for this course.
4947
                    while ($row = Database::fetch_array($result)) {
4948
                        $is_courseMember = true;
4949
                        $is_courseAdmin = false;
4950
                    }
4951
                }
4952
            }
4953
        }
4954
    }
4955
4956
    switch ($visibility) {
4957
        case Course::OPEN_WORLD:
4958
            return true;
4959
        case Course::OPEN_PLATFORM:
4960
            return isset($userid);
4961
        case Course::REGISTERED:
4962
        case Course::CLOSED:
4963
            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...
4964
        case Course::HIDDEN:
4965
            return $is_platformAdmin;
4966
    }
4967
4968
    return false;
4969
}
4970
4971
/**
4972
 * Returns whether an element (forum, message, survey ...) belongs to a session or not.
4973
 *
4974
 * @param string the tool of the element
4975
 * @param int the element id in database
4976
 * @param int the session_id to compare with element session id
4977
 *
4978
 * @return bool true if the element is in the session, false else
4979
 */
4980
function api_is_element_in_the_session($tool, $element_id, $session_id = null)
4981
{
4982
    if (is_null($session_id)) {
4983
        $session_id = api_get_session_id();
4984
    }
4985
4986
    $element_id = (int) $element_id;
4987
4988
    if (empty($element_id)) {
4989
        return false;
4990
    }
4991
4992
    // Get information to build query depending of the tool.
4993
    switch ($tool) {
4994
        case TOOL_SURVEY:
4995
            $table_tool = Database::get_course_table(TABLE_SURVEY);
4996
            $key_field = 'survey_id';
4997
            break;
4998
        case TOOL_ANNOUNCEMENT:
4999
            $table_tool = Database::get_course_table(TABLE_ANNOUNCEMENT);
5000
            $key_field = 'id';
5001
            break;
5002
        case TOOL_AGENDA:
5003
            $table_tool = Database::get_course_table(TABLE_AGENDA);
5004
            $key_field = 'id';
5005
            break;
5006
        case TOOL_GROUP:
5007
            $table_tool = Database::get_course_table(TABLE_GROUP);
5008
            $key_field = 'id';
5009
            break;
5010
        default:
5011
            return false;
5012
    }
5013
    $course_id = api_get_course_int_id();
5014
5015
    $sql = "SELECT session_id FROM $table_tool
5016
            WHERE c_id = $course_id AND $key_field =  ".$element_id;
5017
    $rs = Database::query($sql);
5018
    if ($element_session_id = Database::result($rs, 0, 0)) {
5019
        if ($element_session_id == intval($session_id)) {
5020
            // The element belongs to the session.
5021
            return true;
5022
        }
5023
    }
5024
5025
    return false;
5026
}
5027
5028
/**
5029
 * Replaces "forbidden" characters in a filename string.
5030
 *
5031
 * @param string $filename
5032
 * @param bool   $treat_spaces_as_hyphens
5033
 *
5034
 * @return string
5035
 */
5036
function api_replace_dangerous_char($filename, $treat_spaces_as_hyphens = true)
5037
{
5038
    // Some non-properly encoded file names can cause the whole file to be
5039
    // skipped when uploaded. Avoid this by detecting the encoding and
5040
    // converting to UTF-8, setting the source as ASCII (a reasonably
5041
    // limited characters set) if nothing could be found (BT#
5042
    $encoding = api_detect_encoding($filename);
5043
    if (empty($encoding)) {
5044
        $encoding = 'ASCII';
5045
        if (!api_is_valid_ascii($filename)) {
5046
            // try iconv and try non standard ASCII a.k.a CP437
5047
            // see BT#15022
5048
            if (function_exists('iconv')) {
5049
                $result = iconv('CP437', 'UTF-8', $filename);
5050
                if (api_is_valid_utf8($result)) {
5051
                    $filename = $result;
5052
                    $encoding = 'UTF-8';
5053
                }
5054
            }
5055
        }
5056
    }
5057
5058
    $filename = api_to_system_encoding($filename, $encoding);
5059
5060
    $url = URLify::filter(
5061
        $filename,
5062
        250,
5063
        '',
5064
        true,
5065
        false,
5066
        false
5067
    );
5068
5069
    // Replace multiple dots at the end.
5070
    $regex = "/\.+$/";
5071
5072
    return preg_replace($regex, '', $url);
5073
}
5074
5075
/**
5076
 * Fixes the $_SERVER['REQUEST_URI'] that is empty in IIS6.
5077
 *
5078
 * @author Ivan Tcholakov, 28-JUN-2006.
5079
 */
5080
function api_request_uri()
5081
{
5082
    if (!empty($_SERVER['REQUEST_URI'])) {
5083
        return $_SERVER['REQUEST_URI'];
5084
    }
5085
    $uri = $_SERVER['SCRIPT_NAME'];
5086
    if (!empty($_SERVER['QUERY_STRING'])) {
5087
        $uri .= '?'.$_SERVER['QUERY_STRING'];
5088
    }
5089
    $_SERVER['REQUEST_URI'] = $uri;
5090
5091
    return $uri;
5092
}
5093
5094
/**
5095
 * Gets the current access_url id of the Chamilo Platform.
5096
 *
5097
 * @return int access_url_id of the current Chamilo Installation
5098
 *
5099
 * @author Julio Montoya <[email protected]>
5100
 * @throws Exception
5101
 */
5102
function api_get_current_access_url_id(): int
5103
{
5104
    if (false === api_get_multiple_access_url()) {
5105
        return 1;
5106
    }
5107
5108
    static $id;
5109
    if (!empty($id)) {
5110
        return $id;
5111
    }
5112
5113
    $table = Database::get_main_table(TABLE_MAIN_ACCESS_URL);
5114
    $path = Database::escape_string(api_get_path(WEB_PATH));
5115
    $sql = "SELECT id FROM $table WHERE url = '".$path."'";
5116
    $result = Database::query($sql);
5117
    if (Database::num_rows($result) > 0) {
5118
        $id = Database::result($result, 0, 0);
5119
        if (false === $id) {
5120
            return -1;
5121
        }
5122
5123
        return (int) $id;
5124
    }
5125
5126
    $id = 1;
5127
5128
    //if the url in WEB_PATH was not found, it can only mean that there is
5129
    // either a configuration problem or the first URL has not been defined yet
5130
    // (by default it is http://localhost/). Thus the more sensible thing we can
5131
    // do is return 1 (the main URL) as the user cannot hack this value anyway
5132
    return 1;
5133
}
5134
5135
/**
5136
 * Gets the registered urls from a given user id.
5137
 *
5138
 * @author Julio Montoya <[email protected]>
5139
 *
5140
 * @param int $user_id
5141
 *
5142
 * @return array
5143
 */
5144
function api_get_access_url_from_user($user_id)
5145
{
5146
    $user_id = (int) $user_id;
5147
    $table_url_rel_user = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
5148
    $table_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL);
5149
    $sql = "SELECT access_url_id
5150
            FROM $table_url_rel_user url_rel_user
5151
            INNER JOIN $table_url u
5152
            ON (url_rel_user.access_url_id = u.id)
5153
            WHERE user_id = ".$user_id;
5154
    $result = Database::query($sql);
5155
    $list = [];
5156
    while ($row = Database::fetch_assoc($result)) {
5157
        $list[] = $row['access_url_id'];
5158
    }
5159
5160
    return $list;
5161
}
5162
5163
/**
5164
 * Checks whether the curent user is in a group or not.
5165
 *
5166
 * @param string        The group id - optional (takes it from session if not given)
5167
 * @param string        The course code - optional (no additional check by course if course code is not given)
5168
 *
5169
 * @return bool
5170
 *
5171
 * @author Ivan Tcholakov
5172
 */
5173
function api_is_in_group($groupIdParam = null, $courseCodeParam = null)
5174
{
5175
    if (!empty($courseCodeParam)) {
5176
        $courseCode = api_get_course_id();
5177
        if (!empty($courseCode)) {
5178
            if ($courseCodeParam != $courseCode) {
5179
                return false;
5180
            }
5181
        } else {
5182
            return false;
5183
        }
5184
    }
5185
5186
    $groupId = api_get_group_id();
5187
5188
    if (isset($groupId) && '' != $groupId) {
5189
        if (!empty($groupIdParam)) {
5190
            return $groupIdParam == $groupId;
5191
        } else {
5192
            return true;
5193
        }
5194
    }
5195
5196
    return false;
5197
}
5198
5199
/**
5200
 * Checks whether a secret key is valid.
5201
 *
5202
 * @param string $original_key_secret - secret key from (webservice) client
5203
 * @param string $security_key        - security key from Chamilo
5204
 *
5205
 * @return bool - true if secret key is valid, false otherwise
5206
 */
5207
function api_is_valid_secret_key($original_key_secret, $security_key)
5208
{
5209
    if (empty($original_key_secret) || empty($security_key)) {
5210
        return false;
5211
    }
5212
5213
    return (string) $original_key_secret === hash('sha512', $security_key);
5214
}
5215
5216
/**
5217
 * Checks whether the server's operating system is Windows (TM).
5218
 *
5219
 * @return bool - true if the operating system is Windows, false otherwise
5220
 */
5221
function api_is_windows_os()
5222
{
5223
    if (function_exists('php_uname')) {
5224
        // php_uname() exists as of PHP 4.0.2, according to the documentation.
5225
        // We expect that this function will always work for Chamilo 1.8.x.
5226
        $os = php_uname();
5227
    }
5228
    // The following methods are not needed, but let them stay, just in case.
5229
    elseif (isset($_ENV['OS'])) {
5230
        // Sometimes $_ENV['OS'] may not be present (bugs?)
5231
        $os = $_ENV['OS'];
5232
    } elseif (defined('PHP_OS')) {
5233
        // PHP_OS means on which OS PHP was compiled, this is why
5234
        // using PHP_OS is the last choice for detection.
5235
        $os = PHP_OS;
5236
    } else {
5237
        return false;
5238
    }
5239
5240
    return 'win' == strtolower(substr((string) $os, 0, 3));
5241
}
5242
5243
/**
5244
 * This function informs whether the sent request is XMLHttpRequest.
5245
 */
5246
function api_is_xml_http_request()
5247
{
5248
    return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && 'xmlhttprequest' == strtolower($_SERVER['HTTP_X_REQUESTED_WITH']);
5249
}
5250
5251
/**
5252
 * Returns a list of Chamilo's tools or
5253
 * checks whether a given identificator is a valid Chamilo's tool.
5254
 *
5255
 * @author Isaac flores paz
5256
 *
5257
 * @param string The tool name to filter
5258
 *
5259
 * @return mixed Filtered string or array
5260
 */
5261
function api_get_tools_lists($my_tool = null)
5262
{
5263
    $tools_list = [
5264
        TOOL_DOCUMENT,
5265
        TOOL_THUMBNAIL,
5266
        TOOL_HOTPOTATOES,
5267
        TOOL_CALENDAR_EVENT,
5268
        TOOL_LINK,
5269
        TOOL_COURSE_DESCRIPTION,
5270
        TOOL_SEARCH,
5271
        TOOL_LEARNPATH,
5272
        TOOL_ANNOUNCEMENT,
5273
        TOOL_FORUM,
5274
        TOOL_THREAD,
5275
        TOOL_POST,
5276
        TOOL_DROPBOX,
5277
        TOOL_QUIZ,
5278
        TOOL_USER,
5279
        TOOL_GROUP,
5280
        TOOL_BLOGS,
5281
        TOOL_CHAT,
5282
        TOOL_STUDENTPUBLICATION,
5283
        TOOL_TRACKING,
5284
        TOOL_HOMEPAGE_LINK,
5285
        TOOL_COURSE_SETTING,
5286
        TOOL_BACKUP,
5287
        TOOL_COPY_COURSE_CONTENT,
5288
        TOOL_RECYCLE_COURSE,
5289
        TOOL_COURSE_HOMEPAGE,
5290
        TOOL_COURSE_RIGHTS_OVERVIEW,
5291
        TOOL_UPLOAD,
5292
        TOOL_COURSE_MAINTENANCE,
5293
        TOOL_SURVEY,
5294
        //TOOL_WIKI,
5295
        TOOL_GLOSSARY,
5296
        TOOL_GRADEBOOK,
5297
        TOOL_NOTEBOOK,
5298
        TOOL_ATTENDANCE,
5299
        TOOL_COURSE_PROGRESS,
5300
    ];
5301
    if (empty($my_tool)) {
5302
        return $tools_list;
5303
    }
5304
5305
    return in_array($my_tool, $tools_list) ? $my_tool : '';
5306
}
5307
5308
/**
5309
 * Checks whether we already approved the last version term and condition.
5310
 *
5311
 * @param int user id
5312
 *
5313
 * @return bool true if we pass false otherwise
5314
 */
5315
function api_check_term_condition($userId)
5316
{
5317
    if ('true' === api_get_setting('allow_terms_conditions')) {
5318
        // Check if exists terms and conditions
5319
        if (0 == LegalManager::count()) {
5320
            return true;
5321
        }
5322
5323
        $extraFieldValue = new ExtraFieldValue('user');
5324
        $data = $extraFieldValue->get_values_by_handler_and_field_variable(
5325
            $userId,
5326
            'legal_accept'
5327
        );
5328
5329
        if (!empty($data) && isset($data['value']) && !empty($data['value'])) {
5330
            $result = $data['value'];
5331
            $user_conditions = explode(':', $result);
5332
            $version = $user_conditions[0];
5333
            $langId = $user_conditions[1];
5334
            $realVersion = LegalManager::get_last_version($langId);
5335
5336
            return $version >= $realVersion;
5337
        }
5338
5339
        return false;
5340
    }
5341
5342
    return false;
5343
}
5344
5345
/**
5346
 * Gets all information of a tool into course.
5347
 *
5348
 * @param int The tool id
5349
 *
5350
 * @return array
5351
 */
5352
function api_get_tool_information_by_name($name)
5353
{
5354
    $t_tool = Database::get_course_table(TABLE_TOOL_LIST);
5355
    $course_id = api_get_course_int_id();
5356
5357
    $sql = "SELECT id FROM tool
5358
            WHERE title = '".Database::escape_string($name)."' ";
5359
    $rs = Database::query($sql);
5360
    $data = Database::fetch_array($rs);
5361
    if ($data) {
5362
        $tool = $data['id'];
5363
        $sql = "SELECT * FROM $t_tool
5364
                WHERE c_id = $course_id  AND tool_id = '".$tool."' ";
5365
        $rs = Database::query($sql);
5366
5367
        return Database::fetch_assoc($rs);
0 ignored issues
show
Bug Best Practice introduced by
The expression return Database::fetch_assoc($rs) also could return the type boolean which is incompatible with the documented return type array.
Loading history...
5368
    }
5369
5370
    return [];
5371
}
5372
5373
/**
5374
 * Function used to protect a "global" admin script.
5375
 * The function blocks access when the user has no global platform admin rights.
5376
 * Global admins are the admins that are registered in the main.admin table
5377
 * AND the users who have access to the "principal" portal.
5378
 * That means that there is a record in the main.access_url_rel_user table
5379
 * with his user id and the access_url_id=1.
5380
 *
5381
 * @author Julio Montoya
5382
 *
5383
 * @param int $user_id
5384
 *
5385
 * @return bool
5386
 */
5387
function api_is_global_platform_admin($user_id = null)
5388
{
5389
    $user_id = (int) $user_id;
5390
    if (empty($user_id)) {
5391
        $user_id = api_get_user_id();
5392
    }
5393
    if (api_is_platform_admin_by_id($user_id)) {
5394
        $urlList = api_get_access_url_from_user($user_id);
5395
        // The admin is registered in the first "main" site with access_url_id = 1
5396
        if (in_array(1, $urlList)) {
5397
            return true;
5398
        }
5399
    }
5400
5401
    return false;
5402
}
5403
5404
/**
5405
 * @param int  $admin_id_to_check
5406
 * @param int  $userId
5407
 * @param bool $allow_session_admin
5408
 *
5409
 * @return bool
5410
 */
5411
function api_global_admin_can_edit_admin(
5412
    $admin_id_to_check,
5413
    $userId = 0,
5414
    $allow_session_admin = false
5415
) {
5416
    if (empty($userId)) {
5417
        $userId = api_get_user_id();
5418
    }
5419
5420
    $iam_a_global_admin = api_is_global_platform_admin($userId);
5421
    $user_is_global_admin = api_is_global_platform_admin($admin_id_to_check);
5422
5423
    if ($iam_a_global_admin) {
5424
        // Global admin can edit everything
5425
        return true;
5426
    }
5427
5428
    // If i'm a simple admin
5429
    $is_platform_admin = api_is_platform_admin_by_id($userId);
5430
5431
    if ($allow_session_admin && !$is_platform_admin) {
5432
        $user = api_get_user_entity($userId);
5433
        $is_platform_admin = $user->hasRole('ROLE_SESSION_MANAGER');
5434
    }
5435
5436
    if ($is_platform_admin) {
5437
        if ($user_is_global_admin) {
5438
            return false;
5439
        } else {
5440
            return true;
5441
        }
5442
    }
5443
5444
    return false;
5445
}
5446
5447
/**
5448
 * @param int  $admin_id_to_check
5449
 * @param int  $userId
5450
 * @param bool $allow_session_admin
5451
 *
5452
 * @return bool|null
5453
 */
5454
function api_protect_super_admin($admin_id_to_check, $userId = null, $allow_session_admin = false)
5455
{
5456
    if (api_global_admin_can_edit_admin($admin_id_to_check, $userId, $allow_session_admin)) {
5457
        return true;
5458
    } else {
5459
        api_not_allowed();
5460
    }
5461
}
5462
5463
/**
5464
 * Function used to protect a global admin script.
5465
 * The function blocks access when the user has no global platform admin rights.
5466
 * See also the api_is_global_platform_admin() function wich defines who's a "global" admin.
5467
 *
5468
 * @author Julio Montoya
5469
 */
5470
function api_protect_global_admin_script()
5471
{
5472
    if (!api_is_global_platform_admin()) {
5473
        api_not_allowed();
5474
5475
        return false;
5476
    }
5477
5478
    return true;
5479
}
5480
5481
/**
5482
 * Check browser support for specific file types or features
5483
 * This function checks if the user's browser supports a file format or given
5484
 * feature, or returns the current browser and major version when
5485
 * $format=check_browser. Only a limited number of formats and features are
5486
 * checked by this method. Make sure you check its definition first.
5487
 *
5488
 * @param string $format Can be a file format (extension like svg, webm, ...) or a feature (like autocapitalize, ...)
5489
 *
5490
 * @deprecated
5491
 *
5492
 * @return bool or return text array if $format=check_browser
5493
 *
5494
 * @author Juan Carlos Raña Trabado
5495
 */
5496
function api_browser_support($format = '')
5497
{
5498
    return true;
5499
5500
    $browser = new Browser();
0 ignored issues
show
Unused Code introduced by
$browser = new Browser() is not reachable.

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

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

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

    return false;
}

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

Loading history...
5501
    $current_browser = $browser->getBrowser();
5502
    $a_versiontemp = explode('.', $browser->getVersion());
5503
    $current_majorver = $a_versiontemp[0];
5504
5505
    static $result;
5506
5507
    if (isset($result[$format])) {
5508
        return $result[$format];
5509
    }
5510
5511
    // Native svg support
5512
    if ('svg' == $format) {
5513
        if (('Internet Explorer' == $current_browser && $current_majorver >= 9) ||
5514
            ('Firefox' == $current_browser && $current_majorver > 1) ||
5515
            ('Safari' == $current_browser && $current_majorver >= 4) ||
5516
            ('Chrome' == $current_browser && $current_majorver >= 1) ||
5517
            ('Opera' == $current_browser && $current_majorver >= 9)
5518
        ) {
5519
            $result[$format] = true;
5520
5521
            return true;
5522
        } else {
5523
            $result[$format] = false;
5524
5525
            return false;
5526
        }
5527
    } elseif ('pdf' == $format) {
5528
        // native pdf support
5529
        if ('Chrome' == $current_browser && $current_majorver >= 6) {
5530
            $result[$format] = true;
5531
5532
            return true;
5533
        } else {
5534
            $result[$format] = false;
5535
5536
            return false;
5537
        }
5538
    } elseif ('tif' == $format || 'tiff' == $format) {
5539
        //native tif support
5540
        if ('Safari' == $current_browser && $current_majorver >= 5) {
5541
            $result[$format] = true;
5542
5543
            return true;
5544
        } else {
5545
            $result[$format] = false;
5546
5547
            return false;
5548
        }
5549
    } elseif ('ogg' == $format || 'ogx' == $format || 'ogv' == $format || 'oga' == $format) {
5550
        //native ogg, ogv,oga support
5551
        if (('Firefox' == $current_browser && $current_majorver >= 3) ||
5552
            ('Chrome' == $current_browser && $current_majorver >= 3) ||
5553
            ('Opera' == $current_browser && $current_majorver >= 9)) {
5554
            $result[$format] = true;
5555
5556
            return true;
5557
        } else {
5558
            $result[$format] = false;
5559
5560
            return false;
5561
        }
5562
    } elseif ('mpg' == $format || 'mpeg' == $format) {
5563
        //native mpg support
5564
        if (('Safari' == $current_browser && $current_majorver >= 5)) {
5565
            $result[$format] = true;
5566
5567
            return true;
5568
        } else {
5569
            $result[$format] = false;
5570
5571
            return false;
5572
        }
5573
    } elseif ('mp4' == $format) {
5574
        //native mp4 support (TODO: Android, iPhone)
5575
        if ('Android' == $current_browser || 'iPhone' == $current_browser) {
5576
            $result[$format] = true;
5577
5578
            return true;
5579
        } else {
5580
            $result[$format] = false;
5581
5582
            return false;
5583
        }
5584
    } elseif ('mov' == $format) {
5585
        //native mov support( TODO:check iPhone)
5586
        if ('Safari' == $current_browser && $current_majorver >= 5 || 'iPhone' == $current_browser) {
0 ignored issues
show
introduced by
Consider adding parentheses for clarity. Current Interpretation: ('Safari' == $current_br...ne' == $current_browser, Probably Intended Meaning: 'Safari' == $current_bro...e' == $current_browser)
Loading history...
5587
            $result[$format] = true;
5588
5589
            return true;
5590
        } else {
5591
            $result[$format] = false;
5592
5593
            return false;
5594
        }
5595
    } elseif ('avi' == $format) {
5596
        //native avi support
5597
        if ('Safari' == $current_browser && $current_majorver >= 5) {
5598
            $result[$format] = true;
5599
5600
            return true;
5601
        } else {
5602
            $result[$format] = false;
5603
5604
            return false;
5605
        }
5606
    } elseif ('wmv' == $format) {
5607
        //native wmv support
5608
        if ('Firefox' == $current_browser && $current_majorver >= 4) {
5609
            $result[$format] = true;
5610
5611
            return true;
5612
        } else {
5613
            $result[$format] = false;
5614
5615
            return false;
5616
        }
5617
    } elseif ('webm' == $format) {
5618
        //native webm support (TODO:check IE9, Chrome9, Android)
5619
        if (('Firefox' == $current_browser && $current_majorver >= 4) ||
5620
            ('Opera' == $current_browser && $current_majorver >= 9) ||
5621
            ('Internet Explorer' == $current_browser && $current_majorver >= 9) ||
5622
            ('Chrome' == $current_browser && $current_majorver >= 9) ||
5623
            'Android' == $current_browser
5624
        ) {
5625
            $result[$format] = true;
5626
5627
            return true;
5628
        } else {
5629
            $result[$format] = false;
5630
5631
            return false;
5632
        }
5633
    } elseif ('wav' == $format) {
5634
        //native wav support (only some codecs !)
5635
        if (('Firefox' == $current_browser && $current_majorver >= 4) ||
5636
            ('Safari' == $current_browser && $current_majorver >= 5) ||
5637
            ('Opera' == $current_browser && $current_majorver >= 9) ||
5638
            ('Internet Explorer' == $current_browser && $current_majorver >= 9) ||
5639
            ('Chrome' == $current_browser && $current_majorver > 9) ||
5640
            'Android' == $current_browser ||
5641
            'iPhone' == $current_browser
5642
        ) {
5643
            $result[$format] = true;
5644
5645
            return true;
5646
        } else {
5647
            $result[$format] = false;
5648
5649
            return false;
5650
        }
5651
    } elseif ('mid' == $format || 'kar' == $format) {
5652
        //native midi support (TODO:check Android)
5653
        if ('Opera' == $current_browser && $current_majorver >= 9 || 'Android' == $current_browser) {
0 ignored issues
show
introduced by
Consider adding parentheses for clarity. Current Interpretation: ('Opera' == $current_bro...id' == $current_browser, Probably Intended Meaning: 'Opera' == $current_brow...d' == $current_browser)
Loading history...
5654
            $result[$format] = true;
5655
5656
            return true;
5657
        } else {
5658
            $result[$format] = false;
5659
5660
            return false;
5661
        }
5662
    } elseif ('wma' == $format) {
5663
        //native wma support
5664
        if ('Firefox' == $current_browser && $current_majorver >= 4) {
5665
            $result[$format] = true;
5666
5667
            return true;
5668
        } else {
5669
            $result[$format] = false;
5670
5671
            return false;
5672
        }
5673
    } elseif ('au' == $format) {
5674
        //native au support
5675
        if ('Safari' == $current_browser && $current_majorver >= 5) {
5676
            $result[$format] = true;
5677
5678
            return true;
5679
        } else {
5680
            $result[$format] = false;
5681
5682
            return false;
5683
        }
5684
    } elseif ('mp3' == $format) {
5685
        //native mp3 support (TODO:check Android, iPhone)
5686
        if (('Safari' == $current_browser && $current_majorver >= 5) ||
5687
            ('Chrome' == $current_browser && $current_majorver >= 6) ||
5688
            ('Internet Explorer' == $current_browser && $current_majorver >= 9) ||
5689
            'Android' == $current_browser ||
5690
            'iPhone' == $current_browser ||
5691
            'Firefox' == $current_browser
5692
        ) {
5693
            $result[$format] = true;
5694
5695
            return true;
5696
        } else {
5697
            $result[$format] = false;
5698
5699
            return false;
5700
        }
5701
    } elseif ('autocapitalize' == $format) {
5702
        // Help avoiding showing the autocapitalize option if the browser doesn't
5703
        // support it: this attribute is against the HTML5 standard
5704
        if ('Safari' == $current_browser || 'iPhone' == $current_browser) {
5705
            return true;
5706
        } else {
5707
            return false;
5708
        }
5709
    } elseif ("check_browser" == $format) {
5710
        $array_check_browser = [$current_browser, $current_majorver];
5711
5712
        return $array_check_browser;
5713
    } else {
5714
        $result[$format] = false;
5715
5716
        return false;
5717
    }
5718
}
5719
5720
/**
5721
 * This function checks if exist path and file browscap.ini
5722
 * In order for this to work, your browscap configuration setting in php.ini
5723
 * must point to the correct location of the browscap.ini file on your system
5724
 * http://php.net/manual/en/function.get-browser.php.
5725
 *
5726
 * @return bool
5727
 *
5728
 * @author Juan Carlos Raña Trabado
5729
 */
5730
function api_check_browscap()
5731
{
5732
    $setting = ini_get('browscap');
5733
    if ($setting) {
5734
        $browser = get_browser($_SERVER['HTTP_USER_AGENT'], true);
5735
        if (strpos($setting, 'browscap.ini') && !empty($browser)) {
5736
            return true;
5737
        }
5738
    }
5739
5740
    return false;
5741
}
5742
5743
/**
5744
 * Returns the <script> HTML tag.
5745
 */
5746
function api_get_js($file)
5747
{
5748
    return '<script src="'.api_get_path(WEB_LIBRARY_PATH).'javascript/'.$file.'"></script>'."\n";
5749
}
5750
5751
function api_get_build_js($file)
5752
{
5753
    return '<script src="'.api_get_path(WEB_PUBLIC_PATH).'build/'.$file.'"></script>'."\n";
5754
}
5755
5756
function api_get_build_css($file, $media = 'screen')
5757
{
5758
    return '<link
5759
        href="'.api_get_path(WEB_PUBLIC_PATH).'build/'.$file.'" rel="stylesheet" media="'.$media.'" type="text/css" />'."\n";
5760
}
5761
5762
/**
5763
 * Returns the <script> HTML tag.
5764
 *
5765
 * @return string
5766
 */
5767
function api_get_asset($file)
5768
{
5769
    return '<script src="'.api_get_path(WEB_PUBLIC_PATH).'build/libs/'.$file.'"></script>'."\n";
5770
}
5771
5772
/**
5773
 * Returns the <script> HTML tag.
5774
 *
5775
 * @param string $file
5776
 * @param string $media
5777
 *
5778
 * @return string
5779
 */
5780
function api_get_css_asset($file, $media = 'screen')
5781
{
5782
    return '<link
5783
        href="'.api_get_path(WEB_PUBLIC_PATH).'build/libs/'.$file.'"
5784
        rel="stylesheet" media="'.$media.'" type="text/css" />'."\n";
5785
}
5786
5787
/**
5788
 * Returns the <link> HTML tag.
5789
 *
5790
 * @param string $file
5791
 * @param string $media
5792
 */
5793
function api_get_css($file, $media = 'screen')
5794
{
5795
    return '<link href="'.$file.'" rel="stylesheet" media="'.$media.'" type="text/css" />'."\n";
5796
}
5797
5798
function api_get_bootstrap_and_font_awesome($returnOnlyPath = false, $returnFileLocation = false)
5799
{
5800
    $url = api_get_path(WEB_PUBLIC_PATH).'build/css/bootstrap.css';
5801
5802
    if ($returnOnlyPath) {
5803
        if ($returnFileLocation) {
5804
            return api_get_path(SYS_PUBLIC_PATH).'build/css/bootstrap.css';
5805
        }
5806
5807
        return $url;
5808
    }
5809
5810
    return '<link href="'.$url.'" rel="stylesheet" type="text/css" />'."\n";
5811
}
5812
5813
/**
5814
 * Returns the js header to include the jquery library.
5815
 */
5816
function api_get_jquery_js()
5817
{
5818
    return api_get_asset('jquery/jquery.min.js');
5819
}
5820
5821
/**
5822
 * Returns the jquery path.
5823
 *
5824
 * @return string
5825
 */
5826
function api_get_jquery_web_path()
5827
{
5828
    return api_get_path(WEB_PUBLIC_PATH).'assets/jquery/jquery.min.js';
5829
}
5830
5831
/**
5832
 * @return string
5833
 */
5834
function api_get_jquery_ui_js_web_path()
5835
{
5836
    return api_get_path(WEB_PUBLIC_PATH).'assets/jquery-ui/jquery-ui.min.js';
5837
}
5838
5839
/**
5840
 * @return string
5841
 */
5842
function api_get_jquery_ui_css_web_path()
5843
{
5844
    return api_get_path(WEB_PUBLIC_PATH).'assets/jquery-ui/themes/smoothness/jquery-ui.min.css';
5845
}
5846
5847
/**
5848
 * Returns the jquery-ui library js headers.
5849
 *
5850
 * @return string html tags
5851
 */
5852
function api_get_jquery_ui_js()
5853
{
5854
    $libraries = [];
5855
5856
    return api_get_jquery_libraries_js($libraries);
5857
}
5858
5859
function api_get_jqgrid_js()
5860
{
5861
    return api_get_build_css('legacy_free-jqgrid.css').PHP_EOL
5862
        .api_get_build_js('legacy_free-jqgrid.js');
5863
}
5864
5865
/**
5866
 * Returns the jquery library js and css headers.
5867
 *
5868
 * @param   array   list of jquery libraries supported jquery-ui
5869
 * @param   bool    add the jquery library
5870
 *
5871
 * @return string html tags
5872
 */
5873
function api_get_jquery_libraries_js($libraries)
5874
{
5875
    $js = '';
5876
5877
    //Document multiple upload funcionality
5878
    if (in_array('jquery-uploadzs', $libraries)) {
5879
        $js .= api_get_asset('blueimp-load-image/js/load-image.all.min.js');
5880
        $js .= api_get_asset('blueimp-canvas-to-blob/js/canvas-to-blob.min.js');
5881
        $js .= api_get_asset('jquery-file-upload/js/jquery.iframe-transport.js');
5882
        $js .= api_get_asset('jquery-file-upload/js/jquery.fileupload.js');
5883
        $js .= api_get_asset('jquery-file-upload/js/jquery.fileupload-process.js');
5884
        $js .= api_get_asset('jquery-file-upload/js/jquery.fileupload-image.js');
5885
        $js .= api_get_asset('jquery-file-upload/js/jquery.fileupload-audio.js');
5886
        $js .= api_get_asset('jquery-file-upload/js/jquery.fileupload-video.js');
5887
        $js .= api_get_asset('jquery-file-upload/js/jquery.fileupload-validate.js');
5888
5889
        $js .= api_get_css(api_get_path(WEB_PUBLIC_PATH).'assets/jquery-file-upload/css/jquery.fileupload.css');
5890
        $js .= api_get_css(api_get_path(WEB_PUBLIC_PATH).'assets/jquery-file-upload/css/jquery.fileupload-ui.css');
5891
    }
5892
5893
    // jquery datepicker
5894
    if (in_array('datepicker', $libraries)) {
5895
        $languaje = 'en-GB';
5896
        $platform_isocode = strtolower(api_get_language_isocode());
5897
5898
        $datapicker_langs = [
5899
            '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',
5900
        ];
5901
        if (in_array($platform_isocode, $datapicker_langs)) {
5902
            $languaje = $platform_isocode;
5903
        }
5904
5905
        $js .= api_get_js('jquery-ui/jquery-ui-i18n.min.js');
5906
        $script = '<script>
5907
        $(function(){
5908
            $.datepicker.setDefaults($.datepicker.regional["'.$languaje.'"]);
5909
            $.datepicker.regional["local"] = $.datepicker.regional["'.$languaje.'"];
5910
        });
5911
        </script>
5912
        ';
5913
        $js .= $script;
5914
    }
5915
5916
    return $js;
5917
}
5918
5919
/**
5920
 * Returns the URL to the course or session, removing the complexity of the URL
5921
 * building piece by piece.
5922
 *
5923
 * This function relies on api_get_course_info()
5924
 *
5925
 * @param int $courseId  The course code - optional (takes it from context if not given)
5926
 * @param int $sessionId The session ID  - optional (takes it from context if not given)
5927
 * @param int $groupId   The group ID - optional (takes it from context if not given)
5928
 *
5929
 * @return string The URL to a course, a session, or empty string if nothing works
5930
 *                e.g. https://localhost/courses/ABC/index.php?session_id=3&gidReq=1
5931
 *
5932
 * @author  Julio Montoya
5933
 */
5934
function api_get_course_url($courseId = null, $sessionId = null, $groupId = null)
5935
{
5936
    $url = '';
5937
    // If courseCode not set, get context or []
5938
    if (empty($courseId)) {
5939
        $courseId = api_get_course_int_id();
5940
    }
5941
5942
    // If sessionId not set, get context or 0
5943
    if (empty($sessionId)) {
5944
        $sessionId = api_get_session_id();
5945
    }
5946
5947
    // If groupId not set, get context or 0
5948
    if (empty($groupId)) {
5949
        $groupId = api_get_group_id();
5950
    }
5951
5952
    // Build the URL
5953
    if (!empty($courseId)) {
5954
        $webCourseHome = '/course/'.$courseId.'/home';
5955
        // directory not empty, so we do have a course
5956
        $url = $webCourseHome.'?sid='.$sessionId.'&gid='.$groupId;
5957
    } else {
5958
        if (!empty($sessionId) && 'true' !== api_get_setting('session.remove_session_url')) {
5959
            // if the course was unset and the session was set, send directly to the session
5960
            $url = api_get_path(WEB_CODE_PATH).'session/index.php?session_id='.$sessionId;
5961
        }
5962
    }
5963
5964
    // if not valid combination was found, return an empty string
5965
    return $url;
5966
}
5967
5968
/**
5969
 * Check if there is more than the default URL defined in the access_url table.
5970
 */
5971
function api_get_multiple_access_url(): bool
5972
{
5973
    return Container::$container->get(AccessUrlHelper::class)->isMultiple();
5974
}
5975
5976
/**
5977
 * @deprecated Use AccessUrlHelper::isMultiple
5978
 */
5979
function api_is_multiple_url_enabled(): bool
5980
{
5981
    return api_get_multiple_access_url();
5982
}
5983
5984
/**
5985
 * Returns a md5 unique id.
5986
 *
5987
 * @todo add more parameters
5988
 */
5989
function api_get_unique_id()
5990
{
5991
    return md5(time().uniqid().api_get_user_id().api_get_course_id().api_get_session_id());
5992
}
5993
5994
/**
5995
 * @param int Course id
5996
 * @param int tool id: TOOL_QUIZ, TOOL_FORUM, TOOL_STUDENTPUBLICATION, TOOL_LEARNPATH
5997
 * @param int the item id (tool id, exercise id, lp id)
5998
 *
5999
 * @return bool
6000
 */
6001
function api_resource_is_locked_by_gradebook($item_id, $link_type, $course_code = null)
6002
{
6003
    if (api_is_platform_admin()) {
6004
        return false;
6005
    }
6006
    if ('true' === api_get_setting('gradebook_locking_enabled')) {
6007
        if (empty($course_code)) {
6008
            $course_code = api_get_course_id();
6009
        }
6010
        $table = Database::get_main_table(TABLE_MAIN_GRADEBOOK_LINK);
6011
        $item_id = (int) $item_id;
6012
        $link_type = (int) $link_type;
6013
        $course_code = Database::escape_string($course_code);
6014
        $sql = "SELECT locked FROM $table
6015
                WHERE locked = 1 AND ref_id = $item_id AND type = $link_type AND course_code = '$course_code' ";
6016
        $result = Database::query($sql);
6017
        if (Database::num_rows($result)) {
6018
            return true;
6019
        }
6020
    }
6021
6022
    return false;
6023
}
6024
6025
/**
6026
 * Blocks a page if the item was added in a gradebook.
6027
 *
6028
 * @param int       exercise id, work id, thread id,
6029
 * @param int       LINK_EXERCISE, LINK_STUDENTPUBLICATION, LINK_LEARNPATH LINK_FORUM_THREAD, LINK_ATTENDANCE
6030
 * see gradebook/lib/be/linkfactory
6031
 * @param string    course code
6032
 *
6033
 * @return false|null
6034
 */
6035
function api_block_course_item_locked_by_gradebook($item_id, $link_type, $course_code = null)
6036
{
6037
    if (api_is_platform_admin()) {
6038
        return false;
6039
    }
6040
6041
    if (api_resource_is_locked_by_gradebook($item_id, $link_type, $course_code)) {
6042
        $message = Display::return_message(
6043
            get_lang(
6044
                'This option is not available because this activity is contained by an assessment, which is currently locked. To unlock the assessment, ask your platform administrator.'
6045
            ),
6046
            'warning'
6047
        );
6048
        api_not_allowed(true, $message);
6049
    }
6050
}
6051
6052
/**
6053
 * Checks the PHP version installed is enough to run Chamilo.
6054
 *
6055
 * @param string Include path (used to load the error page)
6056
 */
6057
function api_check_php_version()
6058
{
6059
    if (!function_exists('version_compare') ||
6060
        version_compare(PHP_VERSION, REQUIRED_PHP_VERSION, '<')
6061
    ) {
6062
        throw new Exception('Wrong PHP version');
6063
    }
6064
}
6065
6066
/**
6067
 * Checks whether the Archive directory is present and writeable. If not,
6068
 * prints a warning message.
6069
 */
6070
function api_check_archive_dir()
6071
{
6072
    if (is_dir(api_get_path(SYS_ARCHIVE_PATH)) && !is_writable(api_get_path(SYS_ARCHIVE_PATH))) {
6073
        $message = Display::return_message(
6074
            get_lang(
6075
                'The var/cache/ directory, used by this tool, is not writeable. Please contact your platform administrator.'
6076
            ),
6077
            'warning'
6078
        );
6079
        api_not_allowed(true, $message);
6080
    }
6081
}
6082
6083
/**
6084
 * Returns an array of global configuration settings which should be ignored
6085
 * when printing the configuration settings screens.
6086
 *
6087
 * @return array Array of strings, each identifying one of the excluded settings
6088
 */
6089
function api_get_locked_settings()
6090
{
6091
    return [
6092
        'permanently_remove_deleted_files',
6093
        'account_valid_duration',
6094
        'service_ppt2lp',
6095
        'wcag_anysurfer_public_pages',
6096
        'upload_extensions_list_type',
6097
        'upload_extensions_blacklist',
6098
        'upload_extensions_whitelist',
6099
        'upload_extensions_skip',
6100
        'upload_extensions_replace_by',
6101
        'hide_dltt_markup',
6102
        'split_users_upload_directory',
6103
        'permissions_for_new_directories',
6104
        'permissions_for_new_files',
6105
        'platform_charset',
6106
        'ldap_description',
6107
        'cas_activate',
6108
        'cas_server',
6109
        'cas_server_uri',
6110
        'cas_port',
6111
        'cas_protocol',
6112
        'cas_add_user_activate',
6113
        'update_user_info_cas_with_ldap',
6114
        'languagePriority1',
6115
        'languagePriority2',
6116
        'languagePriority3',
6117
        'languagePriority4',
6118
        'login_is_email',
6119
        'chamilo_database_version',
6120
    ];
6121
}
6122
6123
/**
6124
 * Guess the real ip for register in the database, even in reverse proxy cases.
6125
 * To be recognized, the IP has to be found in either $_SERVER['REMOTE_ADDR'] or
6126
 * in $_SERVER['HTTP_X_FORWARDED_FOR'], which is in common use with rproxies.
6127
 * Note: the result of this function is not SQL-safe. Please escape it before
6128
 * inserting in a database.
6129
 *
6130
 * @return string the user's real ip (unsafe - escape it before inserting to db)
6131
 *
6132
 * @author Jorge Frisancho Jibaja <[email protected]>, USIL - Some changes to allow the use of real IP using reverse proxy
6133
 *
6134
 * @version CEV CHANGE 24APR2012
6135
 * @throws RuntimeException
6136
 */
6137
function api_get_real_ip(): string
6138
{
6139
    if ('cli' === PHP_SAPI) {
6140
        $ip = '127.0.0.1';
6141
    } else {
6142
        $ip = trim($_SERVER['REMOTE_ADDR']);
6143
        if (empty($ip)) {
6144
            throw new RuntimeException("Unable to retrieve remote IP address.");
6145
        }
6146
    }
6147
    if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
6148
        if (preg_match('/,/', $_SERVER['HTTP_X_FORWARDED_FOR'])) {
6149
            @list($ip1, $ip2) = @explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
6150
        } else {
6151
            $ip1 = $_SERVER['HTTP_X_FORWARDED_FOR'];
6152
        }
6153
        $ip = trim($ip1);
6154
    }
6155
6156
    return $ip;
6157
}
6158
6159
/**
6160
 * Checks whether an IP is included inside an IP range.
6161
 *
6162
 * @param string IP address
6163
 * @param string IP range
6164
 * @param string $ip
6165
 *
6166
 * @return bool True if IP is in the range, false otherwise
6167
 *
6168
 * @author claudiu at cnixs dot com  on http://www.php.net/manual/fr/ref.network.php#55230
6169
 * @author Yannick Warnier for improvements and managment of multiple ranges
6170
 *
6171
 * @todo check for IPv6 support
6172
 */
6173
function api_check_ip_in_range($ip, $range)
6174
{
6175
    if (empty($ip) or empty($range)) {
6176
        return false;
6177
    }
6178
    $ip_ip = ip2long($ip);
6179
    // divide range param into array of elements
6180
    if (false !== strpos($range, ',')) {
6181
        $ranges = explode(',', $range);
6182
    } else {
6183
        $ranges = [$range];
6184
    }
6185
    foreach ($ranges as $range) {
0 ignored issues
show
introduced by
$range is overwriting one of the parameters of this function.
Loading history...
6186
        $range = trim($range);
6187
        if (empty($range)) {
6188
            continue;
6189
        }
6190
        if (false === strpos($range, '/')) {
6191
            if (0 === strcmp($ip, $range)) {
6192
                return true; // there is a direct IP match, return OK
6193
            }
6194
            continue; //otherwise, get to the next range
6195
        }
6196
        // the range contains a "/", so analyse completely
6197
        [$net, $mask] = explode("/", $range);
6198
6199
        $ip_net = ip2long($net);
6200
        // mask binary magic
6201
        $ip_mask = ~((1 << (32 - $mask)) - 1);
6202
6203
        $ip_ip_net = $ip_ip & $ip_mask;
6204
        if ($ip_ip_net == $ip_net) {
6205
            return true;
6206
        }
6207
    }
6208
6209
    return false;
6210
}
6211
6212
function api_check_user_access_to_legal($courseInfo)
6213
{
6214
    if (empty($courseInfo)) {
6215
        return false;
6216
    }
6217
6218
    $visibility = (int) $courseInfo['visibility'];
6219
    $visibilityList = [COURSE_VISIBILITY_OPEN_WORLD, COURSE_VISIBILITY_OPEN_PLATFORM];
6220
6221
    return
6222
        in_array($visibility, $visibilityList) ||
6223
        api_is_drh() ||
6224
        (COURSE_VISIBILITY_REGISTERED === $visibility && 1 === (int) $courseInfo['subscribe']);
6225
}
6226
6227
/**
6228
 * Checks if the global chat is enabled or not.
6229
 *
6230
 * @return bool
6231
 */
6232
function api_is_global_chat_enabled()
6233
{
6234
    return
6235
        !api_is_anonymous() &&
6236
        'true' === api_get_setting('allow_global_chat') &&
6237
        'true' === api_get_setting('allow_social_tool');
6238
}
6239
6240
/**
6241
 * @param int   $item_id
6242
 * @param int   $tool_id
6243
 * @param int   $group_id   id
6244
 * @param array $courseInfo
6245
 * @param int   $sessionId
6246
 * @param int   $userId
6247
 *
6248
 * @deprecated
6249
 */
6250
function api_set_default_visibility(
6251
    $item_id,
6252
    $tool_id,
6253
    $group_id = 0,
6254
    $courseInfo = [],
6255
    $sessionId = 0,
6256
    $userId = 0
6257
) {
6258
    $courseInfo = empty($courseInfo) ? api_get_course_info() : $courseInfo;
6259
    $courseId = $courseInfo['real_id'];
6260
    $courseCode = $courseInfo['code'];
6261
    $sessionId = empty($sessionId) ? api_get_session_id() : $sessionId;
6262
    $userId = empty($userId) ? api_get_user_id() : $userId;
6263
6264
    // if group is null force group_id = 0, this force is needed to create a LP folder with group = 0
6265
    if (is_null($group_id)) {
6266
        $group_id = 0;
6267
    } else {
6268
        $group_id = empty($group_id) ? api_get_group_id() : $group_id;
6269
    }
6270
6271
    $groupInfo = [];
6272
    if (!empty($group_id)) {
6273
        $groupInfo = GroupManager::get_group_properties($group_id);
6274
    }
6275
    $original_tool_id = $tool_id;
6276
6277
    switch ($tool_id) {
6278
        case TOOL_LINK:
6279
        case TOOL_LINK_CATEGORY:
6280
            $tool_id = 'links';
6281
            break;
6282
        case TOOL_DOCUMENT:
6283
            $tool_id = 'documents';
6284
            break;
6285
        case TOOL_LEARNPATH:
6286
            $tool_id = 'learning';
6287
            break;
6288
        case TOOL_ANNOUNCEMENT:
6289
            $tool_id = 'announcements';
6290
            break;
6291
        case TOOL_FORUM:
6292
        case TOOL_FORUM_CATEGORY:
6293
        case TOOL_FORUM_THREAD:
6294
            $tool_id = 'forums';
6295
            break;
6296
        case TOOL_QUIZ:
6297
            $tool_id = 'quiz';
6298
            break;
6299
    }
6300
    $setting = api_get_setting('tool_visible_by_default_at_creation');
6301
6302
    if (isset($setting[$tool_id])) {
6303
        $visibility = 'invisible';
6304
        if ('true' === $setting[$tool_id]) {
6305
            $visibility = 'visible';
6306
        }
6307
6308
        // Read the portal and course default visibility
6309
        if ('documents' === $tool_id) {
6310
            $visibility = DocumentManager::getDocumentDefaultVisibility($courseInfo);
6311
        }
6312
6313
        // Fixes default visibility for tests
6314
        switch ($original_tool_id) {
6315
            case TOOL_QUIZ:
6316
                if (empty($sessionId)) {
6317
                    $objExerciseTmp = new Exercise($courseId);
6318
                    $objExerciseTmp->read($item_id);
6319
                    if ('visible' === $visibility) {
6320
                        $objExerciseTmp->enable();
6321
                        $objExerciseTmp->save();
6322
                    } else {
6323
                        $objExerciseTmp->disable();
6324
                        $objExerciseTmp->save();
6325
                    }
6326
                }
6327
                break;
6328
        }
6329
    }
6330
}
6331
6332
function api_get_roles()
6333
{
6334
    $hierarchy = Container::$container->getParameter('security.role_hierarchy.roles');
6335
    $roles = [];
6336
    array_walk_recursive($hierarchy, function ($role) use (&$roles) {
6337
        $roles[$role] = $role;
6338
    });
6339
6340
    return $roles;
6341
}
6342
6343
function api_get_user_roles(): array
6344
{
6345
    $permissionService = Container::$container->get(PermissionServiceHelper::class);
6346
6347
    $roles = $permissionService->getUserRoles();
6348
6349
    return array_combine($roles, $roles);
6350
}
6351
6352
/**
6353
 * @param string $file
6354
 *
6355
 * @return string
6356
 */
6357
function api_get_js_simple($file)
6358
{
6359
    return '<script type="text/javascript" src="'.$file.'"></script>'."\n";
6360
}
6361
6362
/**
6363
 * Modify default memory_limit and max_execution_time limits
6364
 * Needed when processing long tasks.
6365
 */
6366
function api_set_more_memory_and_time_limits()
6367
{
6368
    if (function_exists('ini_set')) {
6369
        api_set_memory_limit('256M');
6370
        ini_set('max_execution_time', 1800);
6371
    }
6372
}
6373
6374
/**
6375
 * Tries to set memory limit, if authorized and new limit is higher than current.
6376
 *
6377
 * @param string $mem New memory limit
6378
 *
6379
 * @return bool True on success, false on failure or current is higher than suggested
6380
 * @assert (null) === false
6381
 * @assert (-1) === false
6382
 * @assert (0) === true
6383
 * @assert ('1G') === true
6384
 */
6385
function api_set_memory_limit($mem)
6386
{
6387
    //if ini_set() not available, this function is useless
6388
    if (!function_exists('ini_set') || is_null($mem) || -1 == $mem) {
6389
        return false;
6390
    }
6391
6392
    $memory_limit = ini_get('memory_limit');
6393
    if (api_get_bytes_memory_limit($mem) > api_get_bytes_memory_limit($memory_limit)) {
6394
        ini_set('memory_limit', $mem);
6395
6396
        return true;
6397
    }
6398
6399
    return false;
6400
}
6401
6402
/**
6403
 * Gets memory limit in bytes.
6404
 *
6405
 * @param string The memory size (128M, 1G, 1000K, etc)
6406
 *
6407
 * @return int
6408
 * @assert (null) === false
6409
 * @assert ('1t')  === 1099511627776
6410
 * @assert ('1g')  === 1073741824
6411
 * @assert ('1m')  === 1048576
6412
 * @assert ('100k') === 102400
6413
 */
6414
function api_get_bytes_memory_limit($mem)
6415
{
6416
    $size = strtolower(substr($mem, -1));
6417
6418
    switch ($size) {
6419
        case 't':
6420
            $mem = (int) substr($mem, -1) * 1024 * 1024 * 1024 * 1024;
6421
            break;
6422
        case 'g':
6423
            $mem = (int) substr($mem, 0, -1) * 1024 * 1024 * 1024;
6424
            break;
6425
        case 'm':
6426
            $mem = (int) substr($mem, 0, -1) * 1024 * 1024;
6427
            break;
6428
        case 'k':
6429
            $mem = (int) substr($mem, 0, -1) * 1024;
6430
            break;
6431
        default:
6432
            // we assume it's integer only
6433
            $mem = (int) $mem;
6434
            break;
6435
    }
6436
6437
    return $mem;
6438
}
6439
6440
/**
6441
 * Finds all the information about a user from username instead of user id.
6442
 *
6443
 * @param string $officialCode
6444
 *
6445
 * @return array $user_info user_id, lastname, firstname, username, email, ...
6446
 *
6447
 * @author Yannick Warnier <[email protected]>
6448
 */
6449
function api_get_user_info_from_official_code($officialCode)
6450
{
6451
    if (empty($officialCode)) {
6452
        return false;
6453
    }
6454
    $sql = "SELECT * FROM ".Database::get_main_table(TABLE_MAIN_USER)."
6455
            WHERE official_code ='".Database::escape_string($officialCode)."'";
6456
    $result = Database::query($sql);
6457
    if (Database::num_rows($result) > 0) {
6458
        $result_array = Database::fetch_array($result);
6459
6460
        return _api_format_user($result_array);
6461
    }
6462
6463
    return false;
6464
}
6465
6466
/**
6467
 * @param string $usernameInputId
6468
 * @param string $passwordInputId
6469
 *
6470
 * @return string|null
6471
 */
6472
function api_get_password_checker_js($usernameInputId, $passwordInputId)
6473
{
6474
    $checkPass = api_get_setting('allow_strength_pass_checker');
6475
    $useStrengthPassChecker = 'true' === $checkPass;
6476
6477
    if (false === $useStrengthPassChecker) {
6478
        return null;
6479
    }
6480
6481
    $minRequirements = Security::getPasswordRequirements()['min'];
6482
6483
    $options = [
6484
        'rules' => [],
6485
    ];
6486
6487
    if ($minRequirements['length'] > 0) {
6488
        $options['rules'][] = [
6489
            'minChar' => $minRequirements['length'],
6490
            'pattern' => '.',
6491
            'helpText' => sprintf(
6492
                get_lang('Minimum %s characters in total'),
6493
                $minRequirements['length']
6494
            ),
6495
        ];
6496
    }
6497
6498
    if ($minRequirements['lowercase'] > 0) {
6499
        $options['rules'][] = [
6500
            'minChar' => $minRequirements['lowercase'],
6501
            'pattern' => '[a-z]',
6502
            'helpText' => sprintf(
6503
                get_lang('Minimum %s lowercase characters'),
6504
                $minRequirements['lowercase']
6505
            ),
6506
        ];
6507
    }
6508
6509
    if ($minRequirements['uppercase'] > 0) {
6510
        $options['rules'][] = [
6511
            'minChar' => $minRequirements['uppercase'],
6512
            'pattern' => '[A-Z]',
6513
            'helpText' => sprintf(
6514
                get_lang('Minimum %s uppercase characters'),
6515
                $minRequirements['uppercase']
6516
            ),
6517
        ];
6518
    }
6519
6520
    if ($minRequirements['numeric'] > 0) {
6521
        $options['rules'][] = [
6522
            'minChar' => $minRequirements['numeric'],
6523
            'pattern' => '[0-9]',
6524
            'helpText' => sprintf(
6525
                get_lang('Minimum %s numerical (0-9) characters'),
6526
                $minRequirements['numeric']
6527
            ),
6528
        ];
6529
    }
6530
6531
    if ($minRequirements['specials'] > 0) {
6532
        $options['rules'][] = [
6533
            'minChar' => $minRequirements['specials'],
6534
            'pattern' => '[!"#$%&\'()*+,\-./\\\:;<=>?@[\\]^_`{|}~]',
6535
            'helpText' => sprintf(
6536
                get_lang('Minimum %s special characters'),
6537
                $minRequirements['specials']
6538
            ),
6539
        ];
6540
    }
6541
6542
    $js = api_get_js('password-checker/password-checker.js');
6543
    $js .= "<script>
6544
    $(function() {
6545
        $('".$passwordInputId."').passwordChecker(".json_encode($options).");
6546
    });
6547
    </script>";
6548
6549
    return $js;
6550
}
6551
6552
/**
6553
 * create an user extra field called 'captcha_blocked_until_date'.
6554
 *
6555
 * @param string $username
6556
 *
6557
 * @return bool
6558
 */
6559
function api_block_account_captcha($username)
6560
{
6561
    $userInfo = api_get_user_info_from_username($username);
6562
    if (empty($userInfo)) {
6563
        return false;
6564
    }
6565
    $minutesToBlock = api_get_setting('captcha_time_to_block');
6566
    $time = time() + $minutesToBlock * 60;
6567
    UserManager::update_extra_field_value(
6568
        $userInfo['user_id'],
6569
        'captcha_blocked_until_date',
6570
        api_get_utc_datetime($time)
6571
    );
6572
6573
    return true;
6574
}
6575
6576
/**
6577
 * @param string $username
6578
 *
6579
 * @return bool
6580
 */
6581
function api_clean_account_captcha($username)
6582
{
6583
    $userInfo = api_get_user_info_from_username($username);
6584
    if (empty($userInfo)) {
6585
        return false;
6586
    }
6587
    Session::erase('loginFailedCount');
6588
    UserManager::update_extra_field_value(
6589
        $userInfo['user_id'],
6590
        'captcha_blocked_until_date',
6591
        null
6592
    );
6593
6594
    return true;
6595
}
6596
6597
/**
6598
 * @param string $username
6599
 *
6600
 * @return bool
6601
 */
6602
function api_get_user_blocked_by_captcha($username)
6603
{
6604
    $userInfo = api_get_user_info_from_username($username);
6605
    if (empty($userInfo)) {
6606
        return false;
6607
    }
6608
    $data = UserManager::get_extra_user_data_by_field(
6609
        $userInfo['user_id'],
6610
        'captcha_blocked_until_date'
6611
    );
6612
    if (isset($data) && isset($data['captcha_blocked_until_date'])) {
6613
        return $data['captcha_blocked_until_date'];
6614
    }
6615
6616
    return false;
6617
}
6618
6619
/**
6620
 * If true, the drh can access all content (courses, users) inside a session.
6621
 *
6622
 * @return bool
6623
 */
6624
function api_drh_can_access_all_session_content()
6625
{
6626
    return 'true' === api_get_setting('drh_can_access_all_session_content');
6627
}
6628
6629
/**
6630
 * Checks if user can login as another user.
6631
 *
6632
 * @param int $loginAsUserId the user id to log in
6633
 * @param int $userId        my user id
6634
 *
6635
 * @return bool
6636
 */
6637
function api_can_login_as($loginAsUserId, $userId = null)
6638
{
6639
    $loginAsUserId = (int) $loginAsUserId;
6640
6641
    if (empty($loginAsUserId)) {
6642
        return false;
6643
    }
6644
6645
    if (empty($userId)) {
6646
        $userId = api_get_user_id();
6647
    }
6648
6649
    if ($loginAsUserId == $userId) {
6650
        return false;
6651
    }
6652
6653
    // Check if the user to login is an admin
6654
    if (api_is_platform_admin_by_id($loginAsUserId)) {
6655
        // Only super admins can login to admin accounts
6656
        if (!api_global_admin_can_edit_admin($loginAsUserId)) {
6657
            return false;
6658
        }
6659
    }
6660
6661
    $userInfo = api_get_user_info($loginAsUserId);
6662
6663
    $isDrh = function () use ($loginAsUserId) {
6664
        if (api_is_drh()) {
6665
            if (api_drh_can_access_all_session_content()) {
6666
                $users = SessionManager::getAllUsersFromCoursesFromAllSessionFromStatus(
6667
                    'drh_all',
6668
                    api_get_user_id()
6669
                );
6670
                $userList = [];
6671
                if (is_array($users)) {
6672
                    foreach ($users as $user) {
6673
                        $userList[] = $user['id'];
6674
                    }
6675
                }
6676
                if (in_array($loginAsUserId, $userList)) {
6677
                    return true;
6678
                }
6679
            } else {
6680
                if (api_is_drh() &&
6681
                    UserManager::is_user_followed_by_drh($loginAsUserId, api_get_user_id())
6682
                ) {
6683
                    return true;
6684
                }
6685
            }
6686
        }
6687
6688
        return false;
6689
    };
6690
6691
    $loginAsStatusForSessionAdmins = [STUDENT];
6692
6693
    if ('true' === api_get_setting('session.allow_session_admin_login_as_teacher')) {
6694
        $loginAsStatusForSessionAdmins[] = COURSEMANAGER;
6695
    }
6696
6697
    return api_is_platform_admin() ||
6698
        (api_is_session_admin() && in_array($userInfo['status'], $loginAsStatusForSessionAdmins)) ||
6699
        $isDrh();
6700
}
6701
6702
/**
6703
 * Return true on https install.
6704
 *
6705
 * @return bool
6706
 */
6707
function api_is_https()
6708
{
6709
    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...
6710
        'https' == $_SERVER['HTTP_X_FORWARDED_PROTO'] || !empty(api_get_configuration_value('force_https_forwarded_proto'))
6711
    ) {
6712
        $isSecured = true;
6713
    } else {
6714
        if (!empty($_SERVER['HTTPS']) && 'off' != $_SERVER['HTTPS']) {
6715
            $isSecured = true;
6716
        } else {
6717
            $isSecured = false;
6718
            // last chance
6719
            if (!empty($_SERVER['SERVER_PORT']) && 443 == $_SERVER['SERVER_PORT']) {
6720
                $isSecured = true;
6721
            }
6722
        }
6723
    }
6724
6725
    return $isSecured;
6726
}
6727
6728
/**
6729
 * Return protocol (http or https).
6730
 *
6731
 * @return string
6732
 */
6733
function api_get_protocol()
6734
{
6735
    return api_is_https() ? 'https' : 'http';
6736
}
6737
6738
/**
6739
 * Get origin.
6740
 *
6741
 * @param string
6742
 *
6743
 * @return string
6744
 */
6745
function api_get_origin()
6746
{
6747
    return isset($_REQUEST['origin']) ? urlencode(Security::remove_XSS(urlencode($_REQUEST['origin']))) : '';
6748
}
6749
6750
/**
6751
 * Warns an user that the portal reach certain limit.
6752
 *
6753
 * @param string $limitName
6754
 */
6755
function api_warn_hosting_contact($limitName)
6756
{
6757
    $hostingParams = api_get_configuration_value(1);
6758
    $email = null;
6759
6760
    if (!empty($hostingParams)) {
6761
        if (isset($hostingParams['hosting_contact_mail'])) {
6762
            $email = $hostingParams['hosting_contact_mail'];
6763
        }
6764
    }
6765
6766
    if (!empty($email)) {
6767
        $subject = get_lang('Hosting warning reached');
6768
        $body = get_lang('Portal name').': '.api_get_path(WEB_PATH)." \n ";
6769
        $body .= get_lang('Portal\'s limit type').': '.$limitName." \n ";
6770
        if (isset($hostingParams[$limitName])) {
6771
            $body .= get_lang('Value').': '.$hostingParams[$limitName];
6772
        }
6773
        api_mail_html(null, $email, $subject, $body);
6774
    }
6775
}
6776
6777
/**
6778
 * Gets value of a variable from config/configuration.php
6779
 * Variables that are not set in the configuration.php file but set elsewhere:
6780
 * - virtual_css_theme_folder (vchamilo plugin)
6781
 * - access_url (global.inc.php)
6782
 * - apc/apc_prefix (global.inc.php).
6783
 *
6784
 * @param string $variable
6785
 *
6786
 * @return bool|mixed
6787
 */
6788
function api_get_configuration_value($variable)
6789
{
6790
    global $_configuration;
6791
    // Check the current url id, id = 1 by default
6792
    $urlId = isset($_configuration['access_url']) ? (int) $_configuration['access_url'] : 1;
6793
6794
    $variable = trim($variable);
6795
6796
    // Check if variable exists
6797
    if (isset($_configuration[$variable])) {
6798
        if (is_array($_configuration[$variable])) {
6799
            // Check if it exists for the sub portal
6800
            if (array_key_exists($urlId, $_configuration[$variable])) {
6801
                return $_configuration[$variable][$urlId];
6802
            } else {
6803
                // Try to found element with id = 1 (master portal)
6804
                if (array_key_exists(1, $_configuration[$variable])) {
6805
                    return $_configuration[$variable][1];
6806
                }
6807
            }
6808
        }
6809
6810
        return $_configuration[$variable];
6811
    }
6812
6813
    return false;
6814
}
6815
6816
/**
6817
 * Loads hosting limits from the YAML file.
6818
 *
6819
 * @return array The hosting limits.
6820
 */
6821
function load_hosting_limits(): array
6822
{
6823
    $container = Container::$container;
6824
6825
    $hostingLimits = $container->getParameter('hosting_limits');
0 ignored issues
show
Bug introduced by
The method getParameter() does not exist on null. ( Ignorable by Annotation )

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

6825
    /** @scrutinizer ignore-call */ 
6826
    $hostingLimits = $container->getParameter('hosting_limits');

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...
6826
6827
    return $hostingLimits['urls'] ?? [];
6828
}
6829
6830
/**
6831
 * Gets a specific hosting limit.
6832
 *
6833
 * @param int $urlId The URL ID.
6834
 * @param string $limitName The name of the limit.
6835
 * @return mixed The value of the limit, or null if not found.
6836
 */
6837
function get_hosting_limit(int $urlId, string $limitName): mixed
6838
{
6839
    $limits = load_hosting_limits();
6840
6841
    foreach ($limits[$urlId] as $limitArray) {
6842
        if (isset($limitArray[$limitName])) {
6843
            return $limitArray[$limitName];
6844
        }
6845
    }
6846
6847
    return null;
6848
}
6849
6850
6851
/**
6852
 * Retrieves an environment variable value with validation and handles boolean conversion.
6853
 *
6854
 * @param string $variable The name of the environment variable.
6855
 * @param mixed $default The default value to return if the variable is not set.
6856
 * @return mixed The value of the environment variable, converted to boolean if necessary, or the default value.
6857
 */
6858
function api_get_env_variable(string $variable, mixed $default = null): mixed
6859
{
6860
    if (Container::$container->hasParameter($variable)) {
6861
        $value = Container::$container->getParameter($variable);
6862
6863
        if ($value === '0') {
6864
            return false;
6865
        }
6866
        if ($value === '1') {
6867
            return true;
6868
        }
6869
6870
        return $value;
6871
    }
6872
6873
    return $default;
6874
}
6875
/**
6876
 * Retreives and returns a value in a hierarchical configuration array
6877
 * api_get_configuration_sub_value('a/b/c') returns api_get_configuration_value('a')['b']['c'].
6878
 *
6879
 * @param string $path      the successive array keys, separated by the separator
6880
 * @param mixed  $default   value to be returned if not found, null by default
6881
 * @param string $separator '/' by default
6882
 * @param array  $array     the active configuration array by default
6883
 *
6884
 * @return mixed the found value or $default
6885
 */
6886
function api_get_configuration_sub_value($path, $default = null, $separator = '/', $array = null)
6887
{
6888
    $pos = strpos($path, $separator);
6889
    if (false === $pos) {
6890
        if (is_null($array)) {
6891
            return api_get_configuration_value($path);
6892
        }
6893
        if (is_array($array) && array_key_exists($path, $array)) {
6894
            return $array[$path];
6895
        }
6896
6897
        return $default;
6898
    }
6899
    $key = substr($path, 0, $pos);
6900
    if (is_null($array)) {
6901
        $newArray = api_get_configuration_value($key);
6902
    } elseif (is_array($array) && array_key_exists($key, $array)) {
6903
        $newArray = $array[$key];
6904
    } else {
6905
        return $default;
6906
    }
6907
    if (is_array($newArray)) {
6908
        $newPath = substr($path, $pos + 1);
6909
6910
        return api_get_configuration_sub_value($newPath, $default, $separator, $newArray);
6911
    }
6912
6913
    return $default;
6914
}
6915
6916
/**
6917
 * Retrieves and returns a value in a hierarchical configuration array
6918
 * api_array_sub_value($array, 'a/b/c') returns $array['a']['b']['c'].
6919
 *
6920
 * @param array  $array     the recursive array that contains the value to be returned (or not)
6921
 * @param string $path      the successive array keys, separated by the separator
6922
 * @param mixed  $default   the value to be returned if not found
6923
 * @param string $separator the separator substring
6924
 *
6925
 * @return mixed the found value or $default
6926
 */
6927
function api_array_sub_value($array, $path, $default = null, $separator = '/')
6928
{
6929
    $pos = strpos($path, $separator);
6930
    if (false === $pos) {
6931
        if (is_array($array) && array_key_exists($path, $array)) {
6932
            return $array[$path];
6933
        }
6934
6935
        return $default;
6936
    }
6937
    $key = substr($path, 0, $pos);
6938
    if (is_array($array) && array_key_exists($key, $array)) {
6939
        $newArray = $array[$key];
6940
    } else {
6941
        return $default;
6942
    }
6943
    if (is_array($newArray)) {
6944
        $newPath = substr($path, $pos + 1);
6945
6946
        return api_array_sub_value($newArray, $newPath, $default);
6947
    }
6948
6949
    return $default;
6950
}
6951
6952
/**
6953
 * Returns supported image extensions in the portal.
6954
 *
6955
 * @param bool $supportVectors Whether vector images should also be accepted or not
6956
 *
6957
 * @return array Supported image extensions in the portal
6958
 */
6959
function api_get_supported_image_extensions($supportVectors = true)
6960
{
6961
    // jpg can also be called jpeg, jpe, jfif and jif. See https://en.wikipedia.org/wiki/JPEG#JPEG_filename_extensions
6962
    $supportedImageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'jpe', 'jfif', 'jif'];
6963
    if ($supportVectors) {
6964
        array_push($supportedImageExtensions, 'svg');
6965
    }
6966
    if (version_compare(PHP_VERSION, '5.5.0', '>=')) {
6967
        array_push($supportedImageExtensions, 'webp');
6968
    }
6969
6970
    return $supportedImageExtensions;
6971
}
6972
6973
/**
6974
 * This setting changes the registration status for the campus.
6975
 *
6976
 * @author Patrick Cool <[email protected]>, Ghent University
6977
 *
6978
 * @version August 2006
6979
 *
6980
 * @param bool $listCampus Whether we authorize
6981
 *
6982
 * @todo the $_settings should be reloaded here. => write api function for this and use this in global.inc.php also.
6983
 */
6984
function api_register_campus($listCampus = true)
6985
{
6986
    $tbl_settings = Database::get_main_table(TABLE_MAIN_SETTINGS);
6987
6988
    $sql = "UPDATE $tbl_settings SET selected_value='true' WHERE variable='registered'";
6989
    Database::query($sql);
6990
6991
    if (!$listCampus) {
6992
        $sql = "UPDATE $tbl_settings SET selected_value='true' WHERE variable='donotlistcampus'";
6993
        Database::query($sql);
6994
    }
6995
}
6996
6997
/**
6998
 * Check whether the user type should be exclude.
6999
 * Such as invited or anonymous users.
7000
 *
7001
 * @param bool $checkDB Optional. Whether check the user status
7002
 * @param int  $userId  Options. The user id
7003
 *
7004
 * @return bool
7005
 */
7006
function api_is_excluded_user_type($checkDB = false, $userId = 0)
7007
{
7008
    if ($checkDB) {
7009
        $userId = empty($userId) ? api_get_user_id() : (int) $userId;
7010
7011
        if (0 == $userId) {
7012
            return true;
7013
        }
7014
7015
        $userInfo = api_get_user_info($userId);
7016
7017
        switch ($userInfo['status']) {
7018
            case INVITEE:
7019
            case ANONYMOUS:
7020
                return true;
7021
            default:
7022
                return false;
7023
        }
7024
    }
7025
7026
    $isInvited = api_is_invitee();
7027
    $isAnonymous = api_is_anonymous();
7028
7029
    if ($isInvited || $isAnonymous) {
7030
        return true;
7031
    }
7032
7033
    return false;
7034
}
7035
7036
/**
7037
 * Get the user status to ignore in reports.
7038
 *
7039
 * @param string $format Optional. The result type (array or string)
7040
 *
7041
 * @return array|string
7042
 */
7043
function api_get_users_status_ignored_in_reports($format = 'array')
7044
{
7045
    $excludedTypes = [
7046
        INVITEE,
7047
        ANONYMOUS,
7048
    ];
7049
7050
    if ('string' == $format) {
7051
        return implode(', ', $excludedTypes);
7052
    }
7053
7054
    return $excludedTypes;
7055
}
7056
7057
/**
7058
 * Set the Site Use Cookie Warning for 1 year.
7059
 */
7060
function api_set_site_use_cookie_warning_cookie()
7061
{
7062
    setcookie('ChamiloUsesCookies', 'ok', time() + 31556926);
7063
}
7064
7065
/**
7066
 * Return true if the Site Use Cookie Warning Cookie warning exists.
7067
 *
7068
 * @return bool
7069
 */
7070
function api_site_use_cookie_warning_cookie_exist()
7071
{
7072
    return isset($_COOKIE['ChamiloUsesCookies']);
7073
}
7074
7075
/**
7076
 * Given a number of seconds, format the time to show hours, minutes and seconds.
7077
 *
7078
 * @param int    $time         The time in seconds
7079
 * @param string $originFormat Optional. PHP o JS
7080
 *
7081
 * @return string (00h00'00")
7082
 */
7083
function api_format_time($time, $originFormat = 'php')
7084
{
7085
    $h = get_lang('h');
7086
    $hours = $time / 3600;
7087
    $mins = ($time % 3600) / 60;
7088
    $secs = ($time % 60);
7089
7090
    if ($time < 0) {
7091
        $hours = 0;
7092
        $mins = 0;
7093
        $secs = 0;
7094
    }
7095
7096
    if ('js' === $originFormat) {
7097
        $formattedTime = trim(sprintf("%02d : %02d : %02d", $hours, $mins, $secs));
7098
    } else {
7099
        $formattedTime = trim(sprintf("%02d$h%02d'%02d\"", $hours, $mins, $secs));
7100
    }
7101
7102
    return $formattedTime;
7103
}
7104
7105
function api_set_noreply_and_from_address_to_mailer(
7106
    TemplatedEmail $email,
7107
    array $sender,
7108
    array $replyToAddress = []
7109
): void {
7110
    $validator = Container::getLegacyHelper()->getValidator();
7111
    $emailConstraint = new Assert\Email();
7112
7113
    $noReplyAddress = api_get_setting('noreply_email_address');
7114
    $avoidReplyToAddress = false;
7115
7116
    if (!empty($noReplyAddress)) {
7117
        // $avoidReplyToAddress = api_get_configuration_value('mail_no_reply_avoid_reply_to');
7118
    }
7119
7120
    // Default values
7121
    $notification = new Notification();
7122
    $defaultSenderName = $notification->getDefaultPlatformSenderName();
7123
    $defaultSenderEmail = $notification->getDefaultPlatformSenderEmail();
7124
7125
    // If the parameter is set don't use the admin.
7126
    $senderName = !empty($sender['name']) ? $sender['name'] : $defaultSenderName;
7127
    $senderEmail = !empty($sender['email']) ? $sender['email'] : $defaultSenderEmail;
7128
7129
    // Send errors to the platform admin
7130
    $adminEmail = api_get_setting('admin.administrator_email');
7131
7132
    $adminEmailValidation = $validator->validate($adminEmail, $emailConstraint);
7133
7134
    if (!empty($adminEmail) && 0 === $adminEmailValidation->count()) {
7135
        $email
7136
            ->getHeaders()
7137
            ->addIdHeader('Errors-To', $adminEmail)
7138
        ;
7139
    }
7140
7141
    if (!$avoidReplyToAddress && !empty($replyToAddress)) {
7142
        $replyToEmailValidation = $validator->validate($replyToAddress['mail'], $emailConstraint);
7143
7144
        if (0 === $replyToEmailValidation->count()) {
7145
            $email->addReplyTo(new Address($replyToAddress['mail'], $replyToAddress['name']));
7146
        }
7147
    }
7148
7149
    if ('true' === api_get_setting('mail.smtp_unique_sender')) {
7150
        $senderName = $defaultSenderName;
7151
        $senderEmail = $defaultSenderEmail;
7152
7153
        $email->sender(new Address($senderEmail, $senderName));
7154
    }
7155
7156
    if ($senderEmail) {
7157
        $email->from(new Address($senderEmail, $senderName));
7158
    }
7159
}
7160
7161
/**
7162
 * Sends an email
7163
 * Sender name and email can be specified, if not specified
7164
 * name and email of the platform admin are used.
7165
 *
7166
 * @param string    name of recipient
7167
 * @param string    email of recipient
7168
 * @param string    email subject
7169
 * @param string    email body
7170
 * @param string    sender name
7171
 * @param string    sender e-mail
7172
 * @param array     extra headers in form $headers = array($name => $value) to allow parsing
7173
 * @param array     data file (path and filename)
7174
 * @param bool      True for attaching a embedded file inside content html (optional)
7175
 * @param array     Additional parameters
7176
 *
7177
 * @return bool true if mail was sent
7178
 */
7179
function api_mail_html(
7180
    $recipientName,
7181
    $recipientEmail,
7182
    $subject,
7183
    $body,
7184
    $senderName = '',
7185
    $senderEmail = '',
7186
    $extra_headers = [],
7187
    $data_file = [],
7188
    $embeddedImage = false,
7189
    $additionalParameters = [],
7190
    string $sendErrorTo = null
7191
) {
7192
    $mailHelper = Container::$container->get(MailHelper::class);
7193
7194
    return $mailHelper->send(
7195
        $recipientName,
7196
        $recipientEmail,
7197
        $subject,
7198
        $body,
7199
        $senderName,
7200
        $senderEmail,
7201
        $extra_headers,
7202
        $data_file,
7203
        $embeddedImage,
7204
        $additionalParameters,
7205
        $sendErrorTo
7206
    );
7207
}
7208
7209
/**
7210
 * @param int  $tool       Possible values: GroupManager::GROUP_TOOL_*
7211
 * @param bool $showHeader
7212
 */
7213
function api_protect_course_group($tool, $showHeader = true)
7214
{
7215
    $groupId = api_get_group_id();
7216
    if (!empty($groupId)) {
7217
        if (api_is_platform_admin()) {
7218
            return true;
7219
        }
7220
7221
        if (api_is_allowed_to_edit(false, true, true)) {
7222
            return true;
7223
        }
7224
7225
        $userId = api_get_user_id();
7226
        $sessionId = api_get_session_id();
7227
        if (!empty($sessionId)) {
7228
            if (api_is_coach($sessionId, api_get_course_int_id())) {
7229
                return true;
7230
            }
7231
7232
            if (api_is_drh()) {
7233
                if (SessionManager::isUserSubscribedAsHRM($sessionId, $userId)) {
7234
                    return true;
7235
                }
7236
            }
7237
        }
7238
7239
        $group = api_get_group_entity($groupId);
7240
7241
        // Group doesn't exists
7242
        if (null === $group) {
7243
            api_not_allowed($showHeader);
7244
        }
7245
7246
        // Check group access
7247
        $allow = GroupManager::userHasAccess(
7248
            $userId,
7249
            $group,
7250
            $tool
7251
        );
7252
7253
        if (!$allow) {
7254
            api_not_allowed($showHeader);
7255
        }
7256
    }
7257
7258
    return false;
7259
}
7260
7261
/**
7262
 * Check if a date is in a date range.
7263
 *
7264
 * @param datetime $startDate
7265
 * @param datetime $endDate
7266
 * @param datetime $currentDate
7267
 *
7268
 * @return bool true if date is in rage, false otherwise
7269
 */
7270
function api_is_date_in_date_range($startDate, $endDate, $currentDate = null)
7271
{
7272
    $startDate = strtotime(api_get_local_time($startDate));
7273
    $endDate = strtotime(api_get_local_time($endDate));
7274
    $currentDate = strtotime(api_get_local_time($currentDate));
7275
7276
    if ($currentDate >= $startDate && $currentDate <= $endDate) {
7277
        return true;
7278
    }
7279
7280
    return false;
7281
}
7282
7283
/**
7284
 * Eliminate the duplicates of a multidimensional array by sending the key.
7285
 *
7286
 * @param array $array multidimensional array
7287
 * @param int   $key   key to find to compare
7288
 *
7289
 * @return array
7290
 */
7291
function api_unique_multidim_array($array, $key)
7292
{
7293
    $temp_array = [];
7294
    $i = 0;
7295
    $key_array = [];
7296
7297
    foreach ($array as $val) {
7298
        if (!in_array($val[$key], $key_array)) {
7299
            $key_array[$i] = $val[$key];
7300
            $temp_array[$i] = $val;
7301
        }
7302
        $i++;
7303
    }
7304
7305
    return $temp_array;
7306
}
7307
7308
/**
7309
 * Limit the access to Session Admins when the limit_session_admin_role
7310
 * configuration variable is set to true.
7311
 */
7312
function api_protect_limit_for_session_admin()
7313
{
7314
    $limitAdmin = api_get_setting('limit_session_admin_role');
7315
    if (api_is_session_admin() && 'true' === $limitAdmin) {
7316
        api_not_allowed(true);
7317
    }
7318
}
7319
7320
/**
7321
 * Limits that a session admin has access to list users.
7322
 * When limit_session_admin_list_users configuration variable is set to true.
7323
 */
7324
function api_protect_session_admin_list_users()
7325
{
7326
    $limitAdmin = ('true' === api_get_setting('session.limit_session_admin_list_users'));
7327
7328
    if (api_is_session_admin() && true === $limitAdmin) {
7329
        api_not_allowed(true);
7330
    }
7331
}
7332
7333
/**
7334
 * @return bool
7335
 */
7336
function api_is_student_view_active(): bool
7337
{
7338
    $studentView = Session::read('studentview');
7339
7340
    return 'studentview' === $studentView;
7341
}
7342
7343
/**
7344
 * Converts string value to float value.
7345
 *
7346
 * 3.141516 => 3.141516
7347
 * 3,141516 => 3.141516
7348
 *
7349
 * @todo WIP
7350
 *
7351
 * @param string $number
7352
 *
7353
 * @return float
7354
 */
7355
function api_float_val($number)
7356
{
7357
    return (float) str_replace(',', '.', trim($number));
7358
}
7359
7360
/**
7361
 * Converts float values
7362
 * Example if $decimals = 2.
7363
 *
7364
 * 3.141516 => 3.14
7365
 * 3,141516 => 3,14
7366
 *
7367
 * @param string $number            number in iso code
7368
 * @param int    $decimals
7369
 * @param string $decimalSeparator
7370
 * @param string $thousandSeparator
7371
 *
7372
 * @return bool|string
7373
 */
7374
function api_number_format($number, $decimals = 0, $decimalSeparator = '.', $thousandSeparator = ',')
7375
{
7376
    $number = api_float_val($number);
7377
7378
    return number_format($number, $decimals, $decimalSeparator, $thousandSeparator);
7379
}
7380
7381
/**
7382
 * Set location url with a exit break by default.
7383
 *
7384
 * @param string $url
7385
 * @param bool   $exit
7386
 */
7387
function api_location($url, $exit = true)
7388
{
7389
    header('Location: '.$url);
7390
7391
    if ($exit) {
7392
        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...
7393
    }
7394
}
7395
7396
/**
7397
 * @param string $from
7398
 * @param string $to
7399
 *
7400
 * @return string
7401
 */
7402
function api_get_relative_path($from, $to)
7403
{
7404
    // some compatibility fixes for Windows paths
7405
    $from = is_dir($from) ? rtrim($from, '\/').'/' : $from;
7406
    $to = is_dir($to) ? rtrim($to, '\/').'/' : $to;
7407
    $from = str_replace('\\', '/', $from);
7408
    $to = str_replace('\\', '/', $to);
7409
7410
    $from = explode('/', $from);
7411
    $to = explode('/', $to);
7412
    $relPath = $to;
7413
7414
    foreach ($from as $depth => $dir) {
7415
        // find first non-matching dir
7416
        if ($dir === $to[$depth]) {
7417
            // ignore this directory
7418
            array_shift($relPath);
7419
        } else {
7420
            // get number of remaining dirs to $from
7421
            $remaining = count($from) - $depth;
7422
            if ($remaining > 1) {
7423
                // add traversals up to first matching dir
7424
                $padLength = (count($relPath) + $remaining - 1) * -1;
7425
                $relPath = array_pad($relPath, $padLength, '..');
7426
                break;
7427
            } else {
7428
                $relPath[0] = './'.$relPath[0];
7429
            }
7430
        }
7431
    }
7432
7433
    return implode('/', $relPath);
7434
}
7435
7436
/**
7437
 * @param string $template
7438
 *
7439
 * @return string
7440
 */
7441
function api_find_template($template)
7442
{
7443
    return Template::findTemplateFilePath($template);
7444
}
7445
7446
/**
7447
 * @return array
7448
 */
7449
function api_get_language_list_for_flag()
7450
{
7451
    $table = Database::get_main_table(TABLE_MAIN_LANGUAGE);
7452
    $sql = "SELECT english_name, isocode FROM $table
7453
            ORDER BY original_name ASC";
7454
    static $languages = [];
7455
    if (empty($languages)) {
7456
        $result = Database::query($sql);
7457
        while ($row = Database::fetch_array($result)) {
7458
            $languages[$row['english_name']] = $row['isocode'];
7459
        }
7460
        $languages['english'] = 'gb';
7461
    }
7462
7463
    return $languages;
7464
}
7465
7466
function api_create_zip(string $name): ZipStream
7467
{
7468
    $zipStreamOptions = new Archive();
7469
    $zipStreamOptions->setSendHttpHeaders(true);
7470
    $zipStreamOptions->setContentDisposition('attachment');
7471
    $zipStreamOptions->setContentType('application/x-zip');
7472
7473
    return new ZipStream($name, $zipStreamOptions);
7474
}
7475
7476
function api_get_language_translate_html(): string
7477
{
7478
    $translate = 'true' === api_get_setting('editor.translate_html');
7479
7480
    if (!$translate) {
7481
        return '';
7482
    }
7483
7484
    /*$languageList = api_get_languages();
7485
    $hideAll = '';
7486
    foreach ($languageList as $isocode => $name) {
7487
        $hideAll .= '
7488
        $(".mce-translatehtml").hide();
7489
        $("span:lang('.$isocode.')").filter(
7490
            function(e, val) {
7491
                // Only find the spans if they have set the lang
7492
                if ($(this).attr("lang") == null) {
7493
                    return false;
7494
                }
7495
                // Ignore ckeditor classes
7496
                return !this.className.match(/cke(.*)/);
7497
        }).hide();'."\n";
7498
    }*/
7499
7500
    $userInfo = api_get_user_info();
7501
    if (!empty($userInfo['language'])) {
7502
        $isoCode = $userInfo['language'];
7503
7504
        return '
7505
            $(function() {
7506
                $(".mce-translatehtml").hide();
7507
                var defaultLanguageFromUser = "'.$isoCode.'";
7508
                $("span:lang('.$isoCode.')").show();
7509
            });
7510
        ';
7511
    }
7512
7513
    return '';
7514
}
7515
7516
function api_protect_webservices()
7517
{
7518
    if (api_get_configuration_value('disable_webservices')) {
7519
        echo "Webservices are disabled. \n";
7520
        echo "To enable, add \$_configuration['disable_webservices'] = true; in configuration.php";
7521
        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...
7522
    }
7523
}
7524
7525
/**
7526
 * Checks if a set of roles have a specific permission.
7527
 *
7528
 * @param string $permissionSlug The slug of the permission to check.
7529
 * @param array  $roles          An array of role codes to check against.
7530
 * @return bool True if any of the roles have the permission, false otherwise.
7531
 */
7532
function api_get_permission(string $permissionSlug, array $roles): bool
7533
{
7534
    $permissionService = Container::$container->get(PermissionServiceHelper::class);
7535
7536
    return $permissionService->hasPermission($permissionSlug, $roles);
7537
}
7538