Issues (160)

Branch: fix-vocab-statistics-styling

src/controller/WebController.php (3 issues)

1
<?php
2
3
/**
4
 * Importing the dependencies.
5
 */
6
use Punic\Language;
7
use Symfony\Bridge\Twig\Extension\TranslationExtension;
8
9
/**
10
 * WebController is an extension of the Controller that handles all
11
 * the requests originating from the view of the website.
12
 */
13
class WebController extends Controller
14
{
15
    /**
16
     * Provides access to the templating engine.
17
     * @property object $twig the twig templating engine.
18
     */
19
    public $twig;
20
    public $honeypot;
21
    public $translator;
22
23
    /**
24
     * Constructor for the WebController.
25
     * @param Model $model
26
     */
27
    public function __construct($model)
28
    {
29
        parent::__construct($model);
30
31
        // initialize Twig templates
32
        $tmpDir = $model->getConfig()->getTemplateCache();
33
34
        // check if the cache pointed by config.ttl exists, if not we create it.
35
        if (!file_exists($tmpDir)) {
36
            mkdir($tmpDir);
37
        }
38
39
        // specify where to look for templates and cache
40
        $loader = new \Twig\Loader\FilesystemLoader([__DIR__ . '/../../custom-templates', __DIR__ . '/../view']);
41
        // initialize Twig environment
42
        $this->twig = new \Twig\Environment($loader, array('cache' => $tmpDir,'auto_reload' => true));
43
        // used for setting the base href for the relative urls
44
        $this->twig->addGlobal("BaseHref", $this->getBaseHref());
45
46
        // pass the GlobalConfig object to templates so they can access configuration
47
        $this->twig->addGlobal("GlobalConfig", $this->model->getConfig());
48
49
        // setting the list of properties to be displayed in the search results
50
        $this->twig->addGlobal("PreferredProperties", array('skos:prefLabel', 'skos:narrower', 'skos:broader', 'skosmos:memberOf', 'skos:altLabel', 'skos:related'));
51
52
        // register a Twig filter for generating URLs for global pages (landing, about, feedback, vocab-home..)
53
        $this->twig->addExtension(new GlobalUrlExtension());
54
55
        // register a Twig filter for generating URLs for vocabulary resources (concepts and groups)
56
        $this->twig->addExtension(new LinkUrlExtension($model));
57
58
        // register a Twig filter for generating strings from language codes with CLDR
59
        $langFilter = new \Twig\TwigFilter('lang_name', function ($langcode, $lang) {
60
            return Language::getName($langcode, $lang);
61
        });
62
        $this->twig->addFilter($langFilter);
63
64
        $this->translator = $model->getTranslator();
65
        $this->twig->addExtension(new TranslationExtension($this->translator));
66
67
        // create the honeypot
68
        $this->honeypot = new \Honeypot();
69
        if (!$this->model->getConfig()->getHoneypotEnabled()) {
70
            $this->honeypot->disable();
71
        }
72
        $this->twig->addGlobal('honeypot', $this->honeypot);
73
74
        // populate the customizable content slots from custom templates
75
        $customTemplates = $this->findCustomTemplates("../custom-templates");
76
        $this->twig->addGlobal('customTemplates', $customTemplates);
77
    }
78
79
    /**
80
     * Find any custom templates from the given directory and return them as an array.
81
     * @param string $dir path of custom templates directory
82
     * @return array array of custom template filenames, keyed by slot
83
     */
84
    public function findCustomTemplates($dir)
85
    {
86
        $customTemplateSubDirs = glob($dir . '/*', GLOB_ONLYDIR);
87
        $customTemplates = [];
88
89
        foreach ($customTemplateSubDirs as $slotDir) {
90
            $slotName = basename($slotDir);
91
            $files = glob($slotDir . '/*.twig');
92
            // Strip the directory part to make the file paths relative to the directory.
93
            // The "custom-templates" directory is registered to the Twig FilesystemLoader.
94
            $customTemplates[$slotName] = array_map(function ($file) use ($dir) {
95
                return str_replace($dir . '/', '', $file);
96
            }, $files);
97
        }
98
99
        return $customTemplates;
100
    }
101
102
    /**
103
     * Guess the language of the user. Return a language string that is one
104
     * of the supported languages defined in the $LANGUAGES setting, e.g. "fi".
105
     * @param Request $request HTTP request
106
     * @param string $vocid identifier for the vocabulary eg. 'yso'.
107
     * @return string returns the language choice as a numeric string value
108
     */
109
    public function guessLanguage($request, $vocid = null)
110
    {
111
        // 1. select language based on SKOSMOS_LANGUAGE cookie
112
        $languageCookie = $request->getCookie('SKOSMOS_LANGUAGE');
113
        if ($languageCookie) {
114
            return $languageCookie;
115
        }
116
117
        // 2. if vocabulary given, select based on the default language of the vocabulary
118
        if ($vocid !== null && $vocid !== '') {
119
            try {
120
                $vocab = $this->model->getVocabulary($vocid);
121
                return $vocab->getConfig()->getDefaultLanguage();
122
            } catch (Exception $e) {
123
                // vocabulary id not found, move on to the next selection method
124
            }
125
        }
126
127
        // 3. select language based on Accept-Language header
128
        header('Vary: Accept-Language'); // inform caches that a decision was made based on Accept header
129
        $this->negotiator = new \Negotiation\LanguageNegotiator();
130
        $langcodes = array_keys($this->languages);
131
        // using a random language from the configured UI languages when there is no accept language header set
132
        $acceptLanguage = $request->getServerConstant('HTTP_ACCEPT_LANGUAGE') ? $request->getServerConstant('HTTP_ACCEPT_LANGUAGE') : $langcodes[0];
133
134
        $bestLang = $this->negotiator->getBest($acceptLanguage, $langcodes);
135
        if (isset($bestLang) && in_array($bestLang->getValue(), $langcodes)) {
136
            return $bestLang->getValue();
137
        }
138
139
        // show default site or prompt for language
140
        return $langcodes[0];
141
    }
142
143
    /**
144
     * Determines a css class that controls width and positioning of the vocabulary list element.
145
     * The layout is wider if the left/right box templates have not been provided.
146
     * @return string css class for the container eg. 'voclist-wide' or 'voclist-right'
147
     */
148
    private function listStyle()
149
    {
150
        $left = file_exists('view/left.inc');
151
        $right = file_exists('view/right.inc');
152
        $ret = 'voclist';
153
        if (!$left && !$right) {
154
            $ret .= '-wide';
155
        } elseif (!($left && $right) && ($right || $left)) {
156
            $ret .= ($right) ? '-left' : '-right';
157
        }
158
        return $ret;
159
    }
160
161
    /**
162
    * Renders the list of supported languages from vocabulary config in order.
163
    * The ordering is done according to the language order parameter in vocabulary config if such exists
164
    * @param Vocabulary $vocab the vocabulary object
165
    * @return array with language codes as keys and language labels as values
166
    */
167
    public function parseVocabularyLanguageOrder($vocab)
168
    {
169
        $vocabContentLanguages = array_flip($vocab->getConfig()->getLanguages());
170
        $languageOrder = $vocab->getConfig()->getLanguageOrder();
171
172
        $tmpList = [];
173
174
        foreach ($languageOrder as $vocLang) {
175
            if (isset($vocabContentLanguages[$vocLang])) {
176
                $tmpList[$vocLang] = $vocabContentLanguages[$vocLang];
177
                unset($vocabContentLanguages[$vocLang]);
178
            }
179
        }
180
        return $tmpList + $vocabContentLanguages;
181
    }
182
183
184
    /**
185
     * Loads and renders the landing page view.
186
     * @param Request $request
187
     */
188
    public function invokeLandingPage($request)
189
    {
190
        $this->model->setLocale($request->getLang());
191
        // load template
192
        $template = $this->twig->load('landing.twig');
193
        // set template variables
194
        $categoryLabel = $this->model->getClassificationLabel($request->getLang());
195
        $sortedVocabs = $this->model->getVocabularyList(false, true);
196
        $contentLanguages = array_flip($this->model->getLanguages($request->getLang()));
197
        $listStyle = $this->listStyle();
198
199
        // render template
200
        echo $template->render(
201
            array(
202
                'sorted_vocabs' => $sortedVocabs,
203
                'category_label' => $categoryLabel,
204
                'languages' => $this->languages,
205
                'content_languages' => $contentLanguages,
206
                'request' => $request,
207
                'list_style' => $listStyle
208
            )
209
        );
210
    }
211
212
    /**
213
     * Invokes the concept page of a single concept in a specific vocabulary.
214
     *
215
     * @param Request $request
216
     */
217
    public function invokeVocabularyConcept(Request $request)
218
    {
219
        $lang = $request->getLang();
0 ignored issues
show
The assignment to $lang is dead and can be removed.
Loading history...
220
        $this->model->setLocale($request->getLang());
221
        $vocab = $request->getVocab();
222
223
        $langcodes = $vocab->getConfig()->getShowLangCodes();
224
        $uri = $vocab->getConceptURI($request->getUri()); // make sure it's a full URI
225
226
        $concept = $vocab->getConceptInfo($uri, $request->getContentLang());
227
        if (empty($concept)) {
228
            $this->invokeGenericErrorPage($request);
229
            return;
230
        }
231
        if ($this->notModified($concept)) {
232
            return;
233
        }
234
        $customLabels = $vocab->getConfig()->getPropertyLabelOverrides();
235
236
        $pluginParameters = json_encode($vocab->getConfig()->getPluginParameters());
237
        $template = $this->twig->load('concept.twig');
238
239
        $crumbs = $vocab->getBreadCrumbs($request->getContentLang(), $uri);
240
        echo $template->render(
241
            array(
242
            'concept' => $concept,
243
            'vocab' => $vocab,
244
            'concept_uri' => $uri,
245
            'languages' => $this->languages,
246
            'content_languages' => $this->parseVocabularyLanguageOrder($vocab),
247
            'explicit_langcodes' => $langcodes,
248
            'visible_breadcrumbs' => $crumbs['breadcrumbs'],
249
            'hidden_breadcrumbs' => $crumbs['combined'],
250
            'request' => $request,
251
            'plugin_params' => $pluginParameters,
252
            'custom_labels' => $customLabels)
253
        );
254
    }
255
256
    /**
257
     * Invokes the feedback page with information of the users current vocabulary.
258
     */
259
    public function invokeFeedbackForm($request)
260
    {
261
        $template = $this->twig->load('feedback.twig');
262
        $this->model->setLocale($request->getLang());
263
        $vocabList = $this->model->getVocabularyList(false);
264
        $vocab = $request->getVocab();
265
266
        $feedbackSent = false;
267
        if ($request->getQueryParamPOST('message')) {
268
            $feedbackSent = true;
269
            $feedbackMsg = $request->getQueryParamPOST('message');
270
            $feedbackName = $request->getQueryParamPOST('name');
271
            $feedbackEmail = $request->getQueryParamPOST('email');
272
            $msgSubject = $request->getQueryParamPOST('msgsubject');
273
            $feedbackVocab = $request->getQueryParamPOST('vocab');
274
            $feedbackVocabEmail = ($feedbackVocab !== null && $feedbackVocab !== '') ?
275
                $this->model->getVocabulary($feedbackVocab)->getConfig()->getFeedbackRecipient() : null;
276
            // if the hidden field has been set a value we have found a spam bot
277
            // and we do not actually send the message.
278
            if ($this->honeypot->validateHoneypot($request->getQueryParamPOST('item-description')) &&
279
                $this->honeypot->validateHoneytime($request->getQueryParamPOST('user-captcha'), $this->model->getConfig()->getHoneypotTime())) {
280
                $this->sendFeedback($request, $feedbackMsg, $msgSubject, $feedbackName, $feedbackEmail, $feedbackVocab, $feedbackVocabEmail);
281
            }
282
        }
283
        echo $template->render(
284
            array(
285
                'languages' => $this->languages,
286
                'vocab' => $vocab,
287
                'vocabList' => $vocabList,
288
                'feedback_sent' => $feedbackSent,
289
                'request' => $request,
290
            )
291
        );
292
    }
293
294
    private function createFeedbackHeaders($fromName, $fromEmail, $toMail, $sender)
295
    {
296
        $headers = "MIME-Version: 1.0" . "\r\n";
297
        $headers .= "Content-type: text/html; charset=UTF-8" . "\r\n";
298
        if (!empty($toMail)) {
299
            $headers .= "Cc: " . $this->model->getConfig()->getFeedbackAddress() . "\r\n";
300
        }
301
        if (!empty($fromEmail)) {
302
            $headers .= "Reply-To: $fromName <$fromEmail>\r\n";
303
        }
304
        $service = $this->model->getConfig()->getServiceName();
305
        return $headers . "From: $fromName via $service <$sender>";
306
    }
307
308
    /**
309
     * Sends the user entered message through the php's mailer.
310
     * @param string $message content given by user.
311
     * @param string $messageSubject subject line given by user.
312
     * @param string $fromName senders own name.
313
     * @param string $fromEmail senders email address.
314
     * @param string $fromVocab which vocabulary is the feedback related to.
315
     */
316
    public function sendFeedback($request, $message, $messageSubject, $fromName = null, $fromEmail = null, $fromVocab = null, $toMail = null)
317
    {
318
        $toAddress = ($toMail) ? $toMail : $this->model->getConfig()->getFeedbackAddress();
319
        $messageSubject = "[" . $this->model->getConfig()->getServiceName() . "] " . $messageSubject;
320
        if ($fromVocab !== null && $fromVocab !== '') {
321
            $message = 'Feedback from vocab: ' . strtoupper($fromVocab) . "<br />" . $message;
322
        }
323
        $envelopeSender = $this->model->getConfig()->getFeedbackEnvelopeSender();
324
        // determine the sender address of the message
325
        $sender = $this->model->getConfig()->getFeedbackSender();
326
        if (empty($sender)) {
327
            $sender = $envelopeSender;
328
        }
329
        if (empty($sender)) {
330
            $sender = $this->model->getConfig()->getFeedbackAddress();
331
        }
332
333
        // determine sender name - default to "anonymous user" if not given by user
334
        if (empty($fromName)) {
335
            $fromName = "anonymous user";
336
        }
337
        $headers = $this->createFeedbackHeaders($fromName, $fromEmail, $toMail, $sender);
338
        $params = empty($envelopeSender) ? '' : "-f $envelopeSender";
339
        // adding some information about the user for debugging purposes.
340
        $message = $message . "<br /><br /> Debugging information:"
341
            . "<br />Timestamp: " . date(DATE_RFC2822)
342
            . "<br />User agent: " . $request->getServerConstant('HTTP_USER_AGENT')
343
            . "<br />Referer: " . $request->getServerConstant('HTTP_REFERER');
344
345
        try {
346
            mail($toAddress, $messageSubject, $message, $headers, $params);
347
        } catch (Exception $e) {
348
            header("HTTP/1.0 404 Not Found");
349
            $template = $this->twig->load('error.twig');
350
            if ($this->model->getConfig()->getLogCaughtExceptions()) {
351
                error_log('Caught exception: ' . $e->getMessage());
352
            }
353
354
            echo $template->render(
355
                array(
356
                    'languages' => $this->languages,
357
                )
358
            );
359
360
            return;
361
        }
362
    }
363
364
    /**
365
     * Invokes the about page for the Skosmos service.
366
     */
367
    public function invokeAboutPage($request)
368
    {
369
        $template = $this->twig->load('about.twig');
370
        $this->model->setLocale($request->getLang());
371
        $url = $request->getServerConstant('HTTP_HOST');
372
373
        echo $template->render(
374
            array(
375
                'languages' => $this->languages,
376
                'server_instance' => $url,
377
                'request' => $request,
378
            )
379
        );
380
    }
381
382
    /**
383
     * Invokes the search for concepts in all the available ontologies.
384
     */
385
    public function invokeGlobalSearch($request)
386
    {
387
        $lang = $request->getLang();
388
        $template = $this->twig->load('global-search.twig');
389
        $this->model->setLocale($request->getLang());
390
391
        $parameters = new ConceptSearchParameters($request, $this->model->getConfig());
392
393
        $vocabs = $request->getQueryParam('vocabs'); # optional
394
        // convert to vocids array to support multi-vocabulary search
395
        $vocids = ($vocabs !== null && $vocabs !== '') ? explode(' ', $vocabs) : null;
396
        $vocabObjects = array();
397
        if ($vocids) {
398
            foreach ($vocids as $vocid) {
399
                try {
400
                    $vocabObjects[] = $this->model->getVocabulary($vocid);
401
                } catch (ValueError $e) {
402
                    // fail fast with an error page if the vocabulary cannot be found
403
                    if ($this->model->getConfig()->getLogCaughtExceptions()) {
404
                        error_log('Caught exception: ' . $e->getMessage());
405
                    }
406
                    header("HTTP/1.0 400 Bad Request");
407
                    $this->invokeGenericErrorPage($request, $e->getMessage());
408
                    return;
409
                }
410
            }
411
        }
412
        $parameters->setVocabularies($vocabObjects);
413
414
        $counts = null;
415
        $searchResults = null;
416
        $errored = false;
417
418
        try {
419
            $countAndResults = $this->model->searchConceptsAndInfo($parameters);
420
            $counts = $countAndResults['count'];
421
            $searchResults = $countAndResults['results'];
422
        } catch (Exception $e) {
423
            $errored = true;
424
            header("HTTP/1.0 500 Internal Server Error");
425
            if ($this->model->getConfig()->getLogCaughtExceptions()) {
426
                error_log('Caught exception: ' . $e->getMessage());
427
            }
428
        }
429
        $vocabList = $this->model->getVocabularyList();
430
        $sortedVocabs = $this->model->getVocabularyList(false, true);
431
        $langList = $this->model->getLanguages($lang);
432
        $contentLanguages = array_flip($this->model->getLanguages($request->getLang()));
433
434
        echo $template->render(
435
            array(
436
                'search_count' => $counts,
437
                'languages' => $this->languages,
438
                'content_languages' => $contentLanguages,
439
                'search_results' => $searchResults,
440
                'rest' => $parameters->getOffset() > 0,
441
                'global_search' => true,
442
                'search_failed' => $errored,
443
                'term' => $request->getQueryParamRaw('q'),
444
                'lang_list' => $langList,
445
                'vocabs' => isset($vocabs) ? str_replace(' ', '+', $vocabs) : null,
446
                'vocab_list' => $vocabList,
447
                'sorted_vocabs' => $sortedVocabs,
448
                'request' => $request,
449
                'parameters' => $parameters
450
            )
451
        );
452
    }
453
454
    /**
455
     * Invokes the search for a single vocabs concepts.
456
     */
457
    public function invokeVocabularySearch($request)
458
    {
459
        $template = $this->twig->load('vocab-search.twig');
460
        $this->model->setLocale($request->getLang());
461
        $vocab = $request->getVocab();
462
        $searchResults = null;
463
        try {
464
            $vocabTypes = $this->model->getTypes($request->getVocabid(), $request->getLang());
465
        } catch (Exception $e) {
466
            header("HTTP/1.0 500 Internal Server Error");
467
            if ($this->model->getConfig()->getLogCaughtExceptions()) {
468
                error_log('Caught exception: ' . $e->getMessage());
469
            }
470
471
            echo $template->render(
472
                array(
473
                    'languages' => $this->languages,
474
                    'vocab' => $vocab,
475
                    'request' => $request,
476
                    'content_languages' => $this->parseVocabularyLanguageOrder($vocab),
477
                    'search_results' => $searchResults
478
                )
479
            );
480
481
            return;
482
        }
483
484
        $langcodes = $vocab->getConfig()->getShowLangCodes();
485
        $parameters = new ConceptSearchParameters($request, $this->model->getConfig());
486
487
        try {
488
            $countAndResults = $this->model->searchConceptsAndInfo($parameters);
489
            $counts = $countAndResults['count'];
490
            $searchResults = $countAndResults['results'];
491
        } catch (Exception $e) {
492
            header("HTTP/1.0 404 Not Found");
493
            if ($this->model->getConfig()->getLogCaughtExceptions()) {
494
                error_log('Caught exception: ' . $e->getMessage());
495
            }
496
497
            echo $template->render(
498
                array(
499
                    'languages' => $this->languages,
500
                    'vocab' => $vocab,
501
                    'term' => $request->getQueryParam('q'),
502
                    'search_results' => $searchResults
503
                )
504
            );
505
            return;
506
        }
507
        echo $template->render(
508
            array(
509
                'languages' => $this->languages,
510
                'content_languages' => $this->parseVocabularyLanguageOrder($vocab),
511
                'vocab' => $vocab,
512
                'search_results' => $searchResults,
513
                'search_count' => $counts,
514
                'rest' => $parameters->getOffset() > 0,
515
                'limit_parent' => $parameters->getParentLimit(),
516
                'limit_type' =>  $request->getQueryParam('type') ? explode('+', $request->getQueryParam('type')) : null,
517
                'limit_group' => $parameters->getGroupLimit(),
518
                'limit_scheme' =>  $request->getQueryParam('scheme') ? explode('+', $request->getQueryParam('scheme')) : null,
519
                'group_index' => $vocab->listConceptGroups($request->getContentLang()),
520
                'parameters' => $parameters,
521
                'term' => $request->getQueryParamRaw('q'),
522
                'types' => $vocabTypes,
523
                'explicit_langcodes' => $langcodes,
524
                'request' => $request,
525
            )
526
        );
527
    }
528
529
    /**
530
     * Loads and renders the view containing a specific vocabulary.
531
     */
532
    public function invokeVocabularyHome($request)
533
    {
534
        $lang = $request->getLang();
0 ignored issues
show
The assignment to $lang is dead and can be removed.
Loading history...
535
        $this->model->setLocale($request->getLang());
536
        $vocab = $request->getVocab();
537
538
        $defaultView = $vocab->getConfig()->getDefaultSidebarView();
539
540
        $pluginParameters = json_encode($vocab->getConfig()->getPluginParameters());
541
542
        $template = $this->twig->load('vocab-home.twig');
543
544
        echo $template->render(
545
            array(
546
                'languages' => $this->languages,
547
                'vocab' => $vocab,
548
                'content_languages' => $this->parseVocabularyLanguageOrder($vocab),
549
                'search_letter' => 'A',
550
                'active_tab' => $defaultView,
551
                'request' => $request,
552
                'plugin_params' => $pluginParameters
553
            )
554
        );
555
    }
556
557
    /**
558
     * Invokes a very generic errorpage.
559
     */
560
    public function invokeGenericErrorPage($request, $message = null)
561
    {
562
        $this->model->setLocale($request->getLang());
563
        header("HTTP/1.0 404 Not Found");
564
        $template = $this->twig->load('error.twig');
565
        echo $template->render(
566
            array(
567
                'languages' => $this->languages,
568
                'request' => $request,
569
                'vocab' => $request->getVocab(),
570
                'message' => $message,
571
                'requested_page' => filter_input(INPUT_SERVER, 'REQUEST_URI', FILTER_SANITIZE_FULL_SPECIAL_CHARS),
0 ignored issues
show
The constant FILTER_SANITIZE_FULL_SPECIAL_CHARS was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
572
            )
573
        );
574
    }
575
}
576