Passed
Pull Request — 1.11.x (#4368)
by Angel Fernando Quiroz
08:11
created

PortfolioController::fixImagesSourcesToHtml()   B

Complexity

Conditions 6
Paths 6

Size

Total Lines 42
Code Lines 22

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
eloc 22
nc 6
nop 1
dl 0
loc 42
rs 8.9457
c 0
b 0
f 0
1
<?php
2
3
/* For licensing terms, see /license.txt */
4
5
use Chamilo\CoreBundle\Component\Utils\ChamiloApi;
6
use Chamilo\CoreBundle\Entity\Course as CourseEntity;
7
use Chamilo\CoreBundle\Entity\ExtraField as ExtraFieldEntity;
8
use Chamilo\CoreBundle\Entity\ExtraFieldRelTag;
9
use Chamilo\CoreBundle\Entity\Portfolio;
10
use Chamilo\CoreBundle\Entity\PortfolioAttachment;
11
use Chamilo\CoreBundle\Entity\PortfolioCategory;
12
use Chamilo\CoreBundle\Entity\PortfolioComment;
13
use Chamilo\CoreBundle\Entity\Tag;
14
use Chamilo\UserBundle\Entity\User;
15
use Doctrine\ORM\Query\Expr\Join;
16
use Symfony\Component\Filesystem\Filesystem;
17
use Symfony\Component\HttpFoundation\Request as HttpRequest;
0 ignored issues
show
Bug introduced by
This use statement conflicts with another class in this namespace, HttpRequest. Consider defining an alias.

Let?s assume that you have a directory layout like this:

.
|-- OtherDir
|   |-- Bar.php
|   `-- Foo.php
`-- SomeDir
    `-- Foo.php

and let?s assume the following content of Bar.php:

// Bar.php
namespace OtherDir;

use SomeDir\Foo; // This now conflicts the class OtherDir\Foo

If both files OtherDir/Foo.php and SomeDir/Foo.php are loaded in the same runtime, you will see a PHP error such as the following:

PHP Fatal error:  Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.php

However, as OtherDir/Foo.php does not necessarily have to be loaded and the error is only triggered if it is loaded before OtherDir/Bar.php, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias:

// Bar.php
namespace OtherDir;

use SomeDir\Foo as SomeDirFoo; // There is no conflict anymore.
Loading history...
18
19
/**
20
 * Class PortfolioController.
21
 */
22
class PortfolioController
23
{
24
    /**
25
     * @var string
26
     */
27
    public $baseUrl;
28
    /**
29
     * @var CourseEntity|null
30
     */
31
    private $course;
32
    /**
33
     * @var \Chamilo\CoreBundle\Entity\Session|null
34
     */
35
    private $session;
36
    /**
37
     * @var \Chamilo\UserBundle\Entity\User
38
     */
39
    private $owner;
40
    /**
41
     * @var \Doctrine\ORM\EntityManager
42
     */
43
    private $em;
44
45
    /**
46
     * PortfolioController constructor.
47
     */
48
    public function __construct()
49
    {
50
        $this->em = Database::getManager();
51
52
        $this->owner = api_get_user_entity(api_get_user_id());
53
        $this->course = api_get_course_entity(api_get_course_int_id());
54
        $this->session = api_get_session_entity(api_get_session_id());
55
56
        $cidreq = api_get_cidreq();
57
        $this->baseUrl = api_get_self().'?'.($cidreq ? $cidreq.'&' : '');
58
    }
59
60
    /**
61
     * @throws \Doctrine\ORM\ORMException
62
     * @throws \Doctrine\ORM\OptimisticLockException
63
     */
64
    public function translateCategory($category, $languages, $languageId)
65
    {
66
        global $interbreadcrumb;
67
68
        $originalName = $category->getTitle();
69
        $variableLanguage = '$'.$this->getLanguageVariable($originalName);
70
71
        $translateUrl = api_get_path(WEB_AJAX_PATH).'lang.ajax.php?a=translate_portfolio_category&sec_token='.Security::get_token();
72
        $form = new FormValidator('new_lang_variable', 'POST', $translateUrl);
73
        $form->addHeader(get_lang('AddWordForTheSubLanguage'));
74
        $form->addText('variable_language', get_lang('LanguageVariable'), false);
75
        $form->addText('original_name', get_lang('OriginalName'), false);
76
77
        $languagesOptions = [0 => get_lang('None')];
78
        foreach ($languages as $language) {
79
            $languagesOptions[$language->getId()] = $language->getOriginalName();
80
        }
81
82
        $form->addSelect(
83
            'sub_language',
84
            [get_lang('SubLanguage'), get_lang('OnlyActiveSubLanguagesAreListed')],
85
            $languagesOptions
86
        );
87
88
        if ($languageId) {
89
            $languageInfo = api_get_language_info($languageId);
90
            $form->addText(
91
                'new_language',
92
                [get_lang('Translation'), get_lang('IfThisTranslationExistsThisWillReplaceTheTerm')]
93
            );
94
95
            $form->addHidden('category_id', $category->getId());
96
            $form->addHidden('id', $languageInfo['parent_id']);
97
            $form->addHidden('sub', $languageInfo['id']);
98
            $form->addHidden('sub_language_id', $languageInfo['id']);
99
            $form->addHidden('redirect', true);
100
            $form->addButtonSave(get_lang('Save'));
101
        }
102
103
        $form->setDefaults([
104
            'variable_language' => $variableLanguage,
105
            'original_name' => $originalName,
106
            'sub_language' => $languageId,
107
        ]);
108
        $form->addRule('sub_language', get_lang('Required'), 'required');
109
        $form->freeze(['variable_language', 'original_name']);
110
111
        $interbreadcrumb[] = [
112
            'name' => get_lang('Portfolio'),
113
            'url' => $this->baseUrl,
114
        ];
115
        $interbreadcrumb[] = [
116
            'name' => get_lang('Categories'),
117
            'url' => $this->baseUrl.'action=list_categories&parent_id='.$category->getParentId(),
118
        ];
119
        $interbreadcrumb[] = [
120
            'name' => Security::remove_XSS($category->getTitle()),
121
            'url' => $this->baseUrl.'action=edit_category&id='.$category->getId(),
122
        ];
123
124
        $actions = [];
125
        $actions[] = Display::url(
126
            Display::return_icon('back.png', get_lang('Back'), [], ICON_SIZE_MEDIUM),
127
            $this->baseUrl.'action=edit_category&id='.$category->getId()
128
        );
129
130
        $js = '<script>
131
            $(function() {
132
              $("select[name=\'sub_language\']").on("change", function () {
133
                    location.href += "&sub_language=" + this.value;
134
                });
135
            });
136
        </script>';
137
        $content = $form->returnForm();
138
139
        $this->renderView($content.$js, get_lang('TranslateCategory'), $actions);
140
    }
141
142
    /**
143
     * @throws \Doctrine\ORM\ORMException
144
     * @throws \Doctrine\ORM\OptimisticLockException
145
     */
146
    public function listCategories()
147
    {
148
        global $interbreadcrumb;
149
150
        $parentId = isset($_REQUEST['parent_id']) ? (int) $_REQUEST['parent_id'] : 0;
151
        $table = new HTML_Table(['class' => 'table table-hover table-striped data_table']);
152
        $headers = [
153
            get_lang('Title'),
154
            get_lang('Description'),
155
        ];
156
        if ($parentId === 0) {
157
            $headers[] = get_lang('SubCategories');
158
        }
159
        $headers[] = get_lang('Actions');
160
161
        $column = 0;
162
        foreach ($headers as $header) {
163
            $table->setHeaderContents(0, $column, $header);
164
            $column++;
165
        }
166
        $currentUserId = api_get_user_id();
167
        $row = 1;
168
        $categories = $this->getCategoriesForIndex(null, $parentId);
169
170
        foreach ($categories as $category) {
171
            $column = 0;
172
            $subcategories = $this->getCategoriesForIndex(null, $category->getId());
173
            $linkSubCategories = $category->getTitle();
174
            if (count($subcategories) > 0) {
175
                $linkSubCategories = Display::url(
176
                    $category->getTitle(),
177
                    $this->baseUrl.'action=list_categories&parent_id='.$category->getId()
178
                );
179
            }
180
            $table->setCellContents($row, $column++, $linkSubCategories);
181
            $table->setCellContents($row, $column++, strip_tags($category->getDescription()));
182
            if ($parentId === 0) {
183
                $table->setCellContents($row, $column++, count($subcategories));
184
            }
185
186
            // Actions
187
            $links = null;
188
            // Edit action
189
            $url = $this->baseUrl.'action=edit_category&id='.$category->getId();
190
            $links .= Display::url(Display::return_icon('edit.png', get_lang('Edit')), $url).'&nbsp;';
191
            // Visible action : if active
192
            if ($category->isVisible() != 0) {
193
                $url = $this->baseUrl.'action=hide_category&id='.$category->getId();
194
                $links .= Display::url(Display::return_icon('visible.png', get_lang('Hide')), $url).'&nbsp;';
195
            } else { // else if not active
196
                $url = $this->baseUrl.'action=show_category&id='.$category->getId();
197
                $links .= Display::url(Display::return_icon('invisible.png', get_lang('Show')), $url).'&nbsp;';
198
            }
199
            // Delete action
200
            $url = $this->baseUrl.'action=delete_category&id='.$category->getId();
201
            $links .= Display::url(Display::return_icon('delete.png', get_lang('Delete')), $url, ['onclick' => 'javascript:if(!confirm(\''.get_lang('AreYouSureToDeleteJS').'\')) return false;']);
202
203
            $table->setCellContents($row, $column++, $links);
204
            $row++;
205
        }
206
207
        $interbreadcrumb[] = [
208
            'name' => get_lang('Portfolio'),
209
            'url' => $this->baseUrl,
210
        ];
211
        if ($parentId > 0) {
212
            $interbreadcrumb[] = [
213
                'name' => get_lang('Categories'),
214
                'url' => $this->baseUrl.'action=list_categories',
215
            ];
216
        }
217
218
        $actions = [];
219
        $actions[] = Display::url(
220
            Display::return_icon('back.png', get_lang('Back'), [], ICON_SIZE_MEDIUM),
221
            $this->baseUrl.($parentId > 0 ? 'action=list_categories' : '')
222
        );
223
        if ($currentUserId == $this->owner->getId() && $parentId === 0) {
224
            $actions[] = Display::url(
225
                Display::return_icon('new_folder.png', get_lang('AddCategory'), [], ICON_SIZE_MEDIUM),
226
                $this->baseUrl.'action=add_category'
227
            );
228
        }
229
        $content = $table->toHtml();
230
231
        $pageTitle = get_lang('Categories');
232
        if ($parentId > 0) {
233
            $em = Database::getManager();
234
            $parentCategory = $em->find('ChamiloCoreBundle:PortfolioCategory', $parentId);
235
            $pageTitle = $parentCategory->getTitle().' : '.get_lang('SubCategories');
236
        }
237
238
        $this->renderView($content, $pageTitle, $actions);
239
    }
240
241
    /**
242
     * @throws \Doctrine\ORM\ORMException
243
     * @throws \Doctrine\ORM\OptimisticLockException
244
     */
245
    public function addCategory()
246
    {
247
        global $interbreadcrumb;
248
249
        Display::addFlash(
250
            Display::return_message(get_lang('PortfolioCategoryFieldHelp'), 'info')
251
        );
252
253
        $form = new FormValidator('add_category', 'post', "{$this->baseUrl}&action=add_category");
254
255
        if (api_get_configuration_value('save_titles_as_html')) {
256
            $form->addHtmlEditor('title', get_lang('Title'), true, false, ['ToolbarSet' => 'TitleAsHtml']);
257
        } else {
258
            $form->addText('title', get_lang('Title'));
259
            $form->applyFilter('title', 'trim');
260
        }
261
262
        $form->addHtmlEditor('description', get_lang('Description'), false, false, ['ToolbarSet' => 'Minimal']);
263
264
        $parentSelect = $form->addSelect(
265
            'parent_id',
266
            get_lang('ParentCategory')
267
        );
268
        $parentSelect->addOption(get_lang('Level0'), 0);
269
        $currentUserId = api_get_user_id();
270
        $categories = $this->getCategoriesForIndex(null, 0);
271
        foreach ($categories as $category) {
272
            $parentSelect->addOption($category->getTitle(), $category->getId());
273
        }
274
275
        $form->addButtonCreate(get_lang('Create'));
276
277
        if ($form->validate()) {
278
            $values = $form->exportValues();
279
280
            $category = new PortfolioCategory();
281
            $category
282
                ->setTitle($values['title'])
283
                ->setDescription($values['description'])
284
                ->setParentId($values['parent_id'])
285
                ->setUser($this->owner);
286
287
            $this->em->persist($category);
288
            $this->em->flush();
289
290
            Display::addFlash(
291
                Display::return_message(get_lang('CategoryAdded'), 'success')
292
            );
293
294
            header("Location: {$this->baseUrl}action=list_categories");
295
            exit;
296
        }
297
298
        $interbreadcrumb[] = [
299
            'name' => get_lang('Portfolio'),
300
            'url' => $this->baseUrl,
301
        ];
302
        $interbreadcrumb[] = [
303
            'name' => get_lang('Categories'),
304
            'url' => $this->baseUrl.'action=list_categories',
305
        ];
306
307
        $actions = [];
308
        $actions[] = Display::url(
309
            Display::return_icon('back.png', get_lang('Back'), [], ICON_SIZE_MEDIUM),
310
            $this->baseUrl.'action=list_categories'
311
        );
312
313
        $content = $form->returnForm();
314
315
        $this->renderView($content, get_lang('AddCategory'), $actions);
316
    }
317
318
    /**
319
     * @throws \Doctrine\ORM\ORMException
320
     * @throws \Doctrine\ORM\OptimisticLockException
321
     * @throws \Exception
322
     */
323
    public function editCategory(PortfolioCategory $category)
324
    {
325
        global $interbreadcrumb;
326
327
        if (!api_is_platform_admin()) {
328
            api_not_allowed(true);
329
        }
330
331
        Display::addFlash(
332
            Display::return_message(get_lang('PortfolioCategoryFieldHelp'), 'info')
333
        );
334
335
        $form = new FormValidator(
336
            'edit_category',
337
            'post',
338
            $this->baseUrl."action=edit_category&id={$category->getId()}"
339
        );
340
341
        if (api_get_configuration_value('save_titles_as_html')) {
342
            $form->addHtmlEditor('title', get_lang('Title'), true, false, ['ToolbarSet' => 'TitleAsHtml']);
343
        } else {
344
            $translateUrl = $this->baseUrl.'action=translate_category&id='.$category->getId();
345
            $translateButton = Display::toolbarButton(get_lang('TranslateThisTerm'), $translateUrl, 'language', 'link');
346
            $form->addText(
347
                'title',
348
                [get_lang('Title'), $translateButton]
349
            );
350
            $form->applyFilter('title', 'trim');
351
        }
352
353
        $form->addHtmlEditor('description', get_lang('Description'), false, false, ['ToolbarSet' => 'Minimal']);
354
        $form->addButtonUpdate(get_lang('Update'));
355
        $form->setDefaults(
356
            [
357
                'title' => $category->getTitle(),
358
                'description' => $category->getDescription(),
359
            ]
360
        );
361
362
        if ($form->validate()) {
363
            $values = $form->exportValues();
364
365
            $category
366
                ->setTitle($values['title'])
367
                ->setDescription($values['description']);
368
369
            $this->em->persist($category);
370
            $this->em->flush();
371
372
            Display::addFlash(
373
                Display::return_message(get_lang('Updated'), 'success')
374
            );
375
376
            header("Location: {$this->baseUrl}action=list_categories&parent_id=".$category->getParentId());
377
            exit;
378
        }
379
380
        $interbreadcrumb[] = [
381
            'name' => get_lang('Portfolio'),
382
            'url' => $this->baseUrl,
383
        ];
384
        $interbreadcrumb[] = [
385
            'name' => get_lang('Categories'),
386
            'url' => $this->baseUrl.'action=list_categories',
387
        ];
388
        if ($category->getParentId() > 0) {
389
            $em = Database::getManager();
390
            $parentCategory = $em->find('ChamiloCoreBundle:PortfolioCategory', $category->getParentId());
391
            $pageTitle = $parentCategory->getTitle().' : '.get_lang('SubCategories');
392
            $interbreadcrumb[] = [
393
                'name' => Security::remove_XSS($pageTitle),
394
                'url' => $this->baseUrl.'action=list_categories&parent_id='.$category->getParentId(),
395
            ];
396
        }
397
398
        $actions = [];
399
        $actions[] = Display::url(
400
            Display::return_icon('back.png', get_lang('Back'), [], ICON_SIZE_MEDIUM),
401
            $this->baseUrl.'action=list_categories&parent_id='.$category->getParentId()
402
        );
403
404
        $content = $form->returnForm();
405
406
        $this->renderView($content, get_lang('EditCategory'), $actions);
407
    }
408
409
    /**
410
     * @throws \Doctrine\ORM\ORMException
411
     * @throws \Doctrine\ORM\OptimisticLockException
412
     */
413
    public function showHideCategory(PortfolioCategory $category)
414
    {
415
        if (!$this->categoryBelongToOwner($category)) {
416
            api_not_allowed(true);
417
        }
418
419
        $category->setIsVisible(!$category->isVisible());
420
421
        $this->em->persist($category);
422
        $this->em->flush();
423
424
        Display::addFlash(
425
            Display::return_message(get_lang('VisibilityChanged'), 'success')
426
        );
427
428
        header("Location: {$this->baseUrl}action=list_categories");
429
        exit;
430
    }
431
432
    /**
433
     * @throws \Doctrine\ORM\ORMException
434
     * @throws \Doctrine\ORM\OptimisticLockException
435
     */
436
    public function deleteCategory(PortfolioCategory $category)
437
    {
438
        if (!api_is_platform_admin()) {
439
            api_not_allowed(true);
440
        }
441
442
        $this->em->remove($category);
443
        $this->em->flush();
444
445
        Display::addFlash(
446
            Display::return_message(get_lang('CategoryDeleted'), 'success')
447
        );
448
449
        header("Location: {$this->baseUrl}action=list_categories");
450
        exit;
451
    }
452
453
    /**
454
     * @throws \Doctrine\ORM\ORMException
455
     * @throws \Doctrine\ORM\OptimisticLockException
456
     * @throws \Doctrine\ORM\TransactionRequiredException
457
     * @throws \Exception
458
     */
459
    public function addItem()
460
    {
461
        global $interbreadcrumb;
462
463
        $form = new FormValidator('add_portfolio', 'post', $this->baseUrl.'action=add_item');
464
465
        if (api_get_configuration_value('save_titles_as_html')) {
466
            $form->addHtmlEditor('title', get_lang('Title'), true, false, ['ToolbarSet' => 'TitleAsHtml']);
467
        } else {
468
            $form->addText('title', get_lang('Title'));
469
            $form->applyFilter('title', 'trim');
470
        }
471
        $editorConfig = [
472
            'ToolbarSet' => 'NotebookStudent',
473
            'Width' => '100%',
474
            'Height' => '400',
475
            'cols-size' => [2, 10, 0],
476
        ];
477
        $form->addHtmlEditor('content', get_lang('Content'), true, false, $editorConfig);
478
479
        $categoriesSelect = $form->addSelect(
480
            'category',
481
            [get_lang('Category'), get_lang('PortfolioCategoryFieldHelp')]
482
        );
483
        $categoriesSelect->addOption(get_lang('SelectACategory'), 0);
484
        $parentCategories = $this->getCategoriesForIndex(null, 0);
485
        foreach ($parentCategories as $parentCategory) {
486
            $categoriesSelect->addOption($this->translateDisplayName($parentCategory->getTitle()), $parentCategory->getId());
487
            $subCategories = $this->getCategoriesForIndex(null, $parentCategory->getId());
488
            if (count($subCategories) > 0) {
489
                foreach ($subCategories as $subCategory) {
490
                    $categoriesSelect->addOption(' &mdash; '.$this->translateDisplayName($subCategory->getTitle()), $subCategory->getId());
491
                }
492
            }
493
        }
494
495
        $extraField = new ExtraField('portfolio');
496
        $extra = $extraField->addElements($form);
497
498
        $this->addAttachmentsFieldToForm($form);
499
500
        $form->addButtonCreate(get_lang('Create'));
501
502
        if ($form->validate()) {
503
            $values = $form->exportValues();
504
            $currentTime = new DateTime(
505
                api_get_utc_datetime(),
506
                new DateTimeZone('UTC')
507
            );
508
509
            $portfolio = new Portfolio();
510
            $portfolio
511
                ->setTitle($values['title'])
512
                ->setContent($values['content'])
513
                ->setUser($this->owner)
514
                ->setCourse($this->course)
515
                ->setSession($this->session)
516
                ->setCategory(
517
                    $this->em->find('ChamiloCoreBundle:PortfolioCategory', $values['category'])
518
                )
519
                ->setCreationDate($currentTime)
520
                ->setUpdateDate($currentTime);
521
522
            $this->em->persist($portfolio);
523
            $this->em->flush();
524
525
            $values['item_id'] = $portfolio->getId();
526
527
            $extraFieldValue = new ExtraFieldValue('portfolio');
528
            $extraFieldValue->saveFieldValues($values);
529
530
            $this->processAttachments(
531
                $form,
532
                $portfolio->getUser(),
533
                $portfolio->getId(),
534
                PortfolioAttachment::TYPE_ITEM
535
            );
536
537
            $hook = HookPortfolioItemAdded::create();
538
            $hook->setEventData(['portfolio' => $portfolio]);
539
            $hook->notifyItemAdded();
540
541
            if (1 == api_get_course_setting('email_alert_teachers_new_post')) {
542
                if ($this->session) {
543
                    $messageCourseTitle = "{$this->course->getTitle()} ({$this->session->getName()})";
0 ignored issues
show
Bug introduced by
The method getTitle() 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

543
                    $messageCourseTitle = "{$this->course->/** @scrutinizer ignore-call */ getTitle()} ({$this->session->getName()})";

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...
544
545
                    $teachers = SessionManager::getCoachesByCourseSession(
546
                        $this->session->getId(),
547
                        $this->course->getId()
548
                    );
549
                    $userIdListToSend = array_values($teachers);
550
                } else {
551
                    $messageCourseTitle = $this->course->getTitle();
552
553
                    $teachers = CourseManager::get_teacher_list_from_course_code($this->course->getCode());
554
555
                    $userIdListToSend = array_keys($teachers);
556
                }
557
558
                $messageSubject = sprintf(get_lang('PortfolioAlertNewPostSubject'), $messageCourseTitle);
559
560
                foreach ($userIdListToSend as $userIdToSend) {
561
                    $messageContent = sprintf(
562
                        get_lang('PortfolioAlertNewPostContent'),
563
                        $this->owner->getCompleteName(),
564
                        $messageCourseTitle,
565
                        $this->baseUrl.http_build_query(['action' => 'view', 'id' => $portfolio->getId()])
566
                    );
567
568
                    MessageManager::send_message_simple($userIdToSend, $messageSubject, $messageContent, 0, false, false, [], false);
569
                }
570
            }
571
572
            Display::addFlash(
573
                Display::return_message(get_lang('PortfolioItemAdded'), 'success')
574
            );
575
576
            header("Location: $this->baseUrl");
577
            exit;
578
        }
579
580
        $interbreadcrumb[] = [
581
            'name' => get_lang('Portfolio'),
582
            'url' => $this->baseUrl,
583
        ];
584
585
        $actions = [];
586
        $actions[] = Display::url(
587
            Display::return_icon('back.png', get_lang('Back'), [], ICON_SIZE_MEDIUM),
588
            $this->baseUrl
589
        );
590
        $actions[] = '<a id="hide_bar_template" href="#" role="button">'.
591
            Display::return_icon('expand.png', get_lang('Expand'), ['id' => 'expand'], ICON_SIZE_MEDIUM).
592
            Display::return_icon('contract.png', get_lang('Collapse'), ['id' => 'contract', 'class' => 'hide'], ICON_SIZE_MEDIUM).'</a>';
593
594
        $js = '<script>
595
            $(function() {
596
                $(".scrollbar-light").scrollbar();
597
                $(".scroll-wrapper").css("height", "550px");
598
                expandColumnToogle("#hide_bar_template", {
599
                    selector: "#template_col",
600
                    width: 3
601
                }, {
602
                    selector: "#doc_form",
603
                    width: 9
604
                });
605
                CKEDITOR.on("instanceReady", function (e) {
606
                    showTemplates();
607
                });
608
                $(window).on("load", function () {
609
                    $("input[name=\'title\']").focus();
610
                });
611
                '.$extra['jquery_ready_content'].'
612
            });
613
        </script>';
614
        $content = '<div class="page-create">
615
            <div class="row" style="overflow:hidden">
616
            <div id="template_col" class="col-md-3">
617
                <div class="panel panel-default">
618
                <div class="panel-body">
619
                    <div id="frmModel" class="items-templates scrollbar-light"></div>
620
                </div>
621
                </div>
622
            </div>
623
            <div id="doc_form" class="col-md-9">
624
                '.$form->returnForm().'
625
            </div>
626
          </div></div>';
627
628
        $this->renderView(
629
            $content.$js,
630
            get_lang('AddPortfolioItem'),
631
            $actions
632
        );
633
    }
634
635
    /**
636
     * @throws \Doctrine\ORM\ORMException
637
     * @throws \Doctrine\ORM\OptimisticLockException
638
     * @throws \Doctrine\ORM\TransactionRequiredException
639
     * @throws \Exception
640
     */
641
    public function editItem(Portfolio $item)
642
    {
643
        global $interbreadcrumb;
644
645
        if (!api_is_allowed_to_edit() && !$this->itemBelongToOwner($item)) {
646
            api_not_allowed(true);
647
        }
648
649
        $itemCourse = $item->getCourse();
650
        $itemSession = $item->getSession();
651
652
        $form = new FormValidator('edit_portfolio', 'post', $this->baseUrl."action=edit_item&id={$item->getId()}");
653
654
        if (api_get_configuration_value('save_titles_as_html')) {
655
            $form->addHtmlEditor('title', get_lang('Title'), true, false, ['ToolbarSet' => 'TitleAsHtml']);
656
        } else {
657
            $form->addText('title', get_lang('Title'));
658
            $form->applyFilter('title', 'trim');
659
        }
660
661
        if ($item->getOrigin()) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $item->getOrigin() of type integer|null is loosely compared to true; this is ambiguous if the integer can be 0. You might want to explicitly use !== null instead.

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

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

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

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
662
            if (Portfolio::TYPE_ITEM === $item->getOriginType()) {
663
                $origin = $this->em->find(Portfolio::class, $item->getOrigin());
664
665
                $form->addLabel(
666
                    sprintf(get_lang('PortfolioItemFromXUser'), $origin->getUser()->getCompleteName()),
667
                    Display::panel(
668
                        Security::remove_XSS($origin->getContent())
669
                    )
670
                );
671
            } elseif (Portfolio::TYPE_COMMENT === $item->getOriginType()) {
672
                $origin = $this->em->find(PortfolioComment::class, $item->getOrigin());
673
674
                $form->addLabel(
675
                    sprintf(get_lang('PortfolioCommentFromXUser'), $origin->getAuthor()->getCompleteName()),
676
                    Display::panel(
677
                        Security::remove_XSS($origin->getContent())
678
                    )
679
                );
680
            }
681
        }
682
        $editorConfig = [
683
            'ToolbarSet' => 'NotebookStudent',
684
            'Width' => '100%',
685
            'Height' => '400',
686
            'cols-size' => [2, 10, 0],
687
        ];
688
        $form->addHtmlEditor('content', get_lang('Content'), true, false, $editorConfig);
689
        $categoriesSelect = $form->addSelect(
690
            'category',
691
            [get_lang('Category'), get_lang('PortfolioCategoryFieldHelp')]
692
        );
693
        $categoriesSelect->addOption(get_lang('SelectACategory'), 0);
694
        $parentCategories = $this->getCategoriesForIndex(null, 0);
695
        foreach ($parentCategories as $parentCategory) {
696
            $categoriesSelect->addOption($this->translateDisplayName($parentCategory->getTitle()), $parentCategory->getId());
697
            $subCategories = $this->getCategoriesForIndex(null, $parentCategory->getId());
698
            if (count($subCategories) > 0) {
699
                foreach ($subCategories as $subCategory) {
700
                    $categoriesSelect->addOption(' &mdash; '.$this->translateDisplayName($subCategory->getTitle()), $subCategory->getId());
701
                }
702
            }
703
        }
704
705
        $extraField = new ExtraField('portfolio');
706
        $extra = $extraField->addElements($form, $item->getId());
707
708
        $attachmentList = $this->generateAttachmentList($item, false);
709
710
        if (!empty($attachmentList)) {
711
            $form->addLabel(get_lang('AttachmentFiles'), $attachmentList);
712
        }
713
714
        $this->addAttachmentsFieldToForm($form);
715
716
        $form->addButtonUpdate(get_lang('Update'));
717
        $form->setDefaults(
718
            [
719
                'title' => $item->getTitle(),
720
                'content' => $item->getContent(),
721
                'category' => $item->getCategory() ? $item->getCategory()->getId() : '',
722
            ]
723
        );
724
725
        if ($form->validate()) {
726
            if ($itemCourse) {
0 ignored issues
show
introduced by
$itemCourse is of type Chamilo\CoreBundle\Entity\Course, thus it always evaluated to true.
Loading history...
727
                api_item_property_update(
728
                    api_get_course_info($itemCourse->getCode()),
729
                    TOOL_PORTFOLIO,
730
                    $item->getId(),
731
                    'PortfolioUpdated',
732
                    api_get_user_id(),
733
                    [],
734
                    null,
735
                    '',
736
                    '',
737
                    $itemSession ? $itemSession->getId() : 0
0 ignored issues
show
introduced by
$itemSession is of type Chamilo\CoreBundle\Entity\Session, thus it always evaluated to true.
Loading history...
738
                );
739
            }
740
741
            $values = $form->exportValues();
742
            $currentTime = new DateTime(api_get_utc_datetime(), new DateTimeZone('UTC'));
743
744
            $item
745
                ->setTitle($values['title'])
746
                ->setContent($values['content'])
747
                ->setUpdateDate($currentTime)
748
                ->setCategory(
749
                    $this->em->find('ChamiloCoreBundle:PortfolioCategory', $values['category'])
750
                );
751
752
            $values['item_id'] = $item->getId();
753
754
            $extraFieldValue = new ExtraFieldValue('portfolio');
755
            $extraFieldValue->saveFieldValues($values);
756
757
            $this->em->persist($item);
758
            $this->em->flush();
759
760
            $this->processAttachments(
761
                $form,
762
                $item->getUser(),
763
                $item->getId(),
764
                PortfolioAttachment::TYPE_ITEM
765
            );
766
767
            Display::addFlash(
768
                Display::return_message(get_lang('ItemUpdated'), 'success')
769
            );
770
771
            header("Location: $this->baseUrl");
772
            exit;
773
        }
774
775
        $interbreadcrumb[] = [
776
            'name' => get_lang('Portfolio'),
777
            'url' => $this->baseUrl,
778
        ];
779
        $actions = [];
780
        $actions[] = Display::url(
781
            Display::return_icon('back.png', get_lang('Back'), [], ICON_SIZE_MEDIUM),
782
            $this->baseUrl
783
        );
784
        $actions[] = '<a id="hide_bar_template" href="#" role="button">'.
785
            Display::return_icon('expand.png', get_lang('Expand'), ['id' => 'expand'], ICON_SIZE_MEDIUM).
786
            Display::return_icon('contract.png', get_lang('Collapse'), ['id' => 'contract', 'class' => 'hide'], ICON_SIZE_MEDIUM).'</a>';
787
788
        $js = '<script>
789
            $(function() {
790
                $(".scrollbar-light").scrollbar();
791
                $(".scroll-wrapper").css("height", "550px");
792
                expandColumnToogle("#hide_bar_template", {
793
                    selector: "#template_col",
794
                    width: 3
795
                }, {
796
                    selector: "#doc_form",
797
                    width: 9
798
                });
799
                CKEDITOR.on("instanceReady", function (e) {
800
                    showTemplates();
801
                });
802
                $(window).on("load", function () {
803
                    $("input[name=\'title\']").focus();
804
                });
805
                '.$extra['jquery_ready_content'].'
806
            });
807
        </script>';
808
        $content = '<div class="page-create">
809
            <div class="row" style="overflow:hidden">
810
            <div id="template_col" class="col-md-3">
811
                <div class="panel panel-default">
812
                <div class="panel-body">
813
                    <div id="frmModel" class="items-templates scrollbar-light"></div>
814
                </div>
815
                </div>
816
            </div>
817
            <div id="doc_form" class="col-md-9">
818
                '.$form->returnForm().'
819
            </div>
820
          </div></div>';
821
822
        $this->renderView(
823
            $content.$js,
824
            get_lang('EditPortfolioItem'),
825
            $actions
826
        );
827
    }
828
829
    /**
830
     * @throws \Doctrine\ORM\ORMException
831
     * @throws \Doctrine\ORM\OptimisticLockException
832
     */
833
    public function showHideItem(Portfolio $item)
834
    {
835
        if (!$this->itemBelongToOwner($item)) {
836
            api_not_allowed(true);
837
        }
838
839
        switch ($item->getVisibility()) {
840
            case Portfolio::VISIBILITY_HIDDEN:
841
                $item->setVisibility(Portfolio::VISIBILITY_VISIBLE);
842
                break;
843
            case Portfolio::VISIBILITY_VISIBLE:
844
                $item->setVisibility(Portfolio::VISIBILITY_HIDDEN_EXCEPT_TEACHER);
845
                break;
846
            case Portfolio::VISIBILITY_HIDDEN_EXCEPT_TEACHER:
847
            default:
848
                $item->setVisibility(Portfolio::VISIBILITY_HIDDEN);
849
                break;
850
        }
851
852
        $this->em->persist($item);
853
        $this->em->flush();
854
855
        Display::addFlash(
856
            Display::return_message(get_lang('VisibilityChanged'), 'success')
857
        );
858
859
        header("Location: $this->baseUrl");
860
        exit;
861
    }
862
863
    /**
864
     * @throws \Doctrine\ORM\ORMException
865
     * @throws \Doctrine\ORM\OptimisticLockException
866
     */
867
    public function deleteItem(Portfolio $item)
868
    {
869
        if (!$this->itemBelongToOwner($item)) {
870
            api_not_allowed(true);
871
        }
872
873
        $this->em->remove($item);
874
        $this->em->flush();
875
876
        Display::addFlash(
877
            Display::return_message(get_lang('ItemDeleted'), 'success')
878
        );
879
880
        header("Location: $this->baseUrl");
881
        exit;
882
    }
883
884
    /**
885
     * @throws \Exception
886
     */
887
    public function index(HttpRequest $httpRequest)
888
    {
889
        $listByUser = false;
890
        $listHighlighted = $httpRequest->query->has('list_highlighted');
891
892
        if ($httpRequest->query->has('user')) {
893
            $this->owner = api_get_user_entity($httpRequest->query->getInt('user'));
894
895
            if (empty($this->owner)) {
896
                api_not_allowed(true);
897
            }
898
899
            $listByUser = true;
900
        }
901
902
        $currentUserId = api_get_user_id();
903
904
        $actions = [];
905
906
        if (api_is_platform_admin()) {
907
            $actions[] = Display::url(
908
                Display::return_icon('add.png', get_lang('Add'), [], ICON_SIZE_MEDIUM),
909
                $this->baseUrl.'action=add_item'
910
            );
911
            $actions[] = Display::url(
912
                Display::return_icon('folder.png', get_lang('AddCategory'), [], ICON_SIZE_MEDIUM),
913
                $this->baseUrl.'action=list_categories'
914
            );
915
            $actions[] = Display::url(
916
                Display::return_icon('waiting_list.png', get_lang('PortfolioDetails'), [], ICON_SIZE_MEDIUM),
917
                $this->baseUrl.'action=details'
918
            );
919
        } else {
920
            if ($currentUserId == $this->owner->getId()) {
921
                $actions[] = Display::url(
922
                    Display::return_icon('add.png', get_lang('Add'), [], ICON_SIZE_MEDIUM),
923
                    $this->baseUrl.'action=add_item'
924
                );
925
                $actions[] = Display::url(
926
                    Display::return_icon('waiting_list.png', get_lang('PortfolioDetails'), [], ICON_SIZE_MEDIUM),
927
                    $this->baseUrl.'action=details'
928
                );
929
            } else {
930
                $actions[] = Display::url(
931
                    Display::return_icon('back.png', get_lang('Back'), [], ICON_SIZE_MEDIUM),
932
                    $this->baseUrl
933
                );
934
            }
935
        }
936
937
        $frmStudentList = null;
938
        $frmTagList = null;
939
940
        $categories = [];
941
        $portfolio = [];
942
        if ($this->course) {
943
            $frmTagList = $this->createFormTagFilter($listByUser);
944
            $frmStudentList = $this->createFormStudentFilter($listByUser, $listHighlighted);
945
            $frmStudentList->setDefaults(['user' => $this->owner->getId()]);
946
            // it translates the category title with the current user language
947
            $categories = $this->getCategoriesForIndex(null, 0);
948
            if (count($categories) > 0) {
949
                foreach ($categories as &$category) {
950
                    $translated = $this->translateDisplayName($category->getTitle());
951
                    $category->setTitle($translated);
952
                }
953
            }
954
        } else {
955
            // it displays the list in Network Social for the current user
956
            $portfolio = $this->getCategoriesForIndex();
957
        }
958
959
        if ($listHighlighted) {
960
            $items = $this->getHighlightedItems();
961
        } else {
962
            $items = $this->getItemsForIndex($listByUser, $frmTagList);
963
        }
964
965
        // it gets and translate the sub-categories
966
        $categoryId = $httpRequest->query->getInt('categoryId');
967
        $subCategoryIdsReq = isset($_REQUEST['subCategoryIds']) ? Security::remove_XSS($_REQUEST['subCategoryIds']) : '';
968
        $subCategoryIds = $subCategoryIdsReq;
969
        if ('all' !== $subCategoryIdsReq) {
970
            $subCategoryIds = !empty($subCategoryIdsReq) ? explode(',', $subCategoryIdsReq) : [];
971
        }
972
        $subcategories = [];
973
        if ($categoryId > 0) {
974
            $subcategories = $this->getCategoriesForIndex(null, $categoryId);
975
            if (count($subcategories) > 0) {
976
                foreach ($subcategories as &$subcategory) {
977
                    $translated = $this->translateDisplayName($subcategory->getTitle());
978
                    $subcategory->setTitle($translated);
979
                }
980
            }
981
        }
982
983
        $template = new Template(null, false, false, false, false, false, false);
984
        $template->assign('user', $this->owner);
985
        $template->assign('course', $this->course);
986
        $template->assign('session', $this->session);
987
        $template->assign('portfolio', $portfolio);
988
        $template->assign('categories', $categories);
989
        $template->assign('uncategorized_items', $items);
990
        $template->assign('frm_student_list', $this->course ? $frmStudentList->returnForm() : '');
991
        $template->assign('frm_tag_list', $this->course ? $frmTagList->returnForm() : '');
992
        $template->assign('category_id', $categoryId);
993
        $template->assign('subcategories', $subcategories);
994
        $template->assign('subcategory_ids', $subCategoryIds);
995
996
        $js = '<script>
997
            $(function() {
998
                $(".category-filters").bind("click", function() {
999
                    var categoryId = parseInt($(this).find("input[type=\'radio\']").val());
1000
                    $("input[name=\'categoryId\']").val(categoryId);
1001
                    $("input[name=\'subCategoryIds\']").val("all");
1002
                    $("#frm_tag_list_submit").trigger("click");
1003
                });
1004
                $(".subcategory-filters").bind("click", function() {
1005
                    var checkedVals = $(".subcategory-filters:checkbox:checked").map(function() {
1006
                        return this.value;
1007
                    }).get();
1008
                    $("input[name=\'subCategoryIds\']").val(checkedVals.join(","));
1009
                    $("#frm_tag_list_submit").trigger("click");
1010
                });
1011
            });
1012
        </script>';
1013
        $template->assign('js_script', $js);
1014
        $layout = $template->get_template('portfolio/list.html.twig');
1015
1016
        Display::addFlash(
1017
            Display::return_message(get_lang('PortfolioPostAddHelp'), 'info', false)
1018
        );
1019
1020
        $content = $template->fetch($layout);
1021
1022
        $this->renderView($content, get_lang('Portfolio'), $actions);
1023
    }
1024
1025
    /**
1026
     * @throws \Doctrine\ORM\ORMException
1027
     * @throws \Doctrine\ORM\OptimisticLockException
1028
     * @throws \Doctrine\ORM\TransactionRequiredException
1029
     */
1030
    public function view(Portfolio $item)
1031
    {
1032
        global $interbreadcrumb;
1033
1034
        if (!$this->itemBelongToOwner($item)) {
1035
            if ($item->getVisibility() === Portfolio::VISIBILITY_HIDDEN
1036
                || ($item->getVisibility() === Portfolio::VISIBILITY_HIDDEN_EXCEPT_TEACHER && !api_is_allowed_to_edit())
1037
            ) {
1038
                api_not_allowed(true);
1039
            }
1040
        }
1041
1042
        HookPortfolioItemViewed::create()
1043
            ->setEventData(['portfolio' => $item])
1044
            ->notifyItemViewed()
1045
        ;
1046
1047
        $itemCourse = $item->getCourse();
1048
        $itemSession = $item->getSession();
1049
1050
        $form = $this->createCommentForm($item);
1051
1052
        $commentsRepo = $this->em->getRepository(PortfolioComment::class);
1053
1054
        $query = $commentsRepo->createQueryBuilder('comment')
1055
            ->where('comment.item = :item')
1056
            ->orderBy('comment.root, comment.lft', 'ASC')
1057
            ->setParameter('item', $item)
1058
            ->getQuery();
1059
1060
        $clockIcon = Display::returnFontAwesomeIcon('clock-o', '', true);
1061
1062
        $commentsHtml = $commentsRepo->buildTree(
1063
            $query->getArrayResult(),
1064
            [
1065
                'decorate' => true,
1066
                'rootOpen' => '<div class="media-list">',
1067
                'rootClose' => '</div>',
1068
                'childOpen' => function ($node) use ($commentsRepo) {
1069
                    /** @var PortfolioComment $comment */
1070
                    $comment = $commentsRepo->find($node['id']);
1071
                    $author = $comment->getAuthor();
1072
1073
                    $userPicture = UserManager::getUserPicture(
1074
                        $comment->getAuthor()->getId(),
1075
                        USER_IMAGE_SIZE_SMALL,
1076
                        null,
1077
                        [
1078
                            'picture_uri' => $author->getPictureUri(),
1079
                            'email' => $author->getEmail(),
1080
                        ]
1081
                    );
1082
1083
                    return '<article class="media" id="comment-'.$node['id'].'">
1084
                        <div class="media-left"><img class="media-object thumbnail" src="'.$userPicture.'" alt="'
1085
                        .$author->getCompleteName().'"></div>
1086
                        <div class="media-body">';
1087
                },
1088
                'childClose' => '</div></article>',
1089
                'nodeDecorator' => function ($node) use ($commentsRepo, $clockIcon, $item) {
1090
                    /** @var PortfolioComment $comment */
1091
                    $comment = $commentsRepo->find($node['id']);
1092
1093
                    $commentActions[] = Display::url(
0 ignored issues
show
Comprehensibility Best Practice introduced by
$commentActions was never initialized. Although not strictly required by PHP, it is generally a good practice to add $commentActions = array(); before regardless.
Loading history...
1094
                        Display::return_icon('discuss.png', get_lang('ReplyToThisComment')),
1095
                        '#',
1096
                        [
1097
                            'data-comment' => htmlspecialchars(
1098
                                json_encode(['id' => $comment->getId()])
1099
                            ),
1100
                            'role' => 'button',
1101
                            'class' => 'btn-reply-to',
1102
                        ]
1103
                    );
1104
                    $commentActions[] = Display::url(
1105
                        Display::return_icon('copy.png', get_lang('CopyToMyPortfolio')),
1106
                        $this->baseUrl.http_build_query(
1107
                            [
1108
                                'action' => 'copy',
1109
                                'copy' => 'comment',
1110
                                'id' => $comment->getId(),
1111
                            ]
1112
                        )
1113
                    );
1114
1115
                    $isAllowedToEdit = api_is_allowed_to_edit();
1116
1117
                    if ($isAllowedToEdit) {
1118
                        $commentActions[] = Display::url(
1119
                            Display::return_icon('copy.png', get_lang('CopyToStudentPortfolio')),
1120
                            $this->baseUrl.http_build_query(
1121
                                [
1122
                                    'action' => 'teacher_copy',
1123
                                    'copy' => 'comment',
1124
                                    'id' => $comment->getId(),
1125
                                ]
1126
                            )
1127
                        );
1128
1129
                        if ($comment->isImportant()) {
1130
                            $commentActions[] = Display::url(
1131
                                Display::return_icon('drawing-pin.png', get_lang('UnmarkCommentAsImportant')),
1132
                                $this->baseUrl.http_build_query(
1133
                                    [
1134
                                        'action' => 'mark_important',
1135
                                        'item' => $item->getId(),
1136
                                        'id' => $comment->getId(),
1137
                                    ]
1138
                                )
1139
                            );
1140
                        } else {
1141
                            $commentActions[] = Display::url(
1142
                                Display::return_icon('drawing-pin.png', get_lang('MarkCommentAsImportant')),
1143
                                $this->baseUrl.http_build_query(
1144
                                    [
1145
                                        'action' => 'mark_important',
1146
                                        'item' => $item->getId(),
1147
                                        'id' => $comment->getId(),
1148
                                    ]
1149
                                )
1150
                            );
1151
                        }
1152
1153
                        if ($this->course && '1' === api_get_course_setting('qualify_portfolio_comment')) {
1154
                            $commentActions[] = Display::url(
1155
                                Display::return_icon('quiz.png', get_lang('QualifyThisPortfolioComment')),
1156
                                $this->baseUrl.http_build_query(
1157
                                    [
1158
                                        'action' => 'qualify',
1159
                                        'comment' => $comment->getId(),
1160
                                    ]
1161
                                )
1162
                            );
1163
                        }
1164
                    }
1165
1166
                    $nodeHtml = '<footer class="media-heading h4">'.PHP_EOL;
1167
1168
                    if ($comment->isImportant()
1169
                        && ($this->itemBelongToOwner($comment->getItem()) || $isAllowedToEdit)
1170
                    ) {
1171
                        $nodeHtml .= '<p class="pull-right label label-warning origin-style">'
1172
                            .get_lang('CommentMarkedAsImportant')
1173
                            .'</p>'.PHP_EOL;
1174
                    }
1175
1176
                    $nodeHtml .= '<p>'.$comment->getAuthor()->getCompleteName().'</p>'.PHP_EOL
1177
                        .'<p class="small">'.$clockIcon.PHP_EOL
1178
                        .Display::dateToStringAgoAndLongDate($comment->getDate()).'</p>'.PHP_EOL;
1179
1180
                    $nodeHtml .= '</footer>'.PHP_EOL
1181
                        .'<div class="pull-right">'.implode(PHP_EOL, $commentActions).'</div>'
1182
                        .Security::remove_XSS($comment->getContent())
1183
                        .PHP_EOL;
1184
1185
                    $nodeHtml .= $this->generateAttachmentList($comment);
1186
1187
                    return $nodeHtml;
1188
                },
1189
            ]
1190
        );
1191
1192
        $template = new Template(null, false, false, false, false, false, false);
1193
        $template->assign('baseurl', $this->baseUrl);
1194
        $template->assign('item', $item);
1195
        $template->assign('item_content', $this->generateItemContent($item));
1196
        $template->assign('comments', $commentsHtml);
1197
        $template->assign('form', $form);
1198
        $template->assign('attachment_list', $this->generateAttachmentList($item));
1199
1200
        if ($itemCourse) {
1201
            $propertyInfo = api_get_item_property_info(
1202
                $itemCourse->getId(),
1203
                TOOL_PORTFOLIO,
1204
                $item->getId(),
1205
                $itemSession ? $itemSession->getId() : 0
1206
            );
1207
1208
            if ($propertyInfo) {
1209
                $template->assign(
1210
                    'last_edit',
1211
                    [
1212
                        'date' => $propertyInfo['lastedit_date'],
1213
                        'user' => api_get_user_entity($propertyInfo['lastedit_user_id'])->getCompleteName(),
1214
                    ]
1215
                );
1216
            }
1217
        }
1218
1219
        $layout = $template->get_template('portfolio/view.html.twig');
1220
        $content = $template->fetch($layout);
1221
1222
        $interbreadcrumb[] = ['name' => get_lang('Portfolio'), 'url' => $this->baseUrl];
1223
1224
        $editLink = $actions[] = Display::url(
0 ignored issues
show
Comprehensibility Best Practice introduced by
$actions was never initialized. Although not strictly required by PHP, it is generally a good practice to add $actions = array(); before regardless.
Loading history...
1225
            Display::return_icon('edit.png', get_lang('Edit'), [], ICON_SIZE_MEDIUM),
1226
            $this->baseUrl.http_build_query(['action' => 'edit_item', 'id' => $item->getId()])
1227
        );
1228
1229
        $actions = [];
1230
        $actions[] = Display::url(
1231
            Display::return_icon('back.png', get_lang('Back'), [], ICON_SIZE_MEDIUM),
1232
            $this->baseUrl
1233
        );
1234
1235
        if ($this->itemBelongToOwner($item)) {
1236
            $actions[] = $editLink;
1237
1238
            $visibilityUrl = $this->baseUrl.http_build_query(['action' => 'visibility', 'id' => $item->getId()]);
1239
1240
            if ($item->getVisibility() === Portfolio::VISIBILITY_HIDDEN) {
1241
                $actions[] = Display::url(
1242
                    Display::return_icon('invisible.png', get_lang('MakeVisible'), [], ICON_SIZE_MEDIUM),
1243
                    $visibilityUrl
1244
                );
1245
            } elseif ($item->getVisibility() === Portfolio::VISIBILITY_VISIBLE) {
1246
                $actions[] = Display::url(
1247
                    Display::return_icon('visible.png', get_lang('MakeVisibleForTeachers'), [], ICON_SIZE_MEDIUM),
1248
                    $visibilityUrl
1249
                );
1250
            } elseif ($item->getVisibility() === Portfolio::VISIBILITY_HIDDEN_EXCEPT_TEACHER) {
1251
                $actions[] = Display::url(
1252
                    Display::return_icon('eye-slash.png', get_lang('MakeInvisible'), [], ICON_SIZE_MEDIUM),
1253
                    $visibilityUrl
1254
                );
1255
            }
1256
1257
            $actions[] = Display::url(
1258
                Display::return_icon('delete.png', get_lang('Delete'), [], ICON_SIZE_MEDIUM),
1259
                $this->baseUrl.http_build_query(['action' => 'delete_item', 'id' => $item->getId()])
1260
            );
1261
        } else {
1262
            $actions[] = Display::url(
1263
                Display::return_icon('copy.png', get_lang('CopyToMyPortfolio'), [], ICON_SIZE_MEDIUM),
1264
                $this->baseUrl.http_build_query(['action' => 'copy', 'id' => $item->getId()])
1265
            );
1266
        }
1267
1268
        if (api_is_allowed_to_edit()) {
1269
            $actions[] = Display::url(
1270
                Display::return_icon('copy.png', get_lang('CopyToStudentPortfolio'), [], ICON_SIZE_MEDIUM),
1271
                $this->baseUrl.http_build_query(['action' => 'teacher_copy', 'copy' => 'item', 'id' => $item->getId()])
1272
            );
1273
            $actions[] = $editLink;
1274
1275
            $highlightedUrl = $this->baseUrl.http_build_query(['action' => 'highlighted', 'id' => $item->getId()]);
1276
1277
            if ($item->isHighlighted()) {
1278
                $actions[] = Display::url(
1279
                    Display::return_icon('award_red.png', get_lang('MarkAsNoHighlighted'), [], ICON_SIZE_MEDIUM),
1280
                    $highlightedUrl
1281
                );
1282
            } else {
1283
                $actions[] = Display::url(
1284
                    Display::return_icon('award_red_na.png', get_lang('MarkAsHighlighted'), [], ICON_SIZE_MEDIUM),
1285
                    $highlightedUrl
1286
                );
1287
            }
1288
1289
            if ($itemCourse && '1' === api_get_course_setting('qualify_portfolio_item')) {
1290
                $actions[] = Display::url(
1291
                    Display::return_icon('quiz.png', get_lang('QualifyThisPortfolioItem'), [], ICON_SIZE_MEDIUM),
1292
                    $this->baseUrl.http_build_query(['action' => 'qualify', 'item' => $item->getId()])
1293
                );
1294
            }
1295
        }
1296
1297
        $this->renderView($content, $item->getTitle(true), $actions, false);
1298
    }
1299
1300
    /**
1301
     * @throws \Doctrine\ORM\ORMException
1302
     * @throws \Doctrine\ORM\OptimisticLockException
1303
     */
1304
    public function copyItem(Portfolio $originItem)
1305
    {
1306
        $currentTime = api_get_utc_datetime(null, false, true);
1307
1308
        $portfolio = new Portfolio();
1309
        $portfolio
1310
            ->setVisibility(Portfolio::VISIBILITY_HIDDEN)
1311
            ->setTitle(
1312
                sprintf(get_lang('PortfolioItemFromXUser'), $originItem->getUser()->getCompleteName())
1313
            )
1314
            ->setContent('')
1315
            ->setUser($this->owner)
1316
            ->setOrigin($originItem->getId())
1317
            ->setOriginType(Portfolio::TYPE_ITEM)
1318
            ->setCourse($this->course)
1319
            ->setSession($this->session)
1320
            ->setCreationDate($currentTime)
1321
            ->setUpdateDate($currentTime);
1322
1323
        $this->em->persist($portfolio);
1324
        $this->em->flush();
1325
1326
        Display::addFlash(
1327
            Display::return_message(get_lang('PortfolioItemAdded'), 'success')
1328
        );
1329
1330
        header("Location: $this->baseUrl".http_build_query(['action' => 'edit_item', 'id' => $portfolio->getId()]));
1331
        exit;
1332
    }
1333
1334
    /**
1335
     * @throws \Doctrine\ORM\ORMException
1336
     * @throws \Doctrine\ORM\OptimisticLockException
1337
     */
1338
    public function copyComment(PortfolioComment $originComment)
1339
    {
1340
        $currentTime = api_get_utc_datetime(null, false, true);
1341
1342
        $portfolio = new Portfolio();
1343
        $portfolio
1344
            ->setVisibility(Portfolio::VISIBILITY_HIDDEN)
1345
            ->setTitle(
1346
                sprintf(get_lang('PortfolioCommentFromXUser'), $originComment->getAuthor()->getCompleteName())
1347
            )
1348
            ->setContent('')
1349
            ->setUser($this->owner)
1350
            ->setOrigin($originComment->getId())
1351
            ->setOriginType(Portfolio::TYPE_COMMENT)
1352
            ->setCourse($this->course)
1353
            ->setSession($this->session)
1354
            ->setCreationDate($currentTime)
1355
            ->setUpdateDate($currentTime);
1356
1357
        $this->em->persist($portfolio);
1358
        $this->em->flush();
1359
1360
        Display::addFlash(
1361
            Display::return_message(get_lang('PortfolioItemAdded'), 'success')
1362
        );
1363
1364
        header("Location: $this->baseUrl".http_build_query(['action' => 'edit_item', 'id' => $portfolio->getId()]));
1365
        exit;
1366
    }
1367
1368
    /**
1369
     * @throws \Doctrine\ORM\ORMException
1370
     * @throws \Doctrine\ORM\OptimisticLockException
1371
     * @throws \Exception
1372
     */
1373
    public function teacherCopyItem(Portfolio $originItem)
1374
    {
1375
        $actionParams = http_build_query(['action' => 'teacher_copy', 'copy' => 'item', 'id' => $originItem->getId()]);
1376
1377
        $form = new FormValidator('teacher_copy_portfolio', 'post', $this->baseUrl.$actionParams);
1378
1379
        if (api_get_configuration_value('save_titles_as_html')) {
1380
            $form->addHtmlEditor('title', get_lang('Title'), true, false, ['ToolbarSet' => 'TitleAsHtml']);
1381
        } else {
1382
            $form->addText('title', get_lang('Title'));
1383
            $form->applyFilter('title', 'trim');
1384
        }
1385
1386
        $form->addLabel(
1387
            sprintf(get_lang('PortfolioItemFromXUser'), $originItem->getUser()->getCompleteName()),
1388
            Display::panel(
1389
                Security::remove_XSS($originItem->getContent())
1390
            )
1391
        );
1392
        $form->addHtmlEditor('content', get_lang('Content'), true, false, ['ToolbarSet' => 'NotebookStudent']);
1393
1394
        $urlParams = http_build_query(
1395
            [
1396
                'a' => 'search_user_by_course',
1397
                'course_id' => $this->course->getId(),
1398
                'session_id' => $this->session ? $this->session->getId() : 0,
1399
            ]
1400
        );
1401
        $form->addSelectAjax(
1402
            'students',
1403
            get_lang('Students'),
1404
            [],
1405
            [
1406
                'url' => api_get_path(WEB_AJAX_PATH)."course.ajax.php?$urlParams",
1407
                'multiple' => true,
1408
            ]
1409
        );
1410
        $form->addRule('students', get_lang('ThisFieldIsRequired'), 'required');
1411
        $form->addButtonCreate(get_lang('Save'));
1412
1413
        $toolName = get_lang('CopyToStudentPortfolio');
1414
        $content = $form->returnForm();
1415
1416
        if ($form->validate()) {
1417
            $values = $form->exportValues();
1418
1419
            $currentTime = api_get_utc_datetime(null, false, true);
1420
1421
            foreach ($values['students'] as $studentId) {
1422
                $owner = api_get_user_entity($studentId);
1423
1424
                $portfolio = new Portfolio();
1425
                $portfolio
1426
                    ->setVisibility(Portfolio::VISIBILITY_HIDDEN)
1427
                    ->setTitle($values['title'])
1428
                    ->setContent($values['content'])
1429
                    ->setUser($owner)
1430
                    ->setOrigin($originItem->getId())
1431
                    ->setOriginType(Portfolio::TYPE_ITEM)
1432
                    ->setCourse($this->course)
1433
                    ->setSession($this->session)
1434
                    ->setCreationDate($currentTime)
1435
                    ->setUpdateDate($currentTime);
1436
1437
                $this->em->persist($portfolio);
1438
            }
1439
1440
            $this->em->flush();
1441
1442
            Display::addFlash(
1443
                Display::return_message(get_lang('PortfolioItemAddedToStudents'), 'success')
1444
            );
1445
1446
            header("Location: $this->baseUrl");
1447
            exit;
1448
        }
1449
1450
        $this->renderView($content, $toolName);
1451
    }
1452
1453
    /**
1454
     * @throws \Doctrine\ORM\ORMException
1455
     * @throws \Doctrine\ORM\OptimisticLockException
1456
     * @throws \Exception
1457
     */
1458
    public function teacherCopyComment(PortfolioComment $originComment)
1459
    {
1460
        $actionParams = http_build_query(
1461
            [
1462
                'action' => 'teacher_copy',
1463
                'copy' => 'comment',
1464
                'id' => $originComment->getId(),
1465
            ]
1466
        );
1467
1468
        $form = new FormValidator('teacher_copy_portfolio', 'post', $this->baseUrl.$actionParams);
1469
1470
        if (api_get_configuration_value('save_titles_as_html')) {
1471
            $form->addHtmlEditor('title', get_lang('Title'), true, false, ['ToolbarSet' => 'TitleAsHtml']);
1472
        } else {
1473
            $form->addText('title', get_lang('Title'));
1474
            $form->applyFilter('title', 'trim');
1475
        }
1476
1477
        $form->addLabel(
1478
            sprintf(get_lang('PortfolioCommentFromXUser'), $originComment->getAuthor()->getCompleteName()),
1479
            Display::panel(
1480
                Security::remove_XSS($originComment->getContent())
1481
            )
1482
        );
1483
        $form->addHtmlEditor('content', get_lang('Content'), true, false, ['ToolbarSet' => 'NotebookStudent']);
1484
1485
        $urlParams = http_build_query(
1486
            [
1487
                'a' => 'search_user_by_course',
1488
                'course_id' => $this->course->getId(),
1489
                'session_id' => $this->session ? $this->session->getId() : 0,
1490
            ]
1491
        );
1492
        $form->addSelectAjax(
1493
            'students',
1494
            get_lang('Students'),
1495
            [],
1496
            [
1497
                'url' => api_get_path(WEB_AJAX_PATH)."course.ajax.php?$urlParams",
1498
                'multiple' => true,
1499
            ]
1500
        );
1501
        $form->addRule('students', get_lang('ThisFieldIsRequired'), 'required');
1502
        $form->addButtonCreate(get_lang('Save'));
1503
1504
        $toolName = get_lang('CopyToStudentPortfolio');
1505
        $content = $form->returnForm();
1506
1507
        if ($form->validate()) {
1508
            $values = $form->exportValues();
1509
1510
            $currentTime = api_get_utc_datetime(null, false, true);
1511
1512
            foreach ($values['students'] as $studentId) {
1513
                $owner = api_get_user_entity($studentId);
1514
1515
                $portfolio = new Portfolio();
1516
                $portfolio
1517
                    ->setVisibility(Portfolio::VISIBILITY_HIDDEN)
1518
                    ->setTitle($values['title'])
1519
                    ->setContent($values['content'])
1520
                    ->setUser($owner)
1521
                    ->setOrigin($originComment->getId())
1522
                    ->setOriginType(Portfolio::TYPE_COMMENT)
1523
                    ->setCourse($this->course)
1524
                    ->setSession($this->session)
1525
                    ->setCreationDate($currentTime)
1526
                    ->setUpdateDate($currentTime);
1527
1528
                $this->em->persist($portfolio);
1529
            }
1530
1531
            $this->em->flush();
1532
1533
            Display::addFlash(
1534
                Display::return_message(get_lang('PortfolioItemAddedToStudents'), 'success')
1535
            );
1536
1537
            header("Location: $this->baseUrl");
1538
            exit;
1539
        }
1540
1541
        $this->renderView($content, $toolName);
1542
    }
1543
1544
    /**
1545
     * @throws \Doctrine\ORM\ORMException
1546
     * @throws \Doctrine\ORM\OptimisticLockException
1547
     */
1548
    public function markImportantCommentInItem(Portfolio $item, PortfolioComment $comment)
1549
    {
1550
        if ($comment->getItem()->getId() !== $item->getId()) {
1551
            api_not_allowed(true);
1552
        }
1553
1554
        $comment->setIsImportant(
1555
            !$comment->isImportant()
1556
        );
1557
1558
        $this->em->persist($comment);
1559
        $this->em->flush();
1560
1561
        Display::addFlash(
1562
            Display::return_message(get_lang('CommentMarkedAsImportant'), 'success')
1563
        );
1564
1565
        header("Location: $this->baseUrl".http_build_query(['action' => 'view', 'id' => $item->getId()]));
1566
        exit;
1567
    }
1568
1569
    /**
1570
     * @throws \Exception
1571
     */
1572
    public function details(HttpRequest $httpRequest)
1573
    {
1574
        $currentUserId = api_get_user_id();
1575
        $isAllowedToFilterStudent = $this->course && api_is_allowed_to_edit();
1576
1577
        $actions = [];
1578
        $actions[] = Display::url(
1579
            Display::return_icon('back.png', get_lang('Back'), [], ICON_SIZE_MEDIUM),
1580
            $this->baseUrl
1581
        );
1582
        $actions[] = Display::url(
1583
            Display::return_icon('pdf.png', get_lang('ExportMyPortfolioDataPdf'), [], ICON_SIZE_MEDIUM),
1584
            $this->baseUrl.http_build_query(['action' => 'export_pdf'])
1585
        );
1586
        $actions[] = Display::url(
1587
            Display::return_icon('save_pack.png', get_lang('ExportMyPortfolioDataZip'), [], ICON_SIZE_MEDIUM),
1588
            $this->baseUrl.http_build_query(['action' => 'export_zip'])
1589
        );
1590
1591
        $frmStudent = null;
1592
1593
        if ($isAllowedToFilterStudent) {
1594
            if ($httpRequest->query->has('user')) {
1595
                $this->owner = api_get_user_entity($httpRequest->query->getInt('user'));
1596
1597
                if (empty($this->owner)) {
1598
                    api_not_allowed(true);
1599
                }
1600
1601
                $actions[1] = Display::url(
1602
                    Display::return_icon('pdf.png', get_lang('ExportMyPortfolioDataPdf'), [], ICON_SIZE_MEDIUM),
1603
                    $this->baseUrl.http_build_query(['action' => 'export_pdf', 'user' => $this->owner->getId()])
1604
                );
1605
                $actions[2] = Display::url(
1606
                    Display::return_icon('save_pack.png', get_lang('ExportMyPortfolioDataZip'), [], ICON_SIZE_MEDIUM),
1607
                    $this->baseUrl.http_build_query(['action' => 'export_zip', 'user' => $this->owner->getId()])
1608
                );
1609
            }
1610
1611
            $frmStudent = new FormValidator('frm_student_list', 'get');
1612
1613
            $urlParams = http_build_query(
1614
                [
1615
                    'a' => 'search_user_by_course',
1616
                    'course_id' => $this->course->getId(),
1617
                    'session_id' => $this->session ? $this->session->getId() : 0,
1618
                ]
1619
            );
1620
1621
            $frmStudent
1622
                ->addSelectAjax(
1623
                    'user',
1624
                    get_lang('SelectLearnerPortfolio'),
1625
                    [],
1626
                    [
1627
                        'url' => api_get_path(WEB_AJAX_PATH)."course.ajax.php?$urlParams",
1628
                        'placeholder' => get_lang('SearchStudent'),
1629
                        'formatResult' => SelectAjax::templateResultForUsersInCourse(),
1630
                        'formatSelection' => SelectAjax::templateSelectionForUsersInCourse(),
1631
                    ]
1632
                )
1633
                ->addOption(
1634
                    $this->owner->getCompleteName(),
1635
                    $this->owner->getId(),
1636
                    [
1637
                        'data-avatarurl' => UserManager::getUserPicture($this->owner->getId()),
1638
                        'data-username' => $this->owner->getUsername(),
1639
                    ]
1640
                )
1641
            ;
1642
            $frmStudent->setDefaults(['user' => $this->owner->getId()]);
1643
            $frmStudent->addHidden('action', 'details');
1644
            $frmStudent->addHidden('cidReq', $this->course->getCode());
1645
            $frmStudent->addHidden('id_session', $this->session ? $this->session->getId() : 0);
1646
            $frmStudent->addButtonFilter(get_lang('Filter'));
1647
        }
1648
1649
        $itemsRepo = $this->em->getRepository(Portfolio::class);
1650
        $commentsRepo = $this->em->getRepository(PortfolioComment::class);
1651
1652
        $getItemsTotalNumber = function () use ($itemsRepo, $isAllowedToFilterStudent, $currentUserId) {
1653
            $qb = $itemsRepo->createQueryBuilder('i');
1654
            $qb
1655
                ->select('COUNT(i)')
1656
                ->where('i.user = :user')
1657
                ->setParameter('user', $this->owner);
1658
1659
            if ($this->course) {
1660
                $qb
1661
                    ->andWhere('i.course = :course')
1662
                    ->setParameter('course', $this->course);
1663
1664
                if ($this->session) {
1665
                    $qb
1666
                        ->andWhere('i.session = :session')
1667
                        ->setParameter('session', $this->session);
1668
                } else {
1669
                    $qb->andWhere('i.session IS NULL');
1670
                }
1671
            }
1672
1673
            if ($isAllowedToFilterStudent && $currentUserId !== $this->owner->getId()) {
1674
                $visibilityCriteria = [
1675
                    Portfolio::VISIBILITY_VISIBLE,
1676
                    Portfolio::VISIBILITY_HIDDEN_EXCEPT_TEACHER,
1677
                ];
1678
1679
                $qb->andWhere(
1680
                    $qb->expr()->in('i.visibility', $visibilityCriteria)
1681
                );
1682
            }
1683
1684
            return $qb->getQuery()->getSingleScalarResult();
1685
        };
1686
        $getItemsData = function ($from, $limit, $columnNo, $orderDirection) use ($itemsRepo, $isAllowedToFilterStudent, $currentUserId) {
1687
            $qb = $itemsRepo->createQueryBuilder('item')
1688
                ->where('item.user = :user')
1689
                ->leftJoin('item.category', 'category')
1690
                ->leftJoin('item.course', 'course')
1691
                ->leftJoin('item.session', 'session')
1692
                ->setParameter('user', $this->owner);
1693
1694
            if ($this->course) {
1695
                $qb
1696
                    ->andWhere('item.course = :course_id')
1697
                    ->setParameter('course_id', $this->course);
1698
1699
                if ($this->session) {
1700
                    $qb
1701
                        ->andWhere('item.session = :session')
1702
                        ->setParameter('session', $this->session);
1703
                } else {
1704
                    $qb->andWhere('item.session IS NULL');
1705
                }
1706
            }
1707
1708
            if ($isAllowedToFilterStudent && $currentUserId !== $this->owner->getId()) {
1709
                $visibilityCriteria = [
1710
                    Portfolio::VISIBILITY_VISIBLE,
1711
                    Portfolio::VISIBILITY_HIDDEN_EXCEPT_TEACHER,
1712
                ];
1713
1714
                $qb->andWhere(
1715
                    $qb->expr()->in('item.visibility', $visibilityCriteria)
1716
                );
1717
            }
1718
1719
            if (0 == $columnNo) {
1720
                $qb->orderBy('item.title', $orderDirection);
1721
            } elseif (1 == $columnNo) {
1722
                $qb->orderBy('item.creationDate', $orderDirection);
1723
            } elseif (2 == $columnNo) {
1724
                $qb->orderBy('item.updateDate', $orderDirection);
1725
            } elseif (3 == $columnNo) {
1726
                $qb->orderBy('category.title', $orderDirection);
1727
            } elseif (5 == $columnNo) {
1728
                $qb->orderBy('item.score', $orderDirection);
1729
            } elseif (6 == $columnNo) {
1730
                $qb->orderBy('course.title', $orderDirection);
1731
            } elseif (7 == $columnNo) {
1732
                $qb->orderBy('session.name', $orderDirection);
1733
            }
1734
1735
            $qb->setFirstResult($from)->setMaxResults($limit);
1736
1737
            return array_map(
1738
                function (Portfolio $item) {
1739
                    $category = $item->getCategory();
1740
1741
                    $row = [];
1742
                    $row[] = $item;
1743
                    $row[] = $item->getCreationDate();
1744
                    $row[] = $item->getUpdateDate();
1745
                    $row[] = $category ? $item->getCategory()->getTitle() : null;
0 ignored issues
show
introduced by
$category is of type Chamilo\CoreBundle\Entity\PortfolioCategory, thus it always evaluated to true.
Loading history...
1746
                    $row[] = $item->getComments()->count();
1747
                    $row[] = $item->getScore();
1748
1749
                    if (!$this->course) {
1750
                        $row[] = $item->getCourse();
1751
                        $row[] = $item->getSession();
1752
                    }
1753
1754
                    return $row;
1755
                },
1756
                $qb->getQuery()->getResult()
1757
            );
1758
        };
1759
1760
        $portfolioItemColumnFilter = function (Portfolio $item) {
1761
            return Display::url(
1762
                $item->getTitle(true),
1763
                $this->baseUrl.http_build_query(['action' => 'view', 'id' => $item->getId()])
1764
            );
1765
        };
1766
        $convertFormatDateColumnFilter = function (DateTime $date) {
1767
            return api_convert_and_format_date($date);
1768
        };
1769
1770
        $tblItems = new SortableTable('tbl_items', $getItemsTotalNumber, $getItemsData, 1, 20, 'DESC');
1771
        $tblItems->set_additional_parameters(['action' => 'details', 'user' => $this->owner->getId()]);
1772
        $tblItems->set_header(0, get_lang('Title'));
1773
        $tblItems->set_column_filter(0, $portfolioItemColumnFilter);
1774
        $tblItems->set_header(1, get_lang('CreationDate'), true, [], ['class' => 'text-center']);
1775
        $tblItems->set_column_filter(1, $convertFormatDateColumnFilter);
1776
        $tblItems->set_header(2, get_lang('LastUpdate'), true, [], ['class' => 'text-center']);
1777
        $tblItems->set_column_filter(2, $convertFormatDateColumnFilter);
1778
        $tblItems->set_header(3, get_lang('Category'));
1779
        $tblItems->set_header(4, get_lang('Comments'), false, [], ['class' => 'text-right']);
1780
        $tblItems->set_header(5, get_lang('Score'), true, [], ['class' => 'text-right']);
1781
1782
        if (!$this->course) {
1783
            $tblItems->set_header(6, get_lang('Course'));
1784
            $tblItems->set_header(7, get_lang('Session'));
1785
        }
1786
1787
        $getCommentsTotalNumber = function () use ($commentsRepo) {
1788
            $qb = $commentsRepo->createQueryBuilder('c');
1789
            $qb
1790
                ->select('COUNT(c)')
1791
                ->where('c.author = :author')
1792
                ->setParameter('author', $this->owner);
1793
1794
            if ($this->course) {
1795
                $qb
1796
                    ->innerJoin('c.item', 'i')
1797
                    ->andWhere('i.course = :course')
1798
                    ->setParameter('course', $this->course);
1799
1800
                if ($this->session) {
1801
                    $qb
1802
                        ->andWhere('i.session = :session')
1803
                        ->setParameter('session', $this->session);
1804
                } else {
1805
                    $qb->andWhere('i.session IS NULL');
1806
                }
1807
            }
1808
1809
            return $qb->getQuery()->getSingleScalarResult();
1810
        };
1811
        $getCommentsData = function ($from, $limit, $columnNo, $orderDirection) use ($commentsRepo) {
1812
            $qb = $commentsRepo->createQueryBuilder('comment');
1813
            $qb
1814
                ->where('comment.author = :user')
1815
                ->innerJoin('comment.item', 'item')
1816
                ->setParameter('user', $this->owner);
1817
1818
            if ($this->course) {
1819
                $qb
1820
                    ->innerJoin('comment.item', 'i')
1821
                    ->andWhere('item.course = :course')
1822
                    ->setParameter('course', $this->course);
1823
1824
                if ($this->session) {
1825
                    $qb
1826
                        ->andWhere('item.session = :session')
1827
                        ->setParameter('session', $this->session);
1828
                } else {
1829
                    $qb->andWhere('item.session IS NULL');
1830
                }
1831
            }
1832
1833
            if (0 == $columnNo) {
1834
                $qb->orderBy('comment.content', $orderDirection);
1835
            } elseif (1 == $columnNo) {
1836
                $qb->orderBy('comment.date', $orderDirection);
1837
            } elseif (2 == $columnNo) {
1838
                $qb->orderBy('item.title', $orderDirection);
1839
            } elseif (3 == $columnNo) {
1840
                $qb->orderBy('comment.score', $orderDirection);
1841
            }
1842
1843
            $qb->setFirstResult($from)->setMaxResults($limit);
1844
1845
            return array_map(
1846
                function (PortfolioComment $comment) {
1847
                    return [
1848
                        $comment,
1849
                        $comment->getDate(),
1850
                        $comment->getItem(),
1851
                        $comment->getScore(),
1852
                    ];
1853
                },
1854
                $qb->getQuery()->getResult()
1855
            );
1856
        };
1857
1858
        $tblComments = new SortableTable('tbl_comments', $getCommentsTotalNumber, $getCommentsData, 1, 20, 'DESC');
1859
        $tblComments->set_additional_parameters(['action' => 'details', 'user' => $this->owner->getId()]);
1860
        $tblComments->set_header(0, get_lang('Resume'));
1861
        $tblComments->set_column_filter(
1862
            0,
1863
            function (PortfolioComment $comment) {
1864
                return Display::url(
1865
                    $comment->getExcerpt(),
1866
                    $this->baseUrl.http_build_query(['action' => 'view', 'id' => $comment->getItem()->getId()])
1867
                    .'#comment-'.$comment->getId()
1868
                );
1869
            }
1870
        );
1871
        $tblComments->set_header(1, get_lang('Date'), true, [], ['class' => 'text-center']);
1872
        $tblComments->set_column_filter(1, $convertFormatDateColumnFilter);
1873
        $tblComments->set_header(2, get_lang('PortfolioItemTitle'));
1874
        $tblComments->set_column_filter(2, $portfolioItemColumnFilter);
1875
        $tblComments->set_header(3, get_lang('Score'), true, [], ['class' => 'text-right']);
1876
1877
        $content = '';
1878
1879
        if ($frmStudent) {
1880
            $content .= $frmStudent->returnForm();
1881
        }
1882
1883
        $totalNumberOfItems = $tblItems->get_total_number_of_items();
1884
        $totalNumberOfComments = $tblComments->get_total_number_of_items();
1885
        $requiredNumberOfItems = (int) api_get_course_setting('portfolio_number_items');
1886
        $requiredNumberOfComments = (int) api_get_course_setting('portfolio_number_comments');
1887
1888
        $itemsSubtitle = '';
1889
1890
        if ($requiredNumberOfItems> 0) {
1891
            $itemsSubtitle = sprintf(
1892
                get_lang('XAddedYRequired'),
1893
                $totalNumberOfItems,
1894
                $requiredNumberOfItems
1895
            );
1896
        }
1897
1898
        $content .= Display::page_subheader2(
1899
            get_lang('PortfolioItems'),
1900
            $itemsSubtitle
1901
        ).PHP_EOL;
1902
1903
        if ($totalNumberOfItems > 0) {
1904
            $content .= $tblItems->return_table().PHP_EOL;
1905
        } else {
1906
            $content .= Display::return_message(get_lang('NoItemsInYourPortfolio'), 'warning');
1907
        }
1908
1909
        $commentsSubtitle = '';
1910
1911
        if ($requiredNumberOfComments > 0) {
1912
            $commentsSubtitle = sprintf(
1913
                get_lang('XAddedYRequired'),
1914
                $totalNumberOfComments,
1915
                $requiredNumberOfComments
1916
            );
1917
        }
1918
1919
        $content .= Display::page_subheader2(
1920
            get_lang('PortfolioCommentsMade'),
1921
            $commentsSubtitle
1922
        ).PHP_EOL;
1923
1924
        if ($totalNumberOfComments > 0) {
1925
            $content .= $tblComments->return_table().PHP_EOL;
1926
        } else {
1927
            $content .= Display::return_message(get_lang('YouHaveNotCommented'), 'warning');
1928
        }
1929
1930
        $this->renderView($content, get_lang('PortfolioDetails'), $actions);
1931
    }
1932
1933
    /**
1934
     * @throws \MpdfException
1935
     */
1936
    public function exportPdf(HttpRequest $httpRequest)
1937
    {
1938
        $currentUserId = api_get_user_id();
1939
        $isAllowedToFilterStudent = $this->course && api_is_allowed_to_edit();
1940
1941
        if ($isAllowedToFilterStudent) {
1942
            if ($httpRequest->query->has('user')) {
1943
                $this->owner = api_get_user_entity($httpRequest->query->getInt('user'));
1944
1945
                if (empty($this->owner)) {
1946
                    api_not_allowed(true);
1947
                }
1948
            }
1949
        }
1950
1951
        $pdfContent = Display::page_header($this->owner->getCompleteName());
1952
1953
        if ($this->course) {
1954
            $pdfContent .= '<p>'.get_lang('Course').': ';
1955
1956
            if ($this->session) {
1957
                $pdfContent .= $this->session->getName().' ('.$this->course->getTitle().')';
1958
            } else {
1959
                $pdfContent .= $this->course->getTitle();
1960
            }
1961
1962
            $pdfContent .= '</p>';
1963
        }
1964
1965
        $visibility = [];
1966
1967
        if ($isAllowedToFilterStudent && $currentUserId !== $this->owner->getId()) {
1968
            $visibility[] = Portfolio::VISIBILITY_VISIBLE;
1969
            $visibility[] = Portfolio::VISIBILITY_HIDDEN_EXCEPT_TEACHER;
1970
        }
1971
1972
        $items = $this->em
1973
            ->getRepository(Portfolio::class)
1974
            ->findItemsByUser(
1975
                $this->owner,
1976
                $this->course,
1977
                $this->session,
1978
                null,
1979
                $visibility
1980
            );
1981
        $comments = $this->em
1982
            ->getRepository(PortfolioComment::class)
1983
            ->findCommentsByUser($this->owner, $this->course, $this->session);
1984
1985
        $itemsHtml = $this->getItemsInHtmlFormatted($items);
1986
        $commentsHtml = $this->getCommentsInHtmlFormatted($comments);
1987
1988
        $pdfContent .= Display::page_subheader2(get_lang('PortfolioItems'));
1989
1990
        if (count($itemsHtml) > 0) {
1991
            $pdfContent .= implode(PHP_EOL, $itemsHtml);
1992
        } else {
1993
            $pdfContent .= Display::return_message(get_lang('NoItemsInYourPortfolio'), 'warning');
1994
        }
1995
1996
        $pdfContent .= Display::page_subheader2(get_lang('PortfolioCommentsMade'));
1997
1998
        if (count($commentsHtml) > 0) {
1999
            $pdfContent .= implode(PHP_EOL, $commentsHtml);
2000
        } else {
2001
            $pdfContent .= Display::return_message(get_lang('YouHaveNotCommented'), 'warning');
2002
        }
2003
2004
        $pdfName = $this->owner->getCompleteName()
2005
            .($this->course ? '_'.$this->course->getCode() : '')
2006
            .'_'.get_lang('Portfolio');
2007
2008
        $pdf = new PDF();
2009
        $pdf->content_to_pdf(
2010
            $pdfContent,
2011
            null,
2012
            $pdfName,
2013
            $this->course ? $this->course->getCode() : null,
2014
            'D',
2015
            false,
2016
            null,
2017
            false,
2018
            true
2019
        );
2020
    }
2021
2022
    public function exportZip(HttpRequest $httpRequest)
2023
    {
2024
        $currentUserId = api_get_user_id();
2025
        $isAllowedToFilterStudent = $this->course && api_is_allowed_to_edit();
2026
2027
        if ($isAllowedToFilterStudent) {
2028
            if ($httpRequest->query->has('user')) {
2029
                $this->owner = api_get_user_entity($httpRequest->query->getInt('user'));
2030
2031
                if (empty($this->owner)) {
2032
                    api_not_allowed(true);
2033
                }
2034
            }
2035
        }
2036
2037
        $itemsRepo = $this->em->getRepository(Portfolio::class);
2038
        $commentsRepo = $this->em->getRepository(PortfolioComment::class);
2039
        $attachmentsRepo = $this->em->getRepository(PortfolioAttachment::class);
2040
2041
        $visibility = [];
2042
2043
        if ($isAllowedToFilterStudent && $currentUserId !== $this->owner->getId()) {
2044
            $visibility[] = Portfolio::VISIBILITY_VISIBLE;
2045
            $visibility[] = Portfolio::VISIBILITY_HIDDEN_EXCEPT_TEACHER;
2046
        }
2047
2048
        $items = $itemsRepo->findItemsByUser(
2049
            $this->owner,
2050
            $this->course,
2051
            $this->session,
2052
            null,
2053
            $visibility
2054
        );
2055
        $comments = $commentsRepo->findCommentsByUser($this->owner, $this->course, $this->session);
2056
2057
        $itemsHtml = $this->getItemsInHtmlFormatted($items);
2058
        $commentsHtml = $this->getCommentsInHtmlFormatted($comments);
2059
2060
        $sysArchivePath = api_get_path(SYS_ARCHIVE_PATH);
2061
        $tempPortfolioDirectory = $sysArchivePath."portfolio/{$this->owner->getId()}";
2062
2063
        $userDirectory = UserManager::getUserPathById($this->owner->getId(), 'system');
2064
        $attachmentsDirectory = $userDirectory.'portfolio_attachments/';
2065
2066
        $tblItemsHeaders = [];
2067
        $tblItemsHeaders[] = get_lang('Title');
2068
        $tblItemsHeaders[] = get_lang('CreationDate');
2069
        $tblItemsHeaders[] = get_lang('LastUpdate');
2070
        $tblItemsHeaders[] = get_lang('Category');
2071
        $tblItemsHeaders[] = get_lang('Category');
2072
        $tblItemsHeaders[] = get_lang('Score');
2073
        $tblItemsHeaders[] = get_lang('Course');
2074
        $tblItemsHeaders[] = get_lang('Session');
2075
        $tblItemsData = [];
2076
2077
        $tblCommentsHeaders = [];
2078
        $tblCommentsHeaders[] = get_lang('Resume');
2079
        $tblCommentsHeaders[] = get_lang('Date');
2080
        $tblCommentsHeaders[] = get_lang('PortfolioItemTitle');
2081
        $tblCommentsHeaders[] = get_lang('Score');
2082
        $tblCommentsData = [];
2083
2084
        $filenames = [];
2085
2086
        $fs = new Filesystem();
2087
2088
        /**
2089
         * @var int       $i
2090
         * @var Portfolio $item
2091
         */
2092
        foreach ($items as $i => $item) {
2093
            $itemCategory = $item->getCategory();
2094
            $itemCourse = $item->getCourse();
2095
            $itemSession = $item->getSession();
2096
2097
            $itemDirectory = $item->getCreationDate()->format('Y-m-d-H-i-s');
2098
2099
            $itemFilename = sprintf('%s/items/%s/item.html', $tempPortfolioDirectory, $itemDirectory);
2100
            $itemFileContent = $this->fixImagesSourcesToHtml($itemsHtml[$i]);
2101
2102
            $fs->dumpFile($itemFilename, $itemFileContent);
2103
2104
            $filenames[] = $itemFilename;
2105
2106
            $attachments = $attachmentsRepo->findFromItem($item);
2107
2108
            /** @var PortfolioAttachment $attachment */
2109
            foreach ($attachments as $attachment) {
2110
                $attachmentFilename = sprintf(
2111
                    '%s/items/%s/attachments/%s',
2112
                    $tempPortfolioDirectory,
2113
                    $itemDirectory,
2114
                    $attachment->getFilename()
2115
                );
2116
2117
                $fs->copy(
2118
                    $attachmentsDirectory.$attachment->getPath(),
2119
                    $attachmentFilename
2120
                );
2121
2122
                $filenames[] = $attachmentFilename;
2123
            }
2124
2125
            $tblItemsData[] = [
2126
                Display::url(
2127
                    Security::remove_XSS($item->getTitle()),
2128
                    sprintf('items/%s/item.html', $itemDirectory)
2129
                ),
2130
                api_convert_and_format_date($item->getCreationDate()),
2131
                api_convert_and_format_date($item->getUpdateDate()),
2132
                $itemCategory ? $itemCategory->getTitle() : null,
2133
                $item->getComments()->count(),
2134
                $item->getScore(),
2135
                $itemCourse->getTitle(),
2136
                $itemSession ? $itemSession->getName() : null,
2137
            ];
2138
        }
2139
2140
        /**
2141
         * @var int              $i
2142
         * @var PortfolioComment $comment
2143
         */
2144
        foreach ($comments as $i => $comment) {
2145
            $commentDirectory = $comment->getDate()->format('Y-m-d-H-i-s');
2146
2147
            $commentFileContent = $this->fixImagesSourcesToHtml($commentsHtml[$i]);
2148
            $commentFilename = sprintf('%s/comments/%s/comment.html', $tempPortfolioDirectory, $commentDirectory);
2149
2150
            $fs->dumpFile($commentFilename, $commentFileContent);
2151
2152
            $filenames[] = $commentFilename;
2153
2154
            $attachments = $attachmentsRepo->findFromComment($comment);
2155
2156
            /** @var PortfolioAttachment $attachment */
2157
            foreach ($attachments as $attachment) {
2158
                $attachmentFilename = sprintf(
2159
                    '%s/comments/%s/attachments/%s',
2160
                    $tempPortfolioDirectory,
2161
                    $commentDirectory,
2162
                    $attachment->getFilename()
2163
                );
2164
2165
                $fs->copy(
2166
                    $attachmentsDirectory.$attachment->getPath(),
2167
                    $attachmentFilename
2168
                );
2169
2170
                $filenames[] = $attachmentFilename;
2171
            }
2172
2173
            $tblCommentsData[] = [
2174
                Display::url(
2175
                    $comment->getExcerpt(),
2176
                    sprintf('comments/%s/comment.html', $commentDirectory)
2177
                ),
2178
                api_convert_and_format_date($comment->getDate()),
2179
                Security::remove_XSS($comment->getItem()->getTitle()),
2180
                $comment->getScore(),
2181
            ];
2182
        }
2183
2184
        $tblItems = new HTML_Table(['class' => 'table table-hover table-striped table-bordered data_table']);
2185
        $tblItems->setHeaders($tblItemsHeaders);
2186
        $tblItems->setData($tblItemsData);
2187
2188
        $tblComments = new HTML_Table(['class' => 'table table-hover table-striped table-bordered data_table']);
2189
        $tblComments->setHeaders($tblCommentsHeaders);
2190
        $tblComments->setData($tblCommentsData);
2191
2192
        $itemFilename = sprintf('%s/index.html', $tempPortfolioDirectory);
2193
2194
        $filenames[] = $itemFilename;
2195
2196
        $fs->dumpFile(
2197
            $itemFilename,
2198
            $this->formatZipIndexFile($tblItems, $tblComments)
2199
        );
2200
2201
        $zipName = $this->owner->getCompleteName()
2202
            .($this->course ? '_'.$this->course->getCode() : '')
2203
            .'_'.get_lang('Portfolio');
2204
        $tempZipFile = $sysArchivePath."portfolio/$zipName.zip";
2205
        $zip = new PclZip($tempZipFile);
2206
2207
        foreach ($filenames as $filename) {
2208
            $zip->add($filename, PCLZIP_OPT_REMOVE_PATH, $tempPortfolioDirectory);
0 ignored issues
show
Bug introduced by
The constant PCLZIP_OPT_REMOVE_PATH was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
2209
        }
2210
2211
        DocumentManager::file_send_for_download($tempZipFile, true, "$zipName.zip");
2212
2213
        $fs->remove($tempPortfolioDirectory);
2214
        $fs->remove($tempZipFile);
2215
    }
2216
2217
    public function qualifyItem(Portfolio $item)
2218
    {
2219
        global $interbreadcrumb;
2220
2221
        $em = Database::getManager();
2222
2223
        $formAction = $this->baseUrl.http_build_query(['action' => 'qualify', 'item' => $item->getId()]);
2224
2225
        $form = new FormValidator('frm_qualify', 'post', $formAction);
2226
        $form->addUserAvatar('user', get_lang('Author'));
2227
        $form->addLabel(get_lang('Title'), $item->getTitle());
2228
2229
        $itemContent = $this->generateItemContent($item);
2230
2231
        $form->addLabel(get_lang('Content'), $itemContent);
2232
        $form->addNumeric(
2233
            'score',
2234
            [get_lang('QualifyNumeric'), null, ' / '.api_get_course_setting('portfolio_max_score')]
2235
        );
2236
        $form->addButtonSave(get_lang('QualifyThisPortfolioItem'));
2237
2238
        if ($form->validate()) {
2239
            $values = $form->exportValues();
2240
2241
            $item->setScore($values['score']);
2242
2243
            $em->persist($item);
2244
            $em->flush();
2245
2246
            Display::addFlash(
2247
                Display::return_message(get_lang('PortfolioItemGraded'), 'success')
2248
            );
2249
2250
            header("Location: $formAction");
2251
            exit();
2252
        }
2253
2254
        $form->setDefaults(
2255
            [
2256
                'user' => $item->getUser(),
2257
                'score' => (float) $item->getScore(),
2258
            ]
2259
        );
2260
2261
        $interbreadcrumb[] = [
2262
            'name' => get_lang('Portfolio'),
2263
            'url' => $this->baseUrl,
2264
        ];
2265
        $interbreadcrumb[] = [
2266
            'name' => $item->getTitle(true),
2267
            'url' => $this->baseUrl.http_build_query(['action' => 'view', 'id' => $item->getId()]),
2268
        ];
2269
2270
        $actions = [];
2271
        $actions[] = Display::url(
2272
            Display::return_icon('back.png', get_lang('Back'), [], ICON_SIZE_MEDIUM),
2273
            $this->baseUrl.http_build_query(['action' => 'view', 'id' => $item->getId()])
2274
        );
2275
2276
        $this->renderView($form->returnForm(), get_lang('Qualify'), $actions);
2277
    }
2278
2279
    public function qualifyComment(PortfolioComment $comment)
2280
    {
2281
        global $interbreadcrumb;
2282
2283
        $em = Database::getManager();
2284
2285
        $item = $comment->getItem();
2286
        $commentPath = $em->getRepository(PortfolioComment::class)->getPath($comment);
2287
2288
        $template = new Template('', false, false, false, true, false, false);
2289
        $template->assign('item', $item);
2290
        $template->assign('comments_path', $commentPath);
2291
        $commentContext = $template->fetch(
2292
            $template->get_template('portfolio/comment_context.html.twig')
2293
        );
2294
2295
        $formAction = $this->baseUrl.http_build_query(['action' => 'qualify', 'comment' => $comment->getId()]);
2296
2297
        $form = new FormValidator('frm_qualify', 'post', $formAction);
2298
        $form->addHtml($commentContext);
2299
        $form->addUserAvatar('user', get_lang('Author'));
2300
        $form->addLabel(get_lang('Comment'), $comment->getContent());
2301
        $form->addNumeric(
2302
            'score',
2303
            [get_lang('QualifyNumeric'), null, '/ '.api_get_course_setting('portfolio_max_score')]
2304
        );
2305
        $form->addButtonSave(get_lang('QualifyThisPortfolioComment'));
2306
2307
        if ($form->validate()) {
2308
            $values = $form->exportValues();
2309
2310
            $comment->setScore($values['score']);
2311
2312
            $em->persist($comment);
2313
            $em->flush();
2314
2315
            Display::addFlash(
2316
                Display::return_message(get_lang('PortfolioCommentGraded'), 'success')
2317
            );
2318
2319
            header("Location: $formAction");
2320
            exit();
2321
        }
2322
2323
        $form->setDefaults(
2324
            [
2325
                'user' => $comment->getAuthor(),
2326
                'score' => (float) $comment->getScore(),
2327
            ]
2328
        );
2329
2330
        $interbreadcrumb[] = [
2331
            'name' => get_lang('Portfolio'),
2332
            'url' => $this->baseUrl,
2333
        ];
2334
        $interbreadcrumb[] = [
2335
            'name' => $item->getTitle(true),
2336
            'url' => $this->baseUrl.http_build_query(['action' => 'view', 'id' => $item->getId()]),
2337
        ];
2338
2339
        $actions = [];
2340
        $actions[] = Display::url(
2341
            Display::return_icon('back.png', get_lang('Back'), [], ICON_SIZE_MEDIUM),
2342
            $this->baseUrl.http_build_query(['action' => 'view', 'id' => $item->getId()])
2343
        );
2344
2345
        $this->renderView($form->returnForm(), get_lang('Qualify'), $actions);
2346
    }
2347
2348
    public function downloadAttachment(HttpRequest $httpRequest)
2349
    {
2350
        $path = $httpRequest->query->get('file');
2351
2352
        if (empty($path)) {
2353
            api_not_allowed(true);
2354
        }
2355
2356
        $em = Database::getManager();
2357
        $attachmentRepo = $em->getRepository(PortfolioAttachment::class);
2358
2359
        $attachment = $attachmentRepo->findOneByPath($path);
2360
2361
        if (empty($attachment)) {
2362
            api_not_allowed(true);
2363
        }
2364
2365
        $originOwnerId = 0;
2366
2367
        if (PortfolioAttachment::TYPE_ITEM === $attachment->getOriginType()) {
2368
            $item = $em->find(Portfolio::class, $attachment->getOrigin());
2369
2370
            $originOwnerId = $item->getUser()->getId();
2371
        } elseif (PortfolioAttachment::TYPE_COMMENT === $attachment->getOriginType()) {
2372
            $comment = $em->find(PortfolioComment::class, $attachment->getOrigin());
2373
2374
            $originOwnerId = $comment->getAuthor()->getId();
2375
        } else {
2376
            api_not_allowed(true);
2377
        }
2378
2379
        $userDirectory = UserManager::getUserPathById($originOwnerId, 'system');
2380
        $attachmentsDirectory = $userDirectory.'portfolio_attachments/';
2381
        $attachmentFilename = $attachmentsDirectory.$attachment->getPath();
2382
2383
        if (!Security::check_abs_path($attachmentFilename, $attachmentsDirectory)) {
2384
            api_not_allowed(true);
2385
        }
2386
2387
        $downloaded = DocumentManager::file_send_for_download(
2388
            $attachmentFilename,
2389
            true,
2390
            $attachment->getFilename()
2391
        );
2392
2393
        if (!$downloaded) {
2394
            api_not_allowed(true);
2395
        }
2396
    }
2397
2398
    public function deleteAttachment(HttpRequest $httpRequest)
2399
    {
2400
        $currentUserId = api_get_user_id();
2401
2402
        $path = $httpRequest->query->get('file');
2403
2404
        if (empty($path)) {
2405
            api_not_allowed(true);
2406
        }
2407
2408
        $em = Database::getManager();
2409
        $fs = new Filesystem();
2410
2411
        $attachmentRepo = $em->getRepository(PortfolioAttachment::class);
2412
        $attachment = $attachmentRepo->findOneByPath($path);
2413
2414
        if (empty($attachment)) {
2415
            api_not_allowed(true);
2416
        }
2417
2418
        $originOwnerId = 0;
2419
        $itemId = 0;
2420
2421
        if (PortfolioAttachment::TYPE_ITEM === $attachment->getOriginType()) {
2422
            $item = $em->find(Portfolio::class, $attachment->getOrigin());
2423
            $originOwnerId = $item->getUser()->getId();
2424
            $itemId = $item->getId();
2425
        } elseif (PortfolioAttachment::TYPE_COMMENT === $attachment->getOriginType()) {
2426
            $comment = $em->find(PortfolioComment::class, $attachment->getOrigin());
2427
            $originOwnerId = $comment->getAuthor()->getId();
2428
            $itemId = $comment->getItem()->getId();
2429
        }
2430
2431
        if ($currentUserId !== $originOwnerId) {
2432
            api_not_allowed(true);
2433
        }
2434
2435
        $em->remove($attachment);
2436
        $em->flush();
2437
2438
        $userDirectory = UserManager::getUserPathById($originOwnerId, 'system');
2439
        $attachmentsDirectory = $userDirectory.'portfolio_attachments/';
2440
        $attachmentFilename = $attachmentsDirectory.$attachment->getPath();
2441
2442
        $fs->remove($attachmentFilename);
2443
2444
        if ($httpRequest->isXmlHttpRequest()) {
2445
            echo Display::return_message(get_lang('AttachmentFileDeleteSuccess'), 'success');
2446
        } else {
2447
            Display::addFlash(
2448
                Display::return_message(get_lang('AttachmentFileDeleteSuccess'), 'success')
2449
            );
2450
2451
            header('Location: '.$this->baseUrl.http_build_query(['action' => 'view', 'id' => $itemId]));
2452
        }
2453
2454
        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...
2455
    }
2456
2457
    /**
2458
     * @throws \Doctrine\ORM\OptimisticLockException
2459
     * @throws \Doctrine\ORM\ORMException
2460
     */
2461
    public function markAsHighlighted(Portfolio $item)
2462
    {
2463
        if ($item->getCourse()->getId() !== (int) api_get_course_int_id()) {
2464
            api_not_allowed(true);
2465
        }
2466
2467
        $item->setIsHighlighted(
2468
            !$item->isHighlighted()
2469
        );
2470
2471
        Database::getManager()->flush();
2472
2473
        Display::addFlash(
2474
            Display::return_message(
2475
                $item->isHighlighted() ? get_lang('MarkedAsHighlighted') : get_lang('MarkedAsNoHighlighted'),
2476
                'success'
2477
            )
2478
        );
2479
2480
        header("Location: $this->baseUrl".http_build_query(['action' => 'view', 'id' => $item->getId()]));
2481
        exit;
2482
    }
2483
2484
    /**
2485
     * @param bool $showHeader
2486
     */
2487
    private function renderView(string $content, string $toolName, array $actions = [], $showHeader = true)
2488
    {
2489
        global $this_section;
2490
2491
        $this_section = $this->course ? SECTION_COURSES : SECTION_SOCIAL;
2492
2493
        $view = new Template($toolName);
2494
2495
        if ($showHeader) {
2496
            $view->assign('header', $toolName);
2497
        }
2498
2499
        $actionsStr = '';
2500
2501
        if ($this->course) {
2502
            $actionsStr .= Display::return_introduction_section(TOOL_PORTFOLIO);
0 ignored issues
show
Bug introduced by
Are you sure the usage of Display::return_introduc...section(TOOL_PORTFOLIO) targeting Display::return_introduction_section() seems to always return null.

This check looks for function or method calls that always return null and whose return value is used.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
if ($a->getObject()) {

The method getObject() can return nothing but null, so it makes no sense to use the return value.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
2503
        }
2504
2505
        if ($actions) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $actions of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
2506
            $actions = implode('', $actions);
2507
2508
            $actionsStr .= Display::toolbarAction('portfolio-toolbar', [$actions]);
2509
        }
2510
2511
        $view->assign('baseurl', $this->baseUrl);
2512
        $view->assign('actions', $actionsStr);
2513
2514
        $view->assign('content', $content);
2515
        $view->display_one_col_template();
2516
    }
2517
2518
    private function categoryBelongToOwner(PortfolioCategory $category): bool
2519
    {
2520
        if ($category->getUser()->getId() != $this->owner->getId()) {
2521
            return false;
2522
        }
2523
2524
        return true;
2525
    }
2526
2527
    private function addAttachmentsFieldToForm(FormValidator $form)
2528
    {
2529
        $form->addButton('add_attachment', get_lang('AddAttachment'), 'plus');
2530
        $form->addHtml('<div id="container-attachments" style="display: none;">');
2531
        $form->addFile('attachment_file[]', get_lang('FilesAttachment'));
2532
        $form->addText('attachment_comment[]', get_lang('Description'), false);
2533
        $form->addHtml('</div>');
2534
2535
        $script = "$(function () {
2536
            var attachmentsTemplate = $('#container-attachments').html();
2537
            var \$btnAdd = $('[name=\"add_attachment\"]');
2538
            var \$reference = \$btnAdd.parents('.form-group');
2539
2540
            \$btnAdd.on('click', function (e) {
2541
                e.preventDefault();
2542
2543
                $(attachmentsTemplate).insertBefore(\$reference);
2544
            });
2545
        })";
2546
2547
        $form->addHtml("<script>$script</script>");
2548
    }
2549
2550
    private function processAttachments(
2551
        FormValidator $form,
2552
        User $user,
2553
        int $originId,
2554
        int $originType
2555
    ) {
2556
        $em = Database::getManager();
2557
        $fs = new Filesystem();
2558
2559
        $comments = $form->getSubmitValue('attachment_comment');
2560
2561
        foreach ($_FILES['attachment_file']['error'] as $i => $attachmentFileError) {
2562
            if ($attachmentFileError != UPLOAD_ERR_OK) {
2563
                continue;
2564
            }
2565
2566
            $_file = [
2567
                'name' => $_FILES['attachment_file']['name'][$i],
2568
                'type' => $_FILES['attachment_file']['type'][$i],
2569
                'tmp_name' => $_FILES['attachment_file']['tmp_name'][$i],
2570
                'size' => $_FILES['attachment_file']['size'][$i],
2571
            ];
2572
2573
            if (empty($_file['type'])) {
2574
                $_file['type'] = DocumentManager::file_get_mime_type($_file['name']);
2575
            }
2576
2577
            $newFileName = add_ext_on_mime(stripslashes($_file['name']), $_file['type']);
2578
2579
            if (!filter_extension($newFileName)) {
2580
                Display::addFlash(Display::return_message(get_lang('UplUnableToSaveFileFilteredExtension'), 'error'));
2581
                continue;
2582
            }
2583
2584
            $newFileName = uniqid();
2585
            $attachmentsDirectory = UserManager::getUserPathById($user->getId(), 'system').'portfolio_attachments/';
2586
2587
            if (!$fs->exists($attachmentsDirectory)) {
2588
                $fs->mkdir($attachmentsDirectory, api_get_permissions_for_new_directories());
2589
            }
2590
2591
            $attachmentFilename = $attachmentsDirectory.$newFileName;
2592
2593
            if (is_uploaded_file($_file['tmp_name'])) {
2594
                $moved = move_uploaded_file($_file['tmp_name'], $attachmentFilename);
2595
2596
                if (!$moved) {
2597
                    Display::addFlash(Display::return_message(get_lang('UplUnableToSaveFile'), 'error'));
2598
                    continue;
2599
                }
2600
            }
2601
2602
            $attachment = new PortfolioAttachment();
2603
            $attachment
2604
                ->setFilename($_file['name'])
2605
                ->setComment($comments[$i])
2606
                ->setPath($newFileName)
2607
                ->setOrigin($originId)
2608
                ->setOriginType($originType)
2609
                ->setSize($_file['size']);
2610
2611
            $em->persist($attachment);
2612
            $em->flush();
2613
        }
2614
    }
2615
2616
    private function itemBelongToOwner(Portfolio $item): bool
2617
    {
2618
        if ($item->getUser()->getId() != $this->owner->getId()) {
2619
            return false;
2620
        }
2621
2622
        return true;
2623
    }
2624
2625
    private function createFormTagFilter(bool $listByUser = false): FormValidator
2626
    {
2627
        $em = Database::getManager();
2628
        $tagTepo = $em->getRepository(Tag::class);
2629
2630
        $frmTagList = new FormValidator(
2631
            'frm_tag_list',
2632
            'get',
2633
            $this->baseUrl.($listByUser ? 'user='.$this->owner->getId() : ''),
2634
            '',
2635
            [],
2636
            FormValidator::LAYOUT_BOX
2637
        );
2638
2639
        $frmTagList->addDatePicker('date', get_lang('CreationDate'));
2640
2641
        /** @var SelectAjax $txtTags */
2642
        $txtTags = $frmTagList->addSelectAjax(
2643
            'tags',
2644
            get_lang('Tags'),
2645
            [],
2646
            [
2647
                'multiple' => 'multiple',
2648
                'url' => api_get_path(WEB_AJAX_PATH)."extra_field.ajax.php?a=search_tags&field_id=29&type=portfolio&byid=1",
2649
            ]
2650
        );
2651
        $selectedTags = $txtTags->getValue();
2652
2653
        if (!empty($selectedTags)) {
2654
            foreach ($tagTepo->findById($selectedTags) as $tag) {
2655
                $txtTags->addOption($tag->getTag(), $tag->getId());
2656
            }
2657
        }
2658
2659
        $frmTagList->addText('text', get_lang('Search'), false)->setIcon('search');
2660
        $frmTagList->applyFilter('text', 'trim');
2661
        $frmTagList->addHtml('<br>');
2662
        $frmTagList->addButtonFilter(get_lang('Filter'));
2663
2664
        if ($this->course) {
2665
            $frmTagList->addHidden('cidReq', $this->course->getCode());
2666
            $frmTagList->addHidden('id_session', $this->session ? $this->session->getId() : 0);
2667
            $frmTagList->addHidden('gidReq', 0);
2668
            $frmTagList->addHidden('gradebook', 0);
2669
            $frmTagList->addHidden('origin', '');
2670
            $frmTagList->addHidden('categoryId', 0);
2671
            $frmTagList->addHidden('subCategoryIds', '');
2672
2673
            if ($listByUser) {
2674
                $frmTagList->addHidden('user', $this->owner->getId());
2675
            }
2676
        }
2677
2678
        return $frmTagList;
2679
    }
2680
2681
    /**
2682
     * @throws Exception
2683
     */
2684
    private function createFormStudentFilter(bool $listByUser = false, bool $listHighlighted = false): FormValidator
2685
    {
2686
        $frmStudentList = new FormValidator(
2687
            'frm_student_list',
2688
            'get',
2689
            $this->baseUrl,
2690
            '',
2691
            [],
2692
            FormValidator::LAYOUT_BOX
2693
        );
2694
2695
        $urlParams = http_build_query(
2696
            [
2697
                'a' => 'search_user_by_course',
2698
                'course_id' => $this->course->getId(),
2699
                'session_id' => $this->session ? $this->session->getId() : 0,
2700
            ]
2701
        );
2702
2703
        /** @var SelectAjax $slctUser */
2704
        $slctUser = $frmStudentList->addSelectAjax(
2705
            'user',
2706
            get_lang('SelectLearnerPortfolio'),
2707
            [],
2708
            [
2709
                'url' => api_get_path(WEB_AJAX_PATH)."course.ajax.php?$urlParams",
2710
                'placeholder' => get_lang('SearchStudent'),
2711
                'formatResult' => SelectAjax::templateResultForUsersInCourse(),
2712
                'formatSelection' => SelectAjax::templateSelectionForUsersInCourse(),
2713
            ]
2714
        );
2715
2716
        if ($listByUser) {
2717
            $slctUser->addOption(
2718
                $this->owner->getCompleteName(),
2719
                $this->owner->getId(),
2720
                [
2721
                    'data-avatarurl' => UserManager::getUserPicture($this->owner->getId()),
2722
                    'data-username' => $this->owner->getUsername(),
2723
                ]
2724
            );
2725
2726
            $link = Display::url(
2727
                get_lang('BackToMainPortfolio'),
2728
                $this->baseUrl
2729
            );
2730
        } else {
2731
            $link = Display::url(
2732
                get_lang('SeeMyPortfolio'),
2733
                $this->baseUrl.http_build_query(['user' => api_get_user_id()])
2734
            );
2735
        }
2736
2737
        $frmStudentList->addHtml("<p>$link</p>");
2738
2739
        if ($listHighlighted) {
2740
            $link = Display::url(
2741
                get_lang('BackToMainPortfolio'),
2742
                $this->baseUrl
2743
            );
2744
        } else {
2745
            $link = Display::url(
2746
                get_lang('SeeHighlights'),
2747
                $this->baseUrl.http_build_query(['list_highlighted' => true])
2748
            );
2749
        }
2750
2751
        $frmStudentList->addHtml("<p>$link</p>");
2752
2753
        return $frmStudentList;
2754
    }
2755
2756
    private function getCategoriesForIndex(?int $currentUserId = null, ?int $parentId = null): array
2757
    {
2758
        $categoriesCriteria = [];
2759
        if (isset($currentUserId)) {
2760
            $categoriesCriteria['user'] = $this->owner;
2761
        }
2762
        if (!api_is_platform_admin() && $currentUserId !== $this->owner->getId()) {
2763
            $categoriesCriteria['isVisible'] = true;
2764
        }
2765
        if (isset($parentId)) {
2766
            $categoriesCriteria['parentId'] = $parentId;
2767
        }
2768
2769
        return $this->em
2770
            ->getRepository(PortfolioCategory::class)
2771
            ->findBy($categoriesCriteria);
2772
    }
2773
2774
    private function getHighlightedItems()
2775
    {
2776
        $queryBuilder = $this->em->createQueryBuilder();
2777
        $queryBuilder
2778
            ->select('pi')
2779
            ->from(Portfolio::class, 'pi')
2780
            ->where('pi.course = :course')
2781
            ->andWhere('pi.isHighlighted = TRUE')
2782
            ->setParameter('course', $this->course);
2783
2784
        if ($this->session) {
2785
            $queryBuilder->andWhere('pi.session = :session');
2786
            $queryBuilder->setParameter('session', $this->session);
2787
        } else {
2788
            $queryBuilder->andWhere('pi.session IS NULL');
2789
        }
2790
2791
        $visibilityCriteria = [Portfolio::VISIBILITY_VISIBLE];
2792
2793
        if (api_is_allowed_to_edit()) {
2794
            $visibilityCriteria[] = Portfolio::VISIBILITY_HIDDEN_EXCEPT_TEACHER;
2795
        }
2796
2797
        $queryBuilder
2798
            ->andWhere(
2799
                $queryBuilder->expr()->orX(
2800
                    'pi.user = :current_user',
2801
                    $queryBuilder->expr()->andX(
2802
                        'pi.user != :current_user',
2803
                        $queryBuilder->expr()->in('pi.visibility', $visibilityCriteria)
2804
                    )
2805
                )
2806
            )
2807
            ->setParameter('current_user', api_get_user_id());
2808
2809
        $queryBuilder->orderBy('pi.creationDate', 'DESC');
2810
2811
        return $queryBuilder->getQuery()->getResult();
2812
    }
2813
2814
    private function getItemsForIndex(
2815
        bool $listByUser = false,
2816
        FormValidator $frmFilterList = null
2817
    ) {
2818
        $currentUserId = api_get_user_id();
2819
2820
        if ($this->course) {
2821
            $queryBuilder = $this->em->createQueryBuilder();
2822
            $queryBuilder
2823
                ->select('pi')
2824
                ->from(Portfolio::class, 'pi')
2825
                ->where('pi.course = :course');
2826
2827
            $queryBuilder->setParameter('course', $this->course);
2828
2829
            if ($this->session) {
2830
                $queryBuilder->andWhere('pi.session = :session');
2831
                $queryBuilder->setParameter('session', $this->session);
2832
            } else {
2833
                $queryBuilder->andWhere('pi.session IS NULL');
2834
            }
2835
2836
            if ($frmFilterList && $frmFilterList->validate()) {
2837
                $values = $frmFilterList->exportValues();
2838
2839
                if (!empty($values['date'])) {
2840
                    $queryBuilder
2841
                        ->andWhere('pi.creationDate >= :date')
2842
                        ->setParameter(':date', api_get_utc_datetime($values['date'], false, true))
2843
                    ;
2844
                }
2845
2846
                if (!empty($values['tags'])) {
2847
                    $queryBuilder
2848
                        ->innerJoin(ExtraFieldRelTag::class, 'efrt', Join::WITH, 'efrt.itemId = pi.id')
2849
                        ->innerJoin(ExtraFieldEntity::class, 'ef', Join::WITH, 'ef.id = efrt.fieldId')
2850
                        ->andWhere('ef.extraFieldType = :efType')
2851
                        ->andWhere('ef.variable = :variable')
2852
                        ->andWhere('efrt.tagId IN (:tags)');
2853
2854
                    $queryBuilder->setParameter('efType', ExtraFieldEntity::PORTFOLIO_TYPE);
2855
                    $queryBuilder->setParameter('variable', 'tags');
2856
                    $queryBuilder->setParameter('tags', $values['tags']);
2857
                }
2858
2859
                if (!empty($values['text'])) {
2860
                    $queryBuilder->andWhere(
2861
                        $queryBuilder->expr()->orX(
2862
                            $queryBuilder->expr()->like('pi.title', ':text'),
2863
                            $queryBuilder->expr()->like('pi.content', ':text')
2864
                        )
2865
                    );
2866
2867
                    $queryBuilder->setParameter('text', '%'.$values['text'].'%');
2868
                }
2869
2870
                // Filters by category level 0
2871
                $searchCategories = [];
2872
                if (!empty($values['categoryId'])) {
2873
                    $searchCategories[] = $values['categoryId'];
2874
                    $subCategories = $this->getCategoriesForIndex(null, $values['categoryId']);
2875
                    if (count($subCategories) > 0) {
2876
                        foreach ($subCategories as $subCategory) {
2877
                            $searchCategories[] = $subCategory->getId();
2878
                        }
2879
                    }
2880
                    $queryBuilder->andWhere('pi.category IN('.implode(',', $searchCategories).')');
2881
                }
2882
2883
                // Filters by sub-category, don't show the selected values
2884
                $diff = [];
2885
                if (!empty($values['subCategoryIds']) && !('all' === $values['subCategoryIds'])) {
2886
                    $subCategoryIds = explode(',', $values['subCategoryIds']);
2887
                    $diff = array_diff($searchCategories, $subCategoryIds);
2888
                } else {
2889
                    if (trim($values['subCategoryIds']) === '') {
2890
                        $diff = $searchCategories;
2891
                    }
2892
                }
2893
                if (!empty($diff)) {
2894
                    unset($diff[0]);
2895
                    if (!empty($diff)) {
2896
                        $queryBuilder->andWhere('pi.category NOT IN('.implode(',', $diff).')');
2897
                    }
2898
                }
2899
            }
2900
2901
            if ($listByUser) {
2902
                $queryBuilder
2903
                    ->andWhere('pi.user = :user')
2904
                    ->setParameter('user', $this->owner);
2905
            }
2906
2907
            $visibilityCriteria = [Portfolio::VISIBILITY_VISIBLE];
2908
2909
            if (api_is_allowed_to_edit()) {
2910
                $visibilityCriteria[] = Portfolio::VISIBILITY_HIDDEN_EXCEPT_TEACHER;
2911
            }
2912
2913
            $queryBuilder
2914
                ->andWhere(
2915
                    $queryBuilder->expr()->orX(
2916
                        'pi.user = :current_user',
2917
                        $queryBuilder->expr()->andX(
2918
                            'pi.user != :current_user',
2919
                            $queryBuilder->expr()->in('pi.visibility', $visibilityCriteria)
2920
                        )
2921
                    )
2922
                )
2923
                ->setParameter('current_user', $currentUserId);
2924
2925
            $queryBuilder->orderBy('pi.creationDate', 'DESC');
2926
2927
            $items = $queryBuilder->getQuery()->getResult();
2928
        } else {
2929
            $itemsCriteria = [];
2930
            $itemsCriteria['category'] = null;
2931
            $itemsCriteria['user'] = $this->owner;
2932
2933
            if ($currentUserId !== $this->owner->getId()) {
2934
                $itemsCriteria['visibility'] = Portfolio::VISIBILITY_VISIBLE;
2935
            }
2936
2937
            $items = $this->em
2938
                ->getRepository(Portfolio::class)
2939
                ->findBy($itemsCriteria, ['creationDate' => 'DESC']);
2940
        }
2941
2942
        return $items;
2943
    }
2944
2945
    /**
2946
     * @throws \Doctrine\ORM\ORMException
2947
     * @throws \Doctrine\ORM\OptimisticLockException
2948
     * @throws \Doctrine\ORM\TransactionRequiredException
2949
     */
2950
    private function createCommentForm(Portfolio $item): string
2951
    {
2952
        $formAction = $this->baseUrl.http_build_query(['action' => 'view', 'id' => $item->getId()]);
2953
2954
        $form = new FormValidator('frm_comment', 'post', $formAction);
2955
        $form->addHeader(get_lang('AddNewComment'));
2956
        $form->addHtmlEditor('content', get_lang('Comments'), true, false, ['ToolbarSet' => 'Minimal']);
2957
        $form->addHidden('item', $item->getId());
2958
        $form->addHidden('parent', 0);
2959
        $form->applyFilter('content', 'trim');
2960
2961
        $this->addAttachmentsFieldToForm($form);
2962
2963
        $form->addButtonSave(get_lang('Save'));
2964
2965
        if ($form->validate()) {
2966
            $values = $form->exportValues();
2967
2968
            $parentComment = $this->em->find(PortfolioComment::class, $values['parent']);
2969
2970
            $comment = new PortfolioComment();
2971
            $comment
2972
                ->setAuthor($this->owner)
2973
                ->setParent($parentComment)
2974
                ->setContent($values['content'])
2975
                ->setDate(api_get_utc_datetime(null, false, true))
2976
                ->setItem($item);
2977
2978
            $this->em->persist($comment);
2979
            $this->em->flush();
2980
2981
            $this->processAttachments(
2982
                $form,
2983
                $comment->getAuthor(),
2984
                $comment->getId(),
2985
                PortfolioAttachment::TYPE_COMMENT
2986
            );
2987
2988
            $hook = HookPortfolioItemCommented::create();
2989
            $hook->setEventData(['comment' => $comment]);
2990
            $hook->notifyItemCommented();
2991
2992
            Display::addFlash(
2993
                Display::return_message(get_lang('CommentAdded'), 'success')
2994
            );
2995
2996
            header("Location: $formAction");
2997
            exit;
0 ignored issues
show
Bug Best Practice introduced by
In this branch, the function will implicitly return null which is incompatible with the type-hinted return string. Consider adding a return statement or allowing null as return value.

For hinted functions/methods where all return statements with the correct type are only reachable via conditions, ?null? gets implicitly returned which may be incompatible with the hinted type. Let?s take a look at an example:

interface ReturnsInt {
    public function returnsIntHinted(): int;
}

class MyClass implements ReturnsInt {
    public function returnsIntHinted(): int
    {
        if (foo()) {
            return 123;
        }
        // here: null is implicitly returned
    }
}
Loading history...
2998
        }
2999
3000
        return $form->returnForm();
3001
    }
3002
3003
    private function generateAttachmentList($post, bool $includeHeader = true): string
3004
    {
3005
        $attachmentsRepo = $this->em->getRepository(PortfolioAttachment::class);
3006
3007
        $postOwnerId = 0;
3008
3009
        if ($post instanceof Portfolio) {
3010
            $attachments = $attachmentsRepo->findFromItem($post);
3011
3012
            $postOwnerId = $post->getUser()->getId();
3013
        } elseif ($post instanceof PortfolioComment) {
3014
            $attachments = $attachmentsRepo->findFromComment($post);
3015
3016
            $postOwnerId = $post->getAuthor()->getId();
3017
        }
3018
3019
        if (empty($attachments)) {
3020
            return '';
3021
        }
3022
3023
        $currentUserId = api_get_user_id();
3024
3025
        $listItems = '<ul class="fa-ul">';
3026
3027
        $deleteIcon = Display::return_icon(
3028
            'delete.png',
3029
            get_lang('DeleteAttachment'),
3030
            ['style' => 'display: inline-block'],
3031
            ICON_SIZE_TINY
3032
        );
3033
        $deleteAttrs = ['class' => 'btn-portfolio-delete'];
3034
3035
        /** @var PortfolioAttachment $attachment */
3036
        foreach ($attachments as $attachment) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $attachments does not seem to be defined for all execution paths leading up to this point.
Loading history...
3037
            $downloadParams = http_build_query(['action' => 'download_attachment', 'file' => $attachment->getPath()]);
3038
            $deleteParams = http_build_query(['action' => 'delete_attachment', 'file' => $attachment->getPath()]);
3039
3040
            $listItems .= '<li>'
3041
                .'<span class="fa-li fa fa-paperclip" aria-hidden="true"></span>'
3042
                .Display::url(
3043
                    Security::remove_XSS($attachment->getFilename()),
3044
                    $this->baseUrl.$downloadParams
3045
                );
3046
3047
            if ($currentUserId === $postOwnerId) {
3048
                $listItems .= PHP_EOL.Display::url($deleteIcon, $this->baseUrl.$deleteParams, $deleteAttrs);
3049
            }
3050
3051
            if ($attachment->getComment()) {
3052
                $listItems .= '<p class="text-muted">'.Security::remove_XSS($attachment->getComment()).'</p>';
3053
            }
3054
3055
            $listItems .= '</li>';
3056
        }
3057
3058
        $listItems .= '</ul>';
3059
3060
        if ($includeHeader) {
3061
            $listItems = '<h1 class="h4">'.get_lang('AttachmentFiles').'</h1>'
3062
                .$listItems;
3063
        }
3064
3065
        return $listItems;
3066
    }
3067
3068
    private function generateItemContent(Portfolio $item): string
3069
    {
3070
        $originId = $item->getOrigin();
3071
3072
        if (empty($originId)) {
3073
            return $item->getContent();
3074
        }
3075
3076
        $em = Database::getManager();
3077
3078
        $originContent = '';
3079
        $originContentFooter = '';
3080
3081
        if (Portfolio::TYPE_ITEM === $item->getOriginType()) {
3082
            $origin = $em->find(Portfolio::class, $item->getOrigin());
3083
3084
            if ($origin) {
3085
                $originContent = $origin->getContent();
3086
                $originContentFooter = vsprintf(
3087
                    get_lang('OriginallyPublishedAsXTitleByYUser'),
3088
                    [
3089
                        "<cite>{$origin->getTitle(true)}</cite>",
3090
                        $origin->getUser()->getCompleteName(),
3091
                    ]
3092
                );
3093
            }
3094
        } elseif (Portfolio::TYPE_COMMENT === $item->getOriginType()) {
3095
            $origin = $em->find(PortfolioComment::class, $item->getOrigin());
3096
3097
            if ($origin) {
3098
                $originContent = $origin->getContent();
3099
                $originContentFooter = vsprintf(
3100
                    get_lang('OriginallyCommentedByXUserInYItem'),
3101
                    [
3102
                        $origin->getAuthor()->getCompleteName(),
3103
                        "<cite>{$origin->getItem()->getTitle(true)}</cite>",
3104
                    ]
3105
                );
3106
            }
3107
        }
3108
3109
        if ($originContent) {
3110
            return "<figure>
3111
                    <blockquote>$originContent</blockquote>
3112
                    <figcaption style=\"margin-bottom: 10px;\">$originContentFooter</figcaption>
3113
                </figure>
3114
                <div class=\"clearfix\">".Security::remove_XSS($item->getContent()).'</div>'
3115
            ;
3116
        }
3117
3118
        return Security::remove_XSS($item->getContent());
3119
    }
3120
3121
    private function getItemsInHtmlFormatted(array $items): array
3122
    {
3123
        $itemsHtml = [];
3124
3125
        /** @var Portfolio $item */
3126
        foreach ($items as $item) {
3127
            $creationDate = api_convert_and_format_date($item->getCreationDate());
3128
            $updateDate = api_convert_and_format_date($item->getUpdateDate());
3129
3130
            $metadata = '<ul class="list-unstyled text-muted">';
3131
3132
            if ($item->getSession()) {
3133
                $metadata .= '<li>'.get_lang('Course').': '.$item->getSession()->getName().' ('
3134
                    .$item->getCourse()->getTitle().') </li>';
3135
            } elseif (!$item->getSession() && $item->getCourse()) {
3136
                $metadata .= '<li>'.get_lang('Course').': '.$item->getCourse()->getTitle().'</li>';
3137
            }
3138
3139
            $metadata .= '<li>'.sprintf(get_lang('CreationDateXDate'), $creationDate).'</li>';
3140
            $metadata .= '<li>'.sprintf(get_lang('UpdateDateXDate'), $updateDate).'</li>';
3141
3142
            if ($item->getCategory()) {
3143
                $metadata .= '<li>'.sprintf(get_lang('CategoryXName'), $item->getCategory()->getTitle()).'</li>';
3144
            }
3145
3146
            $metadata .= '</ul>';
3147
3148
            $itemContent = $this->generateItemContent($item);
3149
3150
            $itemsHtml[] = Display::panel($itemContent, Security::remove_XSS($item->getTitle()), '', 'info', $metadata);
3151
        }
3152
3153
        return $itemsHtml;
3154
    }
3155
3156
    private function getCommentsInHtmlFormatted(array $comments): array
3157
    {
3158
        $commentsHtml = [];
3159
3160
        /** @var PortfolioComment $comment */
3161
        foreach ($comments as $comment) {
3162
            $item = $comment->getItem();
3163
            $date = api_convert_and_format_date($comment->getDate());
3164
3165
            $metadata = '<ul class="list-unstyled text-muted">';
3166
            $metadata .= '<li>'.sprintf(get_lang('DateXDate'), $date).'</li>';
3167
            $metadata .= '<li>'.sprintf(get_lang('PortfolioItemTitleXName'), Security::remove_XSS($item->getTitle()))
3168
                .'</li>';
3169
            $metadata .= '</ul>';
3170
3171
            $commentsHtml[] = Display::panel(
3172
                Security::remove_XSS($comment->getContent()),
3173
                '',
3174
                '',
3175
                'default',
3176
                $metadata
3177
            );
3178
        }
3179
3180
        return $commentsHtml;
3181
    }
3182
3183
    private function fixImagesSourcesToHtml(string $htmlContent): string
3184
    {
3185
        $doc = new DOMDocument();
3186
        @$doc->loadHTML($htmlContent);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition for loadHTML(). This can introduce security issues, and is generally not recommended. ( Ignorable by Annotation )

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

3186
        /** @scrutinizer ignore-unhandled */ @$doc->loadHTML($htmlContent);

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
3187
3188
        $elements = $doc->getElementsByTagName('img');
3189
3190
        if (empty($elements->length)) {
3191
            return $htmlContent;
3192
        }
3193
3194
        $webCoursePath = api_get_path(WEB_COURSE_PATH);
3195
        $webUploadPath = api_get_path(WEB_UPLOAD_PATH);
3196
3197
        /** @var \DOMElement $element */
3198
        foreach ($elements as $element) {
3199
            $src = trim($element->getAttribute('src'));
3200
3201
            if (strpos($src, 'http') === 0) {
3202
                continue;
3203
            }
3204
3205
            if (strpos($src, '/app/upload/') === 0) {
3206
                $element->setAttribute(
3207
                    'src',
3208
                    preg_replace('/\/app/upload\//', $webUploadPath, $src, 1)
3209
                );
3210
3211
                continue;
3212
            }
3213
3214
            if (strpos($src, '/courses/') === 0) {
3215
                $element->setAttribute(
3216
                    'src',
3217
                    preg_replace('/\/courses\//', $webCoursePath, $src, 1)
3218
                );
3219
3220
                continue;
3221
            }
3222
        }
3223
3224
        return $doc->saveHTML();
3225
    }
3226
3227
    private function formatZipIndexFile(HTML_Table $tblItems, HTML_Table $tblComments): string
3228
    {
3229
        $htmlContent = Display::page_header($this->owner->getCompleteNameWithUsername());
3230
        $htmlContent .= Display::page_subheader2(get_lang('PortfolioItems'));
3231
3232
        $htmlContent .= $tblItems->getRowCount() > 0
3233
            ? $tblItems->toHtml()
3234
            : Display::return_message(get_lang('NoItemsInYourPortfolio'), 'warning');
3235
3236
        $htmlContent .= Display::page_subheader2(get_lang('PortfolioCommentsMade'));
3237
3238
        $htmlContent .= $tblComments->getRowCount() > 0
3239
            ? $tblComments->toHtml()
3240
            : Display::return_message(get_lang('YouHaveNotCommented'), 'warning');
3241
3242
        $webAssetsPath = api_get_path(WEB_PUBLIC_PATH).'assets/';
3243
3244
        $doc = new DOMDocument();
3245
        @$doc->loadHTML($htmlContent);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition for loadHTML(). This can introduce security issues, and is generally not recommended. ( Ignorable by Annotation )

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

3245
        /** @scrutinizer ignore-unhandled */ @$doc->loadHTML($htmlContent);

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
3246
3247
        $stylesheet1 = $doc->createElement('link');
3248
        $stylesheet1->setAttribute('rel', 'stylesheet');
3249
        $stylesheet1->setAttribute('href', $webAssetsPath.'bootstrap/dist/css/bootstrap.min.css');
3250
        $stylesheet2 = $doc->createElement('link');
3251
        $stylesheet2->setAttribute('rel', 'stylesheet');
3252
        $stylesheet2->setAttribute('href', $webAssetsPath.'fontawesome/css/font-awesome.min.css');
3253
        $stylesheet3 = $doc->createElement('link');
3254
        $stylesheet3->setAttribute('rel', 'stylesheet');
3255
        $stylesheet3->setAttribute('href', ChamiloApi::getEditorDocStylePath());
3256
3257
        $head = $doc->createElement('head');
3258
        $head->appendChild($stylesheet1);
3259
        $head->appendChild($stylesheet2);
3260
        $head->appendChild($stylesheet3);
3261
3262
        $doc->documentElement->insertBefore(
3263
            $head,
3264
            $doc->getElementsByTagName('body')->item(0)
3265
        );
3266
3267
        return $doc->saveHTML();
3268
    }
3269
3270
    /**
3271
     * It parsers a title for a variable in lang.
3272
     *
3273
     * @param $defaultDisplayText
3274
     *
3275
     * @return string
3276
     */
3277
    private function getLanguageVariable($defaultDisplayText)
3278
    {
3279
        $variableLanguage = api_replace_dangerous_char(strtolower($defaultDisplayText));
3280
        $variableLanguage = preg_replace('/[^A-Za-z0-9\_]/', '', $variableLanguage); // Removes special chars except underscore.
3281
        if (is_numeric($variableLanguage[0])) {
3282
            $variableLanguage = '_'.$variableLanguage;
3283
        }
3284
        $variableLanguage = api_underscore_to_camel_case($variableLanguage);
3285
3286
        return $variableLanguage;
3287
    }
3288
3289
    /**
3290
     * It translates the text as parameter.
3291
     *
3292
     * @param $defaultDisplayText
3293
     *
3294
     * @return mixed
3295
     */
3296
    private function translateDisplayName($defaultDisplayText)
3297
    {
3298
        $variableLanguage = $this->getLanguageVariable($defaultDisplayText);
3299
3300
        return isset($GLOBALS[$variableLanguage]) ? $GLOBALS[$variableLanguage] : $defaultDisplayText;
3301
    }
3302
}
3303