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
define('PAGE_BREAK', 23);
498
499
define('EXERCISE_CATEGORY_RANDOM_SHUFFLED', 1);
500
define('EXERCISE_CATEGORY_RANDOM_ORDERED', 2);
501
define('EXERCISE_CATEGORY_RANDOM_DISABLED', 0);
502
503
// Question selection type
504
define('EX_Q_SELECTION_ORDERED', 1);
505
define('EX_Q_SELECTION_RANDOM', 2);
506
define('EX_Q_SELECTION_CATEGORIES_ORDERED_QUESTIONS_ORDERED', 3);
507
define('EX_Q_SELECTION_CATEGORIES_RANDOM_QUESTIONS_ORDERED', 4);
508
define('EX_Q_SELECTION_CATEGORIES_ORDERED_QUESTIONS_RANDOM', 5);
509
define('EX_Q_SELECTION_CATEGORIES_RANDOM_QUESTIONS_RANDOM', 6);
510
define('EX_Q_SELECTION_CATEGORIES_RANDOM_QUESTIONS_ORDERED_NO_GROUPED', 7);
511
define('EX_Q_SELECTION_CATEGORIES_RANDOM_QUESTIONS_RANDOM_NO_GROUPED', 8);
512
define('EX_Q_SELECTION_CATEGORIES_ORDERED_BY_PARENT_QUESTIONS_ORDERED', 9);
513
define('EX_Q_SELECTION_CATEGORIES_ORDERED_BY_PARENT_QUESTIONS_RANDOM', 10);
514
515
// Used to save the skill_rel_item table
516
define('ITEM_TYPE_EXERCISE', 1);
517
define('ITEM_TYPE_HOTPOTATOES', 2);
518
define('ITEM_TYPE_LINK', 3);
519
define('ITEM_TYPE_LEARNPATH', 4);
520
define('ITEM_TYPE_GRADEBOOK', 5);
521
define('ITEM_TYPE_STUDENT_PUBLICATION', 6);
522
//define('ITEM_TYPE_FORUM', 7);
523
define('ITEM_TYPE_ATTENDANCE', 8);
524
define('ITEM_TYPE_SURVEY', 9);
525
define('ITEM_TYPE_FORUM_THREAD', 10);
526
define('ITEM_TYPE_PORTFOLIO', 11);
527
528
// Course description blocks.
529
define('ADD_BLOCK', 8);
530
531
// one big string with all question types, for the validator in pear/HTML/QuickForm/Rule/QuestionType
532
define(
533
    'QUESTION_TYPES',
534
    UNIQUE_ANSWER.':'.
535
    MULTIPLE_ANSWER.':'.
536
    FILL_IN_BLANKS.':'.
537
    MATCHING.':'.
538
    FREE_ANSWER.':'.
539
    HOT_SPOT.':'.
540
    HOT_SPOT_ORDER.':'.
541
    HOT_SPOT_DELINEATION.':'.
542
    MULTIPLE_ANSWER_COMBINATION.':'.
543
    UNIQUE_ANSWER_NO_OPTION.':'.
544
    MULTIPLE_ANSWER_TRUE_FALSE.':'.
545
    MULTIPLE_ANSWER_COMBINATION_TRUE_FALSE.':'.
546
    ORAL_EXPRESSION.':'.
547
    GLOBAL_MULTIPLE_ANSWER.':'.
548
    MEDIA_QUESTION.':'.
549
    CALCULATED_ANSWER.':'.
550
    UNIQUE_ANSWER_IMAGE.':'.
551
    DRAGGABLE.':'.
552
    MATCHING_DRAGGABLE.':'.
553
    MULTIPLE_ANSWER_TRUE_FALSE_DEGREE_CERTAINTY.':'.
554
    ANNOTATION
555
);
556
557
//Some alias used in the QTI exports
558
define('MCUA', 1);
559
define('TF', 1);
560
define('MCMA', 2);
561
define('FIB', 3);
562
563
// Message
564
define('MESSAGE_STATUS_INVITATION_PENDING', 5);
565
define('MESSAGE_STATUS_INVITATION_ACCEPTED', 6);
566
define('MESSAGE_STATUS_INVITATION_DENIED', 7);
567
define('MESSAGE_STATUS_WALL', 8);
568
569
define('MESSAGE_STATUS_WALL_DELETE', 9);
570
define('MESSAGE_STATUS_WALL_POST', 10);
571
572
define('MESSAGE_STATUS_FORUM', 12);
573
define('MESSAGE_STATUS_PROMOTED', 13);
574
575
// Images
576
define('IMAGE_WALL_SMALL_SIZE', 200);
577
define('IMAGE_WALL_MEDIUM_SIZE', 500);
578
define('IMAGE_WALL_BIG_SIZE', 2000);
579
define('IMAGE_WALL_SMALL', 'small');
580
define('IMAGE_WALL_MEDIUM', 'medium');
581
define('IMAGE_WALL_BIG', 'big');
582
583
// Social PLUGIN PLACES
584
define('SOCIAL_LEFT_PLUGIN', 1);
585
define('SOCIAL_CENTER_PLUGIN', 2);
586
define('SOCIAL_RIGHT_PLUGIN', 3);
587
define('CUT_GROUP_NAME', 50);
588
589
/**
590
 * FormValidator Filter.
591
 */
