Passed
Push — master ( 47a7d1...35a4a4 )
by
unknown
15:07 queued 07:41
created

CkEditor::getFileManagerPicker()   A

Complexity

Conditions 4
Paths 6

Size

Total Lines 25
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 14
nop 0
dl 0
loc 25
rs 9.7998
c 0
b 0
f 0
nc 6
1
<?php
2
3
declare(strict_types=1);
4
5
/* For licensing terms, see /license.txt */
6
7
namespace Chamilo\CoreBundle\Component\Editor\CkEditor;
8
9
use Chamilo\CoreBundle\Component\Editor\Editor;
10
use Chamilo\CoreBundle\Component\Utils\ChamiloApi;
11
use Chamilo\CoreBundle\Entity\Course;
12
use Chamilo\CoreBundle\Entity\SystemTemplate;
13
use Chamilo\CoreBundle\Entity\Templates;
14
use Database;
15
16
class CkEditor extends Editor
17
{
18
    /**
19
     * Return the HTML code required to run editor.
20
     *
21
     * @param string $value
22
     */
23
    public function createHtml($value): string
24
    {
25
        $html = '<textarea id="'.$this->getTextareaId().'" name="'.$this->getName().'" >
26
                 '.$value.'
27
                 </textarea>';
28
        $html .= $this->editorReplace();
29
30
        return $html;
31
    }
32
33
    /**
34
     * Return the HTML code required to run editor.
35
     *
36
     * @param string $value
37
     */
38
    public function createHtmlStyle($value): string
39
    {
40
        $style = '';
41
        $value = trim($value);
42
43
        if ('' === $value || '<html><head><title></title></head><body></body></html>' === $value) {
44
            $style = api_get_bootstrap_and_font_awesome();
45
            $style .= api_get_css(ChamiloApi::getEditorDocStylePath());
46
        }
47
48
        $html = '<textarea id="'.$this->getTextareaId().'" name="'.$this->getName().'" >
49
                 '.$style.$value.'
50
                 </textarea>';
51
        $html .= $this->editorReplace();
52
53
        return $html;
54
    }
55
56
    public function editorReplace(): string
57
    {
58
        $toolbar = new Toolbar\Basic(
59
            $this->urlGenerator,
60
            $this->toolbarSet,
61
            $this->config,
62
            'CkEditor'
63
        );
64
65
        $config = $toolbar->getConfig();
66
        $config['selector'] = '#'.$this->getTextareaId();
67
        $javascript = $this->toJavascript($config);
68
69
        // it replaces [browser] by image picker callback
70
        $javascript = str_replace('"[browser]"', $this->getFileManagerPicker(), $javascript);
71
72
        return "<script>
73
            window.addEventListener('message', function(event) {
74
                if (event.data.url) {
75
                    if (window.parent.tinyMCECallback) {
76
                        window.parent.tinyMCECallback(event.data.url);
77
                        delete window.parent.tinyMCECallback;
78
                    }
79
                }
80
            });
81
            document.addEventListener('DOMContentLoaded', function() {
82
                window.chEditors = window.chEditors || [];
83
                window.chEditors.push($javascript)
84
           });
85
           </script>";
86
    }
87
88
    /**
89
     * @param array $templates
90
     */
91
    public function formatTemplates($templates): string
92
    {
93
        if (empty($templates)) {
94
            return '';
95
        }
96
        $templateList = [];
97
        $cssTheme = api_get_path(WEB_CSS_PATH).'themes/'.api_get_visual_theme().'/';
98
        $search = ['{CSS_THEME}', '{IMG_DIR}', '{REL_PATH}', '{COURSE_DIR}', '{CSS}'];
99
        $replace = [
100
            $cssTheme,
101
            api_get_path(REL_CODE_PATH).'img/',
102
            api_get_path(REL_PATH),
103
            // api_get_path(REL_DEFAULT_COURSE_DOCUMENT_PATH),
104
            '',
105
        ];
106
107
        /** @var SystemTemplate $template */
108
        foreach ($templates as $template) {
109
            $image = $template->getImage();
110
            $image = !empty($image) ? $image : 'empty.gif';
111
112
            /*$image = $this->urlGenerator->generate(
113
                'get_document_template_action',
114
                array('file' => $image),
115
                UrlGenerator::ABSOLUTE_URL
116
            );*/
117
118
            $content = str_replace($search, $replace, $template->getContent());
119
120
            $templateList[] = [
121
                'title' => $this->translator->trans($template->getTitle()),
122
                'description' => $this->translator->trans($template->getComment()),
123
                'image' => $image,
124
                'html' => $content,
125
            ];
126
        }
127
128
        return json_encode($templateList);
129
    }
130
131
    /**
132
     * Get the templates in JSON format.
133
     *
134
     * @return false|string
135
     */
136
    public function simpleFormatTemplates()
137
    {
138
        $templates = $this->getEmptyTemplate();
139
140
        if (api_is_allowed_to_edit(false, true)) {
141
            $platformTemplates = $this->getPlatformTemplates();
142
            $templates = array_merge($templates, $platformTemplates);
143
        }
144
145
        $personalTemplates = $this->getPersonalTemplates();
146
        $templates = array_merge($templates, $personalTemplates);
147
148
        return json_encode($templates);
149
    }
150
151
    /**
152
     * Get a custom image picker.
153
     *
154
     * @return string
155
     */
156
    private function getImagePicker(): string
157
    {
158
        return 'function (cb, value, meta) {
159
            var input = document.createElement("input");
160
            input.setAttribute("type", "file");
161
            input.setAttribute("accept", "image/*");
162
            input.onchange = function () {
163
                var file = this.files[0];
164
                var reader = new FileReader();
165
                reader.onload = function () {
166
                    var id = "blobid" + (new Date()).getTime();
167
                    var blobCache =  tinymce.activeEditor.editorUpload.blobCache;
168
                    var base64 = reader.result.split(",")[1];
169
                    var blobInfo = blobCache.create(id, file, base64);
170
                    blobCache.add(blobInfo);
171
                    cb(blobInfo.blobUri(), { title: file.name });
172
                };
173
                reader.readAsDataURL(file);
174
            };
175
            input.click();
176
        }';
177
    }
