PortfolioController::__construct()   A
last analyzed

Complexity

Conditions 3
Paths 4

Size

Total Lines 13
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 8
c 0
b 0
f 0
dl 0
loc 13
rs 10
cc 3
nc 4
nop 0
1
<?php
2
3
/* For licensing terms, see /license.txt */
4
5
use Chamilo\CoreBundle\Entity\ResourceFile;
6
use Chamilo\CoreBundle\Entity\ResourceLink;
7
use Chamilo\CoreBundle\Enums\ActionIcon;
8
use Chamilo\CoreBundle\Enums\ObjectIcon;
9
use Chamilo\CoreBundle\Enums\StateIcon;
10
use Chamilo\CoreBundle\Component\Utils\ChamiloApi;
11
use Chamilo\CoreBundle\Entity\Course;
12
use Chamilo\CoreBundle\Entity\ExtraField as ExtraFieldEntity;
13
use Chamilo\CoreBundle\Entity\ExtraFieldRelTag;
14
use Chamilo\CoreBundle\Entity\Portfolio;
15
use Chamilo\CoreBundle\Entity\PortfolioAttachment;
16
use Chamilo\CoreBundle\Entity\PortfolioCategory;
17
use Chamilo\CoreBundle\Entity\PortfolioComment;
18
use Chamilo\CoreBundle\Entity\PortfolioRelTag;
19
use Chamilo\CoreBundle\Entity\Session;
20
use Chamilo\CoreBundle\Entity\Tag;
21
use Chamilo\CoreBundle\Entity\User;
22
use Chamilo\CoreBundle\Event\Events;
23
use Chamilo\CoreBundle\Event\PortfolioCommentEditedEvent;
24
use Chamilo\CoreBundle\Event\PortfolioCommentScoredEvent;
25
use Chamilo\CoreBundle\Event\PortfolioItemAddedEvent;
26
use Chamilo\CoreBundle\Event\PortfolioItemCommentedEvent;
27
use Chamilo\CoreBundle\Event\PortfolioItemDeletedEvent;
28
use Chamilo\CoreBundle\Event\PortfolioItemDownloadedEvent;
29
use Chamilo\CoreBundle\Event\PortfolioItemEditedEvent;
30
use Chamilo\CoreBundle\Event\PortfolioItemScoredEvent;
31
use Chamilo\CoreBundle\Event\PortfolioItemViewedEvent;
32
use Chamilo\CoreBundle\Event\PortfolioItemVisibilityChangedEvent;
33
use Chamilo\CoreBundle\Framework\Container;
34
use Chamilo\CoreBundle\Repository\Node\PortfolioCommentRepository;
35
use Chamilo\CoreBundle\Repository\ResourceLinkRepository;
36
use Chamilo\CourseBundle\Entity\CItemProperty;
37
use Doctrine\ORM\Query\Expr\Join;
38
use Mpdf\MpdfException;
39
use Symfony\Component\Filesystem\Exception\FileNotFoundException;
40
use Symfony\Component\Filesystem\Filesystem;
41
use Symfony\Component\HttpFoundation\Request as HttpRequest;
42
43
/**
44
 * Class PortfolioController.
45
 */
