WebController::sendFeedback()   C
last analyzed

Complexity

Conditions 10
Paths 192

Size

Total Lines 45
Code Lines 29

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 29
dl 0
loc 45
rs 6.9
c 0
b 0
f 0
cc 10
nc 192
nop 7

How to fix   Complexity   

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
/**
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
     * Loads and renders the landing page view.
163
     * @param Request $request
164
     */
165
    public function invokeLandingPage($request)
166
    {
167
        $this->model->setLocale($request->getLang());
168
        // load template
169
        $template = $this->twig->load('landing.twig');
170
        // set template variables
171
        $categoryLabel = $this->model->getClassificationLabel($request->getLang());
172
        $sortedVocabs = $this->model->getVocabularyList(false, true);
173
        $langList = $this->model->getLanguages($request->getLang());
174
        $listStyle = $this->listStyle();
175
176
        // render template
177
        echo $template->render(
178
            array(
179
                'sorted_vocabs' => $sortedVocabs,
180
                'category_label' => $categoryLabel,
181
                'languages' => $this->languages,
182
                'lang_list' => $langList,
183
                'request' => $request,
184
                'list_style' => $listStyle
185
            )
186
        );
187
    }
188
189
    /**
190
     * Invokes the concept page of a single concept in a specific vocabulary.
191
     *
192
     * @param Request $request
193
     */
194
    public function invokeVocabularyConcept(Request $request)
195
    {
196
        $lang = $request->getLang();
0 ignored issues
show
Unused Code introduced by
The assignment to $lang is dead and can be removed.
Loading history...
197
        $this->model->setLocale($request->getLang());
198
        $vocab = $request->getVocab();
199
200
        $langcodes = $vocab->getConfig()->getShowLangCodes();
201
        $uri = $vocab->getConceptURI($request->getUri()); // make sure it's a full URI
202
203
        $concept = $vocab->getConceptInfo($uri, $request->getContentLang());
204
        if (empty($concept)) {
205
            $this->invokeGenericErrorPage($request);
206
            return;
207
        }
208
        if ($this->notModified($concept)) {
209
            return;
210
        }
211
        $customLabels = $vocab->getConfig()->getPropertyLabelOverrides();
212
213
        $pluginParameters = json_encode($vocab->getConfig()->getPluginParameters());
214
        $template = $this->twig->load('concept.twig');
215
216
        $crumbs = $vocab->getBreadCrumbs($request->getContentLang(), $uri);
217
        echo $template->render(
218
            array(
219
            'concept' => $concept,
220
            'vocab' => $vocab,
221
            'concept_uri' => $uri,
222
            'languages' => $this->languages,
223
            'explicit_langcodes' => $langcodes,
224
            'visible_breadcrumbs' => $crumbs['breadcrumbs'],
225
            'hidden_breadcrumbs' => $crumbs['combined'],
226
            'request' => $request,
227
            'plugin_params' => $pluginParameters,
228
            'custom_labels' => $customLabels)
229
        );
230
    }
231
232
    /**
233
     * Invokes the feedback page with information of the users current vocabulary.
234
     */
235
    public function invokeFeedbackForm($request)
236
    {
237
        $template = $this->twig->load('feedback.twig');
238
        $this->model->setLocale($request->getLang());
239
        $vocabList = $this->model->getVocabularyList(false);
240
        $vocab = $request->getVocab();
241
242
        $feedbackSent = false;
243
        if ($request->getQueryParamPOST('message')) {
244
            $feedbackSent = true;
245
            $feedbackMsg = $request->getQueryParamPOST('message');
246
            $feedbackName = $request->getQueryParamPOST('name');
247
            $feedbackEmail = $request->getQueryParamPOST('email');
248
            $msgSubject = $request->getQueryParamPOST('msgsubject');
249
            $feedbackVocab = $request->getQueryParamPOST('vocab');
250
            $feedbackVocabEmail = ($feedbackVocab !== null && $feedbackVocab !== '') ?
251
                $this->model->getVocabulary($feedbackVocab)->getConfig()->getFeedbackRecipient() : null;
252
            // if the hidden field has been set a value we have found a spam bot
253
            // and we do not actually send the message.
254
            if ($this->honeypot->validateHoneypot($request->getQueryParamPOST('item-description')) &&
255
                $this->honeypot->validateHoneytime($request->getQueryParamPOST('user-captcha'), $this->model->getConfig()->getHoneypotTime())) {
256
                $this->sendFeedback($request, $feedbackMsg, $msgSubject, $feedbackName, $feedbackEmail, $feedbackVocab, $feedbackVocabEmail);
257
            }
258
        }
259
        echo $template->render(
260
            array(
261
                'languages' => $this->languages,
262
                'vocab' => $vocab,
263
                'vocabList' => $vocabList,
264
                'feedback_sent' => $feedbackSent,
265
                'request' => $request,
266
            )
267
        );
268
    }
