Passed
Push — master ( a02707...7dc539 )
by Julito
12:00
created

ChamiloApi::getPlatformLogoPath()   F

Complexity

Conditions 17
Paths 250

Size

Total Lines 77
Code Lines 44

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 17
eloc 44
nc 250
nop 3
dl 0
loc 77
rs 3.7583
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
/* For licensing terms, see /license.txt */
4
5
namespace Chamilo\CoreBundle\Component\Utils;
6
7
use ChamiloSession as Session;
8
9
/**
10
 * Class ChamiloApi.
11
 */
12
class ChamiloApi
13
{
14
    private static $configuration;
15
16
    /**
17
     * ChamiloApi constructor.
18
     */
19
    public function __construct(array $configuration)
20
    {
21
        self::$configuration = $configuration;
22
    }
23
24
    /**
25
     * @return array
26
     */
27
    public static function getConfigurationArray()
28
    {
29
        return self::$configuration;
30
    }
31
32
    /**
33
     * @param string $variable
34
     *
35
     * @return bool|string
36
     */
37
    public static function getConfigurationValue($variable)
38
    {
39
        $configuration = self::getConfigurationArray();
40
        if (array_key_exists($variable, $configuration)) {
41
            return $configuration[$variable];
42
        }
43
44
        return false;
45
    }
46
47
    /**
48
     * Returns an array of resolutions that can be used for the conversion of documents to images.
49
     *
50
     * @return array
51
     */
52
    public static function getDocumentConversionSizes()
53
    {
54
        return [
55
            '540x405' => '540x405 (3/4)',
56
            '640x480' => '640x480 (3/4)',
57
            '720x540' => '720x540 (3/4)',
58
            '800x600' => '800x600 (3/4)',
59
            '1024x576' => '1024x576 (16/9)',
60
            '1024x768' => '1000x750 (3/4)',
61
            '1280x720' => '1280x720 (16/9)',
62
            '1280x860' => '1280x960 (3/4)',
63
            '1400x1050' => '1400x1050 (3/4)',
64
            '1600x900' => '1600x900 (16/9)',
65
        ];
66
    }
67
68
    /**
69
     * Get the platform logo path.
70
     *
71
     * @param string $theme
72
     * @param bool   $getSysPath
73
     * @param bool   $forcedGetter
74
     *
75
     * @return string
76
     */
77
    public static function getPlatformLogoPath($theme = '', $getSysPath = false, $forcedGetter = false)
78
    {
79
        static $logoPath;
80
81
        // If call from CLI it should be reload.
82
        if ('cli' === PHP_SAPI) {
83
            $logoPath = null;
84
        }
85
86
        if (!isset($logoPath) || $forcedGetter) {
87
        $theme = empty($theme) ? api_get_visual_theme() : $theme;
88
        $accessUrlId = api_get_current_access_url_id();
89
            if ('cli' === PHP_SAPI) {
90
                $accessUrl = api_get_configuration_value('access_url');
91
                if (!empty($accessUrl)) {
92
                    $accessUrlId = $accessUrl;
93
                }
94
            }
95
        $themeDir = \Template::getThemeDir($theme);
96
        $customLogoPath = $themeDir."images/header-logo-custom$accessUrlId.png";
97
98
            $svgIcons = api_get_setting('icons_mode_svg');
99
            if ($svgIcons === 'true') {
100
                $customLogoPathSVG = substr($customLogoPath, 0, -3).'svg';
101
                if (file_exists(api_get_path(SYS_PUBLIC_PATH)."css/$customLogoPathSVG")) {
102
                    if ($getSysPath) {
103
                        $logoPath = api_get_path(SYS_PUBLIC_PATH)."css/$customLogoPathSVG";
104
105
                        return $logoPath;
106
                    }
107
                    $logoPath = api_get_path(WEB_CSS_PATH).$customLogoPathSVG;
108
109
                    return $logoPath;
110
                }
111
            }
112
        if (file_exists(api_get_path(SYS_PUBLIC_PATH)."css/$customLogoPath")) {
113
            if ($getSysPath) {
114
                    $logoPath = api_get_path(SYS_PUBLIC_PATH)."css/$customLogoPath";
115
116
                    return $logoPath;
117
            }
118
119
                $logoPath = api_get_path(WEB_CSS_PATH).$customLogoPath;
120
121
                return $logoPath;
122
        }
123
124
            $originalLogoPath = $themeDir."images/header-logo.png";
125
            if ($svgIcons === 'true') {
126
                $originalLogoPathSVG = $themeDir."images/header-logo.svg";
127
                if (file_exists(api_get_path(SYS_CSS_PATH).$originalLogoPathSVG)) {
128
                    if ($getSysPath) {
129
                        $logoPath = api_get_path(SYS_CSS_PATH).$originalLogoPathSVG;
130
131
                        return $logoPath;
132
                    }
133
                    $logoPath = api_get_path(WEB_CSS_PATH).$originalLogoPathSVG;
134
135
                    return $logoPath;
136
                }
137
            }
138
139
        if (file_exists(api_get_path(SYS_CSS_PATH).$originalLogoPath)) {
140
            if ($getSysPath) {
141
                    $logoPath = api_get_path(SYS_CSS_PATH).$originalLogoPath;
142
143
                    return $logoPath;
144
            }
145
146
                $logoPath = api_get_path(WEB_CSS_PATH).$originalLogoPath;
147
148
                return $logoPath;
149
            }
150
            $logoPath = '';
151
        }
152
153
        return $logoPath;
154
    }
155
156
    /**
157
     * Get the platform logo.
158
     * Return a <img> if the logo image exists. Otherwise return a <h2> with the institution name.
159
     *
160
     * @param string $theme
161
     * @param array  $imageAttributes optional
162
     * @param bool   $getSysPath
163
     * @param bool   $forcedGetter
164
     *
165
     * @return string
166
     */
167
    public static function getPlatformLogo(
168
        $theme = '',
169
        $imageAttributes = [],
170
        $getSysPath = false,
171
        $forcedGetter = false
172
    ) {
173
        $logoPath = self::getPlatformLogoPath($theme, $getSysPath, $forcedGetter);
174
        $institution = api_get_setting('Institution');
175
        $institutionUrl = api_get_setting('InstitutionUrl');
176
        $siteName = api_get_setting('siteName');
177
178
        if (null === $logoPath) {
179
            $headerLogo = \Display::url($siteName, api_get_path(WEB_PATH).'index.php');
180
181
            if (!empty($institutionUrl) && !empty($institution)) {
182
                $headerLogo .= ' - '.\Display::url($institution, $institutionUrl);
183
            }
184
185
            $courseInfo = api_get_course_info();
186
            if (isset($courseInfo['extLink']) && !empty($courseInfo['extLink']['name'])) {
187
                $headerLogo .= '<span class="extLinkSeparator"> - </span>';
188
189
                if (!empty($courseInfo['extLink']['url'])) {
190
                    $headerLogo .= \Display::url(
191
                        $courseInfo['extLink']['name'],
192
                        $courseInfo['extLink']['url'],
193
                        ['class' => 'extLink']
194
                    );
195
                } elseif (!empty($courseInfo['extLink']['url'])) {
196
                    $headerLogo .= $courseInfo['extLink']['url'];
197
                }
198
            }
199
200
            return \Display::tag('h2', $headerLogo, ['class' => 'text-left']);
201
        }
202
203
        $image = \Display::img($logoPath, $institution, $imageAttributes);
204
205
        return \Display::url($image, api_get_path(WEB_PATH).'index.php');
206
    }
207
208
    /**
209
     * Like strip_tags(), but leaves an additional space and removes only the given tags.
210
     *
211
     * @param string $string
212
     * @param array  $tags   Tags to be removed
213
     *
214
     * @return string The original string without the given tags
215
     */
216
    public static function stripGivenTags($string, $tags)
217
    {
218
        foreach ($tags as $tag) {
219
            $string2 = preg_replace('#</\b'.$tag.'\b[^>]*>#i', ' ', $string);
220
            if ($string2 != $string) {
221
                $string = preg_replace('/<\b'.$tag.'\b[^>]*>/i', ' ', $string2);
222
            }
223
        }
224
225
        return $string;
226
    }
227
228
    /**
229
     * Adds or Subtract a time in hh:mm:ss to a datetime.
230
     *
231
     * @param string $time      Time to add or substract in hh:mm:ss format
232
     * @param string $datetime  Datetime to be modified as accepted by the Datetime class constructor
233
     * @param bool   $operation True for Add, False to Subtract
234
     *
235
     * @return string
236
     */
237
    public static function addOrSubTimeToDateTime($time, $datetime = 'now', $operation = true)
238
    {
239
        $date = new \DateTime($datetime);
240
        $hours = $minutes = $seconds = 0;
241
        sscanf($time, '%d:%d:%d', $hours, $minutes, $seconds);
242
        $timeSeconds = isset($seconds) ? $hours * 3600 + $minutes * 60 + $seconds : $hours * 60 + $minutes;
243
        if ($operation) {
244
            $date->add(new \DateInterval('PT'.$timeSeconds.'S'));
245
        } else {
246
            $date->sub(new \DateInterval('PT'.$timeSeconds.'S'));
247
        }
248
249
        return $date->format('Y-m-d H:i:s');
250
    }
251
252
    /**
253
     * Returns the course id (integer) for the given course directory or the current ID if no directory is defined.
254
     *
255
     * @param string $directory The course directory/path that appears in the URL
256
     *
257
     * @return int
258
     */
259
    public static function getCourseIdByDirectory($directory = null)
260
    {
261
        if (!empty($directory)) {
262
            $directory = \Database::escape_string($directory);
263
            $row = \Database::select(
264
                'id',
265
                \Database::get_main_table(TABLE_MAIN_COURSE),
266
                ['where' => ['directory = ?' => [$directory]]],
267
                'first'
268
            );
269
270
            if (is_array($row) && isset($row['id'])) {
271
                return $row['id'];
272
            } else {
273
                return false;
274
            }
275
        }
276
277
        return Session::read('_real_cid', 0);
278
    }
279
280
    /**
281
     * Check if the current HTTP request is by AJAX.
282
     *
283
     * @return bool
284
     */
285
    public static function isAjaxRequest()
286
    {
287
        $requestedWith = isset($_SERVER['HTTP_X_REQUESTED_WITH']) ? $_SERVER['HTTP_X_REQUESTED_WITH'] : null;
288
289
        return 'XMLHttpRequest' === $requestedWith;
290
    }
291
292
    /**
293
     * Get a variable name for language file from a text.
294
     *
295
     * @param string $text
296
     * @param string $prefix
297
     *
298
     * @return string
299
     */
300
    public static function getLanguageVar($text, $prefix = '')
301
    {
302
        $text = api_replace_dangerous_char($text);
303
        $text = str_replace(['-', ' ', '.'], '_', $text);
304
        $text = preg_replace('/\_{1,}/', '_', $text);
305
        //$text = str_replace('_', '', $text);
306
        $text = api_underscore_to_camel_case($text);
307
308
        return $prefix.$text;
309
    }
310
311
    /**
312
     * Get the stylesheet path for HTML documents created with CKEditor.
313
     *
314
     * @return string
315
     */
316
    public static function getEditorDocStylePath()
317
    {
318
        $visualTheme = api_get_visual_theme();
319
320
        $cssFile = api_get_path(SYS_CSS_PATH)."themes/$visualTheme/document.css";
321
322
        if (is_file($cssFile)) {
323
            return api_get_path(WEB_CSS_PATH)."themes/$visualTheme/document.css";
324
        }
325
326
        return api_get_path(WEB_CSS_PATH).'document.css';
327
    }
328
329
    /**
330
     * Get the stylesheet path for HTML blocks created with CKEditor.
331
     *
332
     * @return string
333
     */
334
    public static function getEditorBlockStylePath()
335
    {
336
        $visualTheme = api_get_visual_theme();
337
338
        $cssFile = api_get_path(SYS_CSS_PATH)."themes/$visualTheme/editor_content.css";
339
340
        if (is_file($cssFile)) {
341
            return api_get_path(WEB_CSS_PATH)."themes/$visualTheme/editor_content.css";
342
        }
343
344
        return api_get_path(WEB_CSS_PATH).'editor_content.css';
345
    }
346
347
    /**
348
     * Get a list of colors from the palette at main/palette/pchart/default.color
349
     * and return it as an array of strings.
350
     *
351
     * @param bool $decimalOpacity Whether to return the opacity as 0..100 or 0..1
352
     * @param bool $wrapInRGBA     Whether to return it as 1,1,1,100 or rgba(1,1,1,100)
353
     * @param int  $fillUpTo       If the number of colors is smaller than this number, generate more colors
354
     *
355
     * @return array An array of string colors
356
     */
357
    public static function getColorPalette(
358
        $decimalOpacity = false,
359
        $wrapInRGBA = false,
360
        $fillUpTo = null
361
    ) {
362
        // Get the common colors from the palette used for pchart
363
        $paletteFile = api_get_path(SYS_CODE_PATH).'palettes/pchart/default.color';
364
        $palette = file($paletteFile);
365
        if ($decimalOpacity) {
366
            // Because the pchart palette has transparency as integer values
367
            // (0..100) and chartjs uses percentage (0.0..1.0), we need to divide
368
            // the last value by 100, which is a bit overboard for just one chart
369
            foreach ($palette as $index => $color) {
370
                $components = preg_split('/,/', trim($color));
371
                $components[3] = round($components[3] / 100, 1);
372
                $palette[$index] = implode(',', $components);
373
            }
374
        }
375
        if ($wrapInRGBA) {
376
            foreach ($palette as $index => $color) {
377
                $color = trim($color);
378
                $palette[$index] = 'rgba('.$color.')';
379
            }
380
        }
381
        // If we want more colors, loop through existing colors
382
        $count = count($palette);
383
        if (isset($fillUpTo) && $fillUpTo > $count) {
384
            for ($i = $count; $i < $fillUpTo; $i++) {
385
                $palette[$i] = $palette[$i % $count];
386
            }
387
        }
388
389
        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...
390
    }
391
392
    /**
393
     * Get the local time for the midnight.
394
     *
395
     * @param string|null $utcTime Optional. The time to ve converted.
396
     *                             See api_get_local_time.
397
     *
398
     * @throws \Exception
399
     *
400
     * @return \DateTime
401
     */
402
    public static function getServerMidnightTime($utcTime = null)
403
    {
404
        $localTime = api_get_local_time($utcTime);
405
        $localTimeZone = api_get_timezone();
406
407
        $localMidnight = new \DateTime($localTime, new \DateTimeZone($localTimeZone));
408
        $localMidnight->modify('midnight');
409
410
        return $localMidnight;
411
    }
412
413
    /**
414
     * Get JavaScript code necessary to load quiz markers-rolls in medialement's Markers Rolls plugin.
415
     *
416
     * @return string
417
     */
418
    public static function getQuizMarkersRollsJS()
419
    {
420
        $webCodePath = api_get_path(WEB_CODE_PATH);
421
        $cidReq = api_get_cidreq(true, true, 'embeddable');
422
        $colorPalette = self::getColorPalette(false, true);
423
424
        return "
425
            var \$originalNode = $(originalNode),
426
                    qMarkersRolls = \$originalNode.data('q-markersrolls') || [],
427
                    qMarkersColor = \$originalNode.data('q-markersrolls-color') || '{$colorPalette[0]}';
428
429
                if (0 == qMarkersRolls.length) {
430
                    return;
431
                }
432
433
                instance.options.markersRollsColor = qMarkersColor;
434
                instance.options.markersRollsWidth = 2;
435
                instance.options.markersRolls = {};
436
437
                qMarkersRolls.forEach(function (qMarkerRoll) {
438
                    var url = '{$webCodePath}exercise/exercise_submit.php?$cidReq&'
439
                        + $.param({
440
                            exerciseId: qMarkerRoll[1],
441
                            learnpath_id: 0,
442
                            learnpath_item_id: 0,
443
                            learnpath_item_view_id: 0
444
                        });
445
446
                    instance.options.markersRolls[qMarkerRoll[0]] = url;
447
                });
448
449
                instance.buildmarkersrolls(instance, instance.controls, instance.layers, instance.media);
450
        ";
451
    }
452
}
453