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

PortfolioController::generateAttachmentList()   B

Complexity

Conditions 8
Paths 33

Size

Total Lines 63
Code Lines 36

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 36
c 0
b 0
f 0
dl 0
loc 63
rs 8.0995
cc 8
nc 33
nop 2

How to fix   Long Method   

Long Method

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

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

Commonly applied refactorings include:

1
<?php
2
3
/* For licensing terms, see /license.txt */
4
5
use Chamilo\CoreBundle\Component\Utils\ChamiloApi;
6
use Chamilo\CoreBundle\Entity\Course as CourseEntity;
7
use Chamilo\CoreBundle\Entity\ExtraField as ExtraFieldEntity;
8
use Chamilo\CoreBundle\Entity\ExtraFieldRelTag;
9
use Chamilo\CoreBundle\Entity\Portfolio;
10
use Chamilo\CoreBundle\Entity\PortfolioAttachment;
11
use Chamilo\CoreBundle\Entity\PortfolioCategory;
12
use Chamilo\CoreBundle\Entity\PortfolioComment;
13
use Chamilo\CoreBundle\Entity\PortfolioRelTag;
14
use Chamilo\CoreBundle\Entity\Tag;
15
use Chamilo\UserBundle\Entity\User;
16
use Doctrine\ORM\Query\Expr\Join;
17
use Mpdf\MpdfException;
18
use Symfony\Component\Filesystem\Filesystem;
19
use Symfony\Component\HttpFoundation\Request as HttpRequest;
0 ignored issues
show
Bug introduced by
This use statement conflicts with another class in this namespace, HttpRequest. Consider defining an alias.

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

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

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

// Bar.php
namespace OtherDir;

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

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

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

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

// Bar.php
namespace OtherDir;

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

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

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

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
576
577
                    $teachers = SessionManager::getCoachesByCourseSession(
578
                        $this->session->getId(),
579
                        $this->course->getId()
580
                    );
581
                    $userIdListToSend = array_values($teachers);
582
                } else {
583
                    $messageCourseTitle = $this->course->getTitle();
584
585
                    $teachers = CourseManager::get_teacher_list_from_course_code($this->course->getCode());
586
587
                    $userIdListToSend = array_keys($teachers);
588
                }
589
590
                $messageSubject = sprintf(get_lang('PortfolioAlertNewPostSubject'), $messageCourseTitle);
591
                $messageContent = sprintf(
592
                    get_lang('PortfolioAlertNewPostContent'),
593
                    $this->owner->getCompleteName(),
594
                    $messageCourseTitle,
595
                    $this->baseUrl.http_build_query(['action' => 'view', 'id' => $portfolio->getId()])
596
                );
597
                $messageContent .= '<br><br><dl>'
598
                    .'<dt>'.Security::remove_XSS($portfolio->getTitle()).'</dt>'
599
                    .'<dd>'.$portfolio->getExcerpt().'</dd>'.'</dl>';
600
601
                foreach ($userIdListToSend as $userIdToSend) {
602
                    MessageManager::send_message_simple(
603
                        $userIdToSend,
604
                        $messageSubject,
605
                        $messageContent,
606
                        0,
607
                        false,
608
                        false,
609
                        [],
610
                        false
611
                    );
612
                }
613
            }
614
615
            Display::addFlash(
616
                Display::return_message(get_lang('PortfolioItemAdded'), 'success')
617
            );
618
619
            header("Location: $this->baseUrl");
620
            exit;
621
        }
622
623
        $interbreadcrumb[] = [
624
            'name' => get_lang('Portfolio'),
625
            'url' => $this->baseUrl,
626
        ];
627
628
        $actions = [];
629
        $actions[] = Display::url(
630
            Display::return_icon('back.png', get_lang('Back'), [], ICON_SIZE_MEDIUM),
631
            $this->baseUrl
632
        );
633
        $actions[] = '<a id="hide_bar_template" href="#" role="button">'.
634
            Display::return_icon('expand.png', get_lang('Expand'), ['id' => 'expand'], ICON_SIZE_MEDIUM).
635
            Display::return_icon('contract.png', get_lang('Collapse'), ['id' => 'contract', 'class' => 'hide'], ICON_SIZE_MEDIUM).'</a>';
636
637
        $js = '<script>
