api_is_allowed_to_edit()   F
last analyzed

Complexity

Conditions 26
Paths 2019

Size

Total Lines 84
Code Lines 42

Duplication

Lines 0
Ratio 0 %

Importance

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

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

1001
    /** @scrutinizer ignore-call */ 
1002
    $pluginHelper = Container::$container->get(PluginServiceHelper::class);

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

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

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

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

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

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

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

Loading history...
1030
                        api_get_user_id(),
1031
                        (int) $initialData['exercise_id'],
1032
                        $course_info['real_id'],
1033
                        $session_id
1034
                    );
1035
1036
                    if (empty($results)) {
1037
                        api_not_allowed($print_headers);
1038
                        return false;
1039
                    }
1040
                }
1041
            }
1042
        }
1043
    }
1044
1045
    api_block_inactive_user();
1046
1047
    return true;
1048
}
1049
1050
/**
1051
 * Function used to protect an admin script.
1052
 *
1053
 * The function blocks access when the user has no platform admin rights
1054
 * with an error message printed on default output
1055
 *
1056
 * @param bool Whether to allow session admins as well
1057
 * @param bool Whether to allow HR directors as well
1058
 * @param string An optional message (already passed through get_lang)
1059
 *
1060
 * @return bool True if user is allowed, false otherwise.
1061
 *              The function also outputs an error message in case not allowed
1062
 *
1063
 * @author Roan Embrechts (original author)
1064
 */
1065
function api_protect_admin_script($allow_sessions_admins = false, $allow_drh = false, $message = null)
1066
{
1067
    if (!api_is_platform_admin($allow_sessions_admins, $allow_drh)) {
1068
        api_not_allowed(true, $message);
1069
1070
        return false;
1071
    }
1072
    api_block_inactive_user();
1073
1074
    return true;
1075
}
1076
1077
/**
1078
 * Blocks inactive users with a currently active session from accessing more pages "live".
1079
 *
1080
 * @return bool Returns true if the feature is disabled or the user account is still enabled.
1081
 *              Returns false (and shows a message) if the feature is enabled *and* the user is disabled.
1082
 */
1083
function api_block_inactive_user()
1084
{
1085
    $data = true;
1086
    if ('true' !== api_get_setting('security.security_block_inactive_users_immediately')) {
1087
        return $data;
1088
    }
1089
1090
    $userId = api_get_user_id();
1091
    $homeUrl = api_get_path(WEB_PATH);
1092
    if (0 == $userId) {
1093
        return $data;
1094
    }
1095
1096
    $sql = "SELECT active FROM ".Database::get_main_table(TABLE_MAIN_USER)."
1097
            WHERE id = $userId";
1098
1099
    $result = Database::query($sql);
1100
    if (Database::num_rows($result) > 0) {
1101
        $result_array = Database::fetch_array($result);
1102
        $data = (bool) $result_array['active'];
1103
    }
1104
    if (false == $data) {
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like you are loosely comparing two booleans. Considering using the strict comparison === instead.

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

Loading history...
1105
        $tpl = new Template(null, true, true, false, true, false, true, 0);
1106
        $tpl->assign('hide_login_link', 1);
1107
1108
        //api_not_allowed(true, get_lang('Account inactive'));
1109
        // we were not in a course, return to home page
1110
        $msg = Display::return_message(
1111
            get_lang('Account inactive'),
1112
            'error',
1113
            false
1114
        );
1115
1116
        $msg .= '<p class="text-center">
1117
                 <a class="btn btn--plain" href="'.$homeUrl.'">'.get_lang('Back to Home Page.').'</a></p>';
1118
1119
        $tpl->assign('content', $msg);
1120
        $tpl->display_one_col_template();
1121
        exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

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

Loading history...
1122
    }
1123
1124
    return $data;
1125
}
1126
1127
/**
1128
 * Function used to protect a teacher script.
1129
 * The function blocks access when the user has no teacher rights.
1130
 *
1131
 * @return bool True if the current user can access the script, false otherwise
1132
 *
1133
 * @author Yoselyn Castillo
1134
 */
1135
function api_protect_teacher_script()
1136
{
1137
    if (!api_is_allowed_to_edit()) {
1138
        api_not_allowed(true);
1139
1140
        return false;
1141
    }
1142
1143
    return true;
1144
}
1145
1146
/**
1147
 * Function used to prevent anonymous users from accessing a script.
1148
 *
1149
 * @param bool $printHeaders
1150
 *
1151
 * @return bool
1152
 */
1153
function api_block_anonymous_users($printHeaders = true)
1154
{
1155
    $isAuth = Container::getAuthorizationChecker()->isGranted('IS_AUTHENTICATED');
1156
1157
    if (false === $isAuth) {
1158
        api_not_allowed($printHeaders);
1159
1160
        return false;
1161
    }
1162
1163
    api_block_inactive_user();
1164
1165
    return true;
1166
}
1167
1168
/**
1169
 * Returns a rough evaluation of the browser's name and version based on very
1170
 * simple regexp.
1171
 *
1172
 * @return array with the navigator name and version ['name' => '...', 'version' => '...']
1173
 */
1174
function api_get_navigator()
1175
{
1176
    $navigator = 'Unknown';
1177
    $version = 0;
1178
1179
    if (!isset($_SERVER['HTTP_USER_AGENT'])) {
1180
        return ['name' => 'Unknown', 'version' => '0.0.0'];
1181
    }
1182
1183
    if (false !== strpos($_SERVER['HTTP_USER_AGENT'], 'Opera')) {
1184
        $navigator = 'Opera';
1185
        [, $version] = explode('Opera', $_SERVER['HTTP_USER_AGENT']);
1186
    } elseif (false !== strpos($_SERVER['HTTP_USER_AGENT'], 'Edge')) {
1187
        $navigator = 'Edge';
1188
        [, $version] = explode('Edge', $_SERVER['HTTP_USER_AGENT']);
1189
    } elseif (false !== strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE')) {
1190
        $navigator = 'Internet Explorer';
1191
        [, $version] = explode('MSIE ', $_SERVER['HTTP_USER_AGENT']);
1192
    } elseif (false !== strpos($_SERVER['HTTP_USER_AGENT'], 'Chrome')) {
1193
        $navigator = 'Chrome';
1194
        [, $version] = explode('Chrome', $_SERVER['HTTP_USER_AGENT']);
1195
    } elseif (false !== stripos($_SERVER['HTTP_USER_AGENT'], 'Safari')) {
1196
        $navigator = 'Safari';
1197
        if (false !== stripos($_SERVER['HTTP_USER_AGENT'], 'Version/')) {
1198
            // If this Safari does have the "Version/" string in its user agent
1199
            // then use that as a version indicator rather than what's after
1200
            // "Safari/" which is rather a "build number" or something
1201
            [, $version] = explode('Version/', $_SERVER['HTTP_USER_AGENT']);
1202
        } else {
1203
            [, $version] = explode('Safari/', $_SERVER['HTTP_USER_AGENT']);
1204
        }
1205
    } elseif (false !== strpos($_SERVER['HTTP_USER_AGENT'], 'Firefox')) {
1206
        $navigator = 'Firefox';
1207
        [, $version] = explode('Firefox', $_SERVER['HTTP_USER_AGENT']);
1208
    } elseif (false !== strpos($_SERVER['HTTP_USER_AGENT'], 'Netscape')) {
1209
        $navigator = 'Netscape';
1210
        if (false !== stripos($_SERVER['HTTP_USER_AGENT'], 'Netscape/')) {
1211
            [, $version] = explode('Netscape', $_SERVER['HTTP_USER_AGENT']);
1212
        } else {
1213
            [, $version] = explode('Navigator', $_SERVER['HTTP_USER_AGENT']);
1214
        }
1215
    } elseif (false !== strpos($_SERVER['HTTP_USER_AGENT'], 'Konqueror')) {
1216
        $navigator = 'Konqueror';
1217
        [, $version] = explode('Konqueror', $_SERVER['HTTP_USER_AGENT']);
1218
    } elseif (false !== stripos($_SERVER['HTTP_USER_AGENT'], 'applewebkit')) {
1219
        $navigator = 'AppleWebKit';
1220
        [, $version] = explode('Version/', $_SERVER['HTTP_USER_AGENT']);
1221
    } elseif (false !== strpos($_SERVER['HTTP_USER_AGENT'], 'Gecko')) {
1222
        $navigator = 'Mozilla';
1223
        [, $version] = explode('; rv:', $_SERVER['HTTP_USER_AGENT']);
1224
    }
1225
1226
    // Now cut extra stuff around (mostly *after*) the version number
1227
    $version = preg_replace('/^([\/\s])?([\d\.]+)?.*/', '\2', $version);
1228
1229
    if (false === strpos($version, '.')) {
1230
        $version = number_format(doubleval($version), 1);
1231
    }
1232
1233
    return ['name' => $navigator, 'version' => $version];
1234
}
1235
1236
/**
1237
 * This function returns the id of the user which is stored in the $_user array.
1238
 *
1239
 * example: The function can be used to check if a user is logged in
1240
 *          if (api_get_user_id())
1241
 *
1242
 * @return int the id of the current user, 0 if is empty
1243
 */
1244
function api_get_user_id()
1245
{
1246
    $userInfo = Session::read('_user');
1247
    if ($userInfo && isset($userInfo['user_id'])) {
1248
        return (int) $userInfo['user_id'];
1249
    }
1250
1251
    return 0;
1252
}
1253
1254
/**
1255
 * Formats user information into a standard array
1256
 * This function should be only used inside api_get_user_info().
1257
 *
1258
 * @param array Non-standard user array
0 ignored issues
show
Documentation Bug introduced by
The doc comment Non-standard at position 0 could not be parsed: Unknown type name 'Non-standard' at position 0 in Non-standard.
Loading history...
1259
 * @param bool $add_password
1260
 * @param bool $loadAvatars  turn off to improve performance
1261
 *
1262
 * @return array Standard user array
1263
 */
1264
function _api_format_user($user, $add_password = false, $loadAvatars = true)
1265
{
1266
    $result = [];
1267
1268
    if (!isset($user['id'])) {
1269
        return [];
1270
    }
1271
1272
    $result['firstname'] = null;
1273
    $result['lastname'] = null;
1274
1275
    if (isset($user['firstname']) && isset($user['lastname'])) {
1276
        // with only lowercase
1277
        $result['firstname'] = $user['firstname'];
1278
        $result['lastname'] = $user['lastname'];
1279
    } elseif (isset($user['firstName']) && isset($user['lastName'])) {
1280
        // with uppercase letters
1281
        $result['firstname'] = isset($user['firstName']) ? $user['firstName'] : null;
1282
        $result['lastname'] = isset($user['lastName']) ? $user['lastName'] : null;
1283
    }
1284
1285
    if (isset($user['email'])) {
1286
        $result['mail'] = isset($user['email']) ? $user['email'] : null;
1287
        $result['email'] = isset($user['email']) ? $user['email'] : null;
1288
    } else {
1289
        $result['mail'] = isset($user['mail']) ? $user['mail'] : null;
1290
        $result['email'] = isset($user['mail']) ? $user['mail'] : null;
1291
    }
1292
1293
    $result['complete_name'] = api_get_person_name($result['firstname'], $result['lastname']);
1294
    $result['complete_name_with_username'] = $result['complete_name'];
1295
1296
    if (!empty($user['username']) && 'false' === api_get_setting('profile.hide_username_with_complete_name')) {
1297
        $result['complete_name_with_username'] = $result['complete_name'].' ('.$user['username'].')';
1298
    }
1299
1300
    $showEmail = 'true' === api_get_setting('show_email_addresses');
1301
    if (!empty($user['email'])) {
1302
        $result['complete_name_with_email_forced'] = $result['complete_name'].' ('.$user['email'].')';
1303
        if ($showEmail) {
1304
            $result['complete_name_with_email'] = $result['complete_name'].' ('.$user['email'].')';
1305
        }
1306
    } else {
1307
        $result['complete_name_with_email'] = $result['complete_name'];
1308
        $result['complete_name_with_email_forced'] = $result['complete_name'];
1309
    }
1310
1311
    // Kept for historical reasons
1312
    $result['firstName'] = $result['firstname'];
1313
    $result['lastName'] = $result['lastname'];
1314
1315
    $attributes = [
1316
        'phone',
1317
        'address',
1318
        'picture_uri',
1319
        'official_code',
1320
        'status',
1321
        'active',
1322
        'auth_sources',
1323
        'username',
1324
        'theme',
1325
        'language',
1326
        'locale',
1327
        'creator_id',
1328
        'created_at',
1329
        'hr_dept_id',
1330
        'expiration_date',
1331
        'last_login',
1332
        'user_is_online',
1333
        'profile_completed',
1334
    ];
1335
1336
    if ('true' === api_get_setting('extended_profile')) {
1337
        $attributes[] = 'competences';
1338
        $attributes[] = 'diplomas';
1339
        $attributes[] = 'teach';
1340
        $attributes[] = 'openarea';
1341
    }
1342
1343
    foreach ($attributes as $attribute) {
1344
        $result[$attribute] = $user[$attribute] ?? null;
1345
    }
1346
1347
    $user_id = (int) $user['id'];
1348
    // Maintain the user_id index for backwards compatibility
1349
    $result['user_id'] = $result['id'] = $user_id;
1350
1351
    $hasCertificates = Certificate::getCertificateByUser($user_id);
1352
    $result['has_certificates'] = 0;
1353
    if (!empty($hasCertificates)) {
1354
        $result['has_certificates'] = 1;
1355
    }
1356
1357
    $result['icon_status'] = '';
1358
    $result['icon_status_medium'] = '';
1359
    $result['is_admin'] = UserManager::is_admin($user_id);
1360
1361
    // Getting user avatar.
1362
    if ($loadAvatars) {
1363
        $result['avatar'] = '';
1364
        $result['avatar_no_query'] = '';
1365
        $result['avatar_small'] = '';
1366
        $result['avatar_medium'] = '';
1367
1368
        if (empty($user['avatar'])) {
1369
            $originalFile = UserManager::getUserPicture(
1370
                $user_id,
1371
                USER_IMAGE_SIZE_ORIGINAL,
1372
                null,
1373
                $result
1374
            );
1375
            $result['avatar'] = $originalFile;
1376
            $avatarString = explode('?', $result['avatar']);
1377
            $result['avatar_no_query'] = reset($avatarString);
1378
        } else {
1379
            $result['avatar'] = $user['avatar'];
1380
            $avatarString = explode('?', $user['avatar']);
1381
            $result['avatar_no_query'] = reset($avatarString);
1382
        }
1383
1384
        if (!isset($user['avatar_small'])) {
1385
            $smallFile = UserManager::getUserPicture(
1386
                $user_id,
1387
                USER_IMAGE_SIZE_SMALL,
1388
                null,
1389
                $result
1390
            );
1391
            $result['avatar_small'] = $smallFile;
1392
        } else {
1393
            $result['avatar_small'] = $user['avatar_small'];
1394
        }
1395
1396
        if (!isset($user['avatar_medium'])) {
1397
            $mediumFile = UserManager::getUserPicture(
1398
                $user_id,
1399
                USER_IMAGE_SIZE_MEDIUM,
1400
                null,
1401
                $result
1402
            );
1403
            $result['avatar_medium'] = $mediumFile;
1404
        } else {
1405
            $result['avatar_medium'] = $user['avatar_medium'];
1406
        }
1407
1408
        $urlImg = api_get_path(WEB_IMG_PATH);
1409
        $iconStatus = '';
1410
        $iconStatusMedium = '';
1411
        $label = '';
1412
1413
        switch ($result['status']) {
1414
            case STUDENT:
1415
                if ($result['has_certificates']) {
1416
                    $iconStatus = $urlImg.'icons/svg/identifier_graduated.svg';
1417
                    $label = get_lang('Graduated');
1418
                } else {
1419
                    $iconStatus = $urlImg.'icons/svg/identifier_student.svg';
1420
                    $label = get_lang('Student');
1421
                }
1422
                break;
1423
            case COURSEMANAGER:
1424
                if ($result['is_admin']) {
1425
                    $iconStatus = $urlImg.'icons/svg/identifier_admin.svg';
1426
                    $label = get_lang('Admin');
1427
                } else {
1428
                    $iconStatus = $urlImg.'icons/svg/identifier_teacher.svg';
1429
                    $label = get_lang('Teacher');
1430
                }
1431
                break;
1432
            case STUDENT_BOSS:
1433
                $iconStatus = $urlImg.'icons/svg/identifier_teacher.svg';
1434
                $label = get_lang('StudentBoss');
1435
                break;
1436
        }
1437
1438
        if (!empty($iconStatus)) {
1439
            $iconStatusMedium = '<img src="'.$iconStatus.'" width="32px" height="32px">';
1440
            $iconStatus = '<img src="'.$iconStatus.'" width="22px" height="22px">';
1441
        }
1442
1443
        $result['icon_status'] = $iconStatus;
1444
        $result['icon_status_label'] = $label;
1445
        $result['icon_status_medium'] = $iconStatusMedium;
1446
    }
1447
1448
    if (isset($user['user_is_online'])) {
1449
        $result['user_is_online'] = true == $user['user_is_online'] ? 1 : 0;
1450
    }
1451
    if (isset($user['user_is_online_in_chat'])) {
1452
        $result['user_is_online_in_chat'] = (int) $user['user_is_online_in_chat'];
1453
    }
1454
1455
    if ($add_password) {
1456
        $result['password'] = $user['password'];
1457
    }
1458
1459
    if (isset($result['profile_completed'])) {
1460
        $result['profile_completed'] = $user['profile_completed'];
1461
    }
1462
1463
    $result['profile_url'] = api_get_path(WEB_CODE_PATH).'social/profile.php?u='.$user_id;
1464
1465
    // Send message link
1466
    $sendMessage = api_get_path(WEB_AJAX_PATH).'user_manager.ajax.php?a=get_user_popup&user_id='.$user_id;
1467
    $result['complete_name_with_message_link'] = Display::url(
1468
        $result['complete_name_with_username'],
1469
        $sendMessage,
1470
        ['class' => 'ajax']
1471
    );
1472
1473
    if (isset($user['extra'])) {
1474
        $result['extra'] = $user['extra'];
1475
    }
1476
1477
    return $result;
1478
}
1479
1480
/**
1481
 * Finds all the information about a user.
1482
 * If no parameter is passed you find all the information about the current user.
1483
 *
1484
 * @param int  $user_id
1485
 * @param bool $checkIfUserOnline
1486
 * @param bool $showPassword
1487
 * @param bool $loadExtraData
1488
 * @param bool $loadOnlyVisibleExtraData Get the user extra fields that are visible
1489
 * @param bool $loadAvatars              turn off to improve performance and if avatars are not needed
1490
 * @param bool $updateCache              update apc cache if exists
1491
 *
1492
 * @return mixed $user_info user_id, lastname, firstname, username, email, etc or false on error
1493
 *
1494
 * @author Patrick Cool <[email protected]>
1495
 * @author Julio Montoya
1496
 *
1497
 * @version 21 September 2004
1498
 */