592
define('NO_HTML', 1);
593
define('STUDENT_HTML', 2);
594
define('TEACHER_HTML', 3);
595
define('STUDENT_HTML_FULLPAGE', 4);
596
define('TEACHER_HTML_FULLPAGE', 5);
597
598
// Timeline
599
define('TIMELINE_STATUS_ACTIVE', '1');
600
define('TIMELINE_STATUS_INACTIVE', '2');
601
602
// Event email template class
603
define('EVENT_EMAIL_TEMPLATE_ACTIVE', 1);
604
define('EVENT_EMAIL_TEMPLATE_INACTIVE', 0);
605
606
// Course home
607
define('SHORTCUTS_HORIZONTAL', 0);
608
define('SHORTCUTS_VERTICAL', 1);
609
610
// Course copy
611
define('FILE_SKIP', 1);
612
define('FILE_RENAME', 2);
613
define('FILE_OVERWRITE', 3);
614
define('UTF8_CONVERT', false); //false by default
615
616
define('DOCUMENT', 'file');
617
define('FOLDER', 'folder');
618
619
define('RESOURCE_ASSET', 'asset');
620
define('RESOURCE_DOCUMENT', 'document');
621
define('RESOURCE_GLOSSARY', 'glossary');
622
define('RESOURCE_EVENT', 'calendar_event');
623
define('RESOURCE_LINK', 'link');
624
define('RESOURCE_COURSEDESCRIPTION', 'course_description');
625
define('RESOURCE_LEARNPATH', 'learnpath');
626
define('RESOURCE_LEARNPATH_CATEGORY', 'learnpath_category');
627
define('RESOURCE_ANNOUNCEMENT', 'announcement');
628
define('RESOURCE_FORUM', 'forum');
629
define('RESOURCE_FORUMTOPIC', 'thread');
630
define('RESOURCE_FORUMPOST', 'post');
631
define('RESOURCE_QUIZ', 'quiz');
632
define('RESOURCE_TEST_CATEGORY', 'test_category');
633
define('RESOURCE_QUIZQUESTION', 'Exercise_Question');
634
define('RESOURCE_TOOL_INTRO', 'Tool introduction');
635
define('RESOURCE_LINKCATEGORY', 'Link_Category');
636
define('RESOURCE_FORUMCATEGORY', 'Forum_Category');
637
define('RESOURCE_SCORM', 'Scorm');
638
define('RESOURCE_SURVEY', 'survey');
639
define('RESOURCE_SURVEYQUESTION', 'survey_question');
640
define('RESOURCE_SURVEYINVITATION', 'survey_invitation');
641
define('RESOURCE_WIKI', 'wiki');
642
define('RESOURCE_THEMATIC', 'thematic');
643
define('RESOURCE_ATTENDANCE', 'attendance');
644
define('RESOURCE_WORK', 'work');
645
define('RESOURCE_SESSION_COURSE', 'session_course');
646
define('RESOURCE_GRADEBOOK', 'gradebook');
647
define('ADD_THEMATIC_PLAN', 6);
648
649
// Max online users to show per page (whoisonline)
650
define('MAX_ONLINE_USERS', 12);
651
652
define('TOOL_AUTHORING', 'toolauthoring');
653
define('TOOL_INTERACTION', 'toolinteraction');
654
define('TOOL_COURSE_PLUGIN', 'toolcourseplugin'); //all plugins that can be enabled in courses
655
define('TOOL_ADMIN', 'tooladmin');
656
define('TOOL_ADMIN_PLATFORM', 'tooladminplatform');
657
define('TOOL_DRH', 'tool_drh');
658
define('TOOL_STUDENT_VIEW', 'toolstudentview');
659
define('TOOL_ADMIN_VISIBLE', 'tooladminvisible');
660
661
// Search settings (from main/inc/lib/search/IndexableChunk.class.php )
662
// some constants to avoid serialize string keys on serialized data array
663
define('SE_COURSE_ID', 0);
664
define('SE_TOOL_ID', 1);
665
define('SE_DATA', 2);
666
define('SE_USER', 3);
667
668
// in some cases we need top differenciate xapian documents of the same tool
669
define('SE_DOCTYPE_EXERCISE_EXERCISE', 0);
670
define('SE_DOCTYPE_EXERCISE_QUESTION', 1);
671
672
// xapian prefixes
673
define('XAPIAN_PREFIX_COURSEID', 'C');
674
define('XAPIAN_PREFIX_TOOLID', 'O');
675
676
// User active field constants
677
define('USER_ACTIVE', 1);
678
define('USER_INACTIVE', 0);
679
define('USER_INACTIVE_AUTOMATIC', -1);
680
define('USER_SOFT_DELETED', -2);
681
682
/**
683
 * Returns a path to a certain resource within Chamilo.
684
 *
685
 * @param string $path A path which type is to be converted. Also, it may be a defined constant for a path.
686
 *
687
 * @return string the requested path or the converted path
688
 *
689
 * Notes about the current behaviour model:
690
 * 1. Windows back-slashes are converted to slashes in the result.
691
 * 2. A semi-absolute web-path is detected by its leading slash. On Linux systems, absolute system paths start with
692
 * a slash too, so an additional check about presence of leading system server base is implemented. For example, the function is
693
 * able to distinguish type difference between /var/www/chamilo/courses/ (SYS) and /chamilo/courses/ (REL).
694
 * 3. The function api_get_path() returns only these three types of paths, which in some sense are absolute. The function has
695
 * no a mechanism for processing relative web/system paths, such as: lesson01.html, ./lesson01.html, ../css/my_styles.css.
696
 * It has not been identified as needed yet.
697
 * 4. Also, resolving the meta-symbols "." and ".." within paths has not been implemented, it is to be identified as needed.
698
 *
699
 * Vchamilo changes : allow using an alternate configuration
700
 * to get vchamilo  instance paths
701
 */
