api_set_setting()   F
last analyzed

Complexity

Conditions 23
Paths 2257

Size

Total Lines 87
Code Lines 63

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 23
eloc 63
nc 2257
nop 5
dl 0
loc 87
rs 0
c 0
b 0
f 0

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\Enums\ActionIcon;
13
use Chamilo\CoreBundle\Enums\ObjectIcon;
14
use Chamilo\CoreBundle\Exception\NotAllowedException;
15
use Chamilo\CoreBundle\Framework\Container;
16
use Chamilo\CoreBundle\Helpers\MailHelper;
17
use Chamilo\CoreBundle\Helpers\PermissionHelper;
18
use Chamilo\CoreBundle\Helpers\PluginHelper;
19
use Chamilo\CoreBundle\Helpers\ThemeHelper;
20
use Chamilo\CourseBundle\Entity\CGroup;
21
use Chamilo\CourseBundle\Entity\CLp;
22
use ChamiloSession as Session;
23
use Symfony\Bridge\Twig\Mime\TemplatedEmail;
24
use Symfony\Component\Finder\Finder;
25
use Symfony\Component\Mime\Address;
26
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
27
use Symfony\Component\Security\Core\User\UserInterface;
28
use Symfony\Component\Validator\Constraints as Assert;
29
use ZipStream\Option\Archive;
30
use ZipStream\ZipStream;
31
32
/**
33
 * This is a code library for Chamilo.
34
 * It is included by default in every Chamilo file (through including the global.inc.php)
35
 * This library is in process of being transferred to src/Chamilo/CoreBundle/Helpers/ChamiloHelper.
36
 * Whenever a function is transferred to the ChamiloUtil class, the places where it is used should include
37
 * the "use Chamilo\CoreBundle\Utils\ChamiloUtil;" statement.
38
 */
39
40
// PHP version requirement.
41
define('REQUIRED_PHP_VERSION', '8.2');
42
define('REQUIRED_MIN_MEMORY_LIMIT', '128');
43
define('REQUIRED_MIN_UPLOAD_MAX_FILESIZE', '10');
44
define('REQUIRED_MIN_POST_MAX_SIZE', '10');
45
46
// USER STATUS CONSTANTS
47
/** global status of a user: student */
48
define('STUDENT', 5);
49
/** global status of a user: course manager */
50
define('COURSEMANAGER', 1);
51
/** global status of a user: session admin */
52
define('SESSIONADMIN', 3);
53
/** global status of a user: human resources manager */
54
define('DRH', 4);
55
/** global status of a user: anonymous visitor */
56
define('ANONYMOUS', 6);
57
/** global status of a user: low security, necessary for inserting data from
58
 * the teacher through HTMLPurifier */
59
define('COURSEMANAGERLOWSECURITY', 10);
60
// Soft user status
61
define('PLATFORM_ADMIN', 11);
62
define('SESSION_COURSE_COACH', 12);
63
define('SESSION_GENERAL_COACH', 13);
64
define('COURSE_STUDENT', 14); //student subscribed in a course
65
define('SESSION_STUDENT', 15); //student subscribed in a session course
66
define('COURSE_TUTOR', 16); // student is tutor of a course (NOT in session)
67
define('STUDENT_BOSS', 17); // student is boss
68
define('INVITEE', 20);
69
define('HRM_REQUEST', 21); //HRM has request for linking with user
70
71
// COURSE VISIBILITY CONSTANTS
72
/** only visible for course admin */
73
define('COURSE_VISIBILITY_CLOSED', 0);
74
/** only visible for users registered in the course */
75
define('COURSE_VISIBILITY_REGISTERED', 1);
76
/** Open for all registered users on the platform */
77
define('COURSE_VISIBILITY_OPEN_PLATFORM', 2);
78
/** Open for the whole world */
79
define('COURSE_VISIBILITY_OPEN_WORLD', 3);
80
/** Invisible to all except admin */
81
define('COURSE_VISIBILITY_HIDDEN', 4);
82
83
define('COURSE_REQUEST_PENDING', 0);
84
define('COURSE_REQUEST_ACCEPTED', 1);
85
define('COURSE_REQUEST_REJECTED', 2);
86
define('DELETE_ACTION_ENABLED', false);
87
88
// EMAIL SENDING RECIPIENT CONSTANTS
89
define('SEND_EMAIL_EVERYONE', 1);
90
define('SEND_EMAIL_STUDENTS', 2);
91
define('SEND_EMAIL_TEACHERS', 3);
92
93
// SESSION VISIBILITY CONSTANTS
94
define('SESSION_VISIBLE_READ_ONLY', 1);
95
define('SESSION_VISIBLE', 2);
96
/**
97
 * @deprecated Use Session::INVISIBLE
98
 */
99
define('SESSION_INVISIBLE', 3); // not available
100
define('SESSION_AVAILABLE', 4);
101
102
define('SESSION_LINK_TARGET', '_self');
103
104
define('SUBSCRIBE_ALLOWED', 1);
105
define('SUBSCRIBE_NOT_ALLOWED', 0);
106
define('UNSUBSCRIBE_ALLOWED', 1);
107
define('UNSUBSCRIBE_NOT_ALLOWED', 0);
108
109
// SURVEY VISIBILITY CONSTANTS
110
define('SURVEY_VISIBLE_TUTOR', 0);
111
define('SURVEY_VISIBLE_TUTOR_STUDENT', 1);
112
define('SURVEY_VISIBLE_PUBLIC', 2);
113
114
// CONSTANTS defining all tools, using the english version
115
/* When you add a new tool you must add it into function api_get_tools_lists() too */
116
define('TOOL_DOCUMENT', 'document');
117
define('TOOL_LP_FINAL_ITEM', 'final_item');
118
define('TOOL_READOUT_TEXT', 'readout_text');
119
define('TOOL_THUMBNAIL', 'thumbnail');
120
define('TOOL_HOTPOTATOES', 'hotpotatoes');
121
define('TOOL_CALENDAR_EVENT', 'calendar_event');
122
define('TOOL_LINK', 'link');
123
define('TOOL_LINK_CATEGORY', 'link_category');
124
define('TOOL_COURSE_DESCRIPTION', 'course_description');
125
define('TOOL_SEARCH', 'search');
126
define('TOOL_LEARNPATH', 'learnpath');
127
define('TOOL_LEARNPATH_CATEGORY', 'learnpath_category');
128
define('TOOL_AGENDA', 'agenda');
129
define('TOOL_ANNOUNCEMENT', 'announcement');
130
define('TOOL_FORUM', 'forum');
131
define('TOOL_FORUM_CATEGORY', 'forum_category');
132
define('TOOL_FORUM_THREAD', 'forum_thread');
133
define('TOOL_FORUM_POST', 'forum_post');
134
define('TOOL_FORUM_ATTACH', 'forum_attachment');
135
define('TOOL_FORUM_THREAD_QUALIFY', 'forum_thread_qualify');
136
define('TOOL_THREAD', 'thread');
137
define('TOOL_POST', 'post');
138
define('TOOL_DROPBOX', 'dropbox');
139
define('TOOL_QUIZ', 'quiz');
140
define('TOOL_TEST_CATEGORY', 'test_category');
141
define('TOOL_USER', 'user');
142
define('TOOL_GROUP', 'group');
143
define('TOOL_BLOGS', 'blog_management');
144
define('TOOL_CHAT', 'chat');
145
define('TOOL_STUDENTPUBLICATION', 'student_publication');
146
define('TOOL_TRACKING', 'tracking');
147
define('TOOL_HOMEPAGE_LINK', 'homepage_link');
148
define('TOOL_COURSE_SETTING', 'course_setting');
149
define('TOOL_BACKUP', 'backup');
150
define('TOOL_COPY_COURSE_CONTENT', 'copy_course_content');
151
define('TOOL_RECYCLE_COURSE', 'recycle_course');
152
define('TOOL_COURSE_HOMEPAGE', 'course_homepage');
153
define('TOOL_COURSE_RIGHTS_OVERVIEW', 'course_rights');
154
define('TOOL_UPLOAD', 'file_upload');
155
define('TOOL_COURSE_MAINTENANCE', 'course_maintenance');
156
define('TOOL_SURVEY', 'survey');
157
//define('TOOL_WIKI', 'wiki');
158
define('TOOL_GLOSSARY', 'glossary');
159
define('TOOL_GRADEBOOK', 'gradebook');
160
define('TOOL_NOTEBOOK', 'notebook');
161
define('TOOL_ATTENDANCE', 'attendance');
162
define('TOOL_COURSE_PROGRESS', 'course_progress');
163
define('TOOL_PORTFOLIO', 'portfolio');
164
define('TOOL_PLAGIARISM', 'compilatio');
165
define('TOOL_XAPI', 'xapi');
166
167
// CONSTANTS defining Chamilo interface sections
168
define('SECTION_CAMPUS', 'mycampus');
169
define('SECTION_COURSES', 'mycourses');
170
define('SECTION_CATALOG', 'catalog');
171
define('SECTION_MYPROFILE', 'myprofile');
172
define('SECTION_MYAGENDA', 'myagenda');
173
define('SECTION_COURSE_ADMIN', 'course_admin');
174
define('SECTION_PLATFORM_ADMIN', 'platform_admin');
175
define('SECTION_MYGRADEBOOK', 'mygradebook');
176
define('SECTION_TRACKING', 'session_my_space');
177
define('SECTION_SOCIAL', 'social-network');
178
define('SECTION_DASHBOARD', 'dashboard');
179
define('SECTION_REPORTS', 'reports');
180
define('SECTION_GLOBAL', 'global');
181
define('SECTION_INCLUDE', 'include');
182
define('SECTION_CUSTOMPAGE', 'custompage');
183
184
// event logs types
185
define('LOG_COURSE_DELETE', 'course_deleted');
186
define('LOG_COURSE_CREATE', 'course_created');
187
define('LOG_COURSE_SETTINGS_CHANGED', 'course_settings_changed');
188
189
// @todo replace 'soc_gr' with social_group
190
define('LOG_GROUP_PORTAL_CREATED', 'soc_gr_created');
191
define('LOG_GROUP_PORTAL_UPDATED', 'soc_gr_updated');
192
define('LOG_GROUP_PORTAL_DELETED', 'soc_gr_deleted');
193
define('LOG_GROUP_PORTAL_USER_DELETE_ALL', 'soc_gr_delete_users');
194
195
define('LOG_GROUP_PORTAL_ID', 'soc_gr_portal_id');
196
define('LOG_GROUP_PORTAL_REL_USER_ARRAY', 'soc_gr_user_array');
197
198
define('LOG_GROUP_PORTAL_USER_SUBSCRIBED', 'soc_gr_u_subs');
199
define('LOG_GROUP_PORTAL_USER_UNSUBSCRIBED', 'soc_gr_u_unsubs');
200
define('LOG_GROUP_PORTAL_USER_UPDATE_ROLE', 'soc_gr_update_role');
201
202
define('LOG_MESSAGE_DATA', 'message_data');
203
define('LOG_MESSAGE_DELETE', 'msg_deleted');
204
205
const LOG_RESOURCE_LINK_DELETE = 'resource_link_deleted';
206
const LOG_RESOURCE_LINK_SOFT_DELETE = 'resource_link_soft_deleted';
207
const LOG_RESOURCE_NODE = 'resource_node_id';
208
const LOG_RESOURCE_LINK = 'resource_link_id';
209
const LOG_RESOURCE_NODE_AND_RESOURCE_LINK = 'resource_node_id_and_resource_link_id';
210
211
define('LOG_USER_DELETE', 'user_deleted');
212
define('LOG_USER_PREDELETE', 'user_predeleted');
213
define('LOG_USER_CREATE', 'user_created');
214
define('LOG_USER_UPDATE', 'user_updated');
215
define('LOG_USER_PASSWORD_UPDATE', 'user_password_updated');
216
define('LOG_USER_ENABLE', 'user_enable');
217
define('LOG_USER_DISABLE', 'user_disable');
218
define('LOG_USER_ANONYMIZE', 'user_anonymized');
219
define('LOG_USER_FIELD_CREATE', 'user_field_created');
220
define('LOG_USER_FIELD_DELETE', 'user_field_deleted');
221
define('LOG_SESSION_CREATE', 'session_created');
222
define('LOG_SESSION_DELETE', 'session_deleted');
223
define('LOG_SESSION_ADD_USER_COURSE', 'session_add_user_course');
224
define('LOG_SESSION_DELETE_USER_COURSE', 'session_delete_user_course');
225
define('LOG_SESSION_ADD_USER', 'session_add_user');
226
define('LOG_SESSION_DELETE_USER', 'session_delete_user');
227
define('LOG_SESSION_ADD_COURSE', 'session_add_course');
228
define('LOG_SESSION_DELETE_COURSE', 'session_delete_course');
229
define('LOG_SESSION_CATEGORY_CREATE', 'session_cat_created'); //changed in 1.9.8
230
define('LOG_SESSION_CATEGORY_DELETE', 'session_cat_deleted'); //changed in 1.9.8
231
define('LOG_CONFIGURATION_SETTINGS_CHANGE', 'settings_changed');
232
define('LOG_PLATFORM_LANGUAGE_CHANGE', 'platform_lng_changed'); //changed in 1.9.8
233
define('LOG_SUBSCRIBE_USER_TO_COURSE', 'user_subscribed');
234
define('LOG_UNSUBSCRIBE_USER_FROM_COURSE', 'user_unsubscribed');
235
define('LOG_ATTEMPTED_FORCED_LOGIN', 'attempted_forced_login');
236
define('LOG_PLUGIN_CHANGE', 'plugin_changed');
237
define('LOG_HOMEPAGE_CHANGED', 'homepage_changed');
238
define('LOG_PROMOTION_CREATE', 'promotion_created');
239
define('LOG_PROMOTION_DELETE', 'promotion_deleted');
240
define('LOG_CAREER_CREATE', 'career_created');
241
define('LOG_CAREER_DELETE', 'career_deleted');
242
define('LOG_USER_PERSONAL_DOC_DELETED', 'user_doc_deleted');
243
//define('LOG_WIKI_ACCESS', 'wiki_page_view');
244
// All results from an exercise
245
define('LOG_EXERCISE_RESULT_DELETE', 'exe_result_deleted');
246
// Logs only the one attempt
247
define('LOG_EXERCISE_ATTEMPT_DELETE', 'exe_attempt_deleted');
248
define('LOG_LP_ATTEMPT_DELETE', 'lp_attempt_deleted');
249
define('LOG_QUESTION_RESULT_DELETE', 'qst_attempt_deleted');
250
define('LOG_QUESTION_SCORE_UPDATE', 'score_attempt_updated');
251
252
define('LOG_MY_FOLDER_CREATE', 'my_folder_created');
253
define('LOG_MY_FOLDER_CHANGE', 'my_folder_changed');
254
define('LOG_MY_FOLDER_DELETE', 'my_folder_deleted');
255
define('LOG_MY_FOLDER_COPY', 'my_folder_copied');
256
define('LOG_MY_FOLDER_CUT', 'my_folder_cut');
257
define('LOG_MY_FOLDER_PASTE', 'my_folder_pasted');
258
define('LOG_MY_FOLDER_UPLOAD', 'my_folder_uploaded');
259
260
// Event logs data types (max 20 chars)
261
define('LOG_COURSE_CODE', 'course_code');
262
define('LOG_COURSE_ID', 'course_id');
263
define('LOG_USER_ID', 'user_id');
264
define('LOG_USER_OBJECT', 'user_object');
265
define('LOG_USER_FIELD_VARIABLE', 'user_field_variable');
266
define('LOG_SESSION_ID', 'session_id');
267
268
define('LOG_QUESTION_ID', 'question_id');
269
define('LOG_SESSION_CATEGORY_ID', 'session_category_id');
270
define('LOG_CONFIGURATION_SETTINGS_CATEGORY', 'settings_category');
271
define('LOG_CONFIGURATION_SETTINGS_VARIABLE', 'settings_variable');
272
define('LOG_PLATFORM_LANGUAGE', 'default_platform_language');
273
define('LOG_PLUGIN_UPLOAD', 'plugin_upload');
274
define('LOG_PLUGIN_ENABLE', 'plugin_enable');
275
define('LOG_PLUGIN_SETTINGS_CHANGE', 'plugin_settings_change');
276
define('LOG_CAREER_ID', 'career_id');
277
define('LOG_PROMOTION_ID', 'promotion_id');
278
define('LOG_GRADEBOOK_LOCKED', 'gradebook_locked');
279
define('LOG_GRADEBOOK_UNLOCKED', 'gradebook_unlocked');
280
define('LOG_GRADEBOOK_ID', 'gradebook_id');
281
//define('LOG_WIKI_PAGE_ID', 'wiki_page_id');
282
define('LOG_EXERCISE_ID', 'exercise_id');
283
define('LOG_EXERCISE_AND_USER_ID', 'exercise_and_user_id');
284
define('LOG_LP_ID', 'lp_id');
285
define('LOG_EXERCISE_ATTEMPT_QUESTION_ID', 'exercise_a_q_id');
286
define('LOG_EXERCISE_ATTEMPT', 'exe_id');
287
288
define('LOG_WORK_DIR_DELETE', 'work_dir_delete');
289
define('LOG_WORK_FILE_DELETE', 'work_file_delete');
290
define('LOG_WORK_DATA', 'work_data_array');
291
292
define('LOG_MY_FOLDER_PATH', 'path');
293
define('LOG_MY_FOLDER_NEW_PATH', 'new_path');
294
295
define('LOG_TERM_CONDITION_ACCEPTED', 'term_condition_accepted');
296
define('LOG_USER_CONFIRMED_EMAIL', 'user_confirmed_email');
297
define('LOG_USER_REMOVED_LEGAL_ACCEPT', 'user_removed_legal_accept');
298
299
define('LOG_USER_DELETE_ACCOUNT_REQUEST', 'user_delete_account_request');
300
301
define('LOG_QUESTION_CREATED', 'question_created');
302
define('LOG_QUESTION_UPDATED', 'question_updated');
303
define('LOG_QUESTION_DELETED', 'question_deleted');
304
define('LOG_QUESTION_REMOVED_FROM_QUIZ', 'question_removed_from_quiz');
305
306
define('LOG_SURVEY_ID', 'survey_id');
307
define('LOG_SURVEY_CREATED', 'survey_created');
308
define('LOG_SURVEY_DELETED', 'survey_deleted');
309
define('LOG_SURVEY_CLEAN_RESULTS', 'survey_clean_results');
310
define('USERNAME_PURIFIER', '/[^0-9A-Za-z_\.@\$-]/');
311
312
//used when login_is_email setting is true
313
define('USERNAME_PURIFIER_MAIL', '/[^0-9A-Za-z_\.@]/');
314
define('USERNAME_PURIFIER_SHALLOW', '/\s/');
315
316
// This constant is a result of Windows OS detection, it has a boolean value:
317
// true whether the server runs on Windows OS, false otherwise.
318
define('IS_WINDOWS_OS', api_is_windows_os());
319
320
// Patterns for processing paths. Examples.
321
define('REPEATED_SLASHES_PURIFIER', '/\/{2,}/'); // $path = preg_replace(REPEATED_SLASHES_PURIFIER, '/', $path);
322
define('VALID_WEB_PATH', '/https?:\/\/[^\/]*(\/.*)?/i'); // $is_valid_path = preg_match(VALID_WEB_PATH, $path);
323
// $new_path = preg_replace(VALID_WEB_SERVER_BASE, $new_base, $path);
324
define('VALID_WEB_SERVER_BASE', '/https?:\/\/[^\/]*/i');
325
// Constants for api_get_path() and api_get_path_type(), etc. - registered path types.
326
// basic (leaf elements)
327
define('REL_CODE_PATH', 'REL_CODE_PATH');
328
define('REL_COURSE_PATH', 'REL_COURSE_PATH');
329
define('REL_HOME_PATH', 'REL_HOME_PATH');
330
331
// Constants for api_get_path() and api_get_path_type(), etc. - registered path types.
332
define('WEB_PATH', 'WEB_PATH');
333
define('SYS_PATH', 'SYS_PATH');
334
define('SYMFONY_SYS_PATH', 'SYMFONY_SYS_PATH');
335
336
define('REL_PATH', 'REL_PATH');
337
define('WEB_COURSE_PATH', 'WEB_COURSE_PATH');
338
define('WEB_CODE_PATH', 'WEB_CODE_PATH');
339
define('SYS_CODE_PATH', 'SYS_CODE_PATH');
340
define('SYS_LANG_PATH', 'SYS_LANG_PATH');
341
define('WEB_IMG_PATH', 'WEB_IMG_PATH');
342
define('WEB_CSS_PATH', 'WEB_CSS_PATH');
343
define('WEB_PUBLIC_PATH', 'WEB_PUBLIC_PATH');
344
define('SYS_CSS_PATH', 'SYS_CSS_PATH');
345
define('SYS_PLUGIN_PATH', 'SYS_PLUGIN_PATH');
346
define('WEB_PLUGIN_PATH', 'WEB_PLUGIN_PATH');
347
define('WEB_PLUGIN_ASSET_PATH', 'WEB_PLUGIN_ASSET_PATH');
348
define('SYS_ARCHIVE_PATH', 'SYS_ARCHIVE_PATH');
349
define('WEB_ARCHIVE_PATH', 'WEB_ARCHIVE_PATH');
350
define('LIBRARY_PATH', 'LIBRARY_PATH');
351
define('CONFIGURATION_PATH', 'CONFIGURATION_PATH');
352
define('WEB_LIBRARY_PATH', 'WEB_LIBRARY_PATH');
353
define('WEB_LIBRARY_JS_PATH', 'WEB_LIBRARY_JS_PATH');
354
define('WEB_AJAX_PATH', 'WEB_AJAX_PATH');
355
define('SYS_TEST_PATH', 'SYS_TEST_PATH');
356
define('SYS_TEMPLATE_PATH', 'SYS_TEMPLATE_PATH');
357
define('SYS_PUBLIC_PATH', 'SYS_PUBLIC_PATH');
358
define('SYS_FONTS_PATH', 'SYS_FONTS_PATH');
359
360
// Relations type with Course manager
361
define('COURSE_RELATION_TYPE_COURSE_MANAGER', 1);
362
363
// Relations type with Human resources manager
364
define('COURSE_RELATION_TYPE_RRHH', 1);
365
366
// User image sizes
367
define('USER_IMAGE_SIZE_ORIGINAL', 1);
368
define('USER_IMAGE_SIZE_BIG', 2);
369
define('USER_IMAGE_SIZE_MEDIUM', 3);
370
define('USER_IMAGE_SIZE_SMALL', 4);
371
372
// Gradebook link constants
373
// Please do not change existing values, they are used in the database !
374
define('GRADEBOOK_ITEM_LIMIT', 1000);
375
376
define('LINK_EXERCISE', 1);
377
define('LINK_DROPBOX', 2);
378
define('LINK_STUDENTPUBLICATION', 3);
379
define('LINK_LEARNPATH', 4);
380
define('LINK_FORUM_THREAD', 5);
381
//define('LINK_WORK',6);
382
define('LINK_ATTENDANCE', 7);
383
define('LINK_SURVEY', 8);
384
define('LINK_HOTPOTATOES', 9);
385
define('LINK_PORTFOLIO', 10);
386
387
// Score display types constants
388
define('SCORE_DIV', 1); // X / Y
389
define('SCORE_PERCENT', 2); // XX %
390
define('SCORE_DIV_PERCENT', 3); // X / Y (XX %)
391
define('SCORE_AVERAGE', 4); // XX %
392
define('SCORE_DECIMAL', 5); // 0.50  (X/Y)
393
define('SCORE_BAR', 6); // Uses the Display::bar_progress function
394
define('SCORE_SIMPLE', 7); // X
395
define('SCORE_IGNORE_SPLIT', 8); //  ??
396
define('SCORE_DIV_PERCENT_WITH_CUSTOM', 9); // X / Y (XX %) - Good!
397
define('SCORE_CUSTOM', 10); // Good!
398
define('SCORE_DIV_SIMPLE_WITH_CUSTOM', 11); // X - Good!
399
define('SCORE_DIV_SIMPLE_WITH_CUSTOM_LETTERS', 12); // X - Good!
400
define('SCORE_ONLY_SCORE', 13); // X - Good!
401
define('SCORE_NUMERIC', 14);
402
403
define('SCORE_BOTH', 1);
404
define('SCORE_ONLY_DEFAULT', 2);
405
define('SCORE_ONLY_CUSTOM', 3);
406
407
// From display.lib.php
408
409
define('MAX_LENGTH_BREADCRUMB', 100);
410
define('ICON_SIZE_ATOM', 8);
411
define('ICON_SIZE_TINY', 16);
412
define('ICON_SIZE_SMALL', 22);
413
define('ICON_SIZE_MEDIUM', 32);
414
define('ICON_SIZE_LARGE', 48);
415
define('ICON_SIZE_BIG', 64);
416
define('ICON_SIZE_HUGE', 128);
417
define('SHOW_TEXT_NEAR_ICONS', false);
418
419
// Session catalog
420
define('CATALOG_COURSES', 0);
421
define('CATALOG_SESSIONS', 1);
422
define('CATALOG_COURSES_SESSIONS', 2);
423
424
// Hook type events, pre-process and post-process.
425
// All means to be executed for both hook event types
426
define('HOOK_EVENT_TYPE_PRE', 0);
427
define('HOOK_EVENT_TYPE_POST', 1);
428
define('HOOK_EVENT_TYPE_ALL', 10);
429
430
// Group permissions
431
define('GROUP_PERMISSION_OPEN', '1');
432
define('GROUP_PERMISSION_CLOSED', '2');
433
434
// Group user permissions
435
define('GROUP_USER_PERMISSION_ADMIN', 1); // the admin of a group
436
define('GROUP_USER_PERMISSION_READER', 2); // a normal user
437
define('GROUP_USER_PERMISSION_PENDING_INVITATION', 3); // When an admin/moderator invites a user
438
define('GROUP_USER_PERMISSION_PENDING_INVITATION_SENT_BY_USER', 4); // an user joins a group
439
define('GROUP_USER_PERMISSION_MODERATOR', 5); // a moderator
440
define('GROUP_USER_PERMISSION_ANONYMOUS', 6); // an anonymous user
441
define('GROUP_USER_PERMISSION_HRM', 7); // a human resources manager
442
443
define('GROUP_IMAGE_SIZE_ORIGINAL', 1);
444
define('GROUP_IMAGE_SIZE_BIG', 2);
445
define('GROUP_IMAGE_SIZE_MEDIUM', 3);
446
define('GROUP_IMAGE_SIZE_SMALL', 4);
447
define('GROUP_TITLE_LENGTH', 50);
448
449
// Exercise
450
// @todo move into a class
451
define('ALL_ON_ONE_PAGE', 1);
452
define('ONE_PER_PAGE', 2);
453
454
define('EXERCISE_FEEDBACK_TYPE_END', 0); //Feedback 		 - show score and expected answers
455
define('EXERCISE_FEEDBACK_TYPE_DIRECT', 1); //DirectFeedback - Do not show score nor answers
456
define('EXERCISE_FEEDBACK_TYPE_EXAM', 2); // NoFeedback 	 - Show score only
457
define('EXERCISE_FEEDBACK_TYPE_POPUP', 3); // Popup BT#15827
458
459
define('RESULT_DISABLE_SHOW_SCORE_AND_EXPECTED_ANSWERS', 0); //show score and expected answers
460
define('RESULT_DISABLE_NO_SCORE_AND_EXPECTED_ANSWERS', 1); //Do not show score nor answers
461
define('RESULT_DISABLE_SHOW_SCORE_ONLY', 2); //Show score only
462
define('RESULT_DISABLE_SHOW_FINAL_SCORE_ONLY_WITH_CATEGORIES', 3); //Show final score only with categories
463
define('RESULT_DISABLE_SHOW_SCORE_ATTEMPT_SHOW_ANSWERS_LAST_ATTEMPT', 4);
464
define('RESULT_DISABLE_DONT_SHOW_SCORE_ONLY_IF_USER_FINISHES_ATTEMPTS_SHOW_ALWAYS_FEEDBACK', 5);
465
define('RESULT_DISABLE_RANKING', 6);
466
define('RESULT_DISABLE_SHOW_ONLY_IN_CORRECT_ANSWER', 7);
467
define('RESULT_DISABLE_SHOW_SCORE_AND_EXPECTED_ANSWERS_AND_RANKING', 8);
468
define('RESULT_DISABLE_RADAR', 9);
469
define('RESULT_DISABLE_SHOW_SCORE_ATTEMPT_SHOW_ANSWERS_LAST_ATTEMPT_NO_FEEDBACK', 10);
470
471
define('EXERCISE_MAX_NAME_SIZE', 80);
472
473
// Question types (edit next array as well when adding values)
474
// @todo move into a class
475
define('UNIQUE_ANSWER', 1);
476
define('MULTIPLE_ANSWER', 2);
477
define('FILL_IN_BLANKS', 3);
478
define('MATCHING', 4);
479
define('FREE_ANSWER', 5);
480
define('HOT_SPOT', 6);
481
define('HOT_SPOT_ORDER', 7);
482
define('HOT_SPOT_DELINEATION', 8);
483
define('MULTIPLE_ANSWER_COMBINATION', 9);
484
define('UNIQUE_ANSWER_NO_OPTION', 10);
485
define('MULTIPLE_ANSWER_TRUE_FALSE', 11);
486
define('MULTIPLE_ANSWER_COMBINATION_TRUE_FALSE', 12);
487
define('ORAL_EXPRESSION', 13);
488
define('GLOBAL_MULTIPLE_ANSWER', 14);
489
define('MEDIA_QUESTION', 15);
490
define('CALCULATED_ANSWER', 16);
491
define('UNIQUE_ANSWER_IMAGE', 17);
492
define('DRAGGABLE', 18);
493
define('MATCHING_DRAGGABLE', 19);
494
define('ANNOTATION', 20);
495
define('READING_COMPREHENSION', 21);
496
define('MULTIPLE_ANSWER_TRUE_FALSE_DEGREE_CERTAINTY', 22);
497
498
define('EXERCISE_CATEGORY_RANDOM_SHUFFLED', 1);
499
define('EXERCISE_CATEGORY_RANDOM_ORDERED', 2);
500
define('EXERCISE_CATEGORY_RANDOM_DISABLED', 0);
501
502
// Question selection type
503
define('EX_Q_SELECTION_ORDERED', 1);
504
define('EX_Q_SELECTION_RANDOM', 2);
505
define('EX_Q_SELECTION_CATEGORIES_ORDERED_QUESTIONS_ORDERED', 3);
506
define('EX_Q_SELECTION_CATEGORIES_RANDOM_QUESTIONS_ORDERED', 4);
507
define('EX_Q_SELECTION_CATEGORIES_ORDERED_QUESTIONS_RANDOM', 5);
508
define('EX_Q_SELECTION_CATEGORIES_RANDOM_QUESTIONS_RANDOM', 6);
509
define('EX_Q_SELECTION_CATEGORIES_RANDOM_QUESTIONS_ORDERED_NO_GROUPED', 7);
510
define('EX_Q_SELECTION_CATEGORIES_RANDOM_QUESTIONS_RANDOM_NO_GROUPED', 8);
511
define('EX_Q_SELECTION_CATEGORIES_ORDERED_BY_PARENT_QUESTIONS_ORDERED', 9);
512
define('EX_Q_SELECTION_CATEGORIES_ORDERED_BY_PARENT_QUESTIONS_RANDOM', 10);
513
514
// Used to save the skill_rel_item table
515
define('ITEM_TYPE_EXERCISE', 1);
516
define('ITEM_TYPE_HOTPOTATOES', 2);
517
define('ITEM_TYPE_LINK', 3);
518
define('ITEM_TYPE_LEARNPATH', 4);
519
define('ITEM_TYPE_GRADEBOOK', 5);
520
define('ITEM_TYPE_STUDENT_PUBLICATION', 6);
521
//define('ITEM_TYPE_FORUM', 7);
522
define('ITEM_TYPE_ATTENDANCE', 8);
523
define('ITEM_TYPE_SURVEY', 9);
524
define('ITEM_TYPE_FORUM_THREAD', 10);
525
define('ITEM_TYPE_PORTFOLIO', 11);
526
527
// Course description blocks.
528
define('ADD_BLOCK', 8);
529
530
// one big string with all question types, for the validator in pear/HTML/QuickForm/Rule/QuestionType
531
define(
532
    'QUESTION_TYPES',
533
    UNIQUE_ANSWER.':'.
534
    MULTIPLE_ANSWER.':'.
535
    FILL_IN_BLANKS.':'.
536
    MATCHING.':'.
537
    FREE_ANSWER.':'.
538
    HOT_SPOT.':'.
539
    HOT_SPOT_ORDER.':'.
540
    HOT_SPOT_DELINEATION.':'.
541
    MULTIPLE_ANSWER_COMBINATION.':'.
542
    UNIQUE_ANSWER_NO_OPTION.':'.
543
    MULTIPLE_ANSWER_TRUE_FALSE.':'.
544
    MULTIPLE_ANSWER_COMBINATION_TRUE_FALSE.':'.
545
    ORAL_EXPRESSION.':'.
546
    GLOBAL_MULTIPLE_ANSWER.':'.
547
    MEDIA_QUESTION.':'.
548
    CALCULATED_ANSWER.':'.
549
    UNIQUE_ANSWER_IMAGE.':'.
550
    DRAGGABLE.':'.
551
    MATCHING_DRAGGABLE.':'.
552
    MULTIPLE_ANSWER_TRUE_FALSE_DEGREE_CERTAINTY.':'.
553
    ANNOTATION
554
);
555
556
//Some alias used in the QTI exports
557
define('MCUA', 1);
558
define('TF', 1);
559
define('MCMA', 2);
560
define('FIB', 3);
561
562
// Message
563
define('MESSAGE_STATUS_INVITATION_PENDING', 5);
564
define('MESSAGE_STATUS_INVITATION_ACCEPTED', 6);
565
define('MESSAGE_STATUS_INVITATION_DENIED', 7);
566
define('MESSAGE_STATUS_WALL', 8);
567
568
define('MESSAGE_STATUS_WALL_DELETE', 9);
569
define('MESSAGE_STATUS_WALL_POST', 10);
570
571
define('MESSAGE_STATUS_FORUM', 12);
572
define('MESSAGE_STATUS_PROMOTED', 13);
573
574
// Images
575
define('IMAGE_WALL_SMALL_SIZE', 200);
576
define('IMAGE_WALL_MEDIUM_SIZE', 500);
577
define('IMAGE_WALL_BIG_SIZE', 2000);
578
define('IMAGE_WALL_SMALL', 'small');
579
define('IMAGE_WALL_MEDIUM', 'medium');
580
define('IMAGE_WALL_BIG', 'big');
581
582
// Social PLUGIN PLACES
583
define('SOCIAL_LEFT_PLUGIN', 1);
584
define('SOCIAL_CENTER_PLUGIN', 2);
585
define('SOCIAL_RIGHT_PLUGIN', 3);
586
define('CUT_GROUP_NAME', 50);
587
588
/**
589
 * FormValidator Filter.
590
 */