1499
function api_get_user_info(
1500
    $user_id = 0,
1501
    $checkIfUserOnline = false,
1502
    $showPassword = false,
1503
    $loadExtraData = false,
1504
    $loadOnlyVisibleExtraData = false,
1505
    $loadAvatars = true,
1506
    $updateCache = false
1507
) {
1508
    // Make sure user_id is safe
1509
    $user_id = (int) $user_id;
1510
    $user = false;
1511
    if (empty($user_id)) {
1512
        $userFromSession = Session::read('_user');
1513
        if (isset($userFromSession) && !empty($userFromSession)) {
1514
            return $userFromSession;
1515
            /*
1516
            return _api_format_user(
1517
                $userFromSession,
1518
                $showPassword,
1519
                $loadAvatars
1520
            );*/
1521
        }
1522
1523
        return false;
1524
    }
1525
1526
    $sql = "SELECT * FROM ".Database::get_main_table(TABLE_MAIN_USER)."
1527
            WHERE id = $user_id";
1528
    $result = Database::query($sql);
1529
    if (Database::num_rows($result) > 0) {
1530
        $result_array = Database::fetch_array($result);
1531
        $result_array['auth_sources'] = api_get_user_entity($result_array['id'])->getAuthSourcesAuthentications();
1532
        $result_array['user_is_online_in_chat'] = 0;
1533
        if ($checkIfUserOnline) {
1534
            $use_status_in_platform = user_is_online($user_id);
1535
            $result_array['user_is_online'] = $use_status_in_platform;
1536
            $user_online_in_chat = 0;
1537
            if ($use_status_in_platform) {
1538
                $user_status = UserManager::get_extra_user_data_by_field(
1539
                    $user_id,
1540
                    'user_chat_status',
1541
                    false,
1542
                    true
1543
                );
1544
                if (1 == (int) $user_status['user_chat_status']) {
1545
                    $user_online_in_chat = 1;
1546
                }
1547
            }
1548
            $result_array['user_is_online_in_chat'] = $user_online_in_chat;
1549
        }
1550
1551
        if ($loadExtraData) {
1552
            $fieldValue = new ExtraFieldValue('user');
1553
            $result_array['extra'] = $fieldValue->getAllValuesForAnItem(
1554
                $user_id,
1555
                $loadOnlyVisibleExtraData
1556
            );
1557
        }
1558
        $user = _api_format_user($result_array, $showPassword, $loadAvatars);
1559
    }
1560
1561
    return $user;
1562
}
1563
1564
function api_get_user_info_from_entity(
1565
    User $user,
1566
    $checkIfUserOnline = false,
1567
    $showPassword = false,
1568
    $loadExtraData = false,
1569
    $loadOnlyVisibleExtraData = false,
1570
    $loadAvatars = true,
1571
    $loadCertificate = false
1572
) {
1573
    if (!$user instanceof UserInterface) {
1574
        return false;
1575
    }
1576
1577
    // Make sure user_id is safe
1578
    $user_id = (int) $user->getId();
1579
1580
    if (empty($user_id)) {
1581
        $userFromSession = Session::read('_user');
1582
1583
        if (isset($userFromSession) && !empty($userFromSession)) {
1584
            return $userFromSession;
1585
        }
1586
1587
        return false;
1588
    }
1589
1590
    $result = [];
1591
    $result['user_is_online_in_chat'] = 0;
1592
    if ($checkIfUserOnline) {
1593
        $use_status_in_platform = user_is_online($user_id);
1594
        $result['user_is_online'] = $use_status_in_platform;
1595
        $user_online_in_chat = 0;
1596
        if ($use_status_in_platform) {
1597
            $user_status = UserManager::get_extra_user_data_by_field(
1598
                $user_id,
1599
                'user_chat_status',
1600
                false,
1601
                true
1602
            );
1603
            if (1 == (int) $user_status['user_chat_status']) {
1604
                $user_online_in_chat = 1;
1605
            }
1606
        }
1607
        $result['user_is_online_in_chat'] = $user_online_in_chat;
1608
    }
1609
1610
    if ($loadExtraData) {
1611
        $fieldValue = new ExtraFieldValue('user');
1612
        $result['extra'] = $fieldValue->getAllValuesForAnItem(
1613
            $user_id,
1614
            $loadOnlyVisibleExtraData
1615
        );
1616
    }
1617
1618
    $result['username'] = $user->getUsername();
1619
    $result['status'] = $user->getStatus();
1620
    $result['firstname'] = $user->getFirstname();
1621
    $result['lastname'] = $user->getLastname();
1622
    $result['email'] = $result['mail'] = $user->getEmail();
1623
    $result['complete_name'] = api_get_person_name($result['firstname'], $result['lastname']);
1624
    $result['complete_name_with_username'] = $result['complete_name'];
1625
1626
    if (!empty($result['username']) && 'false' === api_get_setting('profile.hide_username_with_complete_name')) {
1627
        $result['complete_name_with_username'] = $result['complete_name'].' ('.$result['username'].')';
1628
    }
1629
1630
    $showEmail = 'true' === api_get_setting('show_email_addresses');
1631
    if (!empty($result['email'])) {
1632
        $result['complete_name_with_email_forced'] = $result['complete_name'].' ('.$result['email'].')';
1633
        if ($showEmail) {
1634
            $result['complete_name_with_email'] = $result['complete_name'].' ('.$result['email'].')';
1635
        }
1636
    } else {
1637
        $result['complete_name_with_email'] = $result['complete_name'];
1638
        $result['complete_name_with_email_forced'] = $result['complete_name'];
1639
    }
1640
1641
    // Kept for historical reasons
1642
    $result['firstName'] = $result['firstname'];
1643
    $result['lastName'] = $result['lastname'];
1644
1645
    $attributes = [
1646
        'picture_uri',
1647
        'last_login',
1648
        'user_is_online',
1649
    ];
1650
1651
    $result['phone'] = $user->getPhone();
1652
    $result['address'] = $user->getAddress();
1653
    $result['official_code'] = $user->getOfficialCode();
1654
    $result['active'] = $user->isActive();
1655
    $result['auth_sources'] = $user->getAuthSourcesAuthentications();
1656
    $result['language'] = $user->getLocale();
1657
    $result['creator_id'] = $user->getCreatorId();
1658
    $result['created_at'] = $user->getCreatedAt()->format('Y-m-d H:i:s');
1659
    $result['hr_dept_id'] = $user->getHrDeptId();
1660
    $result['expiration_date'] = '';
1661
    if ($user->getExpirationDate()) {
1662
        $result['expiration_date'] = $user->getExpirationDate()->format('Y-m-d H:i:s');
1663
    }
1664
1665
    $result['last_login'] = null;
1666
    if ($user->getLastLogin()) {
1667
        $result['last_login'] = $user->getLastLogin()->format('Y-m-d H:i:s');
1668
    }
1669
1670
    $result['competences'] = $user->getCompetences();
1671
    $result['diplomas'] = $user->getDiplomas();
1672
    $result['teach'] = $user->getTeach();
1673
    $result['openarea'] = $user->getOpenarea();
1674
    $user_id = (int) $user->getId();
1675
1676
    // Maintain the user_id index for backwards compatibility
1677
    $result['user_id'] = $result['id'] = $user_id;
1678
1679
    if ($loadCertificate) {
1680
        $hasCertificates = Certificate::getCertificateByUser($user_id);
1681
        $result['has_certificates'] = 0;
1682
        if (!empty($hasCertificates)) {
1683
            $result['has_certificates'] = 1;
1684
        }
1685
    }
1686
1687
    $result['icon_status'] = '';
1688
    $result['icon_status_medium'] = '';
1689
    $result['is_admin'] = UserManager::is_admin($user_id);
1690
1691
    // Getting user avatar.
1692
    if ($loadAvatars) {
1693
        $result['avatar'] = '';
1694
        $result['avatar_no_query'] = '';
1695
        $result['avatar_small'] = '';
1696
        $result['avatar_medium'] = '';
1697
        $urlImg = '/';
1698
        $iconStatus = '';
1699
        $iconStatusMedium = '';
1700
1701
        switch ($user->getStatus()) {
1702
            case STUDENT:
1703
                if (isset($result['has_certificates']) && $result['has_certificates']) {
1704
                    $iconStatus = $urlImg.'icons/svg/identifier_graduated.svg';
1705
                } else {
1706
                    $iconStatus = $urlImg.'icons/svg/identifier_student.svg';
1707
                }
1708
                break;
1709
            case COURSEMANAGER:
1710
                if ($result['is_admin']) {
1711
                    $iconStatus = $urlImg.'icons/svg/identifier_admin.svg';
1712
                } else {
1713
                    $iconStatus = $urlImg.'icons/svg/identifier_teacher.svg';
1714
                }
1715
                break;
1716
            case STUDENT_BOSS:
1717
                $iconStatus = $urlImg.'icons/svg/identifier_teacher.svg';
1718
                break;
1719
        }
1720
1721
        if (!empty($iconStatus)) {
1722
            $iconStatusMedium = '<img src="'.$iconStatus.'" width="32px" height="32px">';
1723
            $iconStatus = '<img src="'.$iconStatus.'" width="22px" height="22px">';
1724
        }
1725
1726
        $result['icon_status'] = $iconStatus;
1727
        $result['icon_status_medium'] = $iconStatusMedium;
1728
    }
1729
1730
    if (isset($result['user_is_online'])) {
1731
        $result['user_is_online'] = true == $result['user_is_online'] ? 1 : 0;
1732
    }
1733
    if (isset($result['user_is_online_in_chat'])) {
1734
        $result['user_is_online_in_chat'] = $result['user_is_online_in_chat'];
1735
    }
1736
1737
    $result['password'] = '';
1738
    if ($showPassword) {
1739
        $result['password'] = $user->getPassword();
1740
    }
1741
1742
    if (isset($result['profile_completed'])) {
1743
        $result['profile_completed'] = $result['profile_completed'];
1744
    }
1745
1746
    $result['profile_url'] = api_get_path(WEB_CODE_PATH).'social/profile.php?u='.$user_id;
1747
1748
    // Send message link
1749
    $sendMessage = api_get_path(WEB_AJAX_PATH).'user_manager.ajax.php?a=get_user_popup&user_id='.$user_id;
1750
    $result['complete_name_with_message_link'] = Display::url(
1751
        $result['complete_name_with_username'],
1752
        $sendMessage,
1753
        ['class' => 'ajax']
1754
    );
1755
1756
    if (isset($result['extra'])) {
1757
        $result['extra'] = $result['extra'];
1758
    }
1759
1760
    return $result;
1761
}
1762
1763
function api_get_lp_entity(int $id): ?CLp
1764
{
1765
    return Database::getManager()->getRepository(CLp::class)->find($id);
1766
}
1767
1768
function api_get_user_entity(int $userId = 0): ?User
1769
{
1770
    $userId = $userId ?: api_get_user_id();
1771
    $repo = Container::getUserRepository();
1772
1773
    return $repo->find($userId);
1774
}
1775
1776
function api_get_current_user(): ?User
1777
{
1778
    $isLoggedIn = Container::getAuthorizationChecker()->isGranted('IS_AUTHENTICATED_REMEMBERED');
1779
    if (false === $isLoggedIn) {
1780
        return null;
1781
    }
1782
1783
    $token = Container::getTokenStorage()->getToken();
1784
1785
    if (null !== $token) {
1786
        return $token->getUser();
1787
    }
1788
1789
    return null;
1790
}
1791
1792
/**
1793
 * Finds all the information about a user from username instead of user id.
1794
 *
1795
 * @param string $username
1796
 *
1797
 * @return mixed $user_info array user_id, lastname, firstname, username, email or false on error
1798
 *
1799
 * @author Yannick Warnier <[email protected]>
1800
 */
1801
function api_get_user_info_from_username($username)
1802
{
1803
    if (empty($username)) {
1804
        return false;
1805
    }
1806
    $username = trim($username);
1807
1808
    $sql = "SELECT * FROM ".Database::get_main_table(TABLE_MAIN_USER)."
1809
            WHERE username='".Database::escape_string($username)."'";
1810
    $result = Database::query($sql);
1811
    if (Database::num_rows($result) > 0) {
1812
        $resultArray = Database::fetch_array($result);
1813
1814
        return _api_format_user($resultArray);
1815
    }
1816
1817
    return false;
1818
}
1819
1820
/**
1821
 * Get first user with an email.
1822
 *
1823
 * @param string $email
1824
 *
1825
 * @return array|bool
1826
 */
1827
function api_get_user_info_from_email($email = '')
1828
{
1829
    if (empty($email)) {
1830
        return false;
1831
    }
1832
    $sql = "SELECT * FROM ".Database::get_main_table(TABLE_MAIN_USER)."
1833
            WHERE email ='".Database::escape_string($email)."' LIMIT 1";
1834
    $result = Database::query($sql);
1835
    if (Database::num_rows($result) > 0) {
1836
        $resultArray = Database::fetch_array($result);
1837
1838
        return _api_format_user($resultArray);
1839
    }
1840
1841
    return false;
1842
}
1843
1844
/**
1845
 * @return string
1846
 */
1847
function api_get_course_id()
1848
{
1849
    return Session::read('_cid', null);
1850
}
1851
1852
/**
1853
 * Returns the current course id (integer).
1854
 *
1855
 * @param ?string $code Optional course code
1856
 *
1857
 * @return int
1858
 */
1859
function api_get_course_int_id(?string $code = null): int
1860
{
1861
    if (!empty($code)) {
1862
        $code = Database::escape_string($code);
1863
        $row = Database::select(
1864
            'id',
1865
            Database::get_main_table(TABLE_MAIN_COURSE),
1866
            ['where' => ['code = ?' => [$code]]],
1867
            'first'
1868
        );
1869
1870
        if (is_array($row) && isset($row['id'])) {
1871
            return $row['id'];
1872
        } else {
1873
            return 0;
1874
        }
1875
    }
1876
1877
    $cid = Session::read('_real_cid', 0);
1878
    if (empty($cid) && isset($_REQUEST['cid'])) {
1879
        $cid = (int) $_REQUEST['cid'];
1880
    }
1881
1882
    return $cid;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $cid could return the type null which is incompatible with the type-hinted return integer. Consider adding an additional type-check to rule them out.
Loading history...
1883
}
1884
1885
/**
1886
 * Gets a course setting from the current course_setting table. Try always using integer values.
1887
 *
1888
 * @param string       $settingName The name of the setting we want from the table
1889
 * @param Course|array $courseInfo
1890
 * @param bool         $force       force checking the value in the database
1891
 *
1892
 * @return mixed The value of that setting in that table. Return -1 if not found.
1893
 */
1894
function api_get_course_setting($settingName, $courseInfo = null, $force = false)
1895
{
1896
    if (empty($courseInfo)) {
1897
        $courseInfo = api_get_course_info();
1898
    }
1899
1900
    if (empty($courseInfo) || empty($settingName)) {
1901
        return -1;
1902
    }
1903
1904
    if ($courseInfo instanceof Course) {
1905
        $courseId = $courseInfo->getId();
1906
    } else {
1907
        $courseId = isset($courseInfo['real_id']) && !empty($courseInfo['real_id']) ? $courseInfo['real_id'] : 0;
1908
    }
1909
1910
    if (empty($courseId)) {
1911
        return -1;
1912
    }
1913
1914
    static $courseSettingInfo = [];
1915
1916
    if ($force) {
1917
        $courseSettingInfo = [];
1918
    }
1919
1920
    if (!isset($courseSettingInfo[$courseId])) {
1921
        $table = Database::get_course_table(TABLE_COURSE_SETTING);
1922
        $settingName = Database::escape_string($settingName);
1923
1924
        $sql = "SELECT variable, value FROM $table
1925
                WHERE c_id = $courseId ";
1926
        $res = Database::query($sql);
1927
        if (Database::num_rows($res) > 0) {
1928
            $result = Database::store_result($res, 'ASSOC');
1929
            $courseSettingInfo[$courseId] = array_column($result, 'value', 'variable');
1930
1931
            if (isset($courseSettingInfo[$courseId]['email_alert_manager_on_new_quiz'])) {
1932
                $value = $courseSettingInfo[$courseId]['email_alert_manager_on_new_quiz'];
1933
                if (!is_null($value)) {
1934
                    $result = explode(',', $value);
1935
                    $courseSettingInfo[$courseId]['email_alert_manager_on_new_quiz'] = $result;
1936
                }
1937
            }
1938
        }
1939
    }
1940
1941
    if (isset($courseSettingInfo[$courseId]) && isset($courseSettingInfo[$courseId][$settingName])) {
1942
        return $courseSettingInfo[$courseId][$settingName];
1943
    }
1944
1945
    return -1;
1946
}
1947
1948
function api_get_course_plugin_setting($plugin, $settingName, $courseInfo = [])
1949
{
1950
    $value = api_get_course_setting($settingName, $courseInfo, true);
1951
1952
    if (-1 === $value) {
1953
        // Check global settings
1954
        $value = api_get_plugin_setting($plugin, $settingName);
1955
        if ('true' === $value) {
1956
            return 1;
1957
        }
1958
        if ('false' === $value) {
1959
            return 0;
1960
        }
1961
        if (null === $value) {
1962
            return -1;
1963
        }
1964
    }
1965
1966
    return $value;
1967
}
1968
1969
/**
1970
 * Gets an anonymous user ID.
1971
 *
1972
 * For some tools that need tracking, like the learnpath tool, it is necessary
1973
 * to have a usable user-id to enable some kind of tracking, even if not
1974
 * perfect. An anonymous ID is taken from the users table by looking for a
1975
 * status of "6" (anonymous).
1976
 *
1977
 * @return int User ID of the anonymous user, or O if no anonymous user found
1978
 */
1979
function api_get_anonymous_id()
1980
{
1981
    // Find if another anon is connected now
1982
    $table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_LOGIN);
1983
    $tableU = Database::get_main_table(TABLE_MAIN_USER);
1984
    $ip = Database::escape_string(api_get_real_ip());
1985
    $max = (int) api_get_setting('admin.max_anonymous_users');
1986
    if ($max >= 2) {
1987
        $sql = "SELECT * FROM $table as TEL
1988
                JOIN $tableU as U
1989
                ON U.id = TEL.login_user_id
1990
                WHERE TEL.user_ip = '$ip'
1991
                    AND U.status = ".ANONYMOUS."
1992
                    AND U.id != 2 ";
1993
1994
        $result = Database::query($sql);
1995
        if (empty(Database::num_rows($result))) {
1996
            $login = uniqid('anon_');
1997
            $anonList = UserManager::get_user_list(['status' => ANONYMOUS], ['created_at ASC']);
1998
            if (count($anonList) >= $max) {
1999
                foreach ($anonList as $userToDelete) {
2000
                    UserManager::delete_user($userToDelete['user_id']);
2001
                    break;
2002
                }
2003
            }
2004
2005
            return UserManager::create_user(
0 ignored issues
show
Bug Best Practice introduced by
The expression return UserManager::crea...lhost', $login, $login) could also return false which is incompatible with the documented return type integer. Did you maybe forget to handle an error condition?

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

Loading history...
2006
                $login,
2007
                'anon',
2008
                ANONYMOUS,
2009
                ' anonymous@localhost',
2010
                $login,
2011
                $login
2012
            );
2013
        } else {
2014
            $row = Database::fetch_assoc($result);
2015
2016
            return $row['id'];
2017
        }
2018
    }
2019
2020
    $table = Database::get_main_table(TABLE_MAIN_USER);
2021
    $sql = "SELECT id
2022
            FROM $table
2023
            WHERE status = ".ANONYMOUS." ";
2024
    $res = Database::query($sql);
2025
    if (Database::num_rows($res) > 0) {
2026
        $row = Database::fetch_assoc($res);
2027
2028
        return $row['id'];
2029
    }
2030
2031
    // No anonymous user was found.
2032
    return 0;
2033
}
2034
2035
/**
2036
 * @param int $courseId
2037
 * @param int $sessionId
2038
 * @param int $groupId
2039
 *
2040
 * @return string
2041
 */
