Completed
Push — master ( 9de5b8...ac5bab )
by Osma
02:11
created

WebController::createFeedbackHeaders()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
nc 4
nop 4
dl 0
loc 15
rs 9.7666
c 0
b 0
f 0
1
<?php
2
3
/**
4
 * Importing the dependencies.
5
 */
6
use \Punic\Language;
7
8
/**
9
 * WebController is an extension of the Controller that handles all
10
 * the requests originating from the view of the website.
11
 */
12
class WebController extends Controller
13
{
14
    /**
15
     * Provides access to the templating engine.
16
     * @property object $twig the twig templating engine.
17
     */
18
    public $twig;
19
    public $honeypot;
20
21
    /**
22
     * Constructor for the WebController.
23
     * @param Model $model
24
     */
25
    public function __construct($model)
26
    {
27
        parent::__construct($model);
28
29
        // initialize Twig templates
30
        $tmpDir = $model->getConfig()->getTemplateCache();
31
32
        // check if the cache pointed by config.ttl exists, if not we create it.
33
        if (!file_exists($tmpDir)) {
34
            mkdir($tmpDir);
35
        }
36
37
        // specify where to look for templates and cache
38
        $loader = new Twig_Loader_Filesystem('view');
39
        // initialize Twig environment
40
        $this->twig = new Twig_Environment($loader, array('cache' => $tmpDir,'auto_reload' => true));
41
        $this->twig->addExtension(new Twig_Extensions_Extension_I18n());
42
        // used for setting the base href for the relative urls
43
        $this->twig->addGlobal("BaseHref", $this->getBaseHref());
44
        // setting the service name string from the config.ttl
45
        $this->twig->addGlobal("ServiceName", $this->model->getConfig()->getServiceName());
46
47
        // setting the service custom css file from the config.ttl
48
        if ($this->model->getConfig()->getCustomCss() !== null) {
49
            $this->twig->addGlobal("ServiceCustomCss", $this->model->getConfig()->getCustomCss());
50
        }
51
        // used for displaying the ui language selection as a dropdown
52
        if ($this->model->getConfig()->getUiLanguageDropdown() !== null) {
53
            $this->twig->addGlobal("LanguageDropdown", $this->model->getConfig()->getUiLanguageDropdown());
54
        }
55
56
        // setting the list of properties to be displayed in the search results
57
        $this->twig->addGlobal("PreferredProperties", array('skos:prefLabel', 'skos:narrower', 'skos:broader', 'skosmos:memberOf', 'skos:altLabel', 'skos:related'));
58
59
        // register a Twig filter for generating URLs for vocabulary resources (concepts and groups)
60
        $this->twig->addFilter(new Twig_SimpleFilter('link_url', array($this, 'linkUrlFilter')));
61
62
        // register a Twig filter for generating strings from language codes with CLDR
63
        $langFilter = new Twig_SimpleFilter('lang_name', function ($langcode, $lang) {
64
            return Language::getName($langcode, $lang);
65
        });
66
        $this->twig->addFilter($langFilter);
67
68
        // create the honeypot
69
        $this->honeypot = new \Honeypot();
70
        if (!$this->model->getConfig()->getHoneypotEnabled()) {
71
            $this->honeypot->disable();
72
        }
73
        $this->twig->addGlobal('honeypot', $this->honeypot);
74
    }
75
76
    /**
77
     * Creates Skosmos links from uris.
78
     * @param string $uri
79
     * @param Vocabulary $vocab
80
     * @param string $lang
81
     * @param string $type
82
     * @param string $clang content
83
     * @param string $term
84
     */
85
    public function linkUrlFilter($uri, $vocab, $lang, $type = 'page', $clang = null, $term = null) {
86
        // $vocab can either be null, a vocabulary id (string) or a Vocabulary object
87
        if ($vocab === null) {
88
            // target vocabulary is unknown, best bet is to link to the plain URI
89
            return $uri;
90
        } elseif (is_string($vocab)) {
91
            $vocid = $vocab;
92
            $vocab = $this->model->getVocabulary($vocid);
93
        } else {
94
            $vocid = $vocab->getId();
95
        }
96
97
        $params = array();
98
        if (isset($clang) && $clang !== $lang) {
99
            $params['clang'] = $clang;
100
        }
101
102
        if (isset($term)) {
103
            $params['q'] = $term;
104
        }
105
106
        // case 1: URI within vocabulary namespace: use only local name
107
        $localname = $vocab->getLocalName($uri);
108
        if ($localname !== $uri && $localname === urlencode($localname)) {
109
            // check that the prefix stripping worked, and there are no problematic chars in localname
110
            $paramstr = sizeof($params) > 0 ? '?' . http_build_query($params) : '';
111
            if ($type && $type !== '' && $type !== 'vocab' && !($localname === '' && $type === 'page')) {
112
                return "$vocid/$lang/$type/$localname" . $paramstr;
113
            }
114
115
            return "$vocid/$lang/$localname" . $paramstr;
116
        }
117
118
        // case 2: URI outside vocabulary namespace, or has problematic chars
119
        // pass the full URI as parameter instead
120
        $params['uri'] = $uri;
121
        return "$vocid/$lang/$type/?" . http_build_query($params);
122
    }
123
124
    /**
125
     * Guess the language of the user. Return a language string that is one
126
     * of the supported languages defined in the $LANGUAGES setting, e.g. "fi".
127
     * @param string $vocid identifier for the vocabulary eg. 'yso'.
128
     * @return string returns the language choice as a numeric string value
129
     */
130
    public function guessLanguage($vocid = null)
131
    {
132
        // 1. select language based on SKOSMOS_LANGUAGE cookie
133
        if (filter_input(INPUT_COOKIE, 'SKOSMOS_LANGUAGE', FILTER_SANITIZE_STRING)) {
134
            return filter_input(INPUT_COOKIE, 'SKOSMOS_LANGUAGE', FILTER_SANITIZE_STRING);
135
        }
136
137
        // 2. if vocabulary given, select based on the default language of the vocabulary
138
        if ($vocid !== null && $vocid !== '') {
139
            try {
140
                $vocab = $this->model->getVocabulary($vocid);
141
                return $vocab->getConfig()->getDefaultLanguage();
142
            } catch (Exception $e) {
143
                // vocabulary id not found, move on to the next selection method
144
            }
145
        }
146
147
        // 3. select language based on Accept-Language header
148
        header('Vary: Accept-Language'); // inform caches that a decision was made based on Accept header
149
        $this->negotiator = new \Negotiation\LanguageNegotiator();
150
        $langcodes = array_keys($this->languages);
151
        // using a random language from the configured UI languages when there is no accept language header set
152
        $acceptLanguage = filter_input(INPUT_SERVER, 'HTTP_ACCEPT_LANGUAGE', FILTER_SANITIZE_STRING) ? filter_input(INPUT_SERVER, 'HTTP_ACCEPT_LANGUAGE', FILTER_SANITIZE_STRING) : $langcodes[0];
153
        $bestLang = $this->negotiator->getBest($acceptLanguage, $langcodes);
154
        if (isset($bestLang) && in_array($bestLang, $langcodes)) {
155
            return $bestLang->getValue();
156
        }
157
158
        // show default site or prompt for language
159
        return $langcodes[0];
160
    }
161
162
    /**
163
     * Determines a css class that controls width and positioning of the vocabulary list element.
164
     * The layout is wider if the left/right box templates have not been provided.
165
     * @return string css class for the container eg. 'voclist-wide' or 'voclist-right'
166
     */
167
    private function listStyle() {
168
        $left = file_exists('view/left.inc');
169
        $right = file_exists('view/right.inc');
170
        $ret = 'voclist';
171
        if (!$left && !$right) {
172
            $ret .= '-wide';
173
        } else if (!($left && $right) && ($right || $left)) {
174
            $ret .= ($right) ? '-left' : '-right';
175
        }
176
        return $ret;
177
    }
178
179
    /**
180
     * Loads and renders the view containing all the vocabularies.
181
     * @param Request $request
182
     */
183
    public function invokeVocabularies($request)
184
    {
185
        // set language parameters for gettext
186
        $this->setLanguageProperties($request->getLang());
187
        // load template
188
        $template = $this->twig->loadTemplate('light.twig');
189
        // set template variables
190
        $categoryLabel = $this->model->getClassificationLabel($request->getLang());
191
        $sortedVocabs = $this->model->getVocabularyList(false, true);
192
        $langList = $this->model->getLanguages($request->getLang());
193
        $listStyle = $this->listStyle();
194
195
        // render template
196
        echo $template->render(
197
            array(
198
                'sorted_vocabs' => $sortedVocabs,
199
                'category_label' => $categoryLabel,
200
                'languages' => $this->languages,
201
                'lang_list' => $langList,
202
                'request' => $request,
203
                'list_style' => $listStyle
204
            ));
205
    }
206
207
    /**
208
     * Invokes the concept page of a single concept in a specific vocabulary.
209
     *
210
     * @param Request $request
211
     */
212
    public function invokeVocabularyConcept(Request $request)
213
    {
214
        $lang = $request->getLang();
215
        $this->setLanguageProperties($lang);
216
        $vocab = $request->getVocab();
217
218
        $langcodes = $vocab->getConfig()->getShowLangCodes();
219
        $uri = $vocab->getConceptURI($request->getUri()); // make sure it's a full URI
220
221
        $results = $vocab->getConceptInfo($uri, $request->getContentLang());
222
        if (!$results) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $results of type Concept[] 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...
223
            $this->invokeGenericErrorPage($request);
224
            return;
225
        }
226
        $useModifiedDate = $vocab->getConfig()->getUseModifiedDate();
227
        if ($useModifiedDate) {
228
            $modifiedDate = $this->getModifiedDate($results[0], $vocab);
229
            // return if the controller sends the not modified header
230
            if ($this->sendNotModifiedHeader($modifiedDate)) {
0 ignored issues
show
Bug introduced by
It seems like $modifiedDate defined by $this->getModifiedDate($results[0], $vocab) on line 228 can be null; however, Controller::sendNotModifiedHeader() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
231
                return;
232
            }
233
        }
234
        /** @var \Twig\Template $template */
235
        $template = (in_array('skos:Concept', $results[0]->getType()) || in_array('skos:ConceptScheme', $results[0]->getType())) ? $this->twig->loadTemplate('concept-info.twig') : $this->twig->loadTemplate('group-contents.twig');
236
237
        $crumbs = $vocab->getBreadCrumbs($request->getContentLang(), $uri);
238
        echo $template->render(array(
239
            'search_results' => $results,
240
            'vocab' => $vocab,
241
            'languages' => $this->languages,
242
            'explicit_langcodes' => $langcodes,
243
            'bread_crumbs' => $crumbs['breadcrumbs'],
244
            'combined' => $crumbs['combined'],
245
            'request' => $request)
246
        );
247
    }