178
179
    /**
180
     * Generates the JavaScript function for opening the file manager picker in TinyMCE.
181
     *
182
     * Determines the URL based on whether the context is a course or a user.
183
     * Falls back to the image picker if neither is found.
184
     *
185
     * @return string The JavaScript function for TinyMCE's file manager picker.
186
     */
187
    private function getFileManagerPicker(): string
188
    {
189
        $course = api_get_course_entity();
190
        $user = api_get_user_entity();
191
192
        $url = null;
193
        if (null !== $course) {
194
            $resourceNodeId = $course->getResourceNode()->getId();
195
            $url = api_get_path(WEB_PATH).'resources/document/'.$resourceNodeId.'/manager?'.api_get_cidreq().'&type=images';
196
        } else {
197
            if (null !== $user) {
198
                $resourceNodeId = $user->getResourceNode()->getId();
199
                $url = api_get_path(WEB_PATH).'resources/filemanager/personal_list/'.$resourceNodeId;
200
            }
201
        }
202
203
        if (null === $url) {
204
            return $this->getImagePicker();
205
        }
206
207
        return '
208
            function(cb, value, meta) {
209
                window.tinyMCECallback = cb;
210
                let fileType = meta.filetype;
211
                let fileManagerUrl = "'.$url.'";
212
213
                if (fileType === "image") {
214
                    fileManagerUrl += "?type=images";
215
                } else if (fileType === "file") {
216
                    fileManagerUrl += "?type=files";
217
                }
218
219
                tinymce.activeEditor.windowManager.openUrl({
220
                    title: "File Manager",
221
                    url: fileManagerUrl,
222
                    width: 950,
223
                    height: 450
224
                });
225
            }
226
        ';
227
    }