591
define('NO_HTML', 1);
592
define('STUDENT_HTML', 2);
593
define('TEACHER_HTML', 3);
594
define('STUDENT_HTML_FULLPAGE', 4);
595
define('TEACHER_HTML_FULLPAGE', 5);
596
597
// Timeline
598
define('TIMELINE_STATUS_ACTIVE', '1');
599
define('TIMELINE_STATUS_INACTIVE', '2');
600
601
// Event email template class
602
define('EVENT_EMAIL_TEMPLATE_ACTIVE', 1);
603
define('EVENT_EMAIL_TEMPLATE_INACTIVE', 0);
604
605
// Course home
606
define('SHORTCUTS_HORIZONTAL', 0);
607
define('SHORTCUTS_VERTICAL', 1);
608
609
// Course copy
610
define('FILE_SKIP', 1);
611
define('FILE_RENAME', 2);
612
define('FILE_OVERWRITE', 3);
613
define('UTF8_CONVERT', false); //false by default
614
615
define('DOCUMENT', 'file');
616
define('FOLDER', 'folder');
617
618
define('RESOURCE_ASSET', 'asset');
619
define('RESOURCE_DOCUMENT', 'document');
620
define('RESOURCE_GLOSSARY', 'glossary');
621
define('RESOURCE_EVENT', 'calendar_event');
622
define('RESOURCE_LINK', 'link');
623
define('RESOURCE_COURSEDESCRIPTION', 'course_description');
624
define('RESOURCE_LEARNPATH', 'learnpath');
625
define('RESOURCE_LEARNPATH_CATEGORY', 'learnpath_category');
626
define('RESOURCE_ANNOUNCEMENT', 'announcement');
627
define('RESOURCE_FORUM', 'forum');
628
define('RESOURCE_FORUMTOPIC', 'thread');
629
define('RESOURCE_FORUMPOST', 'post');
630
define('RESOURCE_QUIZ', 'quiz');
631
define('RESOURCE_TEST_CATEGORY', 'test_category');
632
define('RESOURCE_QUIZQUESTION', 'Exercise_Question');
633
define('RESOURCE_TOOL_INTRO', 'Tool introduction');
634
define('RESOURCE_LINKCATEGORY', 'Link_Category');
635
define('RESOURCE_FORUMCATEGORY', 'Forum_Category');
636
define('RESOURCE_SCORM', 'Scorm');
637
define('RESOURCE_SURVEY', 'survey');
638
define('RESOURCE_SURVEYQUESTION', 'survey_question');
639
define('RESOURCE_SURVEYINVITATION', 'survey_invitation');
640
define('RESOURCE_WIKI', 'wiki');
641
define('RESOURCE_THEMATIC', 'thematic');
642
define('RESOURCE_ATTENDANCE', 'attendance');
643
define('RESOURCE_WORK', 'work');
644
define('RESOURCE_SESSION_COURSE', 'session_course');
645
define('RESOURCE_GRADEBOOK', 'gradebook');
646
define('ADD_THEMATIC_PLAN', 6);
647
648
// Max online users to show per page (whoisonline)
649
define('MAX_ONLINE_USERS', 12);
650
651
define('TOOL_AUTHORING', 'toolauthoring');
652
define('TOOL_INTERACTION', 'toolinteraction');
653
define('TOOL_COURSE_PLUGIN', 'toolcourseplugin'); //all plugins that can be enabled in courses
654
define('TOOL_ADMIN', 'tooladmin');
655
define('TOOL_ADMIN_PLATFORM', 'tooladminplatform');
656
define('TOOL_DRH', 'tool_drh');
657
define('TOOL_STUDENT_VIEW', 'toolstudentview');
658
define('TOOL_ADMIN_VISIBLE', 'tooladminvisible');
659
660
// Search settings (from main/inc/lib/search/IndexableChunk.class.php )
661
// some constants to avoid serialize string keys on serialized data array
662
define('SE_COURSE_ID', 0);
663
define('SE_TOOL_ID', 1);
664
define('SE_DATA', 2);
665
define('SE_USER', 3);
666
667
// in some cases we need top differenciate xapian documents of the same tool
668
define('SE_DOCTYPE_EXERCISE_EXERCISE', 0);
669
define('SE_DOCTYPE_EXERCISE_QUESTION', 1);
670
671
// xapian prefixes
672
define('XAPIAN_PREFIX_COURSEID', 'C');
673
define('XAPIAN_PREFIX_TOOLID', 'O');
674
675
// User active field constants
676
define('USER_ACTIVE', 1);
677
define('USER_INACTIVE', 0);
678
define('USER_INACTIVE_AUTOMATIC', -1);
679
define('USER_SOFT_DELETED', -2);
680
681
/**
682
 * Returns a path to a certain resource within Chamilo.
683
 *
684
 * @param string $path A path which type is to be converted. Also, it may be a defined constant for a path.
685
 *
686
 * @return string the requested path or the converted path
687
 *
688
 * Notes about the current behaviour model:
689
 * 1. Windows back-slashes are converted to slashes in the result.
690
 * 2. A semi-absolute web-path is detected by its leading slash. On Linux systems, absolute system paths start with
691
 * a slash too, so an additional check about presence of leading system server base is implemented. For example, the function is
692
 * able to distinguish type difference between /var/www/chamilo/courses/ (SYS) and /chamilo/courses/ (REL).
693
 * 3. The function api_get_path() returns only these three types of paths, which in some sense are absolute. The function has
694
 * no a mechanism for processing relative web/system paths, such as: lesson01.html, ./lesson01.html, ../css/my_styles.css.
695
 * It has not been identified as needed yet.
696
 * 4. Also, resolving the meta-symbols "." and ".." within paths has not been implemented, it is to be identified as needed.
697
 *
698
 * Vchamilo changes : allow using an alternate configuration
699
 * to get vchamilo  instance paths
700
 */
701
function api_get_path($path = '', $configuration = [])
702
{
703
    global $paths;
704
705
    // get proper configuration data if exists
706
    global $_configuration;
707
708
    $emptyConfigurationParam = false;
709
    if (empty($configuration)) {
710
        $configuration = (array) $_configuration;
711
        $emptyConfigurationParam = true;
712
    }
713
714
    $root_sys = Container::getProjectDir();
715
    $root_web = '';
716
    if (isset(Container::$container)) {
717
        $root_web = Container::$container->get('router')->generate(
718
            'index',
719
            [],
720
            UrlGeneratorInterface::ABSOLUTE_URL
721
        );
722
    }
723
724
    /*if (api_get_multiple_access_url()) {
725
        // To avoid that the api_get_access_url() function fails since global.inc.php also calls the main_api.lib.php
726
        if (isset($configuration['access_url']) && !empty($configuration['access_url'])) {
727
            // We look into the DB the function api_get_access_url
728
            $urlInfo = api_get_access_url($configuration['access_url']);
729
            // Avoid default value
730
            $defaultValues = ['http://localhost/', 'https://localhost/'];
731
            if (!empty($urlInfo['url']) && !in_array($urlInfo['url'], $defaultValues)) {
732
                $root_web = 1 == $urlInfo['active'] ? $urlInfo['url'] : $configuration['root_web'];
733
            }
734
        }
735
    }*/
736
737
    $paths = [
738
        WEB_PATH => $root_web,
739
        SYMFONY_SYS_PATH => $root_sys,
740
        SYS_PATH => $root_sys.'public/',
741
        REL_PATH => '',
742
        CONFIGURATION_PATH => 'app/config/',
743
        LIBRARY_PATH => $root_sys.'public/main/inc/lib/',
744
745
        REL_COURSE_PATH => '',
746
        REL_CODE_PATH => '/main/',
747
748
        SYS_CODE_PATH => $root_sys.'public/main/',
749
        SYS_CSS_PATH => $root_sys.'public/build/css/',
750
        SYS_PLUGIN_PATH => $root_sys.'public/plugin/',
751
        SYS_ARCHIVE_PATH => $root_sys.'var/cache/',
752
        SYS_TEST_PATH => $root_sys.'tests/',
753
        SYS_TEMPLATE_PATH => $root_sys.'public/main/template/',
754
        SYS_PUBLIC_PATH => $root_sys.'public/',
755
        SYS_FONTS_PATH => $root_sys.'public/fonts/',
756
757
        WEB_CODE_PATH => $root_web.'main/',
758
        WEB_PLUGIN_ASSET_PATH => $root_web.'plugins/',
759
        WEB_COURSE_PATH => $root_web.'course/',
760
        WEB_IMG_PATH => $root_web.'img/',
761
        WEB_CSS_PATH => $root_web.'build/css/',
762
        WEB_AJAX_PATH => $root_web.'main/inc/ajax/',
763
        WEB_LIBRARY_PATH => $root_web.'main/inc/lib/',
764
        WEB_LIBRARY_JS_PATH => $root_web.'main/inc/lib/javascript/',
765
        WEB_PLUGIN_PATH => $root_web.'plugin/',
766
        WEB_PUBLIC_PATH => $root_web,
767
    ];
768
769
    $root_rel = '';
770
771
    global $virtualChamilo;
772
    if (!empty($virtualChamilo)) {
773
        $paths[SYS_ARCHIVE_PATH] = api_add_trailing_slash($virtualChamilo[SYS_ARCHIVE_PATH]);
774
        //$paths[SYS_UPLOAD_PATH] = api_add_trailing_slash($virtualChamilo[SYS_UPLOAD_PATH]);
775
        //$paths[$root_web][WEB_UPLOAD_PATH] = api_add_trailing_slash($virtualChamilo[WEB_UPLOAD_PATH]);
776
        $paths[WEB_ARCHIVE_PATH] = api_add_trailing_slash($virtualChamilo[WEB_ARCHIVE_PATH]);
777
        //$paths[$root_web][WEB_COURSE_PATH] = api_add_trailing_slash($virtualChamilo[WEB_COURSE_PATH]);
778
779
        // WEB_UPLOAD_PATH should be handle by apache htaccess in the vhost
780
781
        // RewriteEngine On
782
        // RewriteRule /app/upload/(.*)$ http://localhost/other/upload/my-chamilo111-net/$1 [QSA,L]
783
784
        //$paths[$root_web][WEB_UPLOAD_PATH] = api_add_trailing_slash($virtualChamilo[WEB_UPLOAD_PATH]);
785
        //$paths[$root_web][REL_PATH] = $virtualChamilo[REL_PATH];
786
        //$paths[$root_web][REL_COURSE_PATH] = $virtualChamilo[REL_COURSE_PATH];
787
    }
788
789
    $path = trim($path);
790
791
    // Retrieving a common-purpose path.
792
    if (isset($paths[$path])) {
793
        return $paths[$path];
794
    }
795
796
    return false;
797
}
798
799
/**
800
 * Adds to a given path a trailing slash if it is necessary (adds "/" character at the end of the string).
801
 *
802
 * @param string $path the input path
803
 *
804
 * @return string returns the modified path
805
 */
806
function api_add_trailing_slash($path)
807
{
808
    return '/' === substr($path, -1) ? $path : $path.'/';
809
}
810
811
/**
812
 * Removes from a given path the trailing slash if it is necessary (removes "/" character from the end of the string).
813
 *
814
 * @param string $path the input path
815
 *
816
 * @return string returns the modified path
817
 */
818
function api_remove_trailing_slash($path)
819
{
820
    return '/' === substr($path, -1) ? substr($path, 0, -1) : $path;
821
}
822
823
/**
824
 * Checks the RFC 3986 syntax of a given URL.
825
 *
826
 * @param string $url      the URL to be checked
827
 * @param bool   $absolute whether the URL is absolute (beginning with a scheme such as "http:")
828
 *
829
 * @return string|false Returns the URL if it is valid, FALSE otherwise.
830
 *                      This function is an adaptation from the function valid_url(), Drupal CMS.
831
 *
832
 * @see http://drupal.org
833
 * Note: The built-in function filter_var($urs, FILTER_VALIDATE_URL) has a bug for some versions of PHP.
834
 * @see http://bugs.php.net/51192
835
 */