269
270
    private function createFeedbackHeaders($fromName, $fromEmail, $toMail, $sender)
271
    {
272
        $headers = "MIME-Version: 1.0" . "\r\n";
273
        $headers .= "Content-type: text/html; charset=UTF-8" . "\r\n";
274
        if (!empty($toMail)) {
275
            $headers .= "Cc: " . $this->model->getConfig()->getFeedbackAddress() . "\r\n";
276
        }
277
        if (!empty($fromEmail)) {
278
            $headers .= "Reply-To: $fromName <$fromEmail>\r\n";
279
        }
280
        $service = $this->model->getConfig()->getServiceName();
281
        return $headers . "From: $fromName via $service <$sender>";
282
    }
283
284
    /**
285
     * Sends the user entered message through the php's mailer.
286
     * @param string $message content given by user.
287
     * @param string $messageSubject subject line given by user.
288
     * @param string $fromName senders own name.
289
     * @param string $fromEmail senders email address.
290
     * @param string $fromVocab which vocabulary is the feedback related to.
291
     */
292
    public function sendFeedback($request, $message, $messageSubject, $fromName = null, $fromEmail = null, $fromVocab = null, $toMail = null)
293
    {
294
        $toAddress = ($toMail) ? $toMail : $this->model->getConfig()->getFeedbackAddress();
295
        $messageSubject = "[" . $this->model->getConfig()->getServiceName() . "] " . $messageSubject;
296
        if ($fromVocab !== null && $fromVocab !== '') {
297
            $message = 'Feedback from vocab: ' . strtoupper($fromVocab) . "<br />" . $message;
298
        }
299
        $envelopeSender = $this->model->getConfig()->getFeedbackEnvelopeSender();
300
        // determine the sender address of the message
301
        $sender = $this->model->getConfig()->getFeedbackSender();
302
        if (empty($sender)) {
303
            $sender = $envelopeSender;
304
        }
305
        if (empty($sender)) {
306
            $sender = $this->model->getConfig()->getFeedbackAddress();
307
        }
308
309
        // determine sender name - default to "anonymous user" if not given by user
310
        if (empty($fromName)) {
311
            $fromName = "anonymous user";
312
        }
313
        $headers = $this->createFeedbackHeaders($fromName, $fromEmail, $toMail, $sender);
314
        $params = empty($envelopeSender) ? '' : "-f $envelopeSender";
315
        // adding some information about the user for debugging purposes.
316
        $message = $message . "<br /><br /> Debugging information:"
317
            . "<br />Timestamp: " . date(DATE_RFC2822)
318
            . "<br />User agent: " . $request->getServerConstant('HTTP_USER_AGENT')
319
            . "<br />Referer: " . $request->getServerConstant('HTTP_REFERER');
320
321
        try {
322
            mail($toAddress, $messageSubject, $message, $headers, $params);
323
        } catch (Exception $e) {
324
            header("HTTP/1.0 404 Not Found");
325
            $template = $this->twig->load('error.twig');
326
            if ($this->model->getConfig()->getLogCaughtExceptions()) {
327
                error_log('Caught exception: ' . $e->getMessage());
328
            }
329
330
            echo $template->render(
331
                array(
332
                    'languages' => $this->languages,
333
                )
334
            );
335
336
            return;
337
        }
338
    }