2042
function api_get_cidreq_params($courseId, $sessionId = 0, $groupId = 0)
2043
{
2044
    $courseId = !empty($courseId) ? (int) $courseId : 0;
2045
    $sessionId = !empty($sessionId) ? (int) $sessionId : 0;
2046
    $groupId = !empty($groupId) ? (int) $groupId : 0;
2047
2048
    $url = 'cid='.$courseId;
2049
    $url .= '&sid='.$sessionId;
2050
    $url .= '&gid='.$groupId;
2051
2052
    return $url;
2053
}
2054
2055
/**
2056
 * Returns the current course url part including session, group, and gradebook params.
2057
 *
2058
 * @param bool   $addSessionId
2059
 * @param bool   $addGroupId
2060
 * @param string $origin
2061
 *
2062
 * @return string Course & session references to add to a URL
2063
 */
2064
function api_get_cidreq($addSessionId = true, $addGroupId = true, $origin = '')
2065
{
2066
    $courseId = api_get_course_int_id();
2067
    if (0 === $courseId && isset($_REQUEST['cid'])) {
2068
        $courseId = (int) $_REQUEST['cid'];
2069
    }
2070
    $url = empty($courseId) ? '' : 'cid='.$courseId;
2071
    $origin = empty($origin) ? api_get_origin() : Security::remove_XSS($origin);
2072
2073
    if ($addSessionId) {
2074
        if (!empty($url)) {
2075
            $sessionId = api_get_session_id();
2076
            if (0 === $sessionId && isset($_REQUEST['sid'])) {
2077
                $sessionId = (int) $_REQUEST['sid'];
2078
            }
2079
            $url .= 0 === $sessionId ? '&sid=0' : '&sid='.$sessionId;
2080
        }
2081
    }
2082
2083
    if ($addGroupId) {
2084
        if (!empty($url)) {
2085
            $url .= 0 == api_get_group_id() ? '&gid=0' : '&gid='.api_get_group_id();
2086
        }
2087
    }
2088
2089
    if (!empty($url)) {
2090
        $url .= '&gradebook='.(int) api_is_in_gradebook();
2091
        if (false !== $origin) {
2092
            $url .= '&origin=' . $origin;
2093
        }
2094
    }
2095
2096
    return $url;
2097
}
2098
2099
/**
2100
 * Get if we visited a gradebook page.
2101
 *
2102
 * @return bool
2103
 */
2104
function api_is_in_gradebook()
2105
{
2106
    return Session::read('in_gradebook', false);
2107
}
2108
2109
/**
2110
 * Set that we are in a page inside a gradebook.
2111
 */
2112
function api_set_in_gradebook()
2113
{
2114
    Session::write('in_gradebook', true);
2115
}
2116
2117
/**
2118
 * Remove gradebook session.
2119
 */
2120
function api_remove_in_gradebook()
2121
{
2122
    Session::erase('in_gradebook');
2123
}
2124
2125
/**
2126
 * Returns the current course info array see api_format_course_array()
2127
 * If the course_code is given, the returned array gives info about that
2128
 * particular course, if none given it gets the course info from the session.
2129
 *
2130
 * @param string $courseCode
2131
 *
2132
 * @return array
2133
 */
2134
function api_get_course_info($courseCode = null)
2135
{
2136
    if (!empty($courseCode)) {
2137
        $course = Container::getCourseRepository()->findOneByCode($courseCode);
2138
2139
        return api_format_course_array($course);
2140
    }
2141
2142
    $course = Session::read('_course');
2143
    if ('-1' == $course) {
2144
        $course = [];
2145
    }
2146
2147
    if (empty($course) && isset($_REQUEST['cid'])) {
2148
        $course = api_get_course_info_by_id((int) $_REQUEST['cid']);
2149
    }
2150
2151
    return $course;
2152
}
2153
2154
/**
2155
 * @param int $courseId
2156
 */
2157
function api_get_course_entity($courseId = 0): ?Course
2158
{
2159
    if (empty($courseId)) {
2160
        $courseId = api_get_course_int_id();
2161
    }
2162
2163
    if (empty($courseId)) {
2164
        return null;
2165
    }
2166
2167
    return Container::getCourseRepository()->find($courseId);
2168
}
2169
2170
/**
2171
 * @param int $id
2172
 */
2173
function api_get_session_entity($id = 0): ?SessionEntity
2174
{
2175
    if (empty($id)) {
2176
        $id = api_get_session_id();
2177
    }
2178
2179
    if (empty($id)) {
2180
        return null;
2181
    }
2182
2183
    return Container::getSessionRepository()->find($id);
2184
}
2185
2186
/**
2187
 * @param int $id
2188
 */
2189
function api_get_group_entity($id = 0): ?CGroup
2190
{
2191
    if (empty($id)) {
2192
        $id = api_get_group_id();
2193
    }
2194
2195
    return Container::getGroupRepository()->find($id);
2196
}
2197
2198
/**
2199
 * @param int $id
2200
 */
2201
function api_get_url_entity($id = 0): ?AccessUrl
2202
{
2203
    if (empty($id)) {
2204
        $id = api_get_current_access_url_id();
2205
    }
2206
2207
    return Container::getAccessUrlRepository()->find($id);
2208
}
2209
2210
/**
2211
 * Returns the current course info array.
2212
2213
 * Now if the course_code is given, the returned array gives info about that
2214
 * particular course, not specially the current one.
2215
 *
2216
 * @param int $id Numeric ID of the course
2217
 *
2218
 * @return array The course info as an array formatted by api_format_course_array, including category.title
2219
 */
2220
function api_get_course_info_by_id(?int $id = 0)
2221
{
2222
    if (empty($id)) {
2223
        $course = Session::read('_course', []);
2224
2225
        return $course;
2226
    }
2227
2228
    $course = Container::getCourseRepository()->find($id);
2229
    if (empty($course)) {
2230
        return [];
2231
    }
2232
2233
    return api_format_course_array($course);
2234
}
2235
2236
/**
2237
 * Reformat the course array (output by api_get_course_info()) in order, mostly,
2238
 * to switch from 'code' to 'id' in the array.
2239
 *
2240
 * @return array
2241
 *
2242
 * @todo eradicate the false "id"=code field of the $_course array and use the int id
2243
 */
2244
function api_format_course_array(Course $course = null)
2245
{
2246
    if (empty($course)) {
2247
        return [];
2248
    }
2249
2250
    $courseData = [];
2251
    $courseData['id'] = $courseData['real_id'] = $course->getId();
2252
2253
    // Added
2254
    $courseData['code'] = $courseData['sysCode'] = $course->getCode();
2255
    $courseData['name'] = $courseData['title'] = $course->getTitle(); // 'name' only used for backwards compatibility - should be removed in the long run
2256
    $courseData['official_code'] = $courseData['visual_code'] = $course->getVisualCode();
2257
    $courseData['creation_date'] = $course->getCreationDate()->format('Y-m-d H:i:s');
2258
    $courseData['titular'] = $course->getTutorName();
2259
    $courseData['language'] = $courseData['course_language'] = $course->getCourseLanguage();
2260
    $courseData['extLink']['url'] = $courseData['department_url'] = $course->getDepartmentUrl();
2261
    $courseData['extLink']['name'] = $courseData['department_name'] = $course->getDepartmentName();
2262
2263
    $courseData['visibility'] = $course->getVisibility();
2264
    $courseData['subscribe_allowed'] = $courseData['subscribe'] = $course->getSubscribe();
2265
    $courseData['unsubscribe'] = $course->getUnsubscribe();
2266
    $courseData['activate_legal'] = $course->getActivateLegal();
2267
    $courseData['legal'] = $course->getLegal();
2268
    $courseData['show_score'] = $course->getShowScore(); //used in the work tool
2269
    $courseData['video_url'] = $course->getVideoUrl();
2270
    $courseData['sticky'] = (int) $course->isSticky();
2271
2272
    $coursePath = '/course/';
2273
    $webCourseHome = $coursePath.$courseData['real_id'].'/home';
2274
2275
    // Course password
2276
    $courseData['registration_code'] = $course->getRegistrationCode();
2277
    $courseData['disk_quota'] = $course->getDiskQuota();
2278
    $courseData['course_public_url'] = $webCourseHome;
2279
    $courseData['about_url'] = $coursePath.$courseData['real_id'].'/about';
2280
    $courseData['add_teachers_to_sessions_courses'] = $course->isAddTeachersToSessionsCourses();
2281
2282
    $image = Display::getMdiIcon(
2283
        ObjectIcon::COURSE,
2284
        'ch-tool-icon',
2285
        null,
2286
        ICON_SIZE_BIG
2287
    );
2288
2289
    $illustration = Container::getIllustrationRepository()->getIllustrationUrl($course);
2290
    if (!empty($illustration)) {
2291
        $image = $illustration;
2292
    }
2293
2294
    $courseData['course_image'] = $image.'?filter=course_picture_small';
2295
    $courseData['course_image_large'] = $image.'?filter=course_picture_medium';
2296
2297
    if ('true' === api_get_setting('course.show_course_duration') && null !== $course->getDuration()) {
2298
        $courseData['duration'] = $course->getDuration();
2299
    }
2300
2301
    return $courseData;
2302
}
2303
2304
/**
2305
 * Returns a difficult to guess password.
2306
 */
2307
function api_generate_password(int $length = 8, $useRequirements = true): string
2308
{
2309
    if ($length < 2) {
2310
        $length = 2;
2311
    }
2312
2313
    $charactersLowerCase = 'abcdefghijkmnopqrstuvwxyz';
2314
    $charactersUpperCase = 'ABCDEFGHJKLMNPQRSTUVWXYZ';
2315
    $charactersSpecials = '!@#$%^&*()_+-=[]{}|;:,.<>?';
2316
    $minNumbers = 2;
2317
    $length = $length - $minNumbers;
2318
    $minLowerCase = round($length / 2);
2319
    $minUpperCase = $length - $minLowerCase;
2320
    $minSpecials = 1; // Default minimum special characters
2321
2322
    $password = '';
2323
    $passwordRequirements = $useRequirements ? Security::getPasswordRequirements() : [];
2324
2325
    $factory = new RandomLib\Factory();
2326
    $generator = $factory->getGenerator(new SecurityLib\Strength(SecurityLib\Strength::MEDIUM));
2327
2328
    if (!empty($passwordRequirements)) {
2329
        $length = $passwordRequirements['min']['length'];
2330
        $minNumbers = $passwordRequirements['min']['numeric'];
2331
        $minLowerCase = $passwordRequirements['min']['lowercase'];
2332
        $minUpperCase = $passwordRequirements['min']['uppercase'];
2333
        $minSpecials = $passwordRequirements['min']['specials'];
2334
2335
        $rest = $length - $minNumbers - $minLowerCase - $minUpperCase - $minSpecials;
2336
        // Add the rest to fill the length requirement
2337
        if ($rest > 0) {
2338
            $password .= $generator->generateString($rest, $charactersLowerCase.$charactersUpperCase);
2339
        }
2340
    }
2341
2342
    // Min digits default 2
2343
    for ($i = 0; $i < $minNumbers; $i++) {
2344
        $password .= $generator->generateInt(2, 9);
2345
    }
2346
2347
    // Min lowercase
2348
    $password .= $generator->generateString($minLowerCase, $charactersLowerCase);
2349
2350
    // Min uppercase
2351
    $password .= $generator->generateString($minUpperCase, $charactersUpperCase);
2352
2353
    // Min special characters
2354
    $password .= $generator->generateString($minSpecials, $charactersSpecials);
2355
2356
    // Shuffle the password to ensure randomness
2357
    $password = str_shuffle($password);
2358
2359
    return $password;
2360
}
2361
2362
/**
2363
 * Checks a password to see wether it is OK to use.
2364
 *
2365
 * @param string $password
2366
 *
2367
 * @return bool if the password is acceptable, false otherwise
2368
 *              Notes about what a password "OK to use" is:
2369
 *              1. The password should be at least 5 characters long.
2370
 *              2. Only English letters (uppercase or lowercase, it doesn't matter) and digits are allowed.
2371
 *              3. The password should contain at least 3 letters.
2372
 *              4. It should contain at least 2 digits.
2373
 *              Settings will change if the configuration value is set: password_requirements
2374
 */
2375
function api_check_password($password)
2376
{
2377
    $passwordRequirements = Security::getPasswordRequirements();
2378
2379
    $minLength = $passwordRequirements['min']['length'];
2380
    $minNumbers = $passwordRequirements['min']['numeric'];
2381
    // Optional
2382
    $minLowerCase = $passwordRequirements['min']['lowercase'];
2383
    $minUpperCase = $passwordRequirements['min']['uppercase'];
2384
2385
    $minLetters = $minLowerCase + $minUpperCase;
2386
    $passwordLength = api_strlen($password);
2387
2388
    $conditions = [
2389
        'min_length' => $passwordLength >= $minLength,
2390
    ];
2391
2392
    $digits = 0;
2393
    $lowerCase = 0;
2394
    $upperCase = 0;
2395
2396
    for ($i = 0; $i < $passwordLength; $i++) {
2397
        $currentCharacterCode = api_ord(api_substr($password, $i, 1));
2398
        if ($currentCharacterCode >= 65 && $currentCharacterCode <= 90) {
2399
            $upperCase++;
2400
        }
2401
2402
        if ($currentCharacterCode >= 97 && $currentCharacterCode <= 122) {
2403
            $lowerCase++;
2404
        }
2405
        if ($currentCharacterCode >= 48 && $currentCharacterCode <= 57) {
2406
            $digits++;
2407
        }
2408
    }
2409
2410
    // Min number of digits
2411
    $conditions['min_numeric'] = $digits >= $minNumbers;
2412
2413
    if (!empty($minUpperCase)) {
2414
        // Uppercase
2415
        $conditions['min_uppercase'] = $upperCase >= $minUpperCase;
2416
    }
2417
2418
    if (!empty($minLowerCase)) {
2419
        // Lowercase
2420
        $conditions['min_lowercase'] = $upperCase >= $minLowerCase;
2421
    }
2422
2423
    // Min letters
2424
    $letters = $upperCase + $lowerCase;
2425
    $conditions['min_letters'] = $letters >= $minLetters;
2426
2427
    $isPasswordOk = true;
2428
    foreach ($conditions as $condition) {
2429
        if (false === $condition) {
2430
            $isPasswordOk = false;
2431
            break;
2432
        }
2433
    }
2434
2435
    if (false === $isPasswordOk) {
2436
        $output = get_lang('The new password does not match the minimum security requirements').'<br />';
2437
        $output .= Security::getPasswordRequirementsToString($conditions);
2438
2439
        Display::addFlash(Display::return_message($output, 'warning', false));
2440
    }
2441
2442
    return $isPasswordOk;
2443
}
2444
2445
/**
2446
 * Gets the current Chamilo (not PHP/cookie) session ID.
2447
 *
2448
 * @return int O if no active session, the session ID otherwise
2449
 */
2450
function api_get_session_id()
2451
{
2452
    return (int) Session::read('sid', 0);
2453
}
2454
2455
/**
2456
 * Gets the current Chamilo (not social network) group ID.
2457
 *
2458
 * @return int O if no active session, the session ID otherwise
2459
 */
2460
function api_get_group_id()
2461
{
2462
    return Session::read('gid', 0);
2463
}
2464
2465
/**
2466
 * Gets the current or given session name.
2467
 *
2468
 * @param   int     Session ID (optional)
2469
 *
2470
 * @return string The session name, or null if not found
2471
 */
2472
function api_get_session_name($session_id = 0)
2473
{
2474
    if (empty($session_id)) {
2475
        $session_id = api_get_session_id();
2476
        if (empty($session_id)) {
2477
            return null;
2478
        }
2479
    }
2480
    $t = Database::get_main_table(TABLE_MAIN_SESSION);
2481
    $s = "SELECT title FROM $t WHERE id = ".(int) $session_id;
2482
    $r = Database::query($s);
2483
    $c = Database::num_rows($r);
2484
    if ($c > 0) {
2485
        //technically, there can be only one, but anyway we take the first
2486
        $rec = Database::fetch_array($r);
2487
2488
        return $rec['title'];
2489
    }
2490
2491
    return null;
2492
}
2493
2494
/**
2495
 * Gets the session info by id.
2496
 *
2497
 * @param int $id Session ID
2498
 *
2499
 * @return array information of the session
2500
 */
2501
function api_get_session_info($id)
2502
{
2503
    return SessionManager::fetch($id);
2504
}
2505
2506
/**
2507
 * Gets the session visibility by session id.
2508
 *
2509
 * @deprecated Use Session::setAccessVisibilityByUser() instead.
2510
 *
2511
 * @param int  $session_id
2512
 * @param int  $courseId
2513
 * @param bool $ignore_visibility_for_admins
2514
 *
2515
 * @return int
2516
 *             0 = session still available,
2517
 *             SESSION_VISIBLE_READ_ONLY = 1,
2518
 *             SESSION_VISIBLE = 2,
2519
 *             SESSION_INVISIBLE = 3
2520
 */
2521
function api_get_session_visibility(
2522
    $session_id,
2523
    $courseId = null,
2524
    $ignore_visibility_for_admins = true,
2525
    $userId = 0
2526
) {
2527
    if (api_is_platform_admin()) {
2528
        if ($ignore_visibility_for_admins) {
2529
            return SESSION_AVAILABLE;
2530
        }
2531
    }
2532
    $userId = empty($userId) ? api_get_user_id() : (int) $userId;
2533
2534
    $now = time();
2535
    if (empty($session_id)) {
2536
        return 0; // Means that the session is still available.
2537
    }
2538
2539
    $session_id = (int) $session_id;
2540
    $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
2541
2542
    $result = Database::query("SELECT * FROM $tbl_session WHERE id = $session_id");
2543
2544
    if (Database::num_rows($result) <= 0) {
2545
        return SESSION_INVISIBLE;
0 ignored issues
show
introduced by
The constant SESSION_INVISIBLE has been deprecated: Use Session::INVISIBLE ( Ignorable by Annotation )

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

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

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

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

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

2606
            $visibility = $start < $now ? SESSION_AVAILABLE : /** @scrutinizer ignore-deprecated */ SESSION_INVISIBLE;
Loading history...
2607
        }
2608
2609
        // Test end date.
2610
        if (!empty($row['coach_access_end_date'])) {
2611
            if (SESSION_AVAILABLE === $visibility) {
2612
                $endDateCoach = api_strtotime($row['coach_access_end_date'], 'UTC');
2613
                $visibility = $endDateCoach >= $now ? SESSION_AVAILABLE : $row['visibility'];
2614
            }
2615
        }
2616
    }
2617
2618
    return $visibility;
2619
}
2620
2621
/**
2622
 * This function returns a (star) session icon if the session is not null and
2623
 * the user is not a student.
2624
 *
2625
 * @param int $sessionId
2626
 * @param int $statusId  User status id - if 5 (student), will return empty
2627
 *
2628
 * @return string Session icon
2629
 */
2630
function api_get_session_image($sessionId, User $user)
2631
{
2632
    $sessionId = (int) $sessionId;
2633
    $image = '';
2634
    if (!$user->hasRole('ROLE_STUDENT')) {
2635
        // Check whether is not a student
2636
        if ($sessionId > 0) {
2637
            $image = '&nbsp;&nbsp;'.Display::getMdiIcon(
2638
                ObjectIcon::STAR,
2639
                'ch-tool-icon',
2640
                'align:absmiddle;',
2641
                ICON_SIZE_SMALL,
2642
                get_lang('Session-specific resource')
2643
            );
2644
        }
2645
    }
2646
2647
    return $image;
2648
}
2649
2650
/**
2651
 * This function add an additional condition according to the session of the course.
2652
 *
2653
 * @param int    $session_id        session id
2654
 * @param bool   $and               optional, true if more than one condition false if the only condition in the query
2655
 * @param bool   $with_base_content optional, true to accept content with session=0 as well,
2656
 *                                  false for strict session condition
2657
 * @param string $session_field
2658
 *
2659
 * @return string condition of the session
2660
 */