248
249
    /**
250
     * @param Concept $concept
251
     * @param Vocabulary $vocab
252
     * @return DateTime|null
253
     */
254
    protected function getModifiedDate(Concept $concept, Vocabulary $vocab)
255
    {
256
        $modifiedDate = $concept->getModifiedDate();
257
        if (!$modifiedDate) {
258
            $conceptSchemeURI = $vocab->getDefaultConceptScheme();
259
            if ($conceptSchemeURI) {
260
                $conceptSchemeGraph = $vocab->getConceptScheme($conceptSchemeURI);
261
                if (!$conceptSchemeGraph->isEmpty()) {
0 ignored issues
show
Bug introduced by
The method isEmpty does only exist in EasyRdf\Graph, but not in EasyRdf\Http\Response and EasyRdf\Sparql\Result.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
262
                    $literal = $conceptSchemeGraph->getLiteral($conceptSchemeURI, "dc:modified");
0 ignored issues
show
Bug introduced by
The method getLiteral does only exist in EasyRdf\Graph, but not in EasyRdf\Http\Response and EasyRdf\Sparql\Result.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
263
                    $modifiedDate = $literal->getValue();
264
                }
265
            }
266
        }
267
        return $modifiedDate;
268
    }
269
270
    /**
271
     * Invokes the feedback page with information of the users current vocabulary.
272
     */