339
340
    /**
341
     * Invokes the about page for the Skosmos service.
342
     */
343
    public function invokeAboutPage($request)
344
    {
345
        $template = $this->twig->load('about.twig');
346
        $this->model->setLocale($request->getLang());
347
        $url = $request->getServerConstant('HTTP_HOST');
348
349
        echo $template->render(
350
            array(
351
                'languages' => $this->languages,
352
                'server_instance' => $url,
353
                'request' => $request,
354
            )
355
        );
356
    }
357
358
    /**
359
     * Invokes the search for concepts in all the available ontologies.
360
     */
361
    public function invokeGlobalSearch($request)
362
    {
363
        $lang = $request->getLang();
364
        $template = $this->twig->load('global-search.twig');
365
        $this->model->setLocale($request->getLang());
366
367
        $parameters = new ConceptSearchParameters($request, $this->model->getConfig());
368
369
        $vocabs = $request->getQueryParam('vocabs'); # optional
370
        // convert to vocids array to support multi-vocabulary search
371
        $vocids = ($vocabs !== null && $vocabs !== '') ? explode(' ', $vocabs) : null;
372
        $vocabObjects = array();
373
        if ($vocids) {
374
            foreach ($vocids as $vocid) {
375
                try {
376
                    $vocabObjects[] = $this->model->getVocabulary($vocid);
377
                } catch (ValueError $e) {
378
                    // fail fast with an error page if the vocabulary cannot be found
379
                    if ($this->model->getConfig()->getLogCaughtExceptions()) {
380
                        error_log('Caught exception: ' . $e->getMessage());
381
                    }
382
                    header("HTTP/1.0 400 Bad Request");
383
                    $this->invokeGenericErrorPage($request, $e->getMessage());
384
                    return;
385
                }
386
            }
387
        }
388
        $parameters->setVocabularies($vocabObjects);
389
390
        $counts = null;
391
        $searchResults = null;
392
        $errored = false;
393
394
        try {
395
            $countAndResults = $this->model->searchConceptsAndInfo($parameters);
396
            $counts = $countAndResults['count'];
397
            $searchResults = $countAndResults['results'];
398
        } catch (Exception $e) {
399
            $errored = true;
400
            header("HTTP/1.0 500 Internal Server Error");
401
            if ($this->model->getConfig()->getLogCaughtExceptions()) {
402
                error_log('Caught exception: ' . $e->getMessage());
403
            }
404
        }
405
        $vocabList = $this->model->getVocabularyList();
406
        $sortedVocabs = $this->model->getVocabularyList(false, true);
407
        $langList = $this->model->getLanguages($lang);
408
409
        echo $template->render(
410
            array(
411
                'search_count' => $counts,
412
                'languages' => $this->languages,
413
                'search_results' => $searchResults,
414
                'rest' => $parameters->getOffset() > 0,
415
                'global_search' => true,
416
                'search_failed' => $errored,
417
                'term' => $request->getQueryParamRaw('q'),
418
                'lang_list' => $langList,
419
                'vocabs' => isset($vocabs) ? str_replace(' ', '+', $vocabs) : null,
420
                'vocab_list' => $vocabList,
421
                'sorted_vocabs' => $sortedVocabs,
422
                'request' => $request,
423
                'parameters' => $parameters
424
            )
425
        );
426
    }
427
428
    /**
429
     * Invokes the search for a single vocabs concepts.
430
     */
431
    public function invokeVocabularySearch($request)