2661
function api_get_session_condition(
2662
    $session_id,
2663
    $and = true,
2664
    $with_base_content = false,
2665
    $session_field = 'session_id'
2666
) {
2667
    $session_id = (int) $session_id;
2668
2669
    if (empty($session_field)) {
2670
        $session_field = 'session_id';
2671
    }
2672
    // Condition to show resources by session
2673
    $condition_add = $and ? ' AND ' : ' WHERE ';
2674
2675
    if ($with_base_content) {
2676
        $condition_session = $condition_add." ( $session_field = $session_id OR $session_field = 0 OR $session_field IS NULL) ";
2677
    } else {
2678
        if (empty($session_id)) {
2679
            $condition_session = $condition_add." ($session_field = $session_id OR $session_field IS NULL)";
2680
        } else {
2681
            $condition_session = $condition_add." $session_field = $session_id ";
2682
        }
2683
    }
2684
2685
    return $condition_session;
2686
}
2687
2688
/**
2689
 * Returns the value of a setting from the web-adjustable admin config settings.
2690
 *
2691
 * WARNING true/false are stored as string, so when comparing you need to check e.g.
2692
 * if (api_get_setting('show_navigation_menu') == 'true') //CORRECT
2693
 * instead of
2694
 * if (api_get_setting('show_navigation_menu') == true) //INCORRECT
2695
 *
2696
 * @param string $variable The variable name
2697
 *
2698
 * @return string|array
2699
 */
2700
function api_get_setting($variable, $isArray = false, $key = null)
2701
{
2702
    $settingsManager = Container::getSettingsManager();
2703
    if (empty($settingsManager)) {
2704
        return '';
2705
    }
2706
    $variable = trim($variable);
2707
2708
    switch ($variable) {
2709
        case 'server_type':
2710
            $test = ['dev', 'test'];
2711
            $environment = Container::getEnvironment();
2712
            if (in_array($environment, $test)) {
2713
                return 'test';
2714
            }
2715
2716
            return 'prod';
2717
        // deprecated settings
2718
        // no break
2719
        case 'openid_authentication':
2720
        case 'service_ppt2lp':
2721
        case 'formLogin_hide_unhide_label':
2722
            return false;
2723
            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...
2724
        case 'tool_visible_by_default_at_creation':
2725
            $values = $settingsManager->getSetting($variable);
2726
            $newResult = [];
2727
            foreach ($values as $parameter) {
2728
                $newResult[$parameter] = 'true';
2729
            }
2730
2731
            return $newResult;
2732
            break;
2733
        default:
2734
            $settingValue = $settingsManager->getSetting($variable, true);
2735
            if (is_string($settingValue) && $isArray && !empty($settingValue)) {
2736
                // Check if the value is a valid JSON string
2737
                $decodedValue = json_decode($settingValue, true);
2738
2739
                // If it's a valid JSON string and the result is an array, return it
2740
                if (is_array($decodedValue)) {
2741
                    return $decodedValue;
2742
                }
2743
2744
                // If it's not an array, continue with the normal flow
2745
                // Optional: If you need to evaluate the value using eval
2746
                $strArrayValue = rtrim($settingValue, ';');
2747
                $value = eval("return $strArrayValue;");
0 ignored issues
show
introduced by
The use of eval() is discouraged.
Loading history...
2748
                if (is_array($value)) {
2749
                    return $value;
2750
                }
2751
            }
2752
2753
            // If the value is not a JSON array or wasn't returned previously, continue with the normal flow
2754
            if (!empty($key) && isset($settingValue[$variable][$key])) {
2755
                return $settingValue[$variable][$key];
2756
            }
2757
2758
            return $settingValue;
2759
            break;
2760
    }
2761
}
2762
2763
/**
2764
 * @param string $variable
2765
 * @param string $option
2766
 *
2767
 * @return bool
2768
 */
2769
function api_get_setting_in_list($variable, $option)
2770
{
2771
    $value = api_get_setting($variable);
2772
2773
    return in_array($option, $value);
2774
}
2775
2776
/**
2777
 * @param string $plugin
2778
 * @param string $variable
2779
 *
2780
 * @return string
2781
 */
2782
function api_get_plugin_setting($plugin, $variable)
2783
{
2784
    $variableName = $plugin.'_'.$variable;
2785
    //$result = api_get_setting($variableName);
2786
    $params = [
2787
        'category = ? AND subkey = ? AND variable = ?' => [
2788
            'Plugins',
2789
            $plugin,
2790
            $variableName,
2791
        ],
2792
    ];
2793
    $table = Database::get_main_table(TABLE_MAIN_SETTINGS);
2794
    $result = Database::select(
2795
        'selected_value',
2796
        $table,
2797
        ['where' => $params],
2798
        'one'
2799
    );
2800
    if ($result) {
2801
        $value = $result['selected_value'];
2802
        $serializedValue = @unserialize($result['selected_value'], []);
2803
        if (false !== $serializedValue) {
2804
            $value = $serializedValue;
2805
        }
2806
2807
        return $value;
2808
    }
2809
2810
    return null;
2811
    /// Old code
2812
2813
    $variableName = $plugin.'_'.$variable;
0 ignored issues
show
Unused Code introduced by
$variableName = $plugin . '_' . $variable is not reachable.

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

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

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

    return false;
}

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

Loading history...
2814
    $result = api_get_setting($variableName);
2815
2816
    if (isset($result[$plugin])) {
2817
        $value = $result[$plugin];
2818
2819
        $unserialized = UnserializeApi::unserialize('not_allowed_classes', $value, true);
2820
2821
        if (false !== $unserialized) {
2822
            $value = $unserialized;
2823
        }
2824
2825
        return $value;
2826
    }
2827
2828
    return null;
2829
}
2830
2831
/**
2832
 * Returns the value of a setting from the web-adjustable admin config settings.
2833
 */
2834
function api_get_settings_params($params)
2835
{
2836
    $table = Database::get_main_table(TABLE_MAIN_SETTINGS);
2837
2838
    return Database::select('*', $table, ['where' => $params]);
2839
}
2840
2841
/**
2842
 * @param array $params example: [id = ? => '1']
2843
 *
2844
 * @return array
2845
 */
2846
function api_get_settings_params_simple($params)
2847
{
2848
    $table = Database::get_main_table(TABLE_MAIN_SETTINGS);
2849
2850
    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...
2851
}
2852
2853
/**
2854
 * Returns the value of a setting from the web-adjustable admin config settings.
2855
 */
2856
function api_delete_settings_params($params)
2857
{
2858
    $table = Database::get_main_table(TABLE_MAIN_SETTINGS);
2859
2860
    return Database::delete($table, $params);
2861
}
2862
2863
/**
2864
 * Returns an escaped version of $_SERVER['PHP_SELF'] to avoid XSS injection.
2865
 *
2866
 * @return string Escaped version of $_SERVER['PHP_SELF']
2867
 */
2868
function api_get_self()
2869
{
2870
    return htmlentities($_SERVER['PHP_SELF']);
2871
}
2872
2873
/**
2874
 * Checks whether current user is a platform administrator.
2875
 *
2876
 * @param bool $allowSessionAdmins Whether session admins should be considered admins or not
2877
 * @param bool $allowDrh           Whether HR directors should be considered admins or not
2878
 *
2879
 * @return bool true if the user has platform admin rights,
2880
 *              false otherwise
2881
 *
2882
 * @see usermanager::is_admin(user_id) for a user-id specific function
2883
 */
2884
function api_is_platform_admin($allowSessionAdmins = false, $allowDrh = false)
2885
{
2886
    $currentUser = api_get_current_user();
2887
2888
    if (null === $currentUser) {
2889
        return false;
2890
    }
2891
2892
    $isAdmin = $currentUser->hasRole('ROLE_ADMIN') || $currentUser->hasRole('ROLE_SUPER_ADMIN');
2893
2894
    if ($isAdmin) {
2895
        return true;
2896
    }
2897
2898
    if ($allowSessionAdmins && $currentUser->hasRole('ROLE_SESSION_MANAGER')) {
2899
        return true;
2900
    }
2901
2902
    if ($allowDrh && $currentUser->hasRole('ROLE_HR')) {
2903
        return true;
2904
    }
2905
2906
    return false;
2907
}
2908
2909
/**
2910
 * Checks whether the user given as user id is in the admin table.
2911
 *
2912
 * @param int $user_id If none provided, will use current user
2913
 * @param int $url     URL ID. If provided, also check if the user is active on given URL
2914
 *
2915
 * @return bool True if the user is admin, false otherwise
2916
 */
2917
function api_is_platform_admin_by_id($user_id = null, $url = null)
2918
{
2919
    $user_id = (int) $user_id;
2920
    if (empty($user_id)) {
2921
        $user_id = api_get_user_id();
2922
    }
2923
    $admin_table = Database::get_main_table(TABLE_MAIN_ADMIN);
2924
    $sql = "SELECT * FROM $admin_table WHERE user_id = $user_id";
2925
    $res = Database::query($sql);
2926
    $is_admin = 1 === Database::num_rows($res);
2927
    if (!$is_admin || !isset($url)) {
2928
        return $is_admin;
2929
    }
2930
    // We get here only if $url is set
2931
    $url = (int) $url;
2932
    $url_user_table = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
2933
    $sql = "SELECT * FROM $url_user_table
2934
            WHERE access_url_id = $url AND user_id = $user_id";
2935
    $res = Database::query($sql);
2936
2937
    return 1 === Database::num_rows($res);
2938
}
2939
2940
/**
2941
 * Checks whether current user is allowed to create courses.
2942
 *
2943
 * @return bool true if the user has course creation rights,
2944
 *              false otherwise
2945
 */
2946
function api_is_allowed_to_create_course()
2947
{
2948
    if (api_is_platform_admin()) {
2949
        return true;
2950
    }
2951
2952
    // Teachers can only create courses
2953
    if (api_is_teacher()) {
2954
        if ('true' === api_get_setting('allow_users_to_create_courses')) {
2955
            return true;
2956
        } else {
2957
            return false;
2958
        }
2959
    }
2960
2961
    return Session::read('is_allowedCreateCourse');
2962
}
2963
2964
/**
2965
 * Checks whether the current user is a course administrator.
2966
 *
2967
 * @return bool True if current user is a course administrator
2968
 */
2969
function api_is_course_admin()
2970
{
2971
    if (api_is_platform_admin()) {
2972
        return true;
2973
    }
2974
2975
    $user = api_get_current_user();
2976
    if ($user) {
2977
        if (
2978
            $user->hasRole('ROLE_CURRENT_COURSE_SESSION_TEACHER') ||
2979
            $user->hasRole('ROLE_CURRENT_COURSE_TEACHER')
2980
        ) {
2981
            return true;
2982
        }
2983
    }
2984
2985
    return false;
2986
}
2987
2988
/**
2989
 * Checks whether the current user is a course coach
2990
 * Based on the presence of user in session_rel_user.relation_type (as session general coach, value 3).
2991
 *
2992
 * @return bool True if current user is a course coach
2993
 */
2994
function api_is_session_general_coach()
2995
{
2996
    return Session::read('is_session_general_coach');
2997
}
2998
2999
/**
3000
 * Checks whether the current user is a course tutor
3001
 * Based on the presence of user in session_rel_course_rel_user.user_id with status = 2.
3002
 *
3003
 * @return bool True if current user is a course tutor
3004
 */
3005
function api_is_course_tutor()
3006
{
3007
    return Session::read('is_courseTutor');
3008
}
3009
3010
/**
3011
 * @param int $user_id
3012
 * @param int $courseId
3013
 * @param int $session_id
3014
 *
3015
 * @return bool
3016
 */
3017
function api_is_course_session_coach($user_id, $courseId, $session_id)
3018
{
3019
    $session_table = Database::get_main_table(TABLE_MAIN_SESSION);
3020
    $session_rel_course_rel_user_table = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
3021
3022
    $user_id = (int) $user_id;
3023
    $session_id = (int) $session_id;
3024
    $courseId = (int) $courseId;
3025
3026
    $sql = "SELECT DISTINCT session.id
3027
            FROM $session_table
3028
            INNER JOIN $session_rel_course_rel_user_table session_rc_ru
3029
            ON session.id = session_rc_ru.session_id
3030
            WHERE
3031
                session_rc_ru.user_id = '".$user_id."'  AND
3032
                session_rc_ru.c_id = '$courseId' AND
3033
                session_rc_ru.status = ".SessionEntity::COURSE_COACH." AND
3034
                session_rc_ru.session_id = '$session_id'";
3035
    $result = Database::query($sql);
3036
3037
    return Database::num_rows($result) > 0;
3038
}
3039
3040
/**
3041
 * Checks whether the current user is a course or session coach.
3042
 *
3043
 * @param int $session_id
3044
 * @param int $courseId
3045
 * @param bool  Check whether we are in student view and, if we are, return false
3046
 * @param int $userId
3047
 *
3048
 * @return bool True if current user is a course or session coach
3049
 */
3050
function api_is_coach($session_id = 0, $courseId = null, $check_student_view = true, $userId = 0)
3051
{
3052
    $userId = empty($userId) ? api_get_user_id() : (int) $userId;
3053
3054
    if (!empty($session_id)) {
3055
        $session_id = (int) $session_id;
3056
    } else {
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 = (int) $courseId;
3067
    } else {
3068
        $courseId = api_get_course_int_id();
3069
    }
3070
3071
    $session_table = Database::get_main_table(TABLE_MAIN_SESSION);
3072
    $session_rel_course_rel_user_table = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
3073
    $tblSessionRelUser = Database::get_main_table(TABLE_MAIN_SESSION_USER);
3074
    $sessionIsCoach = [];
3075
3076
    if (!empty($courseId)) {
3077
        $sql = "SELECT DISTINCT s.id, title, access_start_date, access_end_date
3078
                FROM $session_table s
3079
                INNER JOIN $session_rel_course_rel_user_table session_rc_ru
3080
                ON session_rc_ru.session_id = s.id AND session_rc_ru.user_id = '".$userId."'
3081
                WHERE
3082
                    session_rc_ru.c_id = '$courseId' AND
3083
                    session_rc_ru.status =".SessionEntity::COURSE_COACH." AND
3084
                    session_rc_ru.session_id = '$session_id'";
3085
        $result = Database::query($sql);
3086
        $sessionIsCoach = Database::store_result($result);
3087
    }
3088
3089
    if (!empty($session_id)) {
3090
        $sql = "SELECT DISTINCT s.id
3091
                FROM $session_table AS s
3092
                INNER JOIN $tblSessionRelUser sru
3093
                ON s.id = sru.session_id
3094
                WHERE
3095
                    sru.user_id = $userId AND
3096
                    s.id = $session_id AND
3097
                    sru.relation_type = ".SessionEntity::GENERAL_COACH."
3098
                ORDER BY s.access_start_date, s.access_end_date, s.title";
3099
        $result = Database::query($sql);
3100
        if (!empty($sessionIsCoach)) {
3101
            $sessionIsCoach = array_merge(
3102
                $sessionIsCoach,
3103
                Database::store_result($result)
3104
            );
3105
        } else {
3106
            $sessionIsCoach = Database::store_result($result);
3107
        }
3108
    }
3109
3110
    return count($sessionIsCoach) > 0;
3111
}
3112
3113
function api_user_has_role(string $role, ?User $user = null): bool
3114
{
3115
    if (null === $user) {
3116
        $user = api_get_current_user();
3117
    }
3118
3119
    if (null === $user) {
3120
        return false;
3121
    }
3122
3123
    return $user->hasRole($role);
3124
}
3125
3126
function api_is_allowed_in_course(): bool
3127
{
3128
    if (api_is_platform_admin()) {
3129
        return true;
3130
    }
3131
3132
    $user = api_get_current_user();
3133
    if ($user instanceof User) {
3134
        if ($user->hasRole('ROLE_CURRENT_COURSE_SESSION_STUDENT') ||
3135
            $user->hasRole('ROLE_CURRENT_COURSE_SESSION_TEACHER') ||
3136
            $user->hasRole('ROLE_CURRENT_COURSE_STUDENT') ||
3137
            $user->hasRole('ROLE_CURRENT_COURSE_TEACHER')
3138
        ) {
3139
            return true;
3140
        }
3141
    }
3142
3143
    return false;
3144
}
3145
3146
/**
3147
 * Checks whether current user is a student boss.
3148
 */
3149
function api_is_student_boss(?User $user = null): bool
3150
{
3151
    return api_user_has_role('ROLE_STUDENT_BOSS', $user);
3152
}
3153
3154
/**
3155
 * Checks whether the current user is a session administrator.
3156
 *
3157
 * @return bool True if current user is a course administrator
3158
 */
3159
function api_is_session_admin(?User $user = null)
3160
{
3161
    return api_user_has_role('ROLE_SESSION_MANAGER', $user);
3162
}
3163
3164
/**
3165
 * Checks whether the current user is a human resources manager.
3166
 *
3167
 * @return bool True if current user is a human resources manager
3168
 */
3169
function api_is_drh()
3170
{
3171
    return api_user_has_role('ROLE_HR');
3172
}
3173
3174
/**
3175
 * Checks whether the current user is a student.
3176
 *
3177
 * @return bool True if current user is a human resources manager
3178
 */
3179
function api_is_student()
3180
{
3181
    return api_user_has_role('ROLE_STUDENT');
3182
}
3183
3184
/**
3185
 * Checks whether the current user has the status 'teacher'.
3186
 *
3187
 * @return bool True if current user is a human resources manager
3188
 */
3189
function api_is_teacher()
3190
{
3191
    return api_user_has_role('ROLE_TEACHER');
3192
}
3193
3194
/**
3195
 * Checks whether the current user is a invited user.
3196
 *
3197
 * @return bool
3198
 */
3199
function api_is_invitee()
3200
{
3201
    return api_user_has_role('ROLE_INVITEE');
3202
}
3203
3204
/**
3205
 * This function checks whether a session is assigned into a category.
3206
 *
3207
 * @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...
3208
 * @param string    - category name
3209
 *
3210
 * @return bool - true if is found, otherwise false
3211
 */
3212
function api_is_session_in_category($session_id, $category_name)
3213
{
3214
    $session_id = (int) $session_id;
3215
    $category_name = Database::escape_string($category_name);
3216
    $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
3217
    $tbl_session_category = Database::get_main_table(TABLE_MAIN_SESSION_CATEGORY);
3218
3219
    $sql = "SELECT 1
3220
            FROM $tbl_session
3221
            WHERE $session_id IN (
3222
                SELECT s.id FROM $tbl_session s, $tbl_session_category sc
3223
                WHERE
3224
                  s.session_category_id = sc.id AND
3225
                  sc.name LIKE '%$category_name'
3226
            )";
3227
    $rs = Database::query($sql);
3228
3229
    if (Database::num_rows($rs) > 0) {
3230
        return true;
3231
    }
3232
3233
    return false;
3234
}
3235
3236
/**
3237
 * Displays options for switching between student view and course manager view.
3238
 *
3239
 * Changes in version 1.2 (Patrick Cool)
3240
 * Student view switch now behaves as a real switch. It maintains its current state until the state
3241
 * is changed explicitly
3242
 *
3243
 * Changes in version 1.1 (Patrick Cool)
3244
 * student view now works correctly in subfolders of the document tool
3245
 * student view works correctly in the new links tool
3246
 *
3247
 * Example code for using this in your tools:
3248
 * //if ($is_courseAdmin && api_get_setting('student_view_enabled') == 'true') {
3249
 * //   display_tool_view_option($isStudentView);
3250
 * //}
3251
 * //and in later sections, use api_is_allowed_to_edit()
3252
 *
3253
 * @author Roan Embrechts
3254
 * @author Patrick Cool
3255
 * @author Julio Montoya, changes added in Chamilo
3256
 *
3257
 * @version 1.2
3258
 *
3259
 * @todo rewrite code so it is easier to understand
3260
 */