46
class PortfolioController
47
{
48
    public string $baseUrl;
49
    private ?Course $course;
50
    private ?Session $session;
51
    private User $owner;
52
    private \Doctrine\ORM\EntityManagerInterface $em;
53
    private bool $advancedSharingEnabled;
54
55
    /**
56
     * PortfolioController constructor.
57
     */
58
    public function __construct()
59
    {
60
        $this->em = Database::getManager();
61
62
        $this->owner = api_get_user_entity();
63
        $this->course = api_get_course_entity();
64
        $this->session = api_get_session_entity();
65
66
        $cidreq = api_get_cidreq();
67
        $this->baseUrl = api_get_self().'?'.($cidreq ? $cidreq.'&' : '');
68
69
        $this->advancedSharingEnabled = true === api_get_configuration_value('portfolio_advanced_sharing')
70
            && $this->course;
71
    }
72
73
    /**
74
     * @throws Exception
75
     */
76
    public function translateCategory($category, $languages, $languageId): void
77
    {
78
        global $interbreadcrumb;
79
80
        $originalName = $category->getTitle();
81
        $variableLanguage = '$'.$this->getLanguageVariable($originalName);
82
83
        $translateUrl = api_get_path(WEB_AJAX_PATH).'lang.ajax.php?a=translate_portfolio_category&sec_token='.Security::get_token();
84
        $form = new FormValidator('new_lang_variable', 'POST', $translateUrl);
85
        $form->addHeader(get_lang('Add terms to the sub-language'));
86
        $form->addText('variable_language', get_lang('Language variable'), false);
87
        $form->addText('original_name', get_lang('Original name'), false);
88
89
        $languagesOptions = [0 => get_lang('None')];
90
        foreach ($languages as $language) {
91
            $languagesOptions[$language->getId()] = $language->getOriginalName();
92
        }
93
94
        $form->addSelect(
95
            'sub_language',
96
            [get_lang('Sub-language'), get_lang('Only active sub-languages appear in this list')],
97
            $languagesOptions
98
        );
99
100
        if ($languageId) {
101
            $languageInfo = api_get_language_info($languageId);
102
            $form->addText(
103
                'new_language',
104
                [get_lang('Translation'), get_lang('If this term has already been translated, this operation will replace its translation for this sub-language.')]
105
            );
106
107
            $form->addHidden('category_id', $category->getId());
108
            $form->addHidden('id', $languageInfo['parent_id']);
109
            $form->addHidden('sub', $languageInfo['id']);
110
            $form->addHidden('sub_language_id', $languageInfo['id']);
111
            $form->addHidden('redirect', true);
112
            $form->addButtonSave(get_lang('Save'));
113
        }
114
115
        $form->setDefaults([
116
            'variable_language' => $variableLanguage,
117
            'original_name' => $originalName,
118
            'sub_language' => $languageId,
119
        ]);
120
        $form->addRule('sub_language', get_lang('Required'), 'required');
121
        $form->freeze(['variable_language', 'original_name']);
122
123
        $interbreadcrumb[] = [
124
            'name' => get_lang('Portfolio'),
125
            'url' => $this->baseUrl,
126
        ];
127
        $interbreadcrumb[] = [
128
            'name' => get_lang('Categories'),
129
            'url' => $this->baseUrl.'action=list_categories&parent_id='.$category->getParentId(),
130
        ];
131
        $interbreadcrumb[] = [
132
            'name' => Security::remove_XSS($category->getTitle()),
133
            'url' => $this->baseUrl.'action=edit_category&id='.$category->getId(),
134
        ];
135
136
        $actions = [];
137
        $actions[] = Display::url(
138
            Display::getMdiIcon(ActionIcon::BACK, 'ch-tool-icon', null, ICON_SIZE_MEDIUM, get_lang('Back')),
139
            $this->baseUrl.'action=edit_category&id='.$category->getId()
140
        );
141
142
        $js = '<script>
143
            $(function() {
144
              $("select[name=\'sub_language\']").on("change", function () {
145
                    location.href += "&sub_language=" + this.value;
146
                });
147
            });
148
        </script>';
149
        $content = $form->returnForm();
150
151
        $this->renderView($content.$js, get_lang('Translate category'), $actions);
152
    }
153
154
    public function listCategories(): void
155
    {
156
        global $interbreadcrumb;
157
158
        $parentId = isset($_REQUEST['parent_id']) ? (int) $_REQUEST['parent_id'] : 0;
159
        $table = new HTML_Table(['class' => 'table table-hover table-striped data_table']);
160
        $headers = [
161
            get_lang('Title'),
162
            get_lang('Description'),
163
        ];
164
        if ($parentId === 0) {
165
            $headers[] = get_lang('Sub-categories');
166
        }
167
        $headers[] = get_lang('Actions');
168
169
        $column = 0;
170
        foreach ($headers as $header) {
171
            $table->setHeaderContents(0, $column, $header);
172
            $column++;
173
        }
174
        $currentUserId = api_get_user_id();
175
        $row = 1;
176
        $categories = $this->getCategoriesForIndex($parentId);
177
178
        foreach ($categories as $category) {
179
            $column = 0;
180
            $subcategories = $this->getCategoriesForIndex($category->getId());
181
            $linkSubCategories = $category->getTitle();
182
            if (count($subcategories) > 0) {
183
                $linkSubCategories = Display::url(
184
                    $category->getTitle(),
185
                    $this->baseUrl.'action=list_categories&parent_id='.$category->getId()
186
                );
187
            }
188
            $table->setCellContents($row, $column++, $linkSubCategories);
189
            $table->setCellContents($row, $column++, strip_tags($category->getDescription()));
190
            if ($parentId === 0) {
191
                $table->setCellContents($row, $column++, count($subcategories));
192
            }
193
194
            // Actions
195
            $links = null;
196
            // Edit action
197
            $url = $this->baseUrl.'action=edit_category&id='.$category->getId();
198
            $links .= Display::url(Display::getMdiIcon(ActionIcon::EDIT, 'ch-tool-icon', null, ICON_SIZE_MEDIUM, get_lang('Edit')), $url).'&nbsp;';
199
            // Visible action: if active
200
            if ($category->isVisible() != 0) {
201
                $url = $this->baseUrl.'action=hide_category&id='.$category->getId();
202
                $links .= Display::url(Display::getMdiIcon(ActionIcon::VISIBLE, 'ch-tool-icon', null, ICON_SIZE_MEDIUM, get_lang('Hide')), $url).'&nbsp;';
203
            } else { // else if not active
204
                $url = $this->baseUrl.'action=show_category&id='.$category->getId();
205
                $links .= Display::url(Display::getMdiIcon(ActionIcon::INVISIBLE, 'ch-tool-icon', null, ICON_SIZE_MEDIUM, get_lang('Show')), $url).'&nbsp;';
206
            }
207
            // Delete action
208
            $url = $this->baseUrl.'action=delete_category&id='.$category->getId();
209
            $links .= Display::url(Display::getMdiIcon(ActionIcon::DELETE, 'ch-tool-icon', null, ICON_SIZE_MEDIUM, get_lang('Delete')), $url, ['onclick' => 'javascript:if(!confirm(\''.get_lang('Are you sure to delete').'?\')) return false;']);
210
211
            $table->setCellContents($row, $column++, $links);
212
            $row++;
213
        }
214
215
        $interbreadcrumb[] = [
216
            'name' => get_lang('Portfolio'),
217
            'url' => $this->baseUrl,
218
        ];
219
        if ($parentId > 0) {
220
            $interbreadcrumb[] = [
221
                'name' => get_lang('Categories'),
222
                'url' => $this->baseUrl.'action=list_categories',
223
            ];
224
        }
225
226
        $actions = [];
227
        $actions[] = Display::url(
228
            Display::getMdiIcon(ActionIcon::BACK, 'ch-tool-icon', null, ICON_SIZE_MEDIUM, get_lang('Back')),
229
            $this->baseUrl.($parentId > 0 ? 'action=list_categories' : '')
230
        );
231
        if ($currentUserId == $this->owner->getId() && $parentId === 0) {
232
            $actions[] = Display::url(
233
                Display::getMdiIcon(ActionIcon::CREATE_FOLDER, 'ch-tool-icon', null, ICON_SIZE_MEDIUM, get_lang('Add category')),
234
                $this->baseUrl.'action=add_category'
235
            );
236
        }
237
        $content = $table->toHtml();
238
239
        $pageTitle = get_lang('Categories');
240
        if ($parentId > 0) {
241
            $em = Database::getManager();
242
            $parentCategory = $em->find(PortfolioCategory::class, $parentId);
243
            $pageTitle = $parentCategory->getTitle().' : '.get_lang('Sub-categories');
244
        }
245
246
        $this->renderView($content, $pageTitle, $actions);
247
    }
248
249
    /**
250
     * @throws Exception
251
     */
252
    public function addCategory(): void
253
    {
254
        global $interbreadcrumb;
255
256
        Display::addFlash(
257
            Display::return_message(get_lang('Categories are for organization only in personal portfolio.'), 'info')
258
        );
259
260
        $form = new FormValidator('add_category', 'post', "{$this->baseUrl}&action=add_category");
261
262
        if ('true' === api_get_setting('editor.save_titles_as_html')) {
263
            $form->addHtmlEditor('title', get_lang('Title'), true, false, ['ToolbarSet' => 'TitleAsHtml']);
264
        } else {
265
            $form->addText('title', get_lang('Title'));
266
            $form->applyFilter('title', 'trim');
267
        }
268
269
        $form->addHtmlEditor('description', get_lang('Description'), false, false, ['ToolbarSet' => 'Minimal']);
270
271
        $parentSelect = $form->addSelect(
272
            'parent_id',
273
            get_lang('Parent category')
274
        );
275
        $parentSelect->addOption(sprintf(get_lang('Level %s'), '0'), 0);
276
        $categories = $this->getCategoriesForIndex(0);
277
278
        foreach ($categories as $category) {
279
            $parentSelect->addOption($category->getTitle(), $category->getId());
280
        }
281
282
        $form->addButtonCreate(get_lang('Create'));
283
284
        if ($form->validate()) {
285
            $values = $form->exportValues();
286
287
            $category = new PortfolioCategory();
288
            $category
289
                ->setTitle($values['title'])
290
                ->setDescription($values['description'])
291
                ->setParentId($values['parent_id'])
292
                ->setUser($this->owner);
293
294
            $this->em->persist($category);
295
            $this->em->flush();
296
297
            Display::addFlash(
298
                Display::return_message(get_lang('Category added'), 'success')
299
            );
300
301
            header("Location: {$this->baseUrl}action=list_categories");
302
            exit;
303
        }
304
305
        $interbreadcrumb[] = [
306
            'name' => get_lang('Portfolio'),
307
            'url' => $this->baseUrl,
308
        ];
309
        $interbreadcrumb[] = [
310
            'name' => get_lang('Categories'),
311
            'url' => $this->baseUrl.'action=list_categories',
312
        ];
313
314
        $actions = [];
315
        $actions[] = Display::url(
316
            Display::getMdiIcon(ActionIcon::BACK, 'ch-tool-icon', null, ICON_SIZE_MEDIUM, get_lang('Back')),
317
            $this->baseUrl.'action=list_categories'
318
        );
319
320
        $content = $form->returnForm();
321
322
        $this->renderView($content, get_lang('Add category'), $actions);
323
    }
324
325
    /**
326
     * @throws \Exception
327
     */
328
    public function editCategory(PortfolioCategory $category): void
329
    {
330
        global $interbreadcrumb;
331
332
        if (!api_is_platform_admin()) {
333
            api_not_allowed(true);
334
        }
335
336
        Display::addFlash(
337
            Display::return_message(get_lang('Categories are for organization only in personal portfolio.'), 'info')
338
        );
339
340
        $form = new FormValidator(
341
            'edit_category',
342
            'post',
343
            $this->baseUrl."action=edit_category&id={$category->getId()}"
344
        );
345
346
        if ('true' === api_get_setting('editor.save_titles_as_html')) {
347
            $form->addHtmlEditor('title', get_lang('Title'), true, false, ['ToolbarSet' => 'TitleAsHtml']);
348
        } else {
349
            $translateUrl = $this->baseUrl.'action=translate_category&id='.$category->getId();
350
            $translateButton = Display::toolbarButton(get_lang('Translate this term'), $translateUrl, 'language', 'link');
351
            $form->addText(
352
                'title',
353
                [get_lang('Title'), $translateButton]
354
            );
355
            $form->applyFilter('title', 'trim');
356
        }
357
358
        $form->addHtmlEditor('description', get_lang('Description'), false, false, ['ToolbarSet' => 'Minimal']);
359
        $form->addButtonUpdate(get_lang('Update'));
360
        $form->setDefaults(
361
            [
362
                'title' => $category->getTitle(),
363
                'description' => $category->getDescription(),
364
            ]
365
        );
366
367
        if ($form->validate()) {
368
            $values = $form->exportValues();
369
370
            $category
371
                ->setTitle($values['title'])
372
                ->setDescription($values['description']);
373
374
            $this->em->persist($category);
375
            $this->em->flush();
376
377
            Display::addFlash(
378
                Display::return_message(get_lang('Updated'), 'success')
379
            );
380
381
            header("Location: {$this->baseUrl}action=list_categories&parent_id=".$category->getParentId());
382
            exit;
383
        }
384
385
        $interbreadcrumb[] = [
386
            'name' => get_lang('Portfolio'),
387
            'url' => $this->baseUrl,
388
        ];
389
        $interbreadcrumb[] = [
390
            'name' => get_lang('Categories'),
391
            'url' => $this->baseUrl.'action=list_categories',
392
        ];
393
        if ($category->getParentId() > 0) {
394
            $em = Database::getManager();
395
            $parentCategory = $em->find(PortfolioCategory::class, $category->getParentId());
396
            $pageTitle = $parentCategory->getTitle().' : '.get_lang('Sub-categories');
397
            $interbreadcrumb[] = [
398
                'name' => Security::remove_XSS($pageTitle),
399
                'url' => $this->baseUrl.'action=list_categories&parent_id='.$category->getParentId(),
400
            ];
401
        }
402
403
        $actions = [];
404
        $actions[] = Display::url(
405
            Display::getMdiIcon(ActionIcon::BACK, 'ch-tool-icon', null, ICON_SIZE_MEDIUM, get_lang('Back')),
406
            $this->baseUrl.'action=list_categories&parent_id='.$category->getParentId()
407
        );
408
409
        $content = $form->returnForm();
410
411
        $this->renderView($content, get_lang('Edit this category'), $actions);
412
    }
413
414
    /**
415
     * @throws \Doctrine\ORM\OptimisticLockException
416
     * @throws \Doctrine\ORM\Exception\ORMException
417
     */
418
    public function showHideCategory(PortfolioCategory $category): never
419
    {
420
        if (!$this->categoryBelongToOwner($category)) {
421
            api_not_allowed(true);
422
        }
423
424
        $category->setIsVisible(!$category->isVisible());
425
426
        $this->em->persist($category);
427
        $this->em->flush();
428
429
        Display::addFlash(
430
            Display::return_message(get_lang('Post visibility changed'), 'success')
431
        );
432
433
        header("Location: {$this->baseUrl}action=list_categories");
434
        exit;
435
    }
436
437
    /**
438
     * @throws \Doctrine\ORM\OptimisticLockException
439
     * @throws \Doctrine\ORM\Exception\ORMException
440
     */
441
    public function deleteCategory(PortfolioCategory $category): never
442
    {
443
        if (!api_is_platform_admin()) {
444
            api_not_allowed(true);
445
        }
446
447
        $this->em->remove($category);
448
        $this->em->flush();
449
450
        Display::addFlash(
451
            Display::return_message(get_lang('The category has been deleted.'), 'success')
452
        );
453
454
        header("Location: {$this->baseUrl}action=list_categories");
455
        exit;
456
    }
457
458
    /**
459
     * @throws \Exception
460
     */
461
    public function addItem(): void
462
    {
463
        global $interbreadcrumb;
464
465
        $this->blockIsNotAllowed();
466
467
        $templates = Container::getPortfolioRepository()->findTemplates(
468
            $this->owner,
469
            $this->course,
470
            $this->session
471
        );
472
473
        $form = new FormValidator('add_portfolio', 'post', $this->baseUrl.'action=add_item');
474
        $form->addSelectFromCollection(
475
            'template',
476
            [
477
                get_lang('Template'),
478
                null,
479
                '<span id="portfolio-spinner" class="fa fa-fw fa-spinner fa-spin" style="display: none;"
480
                    aria-hidden="true" aria-label="'.get_lang('Loading').'"></span>',
481
            ],
482
            $templates,
483
            [],
484
            true,
485
            'getTitle'
486
        );
487
488
        if ('true' === api_get_setting('editor.save_titles_as_html')) {
489
            $form->addHtmlEditor('title', get_lang('Title'), true, false, ['ToolbarSet' => 'TitleAsHtml']);
490
        } else {
491
            $form->addText('title', get_lang('Title'));
492
            $form->applyFilter('title', 'trim');
493
        }
494
        $editorConfig = [
495
            'ToolbarSet' => 'Documents',
496
            'Width' => '100%',
497
            'Height' => '400',
498
            'cols-size' => [2, 10, 0],
499
        ];
500
        $form->addHtmlEditor('content', get_lang('Content'), true, false, $editorConfig);
501
502
        $categoriesSelect = $form->addSelect(
503
            'category',
504
            [get_lang('Category'), get_lang('Categories are for organization only in personal portfolio.')]
505
        );
506
        $categoriesSelect->addOption(get_lang('Select a category'), 0);
507
        $parentCategories = $this->getCategoriesForIndex(0);
508
        foreach ($parentCategories as $parentCategory) {
509
            $categoriesSelect->addOption($this->translateDisplayName($parentCategory->getTitle()), $parentCategory->getId());
510
            $subCategories = $this->getCategoriesForIndex($parentCategory->getId());
511
            if (count($subCategories) > 0) {
512
                foreach ($subCategories as $subCategory) {
513
                    $categoriesSelect->addOption(' &mdash; '.$this->translateDisplayName($subCategory->getTitle()), $subCategory->getId());
514
                }
515
            }
516
        }
517
518
        $extraField = new ExtraField('portfolio');
519
        $extra = $extraField->addElements(
520
            $form,
521
            0,
522
            $this->course ? [] : ['tags']
523
        );
524
525
        $this->addAttachmentsFieldToForm($form);
526
527
        $form->addButtonCreate(get_lang('Create'));
528
529
        if ($form->validate()) {
530
            $values = $form->exportValues();
531
532
            $portfolio = new Portfolio();
533
            $portfolio
534
                ->setTitle($values['title'])
535
                ->setContent($values['content'])
536
                ->setCreator($this->owner)
537
                ->setParent($this->owner)
538
                ->addCourseLink($this->course, $this->session)
539
                ->setCategory(
540
                    $this->em->find(PortfolioCategory::class, $values['category'])
541
                )
542
            ;
543
544
            $this->em->persist($portfolio);
545
            $this->em->flush();
546
547
            $values['item_id'] = $portfolio->getId();
548
549
            $extraFieldValue = new ExtraFieldValue('portfolio');
550
            $extraFieldValue->saveFieldValues($values);
551
552
            $this->processAttachments(
553
                $form,
554
                $this->owner,
555
                $portfolio->getId(),
556
                Portfolio::TYPE_ITEM
557
            );
558
559
            Container::getEventDispatcher()->dispatch(
560
                new PortfolioItemAddedEvent(['portfolio' => $portfolio]),
561
                Events::PORTFOLIO_ITEM_ADDED
562
            );
563
564
            if (1 == api_get_course_setting('email_alert_teachers_new_post')) {
565
                if ($this->session) {
566
                    $messageCourseTitle = "{$this->course->getTitle()} ({$this->session->getTitle()})";
567
568
                    $teachers = SessionManager::getCoachesByCourseSession(
569
                        $this->session->getId(),
570
                        $this->course->getId()
571
                    );
572
                    $userIdListToSend = array_values($teachers);
573
                } else {
574
                    $messageCourseTitle = $this->course->getTitle();
575
576
                    $teachers = CourseManager::get_teacher_list_from_course_code($this->course->getCode());
577
578
                    $userIdListToSend = array_keys($teachers);
579
                }
580
581
                $messageSubject = sprintf(get_lang('[Portfolio] New post in course %s'), $messageCourseTitle);
582
                $messageContent = sprintf(
583
                    get_lang("There is a new post by %s in the portfolio of course %s. To view it <a href='%s'>go here</a>."),
584
                    $this->owner->getFullName(),
585
                    $messageCourseTitle,
586
                    $this->baseUrl.http_build_query(['action' => 'view', 'id' => $portfolio->getId()])
587
                );
588
                $messageContent .= '<br><br><dl>'
589
                    .'<dt>'.Security::remove_XSS($portfolio->getTitle()).'</dt>'
590
                    .'<dd>'.$portfolio->getExcerpt().'</dd>'.'</dl>';
591
592
                foreach ($userIdListToSend as $userIdToSend) {
593
                    MessageManager::send_message_simple(
594
                        $userIdToSend,
595
                        $messageSubject,
596
                        $messageContent,
597
                        0,
598
                        false,
599
                        false,
600
                        false
601
                    );
602
                }
603
            }
604
605
            Display::addFlash(
606
                Display::return_message(get_lang('Portfolio item added'), 'success')
607
            );
608
609
            header("Location: $this->baseUrl");
610
            exit;
611
        }
612
613
        $interbreadcrumb[] = [
614
            'name' => get_lang('Portfolio'),
615
            'url' => $this->baseUrl,
616
        ];
617
618
        $actions = [];
619
        $actions[] = Display::url(
620
            Display::getMdiIcon(ActionIcon::BACK, 'ch-tool-icon', null, ICON_SIZE_MEDIUM, get_lang('Back')),
621
            $this->baseUrl
622
        );
623
        $actions[] = '<a id="hide_bar_template" href="#" role="button">'.
624
            Display::getMdiIcon(ActionIcon::EXPAND, 'ch-tool-icon', null, ICON_SIZE_MEDIUM, get_lang('Expand')).
625
            Display::getMdiIcon(ActionIcon::COLLAPSE, 'ch-tool-icon', null, ICON_SIZE_MEDIUM, get_lang('Collapse')).'</a>';
626
627
        $js = '<script>
628
            $(function() {
629
                $(".scrollbar-light").scrollbar();
630
                $(".scroll-wrapper").css("height", "550px");
631
                expandColumnToogle("#hide_bar_template", {
632
                    selector: "#template_col",
633
                    width: 3
634
                }, {
635
                    selector: "#doc_form",
636
                    width: 9
637
                });
638
                CKEDITOR.on("instanceReady", function (e) {
639
                    showTemplates();
640
                });
641
                $(window).on("load", function () {
642
                    $("input[name=\'title\']").focus();
643
                });
644
                $(\'#add_portfolio_template\').on(\'change\', function () {
645
                    $(\'#portfolio-spinner\').show();
646
647
                    $.getJSON(_p.web_ajax + \'portfolio.ajax.php?a=find_template&item=\' + this.value)
648
                        .done(function(response) {
649
                            if (CKEDITOR.instances.title) {
650
                                CKEDITOR.instances.title.setData(response.title);
651
                            } else {
652
                                document.getElementById(\'add_portfolio_title\').value = response.title;
653
                            }
654
655
                            CKEDITOR.instances.content.setData(response.content);
656
                        })
657
                        .fail(function () {
658
                            if (CKEDITOR.instances.title) {
659
                                CKEDITOR.instances.title.setData(\'\');
660
                            } else {
661
                                document.getElementById(\'add_portfolio_title\').value = \'\';
662
                            }
663
664
                            CKEDITOR.instances.content.setData(\'\');
665
                        })
666
                        .always(function() {
667
                          $(\'#portfolio-spinner\').hide();
668
                        });
669
                });
670
                '.$extra['jquery_ready_content'].'
671
            });
672
        </script>';
673
        $content = '<div class="page-create">
674
            <div class="row" style="overflow:hidden">
675
            <div id="template_col" class="col-md-3">
676
                <div class="panel panel-default">
677
                <div class="panel-body">
678
                    <div id="frmModel" class="items-templates scrollbar-light"></div>
679
                </div>
680
                </div>
681
            </div>
682
            <div id="doc_form" class="col-md-9">
683
                '.$form->returnForm().'
684
            </div>
685
          </div></div>';
686
687
        $this->renderView(
688
            $content.$js,
689
            get_lang('Add item to portfolio'),
690
            $actions
691
        );
692
    }
693
694
    /**
695
     * @throws \Exception
696
     */
697
    public function editItem(Portfolio $item): void
698
    {
699
        global $interbreadcrumb;
700
701
        if (!api_is_allowed_to_edit() && !$this->itemBelongToOwner($item)) {
702
            api_not_allowed(true);
703
        }
704
705
        $itemCourse = $item->getCourse();
706
        $itemSession = $item->getSession();
707
708
        $form = new FormValidator('edit_portfolio', 'post', $this->baseUrl."action=edit_item&id={$item->getId()}");
709
710
        if ('true' === api_get_setting('editor.save_titles_as_html')) {
711
            $form->addHtmlEditor('title', get_lang('Title'), true, false, ['ToolbarSet' => 'TitleAsHtml']);
712
        } else {
713
            $form->addText('title', get_lang('Title'));
714
            $form->applyFilter('title', 'trim');
715
        }
716
717
        if ($item->getOrigin()) {
718
            if (Portfolio::TYPE_ITEM === $item->getOriginType()) {
719
                $origin = $this->em->find(Portfolio::class, $item->getOrigin());
720
721
                $form->addLabel(
722
                    sprintf(get_lang('Portfolio item by %s'), $origin->getUser()->getFullName()),
723
                    Display::panel(
724
                        Security::remove_XSS($origin->getContent())
725
                    )
726
                );
727
            } elseif (Portfolio::TYPE_COMMENT === $item->getOriginType()) {
728
                $origin = $this->em->find(PortfolioComment::class, $item->getOrigin());
729
730
                $form->addLabel(
731
                    sprintf(get_lang('Comment by %s'), $origin->getAuthor()->getFullName()),
732
                    Display::panel(
733
                        Security::remove_XSS($origin->getContent())
734
                    )
735
                );
736
            }
737
        }
738
        $editorConfig = [
739
            'ToolbarSet' => 'Documents',
740
            'Width' => '100%',
741
            'Height' => '400',
742
            'cols-size' => [2, 10, 0],
743
        ];
744
        $form->addHtmlEditor('content', get_lang('Content'), true, false, $editorConfig);
745
        $categoriesSelect = $form->addSelect(
746
            'category',
747
            [get_lang('Category'), get_lang('Categories are for organization only in personal portfolio.')]
748
        );
749
        $categoriesSelect->addOption(get_lang('Select a category'), 0);
750
        $parentCategories = $this->getCategoriesForIndex(0);
751
        foreach ($parentCategories as $parentCategory) {
752
            $categoriesSelect->addOption($this->translateDisplayName($parentCategory->getTitle()), $parentCategory->getId());
753
            $subCategories = $this->getCategoriesForIndex($parentCategory->getId());
754
            if (count($subCategories) > 0) {
755
                foreach ($subCategories as $subCategory) {
756
                    $categoriesSelect->addOption(' &mdash; '.$this->translateDisplayName($subCategory->getTitle()), $subCategory->getId());
757
                }
758
            }
759
        }
760
761
        $extraField = new ExtraField('portfolio');
762
        $extra = $extraField->addElements(
763
            $form,
764
            $item->getId(),
765
            $this->course ? [] : ['tags']
766
        );
767
768
        $attachmentList = $this->generateAttachmentList($item, false);
769
770
        if (!empty($attachmentList)) {
771
            $form->addLabel(get_lang('Attachments'), $attachmentList);
772
        }
773
774
        $this->addAttachmentsFieldToForm($form);
775
776
        $form->addButtonUpdate(get_lang('Update'));
777
        $form->setDefaults(
778
            [
779
                'title' => $item->getTitle(),
780
                'content' => $item->getContent(),
781
                'category' => $item->getCategory() ? $item->getCategory()->getId() : '',
782
            ]
783
        );
784
785
        if ($form->validate()) {
786
            if ($itemCourse) {
787
                api_item_property_update(
788
                    api_get_course_info($itemCourse->getCode()),
789
                    TOOL_PORTFOLIO,
790
                    $item->getId(),
791
                    'PortfolioUpdated',
792
                    api_get_user_id(),
793
                    [],
794
                    null,
795
                    '',
796
                    '',
797
                    $itemSession ? $itemSession->getId() : 0
798
                );
799
            }
800
801
            $values = $form->exportValues();
802
            $currentTime = new DateTime(api_get_utc_datetime(), new DateTimeZone('UTC'));
803
804
            $item
805
                ->setTitle($values['title'])
806
                ->setContent($values['content'])
807
                ->setUpdateDate($currentTime)
808
                ->setCategory(
809
                    $this->em->find('ChamiloCoreBundle:PortfolioCategory', $values['category'])
810
                );
811
812
            $values['item_id'] = $item->getId();
813
814
            $extraFieldValue = new ExtraFieldValue('portfolio');
815
            $extraFieldValue->saveFieldValues($values);
816
817
            $this->em->persist($item);
818
            $this->em->flush();
819
820
            Container::getEventDispatcher()->dispatch(
821
                new PortfolioItemEditedEvent(['portfolio' => $item]),
822
                Events::PORTFOLIO_ITEM_EDITED
823
            );
824
825
            $this->processAttachments(
826
                $form,
827
                $item->getUser(),
828
                $item->getId(),
829
                Portfolio::TYPE_ITEM
830
            );
831
832
            Display::addFlash(
833
                Display::return_message(get_lang('Item updated'), 'success')
834
            );
835
836
            header("Location: $this->baseUrl");
837
            exit;
838
        }
839
840
        $interbreadcrumb[] = [
841
            'name' => get_lang('Portfolio'),
842
            'url' => $this->baseUrl,
843
        ];
844
        $actions = [];
845
        $actions[] = Display::url(
846
            Display::getMdiIcon(ActionIcon::BACK, 'ch-tool-icon', null, ICON_SIZE_MEDIUM, get_lang('Back')),
847
            $this->baseUrl
848
        );
849
        $actions[] = '<a id="hide_bar_template" href="#" role="button">'.
850
            Display::getMdiIcon(ActionIcon::EXPAND, 'ch-tool-icon', null, ICON_SIZE_MEDIUM, get_lang('Expand')).
851
            Display::getMdiIcon(ActionIcon::COLLAPSE, 'ch-tool-icon', null, ICON_SIZE_MEDIUM, get_lang('Collapse')).'</a>';
852
853
        $js = '<script>
854
            $(function() {
855
                $(".scrollbar-light").scrollbar();
856
                $(".scroll-wrapper").css("height", "550px");
857
                expandColumnToogle("#hide_bar_template", {
858
                    selector: "#template_col",
859
                    width: 3
860
                }, {
861
                    selector: "#doc_form",
862
                    width: 9
863
                });
864
                CKEDITOR.on("instanceReady", function (e) {
865
                    showTemplates();
866
                });
867
                $(window).on("load", function () {
868
                    $("input[name=\'title\']").focus();
869
                });
870
                '.$extra['jquery_ready_content'].'
871
            });
872
        </script>';
873
        $content = '<div class="page-create">
874
            <div class="row" style="overflow:hidden">
875
            <div id="template_col" class="col-md-3">
876
                <div class="panel panel-default">
877
                <div class="panel-body">
878
                    <div id="frmModel" class="items-templates scrollbar-light"></div>
879
                </div>
880
                </div>
881
            </div>
882
            <div id="doc_form" class="col-md-9">
883
                '.$form->returnForm().'
884
            </div>
885
          </div></div>';
886
887
        $this->renderView(
888
            $content.$js,
889
            get_lang('Edit portfolio item'),
890
            $actions
891
        );
892
    }
893
894
    /**
895
     * @throws \Doctrine\ORM\ORMException
896
     * @throws \Doctrine\ORM\OptimisticLockException
897
     */
898
    public function showHideItem(Portfolio $item): never
899
    {
900
        if (!$this->itemBelongToOwner($item)) {
901
            api_not_allowed(true);
902
        }
903
904
        switch ($item->getVisibility()) {
905
            case Portfolio::VISIBILITY_HIDDEN:
906
                $item->setVisibility(Portfolio::VISIBILITY_VISIBLE);
907
                break;
908
            case Portfolio::VISIBILITY_VISIBLE:
909
                $item->setVisibility(Portfolio::VISIBILITY_HIDDEN_EXCEPT_TEACHER);
910
                break;
911
            case Portfolio::VISIBILITY_HIDDEN_EXCEPT_TEACHER:
912
            default:
913
                $item->setVisibility(Portfolio::VISIBILITY_HIDDEN);
914
                break;
915
        }
916
917
        $this->em->persist($item);
918
        $this->em->flush();
919
920
        Display::addFlash(
921
            Display::return_message(get_lang('The visibility has been changed.'), 'success')
922
        );
923
924
        header("Location: $this->baseUrl");
925
        exit;
926
    }
927
928
    /**
929
     * @throws \Doctrine\ORM\ORMException
930
     * @throws \Doctrine\ORM\OptimisticLockException
931
     */
932
    public function deleteItem(Portfolio $item)
933
    {
934
        if (!$this->itemBelongToOwner($item)) {
935
            api_not_allowed(true);
936
        }
937
938
        Container::getEventDispatcher()->dispatch(
939
            new PortfolioItemDeletedEvent(['portfolio' => $item]),
940
            Events::PORTFOLIO_ITEM_DELETED
941
        );
942
943
        $this->em->remove($item);
944
        $this->em->flush();
945
946
        Display::addFlash(
947
            Display::return_message(get_lang('Item deleted'), 'success')
948
        );
949
950
        header("Location: $this->baseUrl");
951
        exit;
952
    }
953
954
    /**
955
     * @throws \Exception
956
     */
957
    public function index(HttpRequest $httpRequest): void
958
    {
959
        $listByUser = false;
960
        $listHighlighted = $httpRequest->query->has('list_highlighted');
961
        $listAlphabetical = $httpRequest->query->has('list_alphabetical');
962
963
        if ($httpRequest->query->has('user')) {
964
            $this->owner = api_get_user_entity($httpRequest->query->getInt('user'));
965
966
            if (empty($this->owner)) {
967
                api_not_allowed(true);
968
            }
969
970
            $listByUser = true;
971
        }
972
973
        $actions = [];
974
975
        if (api_is_platform_admin()) {
976
            $actions[] = Display::url(
977
                Display::getMdiIcon(ActionIcon::ADD, 'ch-tool-icon', null, ICON_SIZE_MEDIUM, get_lang('Add')),
978
                $this->baseUrl.'action=add_item'
979
            );
980
            $actions[] = Display::url(
981
                Display::getMdiIcon(ActionIcon::CREATE_FOLDER, 'ch-tool-icon', null, ICON_SIZE_MEDIUM, get_lang('Add category')),
982
                $this->baseUrl.'action=list_categories'
983
            );
984
            $actions[] = Display::url(
985
                Display::getMdiIcon(ObjectIcon::WAITING_LIST, 'ch-tool-icon', null, ICON_SIZE_MEDIUM, get_lang('Portfolio details')),
986
                $this->baseUrl.'action=details'
987
            );
988
        } elseif (api_get_user_entity() === $this->owner) {
989
            if ($this->isAllowed()) {
990
                $actions[] = Display::url(
991
                    Display::getMdiIcon(ActionIcon::ADD, 'ch-tool-icon', null, ICON_SIZE_MEDIUM, get_lang('Add')),
992
                    $this->baseUrl.'action=add_item'
993
                );
994
                $actions[] = Display::url(
995
                    Display::getMdiIcon(ObjectIcon::WAITING_LIST, 'ch-tool-icon', null, ICON_SIZE_MEDIUM, get_lang('Portfolio details')),
996
                    $this->baseUrl.'action=details'
997
                );
998
            }
999
        } else {
1000
            $actions[] = Display::url(
1001
                Display::getMdiIcon(ActionIcon::BACK, 'ch-tool-icon', null, ICON_SIZE_MEDIUM, get_lang('Back')),
1002
                $this->baseUrl
1003
            );
1004
        }
1005
1006
        if (api_is_allowed_to_edit()) {
1007
            $actions[] = Display::url(
1008
                Display::getMdiIcon(ObjectIcon::TICKET, 'ch-tool-icon', null, ICON_SIZE_MEDIUM, get_lang('Tags')),
1009
                $this->baseUrl.'action=tags'
1010
            );
1011
        }
1012
1013
        $frmStudentList = null;
1014
        $frmTagList = null;
1015
1016
        $categories = [];
1017
        $portfolio = [];
1018
        if ($this->course) {
1019
            $frmTagList = $this->createFormTagFilter($listByUser);
1020
            $frmStudentList = $this->createFormStudentFilter($listByUser, $listHighlighted, $listAlphabetical);
1021
            $frmStudentList->setDefaults(['user' => $this->owner->getId()]);
1022
            // it translates the category title with the current user language
1023
            $categories = $this->getCategoriesForIndex(0);
1024
            if (count($categories) > 0) {
1025
                foreach ($categories as &$category) {
1026
                    $translated = $this->translateDisplayName($category->getTitle());
1027
                    $category->setTitle($translated);
1028
                }
1029
            }
1030
        } else {
1031
            // it displays the list in Network Social for the current user
1032
            $portfolio = $this->getCategoriesForIndex();
1033
        }
1034
1035
        $foundComments = [];
1036
1037
        if ($listHighlighted) {
1038
            $items = $this->getHighlightedItems();
1039
        } else {
1040
            $items = $this->getItemsForIndex($listByUser, $frmTagList, $listAlphabetical);
1041
1042
            $foundComments = $this->getCommentsForIndex($frmTagList);
1043
        }
1044
1045
        // it gets and translate the subcategories
1046
        $categoryId = $httpRequest->query->getInt('categoryId');
1047
        $subCategoryIdsReq = isset($_REQUEST['subCategoryIds']) ? Security::remove_XSS($_REQUEST['subCategoryIds']) : '';
1048
        $subCategoryIds = $subCategoryIdsReq;
1049
        if ('all' !== $subCategoryIdsReq) {
1050
            $subCategoryIds = !empty($subCategoryIdsReq) ? explode(',', $subCategoryIdsReq) : [];
1051
        }
1052
        $subcategories = [];
1053
        if ($categoryId > 0) {
1054
            $subcategories = $this->getCategoriesForIndex($categoryId);
1055
            if (count($subcategories) > 0) {
1056
                foreach ($subcategories as &$subcategory) {
1057
                    $translated = $this->translateDisplayName($subcategory->getTitle());
1058
                    $subcategory->setTitle($translated);
1059
                }
1060
            }
1061
        }
1062
1063
        $context = [
1064
            'user' => $this->owner,
1065
            'listByUser' => $listByUser,
1066
            'course' => $this->course,
1067
            'session' => $this->session,
1068
            'portfolio' => $portfolio,
1069
            'categories' => $categories,
1070
            'uncategorized_items' => $items,
1071
            'frm_student_list' => $this->course ? $frmStudentList->returnForm() : '',
1072
            'frm_tag_list' => $this->course ? $frmTagList->returnForm() : '',
1073
            'category_id' => $categoryId,
1074
            'subcategories' => $subcategories,
1075
            'subcategory_ids' => $subCategoryIds,
1076
            'found_comments' => $foundComments,
1077
            '_p' => Template::getLegacyP(),
1078
            '_c' => Template::getLegacyC(),
1079
        ];
1080
1081
        $js = '<script>
1082
            $(function() {
1083
                $(".category-filters").bind("click", function() {
1084
                    var categoryId = parseInt($(this).find("input[type=\'radio\']").val());
1085
                    $("input[name=\'categoryId\']").val(categoryId);
1086
                    $("input[name=\'subCategoryIds\']").val("all");
1087
                    $("#frm_tag_list_submit").trigger("click");
1088
                });
1089
                $(".subcategory-filters").bind("click", function() {
1090
                    var checkedVals = $(".subcategory-filters:checkbox:checked").map(function() {
1091
                        return this.value;
1092
                    }).get();
1093
                    $("input[name=\'subCategoryIds\']").val(checkedVals.join(","));
1094
                    $("#frm_tag_list_submit").trigger("click");
1095
                });
1096
            });
1097
        </script>';
1098
        $context['js_script'] = $js;
1099
1100
        $content = Container::getTwig()->render('@ChamiloCore/Portfolio/list.html.twig', $context);
1101
1102
        Display::addFlash(
1103
            Display::return_message(get_lang('Portfolio tool introduction'), 'info', false)
1104
        );
1105
1106
        $this->renderView($content, get_lang('Portfolio'), $actions);
1107
    }
1108
1109
    /**
1110
     * @throws \Doctrine\ORM\ORMException
1111
     * @throws \Doctrine\ORM\OptimisticLockException
1112
     * @throws \Doctrine\ORM\TransactionRequiredException
1113
     */
1114
    public function view(Portfolio $item, $urlUser)
1115
    {
1116
        global $interbreadcrumb;
1117
1118
        /** @var ResourceLinkRepository $resourceLinkRepo */
1119
        $resourceLinkRepo = Database::getManager()->getRepository(ResourceLink::class);
1120
1121
        $firstResourceLink = $item->getFirstResourceLink();
1122
1123
        if (!$this->itemBelongToOwner($item)) {
1124
            if ($this->advancedSharingEnabled) {
1125
                $userLink = $resourceLinkRepo->findLinkForResourceInContext(
1126
                    $item,
1127
                    $this->course,
1128
                    $this->session,
1129
                    null,
1130
                    null,
1131
                    $this->owner
1132
                );
1133
1134
                if ($item->getVisibility() === Portfolio::VISIBILITY_PER_USER && !$userLink) {
1135
                    api_not_allowed(true);
1136
                }
1137
            } elseif ($item->getVisibility() === Portfolio::VISIBILITY_HIDDEN
1138
                || ($item->getVisibility() === Portfolio::VISIBILITY_HIDDEN_EXCEPT_TEACHER && !api_is_allowed_to_edit())
1139
            ) {
1140
                api_not_allowed(true);
1141
            }
1142
        }
1143
1144
        Container::getEventDispatcher()->dispatch(
1145
            new PortfolioItemViewedEvent(['portfolio' => $item]),
1146
            Events::PORTFOLIO_ITEM_VIEWED
1147
        );
1148
1149
        $itemCourse = $firstResourceLink?->getCourse();
1150
        $itemSession = $firstResourceLink?->getSession();
1151
1152
        $form = $this->createCommentForm($item);
1153
1154
        $commentsRepo = Container::getPortfolioCommentRepository();
1155
1156
        $commentsQueryBuilder = $commentsRepo->getResources();
1157
        $commentsQueryBuilder->andWhere('resource.item = :item');
1158
1159
        if ($this->advancedSharingEnabled) {
1160
            // @todo change to left join with resource_link to get resources with advanced sharing
1161
            if ($itemCourse) {
1162
                $commentsQueryBuilder
1163
                    ->andWhere($commentsQueryBuilder->expr()->eq('links.course', ':course'))
1164
                    ->setParameter('course', $itemCourse->getId());
1165
                ;
1166
            }
1167
1168
            $commentsQueryBuilder
1169
                ->andWhere($commentsQueryBuilder->expr()->eq('links.user', ':current_user'))
1170
                ->andWhere(
1171
                    $commentsQueryBuilder->expr()->orX(
1172
                        $commentsQueryBuilder->expr()->eq('resource.visibility', PortfolioComment::VISIBILITY_PER_USER),
1173
                        $commentsQueryBuilder->expr()->andX(
1174
                            $commentsQueryBuilder->expr()->eq('resource.visibility', PortfolioComment::VISIBILITY_VISIBLE),
1175
                            $commentsQueryBuilder->expr()->eq('node.creator', ':current_user')
1176
                        )
1177
                    )
1178
                )
1179
                ->setParameter('current_user', $this->owner->getId())
1180
            ;
1181
        }
1182
1183
        if ('true' === api_get_setting('platform.portfolio_show_base_course_post_in_sessions')
1184
            && $this->session && !$itemSession && !$item->isDuplicatedInSession($this->session)
1185
        ) {
1186
            $comments = [];
1187
        } else {
1188
            $comments = $commentsQueryBuilder
1189
                ->orderBy('node.level', 'ASC')
1190
                ->setParameter('item', $item->getId())
1191
                ->getQuery()
1192
                ->getArrayResult()
1193
            ;
1194
        }
1195
1196
        $clockIcon = Display::returnFontAwesomeIcon('clock-o', '', true);
1197
1198
        $commentsHtml = '';
1199
1200
//        $commentsRepo->buildTree(
1201
//            $comments,
1202
//            [
1203
//                'decorate' => true,
1204
//                'rootOpen' => '<div class="media-list">',
1205
//                'rootClose' => '</div>',
1206
//                'childOpen' => function ($node) use ($commentsRepo) {
1207
//                    /** @var PortfolioComment $comment */
1208
//                    $comment = $commentsRepo->find($node['id']);
1209
//                    $author = $comment->getAuthor();
1210
//
1211
//                    $userPicture = UserManager::getUserPicture(
1212
//                        $comment->getAuthor()->getId(),
1213
//                        USER_IMAGE_SIZE_SMALL,
1214
//                        null,
1215
//                        [
1216
//                            'picture_uri' => $author->getPictureUri(),
1217
//                            'email' => $author->getEmail(),
1218
//                        ]
1219
//                    );
1220
//
1221
//                    return '<article class="media" id="comment-'.$node['id'].'">
1222
//                        <div class="media-left"><img class="media-object thumbnail" src="'.$userPicture.'" alt="'
1223
//                        .$author->getFullName().'"></div>
1224
//                        <div class="media-body">';
1225
//                },
1226
//                'childClose' => '</div></article>',
1227
//                'nodeDecorator' => function ($node) use ($commentsRepo, $clockIcon, $item) {
1228
//                    $commentActions = [];
1229
//                    /** @var PortfolioComment $comment */
1230
//                    $comment = $commentsRepo->find($node['id']);
1231
//
1232
//                    if ($this->commentBelongsToOwner($comment)) {
1233
//                        $commentActions[] = Display::url(
1234
//                            Display::getMdiIcon(
1235
//                                ActionIcon::FIX,
1236
//                                $item->isTemplate() ? 'ch-tool-icon' : 'ch-tool-icon-disabled',
1237
//                                null,
1238
//                                ICON_SIZE_MEDIUM,
1239
//                                $item->isTemplate() ? get_lang('Remove as template') : get_lang('Add as a template'),
1240
//                            ),
1241
//                            $this->baseUrl.http_build_query(['action' => 'template_comment', 'id' => $comment->getId()])
1242
//                        );
1243
//                    }
1244
//
1245
//                    $commentActions[] = Display::url(
1246
//                        Display::getMdiIcon(ActionIcon::COMMENT, 'ch-tool-icon', null, ICON_SIZE_MEDIUM, get_lang('Reply to this comment')),
1247
//                        '#',
1248
//                        [
1249
//                            'data-comment' => htmlspecialchars(
1250
//                                json_encode(['id' => $comment->getId()])
1251
//                            ),
1252
//                            'role' => 'button',
1253
//                            'class' => 'btn-reply-to',
1254
//                        ]
1255
//                    );
1256
//                    $commentActions[] = Display::url(
1257
//                        Display::getMdiIcon(ActionIcon::COPY_CONTENT, 'ch-tool-icon', null, ICON_SIZE_MEDIUM, get_lang('Copy to my portfolio')),
1258
//                        $this->baseUrl.http_build_query(
1259
//                            [
1260
//                                'action' => 'copy',
1261
//                                'copy' => 'comment',
1262
//                                'id' => $comment->getId(),
1263
//                            ]
1264
//                        )
1265
//                    );
1266
//
1267
//                    $isAllowedToEdit = api_is_allowed_to_edit();
1268
//
1269
//                    if ($isAllowedToEdit) {
1270
//                        $commentActions[] = Display::url(
1271
//                            Display::getMdiIcon(ActionIcon::COPY_CONTENT, 'ch-tool-icon', null, ICON_SIZE_MEDIUM, get_lang('Copy to student portfolio')),
1272
//                            $this->baseUrl.http_build_query(
1273
//                                [
1274
//                                    'action' => 'teacher_copy',
1275
//                                    'copy' => 'comment',
1276
//                                    'id' => $comment->getId(),
1277
//                                ]
1278
//                            )
1279
//                        );
1280
//
1281
//                        if ($comment->isImportant()) {
1282
//                            $commentActions[] = Display::url(
1283
//                                Display::getMdiIcon(ObjectIcon::PIN, 'ch-tool-icon', null, ICON_SIZE_MEDIUM, get_lang('Unmark comment as important')),
1284
//                                $this->baseUrl.http_build_query(
1285
//                                    [
1286
//                                        'action' => 'mark_important',
1287
//                                        'item' => $item->getId(),
1288
//                                        'id' => $comment->getId(),
1289
//                                    ]
1290
//                                )
1291
//                            );
1292
//                        } else {
1293
//                            $commentActions[] = Display::url(
1294
//                                Display::getMdiIcon(ObjectIcon::PIN, 'ch-tool-icon', null, ICON_SIZE_MEDIUM, get_lang('Mark comment as important')),
1295
//                                $this->baseUrl.http_build_query(
1296
//                                    [
1297
//                                        'action' => 'mark_important',
1298
//                                        'item' => $item->getId(),
1299
//                                        'id' => $comment->getId(),
1300
//                                    ]
1301
//                                )
1302
//                            );
1303
//                        }
1304
//
1305
//                        if ($this->course && '1' === api_get_course_setting('qualify_portfolio_comment')) {
1306
//                            $commentActions[] = Display::url(
1307
//                                Display::getMdiIcon(ObjectIcon::TEST, 'ch-tool-icon', null, ICON_SIZE_MEDIUM, get_lang('Grade this comment')),
1308
//                                $this->baseUrl.http_build_query(
1309
//                                    [
1310
//                                        'action' => 'qualify',
1311
//                                        'comment' => $comment->getId(),
1312
//                                    ]
1313
//                                )
1314
//                            );
1315
//                        }
1316
//                    }
1317
//
1318
//                    if ($this->commentBelongsToOwner($comment)) {
1319
//                        if ($this->advancedSharingEnabled) {
1320
//                            $commentActions[] = Display::url(
1321
//                                Display::getMdiIcon(ActionIcon::VISIBLE, 'ch-tool-icon', null, ICON_SIZE_MEDIUM, get_lang('Choose recipients')),
1322
//                                $this->baseUrl.http_build_query(['action' => 'comment_visiblity_choose', 'id' => $comment->getId()])
1323
//                            );
1324
//                        }
1325
//
1326
//                        $commentActions[] = Display::url(
1327
//                            Display::getMdiIcon(ActionIcon::EDIT, 'ch-tool-icon', null, ICON_SIZE_MEDIUM, get_lang('Edit')),
1328
//                            $this->baseUrl.http_build_query(['action' => 'edit_comment', 'id' => $comment->getId()])
1329
//                        );
1330
//                        $commentActions[] = Display::url(
1331
//                            Display::getMdiIcon(ActionIcon::DELETE, 'ch-tool-icon', null, ICON_SIZE_MEDIUM, get_lang('Delete')),
1332
//                            $this->baseUrl.http_build_query(['action' => 'delete_comment', 'id' => $comment->getId()])
1333
//                        );
1334
//                    }
1335
//
1336
//                    $nodeHtml = '<div class="pull-right">'.implode(PHP_EOL, $commentActions).'</div>'.PHP_EOL
1337
//                        .'<footer class="media-heading h4">'.PHP_EOL
1338
//                        .'<p>'.$comment->getAuthor()->getFullName().'</p>'.PHP_EOL;
1339
//
1340
//                    if ($comment->isImportant()
1341
//                        && ($this->itemBelongToOwner($comment->getItem()) || $isAllowedToEdit)
1342
//                    ) {
1343
//                        $nodeHtml .= '<span class="pull-right label label-warning origin-style">'
1344
//                            .get_lang('Portfolio item marked as important')
1345
//                            .'</span>'.PHP_EOL;
1346
//                    }
1347
//
1348
//                    $nodeHtml .= '<small>'.$clockIcon.PHP_EOL
1349
//                        .$this->getLabelForCommentDate($comment).'</small>'.PHP_EOL;
1350
//
1351
//                    $nodeHtml .= '</footer>'.PHP_EOL
1352
//                        .Security::remove_XSS($comment->getContent()).PHP_EOL;
1353
//
1354
//                    $nodeHtml .= $this->generateAttachmentList($comment);
1355
//
1356
//                    return $nodeHtml;
1357
//                },
1358
//            ]
1359
//        );
1360
1361
        $context = [];
1362
        $context['baseurl'] = $this->baseUrl;
1363
        $context['item'] = $item;
1364
        $context['course'] = $itemCourse;
1365
        $context['session'] = $itemSession;
1366
        $context['item_content'] = $this->generateItemContent($item);
1367
        $context['count_comments'] = count($comments);
1368
        $context['comments'] = $commentsHtml;
1369
        $context['form'] = $form;
1370
        $context['attachment_list'] = $this->generateAttachmentList($item);
1371
1372
        if ($itemCourse) {
1373
            $context['last_edit'] = [
1374
                'date' => $firstResourceLink->getUpdatedAt(),
1375
                'user' => $item->resourceNode->getCreator()->getFullName(),
1376
            ];
1377
1378
            /*$propertyInfo = api_get_item_property_info(
1379
                $itemCourse->getId(),
1380
                TOOL_PORTFOLIO,
1381
                $item->getId(),
1382
                $itemSession ? $itemSession->getId() : 0
1383
            );
1384
1385
            if ($propertyInfo && empty($propertyInfo['to_user_id'])) {
1386
                $context['last_edit'] = [
1387
                    'date' => $propertyInfo['lastedit_date'],
1388
                    'user' => api_get_user_entity($propertyInfo['lastedit_user_id'])->getFullName(),
1389
                ];
1390
            }*/
1391
        }
1392
1393
        $content = Container::getTwig()->render('@ChamiloCore/Portfolio/view.html.twig', $context);
1394
1395
        $interbreadcrumb[] = ['name' => get_lang('Portfolio'), 'url' => $this->baseUrl];
1396
1397
        $editLink = Display::url(
1398
            Display::getMdiIcon(ActionIcon::EDIT, 'ch-tool-icon', null, ICON_SIZE_MEDIUM, get_lang('Edit')),
1399
            $this->baseUrl.http_build_query(['action' => 'edit_item', 'id' => $item->getId()])
1400
        );
1401
1402
        $urlUserString = "";
1403
        if (!empty($urlUser)) {
1404
            $urlUserString = "user=".$urlUser;
1405
        }
1406
1407
        $actions = [];
1408
        $actions[] = Display::url(
1409
            Display::getMdiIcon(ActionIcon::BACK, 'ch-tool-icon', null, ICON_SIZE_MEDIUM, get_lang('Back')),
1410
            $this->baseUrl.$urlUserString
1411
        );
1412
1413
        if ($this->itemBelongToOwner($item)) {
1414
            $actions[] = $editLink;
1415
1416
            $actions[] = Display::url(
1417
                Display::getMdiIcon(
1418
                    ActionIcon::FIX,
1419
                    $item->isTemplate() ? 'ch-tool-icon' : 'ch-tool-icon-disabled',
1420
                    null,
1421
                    ICON_SIZE_MEDIUM,
1422
                    $item->isTemplate() ? get_lang('Remove template') : get_lang('Add as a template'),
1423
                ),
1424
                $this->baseUrl.http_build_query(['action' => 'template', 'id' => $item->getId()])
1425
            );
1426
1427
            if ($this->advancedSharingEnabled) {
1428
                $actions[] = Display::url(
1429
                    Display::getMdiIcon(ActionIcon::VISIBLE, 'ch-tool-icon', null, ICON_SIZE_MEDIUM, get_lang('Choose recipients')),
1430
                    $this->baseUrl.http_build_query(['action' => 'item_visiblity_choose', 'id' => $item->getId()])
1431
                );
1432
            } else {
1433
                $visibilityUrl = $this->baseUrl.http_build_query(['action' => 'visibility', 'id' => $item->getId()]);
1434
1435
                if ($item->getVisibility() === Portfolio::VISIBILITY_HIDDEN) {
1436
                    $actions[] = Display::url(
1437
                        Display::getMdiIcon(ActionIcon::INVISIBLE, 'ch-tool-icon', null, ICON_SIZE_MEDIUM, get_lang('Make visible')),
1438
                        $visibilityUrl
1439
                    );
1440
                } elseif ($item->getVisibility() === Portfolio::VISIBILITY_VISIBLE) {
1441
                    $actions[] = Display::url(
1442
                        Display::getMdiIcon(ActionIcon::VISIBLE, 'ch-tool-icon', null, ICON_SIZE_MEDIUM, get_lang('Make visible for teachers')),
1443
                        $visibilityUrl
1444
                    );
1445
                } elseif ($item->getVisibility() === Portfolio::VISIBILITY_HIDDEN_EXCEPT_TEACHER) {
1446
                    $actions[] = Display::url(
1447
                        Display::getMdiIcon(StateIcon::CLOSED_VISIBILITY, 'ch-tool-icon', null, ICON_SIZE_MEDIUM, get_lang('Make invisible')),
1448
                        $visibilityUrl
1449
                    );
1450
                }
1451
            }
1452
1453
            $actions[] = Display::url(
1454
                Display::getMdiIcon(ActionIcon::DELETE, 'ch-tool-icon', null, ICON_SIZE_MEDIUM, get_lang('Delete')),
1455
                $this->baseUrl.http_build_query(['action' => 'delete_item', 'id' => $item->getId()])
1456
            );
1457
        } else {
1458
            $actions[] = Display::url(
1459
                Display::getMdiIcon(ActionIcon::COPY_CONTENT, 'ch-tool-icon', null, ICON_SIZE_MEDIUM, get_lang('Copy to my portfolio')),
1460
                $this->baseUrl.http_build_query(['action' => 'copy', 'copy' => 'item', 'id' => $item->getId()])
1461
            );
1462
        }
1463
1464
        if (api_is_allowed_to_edit()) {
1465
            $actions[] = Display::url(
1466
                Display::getMdiIcon(ActionIcon::COPY_CONTENT, 'ch-tool-icon', null, ICON_SIZE_MEDIUM, get_lang('Copy to student portfolio')),
1467
                $this->baseUrl.http_build_query(['action' => 'teacher_copy', 'copy' => 'item', 'id' => $item->getId()])
1468
            );
1469
            $actions[] = $editLink;
1470
1471
            $highlightedUrl = $this->baseUrl.http_build_query(['action' => 'highlighted', 'id' => $item->getId()]);
1472
1473
            if ($item->isHighlighted()) {
1474
                $actions[] = Display::url(
1475
                    Display::getMdiIcon(ActionIcon::AWARD, 'ch-tool-icon', null, ICON_SIZE_MEDIUM, get_lang('Unmark as highlighted')),
1476
                    $highlightedUrl
1477
                );
1478
            } else {
1479
                $actions[] = Display::url(
1480
                    Display::getMdiIcon(ActionIcon::AWARD, 'ch-tool-icon-disabled', null, ICON_SIZE_MEDIUM, get_lang('Mark as highlighted')),
1481
                    $highlightedUrl
1482
                );
1483
            }
1484
1485
            if ($itemCourse && '1' === api_get_course_setting('qualify_portfolio_item')) {
1486
                $actions[] = Display::url(
1487
                    Display::getMdiIcon(ObjectIcon::TEST, 'ch-tool-icon', null, ICON_SIZE_MEDIUM, get_lang('Grade this item')),
1488
                    $this->baseUrl.http_build_query(['action' => 'qualify', 'item' => $item->getId()])
1489
                );
1490
            }
1491
        }
1492
1493
        $this->renderView($content, $item->getTitle(true), $actions, false);
1494
    }
1495
1496
    /**
1497
     * @throws \Doctrine\ORM\ORMException
1498
     * @throws \Doctrine\ORM\OptimisticLockException
1499
     */
1500
    public function copyItem(Portfolio $originItem)
1501
    {
1502
        $this->blockIsNotAllowed();
1503
1504
        $currentTime = api_get_utc_datetime(null, false, true);
1505
1506
        $portfolio = new Portfolio();
1507
        $portfolio
1508
            ->setVisibility(Portfolio::VISIBILITY_HIDDEN_EXCEPT_TEACHER)
1509
            ->setTitle(
1510
                sprintf(get_lang('Portfolio item by %s'), $originItem->getUser()->getFullName())
1511
            )
1512
            ->setContent('')
1513
            ->setUser($this->owner)
1514
            ->setOrigin($originItem->getId())
1515
            ->setOriginType(Portfolio::TYPE_ITEM)
1516
            ->setCourse($this->course)
1517
            ->setSession($this->session)
1518
            ->setCreationDate($currentTime)
1519
            ->setUpdateDate($currentTime);
1520
1521
        $this->em->persist($portfolio);
1522
        $this->em->flush();
1523
1524
        Display::addFlash(
1525
            Display::return_message(get_lang('Portfolio item added'), 'success')
1526
        );
1527
1528
        header("Location: $this->baseUrl".http_build_query(['action' => 'edit_item', 'id' => $portfolio->getId()]));
1529
        exit;
1530
    }
1531
1532
    /**
1533
     * @throws \Doctrine\ORM\ORMException
1534
     * @throws \Doctrine\ORM\OptimisticLockException
1535
     */
1536
    public function copyComment(PortfolioComment $originComment)
1537
    {
1538
        $currentTime = api_get_utc_datetime(null, false, true);
1539
1540
        $portfolio = new Portfolio();
1541
        $portfolio
1542
            ->setVisibility(Portfolio::VISIBILITY_HIDDEN_EXCEPT_TEACHER)
1543
            ->setTitle(
1544
                sprintf(get_lang('Comment by %s'), $originComment->getAuthor()->getFullName())
1545
            )
1546
            ->setContent('')
1547
            ->setUser($this->owner)
1548
            ->setOrigin($originComment->getId())
1549
            ->setOriginType(Portfolio::TYPE_COMMENT)
1550
            ->setCourse($this->course)
1551
            ->setSession($this->session)
1552
            ->setCreationDate($currentTime)
1553
            ->setUpdateDate($currentTime);
1554
1555
        $this->em->persist($portfolio);
1556
        $this->em->flush();
1557
1558
        Display::addFlash(
1559
            Display::return_message(get_lang('Portfolio item added'), 'success')
1560
        );
1561
1562
        header("Location: $this->baseUrl".http_build_query(['action' => 'edit_item', 'id' => $portfolio->getId()]));
1563
        exit;
1564
    }
1565
1566
    /**
1567
     * @throws \Doctrine\ORM\ORMException
1568
     * @throws \Doctrine\ORM\OptimisticLockException
1569
     * @throws \Exception
1570
     */
1571
    public function teacherCopyItem(Portfolio $originItem)
1572
    {
1573
        api_protect_teacher_script();
1574
1575
        $actionParams = http_build_query(['action' => 'teacher_copy', 'copy' => 'item', 'id' => $originItem->getId()]);
1576
1577
        $form = new FormValidator('teacher_copy_portfolio', 'post', $this->baseUrl.$actionParams);
1578
1579
        if ('true' === api_get_setting('editor.save_titles_as_html')) {
1580
            $form->addHtmlEditor('title', get_lang('Title'), true, false, ['ToolbarSet' => 'TitleAsHtml']);
1581
        } else {
1582
            $form->addText('title', get_lang('Title'));
1583
            $form->applyFilter('title', 'trim');
1584
        }
1585
1586
        $form->addLabel(
1587
            sprintf(get_lang('"Portfolio item by %s"'), $originItem->getUser()->getFullName()),
1588
            Display::panel(
1589
                Security::remove_XSS($originItem->getContent())
1590
            )
1591
        );
1592
        $form->addHtmlEditor('content', get_lang('Content'), true, false, ['ToolbarSet' => 'NotebookStudent']);
1593
1594
        $urlParams = http_build_query(
1595
            [
1596
                'a' => 'search_user_by_course',
1597
                'course_id' => $this->course->getId(),
1598
                'session_id' => $this->session ? $this->session->getId() : 0,
1599
            ]
1600
        );
1601
        $form->addSelectAjax(
1602
            'students',
1603
            get_lang('Learners'),
1604
            [],
1605
            [
1606
                'url' => api_get_path(WEB_AJAX_PATH)."course.ajax.php?$urlParams",
1607
                'multiple' => true,
1608
            ]
1609
        );
1610
        $form->addRule('students', get_lang('Required field'), 'required');
1611
        $form->addButtonCreate(get_lang('Save'));
1612
1613
        $toolName = get_lang('Copy to student portfolio');
1614
        $content = $form->returnForm();
1615
1616
        if ($form->validate()) {
1617
            $values = $form->exportValues();
1618
1619
            $currentTime = api_get_utc_datetime(null, false, true);
1620
1621
            foreach ($values['students'] as $studentId) {
1622
                $owner = api_get_user_entity($studentId);
1623
1624
                $portfolio = new Portfolio();
1625
                $portfolio
1626
                    ->setVisibility(Portfolio::VISIBILITY_HIDDEN_EXCEPT_TEACHER)
1627
                    ->setTitle($values['title'])
1628
                    ->setContent($values['content'])
1629
                    ->setUser($owner)
1630
                    ->setOrigin($originItem->getId())
1631
                    ->setOriginType(Portfolio::TYPE_ITEM)
1632
                    ->setCourse($this->course)
1633
                    ->setSession($this->session)
1634
                    ->setCreationDate($currentTime)
1635
                    ->setUpdateDate($currentTime);
1636
1637
                $this->em->persist($portfolio);
1638
            }
1639
1640
            $this->em->flush();
1641
1642
            Display::addFlash(
1643
                Display::return_message(get_lang('Item added to students own portfolio'), 'success')
1644
            );
1645
1646
            header("Location: $this->baseUrl");
1647
            exit;
1648
        }
1649
1650
        $this->renderView($content, $toolName);
1651
    }
1652
1653
    /**
1654
     * @throws \Doctrine\ORM\ORMException
1655
     * @throws \Doctrine\ORM\OptimisticLockException
1656
     * @throws \Exception
1657
     */
1658
    public function teacherCopyComment(PortfolioComment $originComment)
1659
    {
1660
        $actionParams = http_build_query(
1661
            [
1662
                'action' => 'teacher_copy',
1663
                'copy' => 'comment',
1664
                'id' => $originComment->getId(),
1665
            ]
1666
        );
1667
1668
        $form = new FormValidator('teacher_copy_portfolio', 'post', $this->baseUrl.$actionParams);
1669
1670
        if ('true' === api_get_setting('editor.save_titles_as_html')) {
1671
            $form->addHtmlEditor('title', get_lang('Title'), true, false, ['ToolbarSet' => 'TitleAsHtml']);
1672
        } else {
1673
            $form->addText('title', get_lang('Title'));
1674
            $form->applyFilter('title', 'trim');
1675
        }
1676
1677
        $form->addLabel(
1678
            sprintf(get_lang('Comment from %s'), $originComment->getAuthor()->getFullName()),
1679
            Display::panel(
1680
                Security::remove_XSS($originComment->getContent())
1681
            )
1682
        );
1683
        $form->addHtmlEditor('content', get_lang('Content'), true, false, ['ToolbarSet' => 'NotebookStudent']);
1684
1685
        $urlParams = http_build_query(
1686
            [
1687
                'a' => 'search_user_by_course',
1688
                'course_id' => $this->course->getId(),
1689
                'session_id' => $this->session ? $this->session->getId() : 0,
1690
            ]
1691
        );
1692
        $form->addSelectAjax(
1693
            'students',
1694
            get_lang('Learners'),
1695
            [],
1696
            [
1697
                'url' => api_get_path(WEB_AJAX_PATH)."course.ajax.php?$urlParams",
1698
                'multiple' => true,
1699
            ]
1700
        );
1701
        $form->addRule('students', get_lang('Required field'), 'required');
1702
        $form->addButtonCreate(get_lang('Save'));
1703
1704
        $toolName = get_lang('Copy to student portfolio');
1705
        $content = $form->returnForm();
1706
1707
        if ($form->validate()) {
1708
            $values = $form->exportValues();
1709
1710
            $currentTime = api_get_utc_datetime(null, false, true);
1711
1712
            foreach ($values['students'] as $studentId) {
1713
                $owner = api_get_user_entity($studentId);
1714
1715
                $portfolio = new Portfolio();
1716
                $portfolio
1717
                    ->setVisibility(Portfolio::VISIBILITY_HIDDEN_EXCEPT_TEACHER)
1718
                    ->setTitle($values['title'])
1719
                    ->setContent($values['content'])
1720
                    ->setUser($owner)
1721
                    ->setOrigin($originComment->getId())
1722
                    ->setOriginType(Portfolio::TYPE_COMMENT)
1723
                    ->setCourse($this->course)
1724
                    ->setSession($this->session)
1725
                    ->setCreationDate($currentTime)
1726
                    ->setUpdateDate($currentTime);
1727
1728
                $this->em->persist($portfolio);
1729
            }
1730
1731
            $this->em->flush();
1732
1733
            Display::addFlash(
1734
                Display::return_message(get_lang('Item added to students own portfolio'), 'success')
1735
            );
1736
1737
            header("Location: $this->baseUrl");
1738
            exit;
1739
        }
1740
1741
        $this->renderView($content, $toolName);
1742
    }
1743
1744
    /**
1745
     * @throws \Doctrine\ORM\ORMException
1746
     * @throws \Doctrine\ORM\OptimisticLockException
1747
     */
1748
    public function markImportantCommentInItem(Portfolio $item, PortfolioComment $comment)
1749
    {
1750
        if ($comment->getItem()->getId() !== $item->getId()) {
1751
            api_not_allowed(true);
1752
        }
1753
1754
        $comment->setIsImportant(
1755
            !$comment->isImportant()
1756
        );
1757
1758
        $this->em->persist($comment);
1759
        $this->em->flush();
1760
1761
        Display::addFlash(
1762
            Display::return_message(get_lang('Portfolio item marked as important'), 'success')
1763
        );
1764
1765
        header("Location: $this->baseUrl".http_build_query(['action' => 'view', 'id' => $item->getId()]));
1766
        exit;
1767
    }
1768
1769
    /**
1770
     * @throws \Exception
1771
     */
1772
    public function details(HttpRequest $httpRequest)
1773
    {
1774
        $this->blockIsNotAllowed();
1775
1776
        $currentUserId = api_get_user_id();
1777
        $isAllowedToFilterStudent = $this->course && api_is_allowed_to_edit();
1778
1779
        $actions = [];
1780
        $actions[] = Display::url(
1781
            Display::getMdiIcon(ActionIcon::BACK, 'ch-tool-icon', null, ICON_SIZE_MEDIUM, get_lang('Back')),
1782
            $this->baseUrl
1783
        );
1784
        $actions[] = Display::url(
1785
            Display::getMdiIcon(ObjectIcon::PDF, 'ch-tool-icon', null, ICON_SIZE_MEDIUM, get_lang('Export my portfolio data in a PDF file')),
1786
            $this->baseUrl.http_build_query(['action' => 'export_pdf'])
1787
        );
1788
        $actions[] = Display::url(
1789
            Display::getMdiIcon(ActionIcon::EXPORT_ARCHIVE, 'ch-tool-icon', null, ICON_SIZE_MEDIUM, get_lang('Export my portfolio data in a ZIP file')),
1790
            $this->baseUrl.http_build_query(['action' => 'export_zip'])
1791
        );
1792
1793
        $frmStudent = null;
1794
1795
        if ($isAllowedToFilterStudent) {
1796
            if ($httpRequest->query->has('user')) {
1797
                $this->owner = api_get_user_entity($httpRequest->query->getInt('user'));
1798
1799
                if (empty($this->owner)) {
1800
                    api_not_allowed(true);
1801
                }
1802
1803
                $actions[1] = Display::url(
1804
                    Display::getMdiIcon(ObjectIcon::PDF, 'ch-tool-icon', null, ICON_SIZE_MEDIUM, get_lang('Export my portfolio data in a PDF file')),
1805
                    $this->baseUrl.http_build_query(['action' => 'export_pdf', 'user' => $this->owner->getId()])
1806
                );
1807
                $actions[2] = Display::url(
1808
                    Display::getMdiIcon(ActionIcon::EXPORT_ARCHIVE, 'ch-tool-icon', null, ICON_SIZE_MEDIUM, get_lang('Export my portfolio data in a ZIP file')),
1809
                    $this->baseUrl.http_build_query(['action' => 'export_zip', 'user' => $this->owner->getId()])
1810
                );
1811
            }
1812
1813
            $frmStudent = new FormValidator('frm_student_list', 'get');
1814
1815
            $urlParams = http_build_query(
1816
                [
1817
                    'a' => 'search_user_by_course',
1818
                    'course_id' => $this->course->getId(),
1819
                    'session_id' => $this->session ? $this->session->getId() : 0,
1820
                ]
1821
            );
1822
1823
            $frmStudent
1824
                ->addSelectAjax(
1825
                    'user',
1826
                    get_lang('Select a learner portfolio'),
1827
                    [],
1828
                    [
1829
                        'url' => api_get_path(WEB_AJAX_PATH)."course.ajax.php?$urlParams",
1830
                        'placeholder' => get_lang('Search users'),
1831
                        'formatResult' => SelectAjax::templateResultForUsersInCourse(),
1832
                        'formatSelection' => SelectAjax::templateSelectionForUsersInCourse(),
1833
                    ]
1834
                )
1835
                ->addOption(
1836
                    $this->owner->getFullName(),
1837
                    $this->owner->getId(),
1838
                    [
1839
                        'data-avatarurl' => UserManager::getUserPicture($this->owner->getId()),
1840
                        'data-username' => $this->owner->getUsername(),
1841
                    ]
1842
                )
1843
            ;
1844
            $frmStudent->setDefaults(['user' => $this->owner->getId()]);
1845
            $frmStudent->addHidden('action', 'details');
1846
            $frmStudent->addHidden('cid', $this->course->getId());
1847
            $frmStudent->addHidden('sid', $this->session ? $this->session->getId() : 0);
1848
            $frmStudent->addButtonFilter(get_lang('Filter'));
1849
        }
1850
1851
        $itemsRepo = Container::getPortfolioRepository();
1852
        $commentsRepo = $this->em->getRepository(PortfolioComment::class);
1853
1854
        $getItemsTotalNumber = function () use ($itemsRepo, $isAllowedToFilterStudent, $currentUserId) {
1855
            $qb = $itemsRepo->createQueryBuilder('i');
1856
            $qb
1857
                ->select('COUNT(i)')
1858
                ->where('i.user = :user')
1859
                ->setParameter('user', $this->owner);
1860
1861
            if ($this->course) {
1862
                $qb
1863
                    ->andWhere('i.course = :course')
1864
                    ->setParameter('course', $this->course);
1865
1866
                if ($this->session) {
1867
                    $qb
1868
                        ->andWhere('i.session = :session')
1869
                        ->setParameter('session', $this->session);
1870
                } else {
1871
                    $qb->andWhere('i.session IS NULL');
1872
                }
1873
            }
1874
1875
            if ($isAllowedToFilterStudent && $currentUserId !== $this->owner->getId()) {
1876
                $visibilityCriteria = [
1877
                    Portfolio::VISIBILITY_VISIBLE,
1878
                    Portfolio::VISIBILITY_HIDDEN_EXCEPT_TEACHER,
1879
                ];
1880
1881
                $qb->andWhere(
1882
                    $qb->expr()->in('i.visibility', $visibilityCriteria)
1883
                );
1884
            }
1885
1886
            return $qb->getQuery()->getSingleScalarResult();
1887
        };
1888
        $getItemsData = function ($from, $limit, $columnNo, $orderDirection) use ($itemsRepo, $isAllowedToFilterStudent, $currentUserId) {
1889
            $qb = $itemsRepo->createQueryBuilder('item')
1890
                ->where('item.user = :user')
1891
                ->leftJoin('item.category', 'category')
1892
                ->leftJoin('item.course', 'course')
1893
                ->leftJoin('item.session', 'session')
1894
                ->setParameter('user', $this->owner);
1895
1896
            if ($this->course) {
1897
                $qb
1898
                    ->andWhere('item.course = :course_id')
1899
                    ->setParameter('course_id', $this->course);
1900
1901
                if ($this->session) {
1902
                    $qb
1903
                        ->andWhere('item.session = :session')
1904
                        ->setParameter('session', $this->session);
1905
                } else {
1906
                    $qb->andWhere('item.session IS NULL');
1907
                }
1908
            }
1909
1910
            if ($isAllowedToFilterStudent && $currentUserId !== $this->owner->getId()) {
1911
                $visibilityCriteria = [
1912
                    Portfolio::VISIBILITY_VISIBLE,
1913
                    Portfolio::VISIBILITY_HIDDEN_EXCEPT_TEACHER,
1914
                ];
1915
1916
                $qb->andWhere(
1917
                    $qb->expr()->in('item.visibility', $visibilityCriteria)
1918
                );
1919
            }
1920
1921
            if (0 == $columnNo) {
1922
                $qb->orderBy('item.title', $orderDirection);
1923
            } elseif (1 == $columnNo) {
1924
                $qb->orderBy('item.creationDate', $orderDirection);
1925
            } elseif (2 == $columnNo) {
1926
                $qb->orderBy('item.updateDate', $orderDirection);
1927
            } elseif (3 == $columnNo) {
1928
                $qb->orderBy('category.title', $orderDirection);
1929
            } elseif (5 == $columnNo) {
1930
                $qb->orderBy('item.score', $orderDirection);
1931
            } elseif (6 == $columnNo) {
1932
                $qb->orderBy('course.title', $orderDirection);
1933
            } elseif (7 == $columnNo) {
1934
                $qb->orderBy('session.name', $orderDirection);
1935
            }
1936
1937
            $qb->setFirstResult($from)->setMaxResults($limit);
1938
1939
            return array_map(
1940
                function (Portfolio $item) {
1941
                    $category = $item->getCategory();
1942
1943
                    $row = [];
1944
                    $row[] = $item;
1945
                    $row[] = $item->getCreationDate();
1946
                    $row[] = $item->getUpdateDate();
1947
                    $row[] = $category ? $item->getCategory()->getTitle() : null;
1948
                    $row[] = $item->getComments()->count();
1949
                    $row[] = $item->getScore();
1950
1951
                    if (!$this->course) {
1952
                        $row[] = $item->getCourse();
1953
                        $row[] = $item->getSession();
1954
                    }
1955
1956
                    return $row;
1957
                },
1958
                $qb->getQuery()->getResult()
1959
            );
1960
        };
1961
1962
        $portfolioItemColumnFilter = function (Portfolio $item) {
1963
            return Display::url(
1964
                $item->getTitle(true),
1965
                $this->baseUrl.http_build_query(['action' => 'view', 'id' => $item->getId()])
1966
            );
1967
        };
1968
        $convertFormatDateColumnFilter = function (DateTime $date) {
1969
            return api_convert_and_format_date($date);
1970
        };
1971
1972
        $tblItems = new SortableTable('tbl_items', $getItemsTotalNumber, $getItemsData, 1, 20, 'DESC');
1973
        $tblItems->set_additional_parameters(['action' => 'details', 'user' => $this->owner->getId()]);
1974
        $tblItems->set_header(0, get_lang('Title'));
1975
        $tblItems->set_column_filter(0, $portfolioItemColumnFilter);
1976
        $tblItems->set_header(1, get_lang('Creation date'), true, [], ['class' => 'text-center']);
1977
        $tblItems->set_column_filter(1, $convertFormatDateColumnFilter);
1978
        $tblItems->set_header(2, get_lang('Last update'), true, [], ['class' => 'text-center']);
1979
        $tblItems->set_column_filter(2, $convertFormatDateColumnFilter);
1980
        $tblItems->set_header(3, get_lang('Category'));
1981
        $tblItems->set_header(4, get_lang('Comments'), false, [], ['class' => 'text-right']);
1982
        $tblItems->set_header(5, get_lang('Score'), true, [], ['class' => 'text-right']);
1983
1984
        if (!$this->course) {
1985
            $tblItems->set_header(6, get_lang('Course'));
1986
            $tblItems->set_header(7, get_lang('Session'));
1987
        }
1988
1989
        $getCommentsTotalNumber = function () use ($commentsRepo) {
1990
            $qb = $commentsRepo->createQueryBuilder('c');
1991
            $qb
1992
                ->select('COUNT(c)')
1993
                ->where('c.author = :author')
1994
                ->setParameter('author', $this->owner);
1995
1996
            if ($this->course) {
1997
                $qb
1998
                    ->innerJoin('c.item', 'i')
1999
                    ->andWhere('i.course = :course')
2000
                    ->setParameter('course', $this->course);
2001
2002
                if ($this->session) {
2003
                    $qb
2004
                        ->andWhere('i.session = :session')
2005
                        ->setParameter('session', $this->session);
2006
                } else {
2007
                    $qb->andWhere('i.session IS NULL');
2008
                }
2009
            }
2010
2011
            return $qb->getQuery()->getSingleScalarResult();
2012
        };
2013
        $getCommentsData = function ($from, $limit, $columnNo, $orderDirection) use ($commentsRepo) {
2014
            $qb = $commentsRepo->createQueryBuilder('comment');
2015
            $qb
2016
                ->where('comment.author = :user')
2017
                ->innerJoin('comment.item', 'item')
2018
                ->setParameter('user', $this->owner);
2019
2020
            if ($this->course) {
2021
                $qb
2022
                    ->innerJoin('comment.item', 'i')
2023
                    ->andWhere('item.course = :course')
2024
                    ->setParameter('course', $this->course);
2025
2026
                if ($this->session) {
2027
                    $qb
2028
                        ->andWhere('item.session = :session')
2029
                        ->setParameter('session', $this->session);
2030
                } else {
2031
                    $qb->andWhere('item.session IS NULL');
2032
                }
2033
            }
2034
2035
            if (0 == $columnNo) {
2036
                $qb->orderBy('comment.content', $orderDirection);
2037
            } elseif (1 == $columnNo) {
2038
                $qb->orderBy('comment.date', $orderDirection);
2039
            } elseif (2 == $columnNo) {
2040
                $qb->orderBy('item.title', $orderDirection);
2041
            } elseif (3 == $columnNo) {
2042
                $qb->orderBy('comment.score', $orderDirection);
2043
            }
2044
2045
            $qb->setFirstResult($from)->setMaxResults($limit);
2046
2047
            return array_map(
2048
                function (PortfolioComment $comment) {
2049
                    return [
2050
                        $comment,
2051
                        $comment->getDate(),
2052
                        $comment->getItem(),
2053
                        $comment->getScore(),
2054
                    ];
2055
                },
2056
                $qb->getQuery()->getResult()
2057
            );
2058
        };
2059
2060
        $tblComments = new SortableTable('tbl_comments', $getCommentsTotalNumber, $getCommentsData, 1, 20, 'DESC');
2061
        $tblComments->set_additional_parameters(['action' => 'details', 'user' => $this->owner->getId()]);
2062
        $tblComments->set_header(0, get_lang('Resume'));
2063
        $tblComments->set_column_filter(
2064
            0,
2065
            function (PortfolioComment $comment) {
2066
                return Display::url(
2067
                    $comment->getExcerpt(),
2068
                    $this->baseUrl.http_build_query(['action' => 'view', 'id' => $comment->getItem()->getId()])
2069
                    .'#comment-'.$comment->getId()
2070
                );
2071
            }
2072
        );
2073
        $tblComments->set_header(1, get_lang('Date'), true, [], ['class' => 'text-center']);
2074
        $tblComments->set_column_filter(1, $convertFormatDateColumnFilter);
2075
        $tblComments->set_header(2, get_lang('Item title'));
2076
        $tblComments->set_column_filter(2, $portfolioItemColumnFilter);
2077
        $tblComments->set_header(3, get_lang('Score'), true, [], ['class' => 'text-right']);
2078
2079
        $content = '';
2080
2081
        if ($frmStudent) {
2082
            $content .= $frmStudent->returnForm();
2083
        }
2084
2085
        $totalNumberOfItems = $tblItems->get_total_number_of_items();
2086
        $totalNumberOfComments = $tblComments->get_total_number_of_items();
2087
        $requiredNumberOfItems = (int) api_get_course_setting('portfolio_number_items');
2088
        $requiredNumberOfComments = (int) api_get_course_setting('portfolio_number_comments');
2089
2090
        $itemsSubtitle = '';
2091
2092
        if ($requiredNumberOfItems > 0) {
2093
            $itemsSubtitle = sprintf(
2094
                get_lang('%d added / %d required'),
2095
                $totalNumberOfItems,
2096
                $requiredNumberOfItems
2097
            );
2098
        }
2099
2100
        $content .= Display::page_subheader2(
2101
            get_lang('Portfolio items'),
2102
            $itemsSubtitle
2103
        ).PHP_EOL;
2104
2105
        if ($totalNumberOfItems > 0) {
2106
            $content .= $tblItems->return_table().PHP_EOL;
2107
        } else {
2108
            $content .= Display::return_message(get_lang('No items in your portfolio'), 'warning');
2109
        }
2110
2111
        $commentsSubtitle = '';
2112
2113
        if ($requiredNumberOfComments > 0) {
2114
            $commentsSubtitle = sprintf(
2115
                get_lang('%d added / %d required'),
2116
                $totalNumberOfComments,
2117
                $requiredNumberOfComments
2118
            );
2119
        }
2120
2121
        $content .= Display::page_subheader2(
2122
            get_lang('Comments made'),
2123
            $commentsSubtitle
2124
        ).PHP_EOL;
2125
2126
        if ($totalNumberOfComments > 0) {
2127
            $content .= $tblComments->return_table().PHP_EOL;
2128
        } else {
2129
            $content .= Display::return_message(get_lang('You have not commented'), 'warning');
2130
        }
2131
2132
        $this->renderView($content, get_lang('Portfolio details'), $actions);
2133
    }
2134
2135
    /**
2136
     * @throws MpdfException
2137
     */
2138
    public function exportPdf(HttpRequest $httpRequest)
2139
    {
2140
        $currentUserId = api_get_user_id();
2141
        $isAllowedToFilterStudent = $this->course && api_is_allowed_to_edit();
2142
2143
        if ($isAllowedToFilterStudent) {
2144
            if ($httpRequest->query->has('user')) {
2145
                $this->owner = api_get_user_entity($httpRequest->query->getInt('user'));
2146
2147
                if (empty($this->owner)) {
2148
                    api_not_allowed(true);
2149
                }
2150
            }
2151
        }
2152
2153
        $pdfContent = Display::page_header($this->owner->getFullName());
2154
2155
        if ($this->course) {
2156
            $pdfContent .= '<p>'.get_lang('Course').': ';
2157
2158
            if ($this->session) {
2159
                $pdfContent .= $this->session->getTitle().' ('.$this->course->getTitle().')';
2160
            } else {
2161
                $pdfContent .= $this->course->getTitle();
2162
            }
2163
2164
            $pdfContent .= '</p>';
2165
        }
2166
2167
        $visibility = [];
2168
2169
        if ($isAllowedToFilterStudent && $currentUserId !== $this->owner->getId()) {
2170
            $visibility[] = Portfolio::VISIBILITY_VISIBLE;
2171
            $visibility[] = Portfolio::VISIBILITY_HIDDEN_EXCEPT_TEACHER;
2172
        }
2173
2174
        $items = Container::getPortfolioRepository()
2175
            ->findItemsByUser(
2176
                $this->owner,
2177
                $this->course,
2178
                $this->session,
2179
                null,
2180
                $visibility
2181
            );
2182
        $comments = $this->em
2183
            ->getRepository(PortfolioComment::class)
2184
            ->findCommentsByUser($this->owner, $this->course, $this->session);
2185
2186
        $itemsHtml = $this->getItemsInHtmlFormatted($items);
2187
        $commentsHtml = $this->getCommentsInHtmlFormatted($comments);
2188
2189
        $totalNumberOfItems = count($itemsHtml);
2190
        $totalNumberOfComments = count($commentsHtml);
2191
        $requiredNumberOfItems = (int) api_get_course_setting('portfolio_number_items');
2192
        $requiredNumberOfComments = (int) api_get_course_setting('portfolio_number_comments');
2193
2194
        $itemsSubtitle = '';
2195
        $commentsSubtitle = '';
2196
2197
        if ($requiredNumberOfItems > 0) {
2198
            $itemsSubtitle = sprintf(
2199
                get_lang('%d added / %d required'),
2200
                $totalNumberOfItems,
2201
                $requiredNumberOfItems
2202
            );
2203
        }
2204
2205
        if ($requiredNumberOfComments > 0) {
2206
            $commentsSubtitle = sprintf(
2207
                get_lang('%d added / %d required'),
2208
                $totalNumberOfComments,
2209
                $requiredNumberOfComments
2210
            );
2211
        }
2212
2213
        $pdfContent .= Display::page_subheader2(
2214
            get_lang('Portfolio items'),
2215
            $itemsSubtitle
2216
        );
2217
2218
        if ($totalNumberOfItems > 0) {
2219
            $pdfContent .= implode(PHP_EOL, $itemsHtml);
2220
        } else {
2221
            $pdfContent .= Display::return_message(get_lang('No items in your portfolio'), 'warning');
2222
        }
2223
2224
        $pdfContent .= Display::page_subheader2(
2225
            get_lang('Comments made'),
2226
            $commentsSubtitle
2227
        );
2228
2229
        if ($totalNumberOfComments > 0) {
2230
            $pdfContent .= implode(PHP_EOL, $commentsHtml);
2231
        } else {
2232
            $pdfContent .= Display::return_message(get_lang('You have not commented'), 'warning');
2233
        }
2234
2235
        $pdfName = $this->owner->getFullName()
2236
            .($this->course ? '_'.$this->course->getCode() : '')
2237
            .'_'.get_lang('Portfolio');
2238
2239
        Container::getEventDispatcher()->dispatch(
2240
            new PortfolioItemDownloadedEvent(['owner' => $this->owner]),
2241
            Events::PORTFOLIO_DOWNLOADED,
2242
        );
2243
2244
        $pdf = new PDF();
2245
        $pdf->content_to_pdf(
2246
            $pdfContent,
2247
            null,
2248
            $pdfName,
2249
            $this->course ? $this->course->getCode() : null,
2250
            'D',
2251
            false,
2252
            null,
2253
            false,
2254
            true
2255
        );
2256
    }
2257
2258
    public function exportZip(HttpRequest $httpRequest)
2259
    {
2260
        $currentUserId = api_get_user_id();
2261
        $isAllowedToFilterStudent = $this->course && api_is_allowed_to_edit();
2262
2263
        if ($isAllowedToFilterStudent) {
2264
            if ($httpRequest->query->has('user')) {
2265
                $this->owner = api_get_user_entity($httpRequest->query->getInt('user'));
2266
2267
                if (empty($this->owner)) {
2268
                    api_not_allowed(true);
2269
                }
2270
            }
2271
        }
2272
2273
        $commentsRepo = $this->em->getRepository(PortfolioComment::class);
2274
        $attachmentsRepo = $this->em->getRepository(PortfolioAttachment::class);
2275
2276
        $visibility = [];
2277
2278
        if ($isAllowedToFilterStudent && $currentUserId !== $this->owner->getId()) {
2279
            $visibility[] = Portfolio::VISIBILITY_VISIBLE;
2280
            $visibility[] = Portfolio::VISIBILITY_HIDDEN_EXCEPT_TEACHER;
2281
        }
2282
2283
        $items = Container::getPortfolioRepository()->findItemsByUser(
2284
            $this->owner,
2285
            $this->course,
2286
            $this->session,
2287
            null,
2288
            $visibility
2289
        );
2290
        $comments = $commentsRepo->findCommentsByUser($this->owner, $this->course, $this->session);
2291
2292
        $itemsHtml = $this->getItemsInHtmlFormatted($items);
2293
        $commentsHtml = $this->getCommentsInHtmlFormatted($comments);
2294
2295
        $sysArchivePath = api_get_path(SYS_ARCHIVE_PATH);
2296
        $tempPortfolioDirectory = $sysArchivePath."portfolio/{$this->owner->getId()}";
2297
2298
        $userDirectory = UserManager::getUserPathById($this->owner->getId(), 'system');
2299
        $attachmentsDirectory = $userDirectory.'portfolio_attachments/';
2300
2301
        $tblItemsHeaders = [];
2302
        $tblItemsHeaders[] = get_lang('Title');
2303
        $tblItemsHeaders[] = get_lang('Creation date');
2304
        $tblItemsHeaders[] = get_lang('Last update');
2305
        $tblItemsHeaders[] = get_lang('Category');
2306
        $tblItemsHeaders[] = get_lang('Category');
2307
        $tblItemsHeaders[] = get_lang('Score');
2308
        $tblItemsHeaders[] = get_lang('Course');
2309
        $tblItemsHeaders[] = get_lang('Session');
2310
        $tblItemsData = [];
2311
2312
        $tblCommentsHeaders = [];
2313
        $tblCommentsHeaders[] = get_lang('Resume');
2314
        $tblCommentsHeaders[] = get_lang('Date');
2315
        $tblCommentsHeaders[] = get_lang('Item title');
2316
        $tblCommentsHeaders[] = get_lang('Score');
2317
        $tblCommentsData = [];
2318
2319
        $filenames = [];
2320
2321
        $fs = new Filesystem();
2322
2323
        /**
2324
         * @var int       $i
2325
         * @var Portfolio $item
2326
         */
2327
        foreach ($items as $i => $item) {
2328
            $itemCategory = $item->getCategory();
2329
            $itemCourse = $item->getCourse();
2330
            $itemSession = $item->getSession();
2331
2332
            $itemDirectory = $item->getCreationDate()->format('Y-m-d-H-i-s');
2333
2334
            $itemFilename = sprintf('%s/items/%s/item.html', $tempPortfolioDirectory, $itemDirectory);
2335
            $imagePaths = [];
2336
            $itemFileContent = $this->fixMediaSourcesToHtml($itemsHtml[$i], $imagePaths);
2337
2338
            $fs->dumpFile($itemFilename, $itemFileContent);
2339
2340
            $filenames[] = $itemFilename;
2341
2342
            foreach ($imagePaths as $imagePath) {
2343
                $inlineFile = dirname($itemFilename).'/'.basename($imagePath);
2344
2345
                try {
2346
                    $filenames[] = $inlineFile;
2347
                    $fs->copy($imagePath, $inlineFile);
2348
                } catch (FileNotFoundException $notFoundException) {
2349
                    continue;
2350
                }
2351
            }
2352
2353
            $attachments = $attachmentsRepo->findFromItem($item);
2354
2355
            /** @var PortfolioAttachment $attachment */
2356
            foreach ($attachments as $attachment) {
2357
                $attachmentFilename = sprintf(
2358
                    '%s/items/%s/attachments/%s',
2359
                    $tempPortfolioDirectory,
2360
                    $itemDirectory,
2361
                    $attachment->getFilename()
2362
                );
2363
2364
                try {
2365
                    $fs->copy(
2366
                        $attachmentsDirectory.$attachment->getPath(),
2367
                        $attachmentFilename
2368
                    );
2369
                    $filenames[] = $attachmentFilename;
2370
                } catch (FileNotFoundException $notFoundException) {
2371
                    continue;
2372
                }
2373
            }
2374
2375
            $tblItemsData[] = [
2376
                Display::url(
2377
                    Security::remove_XSS($item->getTitle()),
2378
                    sprintf('items/%s/item.html', $itemDirectory)
2379
                ),
2380
                api_convert_and_format_date($item->getCreationDate()),
2381
                api_convert_and_format_date($item->getUpdateDate()),
2382
                $itemCategory ? $itemCategory->getTitle() : null,
2383
                $item->getComments()->count(),
2384
                $item->getScore(),
2385
                $itemCourse->getTitle(),
2386
                $itemSession ? $itemSession->getTitle() : null,
2387
            ];
2388
        }
2389
2390
        /**
2391
         * @var int              $i
2392
         * @var PortfolioComment $comment
2393
         */
2394
        foreach ($comments as $i => $comment) {
2395
            $commentDirectory = $comment->getDate()->format('Y-m-d-H-i-s');
2396
2397
            $imagePaths = [];
2398
            $commentFileContent = $this->fixMediaSourcesToHtml($commentsHtml[$i], $imagePaths);
2399
            $commentFilename = sprintf('%s/comments/%s/comment.html', $tempPortfolioDirectory, $commentDirectory);
2400
2401
            $fs->dumpFile($commentFilename, $commentFileContent);
2402
2403
            $filenames[] = $commentFilename;
2404
2405
            foreach ($imagePaths as $imagePath) {
2406
                $inlineFile = dirname($commentFilename).'/'.basename($imagePath);
2407
2408
                try {
2409
                    $filenames[] = $inlineFile;
2410
                    $fs->copy($imagePath, $inlineFile);
2411
                } catch (FileNotFoundException $notFoundException) {
2412
                    continue;
2413
                }
2414
            }
2415
2416
            $attachments = $attachmentsRepo->findFromComment($comment);
2417
2418
            /** @var PortfolioAttachment $attachment */
2419
            foreach ($attachments as $attachment) {
2420
                $attachmentFilename = sprintf(
2421
                    '%s/comments/%s/attachments/%s',
2422
                    $tempPortfolioDirectory,
2423
                    $commentDirectory,
2424
                    $attachment->getFilename()
2425
                );
2426
2427
                try {
2428
                    $fs->copy(
2429
                        $attachmentsDirectory.$attachment->getPath(),
2430
                        $attachmentFilename
2431
                    );
2432
                    $filenames[] = $attachmentFilename;
2433
                } catch (FileNotFoundException $notFoundException) {
2434
                    continue;
2435
                }
2436
            }
2437
2438
            $tblCommentsData[] = [
2439
                Display::url(
2440
                    $comment->getExcerpt(),
2441
                    sprintf('comments/%s/comment.html', $commentDirectory)
2442
                ),
2443
                api_convert_and_format_date($comment->getDate()),
2444
                Security::remove_XSS($comment->getItem()->getTitle()),
2445
                $comment->getScore(),
2446
            ];
2447
        }
2448
2449
        $tblItems = new HTML_Table(['class' => 'table table-hover table-striped table-bordered data_table']);
2450
        $tblItems->setHeaders($tblItemsHeaders);
2451
        $tblItems->setData($tblItemsData);
2452
2453
        $tblComments = new HTML_Table(['class' => 'table table-hover table-striped table-bordered data_table']);
2454
        $tblComments->setHeaders($tblCommentsHeaders);
2455
        $tblComments->setData($tblCommentsData);
2456
2457
        $itemFilename = sprintf('%s/index.html', $tempPortfolioDirectory);
2458
2459
        $filenames[] = $itemFilename;
2460
2461
        $fs->dumpFile(
2462
            $itemFilename,
2463
            $this->formatZipIndexFile($tblItems, $tblComments)
2464
        );
2465
2466
        $zipName = $this->owner->getFullName()
2467
            .($this->course ? '_'.$this->course->getCode() : '')
2468
            .'_'.get_lang('Portfolio');
2469
        $tempZipFile = $sysArchivePath."portfolio/$zipName.zip";
2470
        $zip = new PclZip($tempZipFile);
2471
2472
        foreach ($filenames as $filename) {
2473
            $zip->add($filename, PCLZIP_OPT_REMOVE_PATH, $tempPortfolioDirectory);
2474
        }
2475
2476
        Container::getEventDispatcher()->dispatch(
2477
            new PortfolioItemDownloadedEvent(['owner' => $this->owner]),
2478
            Events::PORTFOLIO_DOWNLOADED,
2479
        );
2480
2481
        DocumentManager::file_send_for_download($tempZipFile, true, "$zipName.zip");
2482
2483
        $fs->remove($tempPortfolioDirectory);
2484
        $fs->remove($tempZipFile);
2485
    }
2486
2487
    public function qualifyItem(Portfolio $item)
2488
    {
2489
        global $interbreadcrumb;
2490
2491
        $em = Database::getManager();
2492
2493
        $formAction = $this->baseUrl.http_build_query(['action' => 'qualify', 'item' => $item->getId()]);
2494
2495
        $form = new FormValidator('frm_qualify', 'post', $formAction);
2496
        $form->addUserAvatar('user', get_lang('Author'));
2497
        $form->addLabel(get_lang('Title'), $item->getTitle());
2498
2499
        $itemContent = $this->generateItemContent($item);
2500
2501
        $form->addLabel(get_lang('Content'), $itemContent);
2502
        $form->addNumeric(
2503
            'score',
2504
            [get_lang('Score'), null, ' / '.api_get_course_setting('portfolio_max_score')]
2505
        );
2506
        $form->addButtonSave(get_lang('Grade this item'));
2507
2508
        if ($form->validate()) {
2509
            $values = $form->exportValues();
2510
2511
            $item->setScore($values['score']);
2512
2513
            $em->persist($item);
2514
            $em->flush();
2515
2516
            Container::getEventDispatcher()->dispatch(
2517
                new PortfolioItemScoredEvent(['portfolio' => $item]),
2518
                Events::PORTFOLIO_ITEM_SCORED
2519
            );
2520
2521
            Display::addFlash(
2522
                Display::return_message(get_lang('Portfolio item was graded'), 'success')
2523
            );
2524
2525
            header("Location: $formAction");
2526
            exit();
2527
        }
2528
2529
        $form->setDefaults(
2530
            [
2531
                'user' => $item->getUser(),
2532
                'score' => (float) $item->getScore(),
2533
            ]
2534
        );
2535
2536
        $interbreadcrumb[] = [
2537
            'name' => get_lang('Portfolio'),
2538
            'url' => $this->baseUrl,
2539
        ];
2540
        $interbreadcrumb[] = [
2541
            'name' => $item->getTitle(true),
2542
            'url' => $this->baseUrl.http_build_query(['action' => 'view', 'id' => $item->getId()]),
2543
        ];
2544
2545
        $actions = [];
2546
        $actions[] = Display::url(
2547
            Display::getMdiIcon(ActionIcon::BACK, 'ch-tool-icon', null, ICON_SIZE_MEDIUM, get_lang('Back')),
2548
            $this->baseUrl.http_build_query(['action' => 'view', 'id' => $item->getId()])
2549
        );
2550
2551
        $this->renderView($form->returnForm(), get_lang('Qualify'), $actions);
2552
    }
2553
2554
    public function qualifyComment(PortfolioComment $comment)
2555
    {
2556
        global $interbreadcrumb;
2557
2558
        $em = Database::getManager();
2559
2560
        $item = $comment->getItem();
2561
        $commentPath = $em->getRepository(PortfolioComment::class)->getPath($comment);
2562
2563
        $commentContext = Container::getTwig()->render(
2564
            '@ChamiloCore/Portfolio/comment_context.html.twig',
2565
            [
2566
                'item' => $item,
2567
                'comment_path' => $commentPath,
2568
            ]
2569
        );
2570
2571
        $formAction = $this->baseUrl.http_build_query(['action' => 'qualify', 'comment' => $comment->getId()]);
2572
2573
        $form = new FormValidator('frm_qualify', 'post', $formAction);
2574
        $form->addHtml($commentContext);
2575
        $form->addUserAvatar('user', get_lang('Author'));
2576
        $form->addLabel(get_lang('Comment'), $comment->getContent());
2577
        $form->addNumeric(
2578
            'score',
2579
            [get_lang('Score'), null, '/ '.api_get_course_setting('portfolio_max_score')]
2580
        );
2581
        $form->addButtonSave(get_lang('Grade this comment'));
2582
2583
        if ($form->validate()) {
2584
            $values = $form->exportValues();
2585
2586
            $comment->setScore($values['score']);
2587
2588
            $em->persist($comment);
2589
            $em->flush();
2590
2591
            Container::getEventDispatcher()->dispatch(
2592
                new PortfolioCommentScoredEvent(['comment' => $comment]),
2593
                Events::PORTFOLIO_COMMENT_SCORED
2594
            );
2595
2596
            Display::addFlash(
2597
                Display::return_message(get_lang('Portfolio comment was graded'), 'success')
2598
            );
2599
2600
            header("Location: $formAction");
2601
            exit();
2602
        }
2603
2604
        $form->setDefaults(
2605
            [
2606
                'user' => $comment->getAuthor(),
2607
                'score' => (float) $comment->getScore(),
2608
            ]
2609
        );
2610
2611
        $interbreadcrumb[] = [
2612
            'name' => get_lang('Portfolio'),
2613
            'url' => $this->baseUrl,
2614
        ];
2615
        $interbreadcrumb[] = [
2616
            'name' => $item->getTitle(true),
2617
            'url' => $this->baseUrl.http_build_query(['action' => 'view', 'id' => $item->getId()]),
2618
        ];
2619
2620
        $actions = [];
2621
        $actions[] = Display::url(
2622
            Display::getMdiIcon(ActionIcon::BACK, 'ch-tool-icon', null, ICON_SIZE_MEDIUM, get_lang('Back')),
2623
            $this->baseUrl.http_build_query(['action' => 'view', 'id' => $item->getId()])
2624
        );
2625
2626
        $this->renderView($form->returnForm(), get_lang('Qualify'), $actions);
2627
    }
2628
2629
    public function downloadAttachment(HttpRequest $httpRequest)
2630
    {
2631
        $path = $httpRequest->query->get('file');
2632
2633
        if (empty($path)) {
2634
            api_not_allowed(true);
2635
        }
2636
2637
        $em = Database::getManager();
2638
        $attachmentRepo = $em->getRepository(PortfolioAttachment::class);
2639
2640
        $attachment = $attachmentRepo->findOneByPath($path);
2641
2642
        if (empty($attachment)) {
2643
            api_not_allowed(true);
2644
        }
2645
2646
        $originOwnerId = 0;
2647
2648
        if (Portfolio::TYPE_ITEM === $attachment->getOriginType()) {
2649
            $item = $em->find(Portfolio::class, $attachment->getOrigin());
2650
2651
            $originOwnerId = $item->getUser()->getId();
2652
        } elseif (Portfolio::TYPE_COMMENT === $attachment->getOriginType()) {
2653
            $comment = $em->find(PortfolioComment::class, $attachment->getOrigin());
2654
2655
            $originOwnerId = $comment->getAuthor()->getId();
2656
        } else {
2657
            api_not_allowed(true);
2658
        }
2659
2660
        $userDirectory = UserManager::getUserPathById($originOwnerId, 'system');
2661
        $attachmentsDirectory = $userDirectory.'portfolio_attachments/';
2662
        $attachmentFilename = $attachmentsDirectory.$attachment->getPath();
2663
2664
        if (!Security::check_abs_path($attachmentFilename, $attachmentsDirectory)) {
2665
            api_not_allowed(true);
2666
        }
2667
2668
        $downloaded = DocumentManager::file_send_for_download(
2669
            $attachmentFilename,
2670
            true,
2671
            $attachment->getFilename()
2672
        );
2673
2674
        if (!$downloaded) {
2675
            api_not_allowed(true);
2676
        }
2677
    }
2678
2679
    public function deleteAttachment(HttpRequest $httpRequest)
2680
    {
2681
        $currentUserId = api_get_user_id();
2682
2683
        $path = $httpRequest->query->get('file');
2684
2685
        if (empty($path)) {
2686
            api_not_allowed(true);
2687
        }
2688
2689
        $em = Database::getManager();
2690
        $fs = new Filesystem();
2691
2692
        $attachmentRepo = $em->getRepository(PortfolioAttachment::class);
2693
        $attachment = $attachmentRepo->findOneByPath($path);
2694
2695
        if (empty($attachment)) {
2696
            api_not_allowed(true);
2697
        }
2698
2699
        $originOwnerId = 0;
2700
        $itemId = 0;
2701
2702
        if (Portfolio::TYPE_ITEM === $attachment->getOriginType()) {
2703
            $item = $em->find(Portfolio::class, $attachment->getOrigin());
2704
            $originOwnerId = $item->getUser()->getId();
2705
            $itemId = $item->getId();
2706
        } elseif (Portfolio::TYPE_COMMENT === $attachment->getOriginType()) {
2707
            $comment = $em->find(PortfolioComment::class, $attachment->getOrigin());
2708
            $originOwnerId = $comment->getAuthor()->getId();
2709
            $itemId = $comment->getItem()->getId();
2710
        }
2711
2712
        if ($currentUserId !== $originOwnerId) {
2713
            api_not_allowed(true);
2714
        }
2715
2716
        $em->remove($attachment);
2717
        $em->flush();
2718
2719
        $userDirectory = UserManager::getUserPathById($originOwnerId, 'system');
2720
        $attachmentsDirectory = $userDirectory.'portfolio_attachments/';
2721
        $attachmentFilename = $attachmentsDirectory.$attachment->getPath();
2722
2723
        $fs->remove($attachmentFilename);
2724
2725
        if ($httpRequest->isXmlHttpRequest()) {
2726
            echo Display::return_message(get_lang('The attached file has been deleted'), 'success');
2727
        } else {
2728
            Display::addFlash(
2729
                Display::return_message(get_lang('The attached file has been deleted'), 'success')
2730
            );
2731
2732
            $url = $this->baseUrl.http_build_query(['action' => 'view', 'id' => $itemId]);
2733
2734
            if (Portfolio::TYPE_COMMENT === $attachment->getOriginType() && isset($comment)) {
2735
                $url .= '#comment-'.$comment->getId();
2736
            }
2737
2738
            header("Location: $url");
2739
        }
2740
2741
        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...
2742
    }
2743
2744
    /**
2745
     * @throws \Doctrine\ORM\OptimisticLockException
2746
     * @throws \Doctrine\ORM\ORMException
2747
     */
2748
    public function markAsHighlighted(Portfolio $item)
2749
    {
2750
        if ($item->getCourse()->getId() !== (int) api_get_course_int_id()) {
2751
            api_not_allowed(true);
2752
        }
2753
2754
        $item->setIsHighlighted(
2755
            !$item->isHighlighted()
2756
        );
2757
2758
        Database::getManager()->flush();
2759
2760
        if ($item->isHighlighted()) {
2761
            Container::getEventDispatcher()->dispatch(
2762
                new \Chamilo\CoreBundle\Event\PortfolioItemHighlightedEvent(['portfolio' => $item]),
2763
                Events::PORTFOLIO_ITEM_HIGHLIGHTED
2764
            );
2765
        }
2766
2767
        Display::addFlash(
2768
            Display::return_message(
2769
                $item->isHighlighted() ? get_lang('Marked as highlighted') : get_lang('Unmarked as highlighted'),
2770
                'success'
2771
            )
2772
        );
2773
2774
        header("Location: $this->baseUrl".http_build_query(['action' => 'view', 'id' => $item->getId()]));
2775
        exit;
2776
    }
2777
2778
    public function markAsTemplate(Portfolio $item)
2779
    {
2780
        if (!$this->itemBelongToOwner($item)) {
2781
            api_not_allowed(true);
2782
        }
2783
2784
        $item->setIsTemplate(
2785
            !$item->isTemplate()
2786
        );
2787
2788
        Database::getManager()->flush($item);
2789
2790
        Display::addFlash(
2791
            Display::return_message(
2792
                $item->isTemplate() ? get_lang('Portfolio item set as a new template') : get_lang('Portfolio item unset as template'),
2793
                'success'
2794
            )
2795
        );
2796
2797
        header("Location: $this->baseUrl".http_build_query(['action' => 'view', 'id' => $item->getId()]));
2798
        exit;
2799
    }
2800
2801
    public function markAsTemplateComment(PortfolioComment $comment)
2802
    {
2803
        if (!$this->commentBelongsToOwner($comment)) {
2804
            api_not_allowed(true);
2805
        }
2806
2807
        $comment->setIsTemplate(
2808
            !$comment->isTemplate()
2809
        );
2810
2811
        Database::getManager()->flush();
2812
2813
        Display::addFlash(
2814
            Display::return_message(
2815
                $comment->isTemplate() ? get_lang('Portfolio comment set as a new template') : get_lang('Portfolio comment unset as template'),
2816
                'success'
2817
            )
2818
        );
2819
2820
        header("Location: $this->baseUrl".http_build_query(['action' => 'view', 'id' => $comment->getItem()->getId()]));
2821
        exit;
2822
    }
2823
2824
    public function listTags(HttpRequest $request)
2825
    {
2826
        global $interbreadcrumb;
2827
2828
        api_protect_course_script();
2829
        api_protect_teacher_script();
2830
2831
        $em = Database::getManager();
2832
        $tagRepo = $em->getRepository(Tag::class);
2833
2834
        $tagsQuery = $tagRepo->findForPortfolioInCourseQuery($this->course, $this->session);
2835
2836
        $tag = $request->query->has('id')
2837
            ? $tagRepo->find($request->query->getInt('id'))
2838
            : null;
2839
2840
        $formAction = ['action' => $request->query->get('action')];
2841
2842
        if ($tag) {
2843
            $formAction['id'] = $tag->getId();
2844
        }
2845
2846
        $form = new FormValidator('frm_add_tag', 'post', $this->baseUrl.http_build_query($formAction));
2847
        $form->addText('name', get_lang('Tag'));
2848
2849
        if ($tag) {
2850
            $form->addButtonUpdate(get_lang('Edit'));
2851
        } else {
2852
            $form->addButtonCreate(get_lang('Add'));
2853
        }
2854
2855
        if ($form->validate()) {
2856
            $values = $form->exportValues();
2857
2858
            $extraFieldInfo = (new ExtraField('portfolio'))->get_handler_field_info_by_field_variable('tags');
2859
2860
            if (!$tag) {
2861
                $tag = (new Tag())->setCount(0);
2862
2863
                $portfolioRelTag = (new PortfolioRelTag())
2864
                    ->setTag($tag)
2865
                    ->setCourse($this->course)
2866
                    ->setSession($this->session)
2867
                ;
2868
2869
                $em->persist($tag);
2870
                $em->persist($portfolioRelTag);
2871
            }
2872
2873
            $tag
2874
                ->setTag($values['name'])
2875
                ->setFieldId((int) $extraFieldInfo['id'])
2876
            ;
2877
2878
            $em->flush();
2879
2880
            Display::addFlash(
2881
                Display::return_message(get_lang('Tag saved'), 'success')
2882
            );
2883
2884
            header('Location: '.$this->baseUrl.http_build_query($formAction));
2885
            exit();
2886
        } else {
2887
            $form->protect();
2888
2889
            if ($tag) {
2890
                $form->setDefaults(['name' => $tag->getTag()]);
2891
            }
2892
        }
2893
2894
        $langTags = get_lang('Tags');
2895
        $langEdit = get_lang('Edit');
2896
2897
        $deleteIcon = Display::getMdiIcon(ActionIcon::DELETE, 'ch-tool-icon', null, ICON_SIZE_MEDIUM, get_lang('Delete'));
2898
        $editIcon = Display::getMdiIcon(ActionIcon::DELETE, 'ch-tool-icon', null, ICON_SIZE_MEDIUM,$langEdit);
2899
2900
        $table = new SortableTable(
2901
            'portfolio_tags',
2902
            function () use ($tagsQuery) {
2903
                return (int) $tagsQuery
2904
                    ->select('COUNT(t)')
2905
                    ->getQuery()
2906
                    ->getSingleScalarResult()
2907
                ;
2908
            },
2909
            function ($from, $limit, $column, $direction) use ($tagsQuery) {
2910
                $data = [];
2911
2912
                /** @var array<int, Tag> $tags */
2913
                $tags = $tagsQuery
2914
                    ->select('t')
2915
                    ->orderBy('t.tag', $direction)
2916
                    ->setFirstResult($from)
2917
                    ->setMaxResults($limit)
2918
                    ->getQuery()
2919
                    ->getResult();
2920
2921
                foreach ($tags as $tag) {
2922
                    $data[] = [
2923
                        $tag->getTag(),
2924
                        $tag->getId(),
2925
                    ];
2926
                }
2927
2928
                return $data;
2929
            },
2930
            0,
2931
            40
2932
        );
2933
        $table->set_header(0, get_lang('Name'));
2934
        $table->set_header(1, get_lang('Actions'), false, ['class' => 'text-right'], ['class' => 'text-right']);
2935
        $table->set_column_filter(
2936
            1,
2937
            function ($id) use ($editIcon, $deleteIcon) {
2938
                $editParams = http_build_query(['action' => 'edit_tag', 'id' => $id]);
2939
                $deleteParams = http_build_query(['action' => 'delete_tag', 'id' => $id]);
2940
2941
                return Display::url($editIcon, $this->baseUrl.$editParams).PHP_EOL
2942
                    .Display::url($deleteIcon, $this->baseUrl.$deleteParams).PHP_EOL;
2943
            }
2944
        );
2945
        $table->set_additional_parameters(
2946
            [
2947
                'action' => 'tags',
2948
                'cid' => $this->course->getId(),
2949
                'sid' => $this->session ? $this->session->getId() : 0,
2950
                'gid' => 0,
2951
            ]
2952
        );
2953
2954
        $content = $form->returnForm().PHP_EOL
2955
            .$table->return_table();
2956
2957
        $interbreadcrumb[] = [
2958
            'name' => get_lang('Portfolio'),
2959
            'url' => $this->baseUrl,
2960
        ];
2961
2962
        $pageTitle = $langTags;
2963
2964
        if ($tag) {
2965
            $pageTitle = $langEdit;
2966
2967
            $interbreadcrumb[] = [
2968
                'name' => $langTags,
2969
                'url' => $this->baseUrl.'action=tags',
2970
            ];
2971
        }
2972
2973
        $this->renderView($content, $pageTitle);
2974
    }
2975
2976
    public function deleteTag(Tag $tag)
2977
    {
2978
        api_protect_course_script();
2979
        api_protect_teacher_script();
2980
2981
        $em = Database::getManager();
2982
        $portfolioTagRepo = $em->getRepository(PortfolioRelTag::class);
2983
2984
        $portfolioTag = $portfolioTagRepo
2985
            ->findOneBy(['tag' => $tag, 'course' => $this->course, 'session' => $this->session]);
2986
2987
        if ($portfolioTag) {
2988
            $em->remove($portfolioTag);
2989
            $em->flush();
2990
2991
            Display::addFlash(
2992
                Display::return_message(get_lang('Tag deleted'), 'success')
2993
            );
2994
        }
2995
2996
        header('Location: '.$this->baseUrl.http_build_query(['action' => 'tags']));
2997
        exit();
2998
    }
2999
3000
    /**
3001
     * @throws \Doctrine\ORM\OptimisticLockException
3002
     * @throws \Doctrine\ORM\ORMException
3003
     */
3004
    public function editComment(PortfolioComment $comment)
3005
    {
3006
        global $interbreadcrumb;
3007
3008
        if (!$this->commentBelongsToOwner($comment)) {
3009
            api_not_allowed(true);
3010
        }
3011
3012
        $item = $comment->getItem();
3013
        $commmentCourse = $item->getCourse();
3014
        $commmentSession = $item->getSession();
3015
3016
        $formAction = $this->baseUrl.http_build_query(['action' => 'edit_comment', 'id' => $comment->getId()]);
3017
3018
        $form = new FormValidator('frm_comment', 'post', $formAction);
3019
        $form->addLabel(
3020
            get_lang('Date'),
3021
            $this->getLabelForCommentDate($comment)
3022
        );
3023
        $form->addHtmlEditor('content', get_lang('Comments'), true, false, ['ToolbarSet' => 'Minimal']);
3024
        $form->applyFilter('content', 'trim');
3025
3026
        $this->addAttachmentsFieldToForm($form);
3027
3028
        $form->addButtonUpdate(get_lang('Update'));
3029
3030
        if ($form->validate()) {
3031
            if ($commmentCourse) {
3032
                api_item_property_update(
3033
                    api_get_course_info($commmentCourse->getCode()),
3034
                    TOOL_PORTFOLIO_COMMENT,
3035
                    $comment->getId(),
3036
                    'PortfolioCommentUpdated',
3037
                    api_get_user_id(),
3038
                    [],
3039
                    null,
3040
                    '',
3041
                    '',
3042
                    $commmentSession ? $commmentSession->getId() : 0
3043
                );
3044
            }
3045
3046
            $values = $form->exportValues();
3047
3048
            $comment->setContent($values['content']);
3049
3050
            $this->em->flush();
3051
3052
            $this->processAttachments(
3053
                $form,
3054
                $comment->getAuthor(),
3055
                $comment->getId(),
3056
                Portfolio::TYPE_COMMENT
3057
            );
3058
3059
            Container::getEventDispatcher()->dispatch(
3060
                new PortfolioCommentEditedEvent(['comment' => $comment]),
3061
                Events::PORTFOLIO_COMMENT_EDITED
3062
            );
3063
3064
            Display::addFlash(
3065
                Display::return_message(get_lang('Item updated'), 'success')
3066
            );
3067
3068
            header("Location: $this->baseUrl"
3069
                .http_build_query(['action' => 'view', 'id' => $item->getId()])
3070
                .'#comment-'.$comment->getId()
3071
            );
3072
            exit;
3073
        }
3074
3075
        $form->setDefaults([
3076
            'content' => $comment->getContent(),
3077
        ]);
3078
3079
        $interbreadcrumb[] = [
3080
            'name' => get_lang('Portfolio'),
3081
            'url' => $this->baseUrl,
3082
        ];
3083
        $interbreadcrumb[] = [
3084
            'name' => $item->getTitle(true),
3085
            'url' => $this->baseUrl.http_build_query(['action' => 'view', 'id' => $item->getId()]),
3086
        ];
3087
3088
        $actions = [];
3089
        $actions[] = Display::url(
3090
            Display::getMdiIcon(ActionIcon::BACK, 'ch-tool-icon', null, ICON_SIZE_MEDIUM, get_lang('Back')),
3091
            $this->baseUrl
3092
        );
3093
3094
        $content = $form->returnForm()
3095
            .PHP_EOL
3096
            .'<div class="row"> <div class="col-sm-8 col-sm-offset-2">'
3097
            .$this->generateAttachmentList($comment)
3098
            .'</div></div>';
3099
3100
        $this->renderView(
3101
            $content,
3102
            get_lang('Edit portfolio comment'),
3103
            $actions
3104
        );
3105
    }
3106
3107
    /**
3108
     * @throws \Doctrine\ORM\OptimisticLockException
3109
     * @throws \Doctrine\ORM\ORMException
3110
     */
3111
    public function deleteComment(PortfolioComment $comment)
3112
    {
3113
        if (!$this->commentBelongsToOwner($comment)) {
3114
            api_not_allowed(true);
3115
        }
3116
3117
        $this->em->remove($comment);
3118
3119
        $this->em
3120
            ->getRepository(PortfolioAttachment::class)
3121
            ->removeFromComment($comment);
3122
3123
        $this->em->flush();
3124
3125
        Display::addFlash(
3126
            Display::return_message(get_lang('The comment has been deleted.'), 'success')
3127
        );
3128
3129
        header("Location: $this->baseUrl");
3130
        exit;
3131
    }
3132
3133
    public function itemVisibilityChooser(Portfolio $item)
3134
    {
3135
        global $interbreadcrumb;
3136
3137
        if (!$this->itemBelongToOwner($item)) {
3138
            api_not_allowed(true);
3139
        }
3140
3141
        $em = Database::getManager();
3142
        $tblItemProperty = Database::get_course_table(TABLE_ITEM_PROPERTY);
3143
3144
        $courseId = $this->course->getId();
3145
        $sessionId = $this->session ? $this->session->getId() : 0;
3146
3147
        $formAction = $this->baseUrl.http_build_query(['action' => 'item_visiblity_choose', 'id' => $item->getId()]);
3148
3149
        $form = new FormValidator('visibility', 'post', $formAction);
3150
        CourseManager::addUserGroupMultiSelect($form, ['USER:'.$this->owner->getId()]);
3151
        $form->addLabel(
3152
            '',
3153
            Display::return_message(
3154
                get_lang('Only selected users will see the content')
3155
                    .'<br>'.get_lang('Leave empty to enable the content for everyone'),
3156
                'info',
3157
                false
3158
            )
3159
        );
3160
        $form->addCheckBox('hidden', '', get_lang('Hidden but visible for me'));
3161
        $form->addButtonSave(get_lang('Save'));
3162
3163
        if ($form->validate()) {
3164
            $values = $form->exportValues();
3165
            $recipients = CourseManager::separateUsersGroups($values['users'])['users'];
3166
            $courseInfo = api_get_course_info_by_id($courseId);
3167
3168
            Database::delete(
3169
                $tblItemProperty,
3170
                [
3171
                    'c_id = ? ' => [$courseId],
3172
                    'AND tool = ? AND ref = ? ' => [TOOL_PORTFOLIO, $item->getId()],
3173
                    'AND lastedit_type = ? ' => ['visible'],
3174
                ]
3175
            );
3176
3177
            if (empty($recipients) && empty($values['hidden'])) {
3178
                $item->setVisibility(Portfolio::VISIBILITY_VISIBLE);
3179
            } else {
3180
                if (empty($values['hidden'])) {
3181
                    foreach ($recipients as $userId) {
3182
                        api_item_property_update(
3183
                            $courseInfo,
3184
                            TOOL_PORTFOLIO,
3185
                            $item->getId(),
3186
                            'visible',
3187
                            api_get_user_id(),
3188
                            [],
3189
                            $userId,
3190
                            '',
3191
                            '',
3192
                            $sessionId
3193
                        );
3194
                    }
3195
                }
3196
3197
                $item->setVisibility(Portfolio::VISIBILITY_PER_USER);
3198
            }
3199
3200
            $em->flush();
3201
3202
            Container::getEventDispatcher()->dispatch(
3203
                new PortfolioItemVisibilityChangedEvent([
3204
                    'portfolio' => $item,
3205
                    'recipients' => array_values($recipients),
3206
                ]),
3207
                Events::PORTFOLIO_ITEM_VISIBILITY_CHANGED
3208
            );
3209
3210
            Display::addFlash(
3211
                Display::return_message(get_lang('Post visibility changed'), 'success')
3212
            );
3213
3214
            header("Location: $formAction");
3215
            exit;
3216
        }
3217
3218
        $result = Database::select(
3219
            'to_user_id',
3220
            $tblItemProperty,
3221
            [
3222
                'where' => [
3223
                    'c_id = ? ' => [$courseId],
3224
                    'AND tool = ? AND ref = ? ' => [TOOL_PORTFOLIO, $item->getId()],
3225
                    'AND to_user_id IS NOT NULL ' => [],
3226
                ],
3227
            ]
3228
        );
3229
3230
        $recipients = array_map(
3231
            function (array $item): string {
3232
                return 'USER:'.$item['to_user_id'];
3233
            },
3234
            $result
3235
        );
3236
3237
        $defaults = ['users' => $recipients];
3238
3239
        if (empty($recipients) && Portfolio::VISIBILITY_PER_USER === $item->getVisibility()) {
3240
            $defaults['hidden'] = true;
3241
        }
3242
3243
        $form->setDefaults($defaults);
3244
        $form->protect();
3245
3246
        $interbreadcrumb[] = [
3247
            'name' => get_lang('Portfolio'),
3248
            'url' => $this->baseUrl,
3249
        ];
3250
        $interbreadcrumb[] = [
3251
            'name' => $item->getTitle(true),
3252
            'url' => $this->baseUrl.http_build_query(['action' => 'view', 'id' => $item->getId()]),
3253
        ];
3254
3255
        $actions = [];
3256
        $actions[] = Display::url(
3257
            Display::getMdiIcon(ActionIcon::BACK, 'ch-tool-icon', null, ICON_SIZE_MEDIUM, get_lang('Back')),
3258
            $this->baseUrl.http_build_query(['action' => 'view', 'id' => $item->getId()])
3259
        );
3260
3261
        $this->renderView(
3262
            $form->returnForm(),
3263
            get_lang('Choose recipients'),
3264
            $actions
3265
        );
3266
    }
3267
3268
    public function commentVisibilityChooser(PortfolioComment $comment): void
3269
    {
3270
        global $interbreadcrumb;
3271
3272
        if (!$this->commentBelongsToOwner($comment)) {
3273
            api_not_allowed(true);
3274
        }
3275
3276
        $em = Database::getManager();
3277
        $tblItemProperty = Database::get_course_table(TABLE_ITEM_PROPERTY);
3278
3279
        $courseId = $this->course->getId();
3280
        $sessionId = $this->session ? $this->session->getId() : 0;
3281
        $item = $comment->getItem();
3282
3283
        $formAction = $this->baseUrl.http_build_query(['action' => 'comment_visiblity_choose', 'id' => $comment->getId()]);
3284
3285
        $form = new FormValidator('visibility', 'post', $formAction);
3286
        CourseManager::addUserGroupMultiSelect($form, ['USER:'.$this->owner->getId()]);
3287
        $form->addLabel(
3288
            '',
3289
            Display::return_message(
3290
                get_lang('Only selected users will see the content')
3291
                    .'<br>'.get_lang('Leave empty to enable the content for everyone'),
3292
                'info',
3293
                false
3294
            )
3295
        );
3296
        $form->addCheckBox('hidden', '', get_lang('Hidden but visible for me'));
3297
        $form->addButtonSave(get_lang('Save'));
3298
3299
        if ($form->validate()) {
3300
            $values = $form->exportValues();
3301
            $recipients = CourseManager::separateUsersGroups($values['users'])['users'];
3302
            $courseInfo = api_get_course_info_by_id($courseId);
3303
3304
            Database::delete(
3305
                $tblItemProperty,
3306
                [
3307
                    'c_id = ? ' => [$courseId],
3308
                    'AND tool = ? AND ref = ? ' => [TOOL_PORTFOLIO_COMMENT, $comment->getId()],
3309
                    'AND lastedit_type = ? ' => ['visible'],
3310
                ]
3311
            );
3312
3313
            if (empty($recipients) && empty($values['hidden'])) {
3314
                $comment->setVisibility(PortfolioComment::VISIBILITY_VISIBLE);
3315
            } else {
3316
                if (empty($values['hidden'])) {
3317
                    foreach ($recipients as $userId) {
3318
                        api_item_property_update(
3319
                            $courseInfo,
3320
                            TOOL_PORTFOLIO_COMMENT,
3321
                            $comment->getId(),
3322
                            'visible',
3323
                            api_get_user_id(),
3324
                            [],
3325
                            $userId,
3326
                            '',
3327
                            '',
3328
                            $sessionId
3329
                        );
3330
                    }
3331
                }
3332
3333
                $comment->setVisibility(PortfolioComment::VISIBILITY_PER_USER);
3334
            }
3335
3336
            $em->flush();
3337
3338
            Display::addFlash(
3339
                Display::return_message(get_lang('The visibility has been changed.'), 'success')
3340
            );
3341
3342
            header("Location: $formAction");
3343
            exit;
3344
        }
3345
3346
        $result = Database::select(
3347
            'to_user_id',
3348
            $tblItemProperty,
3349
            [
3350
                'where' => [
3351
                    'c_id = ? ' => [$courseId],
3352
                    'AND tool = ? AND ref = ? ' => [TOOL_PORTFOLIO_COMMENT, $comment->getId()],
3353
                    'AND to_user_id IS NOT NULL ' => [],
3354
                ],
3355
            ]
3356
        );
3357
3358
        $recipients = array_map(
3359
            function (array $itemProperty): string {
3360
                return 'USER:'.$itemProperty['to_user_id'];
3361
            },
3362
            $result
3363
        );
3364
3365
        $defaults = ['users' => $recipients];
3366
3367
        if (empty($recipients) && PortfolioComment::VISIBILITY_PER_USER === $comment->getVisibility()) {
3368
            $defaults['hidden'] = true;
3369
        }
3370
3371
        $form->setDefaults($defaults);
3372
        $form->protect();
3373
3374
        $interbreadcrumb[] = [
3375
            'name' => get_lang('Portfolio'),
3376
            'url' => $this->baseUrl,
3377
        ];
3378
        $interbreadcrumb[] = [
3379
            'name' => $item->getTitle(true),
3380
            'url' => $this->baseUrl.http_build_query(['action' => 'view', 'id' => $item->getId()]),
3381
        ];
3382
        $interbreadcrumb[] = [
3383
            'name' => $comment->getExcerpt(40),
3384
            'url' => $this->baseUrl
3385
                .http_build_query(['action' => 'view', 'id' => $item->getId()])
3386
                .'#comment-'.$comment->getId(),
3387
        ];
3388
3389
        $actions = [];
3390
        $actions[] = Display::url(
3391
            Display::getMdiIcon(ActionIcon::BACK, 'ch-tool-icon', null, ICON_SIZE_MEDIUM, get_lang('Back')),
3392
            $this->baseUrl.http_build_query(['action' => 'view', 'id' => $item->getId()])
3393
        );
3394
3395
        $this->renderView(
3396
            $form->returnForm(),
3397
            get_lang('Choose recipients'),
3398
            $actions
3399
        );
3400
    }
3401
3402
    private function isAllowed(): bool
3403
    {
3404
        $isSubscribedInCourse = false;
3405
3406
        if ($this->course) {
3407
            $isSubscribedInCourse = CourseManager::is_user_subscribed_in_course(
3408
                api_get_user_id(),
3409
                $this->course->getCode(),
3410
                (bool) $this->session,
3411
                $this->session ? $this->session->getId() : 0
3412
            );
3413
        }
3414
3415
        if (!$this->course || $isSubscribedInCourse) {
3416
            return true;
3417
        }
3418
3419
        return false;
3420
    }
3421
3422
    private function blockIsNotAllowed(): void
3423
    {
3424
        if (!$this->isAllowed()) {
3425
            api_not_allowed(true);
3426
        }
3427
    }
3428
3429
    /**
3430
     * @param  bool  $showHeader
3431
     */
3432
    private function renderView(string $content, string $toolName, array $actions = [], bool $showHeader = true): void
3433
    {
3434
        global $this_section;
3435
3436
        $this_section = $this->course ? SECTION_COURSES : SECTION_SOCIAL;
3437
3438
        $view = new Template($toolName);
3439
3440
        if ($showHeader) {
3441
            $view->assign('header', $toolName);
3442
        }
3443
3444
        $actionsStr = '';
3445
3446
        if ($this->course) {
3447
            $actionsStr .= Display::return_introduction_section(TOOL_PORTFOLIO);
3448
        }
3449
3450
        if ($actions) {
3451
            $actions = implode('', $actions);
3452
3453
            $actionsStr .= Display::toolbarAction('portfolio-toolbar', [$actions]);
3454
        }
3455
3456
        $view->assign('baseurl', $this->baseUrl);
3457
        $view->assign('actions', $actionsStr);
3458
3459
        $view->assign('content', $content);
3460
        $view->display_one_col_template();
3461
    }
3462
3463
    private function categoryBelongToOwner(PortfolioCategory $category): bool
3464
    {
3465
        if ($category->getUser()->getId() != $this->owner->getId()) {
3466
            return false;
3467
        }
3468
3469
        return true;
3470
    }
3471
3472
    private function addAttachmentsFieldToForm(FormValidator $form): void
3473
    {
3474
        $form->addButton('add_attachment', get_lang('Add attachment'), 'plus');
3475
        $form->addHtml('<div id="container-attachments" style="display: none;">');
3476
        $form->addFile('attachment_file[]', get_lang('Files attachments'));
3477
        $form->addText('attachment_comment[]', get_lang('Description'), false);
3478
        $form->addHtml('</div>');
3479
3480
        $script = "$(function () {
3481
            var attachmentsTemplate = $('#container-attachments').html();
3482
            var \$btnAdd = $('[name=\"add_attachment\"]');
3483
            var \$reference = \$btnAdd.parents('.form-group');
3484
3485
            \$btnAdd.on('click', function (e) {
3486
                e.preventDefault();
3487
3488
                $(attachmentsTemplate).insertBefore(\$reference);
3489
            });
3490
        })";
3491
3492
        $form->addHtml("<script>$script</script>");
3493
    }
3494
3495
    private function processAttachments(
3496
        FormValidator $form,
3497
        User $user,
3498
        int $originId,
3499
        int $originType
3500
    ): void {
3501
        $em = Database::getManager();
3502
        $fs = new Filesystem();
3503
3504
        $comments = $form->getSubmitValue('attachment_comment');
3505
3506
        foreach ($_FILES['attachment_file']['error'] as $i => $attachmentFileError) {
3507
            if ($attachmentFileError != UPLOAD_ERR_OK) {
3508
                continue;
3509
            }
3510
3511
            $_file = [
3512
                'name' => $_FILES['attachment_file']['name'][$i],
3513
                'type' => $_FILES['attachment_file']['type'][$i],
3514
                'tmp_name' => $_FILES['attachment_file']['tmp_name'][$i],
3515
                'size' => $_FILES['attachment_file']['size'][$i],
3516
            ];
3517
3518
            if (empty($_file['type'])) {
3519
                $_file['type'] = DocumentManager::file_get_mime_type($_file['name']);
3520
            }
3521
3522
            $newFileName = add_ext_on_mime(stripslashes($_file['name']), $_file['type']);
3523
3524
            if (!filter_extension($newFileName)) {
3525
                Display::addFlash(Display::return_message(get_lang('File upload failed: this file extension or file type is prohibited'), 'error'));
3526
                continue;
3527
            }
3528
3529
            $newFileName = uniqid();
3530
            $attachmentsDirectory = UserManager::getUserPathById($user->getId(), 'system').'portfolio_attachments/';
3531
3532
            if (!$fs->exists($attachmentsDirectory)) {
3533
                $fs->mkdir($attachmentsDirectory, api_get_permissions_for_new_directories());
3534
            }
3535
3536
            $attachmentFilename = $attachmentsDirectory.$newFileName;
3537
3538
            if (is_uploaded_file($_file['tmp_name'])) {
3539
                $moved = move_uploaded_file($_file['tmp_name'], $attachmentFilename);
3540
3541
                if (!$moved) {
3542
                    Display::addFlash(Display::return_message(get_lang('The uploaded file could not be saved (perhaps a permission problem?)'), 'error'));
3543
                    continue;
3544
                }
3545
            }
3546
3547
            $attachment = new PortfolioAttachment();
3548
            $attachment
3549
                ->setFilename($_file['name'])
3550
                ->setComment($comments[$i])
3551
                ->setPath($newFileName)
3552
                ->setOrigin($originId)
3553
                ->setOriginType($originType)
3554
                ->setSize($_file['size']);
3555
3556
            $em->persist($attachment);
3557
            $em->flush();
3558
        }
3559
    }
3560
3561
    private function itemBelongToOwner(Portfolio $item): bool
3562
    {
3563
        if ($item->getCreator()->getId() != $this->owner->getId()) {
3564
            return false;
3565
        }
3566
3567
        return true;
3568
    }
3569
3570
    private function commentBelongsToOwner(PortfolioComment $comment): bool
3571
    {
3572
        return $comment->getAuthor() === $this->owner;
3573
    }
3574
3575
    private function createFormTagFilter(bool $listByUser = false): FormValidator
3576
    {
3577
        $tags = Database::getManager()
3578
            ->getRepository(Tag::class)
3579
            ->findForPortfolioInCourseQuery($this->course, $this->session)
3580
            ->getQuery()
3581
            ->getResult()
3582
        ;
3583
3584
        $frmTagList = new FormValidator(
3585
            'frm_tag_list',
3586
            'get',
3587
            $this->baseUrl.($listByUser ? 'user='.$this->owner->getId() : ''),
3588
            '',
3589
            [],
3590
            FormValidator::LAYOUT_BOX
3591
        );
3592
3593
        $frmTagList->addDatePicker('date', get_lang('Creation date'));
3594
3595
        $frmTagList->addSelectFromCollection(
3596
            'tags',
3597
            get_lang('Tags'),
3598
            $tags,
3599
            ['multiple' => 'multiple'],
3600
            false,
3601
            'getTag'
3602
        );
3603
3604
        $frmTagList->addText('text', get_lang('Search'), false)->setIcon('search');
3605
        $frmTagList->applyFilter('text', 'trim');
3606
        $frmTagList->addHtml('<br>');
3607
        $frmTagList->addButtonFilter(get_lang('Filter'));
3608
3609
        if ($this->course) {
3610
            $frmTagList->addHidden('cid', $this->course->getId());
3611
            $frmTagList->addHidden('sid', $this->session ? $this->session->getId() : 0);
3612
            $frmTagList->addHidden('gid', 0);
3613
            $frmTagList->addHidden('gradebook', 0);
3614
            $frmTagList->addHidden('origin', '');
3615
            $frmTagList->addHidden('categoryId', 0);
3616
            $frmTagList->addHidden('subCategoryIds', '');
3617
3618
            if ($listByUser) {
3619
                $frmTagList->addHidden('user', $this->owner->getId());
3620
            }
3621
        }
3622
3623
        return $frmTagList;
3624
    }
3625
3626
    /**
3627
     * @throws Exception
3628
     */
3629
    private function createFormStudentFilter(bool $listByUser = false, bool $listHighlighted = false, bool $listAlphabeticalOrder = false): FormValidator
3630
    {
3631
        $frmStudentList = new FormValidator(
3632
            'frm_student_list',
3633
            'get',
3634
            $this->baseUrl,
3635
            '',
3636
            [],
3637
            FormValidator::LAYOUT_BOX
3638
        );
3639
3640
        $urlParams = http_build_query(
3641
            [
3642
                'a' => 'search_user_by_course',
3643
                'course_id' => $this->course->getId(),
3644
                'session_id' => $this->session ? $this->session->getId() : 0,
3645
            ]
3646
        );
3647
3648
        /** @var SelectAjax $slctUser */
3649
        $slctUser = $frmStudentList->addSelectAjax(
3650
            'user',
3651
            get_lang('Select a learner portfolio'),
3652
            [],
3653
            [
3654
                'url' => api_get_path(WEB_AJAX_PATH)."course.ajax.php?$urlParams",
3655
                'placeholder' => get_lang('Search users'),
3656
                'formatResult' => SelectAjax::templateResultForUsersInCourse(),
3657
                'formatSelection' => SelectAjax::templateSelectionForUsersInCourse(),
3658
            ]
3659
        );
3660
3661
        if ($listByUser) {
3662
            $slctUser->addOption(
3663
                $this->owner->getFullName(),
3664
                $this->owner->getId(),
3665
                [
3666
                    'data-avatarurl' => UserManager::getUserPicture($this->owner->getId()),
3667
                    'data-username' => $this->owner->getUsername(),
3668
                ]
3669
            );
3670
3671
            $link = Display::url(
3672
                get_lang('Back to the main course portfolio'),
3673
                $this->baseUrl
3674
            );
3675
        } else {
3676
            $link = Display::url(
3677
                get_lang('See my portfolio in this course'),
3678
                $this->baseUrl.http_build_query(['user' => api_get_user_id()])
3679
            );
3680
        }
3681
3682
        $frmStudentList->addHtml("<p>$link</p>");
3683
3684
        if ($listHighlighted) {
3685
            $link = Display::url(
3686
                get_lang('Back to the main course portfolio'),
3687
                $this->baseUrl
3688
            );
3689
        } else {
3690
            $link = Display::url(
3691
                get_lang('See highlights'),
3692
                $this->baseUrl.http_build_query(['list_highlighted' => true])
3693
            );
3694
        }
3695
3696
        $frmStudentList->addHtml("<p>$link</p>");
3697
3698
        if (true !== api_get_configuration_value('portfolio_order_post_by_alphabetical_order')) {
3699
            if ($listAlphabeticalOrder) {
3700
                $link = Display::url(
3701
                    get_lang('View in chronological order'),
3702
                    $this->baseUrl
3703
                );
3704
            } else {
3705
                $link = Display::url(
3706
                    get_lang('View in alphabetical order'),
3707
                    $this->baseUrl.http_build_query(['list_alphabetical' => true])
3708
                );
3709
            }
3710
3711
            $frmStudentList->addHtml("<p>$link</p>");
3712
        }
3713
3714
        return $frmStudentList;
3715
    }
3716
3717
    private function getCategoriesForIndex(?int $parentId = null): array
3718
    {
3719
        $categoriesCriteria = [];
3720
3721
        if (!api_is_platform_admin() && null !== $this->owner->getId()) {
3722
            $categoriesCriteria['isVisible'] = true;
3723
        }
3724
        if (isset($parentId)) {
3725
            $categoriesCriteria['parent'] = $parentId;
3726
        }
3727
3728
        return $this->em
3729
            ->getRepository(PortfolioCategory::class)
3730
            ->findBy($categoriesCriteria);
3731
    }
3732
3733
    private function getHighlightedItems()
3734
    {
3735
        $queryBuilder = $this->em->createQueryBuilder();
3736
        $queryBuilder
3737
            ->select('pi')
3738
            ->from(Portfolio::class, 'pi')
3739
            ->where('pi.course = :course')
3740
            ->andWhere('pi.isHighlighted = TRUE')
3741
            ->setParameter('course', $this->course);
3742
3743
        if ($this->session) {
3744
            $queryBuilder->andWhere('pi.session = :session');
3745
            $queryBuilder->setParameter('session', $this->session);
3746
        } else {
3747
            $queryBuilder->andWhere('pi.session IS NULL');
3748
        }
3749
3750
        if ($this->advancedSharingEnabled) {
3751
            $queryBuilder
3752
                ->leftJoin(
3753
                    CItemProperty::class,
3754
                    'cip',
3755
                    Join::WITH,
3756
                    "cip.ref = pi.id
3757
                        AND cip.tool = :cip_tool
3758
                        AND cip.course = pi.course
3759
                        AND cip.lasteditType = 'visible'
3760
                        AND cip.toUser = :current_user"
3761
                )
3762
                ->andWhere(
3763
                    sprintf(
3764
                        'pi.visibility = %d
3765
                            OR (
3766
                                pi.visibility = %d AND cip IS NOT NULL OR pi.user = :current_user
3767
                            )',
3768
                        Portfolio::VISIBILITY_VISIBLE,
3769
                        Portfolio::VISIBILITY_PER_USER
3770
                    )
3771
                )
3772
                ->setParameter('cip_tool', TOOL_PORTFOLIO)
3773
            ;
3774
        } else {
3775
            $visibilityCriteria = [Portfolio::VISIBILITY_VISIBLE];
3776
3777
            if (api_is_allowed_to_edit()) {
3778
                $visibilityCriteria[] = Portfolio::VISIBILITY_HIDDEN_EXCEPT_TEACHER;
3779
            }
3780
3781
            $queryBuilder->andWhere(
3782
                $queryBuilder->expr()->orX(
3783
                    'pi.user = :current_user',
3784
                    $queryBuilder->expr()->andX(
3785
                        'pi.user != :current_user',
3786
                        $queryBuilder->expr()->in('pi.visibility', $visibilityCriteria)
3787
                    )
3788
                )
3789
            );
3790
        }
3791
3792
        $queryBuilder->setParameter('current_user', api_get_user_id());
3793
        $queryBuilder->orderBy('pi.creationDate', 'DESC');
3794
3795
        return $queryBuilder->getQuery()->getResult();
3796
    }
3797
3798
    private function getItemsForIndex(
3799
        bool $listByUser = false,
3800
        FormValidator $frmFilterList = null,
3801
        bool $alphabeticalOrder = false
3802
    ) {
3803
        $currentUserId = api_get_user_id();
3804
3805
        $portfolioRepo = Container::getPortfolioRepository();
3806
3807
        if ($this->course) {
3808
            $showBaseContentInSession = $this->session
3809
                && 'true' === api_get_setting('platform.portfolio_show_base_course_post_in_sessions');
3810
3811
            $portfolioCategoryHelper = Container::getPortfolioCategoryHelper();
3812
3813
            $filters = $frmFilterList && $frmFilterList->validate() ? $frmFilterList->exportValues() : [];
3814
3815
            $searchInCategories = [];
3816
3817
            if ($categoryId = $filters['categoryId'] ?? null) {
3818
                $searchInCategories[] = $categoryId;
3819
3820
                foreach ($portfolioCategoryHelper->getListForIndex($categoryId) as $subCategory) {
3821
                    $searchInCategories[] = $subCategory->getId();
3822
                }
3823
            }
3824
3825
            $searchNotInCategories = [];
3826
3827
            if ($subCategoryIdList = $filters['subCategoryIds'] ?? '') {
3828
                $diff = [];
3829
3830
                if ('all' !== $subCategoryIdList) {
3831
                    $subCategoryIds = explode(',', $subCategoryIdList);
3832
                    $diff = array_diff($searchInCategories, $subCategoryIds);
3833
                } elseif (trim($subCategoryIdList) === '') {
3834
                    $diff = $searchInCategories;
3835
                }
3836
3837
                if (!empty($diff)) {
3838
                    unset($diff[0]);
3839
3840
                    $searchNotInCategories = $diff;
3841
                }
3842
            }
3843
3844
            $items = $portfolioRepo->getIndexCourseItems(
3845
                api_get_user_entity(),
3846
                $this->owner,
3847
                $this->course,
3848
                $this->session,
3849
                $showBaseContentInSession,
3850
                $listByUser,
3851
                $filters['date'] ?? null,
3852
                $filters['tags'] ?? [],
3853
                $filters['text'] ?? '',
3854
                $searchInCategories,
3855
                $searchNotInCategories,
3856
                $this->advancedSharingEnabled
3857
            );
3858
3859
            if ($showBaseContentInSession) {
3860
                $items = array_filter(
3861
                    $items,
3862
                    function (Portfolio $item) {
3863
                        $itemResourceLink = $item->getFirstResourceLink();
3864
3865
                        return !($this->session && !$itemResourceLink?->getSession()
3866
                            && $item->isDuplicatedInSession($this->session));
3867
                    }
3868
                );
3869
            }
3870
3871
            return $items;
3872
        } else {
3873
            $queryBuilder = $portfolioRepo->getResourcesByCreator($this->owner);
3874
            $queryBuilder->andWhere($queryBuilder->expr()->isNull('resource.category'));
3875
3876
            if ($currentUserId !== $this->owner->getId()) {
3877
                $queryBuilder
3878
                    ->andWhere($queryBuilder->expr()->eq('resource.visibility', ':visible'))
3879
                    ->setParameter('visible', Portfolio::VISIBILITY_VISIBLE)
3880
                ;
3881
            }
3882
3883
            $items = $queryBuilder
3884
                ->orderBy('node.createdAt', 'DESC')
3885
                ->getQuery()
3886
                ->getResult()
3887
            ;
3888
        }
3889
3890
        return $items;
3891
    }
3892
3893
    /**
3894
     * @throws \Doctrine\ORM\ORMException
3895
     * @throws \Doctrine\ORM\OptimisticLockException
3896
     * @throws \Doctrine\ORM\TransactionRequiredException
3897
     */
3898
    private function createCommentForm(Portfolio $item): string
3899
    {
3900
        $formAction = $this->baseUrl.http_build_query(['action' => 'view', 'id' => $item->getId()]);
3901
        $templates = Container::getPortfolioCommentRepository()->findTemplatesByUser($this->owner);
3902
3903
        $form = new FormValidator('frm_comment', 'post', $formAction);
3904
        $form->addHeader(get_lang('Add a new comment'));
3905
        $form->addSelectFromCollection(
3906
            'template',
3907
            [
3908
                get_lang('Template'),
3909
                null,
3910
                '<span id="portfolio-spinner" class="fa fa-fw fa-spinner fa-spin" style="display: none;"
3911
                    aria-hidden="true" aria-label="'.get_lang('Loading').'"></span>',
3912
            ],
3913
            $templates,
3914
            [],
3915
            true,
3916
            'getExcerpt'
3917
        );
3918
        $form->addHtmlEditor('content', get_lang('Comments'), true, false, ['ToolbarSet' => 'Minimal']);
3919
        $form->addHidden('item', $item->getId());
3920
        $form->addHidden('parent', 0);
3921
        $form->applyFilter('content', 'trim');
3922
3923
        $this->addAttachmentsFieldToForm($form);
3924
3925
        $form->addButtonSave(get_lang('Save'));
3926
3927
        $itemResourceLink = $item->getFirstResourceLink();
3928
3929
        if ($form->validate()) {
3930
            if ($this->session
3931
                && true === api_get_configuration_value('portfolio_show_base_course_post_in_sessions')
3932
                && !$itemResourceLink->getSession()
3933
            ) {
3934
                $duplicate = $item->duplicateInSession($this->session);
3935
3936
                $this->em->persist($duplicate);
3937
                $this->em->flush();
3938
3939
                $item = $duplicate;
3940
3941
                $formAction = $this->baseUrl.http_build_query(['action' => 'view', 'id' => $item->getId()]);
3942
            }
3943
3944
            $values = $form->exportValues();
3945
3946
            $parentComment = $this->em->find(PortfolioComment::class, $values['parent']);
3947
3948
            $comment = new PortfolioComment();
3949
            $comment
3950
                ->setCreator($this->owner)
3951
                ->setParent($parentComment ?: $item)
3952
                ->setContent($values['content'])
3953
                ->setDate(api_get_utc_datetime(null, false, true))
3954
                ->setItem($item);
3955
3956
            $this->em->persist($comment);
3957
            $this->em->flush();
3958
3959
            $this->processAttachments(
3960
                $form,
3961
                $this->owner,
3962
                $comment->getId(),
3963
                Portfolio::TYPE_COMMENT
3964
            );
3965
3966
            Container::getEventDispatcher()->dispatch(
3967
                new PortfolioItemCommentedEvent(['comment' => $comment]),
3968
                Events::PORTFOLIO_ITEM_COMMENTED
3969
            );
3970
3971
            PortfolioNotifier::notifyTeachersAndAuthor($comment);
3972
3973
            Display::addFlash(
3974
                Display::return_message(get_lang('You comment has been added'), 'success')
3975
            );
3976
3977
            header("Location: $formAction");
3978
            exit;
3979
        }
3980
3981
        $js = '<script>
3982
            $(function() {
3983
                $(\'#frm_comment_template\').on(\'change\', function () {
3984
                    $(\'#portfolio-spinner\').show();
3985
3986
                    $.getJSON(_p.web_ajax + \'portfolio.ajax.php?a=find_template_comment&comment=\' + this.value)
3987
                        .done(function(response) {
3988
                            CKEDITOR.instances.content.setData(response.content);
3989
                        })
3990
                        .fail(function () {
3991
                            CKEDITOR.instances.content.setData(\'\');
3992
                        })
3993
                        .always(function() {
3994
                          $(\'#portfolio-spinner\').hide();
3995
                        });
3996
                });
3997
            });
3998
        </script>';
3999
4000
        return $form->returnForm().$js;
4001
    }
4002
4003
    private function generateAttachmentList(Portfolio|PortfolioComment $post, bool $includeHeader = true): string
4004
    {
4005
        $attachments = $post->resourceNode->getResourceFiles();
4006
4007
        $postOwnerId = $post->getCreator()?->getId();
4008
4009
        if (!$attachments->count()) {
4010
            return '';
4011
        }
4012
4013
        $currentUserId = api_get_user_id();
4014
4015
        $listItems = '<ul class="fa-ul">';
4016
4017
        $deleteIcon = Display::getMdiIcon(ActionIcon::DELETE, 'ch-tool-icon', 'display: inline-block', ICON_SIZE_MEDIUM, get_lang('Delete attachment'));
4018
        $deleteAttrs = ['class' => 'btn-portfolio-delete'];
4019
4020
        foreach ($attachments as $attachment) {
4021
            $downloadParams = http_build_query(['action' => 'download_attachment', 'node_id' => $post->resourceNode->getId()]);
4022
            $deleteParams = http_build_query(['action' => 'delete_attachment', 'node_id' => $post->resourceNode->getId()]);
4023
4024
            $listItems .= '<li>'
4025
                .'<span class="fa-li fa fa-paperclip" aria-hidden="true"></span>'
4026
                .Display::url(
4027
                    Security::remove_XSS($attachment->getOriginalName()),
4028
                    $this->baseUrl.$downloadParams
4029
                );
4030
4031
            if ($currentUserId === $postOwnerId) {
4032
                $listItems .= PHP_EOL.Display::url($deleteIcon, $this->baseUrl.$deleteParams, $deleteAttrs);
4033
            }
4034
4035
            if ($fileDescription = $attachment->getDescription()) {
4036
                $listItems .= '<p class="text-muted">'.Security::remove_XSS($fileDescription).'</p>';
4037
            }
4038
4039
            $listItems .= '</li>';
4040
        }
4041
4042
        $listItems .= '</ul>';
4043
4044
        if ($includeHeader) {
4045
            $listItems = '<h1 class="h4">'.get_lang('Files attachments').'</h1>'
4046
                .$listItems;
4047
        }
4048
4049
        return $listItems;
4050
    }
4051
4052
    private function generateItemContent(Portfolio $item): string
4053
    {
4054
        $originId = $item->getOrigin();
4055
4056
        if (empty($originId)) {
4057
            return $item->getContent();
4058
        }
4059
4060
        $em = Database::getManager();
4061
4062
        $originContent = '';
4063
        $originContentFooter = '';
4064
4065
        if (Portfolio::TYPE_ITEM === $item->getOriginType()) {
4066
            $origin = $em->find(Portfolio::class, $item->getOrigin());
4067
4068
            if ($origin) {
4069
                $originContent = Security::remove_XSS($origin->getContent());
4070
                $originContentFooter = vsprintf(
4071
                    get_lang('Originally published as "%s" by %s'),
4072
                    [
4073
                        "<cite>{$origin->getTitle(true)}</cite>",
4074
                        $origin->getUser()->getFullName(),
4075
                    ]
4076
                );
4077
            }
4078
        } elseif (Portfolio::TYPE_COMMENT === $item->getOriginType()) {
4079
            $origin = $em->find(PortfolioComment::class, $item->getOrigin());
4080
4081
            if ($origin) {
4082
                $originContent = Security::remove_XSS($origin->getContent());
4083
                $originContentFooter = vsprintf(
4084
                    get_lang('Originally commented by %s in "%s"'),
4085
                    [
4086
                        $origin->getAuthor()->getFullName(),
4087
                        "<cite>{$origin->getItem()->getTitle(true)}</cite>",
4088
                    ]
4089
                );
4090
            }
4091
        }
4092
4093
        if ($originContent) {
4094
            return "<figure>
4095
                    <blockquote>$originContent</blockquote>
4096
                    <figcaption style=\"margin-bottom: 10px;\">$originContentFooter</figcaption>
4097
                </figure>
4098
                <div class=\"clearfix\">".Security::remove_XSS($item->getContent()).'</div>'
4099
            ;
4100
        }
4101
4102
        return Security::remove_XSS($item->getContent());
4103
    }
4104
4105
    private function getItemsInHtmlFormatted(array $items): array
4106
    {
4107
        $itemsHtml = [];
4108
4109
        /** @var Portfolio $item */
4110
        foreach ($items as $item) {
4111
            $itemCourse = $item->getCourse();
4112
            $itemSession = $item->getSession();
4113
4114
            $creationDate = api_convert_and_format_date($item->getCreationDate());
4115
            $updateDate = api_convert_and_format_date($item->getUpdateDate());
4116
4117
            $metadata = '<ul class="list-unstyled text-muted">';
4118
4119
            if ($itemSession) {
4120
                $metadata .= '<li>'.get_lang('Course').': '.$itemSession->getTitle().' ('
4121
                    .$itemCourse->getTitle().') </li>';
4122
            } elseif ($itemCourse) {
4123
                $metadata .= '<li>'.get_lang('Course').': '.$itemCourse->getTitle().'</li>';
4124
            }
4125
4126
            $metadata .= '<li>'.sprintf(get_lang('Creation date: %s'), $creationDate).'</li>';
4127
4128
            if ($itemCourse) {
4129
                $propertyInfo = api_get_item_property_info(
4130
                    $itemCourse->getId(),
4131
                    TOOL_PORTFOLIO,
4132
                    $item->getId(),
4133
                    $itemSession ? $itemSession->getId() : 0
4134
                );
4135
4136
                if ($propertyInfo) {
4137
                    $metadata .= '<li>'
4138
                        .sprintf(
4139
                            get_lang('Updated on %s by %s'),
4140
                            api_convert_and_format_date($propertyInfo['lastedit_date'], DATE_TIME_FORMAT_LONG),
4141
                            api_get_user_entity($propertyInfo['lastedit_user_id'])->getFullName()
4142
                        )
4143
                        .'</li>';
4144
                }
4145
            } else {
4146
                $metadata .= '<li>'.sprintf(get_lang('Update date: %s'), $updateDate).'</li>';
4147
            }
4148
4149
            if ($item->getCategory()) {
4150
                $metadata .= '<li>'.sprintf(get_lang('Category: %s'), $item->getCategory()->getTitle()).'</li>';
4151
            }
4152
4153
            $metadata .= '</ul>';
4154
4155
            $itemContent = $this->generateItemContent($item);
4156
4157
            $itemsHtml[] = Display::panel($itemContent, Security::remove_XSS($item->getTitle()), '', 'info', $metadata);
4158
        }
4159
4160
        return $itemsHtml;
4161
    }
4162
4163
    private function getCommentsInHtmlFormatted(array $comments): array
4164
    {
4165
        $commentsHtml = [];
4166
4167
        /** @var PortfolioComment $comment */
4168
        foreach ($comments as $comment) {
4169
            $item = $comment->getItem();
4170
            $date = api_convert_and_format_date($comment->getDate());
4171
4172
            $metadata = '<ul class="list-unstyled text-muted">';
4173
            $metadata .= '<li>'.sprintf(get_lang('Date: %s'), $date).'</li>';
4174
            $metadata .= '<li>'.sprintf(get_lang('Item title: %s'), Security::remove_XSS($item->getTitle()))
4175
                .'</li>';
4176
            $metadata .= '</ul>';
4177
4178
            $commentsHtml[] = Display::panel(
4179
                Security::remove_XSS($comment->getContent()),
4180
                '',
4181
                '',
4182
                'default',
4183
                $metadata
4184
            );
4185
        }
4186
4187
        return $commentsHtml;
4188
    }
4189
4190
    /**
4191
     * @param string $htmlContent
4192
     * @param array $imagePaths Relative paths found in $htmlContent
4193
     *
4194
     * @return string
4195
     */
4196
    private function fixMediaSourcesToHtml(string $htmlContent, array &$imagePaths): string
4197
    {
4198
        $doc = new DOMDocument();
4199
        @$doc->loadHTML($htmlContent);
4200
4201
        $tagsWithSrc = ['img', 'video', 'audio', 'source'];
4202
        /** @var array<int, \DOMElement> $elements */
4203
        $elements = [];
4204
4205
        foreach ($tagsWithSrc as $tag) {
4206
            foreach ($doc->getElementsByTagName($tag) as $element) {
4207
                if ($element->hasAttribute('src')) {
4208
                    $elements[] = $element;
4209
                }
4210
            }
4211
        }
4212
4213
        if (empty($elements)) {
4214
            return $htmlContent;
4215
        }
4216
4217
        /** @var array<int, \DOMElement> $anchorElements */
4218
        $anchorElements = $doc->getElementsByTagName('a');
4219
4220
        $webPath = api_get_path(WEB_PATH);
4221
        $sysPath = rtrim(api_get_path(SYS_PATH), '/');
4222
4223
        $paths = [
4224
            '/app/upload/' => $sysPath,
4225
            '/courses/' => $sysPath.'/app'
4226
        ];
4227
4228
        foreach ($elements as $element) {
4229
            $src = trim($element->getAttribute('src'));
4230
4231
            if (!str_starts_with($src, '/')
4232
                && !str_starts_with($src, $webPath)
4233
            ) {
4234
                continue;
4235
            }
4236
4237
            // to search anchors linking to files
4238
            if ($anchorElements->length > 0) {
4239
                foreach ($anchorElements as $anchorElement) {
4240
                    if (!$anchorElement->hasAttribute('href')) {
4241
                        continue;
4242
                    }
4243
4244
                    if ($src === $anchorElement->getAttribute('href')) {
4245
                        $anchorElement->setAttribute('href', basename($src));
4246
                    }
4247
                }
4248
            }
4249
4250
            $src = str_replace($webPath, '/', $src);
4251
4252
            foreach ($paths as $prefix => $basePath) {
4253
                if (str_starts_with($src, $prefix)) {
4254
                    $imagePaths[] = $basePath.urldecode($src);
4255
                    $element->setAttribute('src', basename($src));
4256
                }
4257
            }
4258
        }
4259
4260
        return $doc->saveHTML();
4261
    }
4262
4263
    private function formatZipIndexFile(HTML_Table $tblItems, HTML_Table $tblComments): string
4264
    {
4265
        $htmlContent = Display::page_header($this->owner->getFullNameWithUsername());
4266
        $htmlContent .= Display::page_subheader2(get_lang('Portfolio items'));
4267
4268
        $htmlContent .= $tblItems->getRowCount() > 0
4269
            ? $tblItems->toHtml()
4270
            : Display::return_message(get_lang('No items in your portfolio'), 'warning');
4271
4272
        $htmlContent .= Display::page_subheader2(get_lang('Comments made'));
4273
4274
        $htmlContent .= $tblComments->getRowCount() > 0
4275
            ? $tblComments->toHtml()
4276
            : Display::return_message(get_lang('You have not commented'), 'warning');
4277
4278
        $webAssetsPath = api_get_path(WEB_PUBLIC_PATH).'assets/';
4279
4280
        $doc = new DOMDocument();
4281
        @$doc->loadHTML($htmlContent);
4282
4283
        $stylesheet1 = $doc->createElement('link');
4284
        $stylesheet1->setAttribute('rel', 'stylesheet');
4285
        $stylesheet1->setAttribute('href', $webAssetsPath.'bootstrap/dist/css/bootstrap.min.css');
4286
        $stylesheet2 = $doc->createElement('link');
4287
        $stylesheet2->setAttribute('rel', 'stylesheet');
4288
        $stylesheet2->setAttribute('href', $webAssetsPath.'fontawesome/css/font-awesome.min.css');
4289
        $stylesheet3 = $doc->createElement('link');
4290
        $stylesheet3->setAttribute('rel', 'stylesheet');
4291
        $stylesheet3->setAttribute('href', ChamiloApi::getEditorDocStylePath());
4292
4293
        $head = $doc->createElement('head');
4294
        $head->appendChild($stylesheet1);
4295
        $head->appendChild($stylesheet2);
4296
        $head->appendChild($stylesheet3);
4297
4298
        $doc->documentElement->insertBefore(
4299
            $head,
4300
            $doc->getElementsByTagName('body')->item(0)
4301
        );
4302
4303
        return $doc->saveHTML();
4304
    }
4305
4306
    /**
4307
     * It parsers a title for a variable in lang.
4308
     *
4309
     * @param $defaultDisplayText
4310
     *
4311
     * @return string
4312
     */
4313
    private function getLanguageVariable($defaultDisplayText)
4314
    {
4315
        $variableLanguage = api_replace_dangerous_char(strtolower($defaultDisplayText));
4316
        $variableLanguage = preg_replace('/[^A-Za-z0-9\_]/', '', $variableLanguage); // Removes special chars except underscore.
4317
        if (is_numeric($variableLanguage[0])) {
4318
            $variableLanguage = '_'.$variableLanguage;
4319
        }
4320
        $variableLanguage = api_underscore_to_camel_case($variableLanguage);
4321
4322
        return $variableLanguage;
4323
    }
4324
4325
    /**
4326
     * It translates the text as parameter.
4327
     *
4328
     * @param $defaultDisplayText
4329
     *
4330
     * @return mixed
4331
     */
4332
    private function translateDisplayName($defaultDisplayText)
4333
    {
4334
        $variableLanguage = $this->getLanguageVariable($defaultDisplayText);
4335
4336
        return isset($GLOBALS[$variableLanguage]) ? $GLOBALS[$variableLanguage] : $defaultDisplayText;
4337
    }
4338
4339
    private function getCommentsForIndex(FormValidator $frmFilterList = null): array
4340
    {
4341
        if (null === $frmFilterList) {
4342
            return [];
4343
        }
4344
4345
        if (!$frmFilterList->validate()) {
4346
            return [];
4347
        }
4348
4349
        $values = $frmFilterList->exportValues();
4350
4351
        if (empty($values['date']) && empty($values['text'])) {
4352
            return [];
4353
        }
4354
4355
        $commentsRepo = Container::getPortfolioCommentRepository();
4356
        $queryBuilder = $commentsRepo->getResources();
4357
4358
        if (!empty($values['date'])) {
4359
            $queryBuilder
4360
                ->andWhere($queryBuilder->expr()->gte('node.createdAt', ':date'))
4361
                ->setParameter(':date', api_get_utc_datetime($values['date'], false, true))
4362
            ;
4363
        }
4364
4365
        if (!empty($values['text'])) {
4366
            $queryBuilder
4367
                ->andWhere($queryBuilder->expr()->like('resource.content', ':text'))
4368
                ->setParameter('text', '%'.$values['text'].'%')
4369
            ;
4370
        }
4371
4372
        if ($this->advancedSharingEnabled) {
4373
            // @todo change to left join with resource_link to get resources with advanced sharing
4374
            if ($this->course) {
4375
                $queryBuilder
4376
                    ->andWhere($queryBuilder->expr()->eq('links.course', ':course'))
4377
                    ->setParameter('course', $this->course->getId())
4378
                ;
4379
            }
4380
4381
            $queryBuilder
4382
                ->andWhere($queryBuilder->expr()->eq('links.user', ':current_user'))
4383
                ->andWhere(
4384
                    $queryBuilder->expr()->orX(
4385
                        $queryBuilder->expr()->eq('resource.visibility', Portfolio::VISIBILITY_VISIBLE),
4386
                        $queryBuilder->expr()->andX(
4387
                            $queryBuilder->expr()->eq('resource.visibility', Portfolio::VISIBILITY_PER_USER),
4388
                            $queryBuilder->expr()->eq('node.creator', ':current_user')
4389
                        )
4390
                    )
4391
                )
4392
                ->setParameter('current_user', $this->owner->getId())
4393
            ;
4394
        }
4395
4396
        $queryBuilder->orderBy('node.createdAt', 'DESC');
4397
4398
        return $queryBuilder->getQuery()->getResult();
4399
    }
4400
4401
    private function getLabelForCommentDate(PortfolioComment $comment): string
4402
    {
4403
        $item = $comment->getItem();
4404
        $commmentCourse = $item->getCourse();
4405
        $commmentSession = $item->getSession();
4406
4407
        $dateLabel = Display::dateToStringAgoAndLongDate($comment->getDate()).PHP_EOL;
4408
4409
        if ($commmentCourse) {
4410
            $propertyInfo = api_get_item_property_info(
4411
                $commmentCourse->getId(),
4412
                TOOL_PORTFOLIO_COMMENT,
4413
                $comment->getId(),
4414
                $commmentSession ? $commmentSession->getId() : 0
4415
            );
4416
4417
            if ($propertyInfo) {
4418
                $dateLabel .= '|'.PHP_EOL
4419
                    .sprintf(
4420
                        get_lang('Updated %s'),
4421
                        Display::dateToStringAgoAndLongDate($propertyInfo['lastedit_date'])
4422
                    );
4423
            }
4424
        }
4425
4426
        return $dateLabel;
4427
    }
4428
}
4429