432
    {
433
        $template = $this->twig->load('vocab-search.twig');
434
        $this->model->setLocale($request->getLang());
435
        $vocab = $request->getVocab();
436
        $searchResults = null;
437
        try {
438
            $vocabTypes = $this->model->getTypes($request->getVocabid(), $request->getLang());
439
        } catch (Exception $e) {
440
            header("HTTP/1.0 500 Internal Server Error");
441
            if ($this->model->getConfig()->getLogCaughtExceptions()) {
442
                error_log('Caught exception: ' . $e->getMessage());
443
            }
444
445
            echo $template->render(
446
                array(
447
                    'languages' => $this->languages,
448
                    'vocab' => $vocab,
449
                    'request' => $request,
450
                    'search_results' => $searchResults
451
                )
452
            );
453
454
            return;
455
        }
456
457
        $langcodes = $vocab->getConfig()->getShowLangCodes();
458
        $parameters = new ConceptSearchParameters($request, $this->model->getConfig());
459
460
        try {
461
            $countAndResults = $this->model->searchConceptsAndInfo($parameters);
462
            $counts = $countAndResults['count'];
463
            $searchResults = $countAndResults['results'];
464
        } catch (Exception $e) {
465
            header("HTTP/1.0 404 Not Found");
466
            if ($this->model->getConfig()->getLogCaughtExceptions()) {
467
                error_log('Caught exception: ' . $e->getMessage());
468
            }
469
470
            echo $template->render(
471
                array(
472
                    'languages' => $this->languages,
473
                    'vocab' => $vocab,
474
                    'term' => $request->getQueryParam('q'),
475
                    'search_results' => $searchResults
476
                )
477
            );
478
            return;
479
        }
480
        echo $template->render(
481
            array(
482
                'languages' => $this->languages,
483
                'vocab' => $vocab,
484
                'search_results' => $searchResults,
485
                'search_count' => $counts,
486
                'rest' => $parameters->getOffset() > 0,
487
                'limit_parent' => $parameters->getParentLimit(),
488
                'limit_type' =>  $request->getQueryParam('type') ? explode('+', $request->getQueryParam('type')) : null,
489
                'limit_group' => $parameters->getGroupLimit(),
490
                'limit_scheme' =>  $request->getQueryParam('scheme') ? explode('+', $request->getQueryParam('scheme')) : null,
491
                'group_index' => $vocab->listConceptGroups($request->getContentLang()),
492
                'parameters' => $parameters,
493
                'term' => $request->getQueryParamRaw('q'),
494
                'types' => $vocabTypes,
495
                'explicit_langcodes' => $langcodes,
496
                'request' => $request,
497
            )
498
        );
499
    }
500
501
    /**
502
     * Loads and renders the view containing a specific vocabulary.
503
     */
504
    public function invokeVocabularyHome($request)
505
    {
506
        $lang = $request->getLang();
0 ignored issues
show
Unused Code introduced by
The assignment to $lang is dead and can be removed.
Loading history...
507
        $this->model->setLocale($request->getLang());
508
        $vocab = $request->getVocab();
509
510
        $defaultView = $vocab->getConfig()->getDefaultSidebarView();
511
512
        $pluginParameters = json_encode($vocab->getConfig()->getPluginParameters());
513
514
        $template = $this->twig->load('vocab-home.twig');
515
516
        echo $template->render(
517
            array(
518
                'languages' => $this->languages,
519
                'vocab' => $vocab,
520
                'search_letter' => 'A',
521
                'active_tab' => $defaultView,
522
                'request' => $request,
523
                'plugin_params' => $pluginParameters
524
            )
525
        );
526
    }
527
528
    /**
529
     * Invokes a very generic errorpage.
530
     */
531
    public function invokeGenericErrorPage($request, $message = null)
532
    {
533
        $this->model->setLocale($request->getLang());
534
        header("HTTP/1.0 404 Not Found");
535
        $template = $this->twig->load('error.twig');
536
        echo $template->render(
537
            array(
538
                'languages' => $this->languages,
539
                'request' => $request,
540
                'vocab' => $request->getVocab(),
541
                'message' => $message,
542
                'requested_page' => filter_input(INPUT_SERVER, 'REQUEST_URI', FILTER_SANITIZE_FULL_SPECIAL_CHARS),
0 ignored issues
show
Bug introduced by
The constant FILTER_SANITIZE_FULL_SPECIAL_CHARS was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
543
            )
544
        );
545
    }
546
}
547