273
    public function invokeFeedbackForm($request)
274
    {
275
        $template = $this->twig->loadTemplate('feedback.twig');
276
        $this->setLanguageProperties($request->getLang());
277
        $vocabList = $this->model->getVocabularyList(false);
278
        $vocab = $request->getVocab();
279
280
        $feedbackSent = false;
281
        $feedbackMsg = null;
282
        if ($request->getQueryParamPOST('message')) {
283
            $feedbackSent = true;
284
            $feedbackMsg = $request->getQueryParamPOST('message');
285
        }
286
        $feedbackName = $request->getQueryParamPOST('name');
287
        $feedbackEmail = $request->getQueryParamPOST('email');
288
        $feedbackVocab = $request->getQueryParamPOST('vocab');
289
290
        $feedbackVocabEmail = ($feedbackVocab !== null && $feedbackVocab !== '') ?
291
            $this->model->getVocabulary($feedbackVocab)->getConfig()->getFeedbackRecipient() : null;
292
293
        // if the hidden field has been set a value we have found a spam bot
294
        // and we do not actually send the message.
295
        if ($this->honeypot->validateHoneypot($request->getQueryParamPOST('item-description')) &&
296
            $this->honeypot->validateHoneytime($request->getQueryParamPOST('user-captcha'), $this->model->getConfig()->getHoneypotTime())) {
297
            $this->sendFeedback($request, $feedbackMsg, $feedbackName, $feedbackEmail, $feedbackVocab, $feedbackVocabEmail);
298
        }
299
300
        echo $template->render(
301
            array(
302
                'languages' => $this->languages,
303
                'vocab' => $vocab,
304
                'vocabList' => $vocabList,
305
                'feedback_sent' => $feedbackSent,
306
                'request' => $request,
307
            ));
308
    }
