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

1014
    /** @scrutinizer ignore-call */ 
1015
    $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...
1015
1016
    if ($pluginHelper->isPluginEnabled('Positioning')) {
1017
        $plugin = $pluginHelper->loadLegacyPlugin('Positioning');
1018
1019
        if ($plugin && $plugin->get('block_course_if_initial_exercise_not_attempted') === 'true') {
1020
            $currentPath = $_SERVER['REQUEST_URI'];
1021
1022
            $allowedPatterns = [
1023
                '#^/course/\d+/home#',
1024
                '#^/plugin/Positioning/#',
1025
                '#^/main/course_home/#',
1026
                '#^/main/exercise/#',
1027
                '#^/main/inc/ajax/exercise.ajax.php#',
1028
            ];
1029
1030
            $isWhitelisted = false;
1031
            foreach ($allowedPatterns as $pattern) {
1032
                if (preg_match($pattern, $currentPath)) {
1033
                    $isWhitelisted = true;
1034
                    break;
1035
                }
1036
            }
1037
1038
            if (!$isWhitelisted) {
1039
                $initialData = $plugin->getInitialExercise($course_info['real_id'], $session_id);
1040
1041
                if (!empty($initialData['exercise_id'])) {
1042
                    $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

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

2564
        return /** @scrutinizer ignore-deprecated */ SESSION_INVISIBLE;
Loading history...
2565
    }
2566
2567
    $row = Database::fetch_assoc($result);
2568
    $visibility = $row['visibility'];
2569
2570
    // I don't care the session visibility.
2571
    if (empty($row['access_start_date']) && empty($row['access_end_date'])) {
2572
        // Session duration per student.
2573
        if (isset($row['duration']) && !empty($row['duration'])) {
2574
            $duration = $row['duration'] * 24 * 60 * 60;
2575
            $courseAccess = CourseManager::getFirstCourseAccessPerSessionAndUser($session_id, $userId);
2576
2577
            // If there is a session duration but there is no previous
2578
            // access by the user, then the session is still available
2579
            if (0 == count($courseAccess)) {
2580
                return SESSION_AVAILABLE;
2581
            }
2582
2583
            $currentTime = time();
2584
            $firstAccess = isset($courseAccess['login_course_date'])
2585
                ? api_strtotime($courseAccess['login_course_date'], 'UTC')
2586
                : 0;
2587
            $userDurationData = SessionManager::getUserSession($userId, $session_id);
2588
            $userDuration = isset($userDurationData['duration'])
2589
                ? (intval($userDurationData['duration']) * 24 * 60 * 60)
2590
                : 0;
2591
2592
            $totalDuration = $firstAccess + $duration + $userDuration;
2593
2594
            return $totalDuration > $currentTime ? SESSION_AVAILABLE : SESSION_VISIBLE_READ_ONLY;
2595
        }
2596
2597
        return SESSION_AVAILABLE;
2598
    }
2599
2600
    // If start date was set.
2601
    if (!empty($row['access_start_date'])) {
2602
        $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

2602
        $visibility = $now > api_strtotime($row['access_start_date'], 'UTC') ? SESSION_AVAILABLE : /** @scrutinizer ignore-deprecated */ SESSION_INVISIBLE;
Loading history...
2603
    } else {
2604
        // If there's no start date, assume it's available until the end date
2605
        $visibility = SESSION_AVAILABLE;
2606
    }
2607
2608
    // If the end date was set.
2609
    if (!empty($row['access_end_date'])) {
2610
        // Only if date_start said that it was ok
2611
        if (SESSION_AVAILABLE === $visibility) {
2612
            $visibility = $now < api_strtotime($row['access_end_date'], 'UTC')
2613
                ? SESSION_AVAILABLE // Date still available
2614
                : $row['visibility']; // Session ends
2615
        }
2616
    }
2617
2618
    // If I'm a coach the visibility can change in my favor depending in the coach dates.
2619
    $isCoach = api_is_coach($session_id, $courseId);
2620
2621
    if ($isCoach) {
2622
        // Test start date.
2623
        if (!empty($row['coach_access_start_date'])) {
2624
            $start = api_strtotime($row['coach_access_start_date'], 'UTC');
2625
            $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

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

3345
    $sessionVisibility = /** @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...
3346
    $studentView = api_is_student_view_active();
3347
    $isAllowed = false;
3348
3349
    // If platform admin, allow unless student view is active
3350
    if (api_is_platform_admin($allowSessionAdminEdit)) {
3351
        if ($check_student_view && $studentView) {
3352
            $isAllowed = false;
3353
        } else {
3354
            return true;
3355
        }
3356
    }
3357
3358
    // Respect session course read-only mode from extra field
3359
    if ($sessionId && 'true' === api_get_setting('session.session_courses_read_only_mode')) {
3360
        $efv = new ExtraFieldValue('course');
3361
        $lock = $efv->get_values_by_handler_and_field_variable(
3362
            api_get_course_int_id(),
3363
            'session_courses_read_only_mode'
3364
        );
3365
        if (!empty($lock['value'])) {
3366
            return false;
3367
        }
3368
    }
3369
3370
    // ---------------------------------------------------------------------
3371
    // Explicit student subscription guard (no session context).
3372
    // If the user is subscribed as a learner in the course, do NOT grant edit
3373
    // rights even if "current course teacher" roles are polluted/persisted.
3374
    // ---------------------------------------------------------------------
3375
    $courseCode = api_get_course_id();
3376
    $inCourse = !empty($courseCode) && $courseCode != -1;
3377
3378
    if ($inCourse && empty($sessionId)) {
3379
        if (api_is_explicit_course_student(api_get_user_id(), api_get_course_int_id())) {
3380
            return false;
3381
        }
3382
    }
3383
3384
    $isCourseAdmin = api_is_course_admin();
3385
    $isCoach = api_is_coach(0, null, $check_student_view);
3386
3387
    if (!$isCourseAdmin && $tutor) {
3388
        $isCourseAdmin = api_is_course_tutor();
3389
    }
3390
3391
    if (!$isCourseAdmin && $coach) {
3392
        if (SESSION_VISIBLE_READ_ONLY == $sessionVisibility) {
3393
            $isCoach = false;
3394
        }
3395
        if ('true' === api_get_setting('allow_coach_to_edit_course_session')) {
3396
            $isCourseAdmin = $isCoach;
3397
        }
3398
    }
3399
3400
    if (!$isCourseAdmin && $session_coach) {
3401
        $isCourseAdmin = $isCoach;
3402
    }
3403
3404
    // Handle student view mode
3405
    if ('true' === api_get_setting('student_view_enabled')) {
3406
        if (!empty($sessionId)) {
3407
            if (SESSION_VISIBLE_READ_ONLY == $sessionVisibility) {
3408
                $isCoach = false;
3409
            }
3410
            if ('true' === api_get_setting('allow_coach_to_edit_course_session')) {
3411
                $isAllowed = $isCoach;
3412
            }
3413
3414
            if ($check_student_view) {
3415
                $isAllowed = $isAllowed && !$studentView;
3416
            }
3417
        } else {
3418
            $isAllowed = $isCourseAdmin;
3419
            if ($check_student_view) {
3420
                $isAllowed = $isCourseAdmin && !$studentView;
3421
            }
3422
        }
3423
3424
        if ($isAllowed) {
3425
            return true;
3426
        }
3427
    } else {
3428
        if ($isCourseAdmin) {
3429
            return true;
3430
        }
3431
    }
3432
3433
    // Final fallback: permission-based system (only if nothing before returned true)
3434
    $courseId = api_get_course_id();
3435
    $inCourse = !empty($courseId) && $courseId != -1;
3436
3437
    if (!$inCourse) {
3438
        $userRoles = api_get_user_roles();
3439
        $feature = api_detect_feature_context();
3440
        $permission = $feature.':edit';
3441
3442
        return api_get_permission($permission, $userRoles);
3443
    }
3444
3445
    return $isAllowed;
3446
}
3447
3448
/**
3449
 * UI/legacy safeguard: returns true if the user is explicitly subscribed as STUDENT
3450
 * in the current course (course_rel_user), regardless of Symfony/serialized roles.
3451
 *
3452
 * This is intentionally a low-level check to avoid polluted context roles.
3453
 */
3454
function api_is_explicit_course_student(?int $userId = null, ?int $courseIntId = null): bool
3455
{
3456
    $userId = $userId ?? api_get_user_id();
3457
    $courseIntId = $courseIntId ?? api_get_course_int_id();
3458
3459
    if (empty($userId) || empty($courseIntId)) {
3460
        return false;
3461
    }
3462
3463
    $studentStatus = defined('STUDENT') ? (int) STUDENT : 5;
3464
    $table = Database::get_main_table(TABLE_MAIN_COURSE_USER);
3465
    $sql = "SELECT status
3466
            FROM $table
3467
            WHERE c_id = ".((int) $courseIntId)."
3468
              AND user_id = ".((int) $userId)."
3469
            LIMIT 1";
3470
3471
    $res = Database::query($sql);
3472
    $row = Database::fetch_array($res, 'ASSOC');
3473
3474
    return !empty($row) && (int) $row['status'] === $studentStatus;
3475
}
3476
3477
/**
3478
 * Returns the current main feature (module) based on the current script path.
3479
 * Used to determine permissions for non-course tools.
3480
 */
3481
function api_detect_feature_context(): string
3482
{
3483
    $script = $_SERVER['SCRIPT_NAME'] ?? '';
3484
    $script = basename($script);
3485
3486
    $map = [
3487
        'user_list.php' => 'user',
3488
        'user_add.php' => 'user',
3489
        'user_edit.php' => 'user',
3490
        'session_list.php' => 'session',
3491
        'session_add.php' => 'session',
3492
        'session_edit.php' => 'session',
3493
        'skill_list.php' => 'skill',
3494
        'skill_edit.php' => 'skill',
3495
        'badge_list.php' => 'badge',
3496
        'settings.php' => 'settings',
3497
        'course_list.php' => 'course',
3498
    ];
3499
3500
    if (isset($map[$script])) {
3501
        return $map[$script];
3502
    }
3503
3504
    if (preg_match('#/main/([a-z_]+)/#i', $_SERVER['SCRIPT_NAME'], $matches)) {
3505
        return $matches[1];
3506
    }
3507
3508
    return 'unknown';
3509
}
3510
3511
/**
3512
 * Returns true if user is a course coach of at least one course in session.
3513
 *
3514
 * @param int $sessionId
3515
 *
3516
 * @return bool
3517
 */
3518
function api_is_coach_of_course_in_session($sessionId)
3519
{
3520
    if (api_is_platform_admin()) {
3521
        return true;
3522
    }
3523
3524
    $userId = api_get_user_id();
3525
    $courseList = UserManager::get_courses_list_by_session(
3526
        $userId,
3527
        $sessionId
3528
    );
3529
3530
    // Session visibility.
3531
    $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

3531
    $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...
3532
        $sessionId,
3533
        null,
3534
        false
3535
    );
3536
3537
    if (SESSION_VISIBLE != $visibility && !empty($courseList)) {
3538
        // Course Coach session visibility.
3539
        $blockedCourseCount = 0;
3540
        $closedVisibilityList = [
3541
            COURSE_VISIBILITY_CLOSED,
3542
            COURSE_VISIBILITY_HIDDEN,
3543
        ];
3544
3545
        foreach ($courseList as $course) {
3546
            // Checking session visibility
3547
            $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

3547
            $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...
3548
                $sessionId,
3549
                $course['real_id']
3550
            );
3551
3552
            $courseIsVisible = !in_array(
3553
                $course['visibility'],
3554
                $closedVisibilityList
3555
            );
3556
            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

3556
            if (false === $courseIsVisible || /** @scrutinizer ignore-deprecated */ SESSION_INVISIBLE == $sessionCourseVisibility) {
Loading history...
3557
                $blockedCourseCount++;
3558
            }
3559
        }
3560
3561
        // If all courses are blocked then no show in the list.
3562
        if ($blockedCourseCount === count($courseList)) {
3563
            $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

3563
            $visibility = /** @scrutinizer ignore-deprecated */ SESSION_INVISIBLE;
Loading history...
3564
        } else {
3565
            $visibility = SESSION_VISIBLE;
3566
        }
3567
    }
3568
3569
    switch ($visibility) {
3570
        case SESSION_VISIBLE_READ_ONLY:
3571
        case SESSION_VISIBLE:
3572
        case SESSION_AVAILABLE:
3573
            return true;
3574
            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...
3575
        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

3575
        case /** @scrutinizer ignore-deprecated */ SESSION_INVISIBLE:
Loading history...
3576
            return false;
3577
    }
3578
3579
    return false;
3580
}
3581
3582
/**
3583
 * Checks if a student can edit contents in a session depending
3584
 * on the session visibility.
3585
 *
3586
 * @param bool $tutor Whether to check if the user has the tutor role
3587
 * @param bool $coach Whether to check if the user has the coach role
3588
 *
3589
 * @return bool true: the user has the rights to edit, false: he does not
3590
 */
3591
function api_is_allowed_to_session_edit($tutor = false, $coach = false)
3592
{
3593
    if (api_is_allowed_to_edit($tutor, $coach)) {
3594
        // If I'm a teacher, I will return true in order to not affect the normal behaviour of Chamilo tools.
3595
        return true;
3596
    } else {
3597
        $sessionId = api_get_session_id();
3598
3599
        if (0 == $sessionId) {
3600
            // I'm not in a session so i will return true to not affect the normal behaviour of Chamilo tools.
3601
            return true;
3602
        } else {
3603
            // I'm in a session and I'm a student
3604
            // Get the session visibility
3605
            $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

3605
            $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...
3606
            // if 5 the session is still available
3607
            switch ($session_visibility) {
3608
                case SESSION_VISIBLE_READ_ONLY: // 1
3609
                    return false;
3610
                case SESSION_VISIBLE:           // 2
3611
                    return true;
3612
                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

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

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

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

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

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
7598
        try {
7599
            $courseEntity = Container::getCourseRepository()->find($courseId);
7600
7601
            if ($courseEntity && $courseEntity->getResourceNode()) {
7602
                $resourceNodeParentId = (int) $courseEntity->getResourceNode()->getId();
7603
            }
7604
        } catch (\Throwable $exception) {
7605
            error_log('[Glossary] Failed to resolve resourceNodeParentId from course: '.$exception->getMessage());
7606
        }
7607
    }
7608
7609
    $course  = $courseId ?: 'null';
7610
    $session = $sessionId ?: 'null';
7611
    $parent  = $resourceNodeParentId ?: 'null';
7612
7613
    return '
7614
        <script>
7615
          window.chamiloGlossaryConfig = {
7616
            courseId: ' . $course . ',
7617
            sessionId: ' . $session . ',
7618
            resourceNodeParentId: ' . $parent . ',
7619
            termsEndpoint: "/api/glossaries"
7620
          };
7621
        </script>
7622
        ' . api_get_build_js("glossary_auto.js") . '
7623
    ';
7624
}
7625
7626
7627