3261
function api_display_tool_view_option()
3262
{
3263
    if ('true' != api_get_setting('student_view_enabled')) {
3264
        return '';
3265
    }
3266
3267
    $sourceurl = '';
3268
    $is_framed = false;
3269
    // Exceptions apply for all multi-frames pages
3270
    if (false !== strpos($_SERVER['REQUEST_URI'], 'chat/chat_banner.php')) {
3271
        // The chat is a multiframe bit that doesn't work too well with the student_view, so do not show the link
3272
        return '';
3273
    }
3274
3275
    // Uncomment to remove student view link from document view page
3276
    if (false !== strpos($_SERVER['REQUEST_URI'], 'lp/lp_header.php')) {
3277
        if (empty($_GET['lp_id'])) {
3278
            return '';
3279
        }
3280
        $sourceurl = substr($_SERVER['REQUEST_URI'], 0, strpos($_SERVER['REQUEST_URI'], '?'));
3281
        $sourceurl = str_replace(
3282
            'lp/lp_header.php',
3283
            'lp/lp_controller.php?'.api_get_cidreq().'&action=view&lp_id='.intval($_GET['lp_id']).'&isStudentView='.('studentview' == $_SESSION['studentview'] ? 'false' : 'true'),
3284
            $sourceurl
3285
        );
3286
        //showinframes doesn't handle student view anyway...
3287
        //return '';
3288
        $is_framed = true;
3289
    }
3290
3291
    // Check whether the $_SERVER['REQUEST_URI'] contains already url parameters (thus a questionmark)
3292
    if (!$is_framed) {
3293
        if (false === strpos($_SERVER['REQUEST_URI'], '?')) {
3294
            $sourceurl = api_get_self().'?'.api_get_cidreq();
3295
        } else {
3296
            $sourceurl = $_SERVER['REQUEST_URI'];
3297
        }
3298
    }
3299
3300
    $output_string = '';
3301
    if (!empty($_SESSION['studentview'])) {
3302
        if ('studentview' == $_SESSION['studentview']) {
3303
            // We have to remove the isStudentView=true from the $sourceurl
3304
            $sourceurl = str_replace('&isStudentView=true', '', $sourceurl);
3305
            $sourceurl = str_replace('&isStudentView=false', '', $sourceurl);
3306
            $output_string .= '<a class="btn btn--primary btn-sm" href="'.$sourceurl.'&isStudentView=false" target="_self">'.
3307
                Display::getMdiIcon('eye').' '.get_lang('Switch to teacher view').'</a>';
3308
        } elseif ('teacherview' == $_SESSION['studentview']) {
3309
            // Switching to teacherview
3310
            $sourceurl = str_replace('&isStudentView=true', '', $sourceurl);
3311
            $sourceurl = str_replace('&isStudentView=false', '', $sourceurl);
3312
            $output_string .= '<a class="btn btn--plain btn-sm" href="'.$sourceurl.'&isStudentView=true" target="_self">'.
3313
                Display::getMdiIcon('eye').' '.get_lang('Switch to student view').'</a>';
3314
        }
3315
    } else {
3316
        $output_string .= '<a class="btn btn--plain btn-sm" href="'.$sourceurl.'&isStudentView=true" target="_self">'.
3317
            Display::getMdiIcon('eye').' '.get_lang('Switch to student view').'</a>';
3318
    }
3319
    $output_string = Security::remove_XSS($output_string);
3320
    $html = Display::tag('div', $output_string, ['class' => 'view-options']);
3321
3322
    return $html;
3323
}
3324
3325
/**
3326
 * Function that removes the need to directly use is_courseAdmin global in
3327
 * tool scripts. It returns true or false depending on the user's rights in
3328
 * this particular course.
3329
 * Optionally checking for tutor and coach roles here allows us to use the
3330
 * student_view feature altogether with these roles as well.
3331
 *
3332
 * @param bool  Whether to check if the user has the tutor role
3333
 * @param bool  Whether to check if the user has the coach role
3334
 * @param bool  Whether to check if the user has the session coach role
3335
 * @param bool  check the student view or not
3336
 *
3337
 * @author Roan Embrechts
3338
 * @author Patrick Cool
3339
 * @author Julio Montoya
3340
 *
3341
 * @version 1.1, February 2004
3342
 *
3343
 * @return bool true: the user has the rights to edit, false: he does not
3344
 */
3345
function api_is_allowed_to_edit(
3346
    $tutor = false,
3347
    $coach = false,
3348
    $session_coach = false,
3349
    $check_student_view = true
3350
) {
3351
    $allowSessionAdminEdit = 'true' === api_get_setting('session.session_admins_edit_courses_content');
3352
    // Admins can edit anything.
3353
    if (api_is_platform_admin($allowSessionAdminEdit)) {
3354
        //The student preview was on
3355
        if ($check_student_view && api_is_student_view_active()) {
3356
            return false;
3357
        }
3358
3359
        return true;
3360
    }
3361
3362
    $sessionId = api_get_session_id();
3363
3364
    if ($sessionId && 'true' === api_get_setting('session.session_courses_read_only_mode')) {
3365
        $efv = new ExtraFieldValue('course');
3366
        $lockExrafieldField = $efv->get_values_by_handler_and_field_variable(
3367
            api_get_course_int_id(),
3368
            'session_courses_read_only_mode'
3369
        );
3370
3371
        if (!empty($lockExrafieldField['value'])) {
3372
            return false;
3373
        }
3374
    }
3375
3376
    $is_allowed_coach_to_edit = api_is_coach(null, null, $check_student_view);
3377
    $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

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

3452
    $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...
3453
        $sessionId,
3454
        null,
3455
        false
3456
    );
3457
3458
    if (SESSION_VISIBLE != $visibility && !empty($courseList)) {
3459
        // Course Coach session visibility.
3460
        $blockedCourseCount = 0;
3461
        $closedVisibilityList = [
3462
            COURSE_VISIBILITY_CLOSED,
3463
            COURSE_VISIBILITY_HIDDEN,
3464
        ];
3465
3466
        foreach ($courseList as $course) {
3467
            // Checking session visibility
3468
            $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

3468
            $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...
3469
                $sessionId,
3470
                $course['real_id']
3471
            );
3472
3473
            $courseIsVisible = !in_array(
3474
                $course['visibility'],
3475
                $closedVisibilityList
3476
            );
3477
            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

3477
            if (false === $courseIsVisible || /** @scrutinizer ignore-deprecated */ SESSION_INVISIBLE == $sessionCourseVisibility) {
Loading history...
3478
                $blockedCourseCount++;
3479
            }
3480
        }
3481
3482
        // If all courses are blocked then no show in the list.
3483
        if ($blockedCourseCount === count($courseList)) {
3484
            $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

3484
            $visibility = /** @scrutinizer ignore-deprecated */ SESSION_INVISIBLE;
Loading history...
3485
        } else {
3486
            $visibility = SESSION_VISIBLE;
3487
        }
3488
    }
3489
3490
    switch ($visibility) {
3491
        case SESSION_VISIBLE_READ_ONLY:
3492
        case SESSION_VISIBLE:
3493
        case SESSION_AVAILABLE:
3494
            return true;
3495
            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...
3496
        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

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

3526
            $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...
3527
            // if 5 the session is still available
3528
            switch ($session_visibility) {
3529
                case SESSION_VISIBLE_READ_ONLY: // 1
3530
                    return false;
3531
                case SESSION_VISIBLE:           // 2
3532
                    return true;
3533
                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

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

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

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

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

    return false;
}

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

Loading history...
5533
    $current_browser = $browser->getBrowser();
5534
    $a_versiontemp = explode('.', $browser->getVersion());
5535
    $current_majorver = $a_versiontemp[0];
5536
5537
    static $result;
5538
5539
    if (isset($result[$format])) {
5540
        return $result[$format];
5541
    }
5542
5543
    // Native svg support
5544
    if ('svg' == $format) {
5545
        if (('Internet Explorer' == $current_browser && $current_majorver >= 9) ||
5546
            ('Firefox' == $current_browser && $current_majorver > 1) ||
5547
            ('Safari' == $current_browser && $current_majorver >= 4) ||
5548
            ('Chrome' == $current_browser && $current_majorver >= 1) ||
5549
            ('Opera' == $current_browser && $current_majorver >= 9)
5550
        ) {
5551
            $result[$format] = true;
5552
5553
            return true;
5554
        } else {
5555
            $result[$format] = false;
5556
5557
            return false;
5558
        }
5559
    } elseif ('pdf' == $format) {
5560
        // native pdf support
5561
        if ('Chrome' == $current_browser && $current_majorver >= 6) {
5562
            $result[$format] = true;
5563
5564
            return true;
5565
        } else {
5566
            $result[$format] = false;
5567
5568
            return false;
5569
        }
5570
    } elseif ('tif' == $format || 'tiff' == $format) {
5571
        //native tif support
5572
        if ('Safari' == $current_browser && $current_majorver >= 5) {
5573
            $result[$format] = true;
5574
5575
            return true;
5576
        } else {
5577
            $result[$format] = false;
5578
5579
            return false;
5580
        }
5581
    } elseif ('ogg' == $format || 'ogx' == $format || 'ogv' == $format || 'oga' == $format) {
5582
        //native ogg, ogv,oga support
5583
        if (('Firefox' == $current_browser && $current_majorver >= 3) ||
5584
            ('Chrome' == $current_browser && $current_majorver >= 3) ||
5585
            ('Opera' == $current_browser && $current_majorver >= 9)) {
5586
            $result[$format] = true;
5587
5588
            return true;
5589
        } else {
5590
            $result[$format] = false;
5591
5592
            return false;
5593
        }
5594
    } elseif ('mpg' == $format || 'mpeg' == $format) {
5595
        //native mpg support
5596
        if (('Safari' == $current_browser && $current_majorver >= 5)) {
5597
            $result[$format] = true;
5598
5599
            return true;
5600
        } else {
5601
            $result[$format] = false;
5602
5603
            return false;
5604
        }
5605
    } elseif ('mp4' == $format) {
5606
        //native mp4 support (TODO: Android, iPhone)
5607
        if ('Android' == $current_browser || 'iPhone' == $current_browser) {
5608
            $result[$format] = true;
5609
5610
            return true;
5611
        } else {
5612
            $result[$format] = false;
5613
5614
            return false;
5615
        }
5616
    } elseif ('mov' == $format) {
5617
        //native mov support( TODO:check iPhone)
5618
        if ('Safari' == $current_browser && $current_majorver >= 5 || 'iPhone' == $current_browser) {
0 ignored issues
show
introduced by
Consider adding parentheses for clarity. Current Interpretation: ('Safari' == $current_br...ne' == $current_browser, Probably Intended Meaning: 'Safari' == $current_bro...e' == $current_browser)
Loading history...
5619
            $result[$format] = true;
5620
5621
            return true;
5622
        } else {
5623
            $result[$format] = false;
5624
5625
            return false;
5626
        }
5627
    } elseif ('avi' == $format) {
5628
        //native avi support
5629
        if ('Safari' == $current_browser && $current_majorver >= 5) {
5630
            $result[$format] = true;
5631
5632
            return true;
5633
        } else {
5634
            $result[$format] = false;
5635
5636
            return false;
5637
        }
5638
    } elseif ('wmv' == $format) {
5639
        //native wmv support
5640
        if ('Firefox' == $current_browser && $current_majorver >= 4) {
5641
            $result[$format] = true;
5642
5643
            return true;
5644
        } else {
5645
            $result[$format] = false;
5646
5647
            return false;
5648
        }
5649
    } elseif ('webm' == $format) {
5650
        //native webm support (TODO:check IE9, Chrome9, Android)
5651
        if (('Firefox' == $current_browser && $current_majorver >= 4) ||
5652
            ('Opera' == $current_browser && $current_majorver >= 9) ||
5653
            ('Internet Explorer' == $current_browser && $current_majorver >= 9) ||
5654
            ('Chrome' == $current_browser && $current_majorver >= 9) ||
5655
            'Android' == $current_browser
5656
        ) {
5657
            $result[$format] = true;
5658
5659
            return true;
5660
        } else {
5661
            $result[$format] = false;
5662
5663
            return false;
5664
        }
5665
    } elseif ('wav' == $format) {
5666
        //native wav support (only some codecs !)
5667
        if (('Firefox' == $current_browser && $current_majorver >= 4) ||
5668
            ('Safari' == $current_browser && $current_majorver >= 5) ||
5669
            ('Opera' == $current_browser && $current_majorver >= 9) ||
5670
            ('Internet Explorer' == $current_browser && $current_majorver >= 9) ||
5671
            ('Chrome' == $current_browser && $current_majorver > 9) ||
5672
            'Android' == $current_browser ||
5673
            'iPhone' == $current_browser
5674
        ) {
5675
            $result[$format] = true;
5676
5677
            return true;
5678
        } else {
5679
            $result[$format] = false;
5680
5681
            return false;
5682
        }
5683
    } elseif ('mid' == $format || 'kar' == $format) {
5684
        //native midi support (TODO:check Android)
5685
        if ('Opera' == $current_browser && $current_majorver >= 9 || 'Android' == $current_browser) {
0 ignored issues
show
introduced by
Consider adding parentheses for clarity. Current Interpretation: ('Opera' == $current_bro...id' == $current_browser, Probably Intended Meaning: 'Opera' == $current_brow...d' == $current_browser)
Loading history...
5686
            $result[$format] = true;
5687
5688
            return true;
5689
        } else {
5690
            $result[$format] = false;
5691
5692
            return false;
5693
        }
5694
    } elseif ('wma' == $format) {
5695
        //native wma support
5696
        if ('Firefox' == $current_browser && $current_majorver >= 4) {
5697
            $result[$format] = true;
5698
5699
            return true;
5700
        } else {
5701
            $result[$format] = false;
5702
5703
            return false;
5704
        }
5705
    } elseif ('au' == $format) {
5706
        //native au support
5707
        if ('Safari' == $current_browser && $current_majorver >= 5) {
5708
            $result[$format] = true;
5709
5710
            return true;
5711
        } else {
5712
            $result[$format] = false;
5713
5714
            return false;
5715
        }
5716
    } elseif ('mp3' == $format) {
5717
        //native mp3 support (TODO:check Android, iPhone)
5718
        if (('Safari' == $current_browser && $current_majorver >= 5) ||
5719
            ('Chrome' == $current_browser && $current_majorver >= 6) ||
5720
            ('Internet Explorer' == $current_browser && $current_majorver >= 9) ||
5721
            'Android' == $current_browser ||
5722
            'iPhone' == $current_browser ||
5723
            'Firefox' == $current_browser
5724
        ) {
5725
            $result[$format] = true;
5726
5727
            return true;
5728
        } else {
5729
            $result[$format] = false;
5730
5731
            return false;
5732
        }
5733
    } elseif ('autocapitalize' == $format) {
5734
        // Help avoiding showing the autocapitalize option if the browser doesn't
5735
        // support it: this attribute is against the HTML5 standard
5736
        if ('Safari' == $current_browser || 'iPhone' == $current_browser) {
5737
            return true;
5738
        } else {
5739
            return false;
5740
        }
5741
    } elseif ("check_browser" == $format) {
5742
        $array_check_browser = [$current_browser, $current_majorver];
5743
5744
        return $array_check_browser;
5745
    } else {
5746
        $result[$format] = false;
5747
5748
        return false;
5749
    }
5750
}
5751
5752
/**
5753
 * This function checks if exist path and file browscap.ini
5754
 * In order for this to work, your browscap configuration setting in php.ini
5755
 * must point to the correct location of the browscap.ini file on your system
5756
 * http://php.net/manual/en/function.get-browser.php.
5757
 *
5758
 * @return bool
5759
 *
5760
 * @author Juan Carlos Raña Trabado
5761
 */
5762
function api_check_browscap()
5763
{
5764
    $setting = ini_get('browscap');
5765
    if ($setting) {
5766
        $browser = get_browser($_SERVER['HTTP_USER_AGENT'], true);
5767
        if (strpos($setting, 'browscap.ini') && !empty($browser)) {
5768
            return true;
5769
        }
5770
    }
5771
5772
    return false;
5773
}
5774
5775
/**
5776
 * Returns the <script> HTML tag.
5777
 */
5778
function api_get_js($file)
5779
{
5780
    return '<script src="'.api_get_path(WEB_LIBRARY_PATH).'javascript/'.$file.'"></script>'."\n";
5781
}
5782
5783
function api_get_build_js($file)
5784
{
5785
    return '<script src="'.api_get_path(WEB_PUBLIC_PATH).'build/'.$file.'"></script>'."\n";
5786
}
5787
5788
function api_get_build_css($file, $media = 'screen')
5789
{
5790
    return '<link
5791
        href="'.api_get_path(WEB_PUBLIC_PATH).'build/'.$file.'" rel="stylesheet" media="'.$media.'" type="text/css" />'."\n";
5792
}
5793
5794
/**
5795
 * Returns the <script> HTML tag.
5796
 *
5797
 * @return string
5798
 */
5799
function api_get_asset($file)
5800
{
5801
    return '<script src="'.api_get_path(WEB_PUBLIC_PATH).'build/libs/'.$file.'"></script>'."\n";
5802
}
5803
5804
/**
5805
 * Returns the <script> HTML tag.
5806
 *
5807
 * @param string $file
5808
 * @param string $media
5809
 *
5810
 * @return string
5811
 */
5812
function api_get_css_asset($file, $media = 'screen')
5813
{
5814
    return '<link
5815
        href="'.api_get_path(WEB_PUBLIC_PATH).'build/libs/'.$file.'"
5816
        rel="stylesheet" media="'.$media.'" type="text/css" />'."\n";
5817
}
5818
5819
/**
5820
 * Returns the <link> HTML tag.
5821
 *
5822
 * @param string $file
5823
 * @param string $media
5824
 */
5825
function api_get_css($file, $media = 'screen')
5826
{
5827
    return '<link href="'.$file.'" rel="stylesheet" media="'.$media.'" type="text/css" />'."\n";
5828
}
5829
5830
function api_get_bootstrap_and_font_awesome($returnOnlyPath = false, $returnFileLocation = false)
5831
{
5832
    $url = api_get_path(WEB_PUBLIC_PATH).'build/css/bootstrap.css';
5833
5834
    if ($returnOnlyPath) {
5835
        if ($returnFileLocation) {
5836
            return api_get_path(SYS_PUBLIC_PATH).'build/css/bootstrap.css';
5837
        }
5838
5839
        return $url;
5840
    }
5841
5842
    return '<link href="'.$url.'" rel="stylesheet" type="text/css" />'."\n";
5843
}
5844
5845
/**
5846
 * Returns the js header to include the jquery library.
5847
 */
5848
function api_get_jquery_js()
5849
{
5850
    return api_get_asset('jquery/jquery.min.js');
5851
}
5852
5853
/**
5854
 * Returns the jquery path.
5855
 *
5856
 * @return string
5857
 */