309
310
    private function createFeedbackHeaders($fromName, $fromEmail, $toMail, $sender)
311
    {
312
        $headers = "MIME-Version: 1.0″ . '\r\n";
313
        $headers .= "Content-type: text/html; charset=UTF-8" . "\r\n";
314
        if (!empty($toMail)) {
315
            $headers .= "Cc: " . $this->model->getConfig()->getFeedbackAddress() . "\r\n";
316
        }
317
        if (!empty($fromEmail)) {
318
            $headers .= "Reply-To: $fromName <$fromEmail>\r\n";
319
        }
320
321
        $service = $this->model->getConfig()->getServiceName();
322
        $headers .= "From: $fromName via $service <$sender>";
323
        return $headers;
324
    }
325
326
    /**
327
     * Sends the user entered message through the php's mailer.
328
     * @param string $message only required parameter is the actual message.
329
     * @param string $fromName senders own name.
330
     * @param string $fromEmail senders email adress.
331
     * @param string $fromVocab which vocabulary is the feedback related to.
332
     */
333
    public function sendFeedback($request, $message, $fromName = null, $fromEmail = null, $fromVocab = null, $toMail = null)
334
    {
335
        $toAddress = ($toMail) ? $toMail : $this->model->getConfig()->getFeedbackAddress();
336
        if ($fromVocab !== null && $fromVocab !== '') {
337
            $message = 'Feedback from vocab: ' . strtoupper($fromVocab) . "<br />" . $message;
338
        }
339
340
        $envelopeSender = $this->model->getConfig()->getFeedbackEnvelopeSender();
341
        $subject = $this->model->getConfig()->getServiceName() . " feedback";
342
        // determine the sender address of the message
343
        $sender = $this->model->getConfig()->getFeedbackSender();
344
        if (empty($sender)) $sender = $envelopeSender;
345
        if (empty($sender)) $sender = $this->model->getConfig()->getFeedbackAddress();
346
347
        // determine sender name - default to "anonymous user" if not given by user
348
        if (empty($fromName)) $fromName = "anonymous user";
349
350
        $headers = $this->createFeedbackHeaders($fromName, $fromEmail, $toMail, $sender);
351
        $params = empty($envelopeSender) ? '' : "-f $envelopeSender";
352
353
        // adding some information about the user for debugging purposes.
354
        $message = $message . "<br /><br /> Debugging information:"
355
            . "<br />Timestamp: " . date(DATE_RFC2822)
356
            . "<br />User agent: " . $request->getServerConstant('HTTP_USER_AGENT')
357
            . "<br />Referer: " . $request->getServerConstant('HTTP_REFERER');
358
359
        try {
360
            mail($toAddress, $subject, $message, $headers, $params);
361
        } catch (Exception $e) {
362
            header("HTTP/1.0 404 Not Found");
363
            $template = $this->twig->loadTemplate('error-page.twig');
364
            if ($this->model->getConfig()->getLogCaughtExceptions()) {
365
                error_log('Caught exception: ' . $e->getMessage());
366
            }
367
368
            echo $template->render(
369
                array(
370
                    'languages' => $this->languages,
371
                ));
372
373
            return;
374
        }
375
    }