638
            $(function() {
639
                $(".scrollbar-light").scrollbar();
640
                $(".scroll-wrapper").css("height", "550px");
641
                expandColumnToogle("#hide_bar_template", {
642
                    selector: "#template_col",
643
                    width: 3
644
                }, {
645
                    selector: "#doc_form",
646
                    width: 9
647
                });
648
                CKEDITOR.on("instanceReady", function (e) {
649
                    showTemplates();
650
                });
651
                $(window).on("load", function () {
652
                    $("input[name=\'title\']").focus();
653
                });
654
                $(\'#add_portfolio_template\').on(\'change\', function () {
655
                    $(\'#portfolio-spinner\').show();
656
                
657
                    $.getJSON(_p.web_ajax + \'portfolio.ajax.php?a=find_template&item=\' + this.value)
658
                        .done(function(response) {
659
                            if (CKEDITOR.instances.title) {
660
                                CKEDITOR.instances.title.setData(response.title);
661
                            } else {
662
                                document.getElementById(\'add_portfolio_title\').value = response.title;
663
                            }
664
665
                            CKEDITOR.instances.content.setData(response.content);
666
                        })
667
                        .fail(function () {
668
                            if (CKEDITOR.instances.title) {
669
                                CKEDITOR.instances.title.setData(\'\');
670
                            } else {
671
                                document.getElementById(\'add_portfolio_title\').value = \'\';
672
                            }
673
674
                            CKEDITOR.instances.content.setData(\'\');
675
                        })
676
                        .always(function() {
677
                          $(\'#portfolio-spinner\').hide();
678
                        });
679
                });
680
                '.$extra['jquery_ready_content'].'
681
            });
682
        </script>';
683
        $content = '<div class="page-create">
684
            <div class="row" style="overflow:hidden">
685
            <div id="template_col" class="col-md-3">
686
                <div class="panel panel-default">
687
                <div class="panel-body">
688
                    <div id="frmModel" class="items-templates scrollbar-light"></div>
689
                </div>
690
                </div>
691
            </div>
692
            <div id="doc_form" class="col-md-9">
693
                '.$form->returnForm().'
694
            </div>
695
          </div></div>';
696
697
        $this->renderView(
698
            $content.$js,
699
            get_lang('AddPortfolioItem'),
700
            $actions
701
        );
702
    }
703
704
    /**
705
     * @throws \Doctrine\ORM\ORMException
706
     * @throws \Doctrine\ORM\OptimisticLockException
707
     * @throws \Doctrine\ORM\TransactionRequiredException
708
     * @throws \Exception
709
     */
710
    public function editItem(Portfolio $item)
711
    {
712
        global $interbreadcrumb;
713
714
        if (!api_is_allowed_to_edit() && !$this->itemBelongToOwner($item)) {
715
            api_not_allowed(true);
716
        }
717
718
        $itemCourse = $item->getCourse();
719
        $itemSession = $item->getSession();
720
721
        $form = new FormValidator('edit_portfolio', 'post', $this->baseUrl."action=edit_item&id={$item->getId()}");
722
723
        if (api_get_configuration_value('save_titles_as_html')) {
724
            $form->addHtmlEditor('title', get_lang('Title'), true, false, ['ToolbarSet' => 'TitleAsHtml']);
725
        } else {
726
            $form->addText('title', get_lang('Title'));
727
            $form->applyFilter('title', 'trim');
728
        }
729
730
        if ($item->getOrigin()) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $item->getOrigin() of type integer|null is loosely compared to true; this is ambiguous if the integer can be 0. You might want to explicitly use !== null instead.

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

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

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

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

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

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

}

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

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

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

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

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

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

Loading history...
2898
            $actions = implode('', $actions);
2899
2900
            $actionsStr .= Display::toolbarAction('portfolio-toolbar', [$actions]);
2901
        }
2902
2903
        $view->assign('baseurl', $this->baseUrl);
2904
        $view->assign('actions', $actionsStr);
2905
2906
        $view->assign('content', $content);
2907
        $view->display_one_col_template();
2908
    }
2909
2910
    private function categoryBelongToOwner(PortfolioCategory $category): bool
2911
    {
2912
        if ($category->getUser()->getId() != $this->owner->getId()) {
2913
            return false;
2914
        }
2915
2916
        return true;
2917
    }
2918
2919
    private function addAttachmentsFieldToForm(FormValidator $form)
2920
    {
2921
        $form->addButton('add_attachment', get_lang('AddAttachment'), 'plus');
2922
        $form->addHtml('<div id="container-attachments" style="display: none;">');
2923
        $form->addFile('attachment_file[]', get_lang('FilesAttachment'));
2924
        $form->addText('attachment_comment[]', get_lang('Description'), false);
2925
        $form->addHtml('</div>');
2926
2927
        $script = "$(function () {
2928
            var attachmentsTemplate = $('#container-attachments').html();
2929
            var \$btnAdd = $('[name=\"add_attachment\"]');
2930
            var \$reference = \$btnAdd.parents('.form-group');
2931
2932
            \$btnAdd.on('click', function (e) {
2933
                e.preventDefault();
2934
2935
                $(attachmentsTemplate).insertBefore(\$reference);
2936
            });
2937
        })";
2938
2939
        $form->addHtml("<script>$script</script>");
2940
    }
2941
2942
    private function processAttachments(
2943
        FormValidator $form,
2944
        User $user,
2945
        int $originId,
2946
        int $originType
2947
    ) {
2948
        $em = Database::getManager();
2949
        $fs = new Filesystem();
2950
2951
        $comments = $form->getSubmitValue('attachment_comment');
2952
2953
        foreach ($_FILES['attachment_file']['error'] as $i => $attachmentFileError) {
2954
            if ($attachmentFileError != UPLOAD_ERR_OK) {
2955
                continue;
2956
            }
2957
2958
            $_file = [
2959
                'name' => $_FILES['attachment_file']['name'][$i],
2960
                'type' => $_FILES['attachment_file']['type'][$i],
2961
                'tmp_name' => $_FILES['attachment_file']['tmp_name'][$i],
2962
                'size' => $_FILES['attachment_file']['size'][$i],
2963
            ];
2964
2965
            if (empty($_file['type'])) {
2966
                $_file['type'] = DocumentManager::file_get_mime_type($_file['name']);
2967
            }
2968
2969
            $newFileName = add_ext_on_mime(stripslashes($_file['name']), $_file['type']);
2970
2971
            if (!filter_extension($newFileName)) {
2972
                Display::addFlash(Display::return_message(get_lang('UplUnableToSaveFileFilteredExtension'), 'error'));
2973
                continue;
2974
            }
2975
2976
            $newFileName = uniqid();
2977
            $attachmentsDirectory = UserManager::getUserPathById($user->getId(), 'system').'portfolio_attachments/';
2978
2979
            if (!$fs->exists($attachmentsDirectory)) {
2980
                $fs->mkdir($attachmentsDirectory, api_get_permissions_for_new_directories());
2981
            }
2982
2983
            $attachmentFilename = $attachmentsDirectory.$newFileName;
2984
2985
            if (is_uploaded_file($_file['tmp_name'])) {
2986
                $moved = move_uploaded_file($_file['tmp_name'], $attachmentFilename);
2987
2988
                if (!$moved) {
2989
                    Display::addFlash(Display::return_message(get_lang('UplUnableToSaveFile'), 'error'));
2990
                    continue;
2991
                }
2992
            }
2993
2994
            $attachment = new PortfolioAttachment();
2995
            $attachment
2996
                ->setFilename($_file['name'])
2997
                ->setComment($comments[$i])
2998
                ->setPath($newFileName)
2999
                ->setOrigin($originId)
3000
                ->setOriginType($originType)
3001
                ->setSize($_file['size']);
3002
3003
            $em->persist($attachment);
3004
            $em->flush();
3005
        }
3006
    }
3007
3008
    private function itemBelongToOwner(Portfolio $item): bool
3009
    {
3010
        if ($item->getUser()->getId() != $this->owner->getId()) {
3011
            return false;
3012
        }
3013
3014
        return true;
3015
    }
3016
3017
    private function commentBelongsToOwner(PortfolioComment $comment): bool
3018
    {
3019
        return $comment->getAuthor() === $this->owner;
3020
    }
3021
3022
    private function createFormTagFilter(bool $listByUser = false): FormValidator
3023
    {
3024
        $tags = Database::getManager()
3025
            ->getRepository(Tag::class)
3026
            ->findForPortfolioInCourseQuery($this->course, $this->session)
3027
            ->getQuery()
3028
            ->getResult()
3029
        ;
3030
3031
        $frmTagList = new FormValidator(
3032
            'frm_tag_list',
3033
            'get',
3034
            $this->baseUrl.($listByUser ? 'user='.$this->owner->getId() : ''),
3035
            '',
3036
            [],
3037
            FormValidator::LAYOUT_BOX
3038
        );
3039
3040
        $frmTagList->addDatePicker('date', get_lang('CreationDate'));
3041
3042
        $frmTagList->addSelectFromCollection(
3043
            'tags',
3044
            get_lang('Tags'),
3045
            $tags,
3046
            ['multiple' => 'multiple'],
3047
            false,
3048
            'getTag'
3049
        );
3050
3051
        $frmTagList->addText('text', get_lang('Search'), false)->setIcon('search');
3052
        $frmTagList->applyFilter('text', 'trim');
3053
        $frmTagList->addHtml('<br>');
3054
        $frmTagList->addButtonFilter(get_lang('Filter'));
3055
3056
        if ($this->course) {
3057
            $frmTagList->addHidden('cidReq', $this->course->getCode());
3058
            $frmTagList->addHidden('id_session', $this->session ? $this->session->getId() : 0);
3059
            $frmTagList->addHidden('gidReq', 0);
3060
            $frmTagList->addHidden('gradebook', 0);
3061
            $frmTagList->addHidden('origin', '');
3062
            $frmTagList->addHidden('categoryId', 0);
3063
            $frmTagList->addHidden('subCategoryIds', '');
3064
3065
            if ($listByUser) {
3066
                $frmTagList->addHidden('user', $this->owner->getId());
3067
            }
3068
        }
3069
3070
        return $frmTagList;
3071
    }
3072
3073
    /**
3074
     * @throws Exception
3075
     */
3076
    private function createFormStudentFilter(bool $listByUser = false, bool $listHighlighted = false): FormValidator
3077
    {
3078
        $frmStudentList = new FormValidator(
3079
            'frm_student_list',
3080
            'get',
3081
            $this->baseUrl,
3082
            '',
3083
            [],
3084
            FormValidator::LAYOUT_BOX
3085
        );
3086
3087
        $urlParams = http_build_query(
3088
            [
3089
                'a' => 'search_user_by_course',
3090
                'course_id' => $this->course->getId(),
3091
                'session_id' => $this->session ? $this->session->getId() : 0,
3092
            ]
3093
        );
3094
3095
        /** @var SelectAjax $slctUser */
3096
        $slctUser = $frmStudentList->addSelectAjax(
3097
            'user',
3098
            get_lang('SelectLearnerPortfolio'),
3099
            [],
3100
            [
3101
                'url' => api_get_path(WEB_AJAX_PATH)."course.ajax.php?$urlParams",
3102
                'placeholder' => get_lang('SearchStudent'),
3103
                'formatResult' => SelectAjax::templateResultForUsersInCourse(),
3104
                'formatSelection' => SelectAjax::templateSelectionForUsersInCourse(),
3105
            ]
3106
        );
3107
3108
        if ($listByUser) {
3109
            $slctUser->addOption(
3110
                $this->owner->getCompleteName(),
3111
                $this->owner->getId(),
3112
                [
3113
                    'data-avatarurl' => UserManager::getUserPicture($this->owner->getId()),
3114
                    'data-username' => $this->owner->getUsername(),
3115
                ]
3116
            );
3117
3118
            $link = Display::url(
3119
                get_lang('BackToMainPortfolio'),
3120
                $this->baseUrl
3121
            );
3122
        } else {
3123
            $link = Display::url(
3124
                get_lang('SeeMyPortfolio'),
3125
                $this->baseUrl.http_build_query(['user' => api_get_user_id()])
3126
            );
3127
        }
3128
3129
        $frmStudentList->addHtml("<p>$link</p>");
3130
3131
        if ($listHighlighted) {
3132
            $link = Display::url(
3133
                get_lang('BackToMainPortfolio'),
3134
                $this->baseUrl
3135
            );
3136
        } else {
3137
            $link = Display::url(
3138
                get_lang('SeeHighlights'),
3139
                $this->baseUrl.http_build_query(['list_highlighted' => true])
3140
            );
3141
        }
3142
3143
        $frmStudentList->addHtml("<p>$link</p>");
3144
3145
        return $frmStudentList;
3146
    }
3147
3148
    private function getCategoriesForIndex(?int $currentUserId = null, ?int $parentId = null): array
3149
    {
3150
        $categoriesCriteria = [];
3151
        if (isset($currentUserId)) {
3152
            $categoriesCriteria['user'] = $this->owner;
3153
        }
3154
        if (!api_is_platform_admin() && $currentUserId !== $this->owner->getId()) {
3155
            $categoriesCriteria['isVisible'] = true;
3156
        }
3157
        if (isset($parentId)) {
3158
            $categoriesCriteria['parentId'] = $parentId;
3159
        }
3160
3161
        return $this->em
3162
            ->getRepository(PortfolioCategory::class)
3163
            ->findBy($categoriesCriteria);
3164
    }
3165
3166
    private function getHighlightedItems()
3167
    {
3168
        $queryBuilder = $this->em->createQueryBuilder();
3169
        $queryBuilder
3170
            ->select('pi')
3171
            ->from(Portfolio::class, 'pi')
3172
            ->where('pi.course = :course')
3173
            ->andWhere('pi.isHighlighted = TRUE')
3174
            ->setParameter('course', $this->course);
3175
3176
        if ($this->session) {
3177
            $queryBuilder->andWhere('pi.session = :session');
3178
            $queryBuilder->setParameter('session', $this->session);
3179
        } else {
3180
            $queryBuilder->andWhere('pi.session IS NULL');
3181
        }
3182
3183
        $visibilityCriteria = [Portfolio::VISIBILITY_VISIBLE];
3184
3185
        if (api_is_allowed_to_edit()) {
3186
            $visibilityCriteria[] = Portfolio::VISIBILITY_HIDDEN_EXCEPT_TEACHER;
3187
        }
3188
3189
        $queryBuilder
3190
            ->andWhere(
3191
                $queryBuilder->expr()->orX(
3192
                    'pi.user = :current_user',
3193
                    $queryBuilder->expr()->andX(
3194
                        'pi.user != :current_user',
3195
                        $queryBuilder->expr()->in('pi.visibility', $visibilityCriteria)
3196
                    )
3197
                )
3198
            )
3199
            ->setParameter('current_user', api_get_user_id());
3200
3201
        $queryBuilder->orderBy('pi.creationDate', 'DESC');
3202
3203
        return $queryBuilder->getQuery()->getResult();
3204
    }
3205
3206
    private function getItemsForIndex(
3207
        bool $listByUser = false,
3208
        FormValidator $frmFilterList = null
3209
    ) {
3210
        $currentUserId = api_get_user_id();
3211
3212
        if ($this->course) {
3213
            $queryBuilder = $this->em->createQueryBuilder();
3214
            $queryBuilder
3215
                ->select('pi')
3216
                ->from(Portfolio::class, 'pi')
3217
                ->where('pi.course = :course');
3218
3219
            $queryBuilder->setParameter('course', $this->course);
3220
3221
            if ($this->session) {
3222
                $queryBuilder->andWhere('pi.session = :session');
3223
                $queryBuilder->setParameter('session', $this->session);
3224
            } else {
3225
                $queryBuilder->andWhere('pi.session IS NULL');
3226
            }
3227
3228
            if ($frmFilterList && $frmFilterList->validate()) {
3229
                $values = $frmFilterList->exportValues();
3230
3231
                if (!empty($values['date'])) {
3232
                    $queryBuilder
3233
                        ->andWhere('pi.creationDate >= :date')
3234
                        ->setParameter(':date', api_get_utc_datetime($values['date'], false, true))
3235
                    ;
3236
                }
3237
3238
                if (!empty($values['tags'])) {
3239
                    $queryBuilder
3240
                        ->innerJoin(ExtraFieldRelTag::class, 'efrt', Join::WITH, 'efrt.itemId = pi.id')
3241
                        ->innerJoin(ExtraFieldEntity::class, 'ef', Join::WITH, 'ef.id = efrt.fieldId')
3242
                        ->andWhere('ef.extraFieldType = :efType')
3243
                        ->andWhere('ef.variable = :variable')
3244
                        ->andWhere('efrt.tagId IN (:tags)');
3245
3246
                    $queryBuilder->setParameter('efType', ExtraFieldEntity::PORTFOLIO_TYPE);
3247
                    $queryBuilder->setParameter('variable', 'tags');
3248
                    $queryBuilder->setParameter('tags', $values['tags']);
3249
                }
3250
3251
                if (!empty($values['text'])) {
3252
                    $queryBuilder->andWhere(
3253
                        $queryBuilder->expr()->orX(
3254
                            $queryBuilder->expr()->like('pi.title', ':text'),
3255
                            $queryBuilder->expr()->like('pi.content', ':text')
3256
                        )
3257
                    );
3258
3259
                    $queryBuilder->setParameter('text', '%'.$values['text'].'%');
3260
                }
3261
3262
                // Filters by category level 0
3263
                $searchCategories = [];
3264
                if (!empty($values['categoryId'])) {
3265
                    $searchCategories[] = $values['categoryId'];
3266
                    $subCategories = $this->getCategoriesForIndex(null, $values['categoryId']);
3267
                    if (count($subCategories) > 0) {
3268
                        foreach ($subCategories as $subCategory) {
3269
                            $searchCategories[] = $subCategory->getId();
3270
                        }
3271
                    }
3272
                    $queryBuilder->andWhere('pi.category IN('.implode(',', $searchCategories).')');
3273
                }
3274
3275
                // Filters by sub-category, don't show the selected values
3276
                $diff = [];
3277
                if (!empty($values['subCategoryIds']) && !('all' === $values['subCategoryIds'])) {
3278
                    $subCategoryIds = explode(',', $values['subCategoryIds']);
3279
                    $diff = array_diff($searchCategories, $subCategoryIds);
3280
                } else {
3281
                    if (trim($values['subCategoryIds']) === '') {
3282
                        $diff = $searchCategories;
3283
                    }
3284
                }
3285
                if (!empty($diff)) {
3286
                    unset($diff[0]);
3287
                    if (!empty($diff)) {
3288
                        $queryBuilder->andWhere('pi.category NOT IN('.implode(',', $diff).')');
3289
                    }
3290
                }
3291
            }
3292
3293
            if ($listByUser) {
3294
                $queryBuilder
3295
                    ->andWhere('pi.user = :user')
3296
                    ->setParameter('user', $this->owner);
3297
            }
3298
3299
            $visibilityCriteria = [Portfolio::VISIBILITY_VISIBLE];
3300
3301
            if (api_is_allowed_to_edit()) {
3302
                $visibilityCriteria[] = Portfolio::VISIBILITY_HIDDEN_EXCEPT_TEACHER;
3303
            }
3304
3305
            $queryBuilder
3306
                ->andWhere(
3307
                    $queryBuilder->expr()->orX(
3308
                        'pi.user = :current_user',
3309
                        $queryBuilder->expr()->andX(
3310
                            'pi.user != :current_user',
3311
                            $queryBuilder->expr()->in('pi.visibility', $visibilityCriteria)
3312
                        )
3313
                    )
3314
                )
3315
                ->setParameter('current_user', $currentUserId);
3316
3317
            $queryBuilder->orderBy('pi.creationDate', 'DESC');
3318
3319
            $items = $queryBuilder->getQuery()->getResult();
3320
        } else {
3321
            $itemsCriteria = [];
3322
            $itemsCriteria['category'] = null;
3323
            $itemsCriteria['user'] = $this->owner;
3324
3325
            if ($currentUserId !== $this->owner->getId()) {
3326
                $itemsCriteria['visibility'] = Portfolio::VISIBILITY_VISIBLE;
3327
            }
3328
3329
            $items = $this->em
3330
                ->getRepository(Portfolio::class)
3331
                ->findBy($itemsCriteria, ['creationDate' => 'DESC']);
3332
        }
3333
3334
        return $items;
3335
    }
3336
3337
    /**
3338
     * @throws \Doctrine\ORM\ORMException
3339
     * @throws \Doctrine\ORM\OptimisticLockException
3340
     * @throws \Doctrine\ORM\TransactionRequiredException
3341
     */
3342
    private function createCommentForm(Portfolio $item): string
3343
    {
3344
        $formAction = $this->baseUrl.http_build_query(['action' => 'view', 'id' => $item->getId()]);
3345
3346
        $templates = $this->em
3347
            ->getRepository(PortfolioComment::class)
3348
            ->findBy(
3349
                [
3350
                    'isTemplate' => true,
3351
                    'author' => $this->owner,
3352
                ]
3353
            );
3354
3355
        $form = new FormValidator('frm_comment', 'post', $formAction);
3356
        $form->addHeader(get_lang('AddNewComment'));
3357
        $form->addSelectFromCollection(
3358
            'template',
3359
            [
3360
                get_lang('Template'),
3361
                null,
3362
                '<span id="portfolio-spinner" class="fa fa-fw fa-spinner fa-spin" style="display: none;"
3363
                    aria-hidden="true" aria-label="'.get_lang('Loading').'"></span>',
3364
            ],
3365
            $templates,
3366
            [],
3367
            true,
3368
            'getExcerpt'
3369
        );
3370
        $form->addHtmlEditor('content', get_lang('Comments'), true, false, ['ToolbarSet' => 'Minimal']);
3371
        $form->addHidden('item', $item->getId());
3372
        $form->addHidden('parent', 0);
3373
        $form->applyFilter('content', 'trim');
3374
3375
        $this->addAttachmentsFieldToForm($form);
3376
3377
        $form->addButtonSave(get_lang('Save'));
3378
3379
        if ($form->validate()) {
3380
            $values = $form->exportValues();
3381
3382
            $parentComment = $this->em->find(PortfolioComment::class, $values['parent']);
3383
3384
            $comment = new PortfolioComment();
3385
            $comment
3386
                ->setAuthor($this->owner)
3387
                ->setParent($parentComment)
3388
                ->setContent($values['content'])
3389
                ->setDate(api_get_utc_datetime(null, false, true))
3390
                ->setItem($item);
3391
3392
            $this->em->persist($comment);
3393
            $this->em->flush();
3394
3395
            $this->processAttachments(
3396
                $form,
3397
                $comment->getAuthor(),
3398
                $comment->getId(),
3399
                PortfolioAttachment::TYPE_COMMENT
3400
            );
3401
3402
            $hook = HookPortfolioItemCommented::create();
3403
            $hook->setEventData(['comment' => $comment]);
3404
            $hook->notifyItemCommented();
3405
3406
            PortfolioNotifier::notifyTeachersAndAuthor($comment);
3407
3408
            Display::addFlash(
3409
                Display::return_message(get_lang('CommentAdded'), 'success')
3410
            );
3411
3412
            header("Location: $formAction");
3413
            exit;
0 ignored issues
show
Bug Best Practice introduced by
In this branch, the function will implicitly return null which is incompatible with the type-hinted return string. Consider adding a return statement or allowing null as return value.

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

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

class MyClass implements ReturnsInt {
    public function returnsIntHinted(): int
    {
        if (foo()) {
            return 123;
        }
        // here: null is implicitly returned
    }
}
Loading history...
3414
        }
3415
3416
        $js = '<script>
3417
            $(function() {
3418
                $(\'#frm_comment_template\').on(\'change\', function () {
3419
                    $(\'#portfolio-spinner\').show();
3420
                
3421
                    $.getJSON(_p.web_ajax + \'portfolio.ajax.php?a=find_template_comment&comment=\' + this.value)
3422
                        .done(function(response) {
3423
                            CKEDITOR.instances.content.setData(response.content);
3424
                        })
3425
                        .fail(function () {
3426
                            CKEDITOR.instances.content.setData(\'\');
3427
                        })
3428
                        .always(function() {
3429
                          $(\'#portfolio-spinner\').hide();
3430
                        });
3431
                });
3432
            });
3433
        </script>';
3434
3435
        return $form->returnForm().$js;
3436
    }
3437
3438
    private function generateAttachmentList($post, bool $includeHeader = true): string
3439
    {
3440
        $attachmentsRepo = $this->em->getRepository(PortfolioAttachment::class);
3441
3442
        $postOwnerId = 0;
3443
3444
        if ($post instanceof Portfolio) {
3445
            $attachments = $attachmentsRepo->findFromItem($post);
3446
3447
            $postOwnerId = $post->getUser()->getId();
3448
        } elseif ($post instanceof PortfolioComment) {
3449
            $attachments = $attachmentsRepo->findFromComment($post);
3450
3451
            $postOwnerId = $post->getAuthor()->getId();
3452
        }
3453
3454
        if (empty($attachments)) {
3455
            return '';
3456
        }
3457
3458
        $currentUserId = api_get_user_id();
3459
3460
        $listItems = '<ul class="fa-ul">';
3461
3462
        $deleteIcon = Display::return_icon(
3463
            'delete.png',
3464
            get_lang('DeleteAttachment'),
3465
            ['style' => 'display: inline-block'],
3466
            ICON_SIZE_TINY
3467
        );
3468
        $deleteAttrs = ['class' => 'btn-portfolio-delete'];
3469
3470
        /** @var PortfolioAttachment $attachment */
3471
        foreach ($attachments as $attachment) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $attachments does not seem to be defined for all execution paths leading up to this point.
Loading history...
3472
            $downloadParams = http_build_query(['action' => 'download_attachment', 'file' => $attachment->getPath()]);
3473
            $deleteParams = http_build_query(['action' => 'delete_attachment', 'file' => $attachment->getPath()]);
3474
3475
            $listItems .= '<li>'
3476
                .'<span class="fa-li fa fa-paperclip" aria-hidden="true"></span>'
3477
                .Display::url(
3478
                    Security::remove_XSS($attachment->getFilename()),
3479
                    $this->baseUrl.$downloadParams
3480
                );
3481
3482
            if ($currentUserId === $postOwnerId) {
3483
                $listItems .= PHP_EOL.Display::url($deleteIcon, $this->baseUrl.$deleteParams, $deleteAttrs);
3484
            }
3485
3486
            if ($attachment->getComment()) {
3487
                $listItems .= '<p class="text-muted">'.Security::remove_XSS($attachment->getComment()).'</p>';
3488
            }
3489
3490
            $listItems .= '</li>';
3491
        }
3492
3493
        $listItems .= '</ul>';
3494
3495
        if ($includeHeader) {
3496
            $listItems = '<h1 class="h4">'.get_lang('AttachmentFiles').'</h1>'
3497
                .$listItems;
3498
        }
3499
3500
        return $listItems;
3501
    }
3502
3503
    private function generateItemContent(Portfolio $item): string
3504
    {
3505
        $originId = $item->getOrigin();
3506
3507
        if (empty($originId)) {
3508
            return $item->getContent();
3509
        }
3510
3511
        $em = Database::getManager();
3512
3513
        $originContent = '';
3514
        $originContentFooter = '';
3515
3516
        if (Portfolio::TYPE_ITEM === $item->getOriginType()) {
3517
            $origin = $em->find(Portfolio::class, $item->getOrigin());
3518
3519
            if ($origin) {
3520
                $originContent = $origin->getContent();
3521
                $originContentFooter = vsprintf(
3522
                    get_lang('OriginallyPublishedAsXTitleByYUser'),
3523
                    [
3524
                        "<cite>{$origin->getTitle(true)}</cite>",
3525
                        $origin->getUser()->getCompleteName(),
3526
                    ]
3527
                );
3528
            }
3529
        } elseif (Portfolio::TYPE_COMMENT === $item->getOriginType()) {
3530
            $origin = $em->find(PortfolioComment::class, $item->getOrigin());
3531
3532
            if ($origin) {
3533
                $originContent = $origin->getContent();
3534
                $originContentFooter = vsprintf(
3535
                    get_lang('OriginallyCommentedByXUserInYItem'),
3536
                    [
3537
                        $origin->getAuthor()->getCompleteName(),
3538
                        "<cite>{$origin->getItem()->getTitle(true)}</cite>",
3539
                    ]
3540
                );
3541
            }
3542
        }
3543
3544
        if ($originContent) {
3545
            return "<figure>
3546
                    <blockquote>$originContent</blockquote>
3547
                    <figcaption style=\"margin-bottom: 10px;\">$originContentFooter</figcaption>
3548
                </figure>
3549
                <div class=\"clearfix\">".Security::remove_XSS($item->getContent()).'</div>'
3550
            ;
3551
        }
3552
3553
        return Security::remove_XSS($item->getContent());
3554
    }
3555
3556
    private function getItemsInHtmlFormatted(array $items): array
3557
    {
3558
        $itemsHtml = [];
3559
3560
        /** @var Portfolio $item */
3561
        foreach ($items as $item) {
3562
            $itemCourse = $item->getCourse();
3563
            $itemSession = $item->getSession();
3564
3565
            $creationDate = api_convert_and_format_date($item->getCreationDate());
3566
            $updateDate = api_convert_and_format_date($item->getUpdateDate());
3567
3568
            $metadata = '<ul class="list-unstyled text-muted">';
3569
3570
            if ($itemSession) {
3571
                $metadata .= '<li>'.get_lang('Course').': '.$itemSession->getName().' ('
3572
                    .$itemCourse->getTitle().') </li>';
3573
            } elseif ($itemCourse) {
3574
                $metadata .= '<li>'.get_lang('Course').': '.$itemCourse->getTitle().'</li>';
3575
            }
3576
3577
            $metadata .= '<li>'.sprintf(get_lang('CreationDateXDate'), $creationDate).'</li>';
3578
3579
            if ($itemCourse) {
3580
                $propertyInfo = api_get_item_property_info(
3581
                    $itemCourse->getId(),
3582
                    TOOL_PORTFOLIO,
3583
                    $item->getId(),
3584
                    $itemSession ? $itemSession->getId() : 0
3585
                );
3586
3587
                if ($propertyInfo) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $propertyInfo of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

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

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

Loading history...
3588
                    $metadata .= '<li>'
3589
                        .sprintf(
3590
                            get_lang('UpdatedOnDateXByUserY'),
3591
                            api_convert_and_format_date($propertyInfo['lastedit_date'], DATE_TIME_FORMAT_LONG),
3592
                            api_get_user_entity($propertyInfo['lastedit_user_id'])->getCompleteName()
3593
                        )
3594
                        .'</li>';
3595
                }
3596
            } else {
3597
                $metadata .= '<li>'.sprintf(get_lang('UpdateDateXDate'), $updateDate).'</li>';
3598
            }
3599
3600
            if ($item->getCategory()) {
3601
                $metadata .= '<li>'.sprintf(get_lang('CategoryXName'), $item->getCategory()->getTitle()).'</li>';
3602
            }
3603
3604
            $metadata .= '</ul>';
3605
3606
            $itemContent = $this->generateItemContent($item);
3607
3608
            $itemsHtml[] = Display::panel($itemContent, Security::remove_XSS($item->getTitle()), '', 'info', $metadata);
3609
        }
3610
3611
        return $itemsHtml;
3612
    }
3613
3614
    private function getCommentsInHtmlFormatted(array $comments): array
3615
    {
3616
        $commentsHtml = [];
3617
3618
        /** @var PortfolioComment $comment */
3619
        foreach ($comments as $comment) {
3620
            $item = $comment->getItem();
3621
            $date = api_convert_and_format_date($comment->getDate());
3622
3623
            $metadata = '<ul class="list-unstyled text-muted">';
3624
            $metadata .= '<li>'.sprintf(get_lang('DateXDate'), $date).'</li>';
3625
            $metadata .= '<li>'.sprintf(get_lang('PortfolioItemTitleXName'), Security::remove_XSS($item->getTitle()))
3626
                .'</li>';
3627
            $metadata .= '</ul>';
3628
3629
            $commentsHtml[] = Display::panel(
3630
                Security::remove_XSS($comment->getContent()),
3631
                '',
3632
                '',
3633
                'default',
3634
                $metadata
3635
            );
3636
        }
3637
3638
        return $commentsHtml;
3639
    }
3640
3641
    private function fixImagesSourcesToHtml(string $htmlContent): string
3642
    {
3643
        $doc = new DOMDocument();
3644
        @$doc->loadHTML($htmlContent);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition for loadHTML(). This can introduce security issues, and is generally not recommended. ( Ignorable by Annotation )

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

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

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

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

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
3645
3646
        $elements = $doc->getElementsByTagName('img');
3647
3648
        if (empty($elements->length)) {
3649
            return $htmlContent;
3650
        }
3651
3652
        $webCoursePath = api_get_path(WEB_COURSE_PATH);
3653
        $webUploadPath = api_get_path(WEB_UPLOAD_PATH);
3654
3655
        /** @var \DOMElement $element */
3656
        foreach ($elements as $element) {
3657
            $src = trim($element->getAttribute('src'));
3658
3659
            if (strpos($src, 'http') === 0) {
3660
                continue;
3661
            }
3662
3663
            if (strpos($src, '/app/upload/') === 0) {
3664
                $element->setAttribute(
3665
                    'src',
3666
                    preg_replace('/\/app/upload\//', $webUploadPath, $src, 1)
3667
                );
3668
3669
                continue;
3670
            }
3671
3672
            if (strpos($src, '/courses/') === 0) {
3673
                $element->setAttribute(
3674
                    'src',
3675
                    preg_replace('/\/courses\//', $webCoursePath, $src, 1)
3676
                );
3677
3678
                continue;
3679
            }
3680
        }
3681
3682
        return $doc->saveHTML();
3683
    }
3684
3685
    private function formatZipIndexFile(HTML_Table $tblItems, HTML_Table $tblComments): string
3686
    {
3687
        $htmlContent = Display::page_header($this->owner->getCompleteNameWithUsername());
3688
        $htmlContent .= Display::page_subheader2(get_lang('PortfolioItems'));
3689
3690
        $htmlContent .= $tblItems->getRowCount() > 0
3691
            ? $tblItems->toHtml()
3692
            : Display::return_message(get_lang('NoItemsInYourPortfolio'), 'warning');
3693
3694
        $htmlContent .= Display::page_subheader2(get_lang('PortfolioCommentsMade'));
3695
3696
        $htmlContent .= $tblComments->getRowCount() > 0
3697
            ? $tblComments->toHtml()
3698
            : Display::return_message(get_lang('YouHaveNotCommented'), 'warning');
3699
3700
        $webAssetsPath = api_get_path(WEB_PUBLIC_PATH).'assets/';
3701
3702
        $doc = new DOMDocument();
3703
        @$doc->loadHTML($htmlContent);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition for loadHTML(). This can introduce security issues, and is generally not recommended. ( Ignorable by Annotation )

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

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

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

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

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
3704
3705
        $stylesheet1 = $doc->createElement('link');
3706
        $stylesheet1->setAttribute('rel', 'stylesheet');
3707
        $stylesheet1->setAttribute('href', $webAssetsPath.'bootstrap/dist/css/bootstrap.min.css');
3708
        $stylesheet2 = $doc->createElement('link');
3709
        $stylesheet2->setAttribute('rel', 'stylesheet');
3710
        $stylesheet2->setAttribute('href', $webAssetsPath.'fontawesome/css/font-awesome.min.css');
3711
        $stylesheet3 = $doc->createElement('link');
3712
        $stylesheet3->setAttribute('rel', 'stylesheet');
3713
        $stylesheet3->setAttribute('href', ChamiloApi::getEditorDocStylePath());
3714
3715
        $head = $doc->createElement('head');
3716
        $head->appendChild($stylesheet1);
3717
        $head->appendChild($stylesheet2);
3718
        $head->appendChild($stylesheet3);
3719
3720
        $doc->documentElement->insertBefore(
3721
            $head,
3722
            $doc->getElementsByTagName('body')->item(0)
3723
        );
3724
3725
        return $doc->saveHTML();
3726
    }
3727
3728
    /**
3729
     * It parsers a title for a variable in lang.
3730
     *
3731
     * @param $defaultDisplayText
3732
     *
3733
     * @return string
3734
     */
3735
    private function getLanguageVariable($defaultDisplayText)
3736
    {
3737
        $variableLanguage = api_replace_dangerous_char(strtolower($defaultDisplayText));
3738
        $variableLanguage = preg_replace('/[^A-Za-z0-9\_]/', '', $variableLanguage); // Removes special chars except underscore.
3739
        if (is_numeric($variableLanguage[0])) {
3740
            $variableLanguage = '_'.$variableLanguage;
3741
        }
3742
        $variableLanguage = api_underscore_to_camel_case($variableLanguage);
3743
3744
        return $variableLanguage;
3745
    }
3746
3747
    /**
3748
     * It translates the text as parameter.
3749
     *
3750
     * @param $defaultDisplayText
3751
     *
3752
     * @return mixed
3753
     */
3754
    private function translateDisplayName($defaultDisplayText)
3755
    {
3756
        $variableLanguage = $this->getLanguageVariable($defaultDisplayText);
3757
3758
        return isset($GLOBALS[$variableLanguage]) ? $GLOBALS[$variableLanguage] : $defaultDisplayText;
3759
    }
3760
3761
    private function getCommentsForIndex(FormValidator $frmFilterList = null): array
3762
    {
3763
        if (null === $frmFilterList) {
3764
            return [];
3765
        }
3766
3767
        if (!$frmFilterList->validate()) {
3768
            return [];
3769
        }
3770
3771
        $values = $frmFilterList->exportValues();
3772
3773
        if (empty($values['date']) && empty($values['text'])) {
3774
            return [];
3775
        }
3776
3777
        $queryBuilder = $this->em->createQueryBuilder()
3778
            ->select('c')
3779
            ->from(PortfolioComment::class, 'c')
3780
        ;
3781
3782
        if (!empty($values['date'])) {
3783
            $queryBuilder
3784
                ->andWhere('c.date >= :date')
3785
                ->setParameter(':date', api_get_utc_datetime($values['date'], false, true))
3786
            ;
3787
        }
3788
3789
        if (!empty($values['text'])) {
3790
            $queryBuilder
3791
                ->andWhere('c.content LIKE :text')
3792
                ->setParameter('text', '%'.$values['text'].'%')
3793
            ;
3794
        }
3795
3796
        $queryBuilder->orderBy('c.date', 'DESC');
3797
3798
        return $queryBuilder->getQuery()->getResult();
3799
    }
3800
}
3801