Passed
Push — 1.11.x ( c3488b...67344d )
by Julito
16:26
created

ChamiloApi::getConfigurationValue()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 4
nc 2
nop 1
dl 0
loc 8
rs 10
c 0
b 0
f 0
1
<?php
2
/* For licensing terms, see /license.txt */
3
4
namespace Chamilo\CoreBundle\Component\Utils;
5
6
use ChamiloSession as Session;
7
8
/**
9
 * Class ChamiloApi.
10
 *
11
 * @package Chamilo\CoreBundle\Component
12
 */
13
class ChamiloApi
14
{
15
    private static $configuration;
16
17
    /**
18
     * ChamiloApi constructor.
19
     *
20
     * @param $configuration
21
     */
22
    public function __construct(array $configuration)
23
    {
24
        self::$configuration = $configuration;
25
    }
26
27
    /**
28
     * @return array
29
     */
30
    public static function getConfigurationArray()
31
    {
32
        return self::$configuration;
33
    }
34
35
    /**
36
     * @param string $variable
37
     *
38
     * @return bool|string
39
     */
40
    public static function getConfigurationValue($variable)
41
    {
42
        $configuration = self::getConfigurationArray();
43
        if (array_key_exists($variable, $configuration)) {
44
            return $configuration[$variable];
45
        }
46
47
        return false;
48
    }
49
50
    /**
51
     * Returns an array of resolutions that can be used for the conversion of documents to images.
52
     *
53
     * @return array
54
     */
55
    public static function getDocumentConversionSizes()
56
    {
57
        return [
58
            '540x405' => '540x405 (3/4)',
59
            '640x480' => '640x480 (3/4)',
60
            '720x540' => '720x540 (3/4)',
61
            '800x600' => '800x600 (3/4)',
62
            '1024x576' => '1024x576 (16/9)',
63
            '1024x768' => '1000x750 (3/4)',
64
            '1280x720' => '1280x720 (16/9)',
65
            '1280x860' => '1280x960 (3/4)',
66
            '1400x1050' => '1400x1050 (3/4)',
67
            '1600x900' => '1600x900 (16/9)',
68
        ];
69
    }
70
71
    /**
72
     * Get the platform logo path.
73
     *
74
     * @param string $theme
75
     * @param bool   $getSysPath
76
     *
77
     * @return string
78
     */
79
    public static function getPlatformLogoPath($theme = '', $getSysPath = false)
80
    {
81
        static $logoPath;
82
83
        // If call from CLI it should be reload.
84
        if ('cli' === PHP_SAPI) {
85
            $logoPath = null;
86
        }
87
88
        if (!isset($logoPath)) {
89
            $theme = empty($theme) ? api_get_visual_theme() : $theme;
90
            $accessUrlId = api_get_current_access_url_id();
91
            if ('cli' === PHP_SAPI) {
92
                $accessUrl = api_get_configuration_value('access_url');
93
                if (!empty($accessUrl)) {
94
                    $accessUrlId = $accessUrl;
95
                }
96
            }
97
            $themeDir = \Template::getThemeDir($theme);
98
            $customLogoPath = $themeDir."images/header-logo-custom$accessUrlId.png";
99
100
            $svgIcons = api_get_setting('icons_mode_svg');
101
            if ($svgIcons === 'true') {
102
                $customLogoPathSVG = substr($customLogoPath, 0, -3).'svg';
103
                if (file_exists(api_get_path(SYS_PUBLIC_PATH)."css/$customLogoPathSVG")) {
104
                    if ($getSysPath) {
105
                        $logoPath = api_get_path(SYS_PUBLIC_PATH)."css/$customLogoPathSVG";
106
107
                        return $logoPath;
108
                    }
109
                    $logoPath = api_get_path(WEB_CSS_PATH).$customLogoPathSVG;
110
111
                    return $logoPath;
112
                }
113
            }
114
            if (file_exists(api_get_path(SYS_PUBLIC_PATH)."css/$customLogoPath")) {
115
                if ($getSysPath) {
116
                    $logoPath = api_get_path(SYS_PUBLIC_PATH)."css/$customLogoPath";
117
118
                    return $logoPath;
119
                }
120
121
                $logoPath = api_get_path(WEB_CSS_PATH).$customLogoPath;
122
123
                return $logoPath;
124
            }
125
126
            $originalLogoPath = $themeDir."images/header-logo.png";
127
            if ($svgIcons === 'true') {
128
                $originalLogoPathSVG = $themeDir."images/header-logo.svg";
129
                if (file_exists(api_get_path(SYS_CSS_PATH).$originalLogoPathSVG)) {
130
                    if ($getSysPath) {
131
                        $logoPath = api_get_path(SYS_CSS_PATH).$originalLogoPathSVG;
132
133
                        return $logoPath;
134
                    }
135
                    $logoPath = api_get_path(WEB_CSS_PATH).$originalLogoPathSVG;
136
137
                    return $logoPath;
138
                }
139
            }
140
141
            if (file_exists(api_get_path(SYS_CSS_PATH).$originalLogoPath)) {
142
                if ($getSysPath) {
143
                    $logoPath = api_get_path(SYS_CSS_PATH).$originalLogoPath;
144
145
                    return $logoPath;
146
                }
147
148
                $logoPath = api_get_path(WEB_CSS_PATH).$originalLogoPath;
149
150
                return $logoPath;
151
            }
152
            $logoPath = '';
153
        }
154
155
        return $logoPath;
156
    }
157
158
    /**
159
     * Get the platform logo.
160
     * Return a <img> if the logo image exists. Otherwise return a <h2> with the institution name.
161
     *
162
     * @param string $theme
163
     * @param array  $imageAttributes optional
164
     * @param bool   $getSysPath
165
     *
166
     * @return string
167
     */
168
    public static function getPlatformLogo($theme = '', $imageAttributes = [], $getSysPath = false)
169
    {
170
        $logoPath = self::getPlatformLogoPath($theme, $getSysPath);
171
        $institution = api_get_setting('Institution');
172
        $institutionUrl = api_get_setting('InstitutionUrl');
173
        $siteName = api_get_setting('siteName');
174
175
        if ($logoPath === null) {
176
            $headerLogo = \Display::url($siteName, api_get_path(WEB_PATH).'index.php');
177
178
            if (!empty($institutionUrl) && !empty($institution)) {
179
                $headerLogo .= ' - '.\Display::url($institution, $institutionUrl);
180
            }
181
182
            $courseInfo = api_get_course_info();
183
            if (isset($courseInfo['extLink']) && !empty($courseInfo['extLink']['name'])) {
184
                $headerLogo .= '<span class="extLinkSeparator"> - </span>';
185
186
                if (!empty($courseInfo['extLink']['url'])) {
187
                    $headerLogo .= \Display::url(
188
                        $courseInfo['extLink']['name'],
189
                        $courseInfo['extLink']['url'],
190
                        ['class' => 'extLink']
191
                    );
192
                } elseif (!empty($courseInfo['extLink']['url'])) {
193
                    $headerLogo .= $courseInfo['extLink']['url'];
194
                }
195
            }
196
197
            return \Display::tag('h2', $headerLogo, ['class' => 'text-left']);
198
        }
199
200
        $image = \Display::img($logoPath, $institution, $imageAttributes);
201
202
        return \Display::url($image, api_get_path(WEB_PATH).'index.php');
203
    }
204
205
    /**
206
     * Like strip_tags(), but leaves an additional space and removes only the given tags.
207
     *
208
     * @param string $string
209
     * @param array  $tags   Tags to be removed
210
     *
211
     * @return string The original string without the given tags
212
     */
213
    public static function stripGivenTags($string, $tags)
214
    {
215
        foreach ($tags as $tag) {
216
            $string2 = preg_replace('#</\b'.$tag.'\b[^>]*>#i', ' ', $string);
217
            if ($string2 != $string) {
218
                $string = preg_replace('/<\b'.$tag.'\b[^>]*>/i', ' ', $string2);
219
            }
220
        }
221
222
        return $string;
223
    }
224
225
    /**
226
     * Adds or Subtract a time in hh:mm:ss to a datetime.
227
     *
228
     * @param string $time      Time to add or substract in hh:mm:ss format
229
     * @param string $datetime  Datetime to be modified as accepted by the Datetime class constructor
230
     * @param bool   $operation True for Add, False to Subtract
231
     *
232
     * @return string
233
     */
234
    public static function addOrSubTimeToDateTime($time, $datetime = 'now', $operation = true)
235
    {
236
        $date = new \DateTime($datetime);
237
        $hours = $minutes = $seconds = 0;
238
        sscanf($time, "%d:%d:%d", $hours, $minutes, $seconds);
239
        $timeSeconds = isset($seconds) ? $hours * 3600 + $minutes * 60 + $seconds : $hours * 60 + $minutes;
240
        if ($operation) {
241
            $date->add(new \DateInterval('PT'.$timeSeconds.'S'));
242
        } else {
243
            $date->sub(new \DateInterval('PT'.$timeSeconds.'S'));
244
        }
245
246
        return $date->format('Y-m-d H:i:s');
247
    }
248
249
    /**
250
     * Returns the course id (integer) for the given course directory or the current ID if no directory is defined.
251
     *
252
     * @param string $directory The course directory/path that appears in the URL
253
     *
254
     * @return int
255
     */
256
    public static function getCourseIdByDirectory($directory = null)
257
    {
258
        if (!empty($directory)) {
259
            $directory = \Database::escape_string($directory);
260
            $row = \Database::select(
261
                'id',
262
                \Database::get_main_table(TABLE_MAIN_COURSE),
263
                ['where' => ['directory = ?' => [$directory]]],
264
                'first'
265
            );
266
267
            if (is_array($row) && isset($row['id'])) {
268
                return $row['id'];
269
            } else {
270
                return false;
0 ignored issues
show
Bug Best Practice introduced by
The expression return false returns the type false which is incompatible with the documented return type integer.
Loading history...
271
            }
272
        }
273
274
        return Session::read('_real_cid', 0);
275
    }
276
277
    /**
278
     * Check if the current HTTP request is by AJAX.
279
     *
280
     * @return bool
281
     */
282
    public static function isAjaxRequest()
283
    {
284
        $requestedWith = isset($_SERVER['HTTP_X_REQUESTED_WITH']) ? $_SERVER['HTTP_X_REQUESTED_WITH'] : null;
285
286
        return $requestedWith === 'XMLHttpRequest';
287
    }
288
289
    /**
290
     * Get a variable name for language file from a text.
291
     *
292
     * @param string $text
293
     * @param string $prefix
294
     *
295
     * @return string
296
     */
297
    public static function getLanguageVar($text, $prefix = '')
298
    {
299
        $text = api_replace_dangerous_char($text);
300
        $text = str_replace(['-', ' ', '.'], '_', $text);
301
        $text = preg_replace('/\_{1,}/', '_', $text);
302
        //$text = str_replace('_', '', $text);
303
        $text = api_underscore_to_camel_case($text);
304
305
        return $prefix.$text;
306
    }
307
308
    /**
309
     * Get the stylesheet path for HTML documents created with CKEditor.
310
     *
311
     * @return string
312
     */
313
    public static function getEditorDocStylePath()
314
    {
315
        $visualTheme = api_get_visual_theme();
316
317
        $cssFile = api_get_path(SYS_CSS_PATH)."themes/$visualTheme/document.css";
318
319
        if (is_file($cssFile)) {
320
            return api_get_path(WEB_CSS_PATH)."themes/$visualTheme/document.css";
321
        }
322
323
        return api_get_path(WEB_CSS_PATH).'document.css';
324
    }
325
326
    /**
327
     * Get the stylesheet path for HTML blocks created with CKEditor.
328
     *
329
     * @return string
330
     */
331
    public static function getEditorBlockStylePath()
332
    {
333
        $visualTheme = api_get_visual_theme();
334
335
        $cssFile = api_get_path(SYS_CSS_PATH)."themes/$visualTheme/editor_content.css";
336
337
        if (is_file($cssFile)) {
338
            return api_get_path(WEB_CSS_PATH)."themes/$visualTheme/editor_content.css";
339
        }
340
341
        return api_get_path(WEB_CSS_PATH).'editor_content.css';
342
    }
343
344
    /**
345
     * Get a list of colors from the palette at main/palette/pchart/default.color
346
     * and return it as an array of strings.
347
     *
348
     * @param bool $decimalOpacity Whether to return the opacity as 0..100 or 0..1
349
     * @param bool $wrapInRGBA     Whether to return it as 1,1,1,100 or rgba(1,1,1,100)
350
     * @param int  $fillUpTo       If the number of colors is smaller than this number, generate more colors
351
     *
352
     * @return array An array of string colors
353
     */
354
    public static function getColorPalette(
355
        $decimalOpacity = false,
356
        $wrapInRGBA = false,
357
        $fillUpTo = null
358
    ) {
359
        // Get the common colors from the palette used for pchart
360
        $paletteFile = api_get_path(SYS_CODE_PATH).'palettes/pchart/default.color';
361
        $palette = file($paletteFile);
362
        if ($decimalOpacity) {
363
            // Because the pchart palette has transparency as integer values
364
            // (0..100) and chartjs uses percentage (0.0..1.0), we need to divide
365
            // the last value by 100, which is a bit overboard for just one chart
366
            foreach ($palette as $index => $color) {
367
                $components = preg_split('/,/', trim($color));
368
                $components[3] = round($components[3] / 100, 1);
369
                $palette[$index] = join(',', $components);
0 ignored issues
show
Bug introduced by
It seems like $components can also be of type false; however, parameter $pieces of join() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

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

369
                $palette[$index] = join(',', /** @scrutinizer ignore-type */ $components);
Loading history...
370
            }
371
        }
372
        if ($wrapInRGBA) {
373
            foreach ($palette as $index => $color) {
374
                $color = trim($color);
375
                $palette[$index] = 'rgba('.$color.')';
376
            }
377
        }
378
        // If we want more colors, loop through existing colors
379
        $count = count($palette);
0 ignored issues
show
Bug introduced by
It seems like $palette can also be of type false; however, parameter $var of count() does only seem to accept Countable|array, maybe add an additional type check? ( Ignorable by Annotation )

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

379
        $count = count(/** @scrutinizer ignore-type */ $palette);
Loading history...
380
        if (isset($fillUpTo) && $fillUpTo > $count) {
381
            for ($i = $count; $i < $fillUpTo; $i++) {
382
                $palette[$i] = $palette[$i % $count];
383
            }
384
        }
385
386
        return $palette;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $palette could also return false which is incompatible with the documented return type array. 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...
387
    }
388
389
    /**
390
     * Get the local time for the midnight.
391
     *
392
     * @param string|null $utcTime Optional. The time to ve converted.
393
     *                             See api_get_local_time.
394
     *
395
     * @throws \Exception
396
     *
397
     * @return \DateTime
398
     */
399
    public static function getServerMidnightTime($utcTime = null)
400
    {
401
        $localTime = api_get_local_time($utcTime);
402
        $localTimeZone = api_get_timezone();
403
404
        $localMidnight = new \DateTime($localTime, new \DateTimeZone($localTimeZone));
405
        $localMidnight->modify('midnight');
406
407
        return $localMidnight;
408
    }
409
410
    /**
411
     * Get JavaScript code necessary to load quiz markers-rolls in medialement's Markers Rolls plugin.
412
     *
413
     * @return string
414
     */
415
    public static function getQuizMarkersRollsJS()
416
    {
417
        $webCodePath = api_get_path(WEB_CODE_PATH);
418
        $cidReq = api_get_cidreq(true, true, 'embeddable');
419
        $colorPalette = self::getColorPalette(false, true);
420
421
        return "
422
            var \$originalNode = $(originalNode),
423
                    qMarkersRolls = \$originalNode.data('q-markersrolls') || [],
424
                    qMarkersColor = \$originalNode.data('q-markersrolls-color') || '{$colorPalette[0]}';
425
426
                if (0 == qMarkersRolls.length) {
427
                    return;
428
                }
429
430
                instance.options.markersRollsColor = qMarkersColor;
431
                instance.options.markersRollsWidth = 2;
432
                instance.options.markersRolls = {};
433
434
                qMarkersRolls.forEach(function (qMarkerRoll) {
435
                    var url = '{$webCodePath}exercise/exercise_submit.php?$cidReq&'
436
                        + $.param({
437
                            exerciseId: qMarkerRoll[1],
438
                            learnpath_id: 0,
439
                            learnpath_item_id: 0,
440
                            learnpath_item_view_id: 0
441
                        });
442
443
                    instance.options.markersRolls[qMarkerRoll[0]] = url;
444
                });
445
446
                instance.buildmarkersrolls(instance, instance.controls, instance.layers, instance.media);
447
        ";
448
    }
449
}
450