5858
function api_get_jquery_web_path()
5859
{
5860
    return api_get_path(WEB_PUBLIC_PATH).'assets/jquery/jquery.min.js';
5861
}
5862
5863
/**
5864
 * @return string
5865
 */
5866
function api_get_jquery_ui_js_web_path()
5867
{
5868
    return api_get_path(WEB_PUBLIC_PATH).'assets/jquery-ui/jquery-ui.min.js';
5869
}
5870
5871
/**
5872
 * @return string
5873
 */
5874
function api_get_jquery_ui_css_web_path()
5875
{
5876
    return api_get_path(WEB_PUBLIC_PATH).'assets/jquery-ui/themes/smoothness/jquery-ui.min.css';
5877
}
5878
5879
/**
5880
 * Returns the jquery-ui library js headers.
5881
 *
5882
 * @return string html tags
5883
 */
5884
function api_get_jquery_ui_js()
5885
{
5886
    $libraries = [];
5887
5888
    return api_get_jquery_libraries_js($libraries);
5889
}
5890
5891
function api_get_jqgrid_js()
5892
{
5893
    return api_get_build_css('legacy_free-jqgrid.css').PHP_EOL
5894
        .api_get_build_js('legacy_free-jqgrid.js');
5895
}
5896
5897
/**
5898
 * Returns the jquery library js and css headers.
5899
 *
5900
 * @param   array   list of jquery libraries supported jquery-ui
5901
 * @param   bool    add the jquery library
5902
 *
5903
 * @return string html tags
5904
 */
5905
function api_get_jquery_libraries_js($libraries)
5906
{
5907
    $js = '';
5908
5909
    //Document multiple upload funcionality
5910
    if (in_array('jquery-uploadzs', $libraries)) {
5911
        $js .= api_get_asset('blueimp-load-image/js/load-image.all.min.js');
5912
        $js .= api_get_asset('blueimp-canvas-to-blob/js/canvas-to-blob.min.js');
5913
        $js .= api_get_asset('jquery-file-upload/js/jquery.iframe-transport.js');
5914
        $js .= api_get_asset('jquery-file-upload/js/jquery.fileupload.js');
5915
        $js .= api_get_asset('jquery-file-upload/js/jquery.fileupload-process.js');
5916
        $js .= api_get_asset('jquery-file-upload/js/jquery.fileupload-image.js');
5917
        $js .= api_get_asset('jquery-file-upload/js/jquery.fileupload-audio.js');
5918
        $js .= api_get_asset('jquery-file-upload/js/jquery.fileupload-video.js');
5919
        $js .= api_get_asset('jquery-file-upload/js/jquery.fileupload-validate.js');
5920
5921
        $js .= api_get_css(api_get_path(WEB_PUBLIC_PATH).'assets/jquery-file-upload/css/jquery.fileupload.css');
5922
        $js .= api_get_css(api_get_path(WEB_PUBLIC_PATH).'assets/jquery-file-upload/css/jquery.fileupload-ui.css');
5923
    }
5924
5925
    // jquery datepicker
5926
    if (in_array('datepicker', $libraries)) {
5927
        $languaje = 'en-GB';
5928
        $platform_isocode = strtolower(api_get_language_isocode());
5929
5930
        $datapicker_langs = [
5931
            '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',
5932
        ];
5933
        if (in_array($platform_isocode, $datapicker_langs)) {
5934
            $languaje = $platform_isocode;
5935
        }
5936
5937
        $js .= api_get_js('jquery-ui/jquery-ui-i18n.min.js');
5938
        $script = '<script>
5939
        $(function(){
5940
            $.datepicker.setDefaults($.datepicker.regional["'.$languaje.'"]);
5941
            $.datepicker.regional["local"] = $.datepicker.regional["'.$languaje.'"];
5942
        });
5943
        </script>
5944
        ';
5945
        $js .= $script;
5946
    }
5947
5948
    return $js;
5949
}
5950
5951
/**
5952
 * Returns the URL to the course or session, removing the complexity of the URL
5953
 * building piece by piece.
5954
 *
5955
 * This function relies on api_get_course_info()
5956
 *
5957
 * @param int $courseId  The course code - optional (takes it from context if not given)
5958
 * @param int $sessionId The session ID  - optional (takes it from context if not given)
5959
 * @param int $groupId   The group ID - optional (takes it from context if not given)
5960
 *
5961
 * @return string The URL to a course, a session, or empty string if nothing works
5962
 *                e.g. https://localhost/courses/ABC/index.php?session_id=3&gidReq=1
5963
 *
5964
 * @author  Julio Montoya
5965
 */
5966
function api_get_course_url($courseId = null, $sessionId = null, $groupId = null)
5967
{
5968
    $url = '';
5969
    // If courseCode not set, get context or []
5970
    if (empty($courseId)) {
5971
        $courseId = api_get_course_int_id();
5972
    }
5973
5974
    // If sessionId not set, get context or 0
5975
    if (empty($sessionId)) {
5976
        $sessionId = api_get_session_id();
5977
    }
5978
5979
    // If groupId not set, get context or 0
5980
    if (empty($groupId)) {
5981
        $groupId = api_get_group_id();
5982
    }
5983
5984
    // Build the URL
5985
    if (!empty($courseId)) {
5986
        $webCourseHome = '/course/'.$courseId.'/home';
5987
        // directory not empty, so we do have a course
5988
        $url = $webCourseHome.'?sid='.$sessionId.'&gid='.$groupId;
5989
    } else {
5990
        if (!empty($sessionId) && 'true' !== api_get_setting('session.remove_session_url')) {
5991
            // if the course was unset and the session was set, send directly to the session
5992
            $url = api_get_path(WEB_CODE_PATH).'session/index.php?session_id='.$sessionId;
5993
        }
5994
    }
5995
5996
    // if not valid combination was found, return an empty string
5997
    return $url;
5998
}
5999
6000
/**
6001
 * Check if there is more than the default URL defined in the access_url table.
6002
 */
6003
function api_get_multiple_access_url(): bool
6004
{
6005
    return Container::getAccessUrlHelper()->isMultiple();
6006
}
6007
6008
/**
6009
 * @deprecated Use AccessUrlHelper::isMultiple
6010
 */
6011
function api_is_multiple_url_enabled(): bool
6012
{
6013
    return api_get_multiple_access_url();
6014
}
6015
6016
/**
6017
 * Returns a md5 unique id.
6018
 *
6019
 * @todo add more parameters
6020
 */
6021
function api_get_unique_id()
6022
{
6023
    return md5(time().uniqid().api_get_user_id().api_get_course_id().api_get_session_id());
6024
}
6025
6026
/**
6027
 * @param int Course id
6028
 * @param int tool id: TOOL_QUIZ, TOOL_FORUM, TOOL_STUDENTPUBLICATION, TOOL_LEARNPATH
6029
 * @param int the item id (tool id, exercise id, lp id)
6030
 *
6031
 * @return bool
6032
 */
6033
function api_resource_is_locked_by_gradebook($item_id, $link_type, $course_code = null)
6034
{
6035
    if (api_is_platform_admin()) {
6036
        return false;
6037
    }
6038
    if ('true' === api_get_setting('gradebook_locking_enabled')) {
6039
        if (empty($course_code)) {
6040
            $course_code = api_get_course_id();
6041
        }
6042
        $table = Database::get_main_table(TABLE_MAIN_GRADEBOOK_LINK);
6043
        $item_id = (int) $item_id;
6044
        $link_type = (int) $link_type;
6045
        $course_code = Database::escape_string($course_code);
6046
        $sql = "SELECT locked FROM $table
6047
                WHERE locked = 1 AND ref_id = $item_id AND type = $link_type AND course_code = '$course_code' ";
6048
        $result = Database::query($sql);
6049
        if (Database::num_rows($result)) {
6050
            return true;
6051
        }
6052
    }
6053
6054
    return false;
6055
}
6056
6057
/**
6058
 * Blocks a page if the item was added in a gradebook.
6059
 *
6060
 * @param int       exercise id, work id, thread id,
6061
 * @param int       LINK_EXERCISE, LINK_STUDENTPUBLICATION, LINK_LEARNPATH LINK_FORUM_THREAD, LINK_ATTENDANCE
6062
 * see gradebook/lib/be/linkfactory
6063
 * @param string    course code
6064
 *
6065
 * @return false|null
6066
 */
6067
function api_block_course_item_locked_by_gradebook($item_id, $link_type, $course_code = null)
6068
{
6069
    if (api_is_platform_admin()) {
6070
        return false;
6071
    }
6072
6073
    if (api_resource_is_locked_by_gradebook($item_id, $link_type, $course_code)) {
6074
        $message = Display::return_message(
6075
            get_lang(
6076
                '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.'
6077
            ),
6078
            'warning'
6079
        );
6080
        api_not_allowed(true, $message);
6081
    }
6082
}
6083
6084
/**
6085
 * Checks the PHP version installed is enough to run Chamilo.
6086
 *
6087
 * @param string Include path (used to load the error page)
6088
 */
6089
function api_check_php_version()
6090
{
6091
    if (!function_exists('version_compare') ||
6092
        version_compare(PHP_VERSION, REQUIRED_PHP_VERSION, '<')
6093
    ) {
6094
        throw new Exception('Wrong PHP version');
6095
    }
6096
}
6097
6098
/**
6099
 * Checks whether the Archive directory is present and writeable. If not,
6100
 * prints a warning message.
6101
 */
6102
function api_check_archive_dir()
6103
{
6104
    if (is_dir(api_get_path(SYS_ARCHIVE_PATH)) && !is_writable(api_get_path(SYS_ARCHIVE_PATH))) {
6105
        $message = Display::return_message(
6106
            get_lang(
6107
                'The var/cache/ directory, used by this tool, is not writeable. Please contact your platform administrator.'
6108
            ),
6109
            'warning'
6110
        );
6111
        api_not_allowed(true, $message);
6112
    }
6113
}
6114
6115
/**
6116
 * Returns an array of global configuration settings which should be ignored
6117
 * when printing the configuration settings screens.
6118
 *
6119
 * @return array Array of strings, each identifying one of the excluded settings
6120
 */
6121
function api_get_locked_settings()
6122
{
6123
    return [
6124
        'permanently_remove_deleted_files',
6125
        'account_valid_duration',
6126
        'service_ppt2lp',
6127
        'wcag_anysurfer_public_pages',
6128
        'upload_extensions_list_type',
6129
        'upload_extensions_blacklist',
6130
        'upload_extensions_whitelist',
6131
        'upload_extensions_skip',
6132
        'upload_extensions_replace_by',
6133
        'hide_dltt_markup',
6134
        'split_users_upload_directory',
6135
        'permissions_for_new_directories',
6136
        'permissions_for_new_files',
6137
        'platform_charset',
6138
        'ldap_description',
6139
        'cas_activate',
6140
        'cas_server',
6141
        'cas_server_uri',
6142
        'cas_port',
6143
        'cas_protocol',
6144
        'cas_add_user_activate',
6145
        'update_user_info_cas_with_ldap',
6146
        'languagePriority1',
6147
        'languagePriority2',
6148
        'languagePriority3',
6149
        'languagePriority4',
6150
        'login_is_email',
6151
        'chamilo_database_version',
6152
    ];
6153
}
6154
6155
/**
6156
 * Guess the real ip for register in the database, even in reverse proxy cases.
6157
 * To be recognized, the IP has to be found in either $_SERVER['REMOTE_ADDR'] or
6158
 * in $_SERVER['HTTP_X_FORWARDED_FOR'], which is in common use with rproxies.
6159
 * Note: the result of this function is not SQL-safe. Please escape it before
6160
 * inserting in a database.
6161
 *
6162
 * @return string the user's real ip (unsafe - escape it before inserting to db)
6163
 *
6164
 * @author Jorge Frisancho Jibaja <[email protected]>, USIL - Some changes to allow the use of real IP using reverse proxy
6165
 *
6166
 * @version CEV CHANGE 24APR2012
6167
 * @throws RuntimeException
6168
 */
6169
function api_get_real_ip(): string
6170
{
6171
    if ('cli' === PHP_SAPI) {
6172
        $ip = '127.0.0.1';
6173
    } else {
6174
        $ip = trim($_SERVER['REMOTE_ADDR']);
6175
        if (empty($ip)) {
6176
            throw new RuntimeException("Unable to retrieve remote IP address.");
6177
        }
6178
    }
6179
    if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
6180
        if (preg_match('/,/', $_SERVER['HTTP_X_FORWARDED_FOR'])) {
6181
            @list($ip1, $ip2) = @explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
6182
        } else {
6183
            $ip1 = $_SERVER['HTTP_X_FORWARDED_FOR'];
6184
        }
6185
        $ip = trim($ip1);
6186
    }
6187
6188
    return $ip;
6189
}
6190
6191
/**
6192
 * Checks whether an IP is included inside an IP range.
6193
 *
6194
 * @param string IP address
6195
 * @param string IP range
6196
 * @param string $ip
6197
 *
6198
 * @return bool True if IP is in the range, false otherwise
6199
 *
6200
 * @author claudiu at cnixs dot com  on http://www.php.net/manual/fr/ref.network.php#55230
6201
 * @author Yannick Warnier for improvements and managment of multiple ranges
6202
 *
6203
 * @todo check for IPv6 support
6204
 */
6205
function api_check_ip_in_range($ip, $range)
6206
{
6207
    if (empty($ip) or empty($range)) {
6208
        return false;
6209
    }
6210
    $ip_ip = ip2long($ip);
6211
    // divide range param into array of elements
6212
    if (false !== strpos($range, ',')) {
6213
        $ranges = explode(',', $range);
6214
    } else {
6215
        $ranges = [$range];
6216
    }
6217
    foreach ($ranges as $range) {
0 ignored issues
show
introduced by
$range is overwriting one of the parameters of this function.
Loading history...
6218
        $range = trim($range);
6219
        if (empty($range)) {
6220
            continue;
6221
        }
6222
        if (false === strpos($range, '/')) {
6223
            if (0 === strcmp($ip, $range)) {
6224
                return true; // there is a direct IP match, return OK
6225
            }
6226
            continue; //otherwise, get to the next range
6227
        }
6228
        // the range contains a "/", so analyse completely
6229
        [$net, $mask] = explode("/", $range);
6230
6231
        $ip_net = ip2long($net);
6232
        // mask binary magic
6233
        $ip_mask = ~((1 << (32 - $mask)) - 1);
6234
6235
        $ip_ip_net = $ip_ip & $ip_mask;
6236
        if ($ip_ip_net == $ip_net) {
6237
            return true;
6238
        }
6239
    }
6240
6241
    return false;
6242
}
6243
6244
function api_check_user_access_to_legal($courseInfo)
6245
{
6246
    if (empty($courseInfo)) {
6247
        return false;
6248
    }
6249
6250
    $visibility = (int) $courseInfo['visibility'];
6251
    $visibilityList = [COURSE_VISIBILITY_OPEN_WORLD, COURSE_VISIBILITY_OPEN_PLATFORM];
6252
6253
    return
6254
        in_array($visibility, $visibilityList) ||
6255
        api_is_drh() ||
6256
        (COURSE_VISIBILITY_REGISTERED === $visibility && 1 === (int) $courseInfo['subscribe']);
6257
}
6258
6259
/**
6260
 * Checks if the global chat is enabled or not.
6261
 *
6262
 * @return bool
6263
 */
6264
function api_is_global_chat_enabled()
6265
{
6266
    return
6267
        !api_is_anonymous() &&
6268
        'true' === api_get_setting('allow_global_chat') &&
6269
        'true' === api_get_setting('allow_social_tool');
6270
}
6271
6272
/**
6273
 * @param int   $item_id
6274
 * @param int   $tool_id
6275
 * @param int   $group_id   id
6276
 * @param array $courseInfo
6277
 * @param int   $sessionId
6278
 * @param int   $userId
6279
 *
6280
 * @deprecated
6281
 */
6282
function api_set_default_visibility(
6283
    $item_id,
6284
    $tool_id,
6285
    $group_id = 0,
6286
    $courseInfo = [],
6287
    $sessionId = 0,
6288
    $userId = 0
6289
) {
6290
    $courseInfo = empty($courseInfo) ? api_get_course_info() : $courseInfo;
6291
    $courseId = $courseInfo['real_id'];
6292
    $courseCode = $courseInfo['code'];
6293
    $sessionId = empty($sessionId) ? api_get_session_id() : $sessionId;
6294
    $userId = empty($userId) ? api_get_user_id() : $userId;
6295
6296
    // if group is null force group_id = 0, this force is needed to create a LP folder with group = 0
6297
    if (is_null($group_id)) {
6298
        $group_id = 0;
6299
    } else {
6300
        $group_id = empty($group_id) ? api_get_group_id() : $group_id;
6301
    }
6302
6303
    $groupInfo = [];
6304
    if (!empty($group_id)) {
6305
        $groupInfo = GroupManager::get_group_properties($group_id);
6306
    }
6307
    $original_tool_id = $tool_id;
6308
6309
    switch ($tool_id) {
6310
        case TOOL_LINK:
6311
        case TOOL_LINK_CATEGORY:
6312
            $tool_id = 'links';
6313
            break;
6314
        case TOOL_DOCUMENT:
6315
            $tool_id = 'documents';
6316
            break;
6317
        case TOOL_LEARNPATH:
6318
            $tool_id = 'learning';
6319
            break;
6320
        case TOOL_ANNOUNCEMENT:
6321
            $tool_id = 'announcements';
6322
            break;
6323
        case TOOL_FORUM:
6324
        case TOOL_FORUM_CATEGORY:
6325
        case TOOL_FORUM_THREAD:
6326
            $tool_id = 'forums';
6327
            break;
6328
        case TOOL_QUIZ:
6329
            $tool_id = 'quiz';
6330
            break;
6331
    }
6332
    $setting = api_get_setting('tool_visible_by_default_at_creation');
6333
6334
    if (isset($setting[$tool_id])) {
6335
        $visibility = 'invisible';
6336
        if ('true' === $setting[$tool_id]) {
6337
            $visibility = 'visible';
6338
        }
6339
6340
        // Read the portal and course default visibility
6341
        if ('documents' === $tool_id) {
6342
            $visibility = DocumentManager::getDocumentDefaultVisibility($courseInfo);
6343
        }
6344
6345
        // Fixes default visibility for tests
6346
        switch ($original_tool_id) {
6347
            case TOOL_QUIZ:
6348
                if (empty($sessionId)) {
6349
                    $objExerciseTmp = new Exercise($courseId);
6350
                    $objExerciseTmp->read($item_id);
6351
                    if ('visible' === $visibility) {
6352
                        $objExerciseTmp->enable();
6353
                        $objExerciseTmp->save();
6354
                    } else {
6355
                        $objExerciseTmp->disable();
6356
                        $objExerciseTmp->save();
6357
                    }
6358
                }
6359
                break;
6360
        }
6361
    }
6362
}
6363
6364
function api_get_roles()
6365
{
6366
    $hierarchy = Container::$container->getParameter('security.role_hierarchy.roles');
6367
    $roles = [];
6368
    array_walk_recursive($hierarchy, function ($role) use (&$roles) {
6369
        $roles[$role] = $role;
6370
    });
6371
6372
    return $roles;
6373
}
6374
6375
function api_get_user_roles(): array
6376
{
6377
    $permissionService = Container::$container->get(PermissionServiceHelper::class);
6378
6379
    $roles = $permissionService->getUserRoles();
6380
6381
    return array_combine($roles, $roles);
6382
}
6383
6384
/**
6385
 * @param string $file
6386
 *
6387
 * @return string
6388
 */