702
function api_get_path($path = '', $configuration = [])
703
{
704
    global $paths;
705
706
    // get proper configuration data if exists
707
    global $_configuration;
708
709
    $emptyConfigurationParam = false;
710
    if (empty($configuration)) {
711
        $configuration = (array) $_configuration;
712
        $emptyConfigurationParam = true;
713
    }
714
715
    $root_sys = Container::getProjectDir();
716
    $root_web = '';
717
    if (isset(Container::$container)) {
718
        $root_web = Container::$container->get('router')->generate(
719
            'index',
720
            [],
721
            UrlGeneratorInterface::ABSOLUTE_URL
722
        );
723
    }
724
725
    /*if (api_get_multiple_access_url()) {
726
        // To avoid that the api_get_access_url() function fails since global.inc.php also calls the main_api.lib.php
727
        if (isset($configuration['access_url']) && !empty($configuration['access_url'])) {
728
            // We look into the DB the function api_get_access_url
729
            $urlInfo = api_get_access_url($configuration['access_url']);
730
            // Avoid default value
731
            $defaultValues = ['http://localhost/', 'https://localhost/'];
732
            if (!empty($urlInfo['url']) && !in_array($urlInfo['url'], $defaultValues)) {
733
                $root_web = 1 == $urlInfo['active'] ? $urlInfo['url'] : $configuration['root_web'];
734
            }
735
        }
736
    }*/
737
738
    $paths = [
739
        WEB_PATH => $root_web,
740
        SYMFONY_SYS_PATH => $root_sys,
741
        SYS_PATH => $root_sys.'public/',
742
        REL_PATH => '',
743
        CONFIGURATION_PATH => 'app/config/',
744
        LIBRARY_PATH => $root_sys.'public/main/inc/lib/',
745
746
        REL_COURSE_PATH => '',
747
        REL_CODE_PATH => '/main/',
748
749
        SYS_CODE_PATH => $root_sys.'public/main/',
750
        SYS_CSS_PATH => $root_sys.'public/build/css/',
751
        SYS_PLUGIN_PATH => $root_sys.'public/plugin/',
752
        SYS_ARCHIVE_PATH => $root_sys.'var/cache/',
753
        SYS_TEST_PATH => $root_sys.'tests/',
754
        SYS_TEMPLATE_PATH => $root_sys.'public/main/template/',
755
        SYS_PUBLIC_PATH => $root_sys.'public/',
756
        SYS_FONTS_PATH => $root_sys.'public/fonts/',
757
758
        WEB_CODE_PATH => $root_web.'main/',
759
        WEB_PLUGIN_ASSET_PATH => $root_web.'plugins/',
760
        WEB_COURSE_PATH => $root_web.'course/',
761
        WEB_IMG_PATH => $root_web.'img/',
762
        WEB_CSS_PATH => $root_web.'build/css/',
763
        WEB_AJAX_PATH => $root_web.'main/inc/ajax/',
764
        WEB_LIBRARY_PATH => $root_web.'main/inc/lib/',
765
        WEB_LIBRARY_JS_PATH => $root_web.'main/inc/lib/javascript/',
766
        WEB_PLUGIN_PATH => $root_web.'plugin/',
767
        WEB_PUBLIC_PATH => $root_web,
768
    ];
769
770
    $root_rel = '';
771
772
    global $virtualChamilo;
773
    if (!empty($virtualChamilo)) {
774
        $paths[SYS_ARCHIVE_PATH] = api_add_trailing_slash($virtualChamilo[SYS_ARCHIVE_PATH]);
775
        //$paths[SYS_UPLOAD_PATH] = api_add_trailing_slash($virtualChamilo[SYS_UPLOAD_PATH]);
776
        //$paths[$root_web][WEB_UPLOAD_PATH] = api_add_trailing_slash($virtualChamilo[WEB_UPLOAD_PATH]);
777
        $paths[WEB_ARCHIVE_PATH] = api_add_trailing_slash($virtualChamilo[WEB_ARCHIVE_PATH]);
778
        //$paths[$root_web][WEB_COURSE_PATH] = api_add_trailing_slash($virtualChamilo[WEB_COURSE_PATH]);
779
780
        // WEB_UPLOAD_PATH should be handle by apache htaccess in the vhost
781
782
        // RewriteEngine On
783
        // RewriteRule /app/upload/(.*)$ http://localhost/other/upload/my-chamilo111-net/$1 [QSA,L]
784
785
        //$paths[$root_web][WEB_UPLOAD_PATH] = api_add_trailing_slash($virtualChamilo[WEB_UPLOAD_PATH]);
786
        //$paths[$root_web][REL_PATH] = $virtualChamilo[REL_PATH];
787
        //$paths[$root_web][REL_COURSE_PATH] = $virtualChamilo[REL_COURSE_PATH];
788
    }
789
790
    $path = trim($path);
791
792
    // Retrieving a common-purpose path.
793
    if (isset($paths[$path])) {
794
        return $paths[$path];
795
    }
796
797
    return false;
798
}
799
800
/**
801
 * Adds to a given path a trailing slash if it is necessary (adds "/" character at the end of the string).
802
 *
803
 * @param string $path the input path
804
 *
805
 * @return string returns the modified path
806
 */