228
229
    /**
230
     * Get the empty template.
231
     */
232
    private function getEmptyTemplate(): array
233
    {
234
        return [
235
            [
236
                'title' => get_lang('Blank template'),
237
                'description' => null,
238
                'image' => api_get_path(WEB_PUBLIC_PATH).'img/template_thumb/empty.gif',
239
                'html' => '
240
                <!DOCYTPE html>
241
                <html>
242
                    <head>
243
                        <meta charset="'.api_get_system_encoding().'" />
244
                    </head>
245
                    <body  dir="'.api_get_text_direction().'">
246
                        <p>
247
                            <br/>
248
                        </p>
249
                    </body>
250
                    </html>
251
                </html>
252
            ',
253
            ],
254
        ];
255
    }
256
257
    /**
258
     * Get the platform templates.
259
     */
260
    private function getPlatformTemplates(): array
261
    {
262
        $entityManager = Database::getManager();
263
        $systemTemplates = $entityManager->getRepository(SystemTemplate::class)->findAll();
264
        $cssTheme = api_get_path(WEB_CSS_PATH).'themes/'.api_get_visual_theme().'/';
265
        $search = ['{CSS_THEME}', '{IMG_DIR}', '{REL_PATH}', '{COURSE_DIR}', '{CSS}'];
266
        $replace = [
267
            $cssTheme,
268
            api_get_path(REL_PATH).'public/img/',
269
            api_get_path(REL_PATH),
270
            api_get_path(REL_PATH).'public/img/document/',
271
            '',
272
        ];
273
274
        $templateList = [];
275
276
        foreach ($systemTemplates as $template) {
277
            $image = $template->getImage();
278
            $image = !empty($image) ? $image : 'empty.gif';
279
            $image = api_get_path(WEB_PUBLIC_PATH).'img/template_thumb/'.$image;
280
            $templateContent = $template->getContent();
281
            $content = str_replace($search, $replace, $templateContent);
282
283
            $templateList[] = [
284
                'title' => get_lang($template->getTitle()),
285
                'description' => get_lang($template->getComment()),
286
                'image' => $image,
287
                'html' => $content,
288
            ];
289
        }
290
291
        return $templateList;
292
    }
293
294
    /**
295
     * @param int $userId
296
     *
297
     * @return array
298
     */
299
    private function getPersonalTemplates($userId = 0)
300
    {
301
        if (empty($userId)) {
302
            $userId = api_get_user_id();
303
        }
304
305
        $entityManager = Database::getManager();
306
        $templatesRepo = $entityManager->getRepository(Templates::class);
307
        $user = api_get_user_entity($userId);
308
        $course = $entityManager->find(Course::class, api_get_course_int_id());
309
310
        if (!$user || !$course) {
311
            return [];
312
        }
313
314
        $courseTemplates = $templatesRepo->getCourseTemplates($course, $user);
315
        $templateList = [];
316
317
        foreach ($courseTemplates as $templateData) {
318
            $template = $templateData[0];
319
320
            $templateItem = [];
321
            $templateItem['title'] = $template->getTitle();
322
            $templateItem['description'] = $template->getDescription();
323
            $templateItem['image'] = api_get_path(WEB_PUBLIC_PATH).'img/template_thumb/noimage.gif';
324
            /*$templateItem['html'] = file_get_contents(api_get_path(SYS_COURSE_PATH)
325
                .$courseDirectory.'/document'.$templateData['path']);*/
326
327
            $image = $template->getImage();
328
            if (!empty($image)) {
329
                $templateItem['image'] = api_get_path(WEB_COURSE_PATH)
330
                    .$courseDirectory.'/upload/template_thumbnails/'.$template->getImage();
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $courseDirectory does not exist. Did you maybe mean $course?
Loading history...
331
            }
332
333
            $templateList[] = $templateItem;
334
        }
335
336
        return $templateList;
337
    }
338
}
339