6389
function api_get_js_simple($file)
6390
{
6391
    return '<script type="text/javascript" src="'.$file.'"></script>'."\n";
6392
}
6393
6394
/**
6395
 * Modify default memory_limit and max_execution_time limits
6396
 * Needed when processing long tasks.
6397
 */
6398
function api_set_more_memory_and_time_limits()
6399
{
6400
    if (function_exists('ini_set')) {
6401
        api_set_memory_limit('256M');
6402
        ini_set('max_execution_time', 1800);
6403
    }
6404
}
6405
6406
/**
6407
 * Tries to set memory limit, if authorized and new limit is higher than current.
6408
 *
6409
 * @param string $mem New memory limit
6410
 *
6411
 * @return bool True on success, false on failure or current is higher than suggested
6412
 * @assert (null) === false
6413
 * @assert (-1) === false
6414
 * @assert (0) === true
6415
 * @assert ('1G') === true
6416
 */
6417
function api_set_memory_limit($mem)
6418
{
6419
    //if ini_set() not available, this function is useless
6420
    if (!function_exists('ini_set') || is_null($mem) || -1 == $mem) {
6421
        return false;
6422
    }
6423
6424
    $memory_limit = ini_get('memory_limit');
6425
    if (api_get_bytes_memory_limit($mem) > api_get_bytes_memory_limit($memory_limit)) {
6426
        ini_set('memory_limit', $mem);
6427
6428
        return true;
6429
    }
6430
6431
    return false;
6432
}
6433
6434
/**
6435
 * Gets memory limit in bytes.
6436
 *
6437
 * @param string The memory size (128M, 1G, 1000K, etc)
6438
 *
6439
 * @return int
6440
 * @assert (null) === false
6441
 * @assert ('1t')  === 1099511627776
6442
 * @assert ('1g')  === 1073741824
6443
 * @assert ('1m')  === 1048576
6444
 * @assert ('100k') === 102400
6445
 */
6446
function api_get_bytes_memory_limit($mem)
6447
{
6448
    $size = strtolower(substr($mem, -1));
6449
6450
    switch ($size) {
6451
        case 't':
6452
            $mem = (int) substr($mem, -1) * 1024 * 1024 * 1024 * 1024;
6453
            break;
6454
        case 'g':
6455
            $mem = (int) substr($mem, 0, -1) * 1024 * 1024 * 1024;
6456
            break;
6457
        case 'm':
6458
            $mem = (int) substr($mem, 0, -1) * 1024 * 1024;
6459
            break;
6460
        case 'k':
6461
            $mem = (int) substr($mem, 0, -1) * 1024;
6462
            break;
6463
        default:
6464
            // we assume it's integer only
6465
            $mem = (int) $mem;
6466
            break;
6467
    }
6468
6469
    return $mem;
6470
}
6471
6472
/**
6473
 * Finds all the information about a user from username instead of user id.
6474
 *
6475
 * @param string $officialCode
6476
 *
6477
 * @return array $user_info user_id, lastname, firstname, username, email, ...
6478
 *
6479
 * @author Yannick Warnier <[email protected]>
6480
 */
6481
function api_get_user_info_from_official_code($officialCode)
6482
{
6483
    if (empty($officialCode)) {
6484
        return false;
6485
    }
6486
    $sql = "SELECT * FROM ".Database::get_main_table(TABLE_MAIN_USER)."
6487
            WHERE official_code ='".Database::escape_string($officialCode)."'";
6488
    $result = Database::query($sql);
6489
    if (Database::num_rows($result) > 0) {
6490
        $result_array = Database::fetch_array($result);
6491
6492
        return _api_format_user($result_array);
6493
    }
6494
6495
    return false;
6496
}
6497
6498
/**
6499
 * @param string $usernameInputId
6500
 * @param string $passwordInputId
6501
 *
6502
 * @return string|null
6503
 */
6504
function api_get_password_checker_js($usernameInputId, $passwordInputId)
6505
{
6506
    $checkPass = api_get_setting('allow_strength_pass_checker');
6507
    $useStrengthPassChecker = 'true' === $checkPass;
6508
6509
    if (false === $useStrengthPassChecker) {
6510
        return null;
6511
    }
6512
6513
    $minRequirements = Security::getPasswordRequirements()['min'];
6514
6515
    $options = [
6516
        'rules' => [],
6517
    ];
6518
6519
    if ($minRequirements['length'] > 0) {
6520
        $options['rules'][] = [
6521
            'minChar' => $minRequirements['length'],
6522
            'pattern' => '.',
6523
            'helpText' => sprintf(
6524
                get_lang('Minimum %s characters in total'),
6525
                $minRequirements['length']
6526
            ),
6527
        ];
6528
    }
6529
6530
    if ($minRequirements['lowercase'] > 0) {
6531
        $options['rules'][] = [
6532
            'minChar' => $minRequirements['lowercase'],
6533
            'pattern' => '[a-z]',
6534
            'helpText' => sprintf(
6535
                get_lang('Minimum %s lowercase characters'),
6536
                $minRequirements['lowercase']
6537
            ),
6538
        ];
6539
    }
6540
6541
    if ($minRequirements['uppercase'] > 0) {
6542
        $options['rules'][] = [
6543
            'minChar' => $minRequirements['uppercase'],
6544
            'pattern' => '[A-Z]',
6545
            'helpText' => sprintf(
6546
                get_lang('Minimum %s uppercase characters'),
6547
                $minRequirements['uppercase']
6548
            ),
6549
        ];
6550
    }
6551
6552
    if ($minRequirements['numeric'] > 0) {
6553
        $options['rules'][] = [
6554
            'minChar' => $minRequirements['numeric'],
6555
            'pattern' => '[0-9]',
6556
            'helpText' => sprintf(
6557
                get_lang('Minimum %s numerical (0-9) characters'),
6558
                $minRequirements['numeric']
6559
            ),
6560
        ];
6561
    }
6562
6563
    if ($minRequirements['specials'] > 0) {
6564
        $options['rules'][] = [
6565
            'minChar' => $minRequirements['specials'],
6566
            'pattern' => '[!"#$%&\'()*+,\-./\\\:;<=>?@[\\]^_`{|}~]',
6567
            'helpText' => sprintf(
6568
                get_lang('Minimum %s special characters'),
6569
                $minRequirements['specials']
6570
            ),
6571
        ];
6572
    }
6573
6574
    $js = api_get_js('password-checker/password-checker.js');
6575
    $js .= "<script>
6576
    $(function() {
6577
        $('".$passwordInputId."').passwordChecker(".json_encode($options).");
6578
    });
6579
    </script>";
6580
6581
    return $js;
6582
}
6583
6584
/**
6585
 * create an user extra field called 'captcha_blocked_until_date'.
6586
 *
6587
 * @param string $username
6588
 *
6589
 * @return bool
6590
 */
6591
function api_block_account_captcha($username)
6592
{
6593
    $userInfo = api_get_user_info_from_username($username);
6594
    if (empty($userInfo)) {
6595
        return false;
6596
    }
6597
    $minutesToBlock = api_get_setting('captcha_time_to_block');
6598
    $time = time() + $minutesToBlock * 60;
6599
    UserManager::update_extra_field_value(
6600
        $userInfo['user_id'],
6601
        'captcha_blocked_until_date',
6602
        api_get_utc_datetime($time)
6603
    );
6604
6605
    return true;
6606
}
6607
6608
/**
6609
 * @param string $username
6610
 *
6611
 * @return bool
6612
 */
6613
function api_clean_account_captcha($username)
6614
{
6615
    $userInfo = api_get_user_info_from_username($username);
6616
    if (empty($userInfo)) {
6617
        return false;
6618
    }
6619
    Session::erase('loginFailedCount');
6620
    UserManager::update_extra_field_value(
6621
        $userInfo['user_id'],
6622
        'captcha_blocked_until_date',
6623
        null
6624
    );
6625
6626
    return true;
6627
}
6628
6629
/**
6630
 * @param string $username
6631
 *
6632
 * @return bool
6633
 */
6634
function api_get_user_blocked_by_captcha($username)
6635
{
6636
    $userInfo = api_get_user_info_from_username($username);
6637
    if (empty($userInfo)) {
6638
        return false;
6639
    }
6640
    $data = UserManager::get_extra_user_data_by_field(
6641
        $userInfo['user_id'],
6642
        'captcha_blocked_until_date'
6643
    );
6644
    if (isset($data) && isset($data['captcha_blocked_until_date'])) {
6645
        return $data['captcha_blocked_until_date'];
6646
    }
6647
6648
    return false;
6649
}
6650
6651
/**
6652
 * If true, the drh can access all content (courses, users) inside a session.
6653
 *
6654
 * @return bool
6655
 */
6656
function api_drh_can_access_all_session_content()
6657
{
6658
    return 'true' === api_get_setting('drh_can_access_all_session_content');
6659
}
6660
6661
/**
6662
 * Checks if user can login as another user.
6663
 *
6664
 * @param int $loginAsUserId the user id to log in
6665
 * @param int $userId        my user id
6666
 *
6667
 * @return bool
6668
 */
6669
function api_can_login_as($loginAsUserId, $userId = null)
6670
{
6671
    $loginAsUserId = (int) $loginAsUserId;
6672
6673
    if (empty($loginAsUserId)) {
6674
        return false;
6675
    }
6676
6677
    if (empty($userId)) {
6678
        $userId = api_get_user_id();
6679
    }
6680
6681
    if ($loginAsUserId == $userId) {
6682
        return false;
6683
    }
6684
6685
    // Check if the user to login is an admin
6686
    if (api_is_platform_admin_by_id($loginAsUserId)) {
6687
        // Only super admins can login to admin accounts
6688
        if (!api_global_admin_can_edit_admin($loginAsUserId)) {
6689
            return false;
6690
        }
6691
    }
6692
6693
    $userInfo = api_get_user_info($loginAsUserId);
6694
6695
    $isDrh = function () use ($loginAsUserId) {
6696
        if (api_is_drh()) {
6697
            if (api_drh_can_access_all_session_content()) {
6698
                $users = SessionManager::getAllUsersFromCoursesFromAllSessionFromStatus(
6699
                    'drh_all',
6700
                    api_get_user_id()
6701
                );
6702
                $userList = [];
6703
                if (is_array($users)) {
6704
                    foreach ($users as $user) {
6705
                        $userList[] = $user['id'];
6706
                    }
6707
                }
6708
                if (in_array($loginAsUserId, $userList)) {
6709
                    return true;
6710
                }
6711
            } else {
6712
                if (api_is_drh() &&
6713
                    UserManager::is_user_followed_by_drh($loginAsUserId, api_get_user_id())
6714
                ) {
6715
                    return true;
6716
                }
6717
            }
6718
        }
6719
6720
        return false;
6721
    };
6722
6723
    $loginAsStatusForSessionAdmins = [STUDENT];
6724
6725
    if ('true' === api_get_setting('session.allow_session_admin_login_as_teacher')) {
6726
        $loginAsStatusForSessionAdmins[] = COURSEMANAGER;
6727
    }
6728
6729
    return api_is_platform_admin() ||
6730
        (api_is_session_admin() && in_array($userInfo['status'], $loginAsStatusForSessionAdmins)) ||
6731
        $isDrh();
6732
}
6733
6734
/**
6735
 * Return true on https install.
6736
 *
6737
 * @return bool
6738
 */
6739
function api_is_https()
6740
{
6741
    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...
6742
        'https' == $_SERVER['HTTP_X_FORWARDED_PROTO'] || !empty(api_get_configuration_value('force_https_forwarded_proto'))
6743
    ) {
6744
        $isSecured = true;
6745
    } else {
6746
        if (!empty($_SERVER['HTTPS']) && 'off' != $_SERVER['HTTPS']) {
6747
            $isSecured = true;
6748
        } else {
6749
            $isSecured = false;
6750
            // last chance
6751
            if (!empty($_SERVER['SERVER_PORT']) && 443 == $_SERVER['SERVER_PORT']) {
6752
                $isSecured = true;
6753
            }
6754
        }
6755
    }
6756
6757
    return $isSecured;
6758
}
6759
6760
/**
6761
 * Return protocol (http or https).
6762
 *
6763
 * @return string
6764
 */
6765
function api_get_protocol()
6766
{
6767
    return api_is_https() ? 'https' : 'http';
6768
}
6769
6770
/**
6771
 * Get origin.
6772
 *
6773
 * @param string
6774
 *
6775
 * @return string
6776
 */
6777
function api_get_origin()
6778
{
6779
    return isset($_REQUEST['origin']) ? urlencode(Security::remove_XSS(urlencode($_REQUEST['origin']))) : '';
6780
}
6781
6782
/**
6783
 * Warns an user that the portal reach certain limit.
6784
 *
6785
 * @param string $limitName
6786
 */
6787
function api_warn_hosting_contact($limitName)
6788
{
6789
    $hostingParams = api_get_configuration_value(1);
6790
    $email = null;
6791
6792
    if (!empty($hostingParams)) {
6793
        if (isset($hostingParams['hosting_contact_mail'])) {
6794
            $email = $hostingParams['hosting_contact_mail'];
6795
        }
6796
    }
6797
6798
    if (!empty($email)) {
6799
        $subject = get_lang('Hosting warning reached');
6800
        $body = get_lang('Portal name').': '.api_get_path(WEB_PATH)." \n ";
6801
        $body .= get_lang('Portal\'s limit type').': '.$limitName." \n ";
6802
        if (isset($hostingParams[$limitName])) {
6803
            $body .= get_lang('Value').': '.$hostingParams[$limitName];
6804
        }
6805
        api_mail_html(null, $email, $subject, $body);
6806
    }
6807
}
6808
6809
/**
6810
 * Gets value of a variable from config/configuration.php
6811
 * Variables that are not set in the configuration.php file but set elsewhere:
6812
 * - virtual_css_theme_folder (vchamilo plugin)
6813
 * - access_url (global.inc.php)
6814
 * - apc/apc_prefix (global.inc.php).
6815
 *
6816
 * @param string $variable
6817
 *
6818
 * @return bool|mixed
6819
 */
6820
function api_get_configuration_value($variable)
6821
{
6822
    global $_configuration;
6823
    // Check the current url id, id = 1 by default
6824
    $urlId = isset($_configuration['access_url']) ? (int) $_configuration['access_url'] : 1;
6825
6826
    $variable = trim($variable);
6827
6828
    // Check if variable exists
6829
    if (isset($_configuration[$variable])) {
6830
        if (is_array($_configuration[$variable])) {
6831
            // Check if it exists for the sub portal
6832
            if (array_key_exists($urlId, $_configuration[$variable])) {
6833
                return $_configuration[$variable][$urlId];
6834
            } else {
6835
                // Try to found element with id = 1 (master portal)
6836
                if (array_key_exists(1, $_configuration[$variable])) {
6837
                    return $_configuration[$variable][1];
6838
                }
6839
            }
6840
        }
6841
6842
        return $_configuration[$variable];
6843
    }
6844
6845
    return false;
6846
}
6847
6848
/**
6849
 * Gets a specific hosting limit.
6850
 *
6851
 * @param int $urlId The URL ID.
6852
 * @param string $limitName The name of the limit.
6853
 * @return mixed The value of the limit, or null if not found.
6854
 */
6855
function get_hosting_limit(int $urlId, string $limitName): mixed
6856
{
6857
    if (!Container::$container->hasParameter('settings_overrides')) {
6858
        return [];
6859
    }
6860
6861
    $settingsOverrides = Container::$container->getParameter('settings_overrides');
6862
6863
    $limits = $settingsOverrides[$urlId]['hosting_limit'] ?? $settingsOverrides['default']['hosting_limit'];
6864
6865
    foreach ($limits as $limitArray) {
6866
        if (isset($limitArray[$limitName])) {
6867
            return $limitArray[$limitName];
6868
        }
6869
    }
6870
6871
    return null;
6872
}
6873
6874
6875
/**
6876
 * Retrieves an environment variable value with validation and handles boolean conversion.
6877
 *
6878
 * @param string $variable The name of the environment variable.
6879
 * @param mixed $default The default value to return if the variable is not set.
6880
 * @return mixed The value of the environment variable, converted to boolean if necessary, or the default value.
6881
 */
6882
function api_get_env_variable(string $variable, mixed $default = null): mixed
6883
{
6884
    $variable = strtolower($variable);
6885
    if (Container::$container->hasParameter($variable)) {
6886
        return Container::$container->getParameter($variable);
6887
    }
6888
6889
    return $default;
6890
}
6891
6892
/**
6893
 * Retreives and returns a value in a hierarchical configuration array
6894
 * api_get_configuration_sub_value('a/b/c') returns api_get_configuration_value('a')['b']['c'].
6895
 *
6896
 * @param string $path      the successive array keys, separated by the separator
6897
 * @param mixed  $default   value to be returned if not found, null by default
6898
 * @param string $separator '/' by default
6899
 * @param array  $array     the active configuration array by default
6900
 *
6901
 * @return mixed the found value or $default
6902
 */
6903
function api_get_configuration_sub_value($path, $default = null, $separator = '/', $array = null)
6904
{
6905
    $pos = strpos($path, $separator);
6906
    if (false === $pos) {
6907
        if (is_null($array)) {
6908
            return api_get_configuration_value($path);
6909
        }
6910
        if (is_array($array) && array_key_exists($path, $array)) {
6911
            return $array[$path];
6912
        }
6913
6914
        return $default;
6915
    }
6916
    $key = substr($path, 0, $pos);
6917
    if (is_null($array)) {
6918
        $newArray = api_get_configuration_value($key);
6919
    } elseif (is_array($array) && array_key_exists($key, $array)) {
6920
        $newArray = $array[$key];
6921
    } else {
6922
        return $default;
6923
    }
6924
    if (is_array($newArray)) {
6925
        $newPath = substr($path, $pos + 1);
6926
6927
        return api_get_configuration_sub_value($newPath, $default, $separator, $newArray);
6928
    }
6929
6930
    return $default;
6931
}
6932
6933
/**
6934
 * Retrieves and returns a value in a hierarchical configuration array
6935
 * api_array_sub_value($array, 'a/b/c') returns $array['a']['b']['c'].
6936
 *
6937
 * @param array  $array     the recursive array that contains the value to be returned (or not)
6938
 * @param string $path      the successive array keys, separated by the separator
6939
 * @param mixed  $default   the value to be returned if not found
6940
 * @param string $separator the separator substring
6941
 *
6942
 * @return mixed the found value or $default
6943
 */
6944
function api_array_sub_value($array, $path, $default = null, $separator = '/')
6945
{
6946
    $pos = strpos($path, $separator);
6947
    if (false === $pos) {
6948
        if (is_array($array) && array_key_exists($path, $array)) {
6949
            return $array[$path];
6950
        }
6951
6952
        return $default;
6953
    }
6954
    $key = substr($path, 0, $pos);
6955
    if (is_array($array) && array_key_exists($key, $array)) {
6956
        $newArray = $array[$key];
6957
    } else {
6958
        return $default;
6959
    }
6960
    if (is_array($newArray)) {
6961
        $newPath = substr($path, $pos + 1);
6962
6963
        return api_array_sub_value($newArray, $newPath, $default);
6964
    }
6965
6966
    return $default;
6967
}
6968
6969
/**
6970
 * Returns supported image extensions in the portal.
6971
 *
6972
 * @param bool $supportVectors Whether vector images should also be accepted or not
6973
 *
6974
 * @return array Supported image extensions in the portal
6975
 */
6976
function api_get_supported_image_extensions($supportVectors = true)
6977
{
6978
    // jpg can also be called jpeg, jpe, jfif and jif. See https://en.wikipedia.org/wiki/JPEG#JPEG_filename_extensions
6979
    $supportedImageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'jpe', 'jfif', 'jif'];