807
function api_add_trailing_slash($path)
808
{
809
    return '/' === substr($path, -1) ? $path : $path.'/';
810
}
811
812
/**
813
 * Removes from a given path the trailing slash if it is necessary (removes "/" character from the end of the string).
814
 *
815
 * @param string $path the input path
816
 *
817
 * @return string returns the modified path
818
 */
819
function api_remove_trailing_slash($path)
820
{
821
    return '/' === substr($path, -1) ? substr($path, 0, -1) : $path;
822
}
823
824
/**
825
 * Checks the RFC 3986 syntax of a given URL.
826
 *
827
 * @param string $url      the URL to be checked
828
 * @param bool   $absolute whether the URL is absolute (beginning with a scheme such as "http:")
829
 *
830
 * @return string|false Returns the URL if it is valid, FALSE otherwise.
831
 *                      This function is an adaptation from the function valid_url(), Drupal CMS.
832
 *
833
 * @see http://drupal.org
834
 * Note: The built-in function filter_var($urs, FILTER_VALIDATE_URL) has a bug for some versions of PHP.
835
 * @see http://bugs.php.net/51192
836
 */
837
function api_valid_url($url, $absolute = false)
838
{
839
    if ($absolute) {
840
        if (preg_match("
841
            /^                                                      # Start at the beginning of the text
842
            (?:ftp|https?|feed):\/\/                                # Look for ftp, http, https or feed schemes
843
            (?:                                                     # Userinfo (optional) which is typically
844
                (?:(?:[\w\.\-\+!$&'\(\)*\+,;=]|%[0-9a-f]{2})+:)*    # a username or a username and password
845
                (?:[\w\.\-\+%!$&'\(\)*\+,;=]|%[0-9a-f]{2})+@        # combination
846
            )?
847
            (?:
848
                (?:[a-z0-9\-\.]|%[0-9a-f]{2})+                      # A domain name or a IPv4 address
849
                |(?:\[(?:[0-9a-f]{0,4}:)*(?:[0-9a-f]{0,4})\])       # or a well formed IPv6 address
850
            )
851
            (?::[0-9]+)?                                            # Server port number (optional)
852
            (?:[\/|\?]
853
                (?:[\w#!:\.\?\+=&@$'~*,;\/\(\)\[\]\-]|%[0-9a-f]{2}) # The path and query (optional)
854
            *)?
855
            $/xi", $url)) {
856
            return $url;
857
        }
858
859
        return false;
860
    } else {
861
        return preg_match("/^(?:[\w#!:\.\?\+=&@$'~*,;\/\(\)\[\]\-]|%[0-9a-f]{2})+$/i", $url) ? $url : false;
862
    }
863
}
864
865
/**
866
 * Checks whether a given string looks roughly like an email address.
867
 *
868
 * @param string $address the e-mail address to be checked
869
 *
870
 * @return mixed returns the e-mail if it is valid, FALSE otherwise
871
 */
872
function api_valid_email($address)
873
{
874
    return filter_var($address, FILTER_VALIDATE_EMAIL);
875
}
876
877
/**
878
 * Function used to protect a course script.
879
 * The function blocks access when
880
 * - there is no $_SESSION["_course"] defined; or
881
 * - $is_allowed_in_course is set to false (this depends on the course
882
 * visibility and user status).
883
 *
884
 * This is only the first proposal, test and improve!
885
 *
886
 * @param bool Option to print headers when displaying error message. Default: false
887
 * @param bool whether session admins should be allowed or not
888
 * @param string $checkTool check if tool is available for users (user, group)
889
 *
890
 * @return bool True if the user has access to the current course or is out of a course context, false otherwise
891
 *
892
 * @todo replace global variable
893
 *
894
 * @author Roan Embrechts
895
 */
896
function api_protect_course_script($print_headers = false, $allow_session_admins = false, string $checkTool = '', $cid = null): bool
897
{
898
    $course_info = api_get_course_info();
899
    if (empty($course_info) && isset($_REQUEST['cid'])) {
900
        $course_info = api_get_course_info_by_id((int) $_REQUEST['cid']);
901
    }
902
903
    if (isset($cid)) {
904
        $course_info = api_get_course_info_by_id($cid);
905
    }
906
907
    if (empty($course_info)) {
908
        api_not_allowed($print_headers);
909
910
        return false;
911
    }
912
913
    if (api_is_drh()) {
914
        return true;
915
    }
916
917
    // Session admin has access to course
918
    $sessionAccess = ('true' === api_get_setting('session.session_admins_access_all_content'));
919
    if ($sessionAccess) {
920
        $allow_session_admins = true;
921
    }
922
923
    if (api_is_platform_admin($allow_session_admins)) {
924
        return true;
925
    }
926
927
    $isAllowedInCourse = api_is_allowed_in_course();
928
    $is_visible = false;
929
    if (isset($course_info) && isset($course_info['visibility'])) {
930
        switch ($course_info['visibility']) {
931
            default:
932
            case Course::CLOSED:
933
                // Completely closed: the course is only accessible to the teachers. - 0
934
                if ($isAllowedInCourse && api_get_user_id() && !api_is_anonymous()) {
935
                    $is_visible = true;
936
                }
937
                break;
938
            case Course::REGISTERED:
939
                // Private - access authorized to course members only - 1
940
                if ($isAllowedInCourse && api_get_user_id() && !api_is_anonymous()) {
941
                    $is_visible = true;
942
                }
943
                break;
944
            case Course::OPEN_PLATFORM:
945
                // Open - access allowed for users registered on the platform - 2
946
                if ($isAllowedInCourse && api_get_user_id() && !api_is_anonymous()) {
947
                    $is_visible = true;
948
                }
949
                break;
950
            case Course::OPEN_WORLD:
951
                //Open - access allowed for the whole world - 3
952
                $is_visible = true;
953
                break;
954
            case Course::HIDDEN:
955
                //Completely closed: the course is only accessible to the teachers. - 0
956
                if (api_is_platform_admin()) {
957
                    $is_visible = true;
958
                }
959
                break;
960
        }
961
962
        //If password is set and user is not registered to the course then the course is not visible
963
        if (false === $isAllowedInCourse &&
964
            isset($course_info['registration_code']) &&
965
            !empty($course_info['registration_code'])
966
        ) {
967
            $is_visible = false;
968
        }
969
    }
970
971
    if (!empty($checkTool)) {
972
        if (!api_is_allowed_to_edit(true, true, true)) {
973
            $toolInfo = api_get_tool_information_by_name($checkTool);
974
            if (!empty($toolInfo) && isset($toolInfo['visibility']) && 0 == $toolInfo['visibility']) {
975
                api_not_allowed(true);
976
977
                return false;
978
            }
979
        }
980
    }
981
982
    // Check session visibility
983
    $session_id = api_get_session_id();
984
985
    if (!empty($session_id)) {
986
        // $isAllowedInCourse was set in local.inc.php
987
        if (!$isAllowedInCourse) {
988
            $is_visible = false;
989
        }
990
        // Check if course is inside session.
991
        if (!SessionManager::relation_session_course_exist($session_id, $course_info['real_id'])) {
992
            $is_visible = false;
993
        }
994
    }
995
996
    if (!$is_visible) {
997
        api_not_allowed($print_headers);
998
999
        return false;
1000
    }
1001
1002
    $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

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

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

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

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

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

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

3443
    $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...
3444
        $sessionId,
3445
        null,
3446
        false
3447
    );
3448
3449
    if (SESSION_VISIBLE != $visibility && !empty($courseList)) {
3450
        // Course Coach session visibility.
3451
        $blockedCourseCount = 0;
3452
        $closedVisibilityList = [
3453
            COURSE_VISIBILITY_CLOSED,
3454
            COURSE_VISIBILITY_HIDDEN,
3455
        ];
3456
3457
        foreach ($courseList as $course) {
3458
            // Checking session visibility
3459
            $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

3459
            $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...
3460
                $sessionId,
3461
                $course['real_id']
3462
            );
3463
3464
            $courseIsVisible = !in_array(
3465
                $course['visibility'],
3466
                $closedVisibilityList
3467
            );
3468
            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

3468
            if (false === $courseIsVisible || /** @scrutinizer ignore-deprecated */ SESSION_INVISIBLE == $sessionCourseVisibility) {
Loading history...
3469
                $blockedCourseCount++;
3470
            }
3471
        }
3472
3473
        // If all courses are blocked then no show in the list.
3474
        if ($blockedCourseCount === count($courseList)) {
3475
            $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

3475
            $visibility = /** @scrutinizer ignore-deprecated */ SESSION_INVISIBLE;
Loading history...
3476
        } else {
3477
            $visibility = SESSION_VISIBLE;
3478
        }
3479
    }
3480
3481
    switch ($visibility) {
3482
        case SESSION_VISIBLE_READ_ONLY:
3483
        case SESSION_VISIBLE:
3484
        case SESSION_AVAILABLE:
3485
            return true;
3486
            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...
3487
        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

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

3517
            $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...
3518
            // if 5 the session is still available
3519
            switch ($session_visibility) {
3520
                case SESSION_VISIBLE_READ_ONLY: // 1
3521
                    return false;
3522
                case SESSION_VISIBLE:           // 2
3523
                    return true;
3524
                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

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