376
377
    /**
378
     * Invokes the about page for the Skosmos service.
379
     */
380 View Code Duplication
    public function invokeAboutPage($request)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
381
    {
382
        $template = $this->twig->loadTemplate('about.twig');
383
        $this->setLanguageProperties($request->getLang());
384
        $url = $request->getServerConstant('HTTP_HOST');
385
        $version = $this->model->getVersion();
386
387
        echo $template->render(
388
            array(
389
                'languages' => $this->languages,
390
                'version' => $version,
391
                'server_instance' => $url,
392
                'request' => $request,
393
            ));
394
    }
395
396
    /**
397
     * Invokes the search for concepts in all the availible ontologies.
398
     */
399
    public function invokeGlobalSearch($request)
400
    {
401
        $lang = $request->getLang();
402
        $template = $this->twig->loadTemplate('vocab-search-listing.twig');
403
        $this->setLanguageProperties($lang);
404
405
        $parameters = new ConceptSearchParameters($request, $this->model->getConfig());
406
407
        $vocabs = $request->getQueryParam('vocabs'); # optional
408
        // convert to vocids array to support multi-vocabulary search
409
        $vocids = ($vocabs !== null && $vocabs !== '') ? explode(' ', $vocabs) : null;
410
        $vocabObjects = array();
411
        if ($vocids) {
412
            foreach($vocids as $vocid) {
413
                $vocabObjects[] = $this->model->getVocabulary($vocid);
414
            }
415
        }
416
        $parameters->setVocabularies($vocabObjects);
417
418
        try {
419
            $countAndResults = $this->model->searchConceptsAndInfo($parameters);
420
        } catch (Exception $e) {
421
            header("HTTP/1.0 404 Not Found");
422
            if ($this->model->getConfig()->getLogCaughtExceptions()) {
423
                error_log('Caught exception: ' . $e->getMessage());
424
            }
425
            $this->invokeGenericErrorPage($request, $e->getMessage());
426
            return;
427
        }
428
        $counts = $countAndResults['count'];
429
        $searchResults = $countAndResults['results'];
430
        $vocabList = $this->model->getVocabularyList();
431
        $sortedVocabs = $this->model->getVocabularyList(false, true);
432
        $langList = $this->model->getLanguages($lang);
433
434
        echo $template->render(
435
            array(
436
                'search_count' => $counts,
437
                'languages' => $this->languages,
438
                'search_results' => $searchResults,
439
                'rest' => $parameters->getOffset()>0,
440
                'global_search' => true,
441
                'term' => $request->getQueryParamRaw('q'),
442
                'lang_list' => $langList,
443
                'vocabs' => str_replace(' ', '+', $vocabs),
444
                'vocab_list' => $vocabList,
445
                'sorted_vocabs' => $sortedVocabs,
446
                'request' => $request,
447
                'parameters' => $parameters
448
            ));
449
    }