6980
    if ($supportVectors) {
6981
        array_push($supportedImageExtensions, 'svg');
6982
    }
6983
    if (version_compare(PHP_VERSION, '5.5.0', '>=')) {
6984
        array_push($supportedImageExtensions, 'webp');
6985
    }
6986
6987
    return $supportedImageExtensions;
6988
}
6989
6990
/**
6991
 * This setting changes the registration status for the campus.
6992
 *
6993
 * @author Patrick Cool <[email protected]>, Ghent University
6994
 *
6995
 * @version August 2006
6996
 *
6997
 * @param bool $listCampus Whether we authorize
6998
 *
6999
 * @todo the $_settings should be reloaded here. => write api function for this and use this in global.inc.php also.
7000
 */
7001
function api_register_campus($listCampus = true)
7002
{
7003
    $tbl_settings = Database::get_main_table(TABLE_MAIN_SETTINGS);
7004
7005
    $sql = "UPDATE $tbl_settings SET selected_value='true' WHERE variable='registered'";
7006
    Database::query($sql);
7007
7008
    if (!$listCampus) {
7009
        $sql = "UPDATE $tbl_settings SET selected_value='true' WHERE variable='donotlistcampus'";
7010
        Database::query($sql);
7011
    }
7012
}
7013
7014
/**
7015
 * Check whether the user type should be exclude.
7016
 * Such as invited or anonymous users.
7017
 *
7018
 * @param bool $checkDB Optional. Whether check the user status
7019
 * @param int  $userId  Options. The user id
7020
 *
7021
 * @return bool
7022
 */
7023
function api_is_excluded_user_type($checkDB = false, $userId = 0)
7024
{
7025
    if ($checkDB) {
7026
        $userId = empty($userId) ? api_get_user_id() : (int) $userId;
7027
7028
        if (0 == $userId) {
7029
            return true;
7030
        }
7031
7032
        $userInfo = api_get_user_info($userId);
7033
7034
        switch ($userInfo['status']) {
7035
            case INVITEE:
7036
            case ANONYMOUS:
7037
                return true;
7038
            default:
7039
                return false;
7040
        }
7041
    }
7042
7043
    $isInvited = api_is_invitee();
7044
    $isAnonymous = api_is_anonymous();
7045
7046
    if ($isInvited || $isAnonymous) {
7047
        return true;
7048
    }
7049
7050
    return false;
7051
}
7052
7053
/**
7054
 * Get the user status to ignore in reports.
7055
 *
7056
 * @param string $format Optional. The result type (array or string)
7057
 *
7058
 * @return array|string
7059
 */
7060
function api_get_users_status_ignored_in_reports($format = 'array')
7061
{
7062
    $excludedTypes = [
7063
        INVITEE,
7064
        ANONYMOUS,
7065
    ];
7066
7067
    if ('string' == $format) {
7068
        return implode(', ', $excludedTypes);
7069
    }
7070
7071
    return $excludedTypes;
7072
}
7073
7074
/**
7075
 * Set the Site Use Cookie Warning for 1 year.
7076
 */
7077
function api_set_site_use_cookie_warning_cookie()
7078
{
7079
    setcookie('ChamiloUsesCookies', 'ok', time() + 31556926);
7080
}
7081
7082
/**
7083
 * Return true if the Site Use Cookie Warning Cookie warning exists.
7084
 *
7085
 * @return bool
7086
 */
7087
function api_site_use_cookie_warning_cookie_exist()
7088
{
7089
    return isset($_COOKIE['ChamiloUsesCookies']);
7090
}
7091
7092
/**
7093
 * Given a number of seconds, format the time to show hours, minutes and seconds.
7094
 *
7095
 * @param int    $time         The time in seconds
7096
 * @param string $originFormat Optional. PHP o JS
7097
 *
7098
 * @return string (00h00'00")
7099
 */
7100
function api_format_time($time, $originFormat = 'php')
7101
{
7102
    $h = get_lang('h');
7103
    $hours = $time / 3600;
7104
    $mins = ($time % 3600) / 60;
7105
    $secs = ($time % 60);
7106
7107
    if ($time < 0) {
7108
        $hours = 0;
7109
        $mins = 0;
7110
        $secs = 0;
7111
    }
7112
7113
    if ('js' === $originFormat) {
7114
        $formattedTime = trim(sprintf("%02d : %02d : %02d", $hours, $mins, $secs));
7115
    } else {
7116
        $formattedTime = trim(sprintf("%02d$h%02d'%02d\"", $hours, $mins, $secs));
7117
    }
7118
7119
    return $formattedTime;
7120
}
7121
7122
function api_set_noreply_and_from_address_to_mailer(
7123
    TemplatedEmail $email,
7124
    array $sender,
7125
    array $replyToAddress = []
7126
): void {
7127
    $validator = Container::getLegacyHelper()->getValidator();
7128
    $emailConstraint = new Assert\Email();
7129
7130
    $noReplyAddress = api_get_setting('noreply_email_address');
7131
    $avoidReplyToAddress = false;
7132
7133
    if (!empty($noReplyAddress)) {
7134
        // $avoidReplyToAddress = api_get_configuration_value('mail_no_reply_avoid_reply_to');
7135
    }
7136
7137
    // Default values
7138
    $notification = new Notification();
7139
    $defaultSenderName = $notification->getDefaultPlatformSenderName();
7140
    $defaultSenderEmail = $notification->getDefaultPlatformSenderEmail();
7141
7142
    // If the parameter is set don't use the admin.
7143
    $senderName = !empty($sender['name']) ? $sender['name'] : $defaultSenderName;
7144
    $senderEmail = !empty($sender['email']) ? $sender['email'] : $defaultSenderEmail;
7145
7146
    // Send errors to the platform admin
7147
    $adminEmail = api_get_setting('admin.administrator_email');
7148
7149
    $adminEmailValidation = $validator->validate($adminEmail, $emailConstraint);
7150
7151
    if (!empty($adminEmail) && 0 === $adminEmailValidation->count()) {
7152
        $email
7153
            ->getHeaders()
7154
            ->addIdHeader('Errors-To', $adminEmail)
7155
        ;
7156
    }
7157
7158
    if (!$avoidReplyToAddress && !empty($replyToAddress)) {
7159
        $replyToEmailValidation = $validator->validate($replyToAddress['mail'], $emailConstraint);
7160
7161
        if (0 === $replyToEmailValidation->count()) {
7162
            $email->addReplyTo(new Address($replyToAddress['mail'], $replyToAddress['name']));
7163
        }
7164
    }
7165
7166
    if ('true' === api_get_setting('mail.smtp_unique_sender')) {
7167
        $senderName = $defaultSenderName;
7168
        $senderEmail = $defaultSenderEmail;
7169
7170
        $email->sender(new Address($senderEmail, $senderName));
7171
    }
7172
7173
    if ($senderEmail) {
7174
        $email->from(new Address($senderEmail, $senderName));
7175
    }
7176
}
7177
7178
/**
7179
 * Sends an email
7180
 * Sender name and email can be specified, if not specified
7181
 * name and email of the platform admin are used.
7182
 *
7183
 * @param string    name of recipient
7184
 * @param string    email of recipient
7185
 * @param string    email subject
7186
 * @param string    email body
7187
 * @param string    sender name
7188
 * @param string    sender e-mail
7189
 * @param array     extra headers in form $headers = array($name => $value) to allow parsing
7190
 * @param array     data file (path and filename)
7191
 * @param bool      True for attaching a embedded file inside content html (optional)
7192
 * @param array     Additional parameters
7193
 *
7194
 * @return bool true if mail was sent
7195
 */
7196
function api_mail_html(
7197
    $recipientName,
7198
    $recipientEmail,
7199
    $subject,
7200
    $body,
7201
    $senderName = '',
7202
    $senderEmail = '',
7203
    $extra_headers = [],
7204
    $data_file = [],
7205
    $embeddedImage = false,
7206
    $additionalParameters = [],
7207
    string $sendErrorTo = null
7208
) {
7209
    $mailHelper = Container::$container->get(MailHelper::class);
7210
7211
    return $mailHelper->send(
7212
        $recipientName,
7213
        $recipientEmail,
7214
        $subject,
7215
        $body,
7216
        $senderName,
7217
        $senderEmail,
7218
        $extra_headers,
7219
        $data_file,
7220
        $embeddedImage,
7221
        $additionalParameters,
7222
        $sendErrorTo
7223
    );
7224
}
7225
7226
/**
7227
 * @param int  $tool       Possible values: GroupManager::GROUP_TOOL_*
7228
 * @param bool $showHeader
7229
 */
7230
function api_protect_course_group($tool, $showHeader = true)
7231
{
7232
    $groupId = api_get_group_id();
7233
    if (!empty($groupId)) {
7234
        if (api_is_platform_admin()) {
7235
            return true;
7236
        }
7237
7238
        if (api_is_allowed_to_edit(false, true, true)) {
7239
            return true;
7240
        }
7241
7242
        $userId = api_get_user_id();
7243
        $sessionId = api_get_session_id();
7244
        if (!empty($sessionId)) {
7245
            if (api_is_coach($sessionId, api_get_course_int_id())) {
7246
                return true;
7247
            }
7248
7249
            if (api_is_drh()) {
7250
                if (SessionManager::isUserSubscribedAsHRM($sessionId, $userId)) {
7251
                    return true;
7252
                }
7253
            }
7254
        }
7255
7256
        $group = api_get_group_entity($groupId);
7257
7258
        // Group doesn't exists
7259
        if (null === $group) {
7260
            api_not_allowed($showHeader);
7261
        }
7262
7263
        // Check group access
7264
        $allow = GroupManager::userHasAccess(
7265
            $userId,
7266
            $group,
7267
            $tool
7268
        );
7269
7270
        if (!$allow) {
7271
            api_not_allowed($showHeader);
7272
        }
7273
    }
7274
7275
    return false;
7276
}
7277
7278
/**
7279
 * Check if a date is in a date range.
7280
 *
7281
 * @param datetime $startDate
7282
 * @param datetime $endDate
7283
 * @param datetime $currentDate
7284
 *
7285
 * @return bool true if date is in rage, false otherwise
7286
 */
7287
function api_is_date_in_date_range($startDate, $endDate, $currentDate = null)
7288
{
7289
    $startDate = strtotime(api_get_local_time($startDate));
7290
    $endDate = strtotime(api_get_local_time($endDate));
7291
    $currentDate = strtotime(api_get_local_time($currentDate));
7292
7293
    if ($currentDate >= $startDate && $currentDate <= $endDate) {
7294
        return true;
7295
    }
7296
7297
    return false;
7298
}
7299
7300
/**
7301
 * Eliminate the duplicates of a multidimensional array by sending the key.
7302
 *
7303
 * @param array $array multidimensional array
7304
 * @param int   $key   key to find to compare
7305
 *
7306
 * @return array
7307
 */
7308
function api_unique_multidim_array($array, $key)
7309
{
7310
    $temp_array = [];
7311
    $i = 0;
7312
    $key_array = [];
7313
7314
    foreach ($array as $val) {
7315
        if (!in_array($val[$key], $key_array)) {
7316
            $key_array[$i] = $val[$key];
7317
            $temp_array[$i] = $val;
7318
        }
7319
        $i++;
7320
    }
7321
7322
    return $temp_array;
7323
}
7324
7325
/**
7326
 * Limit the access to Session Admins when the limit_session_admin_role
7327
 * configuration variable is set to true.
7328
 */
7329
function api_protect_limit_for_session_admin()
7330
{
7331
    $limitAdmin = api_get_setting('limit_session_admin_role');
7332
    if (api_is_session_admin() && 'true' === $limitAdmin) {
7333
        api_not_allowed(true);
7334
    }
7335
}
7336
7337
/**
7338
 * Limits that a session admin has access to list users.
7339
 * When limit_session_admin_list_users configuration variable is set to true.
7340
 */
7341
function api_protect_session_admin_list_users()
7342
{
7343
    $limitAdmin = ('true' === api_get_setting('session.limit_session_admin_list_users'));
7344
7345
    if (api_is_session_admin() && true === $limitAdmin) {
7346
        api_not_allowed(true);
7347
    }
7348
}
7349
7350
/**
7351
 * @return bool
7352
 */
7353
function api_is_student_view_active(): bool
7354
{
7355
    $studentView = Session::read('studentview');
7356
7357
    return 'studentview' === $studentView;
7358
}
7359
7360
/**
7361
 * Converts string value to float value.
7362
 *
7363
 * 3.141516 => 3.141516
7364
 * 3,141516 => 3.141516
7365
 *
7366
 * @todo WIP
7367
 *
7368
 * @param string $number
7369
 *
7370
 * @return float
7371
 */
7372
function api_float_val($number)
7373
{
7374
    return (float) str_replace(',', '.', trim($number));
7375
}
7376
7377
/**
7378
 * Converts float values
7379
 * Example if $decimals = 2.
7380
 *
7381
 * 3.141516 => 3.14
7382
 * 3,141516 => 3,14
7383
 *
7384
 * @param string $number            number in iso code
7385
 * @param int    $decimals
7386
 * @param string $decimalSeparator
7387
 * @param string $thousandSeparator
7388
 *
7389
 * @return bool|string
7390
 */
7391
function api_number_format($number, $decimals = 0, $decimalSeparator = '.', $thousandSeparator = ',')
7392
{
7393
    $number = api_float_val($number);
7394
7395
    return number_format($number, $decimals, $decimalSeparator, $thousandSeparator);
7396
}
7397
7398
/**
7399
 * Set location url with a exit break by default.
7400
 *
7401
 * @param string $url
7402
 * @param bool   $exit
7403
 */
7404
function api_location($url, $exit = true)
7405
{
7406
    header('Location: '.$url);
7407
7408
    if ($exit) {
7409
        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...
7410
    }
7411
}
7412
7413
/**
7414
 * @param string $from
7415
 * @param string $to
7416
 *
7417
 * @return string
7418
 */
7419
function api_get_relative_path($from, $to)
7420
{
7421
    // some compatibility fixes for Windows paths
7422
    $from = is_dir($from) ? rtrim($from, '\/').'/' : $from;
7423
    $to = is_dir($to) ? rtrim($to, '\/').'/' : $to;
7424
    $from = str_replace('\\', '/', $from);
7425
    $to = str_replace('\\', '/', $to);
7426
7427
    $from = explode('/', $from);
7428
    $to = explode('/', $to);
7429
    $relPath = $to;
7430
7431
    foreach ($from as $depth => $dir) {
7432
        // find first non-matching dir
7433
        if ($dir === $to[$depth]) {
7434
            // ignore this directory
7435
            array_shift($relPath);
7436
        } else {
7437
            // get number of remaining dirs to $from
7438
            $remaining = count($from) - $depth;
7439
            if ($remaining > 1) {
7440
                // add traversals up to first matching dir
7441
                $padLength = (count($relPath) + $remaining - 1) * -1;
7442
                $relPath = array_pad($relPath, $padLength, '..');
7443
                break;
7444
            } else {
7445
                $relPath[0] = './'.$relPath[0];
7446
            }
7447
        }
7448
    }
7449
7450
    return implode('/', $relPath);
7451
}
7452
7453
/**
7454
 * @param string $template
7455
 *
7456
 * @return string
7457
 */
7458
function api_find_template($template)
7459
{
7460
    return Template::findTemplateFilePath($template);
7461
}
7462
7463
/**
7464
 * @return array
7465
 */
7466
function api_get_language_list_for_flag()
7467
{
7468
    $table = Database::get_main_table(TABLE_MAIN_LANGUAGE);
7469
    $sql = "SELECT english_name, isocode FROM $table
7470
            ORDER BY original_name ASC";
7471
    static $languages = [];
7472
    if (empty($languages)) {
7473
        $result = Database::query($sql);
7474
        while ($row = Database::fetch_array($result)) {
7475
            $languages[$row['english_name']] = $row['isocode'];
7476
        }
7477
        $languages['english'] = 'gb';
7478
    }
7479
7480
    return $languages;
7481
}
7482
7483
function api_create_zip(string $name): ZipStream
7484
{
7485
    $zipStreamOptions = new Archive();
7486
    $zipStreamOptions->setSendHttpHeaders(true);
7487
    $zipStreamOptions->setContentDisposition('attachment');
7488
    $zipStreamOptions->setContentType('application/x-zip');
7489
7490
    return new ZipStream($name, $zipStreamOptions);
7491
}
7492
7493
function api_get_language_translate_html(): string
7494
{
7495
    $translate = 'true' === api_get_setting('editor.translate_html');
7496
7497
    if (!$translate) {
7498
        return '';
7499
    }
7500
7501
    /*$languageList = api_get_languages();
7502
    $hideAll = '';
7503
    foreach ($languageList as $isocode => $name) {
7504
        $hideAll .= '
7505
        $(".mce-translatehtml").hide();
7506
        $("span:lang('.$isocode.')").filter(
7507
            function(e, val) {
7508
                // Only find the spans if they have set the lang
7509
                if ($(this).attr("lang") == null) {
7510
                    return false;
7511
                }
7512
                // Ignore ckeditor classes
7513
                return !this.className.match(/cke(.*)/);
7514
        }).hide();'."\n";
7515
    }*/
7516
7517
    $userInfo = api_get_user_info();
7518
    if (!empty($userInfo['language'])) {
7519
        $isoCode = $userInfo['language'];
7520
7521
        return '
7522
            $(function() {
7523
                $(".mce-translatehtml").hide();
7524
                var defaultLanguageFromUser = "'.$isoCode.'";
7525
                $("span:lang('.$isoCode.')").show();
7526
            });
7527
        ';
7528
    }
7529
7530
    return '';
7531
}
7532
7533
function api_protect_webservices()
7534
{
7535
    if (api_get_configuration_value('disable_webservices')) {
7536
        echo "Webservices are disabled. \n";
7537
        echo "To enable, add \$_configuration['disable_webservices'] = true; in configuration.php";
7538
        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...
7539
    }
7540
}
7541
7542
function api_filename_has_blacklisted_stream_wrapper(string $filename) {
7543
    if (strpos($filename, '://') > 0) {
7544
        $wrappers = stream_get_wrappers();
7545
        $allowedWrappers = ['http', 'https', 'file'];
7546
        foreach ($wrappers as $wrapper) {
7547
            if (in_array($wrapper, $allowedWrappers)) {
7548
                continue;
7549
            }
7550
            if (stripos($filename, $wrapper . '://') === 0) {
7551
                return true;
7552
            }
7553
        }
7554
    }
7555
    return false;
7556
}
7557
7558
/**
7559
 * Checks if a set of roles have a specific permission.
7560
 *
7561
 * @param string $permissionSlug The slug of the permission to check.
7562
 * @param array  $roles          An array of role codes to check against.
7563
 * @return bool True if any of the roles have the permission, false otherwise.
7564
 */
7565
function api_get_permission(string $permissionSlug, array $roles): bool
7566
{
7567
    $permissionService = Container::$container->get(PermissionServiceHelper::class);
7568
7569
    return $permissionService->hasPermission($permissionSlug, $roles);
7570
}
7571
7572
/**
7573
 * Calculate the percentage of change between two numbers.
7574
 *
7575
 * @param int $newValue
7576
 * @param int $oldValue
7577
 * @return string
7578
 */
7579
function api_calculate_increment_percent(int $newValue, int $oldValue): string
7580
{
7581
    if ($oldValue <= 0) {
7582
        $result = " - ";
7583
    } else {
7584
        $result = ' '.round(100 * (($newValue / $oldValue) - 1), 2).' %';
7585
    }
7586
    return $result;
7587
}
7588