aboutsummaryrefslogtreecommitdiff
path: root/app/controllers/oer/market.php
blob: 0c12bffa113025ad06591146c2a9f8c4049a924b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
<?php

class Oer_MarketController extends StudipController
{

    protected $with_session = true;

    function before_filter(&$action, &$args)
    {
        parent::before_filter($action, $args);
        if (
            !Config::get()->OERCAMPUS_ENABLED
            || (
                Config::get()->OER_PUBLIC_STATUS !== 'nobody'
                && !$GLOBALS['perm']->have_perm(Config::get()->OER_PUBLIC_STATUS)
            )
        ) {
            throw new AccessDeniedException();
        }
        Helpbar::Get()->addPlainText(
            _("Lernmaterialien"),
            _("Übungszettel, Musterlösungen, Vorlesungsmitschriften oder gar Folien, selbsterstellte Lernkarteikarten oder alte Klausuren. Das alles wird einmal erstellt und dann meist vergessen. Auf dem Lernmaterialienmarktplatz bleiben sie erhalten. Jeder kann was hochladen und jeder kann alles herunterladen. Alle Inhalte hier sind frei verfügbar für jeden.")
        );
        PageLayout::setTitle(_("Lernmaterialien"));
    }

    public function index_action()
    {
        if (Navigation::hasItem("/oer/market")) {
            Navigation::activateItem("/oer/market");
        }
        $tag_matrix_entries_number = 9;
        $this->best_nine_tags = OERTag::findBest($tag_matrix_entries_number);
        $this->tags = [];
        foreach ($this->best_nine_tags as $tag) {
            $this->tags[] = [
                'tag_hash' => $tag->tag_hash,
                'name'     => $tag->name,
            ];
        }
        if (Request::get("tag")) {
            $this->materialien = OERMaterial::findByTag(Request::get("tag"));
        }
        if (Request::get("category")) {
            $this->materialien = OERMaterial::findBySQL("category = ? ORDER BY oer_material.mkdate DESC", [Request::get("category")]);
        }
        if (Request::get("get") === "all") {
            $this->materialien = OERMaterial::findBySQL("1 ORDER BY oer_material.mkdate DESC");
        }

        $this->material_data = false;
        if (!empty($this->materialien)) {
            $this->material_data = [];
            foreach ($this->materialien as $material) {
                $data = $material->toRawArray();

                $data['tags'] = array_map(function($tag) {
                    return $tag['name'];
                }, $material->getTopics());

                $data['logo_url'] = $material->getLogoURL();
                $data['download_url'] = $material->getDownloadUrl();
                $this->material_data[] = $data;
            }
        }
        $this->new_ones = OERMaterial::findBySQL("LEFT JOIN oer_hosts ON (oer_hosts.host_id = oer_material.host_id)
            WHERE draft = '0'
                AND oer_material.host_id IS NULL
            ORDER BY mkdate DESC LIMIT 9");

        $statement = DBManager::get()->prepare("
            SELECT 1
            FROM oer_abo
            WHERE user_id = ?
                AND material_id IS NULL
        ");
        $statement->execute([$GLOBALS['user']->id]);
        $this->abo = (bool) $statement->fetch(PDO::FETCH_COLUMN, 0);

        if ($GLOBALS['perm']->have_perm('autor')) {
            $actions = new ActionsWidget();
            $actions->addLink(
                _('Neues Lernmaterial hochladen'),
                $this->url_for('oer/mymaterial/edit'),
                Icon::create('add'),
                ['data-dialog' => 'size=auto']
            );
            $actions->addLink(
                $this->abo ? _('Neuigkeiten abbestellen') : _('Neuigkeiten abonnieren'),
                $this->aboURL(),
                Icon::create($this->abo ? 'decline' : 'rss'),
                ['data-dialog' => 'size=auto']
            );
            Sidebar::Get()->addWidget($actions);
        }
    }

    public function get_tags_action()
    {
        $tag_matrix_entries_number = 9;
        $tag_subtags_number = 9;

        if (!count(Request::getArray("tags"))) {
            $this->topics = OERTag::findBest($tag_matrix_entries_number);
            $this->materialien = [];
        } else {
            $tags = $this->tag_history = Request::getArray("tags");
            $this->without_tags = [];
            $tag_to_search_for = array_pop($tags);

            OERMaterial::fetchRemoteSearch(
                null,
                $tag_to_search_for
            );

            foreach (OERTag::findBest($tag_matrix_entries_number, true) as $related_tag) {
                if ($related_tag['tag_hash'] !== $this->tag_history[0]) {
                    $this->without_tags[] = $related_tag['tag_hash'];
                }
            }
            foreach ($tags as $tag) {
                foreach (OERTag::findRelated($tag, $this->without_tags, $tag_subtags_number, true) as $related_tag) {
                    $this->without_tags[] = $related_tag['tag_hash'];
                }
            }
            $this->topics = OERTag::findRelated(
                $tag_to_search_for,
                $this->without_tags,
                $tag_subtags_number
            );
            $this->materialien = OERMaterial::findByTagHash($tag_to_search_for);
        }

        $output = [];
        $output['results'] = [
            'materials' => [],
            'tags' => []
        ];
        foreach ($this->materialien as $material) {
            $data = $material->toRawArray();

            $data['tags'] = array_map(function($tag) {
                return $tag['name'];
            }, $material->getTopics());

            $data['logo_url'] = $material->getLogoURL();
            $data['download_url'] = $material->getDownloadUrl();

            $output['results']['materials'][] = $data;
        }

        foreach ($this->topics as $topic) {
            $output['tags'][] = $topic->toArray();
        }

        $this->render_json($output);
    }


    public function search_action()
    {
        if (Navigation::hasItem("/oer/market")) {
            Navigation::activateItem("/oer/market");
        }
        if (Request::get("search") || Request::get("type") || Request::get("tag") || Request::get("difficulty")) {
            if (Request::get("search")) {
                OERMaterial::fetchRemoteSearch(
                    Request::get("search"),
                    Request::get("tag")
                );
            }
            $this->more = false;
            $search = SQLQuery::table("oer_material", "oer_material")
                ->join("oer_hosts", "oer_hosts.host_id = oer_material.host_id", "LEFT JOIN")
                ->where("draft = '0'")
                ->where("(oer_material.host_id IS NULL OR oer_hosts.`active` = '1')")
                ->groupBy("oer_material.material_id")
                ->orderBy("mkdate DESC");
            if (Request::get("type")) {
                $search->where("search_categories", "category = :category", ['category' => Request::get("type")]);
            }
            if (Request::get("search")) {
                //Tags
                $search->join(
                    "oer_tags_material",
                    "oer_material.material_id = oer_tags_material.material_id",
                    "LEFT JOIN"
                );
                $search->join(
                    "oer_tags",
                    "oer_tags_material.tag_hash = oer_tags.tag_hash",
                    "LEFT JOIN"
                );
                $search->join(
                    "oer_material_users",
                    "oer_material_users.material_id = oer_material.material_id",
                    "LEFT JOIN"
                );
                $search->join(
                    "external_users",
                    "oer_material_users.user_id = external_users.external_contact_id AND oer_material_users.external_contact = '1'",
                    "LEFT JOIN"
                );
                $search->join(
                    "auth_user_md5",
                    "oer_material_users.user_id = auth_user_md5.user_id AND oer_material_users.external_contact = '0'",
                    "LEFT JOIN"
                );
                $search->where(
                    "textsearch",
                    "(oer_material.name LIKE :search OR oer_material.description LIKE :search OR oer_material.short_description LIKE :search OR oer_tags.name LIKE :search OR external_users.name LIKE :search OR CONCAT(auth_user_md5.Vorname, ' ', auth_user_md5.Nachname) LIKE :search)",
                    ['search' => '%'.Request::get("search").'%']
                );
            }
            if (Request::get("difficulty")) {
                $difficulty = explode(",", Request::get("difficulty"));
                $search->where(
                    "difficulty",
                    "((difficulty_start <= :difficulty_start AND difficulty_end >= :difficulty_start) OR (difficulty_start <= :difficulty_end AND difficulty_end >= :difficulty_end) OR (difficulty_start <= :difficulty_start AND difficulty_end >= :difficulty_end) OR (difficulty_start >= :difficulty_start AND difficulty_end <= :difficulty_end))",
                    ['difficulty_start' => $difficulty[0], 'difficulty_end' => $difficulty[1]]
                );
            }
            if (Request::get("limit") || Request::get("offset")) {
                $search->limit(
                    Request::int("limit") + 1,
                    Request::int("offset")
                );
            }

            $this->materialien = $search->fetchAll("OERMaterial");
            if (Request::int("limit") && (count($this->materialien) > Request::int("limit"))) {
                $this->more = true;
                array_pop($this->materialien);
            }

            if (Request::isAjax()) {
                $output = [
                    'materials' => [],
                    'more' => $this->more,
                    'offset' => Request::int("offset", 0)
                ];
                if (Request::int("limit")) {
                    $output['limit'] = Request::int("limit");
                }
                foreach ($this->materialien as $material) {
                    $data = $material->toRawArray();

                    $data['tags'] = array_map(function($tag) {
                        return $tag['name'];
                    }, $material->getTopics());

                    $data['logo_url'] = $material->getLogoURL();
                    $data['download_url'] = $material->getDownloadUrl();

                    $output['materials'][] = $data;
                }
                $this->render_json($output);
            }
        } else {
            $this->redirect("oer/market/index");
        }
    }

    public function details_action($material_id)
    {
        if (Navigation::hasItem("/oer/market")) {
            Navigation::activateItem("/oer/market");
        }
        $this->material = OERMaterial::find($material_id);
        if (!$this->material) {
            PageLayout::postError(_('Lernmaterial existiert nicht mehr.'));
            $this->redirect('oer/market');
            return;
        }

        //OpenGraph tags:
        PageLayout::addHeadElement("meta", ['og:title' => $this->material['name']]);

        $base = URLHelper::setBaseURL($GLOBALS['ABSOLUTE_URI_STUDIP']);
        PageLayout::addHeadElement("meta", ['og:url' => $this->url_for("oer/market/details/".$this->material->getId())]);
        PageLayout::addHeadElement("meta", ['og:description' => $this->material['short_description']]);
        PageLayout::addHeadElement("meta", ['og:image' => $this->material->getLogoURL()]);
        if ($this->material->isVideo()) {
            PageLayout::addHeadElement("meta", ['og:type' => "video"]);
            $url = $this->material['host_id']
                ? $this->material->host->url."download/".$this->material['foreign_material_id']
                : $this->url_for("oer/market/download/".$this->material->getId());
            PageLayout::addHeadElement("meta", ['og:video' => $url]);
            PageLayout::addHeadElement("meta", ['og:video:type' => $this->material['content_type']]);
        } elseif($this->material->isAudio()) {
            PageLayout::addHeadElement("meta", ['og:type' => "audio"]);
            $url = $this->material['host_id']
                ? $this->material->host->url."download/".$this->material['foreign_material_id']
                : $this->url_for("oer/market/download/".$this->material->getId());
            PageLayout::addHeadElement("meta", ['og:audio' => $url]);
            PageLayout::addHeadElement("meta", ['og:audio:type' => $this->material['content_type']]);
        } else {
            PageLayout::addHeadElement("meta", ['og:type' => "article"]);
        }
        URLHelper::setBaseURL($base);

        if ($this->material['host_id']) {
            $success = $this->material->fetchData();
            if ($success === false) {
                PageLayout::postInfo(_("Dieses Material stammt von einem anderen Server, der zur Zeit nicht erreichbar ist."));
            } elseif ($success === "deleted") {
                $material = clone $this->material;
                $this->material->delete();
                $this->material = $material;
                PageLayout::postError(_("Dieses Material ist gelöscht worden und wird gleich aus dem Cache verschwinden."));
            }
            $this->material->resetRelation("users");
        }
        $this->material['rating'] = $this->material->calculateRating();
        $this->material->store();

        $infotext = "";
        foreach ($this->material->users as $index => $materialuser)  {
            if ($index > 0) {
                $infotext .= ', ';
            }
            if ($materialuser['external_contact']) {
                $user = $materialuser['oeruser'];
                $infotext .= $user['name'];
            } else {
                $user = User::find($materialuser['user_id']);
                $infotext .= $user ? $user->getFullName() : _('unbekannt');
            }
        }

        $this->contentBarVueApp = \Studip\VueApp::create('ContentBar')->withProps([
            'title' => $this->material['name'],
            'icon' => 'oer-campus',
            'isContentBar' => true,
        ])->withSlot('info-text', htmlReady($infotext));
    }

    public function embed_action($material_id)
    {
        if (Navigation::hasItem("/oer/market")) {
            Navigation::activateItem("/oer/market");
        }

        $this->material = new OERMaterial($material_id);
    }

    public function review_action($material_id = null)
    {
        if (!$GLOBALS['perm']->have_perm("autor")) {
            throw new AccessDeniedException();
        }
        if (Navigation::hasItem("/oer/market")) {
            Navigation::activateItem("/oer/market");
        }
        $this->material = new OERMaterial($material_id);
        $this->review = OERReview::findOneBySQL("context_id = ? AND user_id = ?", [
            $material_id,
            $GLOBALS['user']->id
        ]);
        if (!$this->review) {
            $this->review = new OERReview();
            $this->review['context_id'] = $this->material->getId();
            $this->review['user_id'] = $GLOBALS['user']->id;
            $this->review['display_class'] = "OERReview";
            $this->review['context_type'] = "public";
        }
        if (Request::isPost()) {
            $this->review['content'] = Request::get("review");
            $this->review['metadata'] = [
                'rating' => Request::get("rating")
            ];
            $this->review->store();

            $this->material['rating'] = $this->material->calculateRating();
            $this->material->store();
            PageLayout::postSuccess(_("Danke für das Review!"));
            $this->redirect("oer/market/details/".$material_id);
        }
    }

    public function discussion_action($review_id)
    {
        if (Navigation::hasItem("/oer/market")) {
            Navigation::activateItem("/oer/market");
        }

        $this->thread = new OERReview($review_id);
        if (!$this->thread->isNew()) {
            $this->thread->markAsRead();
        }
    }


    public function licenseinfo_action()
    {

    }

    public function add_to_course_action($material_id)
    {
        if (!$GLOBALS['perm']->have_perm("autor")) {
            throw new AccessDeniedException();
        }
        $this->material = new OERMaterial($material_id);
        if (Request::option("seminar_id") && $GLOBALS['perm']->have_studip_perm("autor", Request::option("seminar_id"))) {
            $this->course = new Course(Request::option("seminar_id"));

            $this->classes = $this->course->tools->filter(function (ToolActivation $tool) {
                $module = $tool->getStudipModule();
                return $module instanceof OERModule
                    && $module::oerModuleWantsToUseMaterial($this->material);
            })->map(function (ToolActivation $tool): string {
                return get_class($tool->getStudipModule());
            });

            if (Request::get('class') || count($this->classes) === 1) {
                $class = Request::get('class') ?? $this->classes[0] ?? '';
                if (class_exists($class) && in_array($class, $this->classes)) {
                    $response = $class::oerModuleIntegrateMaterialToCourse(
                        $this->material,
                        $this->course
                    );

                    if ($response['type'] === 'error') {
                        PageLayout::postError($response['message'], $response['message_detail']);
                    } else {
                        PageLayout::postSuccess($response['message'], $response['message_detail']);
                    }

                    $this->response->add_header('X-Dialog-Close', 1);
                    $this->relocate($response['redirect_url']);

                    return;
                }
            } else {
                $this->render_template("oer/market/add_to_course_select_class");
            }

        }
        if (!$GLOBALS['perm']->have_perm("admin")) {
            $this->courses = Course::findBySQL("INNER JOIN seminar_user USING (Seminar_id)
                WHERE seminar_user.user_id = ?
                ORDER BY seminare.mkdate DESC", [$GLOBALS['user']->id]
            );
        } else {
            $this->courses = [];
            foreach (AdminCourseFilter::get()->getCourses(false) as $coursedata) {
                $this->courses[] = Course::buildExisting($coursedata);
            }
        }
        $this->semesters = [];
        foreach ($this->courses as $course) {
            foreach ($course->semesters as $semester) {
                $this->semesters[$semester->getId()] = $semester;
            }
        }
        usort($this->semesters, function ($a, $b) {
            return $a['beginn'] < $b['beginn'];
        });
    }

    public function profile_action($external_user_id)
    {
        $this->user = new ExternalUser($external_user_id);
        if ($this->user->isNew()) {
            throw new Exception(_("Nutzer ist nicht erfasst."));
        }
        $this->materials = OERMaterial::findBySQL("LEFT JOIN oer_material_users ON (oer_material_users.material_id = oer_material.material_id AND external_contact = 1)
            WHERE oer_material_users.user_id = ?
            ORDER BY oer_material.mkdate DESC", [
            $external_user_id
        ]);
    }

    public function abo_action()
    {
        $statement = DBManager::get()->prepare("
            SELECT 1
            FROM oer_abo
            WHERE user_id = ?
                AND material_id IS NULL
        ");
        $statement->execute([$GLOBALS['user']->id]);
        $this->abo = (bool) $statement->fetch(PDO::FETCH_COLUMN, 0);
        if (Request::isPost()) {
            if (Request::get("abo")) {
                $statement = DBManager::get()->prepare("
                    INSERT IGNORE INTO oer_abo
                    SET user_id = ?,
                        material_id = NULL
                ");
                $statement->execute([$GLOBALS['user']->id]);
                PageLayout::postSuccess(_("Erfolgreich abonniert."));
            } else {
                $statement = DBManager::get()->prepare("
                    DELETE
                    FROM oer_abo
                    WHERE user_id = ?
                        AND (material_id IS NULL OR material_id = '')
                ");
                $statement->execute([$GLOBALS['user']->id]);
                PageLayout::postSuccess(_("Abgemeldet von Neuigkeiten."));
            }

            $this->redirect("oer/market/index");
        }
    }

    protected function getFolderStructure($folder)
    {
        $structure = [];
        foreach (scandir($folder) as $file) {
            if (!in_array($file, [".", ".."])) {
                $attributes = [
                    'is_folder' => is_dir($folder."/".$file) ? 1 : 0
                ];
                if (is_dir($folder."/".$file)) {
                    $attributes['structure'] = $this->getFolderStructure($folder."/".$file);
                } else {
                    $attributes['size'] = filesize($folder."/".$file);
                }
                $structure[$file] = $attributes;
            }
        }
        return $structure;
    }

}