450
451
    /**
452
     * Invokes the search for a single vocabs concepts.
453
     */
454
    public function invokeVocabularySearch($request)
455
    {
456
        $template = $this->twig->loadTemplate('vocab-search-listing.twig');
457
        $this->setLanguageProperties($request->getLang());
458
        $vocab = $request->getVocab();
459
        try {
460
            $vocabTypes = $this->model->getTypes($request->getVocabid(), $request->getLang());
461
        } catch (Exception $e) {
462
            header("HTTP/1.0 404 Not Found");
463
            if ($this->model->getConfig()->getLogCaughtExceptions()) {
464
                error_log('Caught exception: ' . $e->getMessage());
465
            }
466
467
            echo $template->render(
468
                array(
469
                    'languages' => $this->languages,
470
                ));
471
472
            return;
473
        }
474
475
        $langcodes = $vocab->getConfig()->getShowLangCodes();
476
        $parameters = new ConceptSearchParameters($request, $this->model->getConfig());
477
478
        try {
479
            $countAndResults = $this->model->searchConceptsAndInfo($parameters);
480
            $counts = $countAndResults['count'];
481
            $searchResults = $countAndResults['results'];
482
        } catch (Exception $e) {
483
            header("HTTP/1.0 404 Not Found");
484
            if ($this->model->getConfig()->getLogCaughtExceptions()) {
485
                error_log('Caught exception: ' . $e->getMessage());
486
            }
487
488
            echo $template->render(
489
                array(
490
                    'languages' => $this->languages,
491
                    'vocab' => $vocab,
492
                    'term' => $request->getQueryParam('q'),
493
                ));
494
            return;
495
        }
496
        echo $template->render(
497
            array(
498
                'languages' => $this->languages,
499
                'vocab' => $vocab,
500
                'search_results' => $searchResults,
501
                'search_count' => $counts,
502
                'rest' => $parameters->getOffset()>0,
503
                'limit_parent' => $parameters->getParentLimit(),
504
                'limit_type' =>  $request->getQueryParam('type') ? explode('+', $request->getQueryParam('type')) : null,
505
                'limit_group' => $parameters->getGroupLimit(),
506
                'limit_scheme' =>  $request->getQueryParam('scheme') ? explode('+', $request->getQueryParam('scheme')) : null,
507
                'group_index' => $vocab->listConceptGroups($request->getContentLang()),
508
                'parameters' => $parameters,
509
                'term' => $request->getQueryParamRaw('q'),
510
                'types' => $vocabTypes,
511
                'explicit_langcodes' => $langcodes,
512
                'request' => $request,
513
            ));
514
    }
515
516
    /**
517
     * Invokes the alphabetical listing for a specific vocabulary.
518
     */
519
    public function invokeAlphabeticalIndex($request)