836
function api_valid_url($url, $absolute = false)
837
{
838
    if ($absolute) {
839
        if (preg_match("
840
            /^                                                      # Start at the beginning of the text
841
            (?:ftp|https?|feed):\/\/                                # Look for ftp, http, https or feed schemes
842
            (?:                                                     # Userinfo (optional) which is typically
843
                (?:(?:[\w\.\-\+!$&'\(\)*\+,;=]|%[0-9a-f]{2})+:)*    # a username or a username and password
844
                (?:[\w\.\-\+%!$&'\(\)*\+,;=]|%[0-9a-f]{2})+@        # combination
845
            )?
846
            (?:
847
                (?:[a-z0-9\-\.]|%[0-9a-f]{2})+                      # A domain name or a IPv4 address
848
                |(?:\[(?:[0-9a-f]{0,4}:)*(?:[0-9a-f]{0,4})\])       # or a well formed IPv6 address
849
            )
850
            (?::[0-9]+)?                                            # Server port number (optional)
851
            (?:[\/|\?]
852
                (?:[\w#!:\.\?\+=&@$'~*,;\/\(\)\[\]\-]|%[0-9a-f]{2}) # The path and query (optional)
853
            *)?
854
            $/xi", $url)) {
855
            return $url;
856
        }
857
858
        return false;
859
    } else {
860
        return preg_match("/^(?:[\w#!:\.\?\+=&@$'~*,;\/\(\)\[\]\-]|%[0-9a-f]{2})+$/i", $url) ? $url : false;
861
    }
862
}
863
864
/**
865
 * Checks whether a given string looks roughly like an email address.
866
 *
867
 * @param string $address the e-mail address to be checked
868
 *
869
 * @return mixed returns the e-mail if it is valid, FALSE otherwise
870
 */
871
function api_valid_email($address)
872
{
873
    return filter_var($address, FILTER_VALIDATE_EMAIL);
874
}
875
876
/**
877
 * Function used to protect a course script.
878
 * The function blocks access when
879
 * - there is no $_SESSION["_course"] defined; or
880
 * - $is_allowed_in_course is set to false (this depends on the course
881
 * visibility and user status).
882
 *
883
 * This is only the first proposal, test and improve!
884
 *
885
 * @param bool Option to print headers when displaying error message. Default: false
886
 * @param bool whether session admins should be allowed or not
887
 * @param string $checkTool check if tool is available for users (user, group)
888
 *
889
 * @return bool True if the user has access to the current course or is out of a course context, false otherwise
890
 *
891
 * @todo replace global variable
892
 *
893
 * @author Roan Embrechts
894
 */
895
function api_protect_course_script($print_headers = false, $allow_session_admins = false, string $checkTool = '', $cid = null): bool
896
{
897
    $course_info = api_get_course_info();
898
    if (empty($course_info) && isset($_REQUEST['cid'])) {
899
        $course_info = api_get_course_info_by_id((int) $_REQUEST['cid']);
900
    }
901
902
    if (isset($cid)) {
903
        $course_info = api_get_course_info_by_id($cid);
904
    }
905
906
    if (empty($course_info)) {
907
        api_not_allowed($print_headers);
908
909
        return false;
910
    }
911
912
    if (api_is_drh()) {
913
        return true;
914
    }
915
916
    // Session admin has access to course
917
    $sessionAccess = ('true' === api_get_setting('session.session_admins_access_all_content'));
918
    if ($sessionAccess) {
919
        $allow_session_admins = true;
920
    }
921
922
    if (api_is_platform_admin($allow_session_admins)) {
923
        return true;
924
    }
925
926
    $isAllowedInCourse = api_is_allowed_in_course();
927
    $is_visible = false;
928
    if (isset($course_info) && isset($course_info['visibility'])) {
929
        switch ($course_info['visibility']) {
930
            default:
931
            case Course::CLOSED:
932
                // Completely closed: the course is only accessible to the teachers. - 0
933
                if ($isAllowedInCourse && api_get_user_id() && !api_is_anonymous()) {
934
                    $is_visible = true;
935
                }
936
                break;
937
            case Course::REGISTERED:
938
                // Private - access authorized to course members only - 1
939
                if ($isAllowedInCourse && api_get_user_id() && !api_is_anonymous()) {
940
                    $is_visible = true;
941
                }
942
                break;
943
            case Course::OPEN_PLATFORM:
944
                // Open - access allowed for users registered on the platform - 2
945
                if ($isAllowedInCourse && api_get_user_id() && !api_is_anonymous()) {
946
                    $is_visible = true;
947
                }
948
                break;
949
            case Course::OPEN_WORLD:
950
                //Open - access allowed for the whole world - 3
951
                $is_visible = true;
952
                break;
953
            case Course::HIDDEN:
954
                //Completely closed: the course is only accessible to the teachers. - 0
955
                if (api_is_platform_admin()) {
956
                    $is_visible = true;
957
                }
958
                break;
959
        }
960
961
        //If password is set and user is not registered to the course then the course is not visible
962
        if (false === $isAllowedInCourse &&
963
            isset($course_info['registration_code']) &&
964
            !empty($course_info['registration_code'])
965
        ) {
966
            $is_visible = false;
967
        }
968
    }
969
970
    if (!empty($checkTool)) {
971
        if (!api_is_allowed_to_edit(true, true, true)) {
972
            $toolInfo = api_get_tool_information_by_name($checkTool);
973
            if (!empty($toolInfo) && isset($toolInfo['visibility']) && 0 == $toolInfo['visibility']) {
974
                api_not_allowed(true);
975
976
                return false;
977
            }
978
        }
979
    }
980
981
    // Check session visibility
982
    $session_id = api_get_session_id();
983
984
    if (!empty($session_id)) {
985
        // $isAllowedInCourse was set in local.inc.php
986
        if (!$isAllowedInCourse) {
987
            $is_visible = false;
988
        }
989
        // Check if course is inside session.
990
        if (!SessionManager::relation_session_course_exist($session_id, $course_info['real_id'])) {
991
            $is_visible = false;
992
        }
993
    }
994
995
    if (!$is_visible) {
996
        api_not_allowed($print_headers);
997
998
        return false;
999
    }
1000
1001
    $pluginHelper = Container::$container->get(PluginHelper::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

1001
    /** @scrutinizer ignore-call */ 
1002
    $pluginHelper = Container::$container->get(PluginHelper::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...
1002
1003
    if ($pluginHelper->isPluginEnabled('Positioning')) {
1004
        $plugin = $pluginHelper->loadLegacyPlugin('Positioning');
1005
1006
        if ($plugin && $plugin->get('block_course_if_initial_exercise_not_attempted') === 'true') {
1007
            $currentPath = $_SERVER['REQUEST_URI'];
1008
1009
            $allowedPatterns = [
1010
                '#^/course/\d+/home#',
1011
                '#^/plugin/Positioning/#',
1012
                '#^/main/course_home/#',
1013
                '#^/main/exercise/#',
1014
                '#^/main/inc/ajax/exercise.ajax.php#',
1015
            ];
1016
1017
            $isWhitelisted = false;
1018
            foreach ($allowedPatterns as $pattern) {
1019
                if (preg_match($pattern, $currentPath)) {
1020
                    $isWhitelisted = true;
1021
                    break;
1022
                }
1023
            }
1024
1025
            if (!$isWhitelisted) {
1026
                $initialData = $plugin->getInitialExercise($course_info['real_id'], $session_id);
1027
1028
                if (!empty($initialData['exercise_id'])) {
1029
                    $results = Event::getExerciseResultsByUser(
0 ignored issues
show
Bug introduced by
The method getExerciseResultsByUser() does not exist on Event. ( Ignorable by Annotation )

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

1029
                    /** @scrutinizer ignore-call */ 
1030
                    $results = Event::getExerciseResultsByUser(

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

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

Loading history...
1030
                        api_get_user_id(),
1031
                        (int) $initialData['exercise_id'],
1032
                        $course_info['real_id'],
1033
                        $session_id
1034
                    );
1035
1036
                    if (empty($results)) {
1037
                        api_not_allowed($print_headers);
1038
                        return false;
1039
                    }
1040
                }
1041
            }
1042
        }
1043
    }
1044
1045
    api_block_inactive_user();
1046
1047
    return true;
1048
}
1049
1050
/**
1051
 * Function used to protect an admin script.
1052
 *
1053
 * The function blocks access when the user has no platform admin rights
1054
 * with an error message printed on default output
1055
 *
1056
 * @param bool Whether to allow session admins as well
1057
 * @param bool Whether to allow HR directors as well
1058
 * @param string An optional message (already passed through get_lang)
1059
 *
1060
 * @return bool True if user is allowed, false otherwise.
1061
 *              The function also outputs an error message in case not allowed
1062
 *
1063
 * @author Roan Embrechts (original author)
1064
 */
1065
function api_protect_admin_script($allow_sessions_admins = false, $allow_drh = false, $message = null)
1066
{
1067
    if (!api_is_platform_admin($allow_sessions_admins, $allow_drh)) {
1068
        api_not_allowed(true, $message);
1069
1070
        return false;
1071
    }
1072
    api_block_inactive_user();
1073
1074
    return true;
1075
}
1076
1077
/**
1078
 * Blocks inactive users with a currently active session from accessing more pages "live".
1079
 *
1080
 * @return bool Returns true if the feature is disabled or the user account is still enabled.
1081
 *              Returns false (and shows a message) if the feature is enabled *and* the user is disabled.
1082
 */
1083
function api_block_inactive_user()
1084
{
1085
    $data = true;
1086
    if ('true' !== api_get_setting('security.security_block_inactive_users_immediately')) {
1087
        return $data;
1088
    }
1089
1090
    $userId = api_get_user_id();
1091
    $homeUrl = api_get_path(WEB_PATH);
1092
    if (0 == $userId) {
1093
        return $data;
1094
    }
1095
1096
    $sql = "SELECT active FROM ".Database::get_main_table(TABLE_MAIN_USER)."
1097
            WHERE id = $userId";
1098
1099
    $result = Database::query($sql);
1100
    if (Database::num_rows($result) > 0) {
1101
        $result_array = Database::fetch_array($result);
1102
        $data = (bool) $result_array['active'];
1103
    }
1104
    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...
1105
        $tpl = new Template(null, true, true, false, true, false, true, 0);
1106
        $tpl->assign('hide_login_link', 1);
1107
1108
        //api_not_allowed(true, get_lang('Account inactive'));
1109
        // we were not in a course, return to home page
1110
        $msg = Display::return_message(
1111
            get_lang('Account inactive'),
1112
            'error',
1113
            false
1114
        );
1115
1116
        $msg .= '<p class="text-center">
1117
                 <a class="btn btn--plain" href="'.$homeUrl.'">'.get_lang('Back to Home Page.').'</a></p>';
1118
1119
        $tpl->assign('content', $msg);
1120
        $tpl->display_one_col_template();
1121
        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...
1122
    }
1123
1124
    return $data;
1125
}
1126
1127
/**
1128
 * Function used to protect a teacher script.
1129
 * The function blocks access when the user has no teacher rights.
1130
 *
1131
 * @return bool True if the current user can access the script, false otherwise
1132
 *
1133
 * @author Yoselyn Castillo
1134
 */
1135
function api_protect_teacher_script()
1136
{
1137
    if (!api_is_allowed_to_edit()) {
1138
        api_not_allowed(true);
1139
1140
        return false;
1141
    }
1142
1143
    return true;
1144
}
1145
1146
/**
1147
 * Function used to prevent anonymous users from accessing a script.
1148
 *
1149
 * @param bool $printHeaders
1150
 *
1151
 * @return bool
1152
 */
1153
function api_block_anonymous_users($printHeaders = true)
1154
{
1155
    $isAuth = Container::getAuthorizationChecker()->isGranted('IS_AUTHENTICATED');
1156
1157
    if (false === $isAuth) {
1158
        api_not_allowed($printHeaders);
1159
1160
        return false;
1161
    }
1162
1163
    api_block_inactive_user();
1164
1165
    return true;
1166
}
1167
1168
/**
1169
 * Returns a rough evaluation of the browser's name and version based on very
1170
 * simple regexp.
1171
 *
1172
 * @return array with the navigator name and version ['name' => '...', 'version' => '...']
1173
 */
1174
function api_get_navigator()
1175
{
1176
    $navigator = 'Unknown';
1177
    $version = 0;
1178
1179
    if (!isset($_SERVER['HTTP_USER_AGENT'])) {
1180
        return ['name' => 'Unknown', 'version' => '0.0.0'];
1181
    }
1182
1183
    if (false !== strpos($_SERVER['HTTP_USER_AGENT'], 'Opera')) {
1184
        $navigator = 'Opera';
1185
        [, $version] = explode('Opera', $_SERVER['HTTP_USER_AGENT']);
1186
    } elseif (false !== strpos($_SERVER['HTTP_USER_AGENT'], 'Edge')) {
1187
        $navigator = 'Edge';
1188
        [, $version] = explode('Edge', $_SERVER['HTTP_USER_AGENT']);
1189
    } elseif (false !== strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE')) {
1190
        $navigator = 'Internet Explorer';
1191
        [, $version] = explode('MSIE ', $_SERVER['HTTP_USER_AGENT']);
1192
    } elseif (false !== strpos($_SERVER['HTTP_USER_AGENT'], 'Chrome')) {
1193
        $navigator = 'Chrome';
1194
        [, $version] = explode('Chrome', $_SERVER['HTTP_USER_AGENT']);
1195
    } elseif (false !== stripos($_SERVER['HTTP_USER_AGENT'], 'Safari')) {
1196
        $navigator = 'Safari';
1197
        if (false !== stripos($_SERVER['HTTP_USER_AGENT'], 'Version/')) {
1198
            // If this Safari does have the "Version/" string in its user agent
1199
            // then use that as a version indicator rather than what's after
1200
            // "Safari/" which is rather a "build number" or something
1201
            [, $version] = explode('Version/', $_SERVER['HTTP_USER_AGENT']);
1202
        } else {
1203
            [, $version] = explode('Safari/', $_SERVER['HTTP_USER_AGENT']);
1204
        }
1205
    } elseif (false !== strpos($_SERVER['HTTP_USER_AGENT'], 'Firefox')) {
1206
        $navigator = 'Firefox';
1207
        [, $version] = explode('Firefox', $_SERVER['HTTP_USER_AGENT']);
1208
    } elseif (false !== strpos($_SERVER['HTTP_USER_AGENT'], 'Netscape')) {
1209
        $navigator = 'Netscape';
1210
        if (false !== stripos($_SERVER['HTTP_USER_AGENT'], 'Netscape/')) {
1211
            [, $version] = explode('Netscape', $_SERVER['HTTP_USER_AGENT']);
1212
        } else {
1213
            [, $version] = explode('Navigator', $_SERVER['HTTP_USER_AGENT']);
1214
        }
1215
    } elseif (false !== strpos($_SERVER['HTTP_USER_AGENT'], 'Konqueror')) {
1216
        $navigator = 'Konqueror';
1217
        [, $version] = explode('Konqueror', $_SERVER['HTTP_USER_AGENT']);
1218
    } elseif (false !== stripos($_SERVER['HTTP_USER_AGENT'], 'applewebkit')) {
1219
        $navigator = 'AppleWebKit';
1220
        [, $version] = explode('Version/', $_SERVER['HTTP_USER_AGENT']);
1221
    } elseif (false !== strpos($_SERVER['HTTP_USER_AGENT'], 'Gecko')) {
1222
        $navigator = 'Mozilla';
1223
        [, $version] = explode('; rv:', $_SERVER['HTTP_USER_AGENT']);
1224
    }
1225
1226
    // Now cut extra stuff around (mostly *after*) the version number
1227
    $version = preg_replace('/^([\/\s])?([\d\.]+)?.*/', '\2', $version);
1228
1229
    if (false === strpos($version, '.')) {
1230
        $version = number_format(doubleval($version), 1);
1231
    }
1232
1233
    return ['name' => $navigator, 'version' => $version];
1234
}
1235
1236
/**
1237
 * This function returns the id of the user which is stored in the $_user array.
1238
 *
1239
 * example: The function can be used to check if a user is logged in
1240
 *          if (api_get_user_id())
1241
 *
1242
 * @return int the id of the current user, 0 if is empty
1243
 */
1244
function api_get_user_id()
1245
{
1246
    $userInfo = Session::read('_user');
1247
    if ($userInfo && isset($userInfo['user_id'])) {
1248
        return (int) $userInfo['user_id'];
1249
    }
1250
1251
    return 0;
1252
}
1253
1254
/**
1255
 * Formats user information into a standard array
1256
 * This function should be only used inside api_get_user_info().
1257
 *
1258
 * @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...
1259
 * @param bool $add_password
1260
 * @param bool $loadAvatars  turn off to improve performance
1261
 *
1262
 * @return array Standard user array
1263
 */
1264
function _api_format_user($user, $add_password = false, $loadAvatars = true)
1265
{
1266
    $result = [];
1267
1268
    if (!isset($user['id'])) {
1269
        return [];
1270
    }
1271
1272
    $result['firstname'] = null;
1273
    $result['lastname'] = null;
1274
1275
    if (isset($user['firstname']) && isset($user['lastname'])) {
1276
        // with only lowercase
1277
        $result['firstname'] = $user['firstname'];
1278
        $result['lastname'] = $user['lastname'];
1279
    } elseif (isset($user['firstName']) && isset($user['lastName'])) {
1280
        // with uppercase letters
1281
        $result['firstname'] = isset($user['firstName']) ? $user['firstName'] : null;
1282
        $result['lastname'] = isset($user['lastName']) ? $user['lastName'] : null;
1283
    }
1284
1285
    if (isset($user['email'])) {
1286
        $result['mail'] = isset($user['email']) ? $user['email'] : null;
1287
        $result['email'] = isset($user['email']) ? $user['email'] : null;
1288
    } else {
1289
        $result['mail'] = isset($user['mail']) ? $user['mail'] : null;
1290
        $result['email'] = isset($user['mail']) ? $user['mail'] : null;
1291
    }
1292
1293
    $result['complete_name'] = api_get_person_name($result['firstname'], $result['lastname']);
1294
    $result['complete_name_with_username'] = $result['complete_name'];
1295
1296
    if (!empty($user['username']) && 'false' === api_get_setting('profile.hide_username_with_complete_name')) {
1297
        $result['complete_name_with_username'] = $result['complete_name'].' ('.$user['username'].')';
1298
    }
1299
1300
    $showEmail = 'true' === api_get_setting('show_email_addresses');
1301
    if (!empty($user['email'])) {
1302
        $result['complete_name_with_email_forced'] = $result['complete_name'].' ('.$user['email'].')';
1303
        if ($showEmail) {
1304
            $result['complete_name_with_email'] = $result['complete_name'].' ('.$user['email'].')';
1305
        }
1306
    } else {
1307
        $result['complete_name_with_email'] = $result['complete_name'];
1308
        $result['complete_name_with_email_forced'] = $result['complete_name'];
1309
    }
1310
1311
    // Kept for historical reasons
1312
    $result['firstName'] = $result['firstname'];
1313
    $result['lastName'] = $result['lastname'];
1314
1315
    $attributes = [
1316
        'phone',
1317
        'address',
1318
        'picture_uri',
1319
        'official_code',
1320
        'status',
1321
        'active',
1322
        'auth_sources',
1323
        'username',
1324
        'theme',
1325
        'language',
1326
        'locale',
1327
        'creator_id',
1328
        'created_at',
1329
        'hr_dept_id',
1330
        'expiration_date',
1331
        'last_login',
1332
        'user_is_online',
1333
        'profile_completed',
1334
    ];
1335
1336
    if ('true' === api_get_setting('extended_profile')) {
1337
        $attributes[] = 'competences';
1338
        $attributes[] = 'diplomas';
1339
        $attributes[] = 'teach';
1340
        $attributes[] = 'openarea';
1341
    }
1342
1343
    foreach ($attributes as $attribute) {
1344
        $result[$attribute] = $user[$attribute] ?? null;
1345
    }
1346
1347
    $user_id = (int) $user['id'];
1348
    // Maintain the user_id index for backwards compatibility
1349
    $result['user_id'] = $result['id'] = $user_id;
1350
1351
    $hasCertificates = Certificate::getCertificateByUser($user_id);
1352
    $result['has_certificates'] = 0;
1353
    if (!empty($hasCertificates)) {
1354
        $result['has_certificates'] = 1;
1355
    }
1356
1357
    $result['icon_status'] = '';
1358
    $result['icon_status_medium'] = '';
1359
    $result['is_admin'] = UserManager::is_admin($user_id);
1360
1361
    // Getting user avatar.
1362
    if ($loadAvatars) {
1363
        $result['avatar'] = '';
1364
        $result['avatar_no_query'] = '';
1365
        $result['avatar_small'] = '';
1366
        $result['avatar_medium'] = '';
1367
1368
        if (empty($user['avatar'])) {
1369
            $originalFile = UserManager::getUserPicture(
1370
                $user_id,
1371
                USER_IMAGE_SIZE_ORIGINAL,
1372
                null,
1373
                $result
1374
            );
1375
            $result['avatar'] = $originalFile;
1376
            $avatarString = explode('?', $result['avatar']);
1377
            $result['avatar_no_query'] = reset($avatarString);
1378
        } else {
1379
            $result['avatar'] = $user['avatar'];
1380
            $avatarString = explode('?', $user['avatar']);
1381
            $result['avatar_no_query'] = reset($avatarString);
1382
        }
1383
1384
        if (!isset($user['avatar_small'])) {
1385
            $smallFile = UserManager::getUserPicture(
1386
                $user_id,
1387
                USER_IMAGE_SIZE_SMALL,
1388
                null,
1389
                $result
1390
            );
1391
            $result['avatar_small'] = $smallFile;
1392
        } else {
1393
            $result['avatar_small'] = $user['avatar_small'];
1394
        }
1395
1396
        if (!isset($user['avatar_medium'])) {
1397
            $mediumFile = UserManager::getUserPicture(
1398
                $user_id,
1399
                USER_IMAGE_SIZE_MEDIUM,
1400
                null,
1401
                $result
1402
            );
1403
            $result['avatar_medium'] = $mediumFile;
1404
        } else {
1405
            $result['avatar_medium'] = $user['avatar_medium'];
1406
        }
1407
1408
        $urlImg = api_get_path(WEB_IMG_PATH);
1409
        $iconStatus = '';
1410
        $iconStatusMedium = '';
1411
        $label = '';
1412
1413
        switch ($result['status']) {
1414
            case STUDENT:
1415
                if ($result['has_certificates']) {
1416
                    $iconStatus = $urlImg.'icons/svg/identifier_graduated.svg';
1417
                    $label = get_lang('Graduated');
1418
                } else {
1419
                    $iconStatus = $urlImg.'icons/svg/identifier_student.svg';
1420
                    $label = get_lang('Student');
1421
                }
1422
                break;
1423
            case COURSEMANAGER:
1424
                if ($result['is_admin']) {
1425
                    $iconStatus = $urlImg.'icons/svg/identifier_admin.svg';
1426
                    $label = get_lang('Admin');
1427
                } else {
1428
                    $iconStatus = $urlImg.'icons/svg/identifier_teacher.svg';
1429
                    $label = get_lang('Teacher');
1430
                }
1431
                break;
1432
            case STUDENT_BOSS:
1433
                $iconStatus = $urlImg.'icons/svg/identifier_teacher.svg';
1434
                $label = get_lang('StudentBoss');
1435
                break;
1436
        }
1437
1438
        if (!empty($iconStatus)) {
1439
            $iconStatusMedium = '<img src="'.$iconStatus.'" width="32px" height="32px">';
1440
            $iconStatus = '<img src="'.$iconStatus.'" width="22px" height="22px">';
1441
        }
1442
1443
        $result['icon_status'] = $iconStatus;
1444
        $result['icon_status_label'] = $label;
1445
        $result['icon_status_medium'] = $iconStatusMedium;
1446
    }
1447
1448
    if (isset($user['user_is_online'])) {
1449
        $result['user_is_online'] = true == $user['user_is_online'] ? 1 : 0;
1450
    }
1451
    if (isset($user['user_is_online_in_chat'])) {
1452
        $result['user_is_online_in_chat'] = (int) $user['user_is_online_in_chat'];
1453
    }
1454
1455
    if ($add_password) {
1456
        $result['password'] = $user['password'];
1457
    }
1458
1459
    if (isset($result['profile_completed'])) {
1460
        $result['profile_completed'] = $user['profile_completed'];
1461
    }
1462
1463
    $result['profile_url'] = api_get_path(WEB_CODE_PATH).'social/profile.php?u='.$user_id;
1464
1465
    // Send message link
1466
    $sendMessage = api_get_path(WEB_AJAX_PATH).'user_manager.ajax.php?a=get_user_popup&user_id='.$user_id;
1467
    $result['complete_name_with_message_link'] = Display::url(
1468
        $result['complete_name_with_username'],
1469
        $sendMessage,
1470
        ['class' => 'ajax']
1471
    );
1472
1473
    if (isset($user['extra'])) {
1474
        $result['extra'] = $user['extra'];
1475
    }
1476
1477
    return $result;
1478
}
1479
1480
/**
1481
 * Finds all the information about a user.
1482
 * If no parameter is passed you find all the information about the current user.
1483
 *
1484
 * @param int  $user_id
1485
 * @param bool $checkIfUserOnline
1486
 * @param bool $showPassword
1487
 * @param bool $loadExtraData
1488
 * @param bool $loadOnlyVisibleExtraData Get the user extra fields that are visible
1489
 * @param bool $loadAvatars              turn off to improve performance and if avatars are not needed
1490
 * @param bool $updateCache              update apc cache if exists
1491
 *
1492
 * @return mixed $user_info user_id, lastname, firstname, username, email, etc or false on error
1493
 *
1494
 * @author Patrick Cool <[email protected]>
1495
 * @author Julio Montoya
1496
 *
1497
 * @version 21 September 2004
1498
 */
1499
function api_get_user_info(
1500
    $user_id = 0,
1501
    $checkIfUserOnline = false,
1502
    $showPassword = false,
1503
    $loadExtraData = false,
1504
    $loadOnlyVisibleExtraData = false,
1505
    $loadAvatars = true,
1506
    $updateCache = false
1507
) {
1508
    // Make sure user_id is safe
1509
    $user_id = (int) $user_id;
1510
    $user = false;
1511
    if (empty($user_id)) {
1512
        $userFromSession = Session::read('_user');
1513
        if (isset($userFromSession) && !empty($userFromSession)) {
1514
            return $userFromSession;
1515
            /*
1516
            return _api_format_user(
1517
                $userFromSession,
1518
                $showPassword,
1519
                $loadAvatars
1520
            );*/
1521
        }
1522
1523
        return false;
1524
    }
1525
1526
    $sql = "SELECT * FROM ".Database::get_main_table(TABLE_MAIN_USER)."
1527
            WHERE id = $user_id";
1528
    $result = Database::query($sql);
1529
    if (Database::num_rows($result) > 0) {
1530
        $result_array = Database::fetch_array($result);
1531
        $result_array['auth_sources'] = api_get_user_entity($result_array['id'])->getAuthSourcesAuthentications();
1532
        $result_array['user_is_online_in_chat'] = 0;
1533
        if ($checkIfUserOnline) {
1534
            $use_status_in_platform = user_is_online($user_id);
1535
            $result_array['user_is_online'] = $use_status_in_platform;
1536
            $user_online_in_chat = 0;
1537
            if ($use_status_in_platform) {
1538
                $user_status = UserManager::get_extra_user_data_by_field(
1539
                    $user_id,
1540
                    'user_chat_status',
1541
                    false,
1542
                    true
1543
                );
1544
                if (1 == (int) $user_status['user_chat_status']) {
1545
                    $user_online_in_chat = 1;
1546
                }
1547
            }
1548
            $result_array['user_is_online_in_chat'] = $user_online_in_chat;
1549
        }
1550
1551
        if ($loadExtraData) {
1552
            $fieldValue = new ExtraFieldValue('user');
1553
            $result_array['extra'] = $fieldValue->getAllValuesForAnItem(
1554
                $user_id,
1555
                $loadOnlyVisibleExtraData
1556
            );
1557
        }
1558
        $user = _api_format_user($result_array, $showPassword, $loadAvatars);
1559
    }
1560
1561
    return $user;
1562
}
1563
1564
function api_get_user_info_from_entity(
1565
    User $user,
1566
    $checkIfUserOnline = false,
1567
    $showPassword = false,
1568
    $loadExtraData = false,
1569
    $loadOnlyVisibleExtraData = false,
1570
    $loadAvatars = true,
1571
    $loadCertificate = false
1572
) {
1573
    if (!$user instanceof UserInterface) {
1574
        return false;
1575
    }
1576
1577
    // Make sure user_id is safe
1578
    $user_id = (int) $user->getId();
1579
1580
    if (empty($user_id)) {
1581
        $userFromSession = Session::read('_user');
1582
1583
        if (isset($userFromSession) && !empty($userFromSession)) {
1584
            return $userFromSession;
1585
        }
1586
1587
        return false;
1588
    }
1589
1590
    $result = [];
1591
    $result['user_is_online_in_chat'] = 0;
1592
    if ($checkIfUserOnline) {
1593
        $use_status_in_platform = user_is_online($user_id);
1594
        $result['user_is_online'] = $use_status_in_platform;
1595
        $user_online_in_chat = 0;
1596
        if ($use_status_in_platform) {
1597
            $user_status = UserManager::get_extra_user_data_by_field(
1598
                $user_id,
1599
                'user_chat_status',
1600
                false,
1601
                true
1602
            );
1603
            if (1 == (int) $user_status['user_chat_status']) {
1604
                $user_online_in_chat = 1;
1605
            }
1606
        }
1607
        $result['user_is_online_in_chat'] = $user_online_in_chat;
1608
    }
1609
1610
    if ($loadExtraData) {
1611
        $fieldValue = new ExtraFieldValue('user');
1612
        $result['extra'] = $fieldValue->getAllValuesForAnItem(
1613
            $user_id,
1614
            $loadOnlyVisibleExtraData
1615
        );
1616
    }
1617
1618
    $result['username'] = $user->getUsername();
1619
    $result['status'] = $user->getStatus();
1620
    $result['firstname'] = $user->getFirstname();
1621
    $result['lastname'] = $user->getLastname();
1622
    $result['email'] = $result['mail'] = $user->getEmail();
1623
    $result['complete_name'] = api_get_person_name($result['firstname'], $result['lastname']);
1624
    $result['complete_name_with_username'] = $result['complete_name'];
1625
1626
    if (!empty($result['username']) && 'false' === api_get_setting('profile.hide_username_with_complete_name')) {
1627
        $result['complete_name_with_username'] = $result['complete_name'].' ('.$result['username'].')';
1628
    }
1629
1630
    $showEmail = 'true' === api_get_setting('show_email_addresses');
1631
    if (!empty($result['email'])) {
1632
        $result['complete_name_with_email_forced'] = $result['complete_name'].' ('.$result['email'].')';
1633
        if ($showEmail) {
1634
            $result['complete_name_with_email'] = $result['complete_name'].' ('.$result['email'].')';
1635
        }
1636
    } else {
1637
        $result['complete_name_with_email'] = $result['complete_name'];
1638
        $result['complete_name_with_email_forced'] = $result['complete_name'];
1639
    }
1640
1641
    // Kept for historical reasons
1642
    $result['firstName'] = $result['firstname'];
1643
    $result['lastName'] = $result['lastname'];
1644
1645
    $attributes = [
1646
        'picture_uri',
1647
        'last_login',
1648
        'user_is_online',
1649
    ];
1650
1651
    $result['phone'] = $user->getPhone();
1652
    $result['address'] = $user->getAddress();
1653
    $result['official_code'] = $user->getOfficialCode();
1654
    $result['active'] = $user->isActive();
1655
    $result['auth_sources'] = $user->getAuthSourcesAuthentications();
1656
    $result['language'] = $user->getLocale();
1657
    $result['creator_id'] = $user->getCreatorId();
1658
    $result['created_at'] = $user->getCreatedAt()->format('Y-m-d H:i:s');
1659
    $result['hr_dept_id'] = $user->getHrDeptId();
1660
    $result['expiration_date'] = '';
1661
    if ($user->getExpirationDate()) {
1662
        $result['expiration_date'] = $user->getExpirationDate()->format('Y-m-d H:i:s');
1663
    }
1664
1665
    $result['last_login'] = null;
1666
    if ($user->getLastLogin()) {
1667
        $result['last_login'] = $user->getLastLogin()->format('Y-m-d H:i:s');
1668
    }
1669
1670
    $result['competences'] = $user->getCompetences();
1671
    $result['diplomas'] = $user->getDiplomas();
1672
    $result['teach'] = $user->getTeach();
1673
    $result['openarea'] = $user->getOpenarea();
1674
    $user_id = (int) $user->getId();
1675
1676
    // Maintain the user_id index for backwards compatibility
1677
    $result['user_id'] = $result['id'] = $user_id;
1678
1679
    if ($loadCertificate) {
1680
        $hasCertificates = Certificate::getCertificateByUser($user_id);
1681
        $result['has_certificates'] = 0;
1682
        if (!empty($hasCertificates)) {
1683
            $result['has_certificates'] = 1;
1684
        }
1685
    }
1686
1687
    $result['icon_status'] = '';
1688
    $result['icon_status_medium'] = '';
1689
    $result['is_admin'] = UserManager::is_admin($user_id);
1690
1691
    // Getting user avatar.
1692
    if ($loadAvatars) {
1693
        $result['avatar'] = '';
1694
        $result['avatar_no_query'] = '';
1695
        $result['avatar_small'] = '';
1696
        $result['avatar_medium'] = '';
1697
        $urlImg = '/';
1698
        $iconStatus = '';
1699
        $iconStatusMedium = '';
1700
1701
        switch ($user->getStatus()) {
1702
            case STUDENT:
1703
                if (isset($result['has_certificates']) && $result['has_certificates']) {
1704
                    $iconStatus = $urlImg.'icons/svg/identifier_graduated.svg';
1705
                } else {
1706
                    $iconStatus = $urlImg.'icons/svg/identifier_student.svg';
1707
                }
1708
                break;
1709
            case COURSEMANAGER:
1710
                if ($result['is_admin']) {
1711
                    $iconStatus = $urlImg.'icons/svg/identifier_admin.svg';
1712
                } else {
1713
                    $iconStatus = $urlImg.'icons/svg/identifier_teacher.svg';
1714
                }
1715
                break;
1716
            case STUDENT_BOSS:
1717
                $iconStatus = $urlImg.'icons/svg/identifier_teacher.svg';
1718
                break;
1719
        }
1720
1721
        if (!empty($iconStatus)) {
1722
            $iconStatusMedium = '<img src="'.$iconStatus.'" width="32px" height="32px">';
1723
            $iconStatus = '<img src="'.$iconStatus.'" width="22px" height="22px">';
1724
        }
1725
1726
        $result['icon_status'] = $iconStatus;
1727
        $result['icon_status_medium'] = $iconStatusMedium;
1728
    }
1729
1730
    if (isset($result['user_is_online'])) {
1731
        $result['user_is_online'] = true == $result['user_is_online'] ? 1 : 0;
1732
    }
1733
    if (isset($result['user_is_online_in_chat'])) {
1734
        $result['user_is_online_in_chat'] = $result['user_is_online_in_chat'];
1735
    }
1736
1737
    $result['password'] = '';
1738
    if ($showPassword) {
1739
        $result['password'] = $user->getPassword();
1740
    }
1741
1742
    if (isset($result['profile_completed'])) {
1743
        $result['profile_completed'] = $result['profile_completed'];
1744
    }
1745
1746
    $result['profile_url'] = api_get_path(WEB_CODE_PATH).'social/profile.php?u='.$user_id;
1747
1748
    // Send message link
1749
    $sendMessage = api_get_path(WEB_AJAX_PATH).'user_manager.ajax.php?a=get_user_popup&user_id='.$user_id;
1750
    $result['complete_name_with_message_link'] = Display::url(
1751
        $result['complete_name_with_username'],
1752
        $sendMessage,
1753
        ['class' => 'ajax']
1754
    );
1755
1756
    if (isset($result['extra'])) {
1757
        $result['extra'] = $result['extra'];
1758
    }
1759
1760
    return $result;
1761
}
1762
1763
function api_get_lp_entity(int $id): ?CLp
1764
{
1765
    return Database::getManager()->getRepository(CLp::class)->find($id);
1766
}
1767
1768
function api_get_user_entity(int $userId = 0): ?User
1769
{
1770
    $userId = $userId ?: api_get_user_id();
1771
    $repo = Container::getUserRepository();
1772
1773
    return $repo->find($userId);
1774
}
1775
1776
function api_get_current_user(): ?User
1777
{
1778
    $isLoggedIn = Container::getAuthorizationChecker()->isGranted('IS_AUTHENTICATED_REMEMBERED');
1779
    if (false === $isLoggedIn) {
1780
        return null;
1781
    }
1782
1783
    $token = Container::getTokenStorage()->getToken();
1784
1785
    if (null !== $token) {
1786
        return $token->getUser();
1787
    }
1788
1789
    return null;
1790
}
1791
1792
/**
1793
 * Finds all the information about a user from username instead of user id.
1794
 *
1795
 * @param string $username
1796
 *
1797
 * @return mixed $user_info array user_id, lastname, firstname, username, email or false on error
1798
 *
1799
 * @author Yannick Warnier <[email protected]>
1800
 */
1801
function api_get_user_info_from_username($username)
1802
{
1803
    if (empty($username)) {
1804
        return false;
1805
    }
1806
    $username = trim($username);
1807
1808
    $sql = "SELECT * FROM ".Database::get_main_table(TABLE_MAIN_USER)."
1809
            WHERE username='".Database::escape_string($username)."'";
1810
    $result = Database::query($sql);
1811
    if (Database::num_rows($result) > 0) {
1812
        $resultArray = Database::fetch_array($result);
1813
1814
        return _api_format_user($resultArray);
1815
    }
1816
1817
    return false;
1818
}
1819
1820
/**
1821
 * Get first user with an email.
1822
 *
1823
 * @param string $email
1824
 *
1825
 * @return array|bool
1826
 */
1827
function api_get_user_info_from_email($email = '')
1828
{
1829
    if (empty($email)) {
1830
        return false;
1831
    }
1832
    $sql = "SELECT * FROM ".Database::get_main_table(TABLE_MAIN_USER)."
1833
            WHERE email ='".Database::escape_string($email)."' LIMIT 1";
1834
    $result = Database::query($sql);
1835
    if (Database::num_rows($result) > 0) {
1836
        $resultArray = Database::fetch_array($result);
1837
1838
        return _api_format_user($resultArray);
1839
    }
1840
1841
    return false;
1842
}
1843
1844
/**
1845
 * @return string
1846
 */
1847
function api_get_course_id()
1848
{
1849
    return Session::read('_cid', null);
1850
}
1851
1852
/**
1853
 * Returns the current course id (integer).
1854
 *
1855
 * @param ?string $code Optional course code
1856
 *
1857
 * @return int
1858
 */
1859
function api_get_course_int_id(?string $code = null): int
1860
{
1861
    if (!empty($code)) {
1862
        $code = Database::escape_string($code);
1863
        $row = Database::select(
1864
            'id',
1865
            Database::get_main_table(TABLE_MAIN_COURSE),
1866
            ['where' => ['code = ?' => [$code]]],
1867
            'first'
1868
        );
1869
1870
        if (is_array($row) && isset($row['id'])) {
1871
            return $row['id'];
1872
        } else {
1873
            return 0;
1874
        }
1875
    }
1876
1877
    $cid = Session::read('_real_cid', 0);
1878
    if (empty($cid) && isset($_REQUEST['cid'])) {
1879
        $cid = (int) $_REQUEST['cid'];
1880
    }
1881
1882
    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...
1883
}
1884
1885
/**
1886
 * Gets a course setting from the current course_setting table. Try always using integer values.
1887
 *
1888
 * @param string       $settingName The name of the setting we want from the table
1889
 * @param Course|array $courseInfo
1890
 * @param bool         $force       force checking the value in the database
1891
 *
1892
 * @return mixed The value of that setting in that table. Return -1 if not found.
1893
 */
1894
function api_get_course_setting($settingName, $courseInfo = null, $force = false)
1895
{
1896
    if (empty($courseInfo)) {
1897
        $courseInfo = api_get_course_info();
1898
    }
1899
1900
    if (empty($courseInfo) || empty($settingName)) {
1901
        return -1;
1902
    }
1903
1904
    if ($courseInfo instanceof Course) {
1905
        $courseId = $courseInfo->getId();
1906
    } else {
1907
        $courseId = isset($courseInfo['real_id']) && !empty($courseInfo['real_id']) ? $courseInfo['real_id'] : 0;
1908
    }
1909
1910
    if (empty($courseId)) {
1911
        return -1;
1912
    }
1913
1914
    static $courseSettingInfo = [];
1915
1916
    if ($force) {
1917
        $courseSettingInfo = [];
1918
    }
1919
1920
    if (!isset($courseSettingInfo[$courseId])) {
1921
        $table = Database::get_course_table(TABLE_COURSE_SETTING);
1922
        $settingName = Database::escape_string($settingName);
1923
1924
        $sql = "SELECT variable, value FROM $table
1925
                WHERE c_id = $courseId ";
1926
        $res = Database::query($sql);
1927
        if (Database::num_rows($res) > 0) {
1928
            $result = Database::store_result($res, 'ASSOC');
1929
            $courseSettingInfo[$courseId] = array_column($result, 'value', 'variable');
1930
1931
            if (isset($courseSettingInfo[$courseId]['email_alert_manager_on_new_quiz'])) {
1932
                $value = $courseSettingInfo[$courseId]['email_alert_manager_on_new_quiz'];
1933
                if (!is_null($value)) {
1934
                    $result = explode(',', $value);
1935
                    $courseSettingInfo[$courseId]['email_alert_manager_on_new_quiz'] = $result;
1936
                }
1937
            }
1938
        }
1939
    }
1940
1941
    if (isset($courseSettingInfo[$courseId]) && isset($courseSettingInfo[$courseId][$settingName])) {
1942
        return $courseSettingInfo[$courseId][$settingName];
1943
    }
1944
1945
    return -1;
1946
}
1947
1948
function api_get_course_plugin_setting($plugin, $settingName, $courseInfo = [])
1949
{
1950
    $value = api_get_course_setting($settingName, $courseInfo, true);
1951
1952
    if (-1 === $value) {
1953
        // Check global settings
1954
        $value = api_get_plugin_setting($plugin, $settingName);
1955
        if ('true' === $value) {
1956
            return 1;
1957
        }
1958
        if ('false' === $value) {
1959
            return 0;
1960
        }
1961
        if (null === $value) {
1962
            return -1;
1963
        }
1964
    }
1965
1966
    return $value;
1967
}
1968
1969
/**
1970
 * Gets an anonymous user ID.
1971
 *
1972
 * For some tools that need tracking, like the learnpath tool, it is necessary
1973
 * to have a usable user-id to enable some kind of tracking, even if not
1974
 * perfect. An anonymous ID is taken from the users table by looking for a
1975
 * status of "6" (anonymous).
1976
 *
1977
 * @return int User ID of the anonymous user, or O if no anonymous user found
1978
 */
1979
function api_get_anonymous_id()
1980
{
1981
    // Find if another anon is connected now
1982
    $table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_LOGIN);
1983
    $tableU = Database::get_main_table(TABLE_MAIN_USER);
1984
    $ip = Database::escape_string(api_get_real_ip());
1985
    $max = (int) api_get_setting('admin.max_anonymous_users');
1986
    if ($max >= 2) {
1987
        $sql = "SELECT * FROM $table as TEL
1988
                JOIN $tableU as U
1989
                ON U.id = TEL.login_user_id
1990
                WHERE TEL.user_ip = '$ip'
1991
                    AND U.status = ".ANONYMOUS."
1992
                    AND U.id != 2 ";
1993
1994
        $result = Database::query($sql);
1995
        if (empty(Database::num_rows($result))) {
1996
            $login = uniqid('anon_');
1997
            $anonList = UserManager::get_user_list(['status' => ANONYMOUS], ['created_at ASC']);
1998
            if (count($anonList) >= $max) {
1999
                foreach ($anonList as $userToDelete) {
2000
                    UserManager::delete_user($userToDelete['user_id']);
2001
                    break;
2002
                }
2003
            }
2004
2005
            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...
2006
                $login,
2007
                'anon',
2008
                ANONYMOUS,
2009
                ' anonymous@localhost',
2010
                $login,
2011
                $login
2012
            );
2013
        } else {
2014
            $row = Database::fetch_assoc($result);
2015
2016
            return $row['id'];
2017
        }
2018
    }
2019
2020
    $table = Database::get_main_table(TABLE_MAIN_USER);
2021
    $sql = "SELECT id
2022
            FROM $table
2023
            WHERE status = ".ANONYMOUS." ";
2024
    $res = Database::query($sql);
2025
    if (Database::num_rows($res) > 0) {
2026
        $row = Database::fetch_assoc($res);
2027
2028
        return $row['id'];
2029
    }
2030
2031
    // No anonymous user was found.
2032
    return 0;
2033
}
2034
2035
/**
2036
 * @param int $courseId
2037
 * @param int $sessionId
2038
 * @param int $groupId
2039
 *
2040
 * @return string
2041
 */
2042
function api_get_cidreq_params($courseId, $sessionId = 0, $groupId = 0)
2043
{
2044
    $courseId = !empty($courseId) ? (int) $courseId : 0;
2045
    $sessionId = !empty($sessionId) ? (int) $sessionId : 0;
2046
    $groupId = !empty($groupId) ? (int) $groupId : 0;
2047
2048
    $url = 'cid='.$courseId;
2049
    $url .= '&sid='.$sessionId;
2050
    $url .= '&gid='.$groupId;
2051
2052
    return $url;
2053
}
2054
2055
/**
2056
 * Returns the current course url part including session, group, and gradebook params.
2057
 *
2058
 * @param bool   $addSessionId
2059
 * @param bool   $addGroupId
2060
 * @param string $origin
2061
 *
2062
 * @return string Course & session references to add to a URL
2063
 */
2064
function api_get_cidreq($addSessionId = true, $addGroupId = true, $origin = '')
2065
{
2066
    $courseId = api_get_course_int_id();
2067
    if (0 === $courseId && isset($_REQUEST['cid'])) {
2068
        $courseId = (int) $_REQUEST['cid'];
2069
    }
2070
    $url = empty($courseId) ? '' : 'cid='.$courseId;
2071
    $origin = empty($origin) ? api_get_origin() : Security::remove_XSS($origin);
2072
2073
    if ($addSessionId) {
2074
        if (!empty($url)) {
2075
            $sessionId = api_get_session_id();
2076
            if (0 === $sessionId && isset($_REQUEST['sid'])) {
2077
                $sessionId = (int) $_REQUEST['sid'];
2078
            }
2079
            $url .= 0 === $sessionId ? '&sid=0' : '&sid='.$sessionId;
2080
        }
2081
    }
2082
2083
    if ($addGroupId) {
2084
        if (!empty($url)) {
2085
            $url .= 0 == api_get_group_id() ? '&gid=0' : '&gid='.api_get_group_id();
2086
        }
2087
    }
2088
2089
    if (!empty($url)) {
2090
        $url .= '&gradebook='.(int) api_is_in_gradebook();
2091
        if (false !== $origin) {
2092
            $url .= '&origin=' . $origin;
2093
        }
2094
    }
2095
2096
    return $url;
2097
}
2098
2099
/**
2100
 * Get if we visited a gradebook page.
2101
 *
2102
 * @return bool
2103
 */
2104
function api_is_in_gradebook()
2105
{
2106
    return Session::read('in_gradebook', false);
2107
}
2108
2109
/**
2110
 * Set that we are in a page inside a gradebook.
2111
 */
2112
function api_set_in_gradebook()
2113
{
2114
    Session::write('in_gradebook', true);
2115
}
2116
2117
/**
2118
 * Remove gradebook session.
2119
 */
2120
function api_remove_in_gradebook()
2121
{
2122
    Session::erase('in_gradebook');
2123
}
2124
2125
/**
2126
 * Returns the current course info array see api_format_course_array()
2127
 * If the course_code is given, the returned array gives info about that
2128
 * particular course, if none given it gets the course info from the session.
2129
 *
2130
 * @param string $courseCode
2131
 *
2132
 * @return array
2133
 */
2134
function api_get_course_info($courseCode = null)
2135
{
2136
    if (!empty($courseCode)) {
2137
        $course = Container::getCourseRepository()->findOneByCode($courseCode);
2138
2139
        return api_format_course_array($course);
2140
    }
2141
2142
    $course = Session::read('_course');
2143
    if ('-1' == $course) {
2144
        $course = [];
2145
    }
2146
2147
    if (empty($course) && isset($_REQUEST['cid'])) {
2148
        $course = api_get_course_info_by_id((int) $_REQUEST['cid']);
2149
    }
2150
2151
    return $course;
2152
}
2153
2154
/**
2155
 * @param int $courseId
2156
 */
2157
function api_get_course_entity($courseId = 0): ?Course
2158
{
2159
    if (empty($courseId)) {
2160
        $courseId = api_get_course_int_id();
2161
    }
2162
2163
    if (empty($courseId)) {
2164
        return null;
2165
    }
2166
2167
    return Container::getCourseRepository()->find($courseId);
2168
}
2169
2170
/**
2171
 * @param int $id
2172
 */
2173
function api_get_session_entity($id = 0): ?SessionEntity
2174
{
2175
    if (empty($id)) {
2176
        $id = api_get_session_id();
2177
    }
2178
2179
    if (empty($id)) {
2180
        return null;
2181
    }
2182
2183
    return Container::getSessionRepository()->find($id);
2184
}
2185
2186
/**
2187
 * @param int $id
2188
 */
2189
function api_get_group_entity($id = 0): ?CGroup
2190
{
2191
    if (empty($id)) {
2192
        $id = api_get_group_id();
2193
    }
2194
2195
    return Container::getGroupRepository()->find($id);
2196
}
2197
2198
/**
2199
 * @param int $id
2200
 */
2201
function api_get_url_entity($id = 0): ?AccessUrl
2202
{
2203
    if (empty($id)) {
2204
        $id = api_get_current_access_url_id();
2205
    }
2206
2207
    return Container::getAccessUrlRepository()->find($id);
2208
}
2209
2210
/**
2211
 * Returns the current course info array.
2212
2213
 * Now if the course_code is given, the returned array gives info about that
2214
 * particular course, not specially the current one.
2215
 *
2216
 * @param int $id Numeric ID of the course
2217
 *
2218
 * @return array The course info as an array formatted by api_format_course_array, including category.title
2219
 */
2220
function api_get_course_info_by_id(?int $id = 0)
2221
{
2222
    if (empty($id)) {
2223
        $course = Session::read('_course', []);
2224
2225
        return $course;
2226
    }
2227
2228
    $course = Container::getCourseRepository()->find($id);
2229
    if (empty($course)) {
2230
        return [];
2231
    }
2232
2233
    return api_format_course_array($course);
2234
}
2235
2236
/**
2237
 * Reformat the course array (output by api_get_course_info()) in order, mostly,
2238
 * to switch from 'code' to 'id' in the array.
2239
 *
2240
 * @return array
2241
 *
2242
 * @todo eradicate the false "id"=code field of the $_course array and use the int id
2243
 */
2244
function api_format_course_array(Course $course = null)
2245
{
2246
    if (empty($course)) {
2247
        return [];
2248
    }
2249
2250
    $courseData = [];
2251
    $courseData['id'] = $courseData['real_id'] = $course->getId();
2252
2253
    // Added
2254
    $courseData['code'] = $courseData['sysCode'] = $course->getCode();
2255
    $courseData['name'] = $courseData['title'] = $course->getTitle(); // 'name' only used for backwards compatibility - should be removed in the long run
2256
    $courseData['official_code'] = $courseData['visual_code'] = $course->getVisualCode();
2257
    $courseData['creation_date'] = $course->getCreationDate()->format('Y-m-d H:i:s');
2258
    $courseData['titular'] = $course->getTutorName();
2259
    $courseData['language'] = $courseData['course_language'] = $course->getCourseLanguage();
2260
    $courseData['extLink']['url'] = $courseData['department_url'] = $course->getDepartmentUrl();
2261
    $courseData['extLink']['name'] = $courseData['department_name'] = $course->getDepartmentName();
2262
2263
    $courseData['visibility'] = $course->getVisibility();
2264
    $courseData['subscribe_allowed'] = $courseData['subscribe'] = $course->getSubscribe();
2265
    $courseData['unsubscribe'] = $course->getUnsubscribe();
2266
    $courseData['activate_legal'] = $course->getActivateLegal();
2267
    $courseData['legal'] = $course->getLegal();
2268
    $courseData['show_score'] = $course->getShowScore(); //used in the work tool
2269
    $courseData['video_url'] = $course->getVideoUrl();
2270
    $courseData['sticky'] = (int) $course->isSticky();
2271
2272
    $coursePath = '/course/';
2273
    $webCourseHome = $coursePath.$courseData['real_id'].'/home';
2274
2275
    // Course password
2276
    $courseData['registration_code'] = $course->getRegistrationCode();
2277
    $courseData['disk_quota'] = $course->getDiskQuota();
2278
    $courseData['course_public_url'] = $webCourseHome;
2279
    $courseData['about_url'] = $coursePath.$courseData['real_id'].'/about';
2280
    $courseData['add_teachers_to_sessions_courses'] = $course->isAddTeachersToSessionsCourses();
2281
2282
    $image = Display::getMdiIcon(
2283
        ObjectIcon::COURSE,
2284
        'ch-tool-icon',
2285
        null,
2286
        ICON_SIZE_BIG
2287
    );
2288
2289
    $illustration = Container::getIllustrationRepository()->getIllustrationUrl($course);
2290
    if (!empty($illustration)) {
2291
        $image = $illustration;
2292
    }
2293
2294
    $courseData['course_image'] = $image.'?filter=course_picture_small';
2295
    $courseData['course_image_large'] = $image.'?filter=course_picture_medium';
2296
2297
    if ('true' === api_get_setting('course.show_course_duration') && null !== $course->getDuration()) {
2298
        $courseData['duration'] = $course->getDuration();
2299
    }
2300
2301
    return $courseData;
2302
}
2303
2304
/**
2305
 * Returns a difficult to guess password.
2306
 */
2307
function api_generate_password(int $length = 8, $useRequirements = true): string
2308
{
2309
    if ($length < 2) {
2310
        $length = 2;
2311
    }
2312
2313
    $charactersLowerCase = 'abcdefghijkmnopqrstuvwxyz';
2314
    $charactersUpperCase = 'ABCDEFGHJKLMNPQRSTUVWXYZ';
2315
    $charactersSpecials = '!@#$%^&*()_+-=[]{}|;:,.<>?';
2316
    $minNumbers = 2;
2317
    $length = $length - $minNumbers;
2318
    $minLowerCase = round($length / 2);
2319
    $minUpperCase = $length - $minLowerCase;
2320
    $minSpecials = 1; // Default minimum special characters
2321
2322
    $password = '';
2323
    $passwordRequirements = $useRequirements ? Security::getPasswordRequirements() : [];
2324
2325
    $factory = new RandomLib\Factory();
2326
    $generator = $factory->getGenerator(new SecurityLib\Strength(SecurityLib\Strength::MEDIUM));
2327
2328
    if (!empty($passwordRequirements)) {
2329
        $length = $passwordRequirements['min']['length'];
2330
        $minNumbers = $passwordRequirements['min']['numeric'];
2331
        $minLowerCase = $passwordRequirements['min']['lowercase'];
2332
        $minUpperCase = $passwordRequirements['min']['uppercase'];
2333
        $minSpecials = $passwordRequirements['min']['specials'];
2334
2335
        $rest = $length - $minNumbers - $minLowerCase - $minUpperCase - $minSpecials;
2336
        // Add the rest to fill the length requirement
2337
        if ($rest > 0) {
2338
            $password .= $generator->generateString($rest, $charactersLowerCase.$charactersUpperCase);
2339
        }
2340
    }
2341
2342
    // Min digits default 2
2343
    for ($i = 0; $i < $minNumbers; $i++) {
2344
        $password .= $generator->generateInt(2, 9);
2345
    }
2346
2347
    // Min lowercase
2348
    $password .= $generator->generateString($minLowerCase, $charactersLowerCase);
2349
2350
    // Min uppercase
2351
    $password .= $generator->generateString($minUpperCase, $charactersUpperCase);
2352
2353
    // Min special characters
2354
    $password .= $generator->generateString($minSpecials, $charactersSpecials);
2355
2356
    // Shuffle the password to ensure randomness
2357
    $password = str_shuffle($password);
2358
2359
    return $password;
2360
}
2361
2362
/**
2363
 * Checks a password to see wether it is OK to use.
2364
 *
2365
 * @param string $password
2366
 *
2367
 * @return bool if the password is acceptable, false otherwise
2368
 *              Notes about what a password "OK to use" is:
2369
 *              1. The password should be at least 5 characters long.
2370
 *              2. Only English letters (uppercase or lowercase, it doesn't matter) and digits are allowed.
2371
 *              3. The password should contain at least 3 letters.
2372
 *              4. It should contain at least 2 digits.
2373
 *              Settings will change if the configuration value is set: password_requirements
2374
 */
2375
function api_check_password($password)
2376
{
2377
    $passwordRequirements = Security::getPasswordRequirements();
2378
2379
    $minLength = $passwordRequirements['min']['length'];
2380
    $minNumbers = $passwordRequirements['min']['numeric'];
2381
    // Optional
2382
    $minLowerCase = $passwordRequirements['min']['lowercase'];
2383
    $minUpperCase = $passwordRequirements['min']['uppercase'];
2384
2385
    $minLetters = $minLowerCase + $minUpperCase;
2386
    $passwordLength = api_strlen($password);
2387
2388
    $conditions = [
2389
        'min_length' => $passwordLength >= $minLength,
2390
    ];
2391
2392
    $digits = 0;
2393
    $lowerCase = 0;
2394
    $upperCase = 0;
2395
2396
    for ($i = 0; $i < $passwordLength; $i++) {
2397
        $currentCharacterCode = api_ord(api_substr($password, $i, 1));
2398
        if ($currentCharacterCode >= 65 && $currentCharacterCode <= 90) {
2399
            $upperCase++;
2400
        }
2401
2402
        if ($currentCharacterCode >= 97 && $currentCharacterCode <= 122) {
2403
            $lowerCase++;
2404
        }
2405
        if ($currentCharacterCode >= 48 && $currentCharacterCode <= 57) {
2406
            $digits++;
2407
        }
2408
    }
2409
2410
    // Min number of digits
2411
    $conditions['min_numeric'] = $digits >= $minNumbers;
2412
2413
    if (!empty($minUpperCase)) {
2414
        // Uppercase
2415
        $conditions['min_uppercase'] = $upperCase >= $minUpperCase;
2416
    }
2417
2418
    if (!empty($minLowerCase)) {
2419
        // Lowercase
2420
        $conditions['min_lowercase'] = $upperCase >= $minLowerCase;
2421
    }
2422
2423
    // Min letters
2424
    $letters = $upperCase + $lowerCase;
2425
    $conditions['min_letters'] = $letters >= $minLetters;
2426
2427
    $isPasswordOk = true;
2428
    foreach ($conditions as $condition) {
2429
        if (false === $condition) {
2430
            $isPasswordOk = false;
2431
            break;
2432
        }
2433
    }
2434
2435
    if (false === $isPasswordOk) {
2436
        $output = get_lang('The new password does not match the minimum security requirements').'<br />';
2437
        $output .= Security::getPasswordRequirementsToString($conditions);
2438
2439
        Display::addFlash(Display::return_message($output, 'warning', false));
2440
    }
2441
2442
    return $isPasswordOk;
2443
}
2444
2445
/**
2446
 * Gets the current Chamilo (not PHP/cookie) session ID.
2447
 *
2448
 * @return int O if no active session, the session ID otherwise
2449
 */
2450
function api_get_session_id()
2451
{
2452
    return (int) Session::read('sid', 0);
2453
}
2454
2455
/**
2456
 * Gets the current Chamilo (not social network) group ID.
2457
 *
2458
 * @return int O if no active session, the session ID otherwise
2459
 */
2460
function api_get_group_id()
2461
{
2462
    return Session::read('gid', 0);
2463
}
2464
2465
/**
2466
 * Gets the current or given session name.
2467
 *
2468
 * @param   int     Session ID (optional)
2469
 *
2470
 * @return string The session name, or null if not found
2471
 */
2472
function api_get_session_name($session_id = 0)
2473
{
2474
    if (empty($session_id)) {
2475
        $session_id = api_get_session_id();
2476
        if (empty($session_id)) {
2477
            return null;
2478
        }
2479
    }
2480
    $t = Database::get_main_table(TABLE_MAIN_SESSION);
2481
    $s = "SELECT title FROM $t WHERE id = ".(int) $session_id;
2482
    $r = Database::query($s);
2483
    $c = Database::num_rows($r);
2484
    if ($c > 0) {
2485
        //technically, there can be only one, but anyway we take the first
2486
        $rec = Database::fetch_array($r);
2487
2488
        return $rec['title'];
2489
    }
2490
2491
    return null;
2492
}
2493
2494
/**
2495
 * Gets the session info by id.
2496
 *
2497
 * @param int $id Session ID
2498
 *
2499
 * @return array information of the session
2500
 */
2501
function api_get_session_info($id)
2502
{
2503
    return SessionManager::fetch($id);
2504
}
2505
2506
/**
2507
 * Gets the session visibility by session id.
2508
 *
2509
 * @deprecated Use Session::setAccessVisibilityByUser() instead.
2510
 *
2511
 * @param int  $session_id
2512
 * @param int  $courseId
2513
 * @param bool $ignore_visibility_for_admins
2514
 *
2515
 * @return int
2516
 *             0 = session still available,
2517
 *             SESSION_VISIBLE_READ_ONLY = 1,
2518
 *             SESSION_VISIBLE = 2,
2519
 *             SESSION_INVISIBLE = 3
2520
 */
2521
function api_get_session_visibility(
2522
    $session_id,
2523
    $courseId = null,
2524
    $ignore_visibility_for_admins = true,
2525
    $userId = 0
2526
) {
2527
    if (api_is_platform_admin()) {
2528
        if ($ignore_visibility_for_admins) {
2529
            return SESSION_AVAILABLE;
2530
        }
2531
    }
2532
    $userId = empty($userId) ? api_get_user_id() : (int) $userId;
2533
2534
    $now = time();
2535
    if (empty($session_id)) {
2536
        return 0; // Means that the session is still available.
2537
    }
2538
2539
    $session_id = (int) $session_id;
2540
    $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
2541
2542
    $result = Database::query("SELECT * FROM $tbl_session WHERE id = $session_id");
2543
2544
    if (Database::num_rows($result) <= 0) {
2545
        return SESSION_INVISIBLE;
0 ignored issues
show
introduced by
The constant SESSION_INVISIBLE has been deprecated: Use Session::INVISIBLE ( Ignorable by Annotation )

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

2545
        return /** @scrutinizer ignore-deprecated */ SESSION_INVISIBLE;
Loading history...
2546
    }
2547
2548
    $row = Database::fetch_assoc($result);
2549
    $visibility = $row['visibility'];
2550
2551
    // I don't care the session visibility.
2552
    if (empty($row['access_start_date']) && empty($row['access_end_date'])) {
2553
        // Session duration per student.
2554
        if (isset($row['duration']) && !empty($row['duration'])) {
2555
            $duration = $row['duration'] * 24 * 60 * 60;
2556
            $courseAccess = CourseManager::getFirstCourseAccessPerSessionAndUser($session_id, $userId);
2557
2558
            // If there is a session duration but there is no previous
2559
            // access by the user, then the session is still available
2560
            if (0 == count($courseAccess)) {
2561
                return SESSION_AVAILABLE;
2562
            }
2563
2564
            $currentTime = time();
2565
            $firstAccess = isset($courseAccess['login_course_date'])
2566
                ? api_strtotime($courseAccess['login_course_date'], 'UTC')
2567
                : 0;
2568
            $userDurationData = SessionManager::getUserSession($userId, $session_id);
2569
            $userDuration = isset($userDurationData['duration'])
2570
                ? (intval($userDurationData['duration']) * 24 * 60 * 60)
2571
                : 0;
2572
2573
            $totalDuration = $firstAccess + $duration + $userDuration;
2574
2575
            return $totalDuration > $currentTime ? SESSION_AVAILABLE : SESSION_VISIBLE_READ_ONLY;
2576
        }
2577
2578
        return SESSION_AVAILABLE;
2579
    }
2580
2581
    // If start date was set.
2582
    if (!empty($row['access_start_date'])) {
2583
        $visibility = $now > api_strtotime($row['access_start_date'], 'UTC') ? SESSION_AVAILABLE : SESSION_INVISIBLE;
0 ignored issues
show
introduced by
The constant SESSION_INVISIBLE has been deprecated: Use Session::INVISIBLE ( Ignorable by Annotation )

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

2583
        $visibility = $now > api_strtotime($row['access_start_date'], 'UTC') ? SESSION_AVAILABLE : /** @scrutinizer ignore-deprecated */ SESSION_INVISIBLE;
Loading history...
2584
    } else {
2585
        // If there's no start date, assume it's available until the end date
2586
        $visibility = SESSION_AVAILABLE;
2587
    }
2588
2589
    // If the end date was set.
2590
    if (!empty($row['access_end_date'])) {
2591
        // Only if date_start said that it was ok
2592
        if (SESSION_AVAILABLE === $visibility) {
2593
            $visibility = $now < api_strtotime($row['access_end_date'], 'UTC')
2594
                ? SESSION_AVAILABLE // Date still available
2595
                : $row['visibility']; // Session ends
2596
        }
2597
    }
2598
2599
    // If I'm a coach the visibility can change in my favor depending in the coach dates.
2600
    $isCoach = api_is_coach($session_id, $courseId);
2601
2602
    if ($isCoach) {
2603
        // Test start date.
2604
        if (!empty($row['coach_access_start_date'])) {
2605
            $start = api_strtotime($row['coach_access_start_date'], 'UTC');
2606
            $visibility = $start < $now ? SESSION_AVAILABLE : SESSION_INVISIBLE;
0 ignored issues
show
introduced by
The constant SESSION_INVISIBLE has been deprecated: Use Session::INVISIBLE ( Ignorable by Annotation )

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

2606
            $visibility = $start < $now ? SESSION_AVAILABLE : /** @scrutinizer ignore-deprecated */ SESSION_INVISIBLE;
Loading history...
2607
        }
2608
2609
        // Test end date.
2610
        if (!empty($row['coach_access_end_date'])) {
2611
            if (SESSION_AVAILABLE === $visibility) {
2612
                $endDateCoach = api_strtotime($row['coach_access_end_date'], 'UTC');
2613
                $visibility = $endDateCoach >= $now ? SESSION_AVAILABLE : $row['visibility'];
2614
            }
2615
        }
2616
    }
2617
2618
    return $visibility;
2619
}
2620
2621
/**
2622
 * This function returns a (star) session icon if the session is not null and
2623
 * the user is not a student.
2624
 *
2625
 * @param int $sessionId
2626
 * @param int $statusId  User status id - if 5 (student), will return empty
2627
 *
2628
 * @return string Session icon
2629
 */
2630
function api_get_session_image($sessionId, User $user)
2631
{
2632
    $sessionId = (int) $sessionId;
2633
    $image = '';
2634
    if (!$user->isStudent()) {
2635
        // Check whether is not a student
2636
        if ($sessionId > 0) {
2637
            $image = '&nbsp;&nbsp;'.Display::getMdiIcon(
2638
                ObjectIcon::STAR,
2639
                'ch-tool-icon',
2640
                'align:absmiddle;',
2641
                ICON_SIZE_SMALL,
2642
                get_lang('Session-specific resource')
2643
            );
2644
        }
2645
    }
2646
2647
    return $image;
2648
}
2649
2650
/**
2651
 * This function add an additional condition according to the session of the course.
2652
 *
2653
 * @param int    $session_id        session id
2654
 * @param bool   $and               optional, true if more than one condition false if the only condition in the query
2655
 * @param bool   $with_base_content optional, true to accept content with session=0 as well,
2656
 *                                  false for strict session condition
2657
 * @param string $session_field
2658
 *
2659
 * @return string condition of the session
2660
 */
2661
function api_get_session_condition(
2662
    $session_id,
2663
    $and = true,
2664
    $with_base_content = false,
2665
    $session_field = 'session_id'
2666
) {
2667
    $session_id = (int) $session_id;
2668
2669
    if (empty($session_field)) {
2670
        $session_field = 'session_id';
2671
    }
2672
    // Condition to show resources by session
2673
    $condition_add = $and ? ' AND ' : ' WHERE ';
2674
2675
    if ($with_base_content) {
2676
        $condition_session = $condition_add." ( $session_field = $session_id OR $session_field = 0 OR $session_field IS NULL) ";
2677
    } else {
2678
        if (empty($session_id)) {
2679
            $condition_session = $condition_add." ($session_field = $session_id OR $session_field IS NULL)";
2680
        } else {
2681
            $condition_session = $condition_add." $session_field = $session_id ";
2682
        }
2683
    }
2684
2685
    return $condition_session;
2686
}
2687
2688
/**
2689
 * Returns the value of a setting from the web-adjustable admin config settings.
2690
 *
2691
 * WARNING true/false are stored as string, so when comparing you need to check e.g.
2692
 * if (api_get_setting('show_navigation_menu') == 'true') //CORRECT
2693
 * instead of
2694
 * if (api_get_setting('show_navigation_menu') == true) //INCORRECT
2695
 *
2696
 * @param string $variable The variable name
2697
 *
2698
 * @return string|array
2699
 */
2700
function api_get_setting($variable, $isArray = false, $key = null)
2701
{
2702
    $settingsManager = Container::getSettingsManager();
2703
    if (empty($settingsManager)) {
2704
        return '';
2705
    }
2706
    $variable = trim($variable);
2707
    // Normalize setting name: keep full name for lookup, extract short name for switch matching
2708
    $full   = $variable;
2709
    $short  = str_contains($variable, '.') ? substr($variable, strrpos($variable, '.') + 1) : $variable;
2710
2711
    switch ($short) {
2712
        case 'server_type':
2713
            $settingValue = $settingsManager->getSetting($full, true);
2714
            return $settingValue ?: 'prod';
2715
        case 'openid_authentication':
2716
        case 'service_ppt2lp':
2717
        case 'formLogin_hide_unhide_label':
2718
            return false;
2719
        case 'tool_visible_by_default_at_creation':
2720
            $values = $settingsManager->getSetting($full);
2721
            $newResult = [];
2722
            foreach ($values as $parameter) {
2723
                $newResult[$parameter] = 'true';
2724
            }
2725
2726
            return $newResult;
2727
2728
        default:
2729
            $settingValue = $settingsManager->getSetting($full, true);
2730
            if (is_string($settingValue) && $isArray && $settingValue !== '') {
2731
                // Check if the value is a valid JSON string
2732
                $decodedValue = json_decode($settingValue, true);
2733
2734
                // If it's a valid JSON string and the result is an array, return it
2735
                if (is_array($decodedValue)) {
2736
                    return $decodedValue;
2737
                }
2738
                $value = eval('return ' . rtrim($settingValue, ';') . ';');
0 ignored issues
show
introduced by
The use of eval() is discouraged.
Loading history...
2739
                if (is_array($value)) {
2740
                    return $value;
2741
                }
2742
            }
2743
2744
            // If the value is not a JSON array or wasn't returned previously, continue with the normal flow
2745
            if ($key !== null && isset($settingValue[$variable][$key])) {
2746
                return $settingValue[$variable][$key];
2747
            }
2748
2749
            return $settingValue;
2750
    }
2751
}
2752
2753
/**
2754
 * @param string $variable
2755
 * @param string $option
2756
 *
2757
 * @return bool
2758
 */
2759
function api_get_setting_in_list($variable, $option)
2760
{
2761
    $value = api_get_setting($variable);
2762
2763
    return in_array($option, $value);
2764
}
2765
2766
/**
2767
 * @param string $plugin
2768
 * @param string $variable
2769
 *
2770
 * @return string
2771
 */
2772
function api_get_plugin_setting($plugin, $variable)
2773
{
2774
    $variableName = $plugin.'_'.$variable;
2775
    //$result = api_get_setting($variableName);
2776
    $params = [
2777
        'category = ? AND subkey = ? AND variable = ?' => [
2778
            'Plugins',
2779
            $plugin,
2780
            $variableName,
2781
        ],
2782
    ];
2783
    $table = Database::get_main_table(TABLE_MAIN_SETTINGS);
2784
    $result = Database::select(
2785
        'selected_value',
2786
        $table,
2787
        ['where' => $params],
2788
        'one'
2789
    );
2790
    if ($result) {
2791
        $value = $result['selected_value'];
2792
        $serializedValue = @unserialize($result['selected_value'], []);
2793
        if (false !== $serializedValue) {
2794
            $value = $serializedValue;
2795
        }
2796
2797
        return $value;
2798
    }
2799
2800
    return null;
2801
    /// Old code
2802
2803
    $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...
2804
    $result = api_get_setting($variableName);
2805
2806
    if (isset($result[$plugin])) {
2807
        $value = $result[$plugin];
2808
2809
        $unserialized = UnserializeApi::unserialize('not_allowed_classes', $value, true);
2810
2811
        if (false !== $unserialized) {
2812
            $value = $unserialized;
2813
        }
2814
2815
        return $value;
2816
    }
2817
2818
    return null;
2819
}
2820
2821
/**
2822
 * Returns the value of a setting from the web-adjustable admin config settings.
2823
 */
2824
function api_get_settings_params($params)
2825
{
2826
    $table = Database::get_main_table(TABLE_MAIN_SETTINGS);
2827
2828
    return Database::select('*', $table, ['where' => $params]);
2829
}
2830
2831
/**
2832
 * @param array $params example: [id = ? => '1']
2833
 *
2834
 * @return array
2835
 */
2836
function api_get_settings_params_simple($params)
2837
{
2838
    $table = Database::get_main_table(TABLE_MAIN_SETTINGS);
2839
2840
    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...
2841
}
2842
2843
/**
2844
 * Returns the value of a setting from the web-adjustable admin config settings.
2845
 */
2846
function api_delete_settings_params($params)
2847
{
2848
    $table = Database::get_main_table(TABLE_MAIN_SETTINGS);
2849
2850
    return Database::delete($table, $params);
2851
}
2852
2853
/**
2854
 * Returns an escaped version of $_SERVER['PHP_SELF'] to avoid XSS injection.
2855
 *
2856
 * @return string Escaped version of $_SERVER['PHP_SELF']
2857
 */
2858
function api_get_self()
2859
{
2860
    return htmlentities($_SERVER['PHP_SELF']);
2861
}
2862
2863
/**
2864
 * Checks whether current user is a platform administrator.
2865
 *
2866
 * @param bool $allowSessionAdmins Whether session admins should be considered admins or not
2867
 * @param bool $allowDrh           Whether HR directors should be considered admins or not
2868
 *
2869
 * @return bool true if the user has platform admin rights,
2870
 *              false otherwise
2871
 *
2872
 * @see usermanager::is_admin(user_id) for a user-id specific function
2873
 */
2874
function api_is_platform_admin($allowSessionAdmins = false, $allowDrh = false)
2875
{
2876
    $currentUser = api_get_current_user();
2877
2878
    if (null === $currentUser) {
2879
        return false;
2880
    }
2881
2882
    $isAdmin = $currentUser->isAdmin() || $currentUser->isSuperAdmin();
2883
2884
    if ($isAdmin) {
2885
        return true;
2886
    }
2887
2888
    if ($allowSessionAdmins && $currentUser->isSessionAdmin()) {
2889
        return true;
2890
    }
2891
2892
    if ($allowDrh && $currentUser->isHRM()) {
2893
        return true;
2894
    }
2895
2896
    return false;
2897
}
2898
2899
/**
2900
 * Checks whether the user given as user id is in the admin table.
2901
 *
2902
 * @param int $user_id If none provided, will use current user
2903
 * @param int $url     URL ID. If provided, also check if the user is active on given URL
2904
 *
2905
 * @return bool True if the user is admin, false otherwise
2906
 */
2907
function api_is_platform_admin_by_id($user_id = null, $url = null)
2908
{
2909
    $user_id = (int) $user_id;
2910
    if (empty($user_id)) {
2911
        $user_id = api_get_user_id();
2912
    }
2913
    $admin_table = Database::get_main_table(TABLE_MAIN_ADMIN);
2914
    $sql = "SELECT * FROM $admin_table WHERE user_id = $user_id";
2915
    $res = Database::query($sql);
2916
    $is_admin = 1 === Database::num_rows($res);
2917
    if (!$is_admin || !isset($url)) {
2918
        return $is_admin;
2919
    }
2920
    // We get here only if $url is set
2921
    $url = (int) $url;
2922
    $url_user_table = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
2923
    $sql = "SELECT * FROM $url_user_table
2924
            WHERE access_url_id = $url AND user_id = $user_id";
2925
    $res = Database::query($sql);
2926
2927
    return 1 === Database::num_rows($res);
2928
}
2929
2930
/**
2931
 * Checks whether current user is allowed to create courses.
2932
 *
2933
 * @return bool true if the user has course creation rights,
2934
 *              false otherwise
2935
 */
2936
function api_is_allowed_to_create_course()
2937
{
2938
    if (api_is_platform_admin()) {
2939
        return true;
2940
    }
2941
2942
    // Teachers can only create courses
2943
    if (api_is_teacher()) {
2944
        if ('true' === api_get_setting('allow_users_to_create_courses')) {
2945
            return true;
2946
        } else {
2947
            return false;
2948
        }
2949
    }
2950
2951
    return Session::read('is_allowedCreateCourse');
2952
}
2953
2954
/**
2955
 * Checks whether the current user is a course administrator.
2956
 *
2957
 * @return bool True if current user is a course administrator
2958
 */
2959
function api_is_course_admin()
2960
{
2961
    if (api_is_platform_admin()) {
2962
        return true;
2963
    }
2964
2965
    $user = api_get_current_user();
2966
    if ($user) {
2967
        if (
2968
            $user->hasRole('ROLE_CURRENT_COURSE_SESSION_TEACHER') ||
2969
            $user->hasRole('ROLE_CURRENT_COURSE_TEACHER')
2970
        ) {
2971
            return true;
2972
        }
2973
    }
2974
2975
    return false;
2976
}
2977
2978
/**
2979
 * Checks whether the current user is a course coach
2980
 * Based on the presence of user in session_rel_user.relation_type (as session general coach, value 3).
2981
 *
2982
 * @return bool True if current user is a course coach
2983
 */
2984
function api_is_session_general_coach()
2985
{
2986
    return Session::read('is_session_general_coach');
2987
}
2988
2989
/**
2990
 * Checks whether the current user is a course tutor
2991
 * Based on the presence of user in session_rel_course_rel_user.user_id with status = 2.
2992
 *
2993
 * @return bool True if current user is a course tutor
2994
 */
2995
function api_is_course_tutor()
2996
{
2997
    return Session::read('is_courseTutor');
2998
}
2999
3000
/**
3001
 * @param int $user_id
3002
 * @param int $courseId
3003
 * @param int $session_id
3004
 *
3005
 * @return bool
3006
 */
3007
function api_is_course_session_coach($user_id, $courseId, $session_id)
3008
{
3009
    $session_table = Database::get_main_table(TABLE_MAIN_SESSION);
3010
    $session_rel_course_rel_user_table = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
3011
3012
    $user_id = (int) $user_id;
3013
    $session_id = (int) $session_id;
3014
    $courseId = (int) $courseId;
3015
3016
    $sql = "SELECT DISTINCT session.id
3017
            FROM $session_table
3018
            INNER JOIN $session_rel_course_rel_user_table session_rc_ru
3019
            ON session.id = session_rc_ru.session_id
3020
            WHERE
3021
                session_rc_ru.user_id = '".$user_id."'  AND
3022
                session_rc_ru.c_id = '$courseId' AND
3023
                session_rc_ru.status = ".SessionEntity::COURSE_COACH." AND
3024
                session_rc_ru.session_id = '$session_id'";
3025
    $result = Database::query($sql);
3026
3027
    return Database::num_rows($result) > 0;
3028
}
3029
3030
/**
3031
 * Checks whether the current user is a course or session coach.
3032
 *
3033
 * @param int $session_id
3034
 * @param int $courseId
3035
 * @param bool  Check whether we are in student view and, if we are, return false
3036
 * @param int $userId
3037
 *
3038
 * @return bool True if current user is a course or session coach
3039
 */
3040
function api_is_coach($session_id = 0, $courseId = null, $check_student_view = true, $userId = 0)
3041
{
3042
    $userId = empty($userId) ? api_get_user_id() : (int) $userId;
3043
3044
    if (!empty($session_id)) {
3045
        $session_id = (int) $session_id;
3046
    } else {
3047
        $session_id = api_get_session_id();
3048
    }
3049
3050
    // The student preview was on
3051
    if ($check_student_view && api_is_student_view_active()) {
3052
        return false;
3053
    }
3054
3055
    if (!empty($courseId)) {
3056
        $courseId = (int) $courseId;
3057
    } else {
3058
        $courseId = api_get_course_int_id();
3059
    }
3060
3061
    $session_table = Database::get_main_table(TABLE_MAIN_SESSION);
3062
    $session_rel_course_rel_user_table = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
3063
    $tblSessionRelUser = Database::get_main_table(TABLE_MAIN_SESSION_USER);
3064
    $sessionIsCoach = [];
3065
3066
    if (!empty($courseId)) {
3067
        $sql = "SELECT DISTINCT s.id, title, access_start_date, access_end_date
3068
                FROM $session_table s
3069
                INNER JOIN $session_rel_course_rel_user_table session_rc_ru
3070
                ON session_rc_ru.session_id = s.id AND session_rc_ru.user_id = '".$userId."'
3071
                WHERE
3072
                    session_rc_ru.c_id = '$courseId' AND
3073
                    session_rc_ru.status =".SessionEntity::COURSE_COACH." AND
3074
                    session_rc_ru.session_id = '$session_id'";
3075
        $result = Database::query($sql);
3076
        $sessionIsCoach = Database::store_result($result);
3077
    }
3078
3079
    if (!empty($session_id)) {
3080
        $sql = "SELECT DISTINCT s.id
3081
                FROM $session_table AS s
3082
                INNER JOIN $tblSessionRelUser sru
3083
                ON s.id = sru.session_id
3084
                WHERE
3085
                    sru.user_id = $userId AND
3086
                    s.id = $session_id AND
3087
                    sru.relation_type = ".SessionEntity::GENERAL_COACH."
3088
                ORDER BY s.access_start_date, s.access_end_date, s.title";
3089
        $result = Database::query($sql);
3090
        if (!empty($sessionIsCoach)) {
3091
            $sessionIsCoach = array_merge(
3092
                $sessionIsCoach,
3093
                Database::store_result($result)
3094
            );
3095
        } else {
3096
            $sessionIsCoach = Database::store_result($result);
3097
        }
3098
    }
3099
3100
    return count($sessionIsCoach) > 0;
3101
}
3102
3103
function api_user_has_role(string $role, ?User $user = null): bool
3104
{
3105
    if (null === $user) {
3106
        $user = api_get_current_user();
3107
    }
3108
3109
    if (null === $user) {
3110
        return false;
3111
    }
3112
3113
    return $user->hasRole($role);
3114
}
3115
3116
function api_is_allowed_in_course(): bool
3117
{
3118
    if (api_is_platform_admin()) {
3119
        return true;
3120
    }
3121
3122
    $user = api_get_current_user();
3123
    if ($user instanceof User) {
3124
        if ($user->hasRole('ROLE_CURRENT_COURSE_SESSION_STUDENT') ||
3125
            $user->hasRole('ROLE_CURRENT_COURSE_SESSION_TEACHER') ||
3126
            $user->hasRole('ROLE_CURRENT_COURSE_STUDENT') ||
3127
            $user->hasRole('ROLE_CURRENT_COURSE_TEACHER')
3128
        ) {
3129
            return true;
3130
        }
3131
    }
3132
3133
    return false;
3134
}
3135
3136
/**
3137
 * Checks whether current user is a student boss.
3138
 */
3139
function api_is_student_boss(?User $user = null): bool
3140
{
3141
    return api_user_has_role('ROLE_STUDENT_BOSS', $user);
3142
}
3143
3144
/**
3145
 * Checks whether the current user is a session administrator.
3146
 *
3147
 * @return bool True if current user is a course administrator
3148
 */
3149
function api_is_session_admin(?User $user = null)
3150
{
3151
    return api_user_has_role('ROLE_SESSION_MANAGER', $user);
3152
}
3153
3154
/**
3155
 * Checks whether the current user is a human resources manager.
3156
 *
3157
 * @return bool True if current user is a human resources manager
3158
 */
3159
function api_is_drh()
3160
{
3161
    return api_user_has_role('ROLE_HR');
3162
}
3163
3164
/**
3165
 * Checks whether the current user is a student.
3166
 *
3167
 * @return bool True if current user is a human resources manager
3168
 */
3169
function api_is_student()
3170
{
3171
    return api_user_has_role('ROLE_STUDENT');
3172
}
3173
3174
/**
3175
 * Checks whether the current user has the status 'teacher'.
3176
 *
3177
 * @return bool True if current user is a human resources manager
3178
 */
3179
function api_is_teacher()
3180
{
3181
    return api_user_has_role('ROLE_TEACHER');
3182
}
3183
3184
/**
3185
 * Checks whether the current user is a invited user.
3186
 *
3187
 * @return bool
3188
 */
3189
function api_is_invitee()
3190
{
3191
    return api_user_has_role('ROLE_INVITEE');
3192
}
3193
3194
/**
3195
 * This function checks whether a session is assigned into a category.
3196
 *
3197
 * @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...
3198
 * @param string    - category name
3199
 *
3200
 * @return bool - true if is found, otherwise false
3201
 */
3202
function api_is_session_in_category($session_id, $category_name)
3203
{
3204
    $session_id = (int) $session_id;
3205
    $category_name = Database::escape_string($category_name);
3206
    $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
3207
    $tbl_session_category = Database::get_main_table(TABLE_MAIN_SESSION_CATEGORY);
3208
3209
    $sql = "SELECT 1
3210
            FROM $tbl_session
3211
            WHERE $session_id IN (
3212
                SELECT s.id FROM $tbl_session s, $tbl_session_category sc
3213
                WHERE
3214
                  s.session_category_id = sc.id AND
3215
                  sc.name LIKE '%$category_name'
3216
            )";
3217
    $rs = Database::query($sql);
3218
3219
    if (Database::num_rows($rs) > 0) {
3220
        return true;
3221
    }
3222
3223
    return false;
3224
}
3225
3226
/**
3227
 * Displays options for switching between student view and course manager view.
3228
 *
3229
 * Changes in version 1.2 (Patrick Cool)
3230
 * Student view switch now behaves as a real switch. It maintains its current state until the state
3231
 * is changed explicitly
3232
 *
3233
 * Changes in version 1.1 (Patrick Cool)
3234
 * student view now works correctly in subfolders of the document tool
3235
 * student view works correctly in the new links tool
3236
 *
3237
 * Example code for using this in your tools:
3238
 * //if ($is_courseAdmin && api_get_setting('student_view_enabled') == 'true') {
3239
 * //   display_tool_view_option($isStudentView);
3240
 * //}
3241
 * //and in later sections, use api_is_allowed_to_edit()
3242
 *
3243
 * @author Roan Embrechts
3244
 * @author Patrick Cool
3245
 * @author Julio Montoya, changes added in Chamilo
3246
 *
3247
 * @version 1.2
3248
 *
3249
 * @todo rewrite code so it is easier to understand
3250
 */
3251
function api_display_tool_view_option()
3252
{
3253
    if ('true' != api_get_setting('student_view_enabled')) {
3254
        return '';
3255
    }
3256
3257
    $sourceurl = '';
3258
    $is_framed = false;
3259
    // Exceptions apply for all multi-frames pages
3260
    if (false !== strpos($_SERVER['REQUEST_URI'], 'chat/chat_banner.php')) {
3261
        // The chat is a multiframe bit that doesn't work too well with the student_view, so do not show the link
3262
        return '';
3263
    }
3264
3265
    // Uncomment to remove student view link from document view page
3266
    if (false !== strpos($_SERVER['REQUEST_URI'], 'lp/lp_header.php')) {
3267
        if (empty($_GET['lp_id'])) {
3268
            return '';
3269
        }
3270
        $sourceurl = substr($_SERVER['REQUEST_URI'], 0, strpos($_SERVER['REQUEST_URI'], '?'));
3271
        $sourceurl = str_replace(
3272
            'lp/lp_header.php',
3273
            'lp/lp_controller.php?'.api_get_cidreq().'&action=view&lp_id='.intval($_GET['lp_id']).'&isStudentView='.('studentview' == $_SESSION['studentview'] ? 'false' : 'true'),
3274
            $sourceurl
3275
        );
3276
        //showinframes doesn't handle student view anyway...
3277
        //return '';
3278
        $is_framed = true;
3279
    }
3280
3281
    // Check whether the $_SERVER['REQUEST_URI'] contains already url parameters (thus a questionmark)
3282
    if (!$is_framed) {
3283
        if (false === strpos($_SERVER['REQUEST_URI'], '?')) {
3284
            $sourceurl = api_get_self().'?'.api_get_cidreq();
3285
        } else {
3286
            $sourceurl = $_SERVER['REQUEST_URI'];
3287
        }
3288
    }
3289
3290
    $output_string = '';
3291
    if (!empty($_SESSION['studentview'])) {
3292
        if ('studentview' == $_SESSION['studentview']) {
3293
            // We have to remove the isStudentView=true from the $sourceurl
3294
            $sourceurl = str_replace('&isStudentView=true', '', $sourceurl);
3295
            $sourceurl = str_replace('&isStudentView=false', '', $sourceurl);
3296
            $output_string .= '<a class="btn btn--primary btn-sm" href="'.$sourceurl.'&isStudentView=false" target="_self">'.
3297
                Display::getMdiIcon('eye').' '.get_lang('Switch to teacher view').'</a>';
3298
        } elseif ('teacherview' == $_SESSION['studentview']) {
3299
            // Switching to teacherview
3300
            $sourceurl = str_replace('&isStudentView=true', '', $sourceurl);
3301
            $sourceurl = str_replace('&isStudentView=false', '', $sourceurl);
3302
            $output_string .= '<a class="btn btn--plain btn-sm" href="'.$sourceurl.'&isStudentView=true" target="_self">'.
3303
                Display::getMdiIcon('eye').' '.get_lang('Switch to student view').'</a>';
3304
        }
3305
    } else {
3306
        $output_string .= '<a class="btn btn--plain btn-sm" href="'.$sourceurl.'&isStudentView=true" target="_self">'.
3307
            Display::getMdiIcon('eye').' '.get_lang('Switch to student view').'</a>';
3308
    }
3309
    $output_string = Security::remove_XSS($output_string);
3310
    $html = Display::tag('div', $output_string, ['class' => 'view-options']);
3311
3312
    return $html;
3313
}
3314
3315
/**
3316
 * Function that removes the need to directly use is_courseAdmin global in
3317
 * tool scripts. It returns true or false depending on the user's rights in
3318
 * this particular course.
3319
 * Optionally checking for tutor and coach roles here allows us to use the
3320
 * student_view feature altogether with these roles as well.
3321
 *
3322
 * @param bool  Whether to check if the user has the tutor role
3323
 * @param bool  Whether to check if the user has the coach role
3324
 * @param bool  Whether to check if the user has the session coach role
3325
 * @param bool  check the student view or not
3326
 *
3327
 * @author Roan Embrechts
3328
 * @author Patrick Cool
3329
 * @author Julio Montoya
3330
 *
3331
 * @version 1.1, February 2004
3332
 *
3333
 * @return bool true: the user has the rights to edit, false: he does not
3334
 */
3335
function api_is_allowed_to_edit(
3336
    $tutor = false,
3337
    $coach = false,
3338
    $session_coach = false,
3339
    $check_student_view = true
3340
) {
3341
    $allowSessionAdminEdit = 'true' === api_get_setting('session.session_admins_edit_courses_content');
3342
    // Admins can edit anything.
3343
    if (api_is_platform_admin($allowSessionAdminEdit)) {
3344
        //The student preview was on
3345
        if ($check_student_view && api_is_student_view_active()) {
3346
            return false;
3347
        }
3348
3349
        return true;
3350
    }
3351
3352
    $sessionId = api_get_session_id();
3353
3354
    if ($sessionId && 'true' === api_get_setting('session.session_courses_read_only_mode')) {
3355
        $efv = new ExtraFieldValue('course');
3356
        $lockExrafieldField = $efv->get_values_by_handler_and_field_variable(
3357
            api_get_course_int_id(),
3358
            'session_courses_read_only_mode'
3359
        );
3360
3361
        if (!empty($lockExrafieldField['value'])) {
3362
            return false;
3363
        }
3364
    }
3365
3366
    $is_allowed_coach_to_edit = api_is_coach(null, null, $check_student_view);
3367
    $session_visibility = api_get_session_visibility($sessionId);
0 ignored issues
show
Deprecated Code introduced by
The function api_get_session_visibility() has been deprecated: Use Session::setAccessVisibilityByUser() instead. ( Ignorable by Annotation )

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

3367
    $session_visibility = /** @scrutinizer ignore-deprecated */ api_get_session_visibility($sessionId);

This function has been deprecated. The supplier of the function has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed and what other function to use instead.

Loading history...
3368
    $is_courseAdmin = api_is_course_admin();
3369
3370
    if (!$is_courseAdmin && $tutor) {
3371
        // If we also want to check if the user is a tutor...
3372
        $is_courseAdmin = $is_courseAdmin || api_is_course_tutor();
3373
    }
3374
3375
    if (!$is_courseAdmin && $coach) {
3376
        // If we also want to check if the user is a coach...';
3377
        // Check if session visibility is read only for coaches.
3378
        if (SESSION_VISIBLE_READ_ONLY == $session_visibility) {
3379
            $is_allowed_coach_to_edit = false;
3380
        }
3381
3382
        if ('true' === api_get_setting('allow_coach_to_edit_course_session')) {
3383
            // Check if coach is allowed to edit a course.
3384
            $is_courseAdmin = $is_courseAdmin || $is_allowed_coach_to_edit;
3385
        }
3386
    }
3387
3388
    if (!$is_courseAdmin && $session_coach) {
3389
        $is_courseAdmin = $is_courseAdmin || $is_allowed_coach_to_edit;
3390
    }
3391
3392
    // Check if the student_view is enabled, and if so, if it is activated.
3393
    if ('true' === api_get_setting('student_view_enabled')) {
3394
        $studentView = api_is_student_view_active();
3395
        if (!empty($sessionId)) {
3396
            // Check if session visibility is read only for coaches.
3397
            if (SESSION_VISIBLE_READ_ONLY == $session_visibility) {
3398
                $is_allowed_coach_to_edit = false;
3399
            }
3400
3401
            $is_allowed = false;
3402
            if ('true' === api_get_setting('allow_coach_to_edit_course_session')) {
3403
                // Check if coach is allowed to edit a course.
3404
                $is_allowed = $is_allowed_coach_to_edit;
3405
            }
3406
            if ($check_student_view) {
3407
                $is_allowed = $is_allowed && false === $studentView;
3408
            }
3409
        } else {
3410
            $is_allowed = $is_courseAdmin;
3411
            if ($check_student_view) {
3412
                $is_allowed = $is_courseAdmin && false === $studentView;
3413
            }
3414
        }
3415
3416
        return $is_allowed;
3417
    } else {
3418
        return $is_courseAdmin;
3419
    }
3420
}
3421
3422
/**
3423
 * Returns true if user is a course coach of at least one course in session.
3424
 *
3425
 * @param int $sessionId
3426
 *
3427
 * @return bool
3428
 */
3429
function api_is_coach_of_course_in_session($sessionId)
3430
{
3431
    if (api_is_platform_admin()) {
3432
        return true;
3433
    }
3434
3435
    $userId = api_get_user_id();
3436
    $courseList = UserManager::get_courses_list_by_session(
3437
        $userId,
3438
        $sessionId
3439
    );
3440
3441
    // Session visibility.
3442
    $visibility = api_get_session_visibility(
0 ignored issues
show
Deprecated Code introduced by
The function api_get_session_visibility() has been deprecated: Use Session::setAccessVisibilityByUser() instead. ( Ignorable by Annotation )

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

3442
    $visibility = /** @scrutinizer ignore-deprecated */ api_get_session_visibility(

This function has been deprecated. The supplier of the function has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed and what other function to use instead.

Loading history...
3443
        $sessionId,
3444
        null,
3445
        false
3446
    );
3447
3448
    if (SESSION_VISIBLE != $visibility && !empty($courseList)) {
3449
        // Course Coach session visibility.
3450
        $blockedCourseCount = 0;
3451
        $closedVisibilityList = [
3452
            COURSE_VISIBILITY_CLOSED,
3453
            COURSE_VISIBILITY_HIDDEN,
3454
        ];
3455
3456
        foreach ($courseList as $course) {
3457
            // Checking session visibility
3458
            $sessionCourseVisibility = api_get_session_visibility(
0 ignored issues
show
Deprecated Code introduced by
The function api_get_session_visibility() has been deprecated: Use Session::setAccessVisibilityByUser() instead. ( Ignorable by Annotation )

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

3458
            $sessionCourseVisibility = /** @scrutinizer ignore-deprecated */ api_get_session_visibility(

This function has been deprecated. The supplier of the function has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed and what other function to use instead.

Loading history...
3459
                $sessionId,
3460
                $course['real_id']
3461
            );
3462
3463
            $courseIsVisible = !in_array(
3464
                $course['visibility'],
3465
                $closedVisibilityList
3466
            );
3467
            if (false === $courseIsVisible || SESSION_INVISIBLE == $sessionCourseVisibility) {
0 ignored issues
show
introduced by
The constant SESSION_INVISIBLE has been deprecated: Use Session::INVISIBLE ( Ignorable by Annotation )

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

3467
            if (false === $courseIsVisible || /** @scrutinizer ignore-deprecated */ SESSION_INVISIBLE == $sessionCourseVisibility) {
Loading history...
3468
                $blockedCourseCount++;
3469
            }
3470
        }
3471
3472
        // If all courses are blocked then no show in the list.
3473
        if ($blockedCourseCount === count($courseList)) {
3474
            $visibility = SESSION_INVISIBLE;
0 ignored issues
show
introduced by
The constant SESSION_INVISIBLE has been deprecated: Use Session::INVISIBLE ( Ignorable by Annotation )

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

3474
            $visibility = /** @scrutinizer ignore-deprecated */ SESSION_INVISIBLE;
Loading history...
3475
        } else {
3476
            $visibility = SESSION_VISIBLE;
3477
        }
3478
    }
3479
3480
    switch ($visibility) {
3481
        case SESSION_VISIBLE_READ_ONLY:
3482
        case SESSION_VISIBLE:
3483
        case SESSION_AVAILABLE:
3484
            return true;
3485
            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...
3486
        case SESSION_INVISIBLE:
0 ignored issues
show
introduced by
The constant SESSION_INVISIBLE has been deprecated: Use Session::INVISIBLE ( Ignorable by Annotation )

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

3486
        case /** @scrutinizer ignore-deprecated */ SESSION_INVISIBLE:
Loading history...
3487
            return false;
3488
    }
3489
3490
    return false;
3491
}
3492
3493
/**
3494
 * Checks if a student can edit contents in a session depending
3495
 * on the session visibility.
3496
 *
3497
 * @param bool $tutor Whether to check if the user has the tutor role
3498
 * @param bool $coach Whether to check if the user has the coach role
3499
 *
3500
 * @return bool true: the user has the rights to edit, false: he does not
3501
 */
3502
function api_is_allowed_to_session_edit($tutor = false, $coach = false)
3503
{
3504
    if (api_is_allowed_to_edit($tutor, $coach)) {
3505
        // If I'm a teacher, I will return true in order to not affect the normal behaviour of Chamilo tools.
3506
        return true;
3507
    } else {
3508
        $sessionId = api_get_session_id();
3509
3510
        if (0 == $sessionId) {
3511
            // I'm not in a session so i will return true to not affect the normal behaviour of Chamilo tools.
3512
            return true;
3513
        } else {
3514
            // I'm in a session and I'm a student
3515
            // Get the session visibility
3516
            $session_visibility = api_get_session_visibility($sessionId);
0 ignored issues
show
Deprecated Code introduced by
The function api_get_session_visibility() has been deprecated: Use Session::setAccessVisibilityByUser() instead. ( Ignorable by Annotation )

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

3516
            $session_visibility = /** @scrutinizer ignore-deprecated */ api_get_session_visibility($sessionId);

This function has been deprecated. The supplier of the function has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed and what other function to use instead.

Loading history...
3517
            // if 5 the session is still available
3518
            switch ($session_visibility) {
3519
                case SESSION_VISIBLE_READ_ONLY: // 1
3520
                    return false;
3521
                case SESSION_VISIBLE:           // 2
3522
                    return true;
3523
                case SESSION_INVISIBLE:         // 3
0 ignored issues
show
introduced by
The constant SESSION_INVISIBLE has been deprecated: Use Session::INVISIBLE ( Ignorable by Annotation )

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

3523
                case /** @scrutinizer ignore-deprecated */ SESSION_INVISIBLE:         // 3
Loading history...
3524
                    return false;
3525
                case SESSION_AVAILABLE:         //5
3526
                    return true;
3527
            }
3528
        }
3529
    }
3530
3531
    return false;
3532
}
3533
3534
/**
3535
 * Current user is anon?
3536
 *
3537
 * @return bool true if this user is anonymous, false otherwise
3538
 */
3539
function api_is_anonymous()
3540
{
3541
    return !Container::getAuthorizationChecker()->isGranted('IS_AUTHENTICATED');
3542
}
3543
3544
/**
3545
 * Displays message "You are not allowed here..." and exits the entire script.
3546
 */
3547
function api_not_allowed(
3548
    bool $printHeaders = false,
3549
    string $message = null,
3550
    int $responseCode = 0,
3551
    string $severity = 'warning'
3552
): never {
3553
    throw new NotAllowedException(
3554
        $message ?: get_lang('You are not allowed'),
3555
        $severity,
3556
        403,
3557
        [],
3558
        $responseCode,
3559
        null
3560
    );
3561
}
3562
3563
/**
3564
 * @param string $languageIsoCode
3565
 *
3566
 * @return string
3567
 */
3568
function languageToCountryIsoCode($languageIsoCode)
3569
{
3570
    $allow = ('true' === api_get_setting('language.language_flags_by_country'));
3571
3572
    // @todo save in DB
3573
    switch ($languageIsoCode) {
3574
        case 'ar':
3575
            $country = 'ae';
3576
            break;
3577
        case 'bs':
3578
            $country = 'ba';
3579
            break;
3580
        case 'ca':
3581
            $country = 'es';
3582
            if ($allow) {
3583
                $country = 'catalan';
3584
            }
3585
            break;
3586
        case 'cs':
3587
            $country = 'cz';
3588
            break;
3589
        case 'da':
3590
            $country = 'dk';
3591
            break;
3592
        case 'el':
3593
            $country = 'ae';
3594
            break;
3595
        case 'en':
3596
            $country = 'gb';
3597
            break;
3598
        case 'eu': // Euskera
3599
            $country = 'es';
3600
            if ($allow) {
3601
                $country = 'basque';
3602
            }
3603
            break;
3604
        case 'gl': // galego
3605
            $country = 'es';
3606
            if ($allow) {
3607
                $country = 'galician';
3608
            }
3609
            break;
3610
        case 'he':
3611
            $country = 'il';
3612
            break;
3613
        case 'ja':
3614
            $country = 'jp';
3615
            break;
3616
        case 'ka':
3617
            $country = 'ge';
3618
            break;
3619
        case 'ko':
3620
            $country = 'kr';
3621
            break;
3622
        case 'ms':
3623
            $country = 'my';
3624
            break;
3625
        case 'pt-BR':
3626
            $country = 'br';
3627
            break;
3628
        case 'qu':
3629
            $country = 'pe';
3630
            break;
3631
        case 'sl':
3632
            $country = 'si';
3633
            break;
3634
        case 'sv':
3635
            $country = 'se';
3636
            break;
3637
        case 'uk': // Ukraine
3638
            $country = 'ua';
3639
            break;
3640
        case 'zh-TW':
3641
        case 'zh':
3642
            $country = 'cn';
3643
            break;
3644
        default:
3645
            $country = $languageIsoCode;
3646
            break;
3647
    }
3648
    $country = strtolower($country);
3649
3650
    return $country;
3651
}
3652
3653
/**
3654
 * Returns a list of all the languages that are made available by the admin.
3655
 *
3656
 * @return array An array with all languages. Structure of the array is
3657
 *               array['name'] = An array with the name of every language
3658
 *               array['folder'] = An array with the corresponding names of the language-folders in the filesystem
3659
 */
3660
function api_get_languages()
3661
{
3662
    $table = Database::get_main_table(TABLE_MAIN_LANGUAGE);
3663
    $sql = "SELECT * FROM $table WHERE available='1'
3664
            ORDER BY original_name ASC";
3665
    $result = Database::query($sql);
3666
    $languages = [];
3667
    while ($row = Database::fetch_assoc($result)) {
3668
        $languages[$row['isocode']] = $row['original_name'];
3669
    }
3670
3671
    return $languages;
3672
}
3673
3674
/**
3675
 * Returns the id (the database id) of a language.
3676
 *
3677
 * @param   string  language name (the corresponding name of the language-folder in the filesystem)
3678
 *
3679
 * @return int id of the language
3680
 */
3681
function api_get_language_id($language)
3682
{
3683
    $tbl_language = Database::get_main_table(TABLE_MAIN_LANGUAGE);
3684
    if (empty($language)) {
3685
        return null;
3686
    }
3687
3688
    // We check the language by iscocode
3689
    $langInfo = api_get_language_from_iso($language);
3690
    if (null !== $langInfo && !empty($langInfo->getId())) {
3691
        return $langInfo->getId();
3692
    }
3693
3694
    $language = Database::escape_string($language);
3695
    $sql = "SELECT id FROM $tbl_language
3696
            WHERE english_name = '$language' LIMIT 1";
3697
    $result = Database::query($sql);
3698
    $row = Database::fetch_array($result);
3699
3700
    return $row['id'];
3701
}
3702
3703
/**
3704
 * Get the language information by its id.
3705
 *
3706
 * @param int $languageId
3707
 *
3708
 * @throws Exception
3709
 *
3710
 * @return array
3711
 */
3712
function api_get_language_info($languageId)
3713
{
3714
    if (empty($languageId)) {
3715
        return [];
3716
    }
3717
3718
    $language = Database::getManager()->find(Language::class, $languageId);
3719
3720
    if (!$language) {
3721
        return [];
3722
    }
3723
3724
    return [
3725
        'id' => $language->getId(),
3726
        'original_name' => $language->getOriginalName(),
3727
        'english_name' => $language->getEnglishName(),
3728
        'isocode' => $language->getIsocode(),
3729
        'available' => $language->getAvailable(),
3730
        'parent_id' => $language->getParent() ? $language->getParent()->getId() : null,
3731
    ];
3732
}
3733
3734
/**
3735
 * @param string $code
3736
 *
3737
 * @return Language
3738
 */
3739
function api_get_language_from_iso($code)
3740
{
3741
    $em = Database::getManager();
3742
3743
    return $em->getRepository(Language::class)->findOneBy(['isocode' => $code]);
3744
}
3745
3746
/**
3747
 * Shortcut to ThemeHelper::getVisualTheme()
3748
 */
3749
function api_get_visual_theme(): string
3750
{
3751
    $themeHelper = Container::$container->get(ThemeHelper::class);
3752
3753
    return $themeHelper->getVisualTheme();
3754
}
3755
3756
/**
3757
 * Returns a list of CSS themes currently available in the CSS folder
3758
 * The folder must have a default.css file.
3759
 *
3760
 * @param bool $getOnlyThemeFromVirtualInstance Used by the vchamilo plugin
3761
 *
3762
 * @return array list of themes directories from the css folder
3763
 *               Note: Directory names (names of themes) in the file system should contain ASCII-characters only
3764
 */
3765
function api_get_themes($getOnlyThemeFromVirtualInstance = false)
3766
{
3767
    // This configuration value is set by the vchamilo plugin
3768
    $virtualTheme = api_get_configuration_value('virtual_css_theme_folder');
3769
3770
    $readCssFolder = function ($dir) use ($virtualTheme) {
3771
        $finder = new Finder();
3772
        $themes = $finder->directories()->in($dir)->depth(0)->sortByName();
3773
        $list = [];
3774
        /** @var Symfony\Component\Finder\SplFileInfo $theme */
3775
        foreach ($themes as $theme) {
3776
            $folder = $theme->getFilename();
3777
            // A theme folder is consider if there's a default.css file
3778
            if (!file_exists($theme->getPathname().'/default.css')) {
3779
                continue;
3780
            }
3781
            $name = ucwords(str_replace('_', ' ', $folder));
3782
            if ($folder == $virtualTheme) {
3783
                continue;
3784
            }
3785
            $list[$folder] = $name;
3786
        }
3787
3788
        return $list;
3789
    };
3790
3791
    $dir = Container::getProjectDir().'var/themes/';
3792
    $list = $readCssFolder($dir);
3793
3794
    if (!empty($virtualTheme)) {
3795
        $newList = $readCssFolder($dir.'/'.$virtualTheme);
3796
        if ($getOnlyThemeFromVirtualInstance) {
3797
            return $newList;
3798
        }
3799
        $list = $list + $newList;
3800
        asort($list);
3801
    }
3802
3803
    return $list;
3804
}
3805
3806
/**
3807
 * Find the largest sort value in a given user_course_category
3808
 * This function is used when we are moving a course to a different category
3809
 * and also when a user subscribes to courses (the new course is added at the end of the main category.
3810
 *
3811
 * @param int $courseCategoryId the id of the user_course_category
3812
 * @param int $userId
3813
 *
3814
 * @return int the value of the highest sort of the user_course_category
3815
 */
3816
function api_max_sort_value($courseCategoryId, $userId)
3817
{
3818
    $user = api_get_user_entity($userId);
3819
    $userCourseCategory = Database::getManager()->getRepository(UserCourseCategory::class)->find($courseCategoryId);
3820
3821
    return null === $user ? 0 : $user->getMaxSortValue($userCourseCategory);
3822
}
3823
3824
/**
3825
 * Transforms a number of seconds in hh:mm:ss format.
3826
 *
3827
 * @author Julian Prud'homme
3828
 *
3829
 * @param int    $seconds      number of seconds
3830
 * @param string $space
3831
 * @param bool   $showSeconds
3832
 * @param bool   $roundMinutes
3833
 *
3834
 * @return string the formatted time
3835
 */
3836
function api_time_to_hms($seconds, $space = ':', $showSeconds = true, $roundMinutes = false)
3837
{
3838
    // $seconds = -1 means that we have wrong data in the db.
3839
    if (-1 == $seconds) {
3840
        return
3841
            get_lang('Unknown').
3842
            Display::getMdiIcon(
3843
                ActionIcon::INFORMATION,
3844
                'ch-tool-icon',
3845
                'align: absmiddle; hspace: 3px',
3846
                ICON_SIZE_SMALL,
3847
                get_lang('The datas about this user were registered when the calculation of time spent on the platform wasn\'t possible.')
3848
            );
3849
    }
3850
3851
    // How many hours ?
3852
    $hours = floor($seconds / 3600);
3853
3854
    // How many minutes ?
3855
    $min = floor(($seconds - ($hours * 3600)) / 60);
3856
3857
    if ($roundMinutes) {
3858
        if ($min >= 45) {
3859
            $min = 45;
3860
        }
3861
3862
        if ($min >= 30 && $min <= 44) {
3863
            $min = 30;
3864
        }
3865
3866
        if ($min >= 15 && $min <= 29) {
3867
            $min = 15;
3868
        }
3869
3870
        if ($min >= 0 && $min <= 14) {
3871
            $min = 0;
3872
        }
3873
    }
3874
3875
    // How many seconds
3876
    $sec = floor($seconds - ($hours * 3600) - ($min * 60));
3877
3878
    if ($hours < 10) {
3879
        $hours = "0$hours";
3880
    }
3881
3882
    if ($sec < 10) {
3883
        $sec = "0$sec";
3884
    }
3885
3886
    if ($min < 10) {
3887
        $min = "0$min";
3888
    }
3889
3890
    $seconds = '';
3891
    if ($showSeconds) {
3892
        $seconds = $space.$sec;
3893
    }
3894
3895
    return $hours.$space.$min.$seconds;
3896
}
3897
3898
/**
3899
 * Returns the permissions to be assigned to every newly created directory by the web-server.
3900
 * The return value is based on the platform administrator's setting
3901
 * "Administration > Configuration settings > Security > Permissions for new directories".
3902
 *
3903
 * @return int returns the permissions in the format "Owner-Group-Others, Read-Write-Execute", as an integer value
3904
 */
3905
function api_get_permissions_for_new_directories()
3906
{
3907
    static $permissions;
3908
    if (!isset($permissions)) {
3909
        $permissions = trim(api_get_setting('permissions_for_new_directories'));
3910
        // The default value 0777 is according to that in the platform administration panel after fresh system installation.
3911
        $permissions = octdec(!empty($permissions) ? $permissions : '0777');
3912
    }
3913
3914
    return $permissions;
3915
}
3916
3917
/**
3918
 * Returns the permissions to be assigned to every newly created directory by the web-server.
3919
 * The return value is based on the platform administrator's setting
3920
 * "Administration > Configuration settings > Security > Permissions for new files".
3921
 *
3922
 * @return int returns the permissions in the format
3923
 *             "Owner-Group-Others, Read-Write-Execute", as an integer value
3924
 */
3925
function api_get_permissions_for_new_files()
3926
{
3927
    static $permissions;
3928
    if (!isset($permissions)) {
3929
        $permissions = trim(api_get_setting('permissions_for_new_files'));
3930
        // The default value 0666 is according to that in the platform
3931
        // administration panel after fresh system installation.
3932
        $permissions = octdec(!empty($permissions) ? $permissions : '0666');
3933
    }
3934
3935
    return $permissions;
3936
}
3937
3938
/**
3939
 * Deletes a file, or a folder and its contents.
3940
 *
3941
 * @author      Aidan Lister <[email protected]>
3942
 *
3943
 * @version     1.0.3
3944
 *
3945
 * @param string $dirname Directory to delete
3946
 * @param       bool     Deletes only the content or not
3947
 * @param bool $strict if one folder/file fails stop the loop
3948
 *
3949
 * @return bool Returns TRUE on success, FALSE on failure
3950
 *
3951
 * @see http://aidanlister.com/2004/04/recursively-deleting-a-folder-in-php/
3952
 *
3953
 * @author      Yannick Warnier, adaptation for the Chamilo LMS, April, 2008
3954
 * @author      Ivan Tcholakov, a sanity check about Directory class creation has been added, September, 2009
3955
 */
3956
function rmdirr($dirname, $delete_only_content_in_folder = false, $strict = false)
3957
{
3958
    $res = true;
3959
    // A sanity check.
3960
    if (!file_exists($dirname)) {
3961
        return false;
3962
    }
3963
    $php_errormsg = '';
3964
    // Simple delete for a file.
3965
    if (is_file($dirname) || is_link($dirname)) {
3966
        $res = unlink($dirname);
3967
        if (false === $res) {
3968
            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);
3969
        }
3970
3971
        return $res;
3972
    }
3973
3974
    // Loop through the folder.
3975
    $dir = dir($dirname);
3976
    // A sanity check.
3977
    $is_object_dir = is_object($dir);
3978
    if ($is_object_dir) {
3979
        while (false !== $entry = $dir->read()) {
3980
            // Skip pointers.
3981
            if ('.' == $entry || '..' == $entry) {
3982
                continue;
3983
            }
3984
3985
            // Recurse.
3986
            if ($strict) {
3987
                $result = rmdirr("$dirname/$entry");
3988
                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...
3989
                    $res = false;
3990
                    break;
3991
                }
3992
            } else {
3993
                rmdirr("$dirname/$entry");
3994
            }
3995
        }
3996
    }
3997
3998
    // Clean up.
3999
    if ($is_object_dir) {
4000
        $dir->close();
4001
    }
4002
4003
    if (false == $delete_only_content_in_folder) {
4004
        $res = rmdir($dirname);
4005
        if (false === $res) {
4006
            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);
4007
        }
4008
    }
4009
4010
    return $res;
4011
}
4012
4013
// TODO: This function is to be simplified. File access modes to be implemented.
4014
/**
4015
 * function adapted from a php.net comment
4016
 * copy recursively a folder.
4017
 *
4018
 * @param the source folder
4019
 * @param the dest folder
4020
 * @param an array of excluded file_name (without extension)
4021
 * @param copied_files the returned array of copied files
4022
 * @param string $source
4023
 * @param string $dest
4024
 */
4025
function copyr($source, $dest, $exclude = [], $copied_files = [])
4026
{
4027
    if (empty($dest)) {
4028
        return false;
4029
    }
4030
    // Simple copy for a file
4031
    if (is_file($source)) {
4032
        $path_info = pathinfo($source);
4033
        if (!in_array($path_info['filename'], $exclude)) {
4034
            copy($source, $dest);
4035
        }
4036
4037
        return true;
4038
    } elseif (!is_dir($source)) {
4039
        //then source is not a dir nor a file, return
4040
        return false;
4041
    }
4042
4043
    // Make destination directory.
4044
    if (!is_dir($dest)) {
4045
        mkdir($dest, api_get_permissions_for_new_directories());
4046
    }
4047
4048
    // Loop through the folder.
4049
    $dir = dir($source);
4050
    while (false !== $entry = $dir->read()) {
4051
        // Skip pointers
4052
        if ('.' == $entry || '..' == $entry) {
4053
            continue;
4054
        }
4055
4056
        // Deep copy directories.
4057
        if ($dest !== "$source/$entry") {
4058
            $files = copyr("$source/$entry", "$dest/$entry", $exclude, $copied_files);
4059
        }
4060
    }
4061
    // Clean up.
4062
    $dir->close();
4063
4064
    return true;
4065
}
4066
4067
/**
4068
 * @todo: Using DIRECTORY_SEPARATOR is not recommended, this is an obsolete approach.
4069
 * Documentation header to be added here.
4070
 *
4071
 * @param string $pathname
4072
 * @param string $base_path_document
4073
 * @param int    $session_id
4074
 *
4075
 * @return mixed True if directory already exists, false if a file already exists at
4076
 *               the destination and null if everything goes according to plan
4077
 */
4078
function copy_folder_course_session(
4079
    $pathname,
4080
    $base_path_document,
4081
    $session_id,
4082
    $course_info,
4083
    $document,
4084
    $source_course_id,
4085
    array $originalFolderNameList = [],
4086
    string $originalBaseName = ''
4087
) {
4088
    $table = Database::get_course_table(TABLE_DOCUMENT);
4089
    $session_id = intval($session_id);
4090
    $source_course_id = intval($source_course_id);
4091
4092
    // Check whether directory already exists.
4093
    if (empty($pathname) || is_dir($pathname)) {
4094
        return true;
4095
    }
4096
4097
    // Ensure that a file with the same name does not already exist.
4098
    if (is_file($pathname)) {
4099
        trigger_error('copy_folder_course_session(): File exists', E_USER_WARNING);
4100
4101
        return false;
4102
    }
4103
4104
    $baseNoDocument = str_replace('document', '', $originalBaseName);
4105
    $folderTitles = explode('/', $baseNoDocument);
4106
    $folderTitles = array_filter($folderTitles);
4107
4108
    $table = Database::get_course_table(TABLE_DOCUMENT);
4109
    $session_id = (int) $session_id;
4110
    $source_course_id = (int) $source_course_id;
4111
4112
    $course_id = $course_info['real_id'];
4113
    $folders = explode(DIRECTORY_SEPARATOR, str_replace($base_path_document.DIRECTORY_SEPARATOR, '', $pathname));
4114
    $new_pathname = $base_path_document;
4115
    $path = '';
4116
4117
    foreach ($folders as $index => $folder) {
4118
        $new_pathname .= DIRECTORY_SEPARATOR.$folder;
4119
        $path .= DIRECTORY_SEPARATOR.$folder;
4120
4121
        if (!file_exists($new_pathname)) {
4122
            $path = Database::escape_string($path);
4123
4124
            $sql = "SELECT * FROM $table
4125
                    WHERE
4126
                        c_id = $source_course_id AND
4127
                        path = '$path' AND
4128
                        filetype = 'folder' AND
4129
                        session_id = '$session_id'";
4130
            $rs1 = Database::query($sql);
4131
            $num_rows = Database::num_rows($rs1);
4132
4133
            if (0 == $num_rows) {
4134
                mkdir($new_pathname, api_get_permissions_for_new_directories());
4135
                $title = basename($new_pathname);
4136
4137
                if (isset($folderTitles[$index + 1])) {
4138
                    $checkPath = $folderTitles[$index +1];
4139
4140
                    if (isset($originalFolderNameList[$checkPath])) {
4141
                        $title = $originalFolderNameList[$checkPath];
4142
                    }
4143
                }
4144
4145
                // Insert new folder with destination session_id.
4146
                $params = [
4147
                    'c_id' => $course_id,
4148
                    'path' => $path,
4149
                    'comment' => $document->comment,
4150
                    'title' => $title,
4151
                    'filetype' => 'folder',
4152
                    'size' => '0',
4153
                    'session_id' => $session_id,
4154
                ];
4155
                Database::insert($table, $params);
4156
            }
4157
        }
4158
    } // en foreach
4159
}
4160
4161
// TODO: chmodr() is a better name. Some corrections are needed. Documentation header to be added here.
4162
/**
4163
 * @param string $path
4164
 */
4165
function api_chmod_R($path, $filemode)
4166
{
4167
    if (!is_dir($path)) {
4168
        return chmod($path, $filemode);
4169
    }
4170
4171
    $handler = opendir($path);
4172
    while ($file = readdir($handler)) {
4173
        if ('.' != $file && '..' != $file) {
4174
            $fullpath = "$path/$file";
4175
            if (!is_dir($fullpath)) {
4176
                if (!chmod($fullpath, $filemode)) {
4177
                    return false;
4178
                }
4179
            } else {
4180
                if (!api_chmod_R($fullpath, $filemode)) {
4181
                    return false;
4182
                }
4183
            }
4184
        }
4185
    }
4186
4187
    closedir($handler);
4188
4189
    return chmod($path, $filemode);
4190
}
4191
4192
// TODO: Where the following function has been copy/pased from? There is no information about author and license. Style, coding conventions...
4193
/**
4194
 * Parse info file format. (e.g: file.info).
4195
 *
4196
 * Files should use an ini-like format to specify values.
4197
 * White-space generally doesn't matter, except inside values.
4198
 * e.g.
4199
 *
4200
 * @verbatim
4201
 *   key = value
4202
 *   key = "value"
4203
 *   key = 'value'
4204
 *   key = "multi-line
4205
 *
4206
 *   value"
4207
 *   key = 'multi-line
4208
 *
4209
 *   value'
4210
 *   key
4211
 *   =
4212
 *   'value'
4213
 * @endverbatim
4214
 *
4215
 * Arrays are created using a GET-like syntax:
4216
 *
4217
 * @verbatim
4218
 *   key[] = "numeric array"
4219
 *   key[index] = "associative array"
4220
 *   key[index][] = "nested numeric array"
4221
 *   key[index][index] = "nested associative array"
4222
 * @endverbatim
4223
 *
4224
 * PHP constants are substituted in, but only when used as the entire value:
4225
 *
4226
 * Comments should start with a semi-colon at the beginning of a line.
4227
 *
4228
 * This function is NOT for placing arbitrary module-specific settings. Use
4229
 * variable_get() and variable_set() for that.
4230
 *
4231
 * Information stored in the module.info file:
4232
 * - name: The real name of the module for display purposes.
4233
 * - description: A brief description of the module.
4234
 * - dependencies: An array of shortnames of other modules this module depends on.
4235
 * - package: The name of the package of modules this module belongs to.
4236
 *
4237
 * Example of .info file:
4238
 * <code>
4239
 * @verbatim
4240
 *   name = Forum
4241
 *   description = Enables threaded discussions about general topics.
4242
 *   dependencies[] = taxonomy
4243
 *   dependencies[] = comment
4244
 *   package = Core - optional
4245
 *   version = VERSION
4246
 * @endverbatim
4247
 * </code>
4248
 *
4249
 * @param string $filename
4250
 *                         The file we are parsing. Accepts file with relative or absolute path.
4251
 *
4252
 * @return
4253
 *   The info array
4254
 */
4255
function api_parse_info_file($filename)
4256
{
4257
    $info = [];
4258
4259
    if (!file_exists($filename)) {
4260
        return $info;
4261
    }
4262
4263
    $data = file_get_contents($filename);
4264
    if (preg_match_all('
4265
        @^\s*                           # Start at the beginning of a line, ignoring leading whitespace
4266
        ((?:
4267
          [^=;\[\]]|                    # Key names cannot contain equal signs, semi-colons or square brackets,
4268
          \[[^\[\]]*\]                  # unless they are balanced and not nested
4269
        )+?)
4270
        \s*=\s*                         # Key/value pairs are separated by equal signs (ignoring white-space)
4271
        (?:
4272
          ("(?:[^"]|(?<=\\\\)")*")|     # Double-quoted string, which may contain slash-escaped quotes/slashes
4273
          (\'(?:[^\']|(?<=\\\\)\')*\')| # Single-quoted string, which may contain slash-escaped quotes/slashes
4274
          ([^\r\n]*?)                   # Non-quoted string
4275
        )\s*$                           # Stop at the next end of a line, ignoring trailing whitespace
4276
        @msx', $data, $matches, PREG_SET_ORDER)) {
4277
        $key = $value1 = $value2 = $value3 = '';
4278
        foreach ($matches as $match) {
4279
            // Fetch the key and value string.
4280
            $i = 0;
4281
            foreach (['key', 'value1', 'value2', 'value3'] as $var) {
4282
                $$var = isset($match[++$i]) ? $match[$i] : '';
4283
            }
4284
            $value = stripslashes(substr($value1, 1, -1)).stripslashes(substr($value2, 1, -1)).$value3;
4285
4286
            // Parse array syntax.
4287
            $keys = preg_split('/\]?\[/', rtrim($key, ']'));
4288
            $last = array_pop($keys);
4289
            $parent = &$info;
4290
4291
            // Create nested arrays.
4292
            foreach ($keys as $key) {
4293
                if ('' == $key) {
4294
                    $key = count($parent);
4295
                }
4296
                if (!isset($parent[$key]) || !is_array($parent[$key])) {
4297
                    $parent[$key] = [];
4298
                }
4299
                $parent = &$parent[$key];
4300
            }
4301
4302
            // Handle PHP constants.
4303
            if (defined($value)) {
4304
                $value = constant($value);
4305
            }
4306
4307
            // Insert actual value.
4308
            if ('' == $last) {
4309
                $last = count($parent);
4310
            }
4311
            $parent[$last] = $value;
4312
        }
4313
    }
4314
4315
    return $info;
4316
}
4317
4318
/**
4319
 * Gets Chamilo version from the configuration files.
4320
 *
4321
 * @return string A string of type "1.8.4", or an empty string if the version could not be found
4322
 */
4323
function api_get_version()
4324
{
4325
    return (string) api_get_configuration_value('system_version');
4326
}
4327
4328
/**
4329
 * Gets the software name (the name/brand of the Chamilo-based customized system).
4330
 *
4331
 * @return string
4332
 */
4333
function api_get_software_name()
4334
{
4335
    $name = api_get_env_variable('SOFTWARE_NAME', 'Chamilo');
4336
    return $name;
4337
}
4338
4339
function api_get_status_list()
4340
{
4341
    $list = [];
4342
    // Table of status
4343
    $list[COURSEMANAGER] = 'teacher'; // 1
4344
    $list[SESSIONADMIN] = 'session_admin'; // 3
4345
    $list[DRH] = 'drh'; // 4
4346
    $list[STUDENT] = 'user'; // 5
4347
    $list[ANONYMOUS] = 'anonymous'; // 6
4348
    $list[INVITEE] = 'invited'; // 20
4349
4350
    return $list;
4351
}
4352
4353
/**
4354
 * Checks whether status given in parameter exists in the platform.
4355
 *
4356
 * @param mixed the status (can be either int either string)
4357
 *
4358
 * @return bool if the status exists, else returns false
4359
 */
4360
function api_status_exists($status_asked)
4361
{
4362
    $list = api_get_status_list();
4363
4364
    return in_array($status_asked, $list) ? true : isset($list[$status_asked]);
4365
}
4366
4367
/**
4368
 * Checks whether status given in parameter exists in the platform. The function
4369
 * returns the status ID or false if it does not exist, but given the fact there
4370
 * is no "0" status, the return value can be checked against
4371
 * if(api_status_key()) to know if it exists.
4372
 *
4373
 * @param   mixed   The status (can be either int or string)
4374
 *
4375
 * @return mixed Status ID if exists, false otherwise
4376
 */
4377
function api_status_key($status)
4378
{
4379
    $list = api_get_status_list();
4380
4381
    return isset($list[$status]) ? $status : array_search($status, $list);
4382
}
4383
4384
/**
4385
 * Gets the status langvars list.
4386
 *
4387
 * @return string[] the list of status with their translations
4388
 */
4389
function api_get_status_langvars()
4390
{
4391
    return [
4392
        COURSEMANAGER => get_lang('Teacher'),
4393
        SESSIONADMIN => get_lang('Sessions administrator'),
4394
        DRH => get_lang('Human Resources Manager'),
4395
        STUDENT => get_lang('Learner'),
4396
        ANONYMOUS => get_lang('Anonymous'),
4397
        STUDENT_BOSS => get_lang('Student boss'),
4398
        INVITEE => get_lang('Invited'),
4399
    ];
4400
}
4401
4402
/**
4403
 * The function that retrieves all the possible settings for a certain config setting.
4404
 *
4405
 * @author Patrick Cool <[email protected]>, Ghent University
4406
 */
4407
function api_get_settings_options($var)
4408
{
4409
    $table_settings_options = Database::get_main_table(TABLE_MAIN_SETTINGS_OPTIONS);
4410
    $var = Database::escape_string($var);
4411
    $sql = "SELECT * FROM $table_settings_options
4412
            WHERE variable = '$var'
4413
            ORDER BY id";
4414
    $result = Database::query($sql);
4415
    $settings_options_array = [];
4416
    while ($row = Database::fetch_assoc($result)) {
4417
        $settings_options_array[] = $row;
4418
    }
4419
4420
    return $settings_options_array;
4421
}
4422
4423
/**
4424
 * @param array $params
4425
 */
4426
function api_set_setting_option($params)
4427
{
4428
    $table = Database::get_main_table(TABLE_MAIN_SETTINGS_OPTIONS);
4429
    if (empty($params['id'])) {
4430
        Database::insert($table, $params);
4431
    } else {
4432
        Database::update($table, $params, ['id = ? ' => $params['id']]);
4433
    }
4434
}
4435
4436
/**
4437
 * @param array $params
4438
 */
4439
function api_set_setting_simple($params)
4440
{
4441
    $table = Database::get_main_table(TABLE_MAIN_SETTINGS);
4442
    $url_id = api_get_current_access_url_id();
4443
4444
    if (empty($params['id'])) {
4445
        $params['access_url'] = $url_id;
4446
        Database::insert($table, $params);
4447
    } else {
4448
        Database::update($table, $params, ['id = ? ' => [$params['id']]]);
4449
    }
4450
}
4451
4452
/**
4453
 * @param int $id
4454
 */
4455
function api_delete_setting_option($id)
4456
{
4457
    $table = Database::get_main_table(TABLE_MAIN_SETTINGS_OPTIONS);
4458
    if (!empty($id)) {
4459
        Database::delete($table, ['id = ? ' => $id]);
4460
    }
4461
}
4462
4463
/**
4464
 * Sets a platform configuration setting to a given value.
4465
 *
4466
 * @param string    The variable we want to update
4467
 * @param string    The value we want to record
4468
 * @param string    The sub-variable if any (in most cases, this will remain null)
4469
 * @param string    The category if any (in most cases, this will remain null)
4470
 * @param int       The access_url for which this parameter is valid
4471
 * @param string $cat
4472
 *
4473
 * @return bool|null
4474
 */
4475
function api_set_setting($var, $value, $subvar = null, $cat = null, $access_url = 1)
4476
{
4477
    if (empty($var)) {
4478
        return false;
4479
    }
4480
    $t_settings = Database::get_main_table(TABLE_MAIN_SETTINGS);
4481
    $var = Database::escape_string($var);
4482
    $value = Database::escape_string($value);
4483
    $access_url = (int) $access_url;
4484
    if (empty($access_url)) {
4485
        $access_url = 1;
4486
    }
4487
    $select = "SELECT id FROM $t_settings WHERE variable = '$var' ";
4488
    if (!empty($subvar)) {
4489
        $subvar = Database::escape_string($subvar);
4490
        $select .= " AND subkey = '$subvar'";
4491
    }
4492
    if (!empty($cat)) {
4493
        $cat = Database::escape_string($cat);
4494
        $select .= " AND category = '$cat'";
4495
    }
4496
    if ($access_url > 1) {
4497
        $select .= " AND access_url = $access_url";
4498
    } else {
4499
        $select .= " AND access_url = 1 ";
4500
    }
4501
4502
    $res = Database::query($select);
4503
    if (Database::num_rows($res) > 0) {
4504
        // Found item for this access_url.
4505
        $row = Database::fetch_array($res);
4506
        $sql = "UPDATE $t_settings SET selected_value = '$value'
4507
                WHERE id = ".$row['id'];
4508
        Database::query($sql);
4509
    } else {
4510
        // Item not found for this access_url, we have to check if it exist with access_url = 1
4511
        $select = "SELECT * FROM $t_settings
4512
                   WHERE variable = '$var' AND access_url = 1 ";
4513
        // Just in case
4514
        if (1 == $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
            if (Database::num_rows($res) > 0) {
4523
                // We have a setting for access_url 1, but none for the current one, so create one.
4524
                $row = Database::fetch_array($res);
4525
                $insert = "INSERT INTO $t_settings (variable, subkey, type,category, selected_value, title, comment, scope, subkeytext, access_url)
4526
                        VALUES
4527
                        ('".$row['variable']."',".(!empty($row['subkey']) ? "'".$row['subkey']."'" : "NULL").",".
4528
                    "'".$row['type']."','".$row['category']."',".
4529
                    "'$value','".$row['title']."',".
4530
                    "".(!empty($row['comment']) ? "'".$row['comment']."'" : "NULL").",".(!empty($row['scope']) ? "'".$row['scope']."'" : "NULL").",".
4531
                    "".(!empty($row['subkeytext']) ? "'".$row['subkeytext']."'" : "NULL").",$access_url)";
4532
                Database::query($insert);
4533
            } else {
4534
                // Such a setting does not exist.
4535
                //error_log(__FILE__.':'.__LINE__.': Attempting to update setting '.$var.' ('.$subvar.') which does not exist at all', 0);
4536
            }
4537
        } else {
4538
            // Other access url.
4539
            if (!empty($subvar)) {
4540
                $select .= " AND subkey = '$subvar'";
4541
            }
4542
            if (!empty($cat)) {
4543
                $select .= " AND category = '$cat'";
4544
            }
4545
            $res = Database::query($select);
4546
4547
            if (Database::num_rows($res) > 0) {
4548
                // We have a setting for access_url 1, but none for the current one, so create one.
4549
                $row = Database::fetch_array($res);
4550
                if (1 == $row['access_url_changeable']) {
4551
                    $insert = "INSERT INTO $t_settings (variable,subkey, type,category, selected_value,title, comment,scope, subkeytext,access_url, access_url_changeable) VALUES
4552
                            ('".$row['variable']."',".
4553
                        (!empty($row['subkey']) ? "'".$row['subkey']."'" : "NULL").",".
4554
                        "'".$row['type']."','".$row['category']."',".
4555
                        "'$value','".$row['title']."',".
4556
                        "".(!empty($row['comment']) ? "'".$row['comment']."'" : "NULL").",".
4557
                        (!empty($row['scope']) ? "'".$row['scope']."'" : "NULL").",".
4558
                        "".(!empty($row['subkeytext']) ? "'".$row['subkeytext']."'" : "NULL").",$access_url,".$row['access_url_changeable'].")";
4559
                    Database::query($insert);
4560
                }
4561
            } else { // Such a setting does not exist.
4562
                //error_log(__FILE__.':'.__LINE__.': Attempting to update setting '.$var.' ('.$subvar.') which does not exist at all. The access_url is: '.$access_url.' ',0);
4563
            }
4564
        }
4565
    }
4566
}
4567
4568
/**
4569
 * Sets a whole category of settings to one specific value.
4570
 *
4571
 * @param string    Category
4572
 * @param string    Value
4573
 * @param int       Access URL. Optional. Defaults to 1
4574
 * @param array     Optional array of filters on field type
4575
 * @param string $category
4576
 * @param string $value
4577
 *
4578
 * @return bool
4579
 */
4580
function api_set_settings_category($category, $value = null, $access_url = 1, $fieldtype = [])
4581
{
4582
    if (empty($category)) {
4583
        return false;
4584
    }
4585
    $category = Database::escape_string($category);
4586
    $t_s = Database::get_main_table(TABLE_MAIN_SETTINGS);
4587
    $access_url = (int) $access_url;
4588
    if (empty($access_url)) {
4589
        $access_url = 1;
4590
    }
4591
    if (isset($value)) {
4592
        $value = Database::escape_string($value);
4593
        $sql = "UPDATE $t_s SET selected_value = '$value'
4594
                WHERE category = '$category' AND access_url = $access_url";
4595
        if (is_array($fieldtype) && count($fieldtype) > 0) {
4596
            $sql .= " AND ( ";
4597
            $i = 0;
4598
            foreach ($fieldtype as $type) {
4599
                if ($i > 0) {
4600
                    $sql .= ' OR ';
4601
                }
4602
                $type = Database::escape_string($type);
4603
                $sql .= " type='".$type."' ";
4604
                $i++;
4605
            }
4606
            $sql .= ")";
4607
        }
4608
        $res = Database::query($sql);
4609
4610
        return false !== $res;
4611
    } else {
4612
        $sql = "UPDATE $t_s SET selected_value = NULL
4613
                WHERE category = '$category' AND access_url = $access_url";
4614
        if (is_array($fieldtype) && count($fieldtype) > 0) {
4615
            $sql .= " AND ( ";
4616
            $i = 0;
4617
            foreach ($fieldtype as $type) {
4618
                if ($i > 0) {
4619
                    $sql .= ' OR ';
4620
                }
4621
                $type = Database::escape_string($type);
4622
                $sql .= " type='".$type."' ";
4623
                $i++;
4624
            }
4625
            $sql .= ")";
4626
        }
4627
        $res = Database::query($sql);
4628
4629
        return false !== $res;
4630
    }
4631
}
4632
4633
/**
4634
 * Gets all available access urls in an array (as in the database).
4635
 *
4636
 * @return array An array of database records
4637
 */
4638
function api_get_access_urls($from = 0, $to = 1000000, $order = 'url', $direction = 'ASC')
4639
{
4640
    $table = Database::get_main_table(TABLE_MAIN_ACCESS_URL);
4641
    $from = (int) $from;
4642
    $to = (int) $to;
4643
    $order = Database::escape_string($order);
4644
    $direction = Database::escape_string($direction);
4645
    $direction = !in_array(strtolower(trim($direction)), ['asc', 'desc']) ? 'asc' : $direction;
4646
    $sql = "SELECT id, url, description, active, created_by, tms
4647
            FROM $table
4648
            ORDER BY `$order` $direction
4649
            LIMIT $to OFFSET $from";
4650
    $res = Database::query($sql);
4651
4652
    return Database::store_result($res);
4653
}
4654
4655
/**
4656
 * Gets the access url info in an array.
4657
 *
4658
 * @param int  $id            Id of the access url
4659
 * @param bool $returnDefault Set to false if you want the real URL if URL 1 is still 'http://localhost/'
4660
 *
4661
 * @return array All the info (url, description, active, created_by, tms)
4662
 *               from the access_url table
4663
 *
4664
 * @author Julio Montoya
4665
 */
4666
function api_get_access_url($id, $returnDefault = true)
4667
{
4668
    static $staticResult;
4669
    $id = (int) $id;
4670
4671
    if (isset($staticResult[$id])) {
4672
        $result = $staticResult[$id];
4673
    } else {
4674
        // Calling the Database:: library dont work this is handmade.
4675
        $table_access_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL);
4676
        $sql = "SELECT url, description, active, created_by, tms
4677
                FROM $table_access_url WHERE id = '$id' ";
4678
        $res = Database::query($sql);
4679
        $result = @Database::fetch_array($res);
4680
        $staticResult[$id] = $result;
4681
    }
4682
4683
    // If the result url is 'http://localhost/' (the default) and the root_web
4684
    // (=current url) is different, and the $id is = 1 (which might mean
4685
    // api_get_current_access_url_id() returned 1 by default), then return the
4686
    // root_web setting instead of the current URL
4687
    // This is provided as an option to avoid breaking the storage of URL-specific
4688
    // homepages in home/localhost/
4689
    if (1 === $id && false === $returnDefault) {
4690
        $currentUrl = api_get_current_access_url_id();
4691
        // only do this if we are on the main URL (=1), otherwise we could get
4692
        // information on another URL instead of the one asked as parameter
4693
        if (1 === $currentUrl) {
4694
            $rootWeb = api_get_path(WEB_PATH);
4695
            $default = AccessUrl::DEFAULT_ACCESS_URL;
4696
            if ($result['url'] === $default && $rootWeb != $default) {
4697
                $result['url'] = $rootWeb;
4698
            }
4699
        }
4700
    }
4701
4702
    return $result;
4703
}
4704
4705
/**
4706
 * Gets all the current settings for a specific access url.
4707
 *
4708
 * @param string    The category, if any, that we want to get
4709
 * @param string    Whether we want a simple list (display a category) or
4710
 * a grouped list (group by variable as in settings.php default). Values: 'list' or 'group'
4711
 * @param int       Access URL's ID. Optional. Uses 1 by default, which is the unique URL
4712
 *
4713
 * @return array Array of database results for the current settings of the current access URL
4714
 */
4715
function &api_get_settings($cat = null, $ordering = 'list', $access_url = 1, $url_changeable = 0)
4716
{
4717
    $table = Database::get_main_table(TABLE_MAIN_SETTINGS);
4718
    $access_url = (int) $access_url;
4719
    $where_condition = '';
4720
    if (1 == $url_changeable) {
4721
        $where_condition = " AND access_url_changeable= '1' ";
4722
    }
4723
    if (empty($access_url) || -1 == $access_url) {
4724
        $access_url = 1;
4725
    }
4726
    $sql = "SELECT * FROM $table
4727
            WHERE access_url = $access_url  $where_condition ";
4728
4729
    if (!empty($cat)) {
4730
        $cat = Database::escape_string($cat);
4731
        $sql .= " AND category='$cat' ";
4732
    }
4733
    if ('group' == $ordering) {
4734
        $sql .= " ORDER BY id ASC";
4735
    } else {
4736
        $sql .= " ORDER BY 1,2 ASC";
4737
    }
4738
    $result = Database::query($sql);
4739
    if (null === $result) {
4740
        $result = [];
4741
        return $result;
4742
    }
4743
    $result = Database::store_result($result, 'ASSOC');
4744
4745
    return $result;
4746
}
4747
4748
/**
4749
 * @param string $value       The value we want to record
4750
 * @param string $variable    The variable name we want to insert
4751
 * @param string $subKey      The subkey for the variable we want to insert
4752
 * @param string $type        The type for the variable we want to insert
4753
 * @param string $category    The category for the variable we want to insert
4754
 * @param string $title       The title
4755
 * @param string $comment     The comment
4756
 * @param string $scope       The scope
4757
 * @param string $subKeyText  The subkey text
4758
 * @param int    $accessUrlId The access_url for which this parameter is valid
4759
 * @param int    $visibility  The changeability of this setting for non-master urls
4760
 *
4761
 * @return int The setting ID
4762
 */
4763
function api_add_setting(
4764
    $value,
4765
    $variable,
4766
    $subKey = '',
4767
    $type = 'textfield',
4768
    $category = '',
4769
    $title = '',
4770
    $comment = '',
4771
    $scope = '',
4772
    $subKeyText = '',
4773
    $accessUrlId = 1,
4774
    $visibility = 0
4775
) {
4776
    $em = Database::getManager();
4777
4778
    $settingRepo = $em->getRepository(SettingsCurrent::class);
4779
    $accessUrlId = (int) $accessUrlId ?: 1;
4780
4781
    if (is_array($value)) {
4782
        $value = serialize($value);
4783
    } else {
4784
        $value = trim($value);
4785
    }
4786
4787
    $criteria = ['variable' => $variable, 'url' => $accessUrlId];
4788
4789
    if (!empty($subKey)) {
4790
        $criteria['subkey'] = $subKey;
4791
    }
4792
4793
    // Check if this variable doesn't exist already
4794
    /** @var SettingsCurrent $setting */
4795
    $setting = $settingRepo->findOneBy($criteria);
4796
4797
    if ($setting) {
0 ignored issues
show
introduced by
$setting is of type Chamilo\CoreBundle\Entity\SettingsCurrent, thus it always evaluated to true.
Loading history...
4798
        $setting->setSelectedValue($value);
4799
4800
        $em->persist($setting);
4801
        $em->flush();
4802
4803
        return $setting->getId();
4804
    }
4805
4806
    // Item not found for this access_url, we have to check if the whole thing is missing
4807
    // (in which case we ignore the insert) or if there *is* a record but just for access_url = 1
4808
    $setting = new SettingsCurrent();
4809
    $url = api_get_url_entity();
4810
4811
    $setting
4812
        ->setVariable($variable)
4813
        ->setSelectedValue($value)
4814
        ->setType($type)
4815
        ->setCategory($category)
4816
        ->setSubkey($subKey)
4817
        ->setTitle($title)
4818
        ->setComment($comment)
4819
        ->setScope($scope)
4820
        ->setSubkeytext($subKeyText)
4821
        ->setUrl(api_get_url_entity())
4822
        ->setAccessUrlChangeable($visibility);
4823
4824
    $em->persist($setting);
4825
    $em->flush();
4826
4827
    return $setting->getId();
4828
}
4829
4830
/**
4831
 * Checks wether a user can or can't view the contents of a course.
4832
 *
4833
 * @deprecated use CourseManager::is_user_subscribed_in_course
4834
 *
4835
 * @param int $userid User id or NULL to get it from $_SESSION
4836
 * @param int $cid    course id to check whether the user is allowed
4837
 *
4838
 * @return bool
4839
 */
4840
function api_is_course_visible_for_user($userid = null, $cid = null)
4841
{
4842
    if (null === $userid) {
4843
        $userid = api_get_user_id();
4844
    }
4845
    if (empty($userid) || strval(intval($userid)) != $userid) {
4846
        if (api_is_anonymous()) {
4847
            $userid = api_get_anonymous_id();
4848
        } else {
4849
            return false;
4850
        }
4851
    }
4852
    $cid = Database::escape_string($cid);
4853
4854
    $courseInfo = api_get_course_info($cid);
4855
    $courseId = $courseInfo['real_id'];
4856
    $is_platformAdmin = api_is_platform_admin();
4857
4858
    $course_table = Database::get_main_table(TABLE_MAIN_COURSE);
4859
    $course_cat_table = Database::get_main_table(TABLE_MAIN_CATEGORY);
4860
4861
    $sql = "SELECT
4862
                $course_cat_table.code AS category_code,
4863
                $course_table.visibility,
4864
                $course_table.code,
4865
                $course_cat_table.code
4866
            FROM $course_table
4867
            LEFT JOIN $course_cat_table
4868
                ON $course_table.category_id = $course_cat_table.id
4869
            WHERE
4870
                $course_table.code = '$cid'
4871
            LIMIT 1";
4872
4873
    $result = Database::query($sql);
4874
4875
    if (Database::num_rows($result) > 0) {
4876
        $visibility = Database::fetch_array($result);
4877
        $visibility = $visibility['visibility'];
4878
    } else {
4879
        $visibility = 0;
4880
    }
4881
    // Shortcut permissions in case the visibility is "open to the world".
4882
    if (COURSE_VISIBILITY_OPEN_WORLD === $visibility) {
4883
        return true;
4884
    }
4885
4886
    $tbl_course_user = Database::get_main_table(TABLE_MAIN_COURSE_USER);
4887
4888
    $sql = "SELECT
4889
                is_tutor, status
4890
            FROM $tbl_course_user
4891
            WHERE
4892
                user_id  = '$userid' AND
4893
                relation_type <> '".COURSE_RELATION_TYPE_RRHH."' AND
4894
                c_id = $courseId
4895
            LIMIT 1";
4896
4897
    $result = Database::query($sql);
4898
4899
    if (Database::num_rows($result) > 0) {
4900
        // This user has got a recorded state for this course.
4901
        $cuData = Database::fetch_array($result);
4902
        $is_courseMember = true;
4903
        $is_courseAdmin = (1 == $cuData['status']);
4904
    }
4905
4906
    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...
4907
        // This user has no status related to this course.
4908
        // Is it the session coach or the session admin?
4909
        $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
4910
        $tbl_session_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
4911
        $tblSessionRelUser = Database::get_main_table(TABLE_MAIN_SESSION_USER);
4912
        $tbl_session_course_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
4913
4914
        $sql = "SELECT sru_2.user_id AS session_admin_id, sru_1.user_id AS session_coach_id
4915
                FROM $tbl_session AS s
4916
                INNER JOIN $tblSessionRelUser sru_1
4917
                ON (sru_1.session_id = s.id AND sru_1.relation_type = ".SessionEntity::GENERAL_COACH.")
4918
                INNER JOIN $tblSessionRelUser sru_2
4919
                ON (sru_2.session_id = s.id AND sru_2.relation_type = ".SessionEntity::SESSION_ADMIN.")
4920
                INNER JOIN $tbl_session_course src
4921
                ON (src.session_id = s.id AND src.c_id = $courseId)";
4922
4923
        $result = Database::query($sql);
4924
        $row = Database::store_result($result);
4925
        $sessionAdminsId = array_column($row, 'session_admin_id');
4926
        $sessionCoachesId = array_column($row, 'session_coach_id');
4927
4928
        if (in_array($userid, $sessionCoachesId)) {
4929
            $is_courseMember = true;
4930
            $is_courseAdmin = false;
4931
        } elseif (in_array($userid, $sessionAdminsId)) {
4932
            $is_courseMember = false;
4933
            $is_courseAdmin = false;
4934
        } else {
4935
            // Check if the current user is the course coach.
4936
            $sql = "SELECT 1
4937
                    FROM $tbl_session_course
4938
                    WHERE session_rel_course.c_id = '$courseId'
4939
                    AND session_rel_course.id_coach = '$userid'
4940
                    LIMIT 1";
4941
4942
            $result = Database::query($sql);
4943
4944
            //if ($row = Database::fetch_array($result)) {
4945
            if (Database::num_rows($result) > 0) {
4946
                $is_courseMember = true;
4947
                $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
4948
4949
                $sql = "SELECT status FROM $tbl_user
4950
                        WHERE id = $userid
4951
                        LIMIT 1";
4952
4953
                $result = Database::query($sql);
4954
4955
                if (1 == Database::result($result, 0, 0)) {
4956
                    $is_courseAdmin = true;
4957
                } else {
4958
                    $is_courseAdmin = false;
4959
                }
4960
            } else {
4961
                // Check if the user is a student is this session.
4962
                $sql = "SELECT  id
4963
                        FROM $tbl_session_course_user
4964
                        WHERE
4965
                            user_id  = '$userid' AND
4966
                            c_id = '$courseId'
4967
                        LIMIT 1";
4968
4969
                if (Database::num_rows($result) > 0) {
4970
                    // This user haa got a recorded state for this course.
4971
                    while ($row = Database::fetch_array($result)) {
4972
                        $is_courseMember = true;
4973
                        $is_courseAdmin = false;
4974
                    }
4975
                }
4976
            }
4977
        }
4978
    }
4979
4980
    switch ($visibility) {
4981
        case Course::OPEN_WORLD:
4982
            return true;
4983
        case Course::OPEN_PLATFORM:
4984
            return isset($userid);
4985
        case Course::REGISTERED:
4986
        case Course::CLOSED:
4987
            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...
4988
        case Course::HIDDEN:
4989
            return $is_platformAdmin;
4990
    }
4991
4992
    return false;
4993
}
4994
4995
/**
4996
 * Returns whether an element (forum, message, survey ...) belongs to a session or not.
4997
 *
4998
 * @param string the tool of the element
4999
 * @param int the element id in database
5000
 * @param int the session_id to compare with element session id
5001
 *
5002
 * @return bool true if the element is in the session, false else
5003
 */
5004
function api_is_element_in_the_session($tool, $element_id, $session_id = null)
5005
{
5006
    if (is_null($session_id)) {
5007
        $session_id = api_get_session_id();
5008
    }
5009
5010
    $element_id = (int) $element_id;
5011
5012
    if (empty($element_id)) {
5013
        return false;
5014
    }
5015
5016
    // Get information to build query depending of the tool.
5017
    switch ($tool) {
5018
        case TOOL_SURVEY:
5019
            $table_tool = Database::get_course_table(TABLE_SURVEY);
5020
            $key_field = 'survey_id';
5021
            break;
5022
        case TOOL_ANNOUNCEMENT:
5023
            $table_tool = Database::get_course_table(TABLE_ANNOUNCEMENT);
5024
            $key_field = 'id';
5025
            break;
5026
        case TOOL_AGENDA:
5027
            $table_tool = Database::get_course_table(TABLE_AGENDA);
5028
            $key_field = 'id';
5029
            break;
5030
        case TOOL_GROUP:
5031
            $table_tool = Database::get_course_table(TABLE_GROUP);
5032
            $key_field = 'id';
5033
            break;
5034
        default:
5035
            return false;
5036
    }
5037
    $course_id = api_get_course_int_id();
5038
5039
    $sql = "SELECT session_id FROM $table_tool
5040
            WHERE c_id = $course_id AND $key_field =  ".$element_id;
5041
    $rs = Database::query($sql);
5042
    if ($element_session_id = Database::result($rs, 0, 0)) {
5043
        if ($element_session_id == intval($session_id)) {
5044
            // The element belongs to the session.
5045
            return true;
5046
        }
5047
    }
5048
5049
    return false;
5050
}
5051
5052
/**
5053
 * Replaces "forbidden" characters in a filename string.
5054
 *
5055
 * @param string $filename
5056
 * @param bool   $treat_spaces_as_hyphens
5057
 *
5058
 * @return string
5059
 */
5060
function api_replace_dangerous_char($filename, $treat_spaces_as_hyphens = true)
5061
{
5062
    // Some non-properly encoded file names can cause the whole file to be
5063
    // skipped when uploaded. Avoid this by detecting the encoding and
5064
    // converting to UTF-8, setting the source as ASCII (a reasonably
5065
    // limited characters set) if nothing could be found (BT#
5066
    $encoding = api_detect_encoding($filename);
5067
    if (empty($encoding)) {
5068
        $encoding = 'ASCII';
5069
        if (!api_is_valid_ascii($filename)) {
5070
            // try iconv and try non standard ASCII a.k.a CP437
5071
            // see BT#15022
5072
            if (function_exists('iconv')) {
5073
                $result = iconv('CP437', 'UTF-8', $filename);
5074
                if (api_is_valid_utf8($result)) {
5075
                    $filename = $result;
5076
                    $encoding = 'UTF-8';
5077
                }
5078
            }
5079
        }
5080
    }
5081
5082
    $filename = api_to_system_encoding($filename, $encoding);
5083
5084
    $url = URLify::filter(
5085
        $filename,
5086
        250,
5087
        '',
5088
        true,
5089
        false,
5090
        false
5091
    );
5092
5093
    // Replace multiple dots at the end.
5094
    $regex = "/\.+$/";
5095
5096
    return preg_replace($regex, '', $url);
5097
}
5098
5099
/**
5100
 * Fixes the $_SERVER['REQUEST_URI'] that is empty in IIS6.
5101
 *
5102
 * @author Ivan Tcholakov, 28-JUN-2006.
5103
 */
5104
function api_request_uri()
5105
{
5106
    if (!empty($_SERVER['REQUEST_URI'])) {
5107
        return $_SERVER['REQUEST_URI'];
5108
    }
5109
    $uri = $_SERVER['SCRIPT_NAME'];
5110
    if (!empty($_SERVER['QUERY_STRING'])) {
5111
        $uri .= '?'.$_SERVER['QUERY_STRING'];
5112
    }
5113
    $_SERVER['REQUEST_URI'] = $uri;
5114
5115
    return $uri;
5116
}
5117
5118
/**
5119
 * Gets the current access_url id of the Chamilo Platform.
5120
 *
5121
 * @return int access_url_id of the current Chamilo Installation
5122
 *
5123
 * @author Julio Montoya <[email protected]>
5124
 * @throws Exception
5125
 */
5126
function api_get_current_access_url_id(): int
5127
{
5128
    if (false === api_get_multiple_access_url()) {
5129
        return 1;
5130
    }
5131
5132
    static $id;
5133
    if (!empty($id)) {
5134
        return $id;
5135
    }
5136
5137
    $table = Database::get_main_table(TABLE_MAIN_ACCESS_URL);
5138
    $path = Database::escape_string(api_get_path(WEB_PATH));
5139
    $sql = "SELECT id FROM $table WHERE url = '".$path."'";
5140
    $result = Database::query($sql);
5141
    if (Database::num_rows($result) > 0) {
5142
        $id = Database::result($result, 0, 0);
5143
        if (false === $id) {
5144
            return -1;
5145
        }
5146
5147
        return (int) $id;
5148
    }
5149
5150
    $id = 1;
5151
5152
    //if the url in WEB_PATH was not found, it can only mean that there is
5153
    // either a configuration problem or the first URL has not been defined yet
5154
    // (by default it is http://localhost/). Thus the more sensible thing we can
5155
    // do is return 1 (the main URL) as the user cannot hack this value anyway
5156
    return 1;
5157
}
5158
5159
/**
5160
 * Gets the registered urls from a given user id.
5161
 *
5162
 * @author Julio Montoya <[email protected]>
5163
 *
5164
 * @param int $user_id
5165
 *
5166
 * @return array
5167
 */
5168
function api_get_access_url_from_user($user_id)
5169
{
5170
    $user_id = (int) $user_id;
5171
    $table_url_rel_user = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
5172
    $table_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL);
5173
    $sql = "SELECT access_url_id
5174
            FROM $table_url_rel_user url_rel_user
5175
            INNER JOIN $table_url u
5176
            ON (url_rel_user.access_url_id = u.id)
5177
            WHERE user_id = ".$user_id;
5178
    $result = Database::query($sql);
5179
    $list = [];
5180
    while ($row = Database::fetch_assoc($result)) {
5181
        $list[] = $row['access_url_id'];
5182
    }
5183
5184
    return $list;
5185
}
5186
5187
/**
5188
 * Checks whether the curent user is in a group or not.
5189
 *
5190
 * @param string        The group id - optional (takes it from session if not given)
5191
 * @param string        The course code - optional (no additional check by course if course code is not given)
5192
 *
5193
 * @return bool
5194
 *
5195
 * @author Ivan Tcholakov
5196
 */
5197
function api_is_in_group($groupIdParam = null, $courseCodeParam = null)
5198
{
5199
    if (!empty($courseCodeParam)) {
5200
        $courseCode = api_get_course_id();
5201
        if (!empty($courseCode)) {
5202
            if ($courseCodeParam != $courseCode) {
5203
                return false;
5204
            }
5205
        } else {
5206
            return false;
5207
        }
5208
    }
5209
5210
    $groupId = api_get_group_id();
5211
5212
    if (isset($groupId) && '' != $groupId) {
5213
        if (!empty($groupIdParam)) {
5214
            return $groupIdParam == $groupId;
5215
        } else {
5216
            return true;
5217
        }
5218
    }
5219
5220
    return false;
5221
}
5222
5223
/**
5224
 * Checks whether a secret key is valid.
5225
 *
5226
 * @param string $original_key_secret - secret key from (webservice) client
5227
 * @param string $security_key        - security key from Chamilo
5228
 *
5229
 * @return bool - true if secret key is valid, false otherwise
5230
 */
5231
function api_is_valid_secret_key($original_key_secret, $security_key)
5232
{
5233
    if (empty($original_key_secret) || empty($security_key)) {
5234
        return false;
5235
    }
5236
5237
    return (string) $original_key_secret === hash('sha512', $security_key);
5238
}
5239
5240
/**
5241
 * Checks whether the server's operating system is Windows (TM).
5242
 *
5243
 * @return bool - true if the operating system is Windows, false otherwise
5244
 */
5245
function api_is_windows_os()
5246
{
5247
    if (function_exists('php_uname')) {
5248
        // php_uname() exists as of PHP 4.0.2, according to the documentation.
5249
        // We expect that this function will always work for Chamilo 1.8.x.
5250
        $os = php_uname();
5251
    }
5252
    // The following methods are not needed, but let them stay, just in case.
5253
    elseif (isset($_ENV['OS'])) {
5254
        // Sometimes $_ENV['OS'] may not be present (bugs?)
5255
        $os = $_ENV['OS'];
5256
    } elseif (defined('PHP_OS')) {
5257
        // PHP_OS means on which OS PHP was compiled, this is why
5258
        // using PHP_OS is the last choice for detection.
5259
        $os = PHP_OS;
5260
    } else {
5261
        return false;
5262
    }
5263
5264
    return 'win' == strtolower(substr((string) $os, 0, 3));
5265
}
5266
5267
/**
5268
 * This function informs whether the sent request is XMLHttpRequest.
5269
 */
5270
function api_is_xml_http_request()
5271
{
5272
    return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && 'xmlhttprequest' == strtolower($_SERVER['HTTP_X_REQUESTED_WITH']);
5273
}
5274
5275
/**
5276
 * Returns a list of Chamilo's tools or
5277
 * checks whether a given identificator is a valid Chamilo's tool.
5278
 *
5279
 * @author Isaac flores paz
5280
 *
5281
 * @param string The tool name to filter
5282
 *
5283
 * @return mixed Filtered string or array
5284
 */
5285
function api_get_tools_lists($my_tool = null)
5286
{
5287
    $tools_list = [
5288
        TOOL_DOCUMENT,
5289
        TOOL_THUMBNAIL,
5290
        TOOL_HOTPOTATOES,
5291
        TOOL_CALENDAR_EVENT,
5292
        TOOL_LINK,
5293
        TOOL_COURSE_DESCRIPTION,
5294
        TOOL_SEARCH,
5295
        TOOL_LEARNPATH,
5296
        TOOL_ANNOUNCEMENT,
5297
        TOOL_FORUM,
5298
        TOOL_THREAD,
5299
        TOOL_POST,
5300
        TOOL_DROPBOX,
5301
        TOOL_QUIZ,
5302
        TOOL_USER,
5303
        TOOL_GROUP,
5304
        TOOL_BLOGS,
5305
        TOOL_CHAT,
5306
        TOOL_STUDENTPUBLICATION,
5307
        TOOL_TRACKING,
5308
        TOOL_HOMEPAGE_LINK,
5309
        TOOL_COURSE_SETTING,
5310
        TOOL_BACKUP,
5311
        TOOL_COPY_COURSE_CONTENT,
5312
        TOOL_RECYCLE_COURSE,
5313
        TOOL_COURSE_HOMEPAGE,
5314
        TOOL_COURSE_RIGHTS_OVERVIEW,
5315
        TOOL_UPLOAD,
5316
        TOOL_COURSE_MAINTENANCE,
5317
        TOOL_SURVEY,
5318
        //TOOL_WIKI,
5319
        TOOL_GLOSSARY,
5320
        TOOL_GRADEBOOK,
5321
        TOOL_NOTEBOOK,
5322
        TOOL_ATTENDANCE,
5323
        TOOL_COURSE_PROGRESS,
5324
    ];
5325
    if (empty($my_tool)) {
5326
        return $tools_list;
5327
    }
5328
5329
    return in_array($my_tool, $tools_list) ? $my_tool : '';
5330
}
5331
5332
/**
5333
 * Checks whether we already approved the last version term and condition.
5334
 *
5335
 * @param int user id
5336
 *
5337
 * @return bool true if we pass false otherwise
5338
 */
5339
function api_check_term_condition($userId)
5340
{
5341
    if ('true' === api_get_setting('allow_terms_conditions')) {
5342
        // Check if exists terms and conditions
5343
        if (0 == LegalManager::count()) {
5344
            return true;
5345
        }
5346
5347
        $extraFieldValue = new ExtraFieldValue('user');
5348
        $data = $extraFieldValue->get_values_by_handler_and_field_variable(
5349
            $userId,
5350
            'legal_accept'
5351
        );
5352
5353
        if (!empty($data) && isset($data['value']) && !empty($data['value'])) {
5354
            $result = $data['value'];
5355
            $user_conditions = explode(':', $result);
5356
            $version = $user_conditions[0];
5357
            $langId = $user_conditions[1];
5358
            $realVersion = LegalManager::get_last_version($langId);
5359
5360
            return $version >= $realVersion;
5361
        }
5362
5363
        return false;
5364
    }
5365
5366
    return false;
5367
}
5368
5369
/**
5370
 * Gets all information of a tool into course.
5371
 *
5372
 * @param int The tool id
5373
 *
5374
 * @return array
5375
 */
5376
function api_get_tool_information_by_name($name)
5377
{
5378
    $t_tool = Database::get_course_table(TABLE_TOOL_LIST);
5379
    $course_id = api_get_course_int_id();
5380
5381
    $sql = "SELECT id FROM tool
5382
            WHERE title = '".Database::escape_string($name)."' ";
5383
    $rs = Database::query($sql);
5384
    $data = Database::fetch_array($rs);
5385
    if ($data) {
5386
        $tool = $data['id'];
5387
        $sql = "SELECT * FROM $t_tool
5388
                WHERE c_id = $course_id  AND tool_id = '".$tool."' ";
5389
        $rs = Database::query($sql);
5390
5391
        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...
5392
    }
5393
5394
    return [];
5395
}
5396
5397
/**
5398
 * Function used to protect a "global" admin script.
5399
 * The function blocks access when the user has no global platform admin rights.
5400
 * Global admins are the admins that are registered in the main.admin table
5401
 * AND the users who have access to the "principal" portal.
5402
 * That means that there is a record in the main.access_url_rel_user table
5403
 * with his user id and the access_url_id=1.
5404
 *
5405
 * @author Julio Montoya
5406
 *
5407
 * @param int $user_id
5408
 *
5409
 * @return bool
5410
 */
5411
function api_is_global_platform_admin($user_id = null)
5412
{
5413
    $user_id = (int) $user_id;
5414
    if (empty($user_id)) {
5415
        $user_id = api_get_user_id();
5416
    }
5417
    if (api_is_platform_admin_by_id($user_id)) {
5418
        $urlList = api_get_access_url_from_user($user_id);
5419
        // The admin is registered in the first "main" site with access_url_id = 1
5420
        if (in_array(1, $urlList)) {
5421
            return true;
5422
        }
5423
    }
5424
5425
    return false;
5426
}
5427
5428
/**
5429
 * @param int  $admin_id_to_check
5430
 * @param int  $userId
5431
 * @param bool $allow_session_admin
5432
 *
5433
 * @return bool
5434
 */
5435
function api_global_admin_can_edit_admin(
5436
    $admin_id_to_check,
5437
    $userId = 0,
5438
    $allow_session_admin = false
5439
) {
5440
    if (empty($userId)) {
5441
        $userId = api_get_user_id();
5442
    }
5443
5444
    $iam_a_global_admin = api_is_global_platform_admin($userId);
5445
    $user_is_global_admin = api_is_global_platform_admin($admin_id_to_check);
5446
5447
    if ($iam_a_global_admin) {
5448
        // Global admin can edit everything
5449
        return true;
5450
    }
5451
5452
    // If i'm a simple admin
5453
    $is_platform_admin = api_is_platform_admin_by_id($userId);
5454
5455
    if ($allow_session_admin && !$is_platform_admin) {
5456
        $user = api_get_user_entity($userId);
5457
        $is_platform_admin = $user->isSessionAdmin();
5458
    }
5459
5460
    if ($is_platform_admin) {
5461
        if ($user_is_global_admin) {
5462
            return false;
5463
        } else {
5464
            return true;
5465
        }
5466
    }
5467
5468
    return false;
5469
}
5470
5471
/**
5472
 * @param int  $admin_id_to_check
5473
 * @param int  $userId
5474
 * @param bool $allow_session_admin
5475
 *
5476
 * @return bool|null
5477
 */
5478
function api_protect_super_admin($admin_id_to_check, $userId = null, $allow_session_admin = false)
5479
{
5480
    if (api_global_admin_can_edit_admin($admin_id_to_check, $userId, $allow_session_admin)) {
5481
        return true;
5482
    } else {
5483
        api_not_allowed();
5484
    }
5485
}
5486
5487
/**
5488
 * Function used to protect a global admin script.
5489
 * The function blocks access when the user has no global platform admin rights.
5490
 * See also the api_is_global_platform_admin() function wich defines who's a "global" admin.
5491
 *
5492
 * @author Julio Montoya
5493
 */
5494
function api_protect_global_admin_script()
5495
{
5496
    if (!api_is_global_platform_admin()) {
5497
        api_not_allowed();
5498
5499
        return false;
5500
    }
5501
5502
    return true;
5503
}
5504
5505
/**
5506
 * Check browser support for specific file types or features
5507
 * This function checks if the user's browser supports a file format or given
5508
 * feature, or returns the current browser and major version when
5509
 * $format=check_browser. Only a limited number of formats and features are
5510
 * checked by this method. Make sure you check its definition first.
5511
 *
5512
 * @param string $format Can be a file format (extension like svg, webm, ...) or a feature (like autocapitalize, ...)
5513
 *
5514
 * @deprecated
5515
 *
5516
 * @return bool or return text array if $format=check_browser
5517
 *
5518
 * @author Juan Carlos Raña Trabado
5519
 */
5520
function api_browser_support($format = '')
5521
{
5522
    return true;
5523
5524
    $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...
5525
    $current_browser = $browser->getBrowser();
5526
    $a_versiontemp = explode('.', $browser->getVersion());
5527
    $current_majorver = $a_versiontemp[0];
5528
5529
    static $result;
5530
5531
    if (isset($result[$format])) {
5532
        return $result[$format];
5533
    }
5534
5535
    // Native svg support
5536
    if ('svg' == $format) {
5537
        if (('Internet Explorer' == $current_browser && $current_majorver >= 9) ||
5538
            ('Firefox' == $current_browser && $current_majorver > 1) ||
5539
            ('Safari' == $current_browser && $current_majorver >= 4) ||
5540
            ('Chrome' == $current_browser && $current_majorver >= 1) ||
5541
            ('Opera' == $current_browser && $current_majorver >= 9)
5542
        ) {
5543
            $result[$format] = true;
5544
5545
            return true;
5546
        } else {
5547
            $result[$format] = false;
5548
5549
            return false;
5550
        }
5551
    } elseif ('pdf' == $format) {
5552
        // native pdf support
5553
        if ('Chrome' == $current_browser && $current_majorver >= 6) {
5554
            $result[$format] = true;
5555
5556
            return true;
5557
        } else {
5558
            $result[$format] = false;
5559
5560
            return false;
5561
        }
5562
    } elseif ('tif' == $format || 'tiff' == $format) {
5563
        //native tif 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 ('ogg' == $format || 'ogx' == $format || 'ogv' == $format || 'oga' == $format) {
5574
        //native ogg, ogv,oga support
5575
        if (('Firefox' == $current_browser && $current_majorver >= 3) ||
5576
            ('Chrome' == $current_browser && $current_majorver >= 3) ||
5577
            ('Opera' == $current_browser && $current_majorver >= 9)) {
5578
            $result[$format] = true;
5579
5580
            return true;
5581
        } else {
5582
            $result[$format] = false;
5583
5584
            return false;
5585
        }
5586
    } elseif ('mpg' == $format || 'mpeg' == $format) {
5587
        //native mpg support
5588
        if (('Safari' == $current_browser && $current_majorver >= 5)) {
5589
            $result[$format] = true;
5590
5591
            return true;
5592
        } else {
5593
            $result[$format] = false;
5594
5595
            return false;
5596
        }
5597
    } elseif ('mp4' == $format) {
5598
        //native mp4 support (TODO: Android, iPhone)
5599
        if ('Android' == $current_browser || 'iPhone' == $current_browser) {
5600
            $result[$format] = true;
5601
5602
            return true;
5603
        } else {
5604
            $result[$format] = false;
5605
5606
            return false;
5607
        }
5608
    } elseif ('mov' == $format) {
5609
        //native mov support( TODO:check iPhone)
5610
        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...
5611
            $result[$format] = true;
5612
5613
            return true;
5614
        } else {
5615
            $result[$format] = false;
5616
5617
            return false;
5618
        }
5619
    } elseif ('avi' == $format) {
5620
        //native avi support
5621
        if ('Safari' == $current_browser && $current_majorver >= 5) {
5622
            $result[$format] = true;
5623
5624
            return true;
5625
        } else {
5626
            $result[$format] = false;
5627
5628
            return false;
5629
        }
5630
    } elseif ('wmv' == $format) {
5631
        //native wmv support
5632
        if ('Firefox' == $current_browser && $current_majorver >= 4) {
5633
            $result[$format] = true;
5634
5635
            return true;
5636
        } else {
5637
            $result[$format] = false;
5638
5639
            return false;
5640
        }
5641
    } elseif ('webm' == $format) {
5642
        //native webm support (TODO:check IE9, Chrome9, Android)
5643
        if (('Firefox' == $current_browser && $current_majorver >= 4) ||
5644
            ('Opera' == $current_browser && $current_majorver >= 9) ||
5645
            ('Internet Explorer' == $current_browser && $current_majorver >= 9) ||
5646
            ('Chrome' == $current_browser && $current_majorver >= 9) ||
5647
            'Android' == $current_browser
5648
        ) {
5649
            $result[$format] = true;
5650
5651
            return true;
5652
        } else {
5653
            $result[$format] = false;
5654
5655
            return false;
5656
        }
5657
    } elseif ('wav' == $format) {
5658
        //native wav support (only some codecs !)
5659
        if (('Firefox' == $current_browser && $current_majorver >= 4) ||
5660
            ('Safari' == $current_browser && $current_majorver >= 5) ||
5661
            ('Opera' == $current_browser && $current_majorver >= 9) ||
5662
            ('Internet Explorer' == $current_browser && $current_majorver >= 9) ||
5663
            ('Chrome' == $current_browser && $current_majorver > 9) ||
5664
            'Android' == $current_browser ||
5665
            'iPhone' == $current_browser
5666
        ) {
5667
            $result[$format] = true;
5668
5669
            return true;
5670
        } else {
5671
            $result[$format] = false;
5672
5673
            return false;
5674
        }
5675
    } elseif ('mid' == $format || 'kar' == $format) {
5676
        //native midi support (TODO:check Android)
5677
        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...
5678
            $result[$format] = true;
5679
5680
            return true;
5681
        } else {
5682
            $result[$format] = false;
5683
5684
            return false;
5685
        }
5686
    } elseif ('wma' == $format) {
5687
        //native wma support
5688
        if ('Firefox' == $current_browser && $current_majorver >= 4) {
5689
            $result[$format] = true;
5690
5691
            return true;
5692
        } else {
5693
            $result[$format] = false;
5694
5695
            return false;
5696
        }
5697
    } elseif ('au' == $format) {
5698
        //native au support
5699
        if ('Safari' == $current_browser && $current_majorver >= 5) {
5700
            $result[$format] = true;
5701
5702
            return true;
5703
        } else {
5704
            $result[$format] = false;
5705
5706
            return false;
5707
        }
5708
    } elseif ('mp3' == $format) {
5709
        //native mp3 support (TODO:check Android, iPhone)
5710
        if (('Safari' == $current_browser && $current_majorver >= 5) ||
5711
            ('Chrome' == $current_browser && $current_majorver >= 6) ||
5712
            ('Internet Explorer' == $current_browser && $current_majorver >= 9) ||
5713
            'Android' == $current_browser ||
5714
            'iPhone' == $current_browser ||
5715
            'Firefox' == $current_browser
5716
        ) {
5717
            $result[$format] = true;
5718
5719
            return true;
5720
        } else {
5721
            $result[$format] = false;
5722
5723
            return false;
5724
        }
5725
    } elseif ('autocapitalize' == $format) {
5726
        // Help avoiding showing the autocapitalize option if the browser doesn't
5727
        // support it: this attribute is against the HTML5 standard
5728
        if ('Safari' == $current_browser || 'iPhone' == $current_browser) {
5729
            return true;
5730
        } else {
5731
            return false;
5732
        }
5733
    } elseif ("check_browser" == $format) {
5734
        $array_check_browser = [$current_browser, $current_majorver];
5735
5736
        return $array_check_browser;
5737
    } else {
5738
        $result[$format] = false;
5739
5740
        return false;
5741
    }
5742
}
5743
5744
/**
5745
 * This function checks if exist path and file browscap.ini
5746
 * In order for this to work, your browscap configuration setting in php.ini
5747
 * must point to the correct location of the browscap.ini file on your system
5748
 * http://php.net/manual/en/function.get-browser.php.
5749
 *
5750
 * @return bool
5751
 *
5752
 * @author Juan Carlos Raña Trabado
5753
 */
5754
function api_check_browscap()
5755
{
5756
    $setting = ini_get('browscap');
5757
    if ($setting) {
5758
        $browser = get_browser($_SERVER['HTTP_USER_AGENT'], true);
5759
        if (strpos($setting, 'browscap.ini') && !empty($browser)) {
5760
            return true;
5761
        }
5762
    }
5763
5764
    return false;
5765
}
5766
5767
/**
5768
 * Returns the <script> HTML tag.
5769
 */
5770
function api_get_js($file)
5771
{
5772
    return '<script src="'.api_get_path(WEB_LIBRARY_PATH).'javascript/'.$file.'"></script>'."\n";
5773
}
5774
5775
function api_get_build_js($file)
5776
{
5777
    return '<script src="'.api_get_path(WEB_PUBLIC_PATH).'build/'.$file.'"></script>'."\n";
5778
}
5779
5780
function api_get_build_css($file, $media = 'screen')
5781
{
5782
    return '<link
5783
        href="'.api_get_path(WEB_PUBLIC_PATH).'build/'.$file.'" rel="stylesheet" media="'.$media.'" type="text/css" />'."\n";
5784
}
5785
5786
/**
5787
 * Returns the <script> HTML tag.
5788
 *
5789
 * @return string
5790
 */
5791
function api_get_asset($file)
5792
{
5793
    return '<script src="'.api_get_path(WEB_PUBLIC_PATH).'build/libs/'.$file.'"></script>'."\n";
5794
}
5795
5796
/**
5797
 * Returns the <script> HTML tag.
5798
 *
5799
 * @param string $file
5800
 * @param string $media
5801
 *
5802
 * @return string
5803
 */
5804
function api_get_css_asset($file, $media = 'screen')
5805
{
5806
    return '<link
5807
        href="'.api_get_path(WEB_PUBLIC_PATH).'build/libs/'.$file.'"
5808
        rel="stylesheet" media="'.$media.'" type="text/css" />'."\n";
5809
}
5810
5811
/**
5812
 * Returns the <link> HTML tag.
5813
 *
5814
 * @param string $file
5815
 * @param string $media
5816
 */
5817
function api_get_css($file, $media = 'screen')
5818
{
5819
    return '<link href="'.$file.'" rel="stylesheet" media="'.$media.'" type="text/css" />'."\n";
5820
}
5821
5822
function api_get_bootstrap_and_font_awesome($returnOnlyPath = false, $returnFileLocation = false)
5823
{
5824
    $url = api_get_path(WEB_PUBLIC_PATH).'build/css/bootstrap.css';
5825
5826
    if ($returnOnlyPath) {
5827
        if ($returnFileLocation) {
5828
            return api_get_path(SYS_PUBLIC_PATH).'build/css/bootstrap.css';
5829
        }
5830
5831
        return $url;
5832
    }
5833
5834
    return '<link href="'.$url.'" rel="stylesheet" type="text/css" />'."\n";
5835
}
5836
5837
/**
5838
 * Returns the js header to include the jquery library.
5839
 */
5840
function api_get_jquery_js()
5841
{
5842
    return api_get_asset('jquery/jquery.min.js');
5843
}
5844
5845
/**
5846
 * Returns the jquery path.
5847
 *
5848
 * @return string
5849
 */
5850
function api_get_jquery_web_path()
5851
{
5852
    return api_get_path(WEB_PUBLIC_PATH).'assets/jquery/jquery.min.js';
5853
}
5854
5855
/**
5856
 * @return string
5857
 */
5858
function api_get_jquery_ui_js_web_path()
5859
{
5860
    return api_get_path(WEB_PUBLIC_PATH).'assets/jquery-ui/jquery-ui.min.js';
5861
}
5862
5863
/**
5864
 * @return string
5865
 */
5866
function api_get_jquery_ui_css_web_path()
5867
{
5868
    return api_get_path(WEB_PUBLIC_PATH).'assets/jquery-ui/themes/smoothness/jquery-ui.min.css';
5869
}
5870
5871
/**
5872
 * Returns the jquery-ui library js headers.
5873
 *
5874
 * @return string html tags
5875
 */
5876
function api_get_jquery_ui_js()
5877
{
5878
    $libraries = [];
5879
5880
    return api_get_jquery_libraries_js($libraries);
5881
}
5882
5883
function api_get_jqgrid_js()
5884
{
5885
    return api_get_build_css('legacy_free-jqgrid.css').PHP_EOL
5886
        .api_get_build_js('legacy_free-jqgrid.js');
5887
}
5888
5889
/**
5890
 * Returns the jquery library js and css headers.
5891
 *
5892
 * @param   array   list of jquery libraries supported jquery-ui
5893
 * @param   bool    add the jquery library
5894
 *
5895
 * @return string html tags
5896
 */
5897
function api_get_jquery_libraries_js($libraries)
5898
{
5899
    $js = '';
5900
5901
    //Document multiple upload funcionality
5902
    if (in_array('jquery-uploadzs', $libraries)) {
5903
        $js .= api_get_asset('blueimp-load-image/js/load-image.all.min.js');
5904
        $js .= api_get_asset('blueimp-canvas-to-blob/js/canvas-to-blob.min.js');
5905
        $js .= api_get_asset('jquery-file-upload/js/jquery.iframe-transport.js');
5906
        $js .= api_get_asset('jquery-file-upload/js/jquery.fileupload.js');
5907
        $js .= api_get_asset('jquery-file-upload/js/jquery.fileupload-process.js');
5908
        $js .= api_get_asset('jquery-file-upload/js/jquery.fileupload-image.js');
5909
        $js .= api_get_asset('jquery-file-upload/js/jquery.fileupload-audio.js');
5910
        $js .= api_get_asset('jquery-file-upload/js/jquery.fileupload-video.js');
5911
        $js .= api_get_asset('jquery-file-upload/js/jquery.fileupload-validate.js');
5912
5913
        $js .= api_get_css(api_get_path(WEB_PUBLIC_PATH).'assets/jquery-file-upload/css/jquery.fileupload.css');
5914
        $js .= api_get_css(api_get_path(WEB_PUBLIC_PATH).'assets/jquery-file-upload/css/jquery.fileupload-ui.css');
5915
    }
5916
5917
    // jquery datepicker
5918
    if (in_array('datepicker', $libraries)) {
5919
        $languaje = 'en-GB';
5920
        $platform_isocode = strtolower(api_get_language_isocode());
5921
5922
        $datapicker_langs = [
5923
            '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',
5924
        ];
5925
        if (in_array($platform_isocode, $datapicker_langs)) {
5926
            $languaje = $platform_isocode;
5927
        }
5928
5929
        $js .= api_get_js('jquery-ui/jquery-ui-i18n.min.js');
5930
        $script = '<script>
5931
        $(function(){
5932
            $.datepicker.setDefaults($.datepicker.regional["'.$languaje.'"]);
5933
            $.datepicker.regional["local"] = $.datepicker.regional["'.$languaje.'"];
5934
        });
5935
        </script>
5936
        ';
5937
        $js .= $script;
5938
    }
5939
5940
    return $js;
5941
}
5942
5943
/**
5944
 * Returns the URL to the course or session, removing the complexity of the URL
5945
 * building piece by piece.
5946
 *
5947
 * This function relies on api_get_course_info()
5948
 *
5949
 * @param int $courseId  The course code - optional (takes it from context if not given)
5950
 * @param int $sessionId The session ID  - optional (takes it from context if not given)
5951
 * @param int $groupId   The group ID - optional (takes it from context if not given)
5952
 *
5953
 * @return string The URL to a course, a session, or empty string if nothing works
5954
 *                e.g. https://localhost/courses/ABC/index.php?session_id=3&gidReq=1
5955
 *
5956
 * @author  Julio Montoya
5957
 */
5958
function api_get_course_url($courseId = null, $sessionId = null, $groupId = null)
5959
{
5960
    $url = '';
5961
    // If courseCode not set, get context or []
5962
    if (empty($courseId)) {
5963
        $courseId = api_get_course_int_id();
5964
    }
5965
5966
    // If sessionId not set, get context or 0
5967
    if (empty($sessionId)) {
5968
        $sessionId = api_get_session_id();
5969
    }
5970
5971
    // If groupId not set, get context or 0
5972
    if (empty($groupId)) {
5973
        $groupId = api_get_group_id();
5974
    }
5975
5976
    // Build the URL
5977
    if (!empty($courseId)) {
5978
        $webCourseHome = '/course/'.$courseId.'/home';
5979
        // directory not empty, so we do have a course
5980
        $url = $webCourseHome.'?sid='.$sessionId.'&gid='.$groupId;
5981
    } else {
5982
        if (!empty($sessionId) && 'true' !== api_get_setting('session.remove_session_url')) {
5983
            // if the course was unset and the session was set, send directly to the session
5984
            $url = api_get_path(WEB_CODE_PATH).'session/index.php?session_id='.$sessionId;
5985
        }
5986
    }
5987
5988
    // if not valid combination was found, return an empty string
5989
    return $url;
5990
}
5991
5992
/**
5993
 * Check if there is more than the default URL defined in the access_url table.
5994
 */
5995
function api_get_multiple_access_url(): bool
5996
{
5997
    return Container::getAccessUrlUtil()->isMultiple();
5998
}
5999
6000
/**
6001
 * @deprecated Use AccessUrlUtil::isMultiple
6002
 */
6003
function api_is_multiple_url_enabled(): bool
6004
{
6005
    return api_get_multiple_access_url();
6006
}
6007
6008
/**
6009
 * Returns a md5 unique id.
6010
 *
6011
 * @todo add more parameters
6012
 */
6013
function api_get_unique_id()
6014
{
6015
    return md5(time().uniqid().api_get_user_id().api_get_course_id().api_get_session_id());
6016
}
6017
6018
/**
6019
 * @param int Course id
6020
 * @param int tool id: TOOL_QUIZ, TOOL_FORUM, TOOL_STUDENTPUBLICATION, TOOL_LEARNPATH
6021
 * @param int the item id (tool id, exercise id, lp id)
6022
 *
6023
 * @return bool
6024
 */
6025
function api_resource_is_locked_by_gradebook($item_id, $link_type, $course_code = null)
6026
{
6027
    if (api_is_platform_admin()) {
6028
        return false;
6029
    }
6030
    if ('true' === api_get_setting('gradebook_locking_enabled')) {
6031
        if (empty($course_code)) {
6032
            $course_code = api_get_course_id();
6033
        }
6034
        $table = Database::get_main_table(TABLE_MAIN_GRADEBOOK_LINK);
6035
        $item_id = (int) $item_id;
6036
        $link_type = (int) $link_type;
6037
        $course_code = Database::escape_string($course_code);
6038
        $sql = "SELECT locked FROM $table
6039
                WHERE locked = 1 AND ref_id = $item_id AND type = $link_type AND course_code = '$course_code' ";
6040
        $result = Database::query($sql);
6041
        if (Database::num_rows($result)) {
6042
            return true;
6043
        }
6044
    }
6045
6046
    return false;
6047
}
6048
6049
/**
6050
 * Blocks a page if the item was added in a gradebook.
6051
 *
6052
 * @param int       exercise id, work id, thread id,
6053
 * @param int       LINK_EXERCISE, LINK_STUDENTPUBLICATION, LINK_LEARNPATH LINK_FORUM_THREAD, LINK_ATTENDANCE
6054
 * see gradebook/lib/be/linkfactory
6055
 * @param string    course code
6056
 *
6057
 * @return false|null
6058
 */
6059
function api_block_course_item_locked_by_gradebook($item_id, $link_type, $course_code = null)
6060
{
6061
    if (api_is_platform_admin()) {
6062
        return false;
6063
    }
6064
6065
    if (api_resource_is_locked_by_gradebook($item_id, $link_type, $course_code)) {
6066
        $message = Display::return_message(
6067
            get_lang(
6068
                '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.'
6069
            ),
6070
            'warning'
6071
        );
6072
        api_not_allowed(true, $message);
6073
    }
6074
}
6075
6076
/**
6077
 * Checks the PHP version installed is enough to run Chamilo.
6078
 *
6079
 * @param string Include path (used to load the error page)
6080
 */
6081
function api_check_php_version()
6082
{
6083
    if (!function_exists('version_compare') ||
6084
        version_compare(PHP_VERSION, REQUIRED_PHP_VERSION, '<')
6085
    ) {
6086
        throw new Exception('Wrong PHP version');
6087
    }
6088
}
6089
6090
/**
6091
 * Checks whether the Archive directory is present and writeable. If not,
6092
 * prints a warning message.
6093
 */
6094
function api_check_archive_dir()
6095
{
6096
    if (is_dir(api_get_path(SYS_ARCHIVE_PATH)) && !is_writable(api_get_path(SYS_ARCHIVE_PATH))) {
6097
        $message = Display::return_message(
6098
            get_lang(
6099
                'The var/cache/ directory, used by this tool, is not writeable. Please contact your platform administrator.'
6100
            ),
6101
            'warning'
6102
        );
6103
        api_not_allowed(true, $message);
6104
    }
6105
}
6106
6107
/**
6108
 * Returns an array of global configuration settings which should be ignored
6109
 * when printing the configuration settings screens.
6110
 *
6111
 * @return array Array of strings, each identifying one of the excluded settings
6112
 */
6113
function api_get_locked_settings()
6114
{
6115
    return [
6116
        'permanently_remove_deleted_files',
6117
        'account_valid_duration',
6118
        'service_ppt2lp',
6119
        'wcag_anysurfer_public_pages',
6120
        'upload_extensions_list_type',
6121
        'upload_extensions_blacklist',
6122
        'upload_extensions_whitelist',
6123
        'upload_extensions_skip',
6124
        'upload_extensions_replace_by',
6125
        'hide_dltt_markup',
6126
        'split_users_upload_directory',
6127
        'permissions_for_new_directories',
6128
        'permissions_for_new_files',
6129
        'platform_charset',
6130
        'ldap_description',
6131
        'cas_activate',
6132
        'cas_server',
6133
        'cas_server_uri',
6134
        'cas_port',
6135
        'cas_protocol',
6136
        'cas_add_user_activate',
6137
        'update_user_info_cas_with_ldap',
6138
        'languagePriority1',
6139
        'languagePriority2',
6140
        'languagePriority3',
6141
        'languagePriority4',
6142
        'login_is_email',
6143
        'chamilo_database_version',
6144
    ];
6145
}
6146
6147
/**
6148
 * Guess the real ip for register in the database, even in reverse proxy cases.
6149
 * To be recognized, the IP has to be found in either $_SERVER['REMOTE_ADDR'] or
6150
 * in $_SERVER['HTTP_X_FORWARDED_FOR'], which is in common use with rproxies.
6151
 * Note: the result of this function is not SQL-safe. Please escape it before
6152
 * inserting in a database.
6153
 *
6154
 * @return string the user's real ip (unsafe - escape it before inserting to db)
6155
 *
6156
 * @author Jorge Frisancho Jibaja <[email protected]>, USIL - Some changes to allow the use of real IP using reverse proxy
6157
 *
6158
 * @version CEV CHANGE 24APR2012
6159
 * @throws RuntimeException
6160
 */
6161
function api_get_real_ip(): string
6162
{
6163
    if ('cli' === PHP_SAPI) {
6164
        $ip = '127.0.0.1';
6165
    } else {
6166
        $ip = trim($_SERVER['REMOTE_ADDR']);
6167
        if (empty($ip)) {
6168
            throw new RuntimeException("Unable to retrieve remote IP address.");
6169
        }
6170
    }
6171
    if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
6172
        if (preg_match('/,/', $_SERVER['HTTP_X_FORWARDED_FOR'])) {
6173
            @list($ip1, $ip2) = @explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
6174
        } else {
6175
            $ip1 = $_SERVER['HTTP_X_FORWARDED_FOR'];
6176
        }
6177
        $ip = trim($ip1);
6178
    }
6179
6180
    return $ip;
6181
}
6182
6183
/**
6184
 * Checks whether an IP is included inside an IP range.
6185
 *
6186
 * @param string IP address
6187
 * @param string IP range
6188
 * @param string $ip
6189
 *
6190
 * @return bool True if IP is in the range, false otherwise
6191
 *
6192
 * @author claudiu at cnixs dot com  on http://www.php.net/manual/fr/ref.network.php#55230
6193
 * @author Yannick Warnier for improvements and managment of multiple ranges
6194
 *
6195
 * @todo check for IPv6 support
6196
 */
6197
function api_check_ip_in_range($ip, $range)
6198
{
6199
    if (empty($ip) or empty($range)) {
6200
        return false;
6201
    }
6202
    $ip_ip = ip2long($ip);
6203
    // divide range param into array of elements
6204
    if (false !== strpos($range, ',')) {
6205
        $ranges = explode(',', $range);
6206
    } else {
6207
        $ranges = [$range];
6208
    }
6209
    foreach ($ranges as $range) {
0 ignored issues
show
introduced by
$range is overwriting one of the parameters of this function.
Loading history...
6210
        $range = trim($range);
6211
        if (empty($range)) {
6212
            continue;
6213
        }
6214
        if (false === strpos($range, '/')) {
6215
            if (0 === strcmp($ip, $range)) {
6216
                return true; // there is a direct IP match, return OK
6217
            }
6218
            continue; //otherwise, get to the next range
6219
        }
6220
        // the range contains a "/", so analyse completely
6221
        [$net, $mask] = explode("/", $range);
6222
6223
        $ip_net = ip2long($net);
6224
        // mask binary magic
6225
        $ip_mask = ~((1 << (32 - $mask)) - 1);
6226
6227
        $ip_ip_net = $ip_ip & $ip_mask;
6228
        if ($ip_ip_net == $ip_net) {
6229
            return true;
6230
        }
6231
    }
6232
6233
    return false;
6234
}
6235
6236
function api_check_user_access_to_legal($courseInfo)
6237
{
6238
    if (empty($courseInfo)) {
6239
        return false;
6240
    }
6241
6242
    $visibility = (int) $courseInfo['visibility'];
6243
    $visibilityList = [COURSE_VISIBILITY_OPEN_WORLD, COURSE_VISIBILITY_OPEN_PLATFORM];
6244
6245
    return
6246
        in_array($visibility, $visibilityList) ||
6247
        api_is_drh() ||
6248
        (COURSE_VISIBILITY_REGISTERED === $visibility && 1 === (int) $courseInfo['subscribe']);
6249
}
6250
6251
/**
6252
 * Checks if the global chat is enabled or not.
6253
 *
6254
 * @return bool
6255
 */
6256
function api_is_global_chat_enabled()
6257
{
6258
    return
6259
        !api_is_anonymous() &&
6260
        'true' === api_get_setting('allow_global_chat') &&
6261
        'true' === api_get_setting('allow_social_tool');
6262
}
6263
6264
/**
6265
 * @param int   $item_id
6266
 * @param int   $tool_id
6267
 * @param int   $group_id   id
6268
 * @param array $courseInfo
6269
 * @param int   $sessionId
6270
 * @param int   $userId
6271
 *
6272
 * @deprecated
6273
 */
6274
function api_set_default_visibility(
6275
    $item_id,
6276
    $tool_id,
6277
    $group_id = 0,
6278
    $courseInfo = [],
6279
    $sessionId = 0,
6280
    $userId = 0
6281
) {
6282
    $courseInfo = empty($courseInfo) ? api_get_course_info() : $courseInfo;
6283
    $courseId = $courseInfo['real_id'];
6284
    $courseCode = $courseInfo['code'];
6285
    $sessionId = empty($sessionId) ? api_get_session_id() : $sessionId;
6286
    $userId = empty($userId) ? api_get_user_id() : $userId;
6287
6288
    // if group is null force group_id = 0, this force is needed to create a LP folder with group = 0
6289
    if (is_null($group_id)) {
6290
        $group_id = 0;
6291
    } else {
6292
        $group_id = empty($group_id) ? api_get_group_id() : $group_id;
6293
    }
6294
6295
    $groupInfo = [];
6296
    if (!empty($group_id)) {
6297
        $groupInfo = GroupManager::get_group_properties($group_id);
6298
    }
6299
    $original_tool_id = $tool_id;
6300
6301
    switch ($tool_id) {
6302
        case TOOL_LINK:
6303
        case TOOL_LINK_CATEGORY:
6304
            $tool_id = 'links';
6305
            break;
6306
        case TOOL_DOCUMENT:
6307
            $tool_id = 'documents';
6308
            break;
6309
        case TOOL_LEARNPATH:
6310
            $tool_id = 'learning';
6311
            break;
6312
        case TOOL_ANNOUNCEMENT:
6313
            $tool_id = 'announcements';
6314
            break;
6315
        case TOOL_FORUM:
6316
        case TOOL_FORUM_CATEGORY:
6317
        case TOOL_FORUM_THREAD:
6318
            $tool_id = 'forums';
6319
            break;
6320
        case TOOL_QUIZ:
6321
            $tool_id = 'quiz';
6322
            break;
6323
    }
6324
    $setting = api_get_setting('tool_visible_by_default_at_creation');
6325
6326
    if (isset($setting[$tool_id])) {
6327
        $visibility = 'invisible';
6328
        if ('true' === $setting[$tool_id]) {
6329
            $visibility = 'visible';
6330
        }
6331
6332
        // Read the portal and course default visibility
6333
        if ('documents' === $tool_id) {
6334
            $visibility = DocumentManager::getDocumentDefaultVisibility($courseInfo);
6335
        }
6336
6337
        // Fixes default visibility for tests
6338
        switch ($original_tool_id) {
6339
            case TOOL_QUIZ:
6340
                if (empty($sessionId)) {
6341
                    $objExerciseTmp = new Exercise($courseId);
6342
                    $objExerciseTmp->read($item_id);
6343
                    if ('visible' === $visibility) {
6344
                        $objExerciseTmp->enable();
6345
                        $objExerciseTmp->save();
6346
                    } else {
6347
                        $objExerciseTmp->disable();
6348
                        $objExerciseTmp->save();
6349
                    }
6350
                }
6351
                break;
6352
        }
6353
    }
6354
}
6355
6356
function api_get_roles()
6357
{
6358
    $hierarchy = Container::$container->getParameter('security.role_hierarchy.roles');
6359
    $roles = [];
6360
    array_walk_recursive($hierarchy, function ($role) use (&$roles) {
6361
        $roles[$role] = $role;
6362
    });
6363
6364
    return $roles;
6365
}
6366
6367
function api_get_user_roles(): array
6368
{
6369
    $permissionService = Container::$container->get(PermissionHelper::class);
6370
6371
    $roles = $permissionService->getUserRoles();
6372
6373
    return array_combine($roles, $roles);
6374
}
6375
6376
/**
6377
 * @param string $file
6378
 *
6379
 * @return string
6380
 */
6381
function api_get_js_simple($file)
6382
{
6383
    return '<script type="text/javascript" src="'.$file.'"></script>'."\n";
6384
}
6385
6386
/**
6387
 * Modify default memory_limit and max_execution_time limits
6388
 * Needed when processing long tasks.
6389
 */
6390
function api_set_more_memory_and_time_limits()
6391
{
6392
    if (function_exists('ini_set')) {
6393
        api_set_memory_limit('256M');
6394
        ini_set('max_execution_time', 1800);
6395
    }
6396
}
6397
6398
/**
6399
 * Tries to set memory limit, if authorized and new limit is higher than current.
6400
 *
6401
 * @param string $mem New memory limit
6402
 *
6403
 * @return bool True on success, false on failure or current is higher than suggested
6404
 * @assert (null) === false
6405
 * @assert (-1) === false
6406
 * @assert (0) === true
6407
 * @assert ('1G') === true
6408
 */
6409
function api_set_memory_limit($mem)
6410
{
6411
    //if ini_set() not available, this function is useless
6412
    if (!function_exists('ini_set') || is_null($mem) || -1 == $mem) {
6413
        return false;
6414
    }
6415
6416
    $memory_limit = ini_get('memory_limit');
6417
    if (api_get_bytes_memory_limit($mem) > api_get_bytes_memory_limit($memory_limit)) {
6418
        ini_set('memory_limit', $mem);
6419
6420
        return true;
6421
    }
6422
6423
    return false;
6424
}
6425
6426
/**
6427
 * Gets memory limit in bytes.
6428
 *
6429
 * @param string The memory size (128M, 1G, 1000K, etc)
6430
 *
6431
 * @return int
6432
 * @assert (null) === false
6433
 * @assert ('1t')  === 1099511627776
6434
 * @assert ('1g')  === 1073741824
6435
 * @assert ('1m')  === 1048576
6436
 * @assert ('100k') === 102400
6437
 */
6438
function api_get_bytes_memory_limit($mem)
6439
{
6440
    $size = strtolower(substr($mem, -1));
6441
6442
    switch ($size) {
6443
        case 't':
6444
            $mem = (int) substr($mem, -1) * 1024 * 1024 * 1024 * 1024;
6445
            break;
6446
        case 'g':
6447
            $mem = (int) substr($mem, 0, -1) * 1024 * 1024 * 1024;
6448
            break;
6449
        case 'm':
6450
            $mem = (int) substr($mem, 0, -1) * 1024 * 1024;
6451
            break;
6452
        case 'k':
6453
            $mem = (int) substr($mem, 0, -1) * 1024;
6454
            break;
6455
        default:
6456
            // we assume it's integer only
6457
            $mem = (int) $mem;
6458
            break;
6459
    }
6460
6461
    return $mem;
6462
}
6463
6464
/**
6465
 * Finds all the information about a user from username instead of user id.
6466
 *
6467
 * @param string $officialCode
6468
 *
6469
 * @return array $user_info user_id, lastname, firstname, username, email, ...
6470
 *
6471
 * @author Yannick Warnier <[email protected]>
6472
 */
6473
function api_get_user_info_from_official_code($officialCode)
6474
{
6475
    if (empty($officialCode)) {
6476
        return false;
6477
    }
6478
    $sql = "SELECT * FROM ".Database::get_main_table(TABLE_MAIN_USER)."
6479
            WHERE official_code ='".Database::escape_string($officialCode)."'";
6480
    $result = Database::query($sql);
6481
    if (Database::num_rows($result) > 0) {
6482
        $result_array = Database::fetch_array($result);
6483
6484
        return _api_format_user($result_array);
6485
    }
6486
6487
    return false;
6488
}
6489
6490
/**
6491
 * @param string $usernameInputId
6492
 * @param string $passwordInputId
6493
 *
6494
 * @return string|null
6495
 */
6496
function api_get_password_checker_js($usernameInputId, $passwordInputId)
6497
{
6498
    $checkPass = api_get_setting('allow_strength_pass_checker');
6499
    $useStrengthPassChecker = 'true' === $checkPass;
6500
6501
    if (false === $useStrengthPassChecker) {
6502
        return null;
6503
    }
6504
6505
    $minRequirements = Security::getPasswordRequirements()['min'];
6506
6507
    $options = [
6508
        'rules' => [],
6509
    ];
6510
6511
    if ($minRequirements['length'] > 0) {
6512
        $options['rules'][] = [
6513
            'minChar' => $minRequirements['length'],
6514
            'pattern' => '.',
6515
            'helpText' => sprintf(
6516
                get_lang('Minimum %s characters in total'),
6517
                $minRequirements['length']
6518
            ),
6519
        ];
6520
    }
6521
6522
    if ($minRequirements['lowercase'] > 0) {
6523
        $options['rules'][] = [
6524
            'minChar' => $minRequirements['lowercase'],
6525
            'pattern' => '[a-z]',
6526
            'helpText' => sprintf(
6527
                get_lang('Minimum %s lowercase characters'),
6528
                $minRequirements['lowercase']
6529
            ),
6530
        ];
6531
    }
6532
6533
    if ($minRequirements['uppercase'] > 0) {
6534
        $options['rules'][] = [
6535
            'minChar' => $minRequirements['uppercase'],
6536
            'pattern' => '[A-Z]',
6537
            'helpText' => sprintf(
6538
                get_lang('Minimum %s uppercase characters'),
6539
                $minRequirements['uppercase']
6540
            ),
6541
        ];
6542
    }
6543
6544
    if ($minRequirements['numeric'] > 0) {
6545
        $options['rules'][] = [
6546
            'minChar' => $minRequirements['numeric'],
6547
            'pattern' => '[0-9]',
6548
            'helpText' => sprintf(
6549
                get_lang('Minimum %s numerical (0-9) characters'),
6550
                $minRequirements['numeric']
6551
            ),
6552
        ];
6553
    }
6554
6555
    if ($minRequirements['specials'] > 0) {
6556
        $options['rules'][] = [
6557
            'minChar' => $minRequirements['specials'],
6558
            'pattern' => '[!"#$%&\'()*+,\-./\\\:;<=>?@[\\]^_`{|}~]',
6559
            'helpText' => sprintf(
6560
                get_lang('Minimum %s special characters'),
6561
                $minRequirements['specials']
6562
            ),
6563
        ];
6564
    }
6565
6566
    $js = api_get_js('password-checker/password-checker.js');
6567
    $js .= "<script>
6568
    $(function() {
6569
        $('".$passwordInputId."').passwordChecker(".json_encode($options).");
6570
    });
6571
    </script>";
6572
6573
    return $js;
6574
}
6575
6576
/**
6577
 * create an user extra field called 'captcha_blocked_until_date'.
6578
 *
6579
 * @param string $username
6580
 *
6581
 * @return bool
6582
 */
6583
function api_block_account_captcha($username)
6584
{
6585
    $userInfo = api_get_user_info_from_username($username);
6586
    if (empty($userInfo)) {
6587
        return false;
6588
    }
6589
    $minutesToBlock = api_get_setting('captcha_time_to_block');
6590
    $time = time() + $minutesToBlock * 60;
6591
    UserManager::update_extra_field_value(
6592
        $userInfo['user_id'],
6593
        'captcha_blocked_until_date',
6594
        api_get_utc_datetime($time)
6595
    );
6596
6597
    return true;
6598
}
6599
6600
/**
6601
 * @param string $username
6602
 *
6603
 * @return bool
6604
 */
6605
function api_clean_account_captcha($username)
6606
{
6607
    $userInfo = api_get_user_info_from_username($username);
6608
    if (empty($userInfo)) {
6609
        return false;
6610
    }
6611
    Session::erase('loginFailedCount');
6612
    UserManager::update_extra_field_value(
6613
        $userInfo['user_id'],
6614
        'captcha_blocked_until_date',
6615
        null
6616
    );
6617
6618
    return true;
6619
}
6620
6621
/**
6622
 * @param string $username
6623
 *
6624
 * @return bool
6625
 */
6626
function api_get_user_blocked_by_captcha($username)
6627
{
6628
    $userInfo = api_get_user_info_from_username($username);
6629
    if (empty($userInfo)) {
6630
        return false;
6631
    }
6632
    $data = UserManager::get_extra_user_data_by_field(
6633
        $userInfo['user_id'],
6634
        'captcha_blocked_until_date'
6635
    );
6636
    if (isset($data) && isset($data['captcha_blocked_until_date'])) {
6637
        return $data['captcha_blocked_until_date'];
6638
    }
6639
6640
    return false;
6641
}
6642
6643
/**
6644
 * If true, the drh can access all content (courses, users) inside a session.
6645
 *
6646
 * @return bool
6647
 */
6648
function api_drh_can_access_all_session_content()
6649
{
6650
    return 'true' === api_get_setting('drh_can_access_all_session_content');
6651
}
6652
6653
/**
6654
 * Checks if user can login as another user.
6655
 *
6656
 * @param int $loginAsUserId the user id to log in
6657
 * @param int $userId        my user id
6658
 *
6659
 * @return bool
6660
 */
6661
function api_can_login_as($loginAsUserId, $userId = null)
6662
{
6663
    $loginAsUserId = (int) $loginAsUserId;
6664
6665
    if (empty($loginAsUserId)) {
6666
        return false;
6667
    }
6668
6669
    if (empty($userId)) {
6670
        $userId = api_get_user_id();
6671
    }
6672
6673
    if ($loginAsUserId == $userId) {
6674
        return false;
6675
    }
6676
6677
    // Check if the user to login is an admin
6678
    if (api_is_platform_admin_by_id($loginAsUserId)) {
6679
        // Only super admins can login to admin accounts
6680
        if (!api_global_admin_can_edit_admin($loginAsUserId)) {
6681
            return false;
6682
        }
6683
    }
6684
6685
    $userInfo = api_get_user_info($loginAsUserId);
6686
6687
    $isDrh = function () use ($loginAsUserId) {
6688
        if (api_is_drh()) {
6689
            if (api_drh_can_access_all_session_content()) {
6690
                $users = SessionManager::getAllUsersFromCoursesFromAllSessionFromStatus(
6691
                    'drh_all',
6692
                    api_get_user_id()
6693
                );
6694
                $userList = [];
6695
                if (is_array($users)) {
6696
                    foreach ($users as $user) {
6697
                        $userList[] = $user['id'];
6698
                    }
6699
                }
6700
                if (in_array($loginAsUserId, $userList)) {
6701
                    return true;
6702
                }
6703
            } else {
6704
                if (api_is_drh() &&
6705
                    UserManager::is_user_followed_by_drh($loginAsUserId, api_get_user_id())
6706
                ) {
6707
                    return true;
6708
                }
6709
            }
6710
        }
6711
6712
        return false;
6713
    };
6714
6715
    $loginAsStatusForSessionAdmins = [STUDENT];
6716
6717
    if ('true' === api_get_setting('session.allow_session_admin_login_as_teacher')) {
6718
        $loginAsStatusForSessionAdmins[] = COURSEMANAGER;
6719
    }
6720
6721
    return api_is_platform_admin() ||
6722
        (api_is_session_admin() && in_array($userInfo['status'], $loginAsStatusForSessionAdmins)) ||
6723
        $isDrh();
6724
}
6725
6726
/**
6727
 * Return true on https install.
6728
 *
6729
 * @return bool
6730
 */
6731
function api_is_https()
6732
{
6733
    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...
6734
        'https' == $_SERVER['HTTP_X_FORWARDED_PROTO'] || !empty(api_get_configuration_value('force_https_forwarded_proto'))
6735
    ) {
6736
        $isSecured = true;
6737
    } else {
6738
        if (!empty($_SERVER['HTTPS']) && 'off' != $_SERVER['HTTPS']) {
6739
            $isSecured = true;
6740
        } else {
6741
            $isSecured = false;
6742
            // last chance
6743
            if (!empty($_SERVER['SERVER_PORT']) && 443 == $_SERVER['SERVER_PORT']) {
6744
                $isSecured = true;
6745
            }
6746
        }
6747
    }
6748
6749
    return $isSecured;
6750
}
6751
6752
/**
6753
 * Return protocol (http or https).
6754
 *
6755
 * @return string
6756
 */
6757
function api_get_protocol()
6758
{
6759
    return api_is_https() ? 'https' : 'http';
6760
}
6761
6762
/**
6763
 * Get origin.
6764
 *
6765
 * @param string
6766
 *
6767
 * @return string
6768
 */
6769
function api_get_origin()
6770
{
6771
    return isset($_REQUEST['origin']) ? urlencode(Security::remove_XSS(urlencode($_REQUEST['origin']))) : '';
6772
}
6773
6774
/**
6775
 * Warns an user that the portal reach certain limit.
6776
 *
6777
 * @param string $limitName
6778
 */
6779
function api_warn_hosting_contact($limitName)
6780
{
6781
    $hostingParams = api_get_configuration_value(1);
6782
    $email = null;
6783
6784
    if (!empty($hostingParams)) {
6785
        if (isset($hostingParams['hosting_contact_mail'])) {
6786
            $email = $hostingParams['hosting_contact_mail'];
6787
        }
6788
    }
6789
6790
    if (!empty($email)) {
6791
        $subject = get_lang('Hosting warning reached');
6792
        $body = get_lang('Portal name').': '.api_get_path(WEB_PATH)." \n ";
6793
        $body .= get_lang('Portal\'s limit type').': '.$limitName." \n ";
6794
        if (isset($hostingParams[$limitName])) {
6795
            $body .= get_lang('Value').': '.$hostingParams[$limitName];
6796
        }
6797
        api_mail_html(null, $email, $subject, $body);
6798
    }
6799
}
6800
6801
/**
6802
 * Gets value of a variable from config/configuration.php
6803
 * Variables that are not set in the configuration.php file but set elsewhere:
6804
 * - virtual_css_theme_folder (vchamilo plugin)
6805
 * - access_url (global.inc.php)
6806
 * - apc/apc_prefix (global.inc.php).
6807
 *
6808
 * @param string $variable
6809
 *
6810
 * @return bool|mixed
6811
 */
6812
function api_get_configuration_value($variable)
6813
{
6814
    global $_configuration;
6815
    // Check the current url id, id = 1 by default
6816
    $urlId = isset($_configuration['access_url']) ? (int) $_configuration['access_url'] : 1;
6817
6818
    $variable = trim($variable);
6819
6820
    // Check if variable exists
6821
    if (isset($_configuration[$variable])) {
6822
        if (is_array($_configuration[$variable])) {
6823
            // Check if it exists for the sub portal
6824
            if (array_key_exists($urlId, $_configuration[$variable])) {
6825
                return $_configuration[$variable][$urlId];
6826
            } else {
6827
                // Try to found element with id = 1 (master portal)
6828
                if (array_key_exists(1, $_configuration[$variable])) {
6829
                    return $_configuration[$variable][1];
6830
                }
6831
            }
6832
        }
6833
6834
        return $_configuration[$variable];
6835
    }
6836
6837
    return false;
6838
}
6839
6840
/**
6841
 * Gets a specific hosting limit.
6842
 *
6843
 * @param int $urlId The URL ID.
6844
 * @param string $limitName The name of the limit.
6845
 * @return mixed The value of the limit, or null if not found.
6846
 */
6847
function get_hosting_limit(int $urlId, string $limitName): mixed
6848
{
6849
    if (!Container::$container->hasParameter('settings_overrides')) {
6850
        return [];
6851
    }
6852
6853
    $settingsOverrides = Container::$container->getParameter('settings_overrides');
6854
6855
    $limits = $settingsOverrides[$urlId]['hosting_limit'] ?? $settingsOverrides['default']['hosting_limit'];
6856
6857
    foreach ($limits as $limitArray) {
6858
        if (isset($limitArray[$limitName])) {
6859
            return $limitArray[$limitName];
6860
        }
6861
    }
6862
6863
    return null;
6864
}
6865
6866
6867
/**
6868
 * Retrieves an environment variable value with validation and handles boolean conversion.
6869
 *
6870
 * @param string $variable The name of the environment variable.
6871
 * @param mixed $default The default value to return if the variable is not set.
6872
 * @return mixed The value of the environment variable, converted to boolean if necessary, or the default value.
6873
 */
6874
function api_get_env_variable(string $variable, mixed $default = null): mixed
6875
{
6876
    $variable = strtolower($variable);
6877
    if (Container::$container->hasParameter($variable)) {
6878
        return Container::$container->getParameter($variable);
6879
    }
6880
6881
    return $default;
6882
}
6883
6884
/**
6885
 * Retreives and returns a value in a hierarchical configuration array
6886
 * api_get_configuration_sub_value('a/b/c') returns api_get_configuration_value('a')['b']['c'].
6887
 *
6888
 * @param string $path      the successive array keys, separated by the separator
6889
 * @param mixed  $default   value to be returned if not found, null by default
6890
 * @param string $separator '/' by default
6891
 * @param array  $array     the active configuration array by default
6892
 *
6893
 * @return mixed the found value or $default
6894
 */
6895
function api_get_configuration_sub_value($path, $default = null, $separator = '/', $array = null)
6896
{
6897
    $pos = strpos($path, $separator);
6898
    if (false === $pos) {
6899
        if (is_null($array)) {
6900
            return api_get_configuration_value($path);
6901
        }
6902
        if (is_array($array) && array_key_exists($path, $array)) {
6903
            return $array[$path];
6904
        }
6905
6906
        return $default;
6907
    }
6908
    $key = substr($path, 0, $pos);
6909
    if (is_null($array)) {
6910
        $newArray = api_get_configuration_value($key);
6911
    } elseif (is_array($array) && array_key_exists($key, $array)) {
6912
        $newArray = $array[$key];
6913
    } else {
6914
        return $default;
6915
    }
6916
    if (is_array($newArray)) {
6917
        $newPath = substr($path, $pos + 1);
6918
6919
        return api_get_configuration_sub_value($newPath, $default, $separator, $newArray);
6920
    }
6921
6922
    return $default;
6923
}
6924
6925
/**
6926
 * Retrieves and returns a value in a hierarchical configuration array
6927
 * api_array_sub_value($array, 'a/b/c') returns $array['a']['b']['c'].
6928
 *
6929
 * @param array  $array     the recursive array that contains the value to be returned (or not)
6930
 * @param string $path      the successive array keys, separated by the separator
6931
 * @param mixed  $default   the value to be returned if not found
6932
 * @param string $separator the separator substring
6933
 *
6934
 * @return mixed the found value or $default
6935
 */
6936
function api_array_sub_value($array, $path, $default = null, $separator = '/')
6937
{
6938
    $pos = strpos($path, $separator);
6939
    if (false === $pos) {
6940
        if (is_array($array) && array_key_exists($path, $array)) {
6941
            return $array[$path];
6942
        }
6943
6944
        return $default;
6945
    }
6946
    $key = substr($path, 0, $pos);
6947
    if (is_array($array) && array_key_exists($key, $array)) {
6948
        $newArray = $array[$key];
6949
    } else {
6950
        return $default;
6951
    }
6952
    if (is_array($newArray)) {
6953
        $newPath = substr($path, $pos + 1);
6954
6955
        return api_array_sub_value($newArray, $newPath, $default);
6956
    }
6957
6958
    return $default;
6959
}
6960
6961
/**
6962
 * Returns supported image extensions in the portal.
6963
 *
6964
 * @param bool $supportVectors Whether vector images should also be accepted or not
6965
 *
6966
 * @return array Supported image extensions in the portal
6967
 */
6968
function api_get_supported_image_extensions($supportVectors = true)
6969
{
6970
    // jpg can also be called jpeg, jpe, jfif and jif. See https://en.wikipedia.org/wiki/JPEG#JPEG_filename_extensions
6971
    $supportedImageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'jpe', 'jfif', 'jif'];
6972
    if ($supportVectors) {
6973
        array_push($supportedImageExtensions, 'svg');
6974
    }
6975
    if (version_compare(PHP_VERSION, '5.5.0', '>=')) {
6976
        array_push($supportedImageExtensions, 'webp');
6977
    }
6978
6979
    return $supportedImageExtensions;
6980
}
6981
6982
/**
6983
 * This setting changes the registration status for the campus.
6984
 *
6985
 * @author Patrick Cool <[email protected]>, Ghent University
6986
 *
6987
 * @version August 2006
6988
 *
6989
 * @param bool $listCampus Whether we authorize
6990
 *
6991
 * @todo the $_settings should be reloaded here. => write api function for this and use this in global.inc.php also.
6992
 */
6993
function api_register_campus($listCampus = true)
6994
{
6995
    $tbl_settings = Database::get_main_table(TABLE_MAIN_SETTINGS);
6996
6997
    $sql = "UPDATE $tbl_settings SET selected_value='true' WHERE variable='registered'";
6998
    Database::query($sql);
6999
7000
    if (!$listCampus) {
7001
        $sql = "UPDATE $tbl_settings SET selected_value='true' WHERE variable='donotlistcampus'";
7002
        Database::query($sql);
7003
    }
7004
}
7005
7006
/**
7007
 * Check whether the user type should be exclude.
7008
 * Such as invited or anonymous users.
7009
 *
7010
 * @param bool $checkDB Optional. Whether check the user status
7011
 * @param int  $userId  Options. The user id
7012
 *
7013
 * @return bool
7014
 */
7015
function api_is_excluded_user_type($checkDB = false, $userId = 0)
7016
{
7017
    if ($checkDB) {
7018
        $userId = empty($userId) ? api_get_user_id() : (int) $userId;
7019
7020
        if (0 == $userId) {
7021
            return true;
7022
        }
7023
7024
        $userInfo = api_get_user_info($userId);
7025
7026
        switch ($userInfo['status']) {
7027
            case INVITEE:
7028
            case ANONYMOUS:
7029
                return true;
7030
            default:
7031
                return false;
7032
        }
7033
    }
7034
7035
    $isInvited = api_is_invitee();
7036
    $isAnonymous = api_is_anonymous();
7037
7038
    if ($isInvited || $isAnonymous) {
7039
        return true;
7040
    }
7041
7042
    return false;
7043
}
7044
7045
/**
7046
 * Get the user status to ignore in reports.
7047
 *
7048
 * @param string $format Optional. The result type (array or string)
7049
 *
7050
 * @return array|string
7051
 */
7052
function api_get_users_status_ignored_in_reports($format = 'array')
7053
{
7054
    $excludedTypes = [
7055
        INVITEE,
7056
        ANONYMOUS,
7057
    ];
7058
7059
    if ('string' == $format) {
7060
        return implode(', ', $excludedTypes);
7061
    }
7062
7063
    return $excludedTypes;
7064
}
7065
7066
/**
7067
 * Set the Site Use Cookie Warning for 1 year.
7068
 */
7069
function api_set_site_use_cookie_warning_cookie()
7070
{
7071
    setcookie('ChamiloUsesCookies', 'ok', time() + 31556926);
7072
}
7073
7074
/**
7075
 * Return true if the Site Use Cookie Warning Cookie warning exists.
7076
 *
7077
 * @return bool
7078
 */
7079
function api_site_use_cookie_warning_cookie_exist()
7080
{
7081
    return isset($_COOKIE['ChamiloUsesCookies']);
7082
}
7083
7084
/**
7085
 * Given a number of seconds, format the time to show hours, minutes and seconds.
7086
 *
7087
 * @param int    $time         The time in seconds
7088
 * @param string $originFormat Optional. PHP o JS
7089
 *
7090
 * @return string (00h00'00")
7091
 */
7092
function api_format_time($time, $originFormat = 'php')
7093
{
7094
    $h = get_lang('h');
7095
    $hours = $time / 3600;
7096
    $mins = ($time % 3600) / 60;
7097
    $secs = ($time % 60);
7098
7099
    if ($time < 0) {
7100
        $hours = 0;
7101
        $mins = 0;
7102
        $secs = 0;
7103
    }
7104
7105
    if ('js' === $originFormat) {
7106
        $formattedTime = trim(sprintf("%02d : %02d : %02d", $hours, $mins, $secs));
7107
    } else {
7108
        $formattedTime = trim(sprintf("%02d$h%02d'%02d\"", $hours, $mins, $secs));
7109
    }
7110
7111
    return $formattedTime;
7112
}
7113
7114
/**
7115
 * Sends an email
7116
 * Sender name and email can be specified, if not specified
7117
 * name and email of the platform admin are used.
7118
 *
7119
 * @param string    name of recipient
7120
 * @param string    email of recipient
7121
 * @param string    email subject
7122
 * @param string    email body
7123
 * @param string    sender name
7124
 * @param string    sender e-mail
7125
 * @param array     extra headers in form $headers = array($name => $value) to allow parsing
7126
 * @param array     data file (path and filename)
7127
 * @param bool      True for attaching a embedded file inside content html (optional)
7128
 * @param array     Additional parameters
7129
 *
7130
 * @return bool true if mail was sent
7131
 */
7132
function api_mail_html(
7133
    $recipientName,
7134
    $recipientEmail,
7135
    $subject,
7136
    $body,
7137
    $senderName = '',
7138
    $senderEmail = '',
7139
    $extra_headers = [],
7140
    $data_file = [],
7141
    $embeddedImage = false,
7142
    $additionalParameters = [],
7143
    string $sendErrorTo = null
7144
) {
7145
    $mailHelper = Container::$container->get(MailHelper::class);
7146
7147
    return $mailHelper->send(
7148
        $recipientName,
7149
        $recipientEmail,
7150
        $subject,
7151
        $body,
7152
        $senderName,
7153
        $senderEmail,
7154
        $extra_headers,
7155
        $data_file,
7156
        $embeddedImage,
7157
        $additionalParameters,
7158
        $sendErrorTo
7159
    );
7160
}
7161
7162
/**
7163
 * @param int  $tool       Possible values: GroupManager::GROUP_TOOL_*
7164
 * @param bool $showHeader
7165
 */
7166
function api_protect_course_group($tool, $showHeader = true)
7167
{
7168
    $groupId = api_get_group_id();
7169
    if (!empty($groupId)) {
7170
        if (api_is_platform_admin()) {
7171
            return true;
7172
        }
7173
7174
        if (api_is_allowed_to_edit(false, true, true)) {
7175
            return true;
7176
        }
7177
7178
        $userId = api_get_user_id();
7179
        $sessionId = api_get_session_id();
7180
        if (!empty($sessionId)) {
7181
            if (api_is_coach($sessionId, api_get_course_int_id())) {
7182
                return true;
7183
            }
7184
7185
            if (api_is_drh()) {
7186
                if (SessionManager::isUserSubscribedAsHRM($sessionId, $userId)) {
7187
                    return true;
7188
                }
7189
            }
7190
        }
7191
7192
        $group = api_get_group_entity($groupId);
7193
7194
        // Group doesn't exists
7195
        if (null === $group) {
7196
            api_not_allowed($showHeader);
7197
        }
7198
7199
        // Check group access
7200
        $allow = GroupManager::userHasAccess(
7201
            $userId,
7202
            $group,
7203
            $tool
7204
        );
7205
7206
        if (!$allow) {
7207
            api_not_allowed($showHeader);
7208
        }
7209
    }
7210
7211
    return false;
7212
}
7213
7214
/**
7215
 * Check if a date is in a date range.
7216
 *
7217
 * @param datetime $startDate
7218
 * @param datetime $endDate
7219
 * @param datetime $currentDate
7220
 *
7221
 * @return bool true if date is in rage, false otherwise
7222
 */
7223
function api_is_date_in_date_range($startDate, $endDate, $currentDate = null)
7224
{
7225
    $startDate = strtotime(api_get_local_time($startDate));
7226
    $endDate = strtotime(api_get_local_time($endDate));
7227
    $currentDate = strtotime(api_get_local_time($currentDate));
7228
7229
    if ($currentDate >= $startDate && $currentDate <= $endDate) {
7230
        return true;
7231
    }
7232
7233
    return false;
7234
}
7235
7236
/**
7237
 * Eliminate the duplicates of a multidimensional array by sending the key.
7238
 *
7239
 * @param array $array multidimensional array
7240
 * @param int   $key   key to find to compare
7241
 *
7242
 * @return array
7243
 */
7244
function api_unique_multidim_array($array, $key)
7245
{
7246
    $temp_array = [];
7247
    $i = 0;
7248
    $key_array = [];
7249
7250
    foreach ($array as $val) {
7251
        if (!in_array($val[$key], $key_array)) {
7252
            $key_array[$i] = $val[$key];
7253
            $temp_array[$i] = $val;
7254
        }
7255
        $i++;
7256
    }
7257
7258
    return $temp_array;
7259
}
7260
7261
/**
7262
 * Limit the access to Session Admins when the limit_session_admin_role
7263
 * configuration variable is set to true.
7264
 */
7265
function api_protect_limit_for_session_admin()
7266
{
7267
    $limitAdmin = api_get_setting('limit_session_admin_role');
7268
    if (api_is_session_admin() && 'true' === $limitAdmin) {
7269
        api_not_allowed(true);
7270
    }
7271
}
7272
7273
/**
7274
 * Limits that a session admin has access to list users.
7275
 * When limit_session_admin_list_users configuration variable is set to true.
7276
 */
7277
function api_protect_session_admin_list_users()
7278
{
7279
    $limitAdmin = ('true' === api_get_setting('session.limit_session_admin_list_users'));
7280
7281
    if (api_is_session_admin() && true === $limitAdmin) {
7282
        api_not_allowed(true);
7283
    }
7284
}
7285
7286
/**
7287
 * @return bool
7288
 */
7289
function api_is_student_view_active(): bool
7290
{
7291
    $studentView = Session::read('studentview');
7292
7293
    return 'studentview' === $studentView;
7294
}
7295
7296
/**
7297
 * Converts string value to float value.
7298
 *
7299
 * 3.141516 => 3.141516
7300
 * 3,141516 => 3.141516
7301
 *
7302
 * @todo WIP
7303
 *
7304
 * @param string $number
7305
 *
7306
 * @return float
7307
 */
7308
function api_float_val($number)
7309
{
7310
    return (float) str_replace(',', '.', trim($number));
7311
}
7312
7313
/**
7314
 * Converts float values
7315
 * Example if $decimals = 2.
7316
 *
7317
 * 3.141516 => 3.14
7318
 * 3,141516 => 3,14
7319
 *
7320
 * @param string $number            number in iso code
7321
 * @param int    $decimals
7322
 * @param string $decimalSeparator
7323
 * @param string $thousandSeparator
7324
 *
7325
 * @return bool|string
7326
 */
7327
function api_number_format($number, $decimals = 0, $decimalSeparator = '.', $thousandSeparator = ',')
7328
{
7329
    $number = api_float_val($number);
7330
7331
    return number_format($number, $decimals, $decimalSeparator, $thousandSeparator);
7332
}
7333
7334
/**
7335
 * Set location url with a exit break by default.
7336
 *
7337
 * @param string $url
7338
 * @param bool   $exit
7339
 */
7340
function api_location($url, $exit = true)
7341
{
7342
    header('Location: '.$url);
7343
7344
    if ($exit) {
7345
        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...
7346
    }
7347
}
7348
7349
/**
7350
 * @param string $from
7351
 * @param string $to
7352
 *
7353
 * @return string
7354
 */
7355
function api_get_relative_path($from, $to)
7356
{
7357
    // some compatibility fixes for Windows paths
7358
    $from = is_dir($from) ? rtrim($from, '\/').'/' : $from;
7359
    $to = is_dir($to) ? rtrim($to, '\/').'/' : $to;
7360
    $from = str_replace('\\', '/', $from);
7361
    $to = str_replace('\\', '/', $to);
7362
7363
    $from = explode('/', $from);
7364
    $to = explode('/', $to);
7365
    $relPath = $to;
7366
7367
    foreach ($from as $depth => $dir) {
7368
        // find first non-matching dir
7369
        if ($dir === $to[$depth]) {
7370
            // ignore this directory
7371
            array_shift($relPath);
7372
        } else {
7373
            // get number of remaining dirs to $from
7374
            $remaining = count($from) - $depth;
7375
            if ($remaining > 1) {
7376
                // add traversals up to first matching dir
7377
                $padLength = (count($relPath) + $remaining - 1) * -1;
7378
                $relPath = array_pad($relPath, $padLength, '..');
7379
                break;
7380
            } else {
7381
                $relPath[0] = './'.$relPath[0];
7382
            }
7383
        }
7384
    }
7385
7386
    return implode('/', $relPath);
7387
}
7388
7389
/**
7390
 * @param string $template
7391
 *
7392
 * @return string
7393
 */
7394
function api_find_template($template)
7395
{
7396
    return Template::findTemplateFilePath($template);
7397
}
7398
7399
/**
7400
 * @return array
7401
 */
7402
function api_get_language_list_for_flag()
7403
{
7404
    $table = Database::get_main_table(TABLE_MAIN_LANGUAGE);
7405
    $sql = "SELECT english_name, isocode FROM $table
7406
            ORDER BY original_name ASC";
7407
    static $languages = [];
7408
    if (empty($languages)) {
7409
        $result = Database::query($sql);
7410
        while ($row = Database::fetch_array($result)) {
7411
            $languages[$row['english_name']] = $row['isocode'];
7412
        }
7413
        $languages['english'] = 'gb';
7414
    }
7415
7416
    return $languages;
7417
}
7418
7419
function api_create_zip(string $name): ZipStream
7420
{
7421
    $zipStreamOptions = new Archive();
7422
    $zipStreamOptions->setSendHttpHeaders(true);
7423
    $zipStreamOptions->setContentDisposition('attachment');
7424
    $zipStreamOptions->setContentType('application/x-zip');
7425
7426
    return new ZipStream($name, $zipStreamOptions);
7427
}
7428
7429
function api_get_language_translate_html(): string
7430
{
7431
    $translate = 'true' === api_get_setting('editor.translate_html');
7432
7433
    if (!$translate) {
7434
        return '';
7435
    }
7436
7437
    /*$languageList = api_get_languages();
7438
    $hideAll = '';
7439
    foreach ($languageList as $isocode => $name) {
7440
        $hideAll .= '
7441
        $(".mce-translatehtml").hide();
7442
        $("span:lang('.$isocode.')").filter(
7443
            function(e, val) {
7444
                // Only find the spans if they have set the lang
7445
                if ($(this).attr("lang") == null) {
7446
                    return false;
7447
                }
7448
                // Ignore ckeditor classes
7449
                return !this.className.match(/cke(.*)/);
7450
        }).hide();'."\n";
7451
    }*/
7452
7453
    $userInfo = api_get_user_info();
7454
    if (!empty($userInfo['language'])) {
7455
        $isoCode = $userInfo['language'];
7456
7457
        return '
7458
            $(function() {
7459
                $(".mce-translatehtml").hide();
7460
                var defaultLanguageFromUser = "'.$isoCode.'";
7461
                $("span:lang('.$isoCode.')").show();
7462
            });
7463
        ';
7464
    }
7465
7466
    return '';
7467
}
7468
7469
function api_protect_webservices()
7470
{
7471
    if (api_get_configuration_value('disable_webservices')) {
7472
        echo "Webservices are disabled. \n";
7473
        echo "To enable, add \$_configuration['disable_webservices'] = true; in configuration.php";
7474
        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...
7475
    }
7476
}
7477
7478
function api_filename_has_blacklisted_stream_wrapper(string $filename) {
7479
    if (strpos($filename, '://') > 0) {
7480
        $wrappers = stream_get_wrappers();
7481
        $allowedWrappers = ['http', 'https', 'file'];
7482
        foreach ($wrappers as $wrapper) {
7483
            if (in_array($wrapper, $allowedWrappers)) {
7484
                continue;
7485
            }
7486
            if (stripos($filename, $wrapper . '://') === 0) {
7487
                return true;
7488
            }
7489
        }
7490
    }
7491
    return false;
7492
}
7493
7494
/**
7495
 * Checks if a set of roles have a specific permission.
7496
 *
7497
 * @param string $permissionSlug The slug of the permission to check.
7498
 * @param array  $roles          An array of role codes to check against.
7499
 * @return bool True if any of the roles have the permission, false otherwise.
7500
 */
7501
function api_get_permission(string $permissionSlug, array $roles): bool
7502
{
7503
    $permissionService = Container::$container->get(PermissionHelper::class);
7504
7505
    return $permissionService->hasPermission($permissionSlug, $roles);
7506
}
7507
7508
/**
7509
 * Calculate the percentage of change between two numbers.
7510
 *
7511
 * @param int $newValue
7512
 * @param int $oldValue
7513
 * @return string
7514
 */
7515
function api_calculate_increment_percent(int $newValue, int $oldValue): string
7516
{
7517
    if ($oldValue <= 0) {
7518
        $result = " - ";
7519
    } else {
7520
        $result = ' '.round(100 * (($newValue / $oldValue) - 1), 2).' %';
7521
    }
7522
    return $result;
7523
}
7524
7525
/**
7526
 * @todo Move to UserRegistrationHelper when migrating inscription.php to Symfony
7527
 */
7528
function api_email_reached_registration_limit(string $email): bool
7529
{
7530
    $limit = (int) api_get_setting('platform.hosting_limit_identical_email');
7531
7532
    if ($limit <= 0 || empty($email)) {
7533
        return false;
7534
    }
7535
7536
    $repo = Container::getUserRepository();
7537
    $count = $repo->countUsersByEmail($email);
7538
7539
    return $count >= $limit;
7540
}
7541
7542