520
    {
521
        $lang = $request->getLang();
522
        $this->setLanguageProperties($lang);
523
        $template = $this->twig->loadTemplate('alphabetical-index.twig');
524
        $vocab = $request->getVocab();
525
526
        $offset = ($request->getQueryParam('offset') && is_numeric($request->getQueryParam('offset')) && $request->getQueryParam('offset') >= 0) ? $request->getQueryParam('offset') : 0;
527
        if ($request->getQueryParam('limit')) {
528
            $count = $request->getQueryParam('limit');
529
        } else {
530
            $count = ($offset > 0) ? null : 250;
531
        }
532
533
        $contentLang = $request->getContentLang();
534
535
        $allAtOnce = $vocab->getConfig()->getAlphabeticalFull();
536
        if (!$allAtOnce) {
537
            $letters = $vocab->getAlphabet($contentLang);
538
            $letter = $request->getLetter();
539
            if ($letter === '') {
540
                $letter = $letters[0];
541
            }
542
            $searchResults = $vocab->searchConceptsAlphabetical($letter, $count, $offset, $contentLang);
543
        } else {
544
            $letters = null;
545
            $searchResults = $vocab->searchConceptsAlphabetical('*', null, null, $contentLang);
546
        }
547
548
        $request->setContentLang($contentLang);
549
550
        echo $template->render(
551
            array(
552
                'languages' => $this->languages,
553
                'vocab' => $vocab,
554
                'alpha_results' => $searchResults,
555
                'letters' => $letters,
556
                'all_letters' => $allAtOnce,
557
                'request' => $request,
558
            ));
559
    }
560
561
    /**
562
     * Invokes the vocabulary group index page template.
563
     * @param boolean $stats set to true to get vocabulary statistics visible.
564
     */
565 View Code Duplication
    public function invokeGroupIndex($request, $stats = false)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
566
    {
567
        $lang = $request->getLang();
568
        $this->setLanguageProperties($lang);
569
        $template = $this->twig->loadTemplate('group-index.twig');
570
        $vocab = $request->getVocab();
571
572
        echo $template->render(
573
            array(
574
                'languages' => $this->languages,
575
                'stats' => $stats,
576
                'vocab' => $vocab,
577
                'request' => $request,
578
            ));
579
    }
580
581
    /**
582
     * Loads and renders the view containing a specific vocabulary.
583
     */
584
    public function invokeVocabularyHome($request)
585
    {
586
        $lang = $request->getLang();
587
        // set language parameters for gettext
588
        $this->setLanguageProperties($lang);
589
        $vocab = $request->getVocab();
590
591
        $defaultView = $vocab->getConfig()->getDefaultSidebarView();
592
        // load template
593
        if ($defaultView === 'groups') {
594
            $this->invokeGroupIndex($request, true);
595
            return;
596
        }
597
598
        $template = $this->twig->loadTemplate('vocab.twig');
599
600
        echo $template->render(
601
            array(
602
                'languages' => $this->languages,
603
                'vocab' => $vocab,
604
                'search_letter' => 'A',
605
                'active_tab' => $defaultView,
606
                'request' => $request,
607
            ));
608
    }
609
610
    /**
611
     * Invokes a very generic errorpage.
612
     */
613
    public function invokeGenericErrorPage($request, $message = null)
614
    {
615
        $this->setLanguageProperties($request->getLang());
616
        header("HTTP/1.0 404 Not Found");
617
        $template = $this->twig->loadTemplate('error-page.twig');
618
        echo $template->render(
619
            array(
620
                'languages' => $this->languages,
621
                'request' => $request,
622
                'message' => $message,
623
                'requested_page' => filter_input(INPUT_SERVER, 'REQUEST_URI', FILTER_SANITIZE_STRING),
624
            ));
625
    }
626
627
    /**
628
     * Loads and renders the view containing a list of recent changes in the vocabulary.
629
     * @param Request $request
630
     */
631
    public function invokeChangeList($request, $prop='dc:created')
632
    {
633
        // set language parameters for gettext
634
        $this->setLanguageProperties($request->getLang());
635
        $vocab = $request->getVocab();
636
        $offset = ($request->getQueryParam('offset') && is_numeric($request->getQueryParam('offset')) && $request->getQueryParam('offset') >= 0) ? $request->getQueryParam('offset') : 0;
637
        $changeList = $vocab->getChangeList($prop, $request->getContentLang(), $request->getLang(), $offset);
638
        // load template
639
        $template = $this->twig->loadTemplate('changes.twig');
640
641
        // render template
642
        echo $template->render(
643
            array(
644
                'vocab' => $vocab,
645
                'languages' => $this->languages,
646
                'request' => $request,
647
                'changeList' => $changeList)
648
            );
649
    }
650
651
}
652