Completed
Push — develop ( 004a61...75ca32 )
by John
02:31
created

before_displayPageFoot_callback()   F

Complexity

Conditions 16
Paths 518

Size

Total Lines 69
Code Lines 41

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 2
Metric Value
c 2
b 0
f 2
dl 0
loc 69
rs 3.5202
cc 16
eloc 41
nc 518
nop 0

How to fix   Long Method    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
namespace Alpha\Controller;
4
5
use Alpha\Util\Logging\Logger;
6
use Alpha\Util\Logging\KPI;
7
use Alpha\Util\Config\ConfigProvider;
8
use Alpha\Util\Security\SecurityUtils;
9
use Alpha\Util\Extension\TCPDFFacade;
10
use Alpha\Util\Http\Request;
11
use Alpha\Util\Http\Response;
12
use Alpha\Util\Http\Session\SessionProviderFactory;
13
use Alpha\Util\File\FileUtils;
14
use Alpha\Model\Article;
15
use Alpha\Model\ArticleComment;
16
use Alpha\Model\Type\Relation;
17
use Alpha\View\View;
18
use Alpha\View\ViewState;
19
use Alpha\View\Widget\Button;
20
use Alpha\Exception\SecurityException;
21
use Alpha\Exception\AlphaException;
22
use Alpha\Exception\RecordNotFoundException;
23
use Alpha\Exception\IllegalArguementException;
24
use Alpha\Exception\ResourceNotFoundException;
25
use Alpha\Exception\FileNotFoundException;
26
use Alpha\Model\ActiveRecord;
27
use Alpha\Controller\Front\FrontController;
28
29
/**
30
 * Controller used handle Article objects.
31
 *
32
 * @since 1.0
33
 *
34
 * @author John Collins <[email protected]>
35
 * @license http://www.opensource.org/licenses/bsd-license.php The BSD License
36
 * @copyright Copyright (c) 2017, John Collins (founder of Alpha Framework).
37
 * All rights reserved.
38
 *
39
 * <pre>
40
 * Redistribution and use in source and binary forms, with or
41
 * without modification, are permitted provided that the
42
 * following conditions are met:
43
 *
44
 * * Redistributions of source code must retain the above
45
 *   copyright notice, this list of conditions and the
46
 *   following disclaimer.
47
 * * Redistributions in binary form must reproduce the above
48
 *   copyright notice, this list of conditions and the
49
 *   following disclaimer in the documentation and/or other
50
 *   materials provided with the distribution.
51
 * * Neither the name of the Alpha Framework nor the names
52
 *   of its contributors may be used to endorse or promote
53
 *   products derived from this software without specific
54
 *   prior written permission.
55
 *
56
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
57
 * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
58
 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
59
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
60
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
61
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
62
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
63
 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
64
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
65
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
66
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
67
 * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
68
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
69
 * </pre>
70
 */
71
class ArticleController extends ActiveRecordController implements ControllerInterface
72
{
73
    /**
74
     * The Article record object that this controller is currently working with.
75
     *
76
     * @var \Alpha\Model\Article
77
     *
78
     * @since 3.0
79
     */
80
    protected $record = null;
81
82
    /**
83
     * Trace logger.
84
     *
85
     * @var \Alpha\Util\Logging\Logger
86
     *
87
     * @since 1.0
88
     */
89
    private static $logger = null;
0 ignored issues
show
Comprehensibility introduced by
Consider using a different property name as you override a private property of the parent class.
Loading history...
90
91
    /**
92
     * constructor to set up the object.
93
     *
94
     * @since 1.0
95
     */
96
    public function __construct()
97
    {
98
        self::$logger = new Logger('ArticleController');
99
        self::$logger->debug('>>__construct()');
100
101
        // ensure that the super class constructor is called, indicating the rights group
102
        parent::__construct('Public');
103
104
        self::$logger->debug('<<__construct');
105
    }
106
107
    /**
108
     * Handle GET requests.
109
     *
110
     * @param \Alpha\Util\Http\Request
111
     *
112
     * @return \Alpha\Util\Http\Response
113
     *
114
     * @throws \Alpha\Exception\ResourceNotFoundException
115
     *
116
     * @since 1.0
117
     */
118
    public function doGET($request)
119
    {
120
        self::$logger->debug('>>doGET($request=['.var_export($request, true).'])');
121
122
        $config = ConfigProvider::getInstance();
123
124
        $params = $request->getParams();
125
126
        $body = '';
127
128
        // handle requests for PDFs
129
        if (isset($params['title']) && (isset($params['pdf']) || $request->getHeader('Accept') == 'application/pdf')) {
130
            try {
131
                $title = str_replace($config->get('cms.url.title.separator'), ' ', $params['title']);
132
133
                if (isset($params['ActiveRecordType']) && class_exists($params['ActiveRecordType'])) {
134
                    $record = new $params['ActiveRecordType'];
135
                } else {
136
                    $record = new Article();
137
                }
138
                $record->loadByAttribute('title', $title);
139
                $this->record = $record;
140
141
                ActiveRecord::disconnect();
142
143
                $pdf = new TCPDFFacade($record);
144
                $pdfData = $pdf->getPDFData();
145
                $pdfDownloadName = str_replace(' ', '-', $record->get('title').'.pdf');
146
147
                $headers = array(
148
                    'Pragma' => 'public',
149
                    'Expires' => 0,
150
                    'Cache-Control' => 'must-revalidate, post-check=0, pre-check=0',
151
                    'Content-Transfer-Encoding' => 'binary',
152
                    'Content-Type' => 'application/pdf',
153
                    'Content-Length' => strlen($pdfData),
154
                    'Content-Disposition' => 'attachment; filename="'.$pdfDownloadName.'";',
155
                );
156
157
                return new Response(200, $pdfData, $headers);
158
            } catch (IllegalArguementException $e) {
159
                self::$logger->error($e->getMessage());
160
                throw new ResourceNotFoundException($e->getMessage());
161
            } catch (RecordNotFoundException $e) {
162
                self::$logger->error($e->getMessage());
163
                throw new ResourceNotFoundException($e->getMessage());
164
            }
165
        }
166
167
        // view edit article requests
168
        if ((isset($params['view']) && $params['view'] == 'edit') && (isset($params['title']) || isset($params['ActiveRecordID']))) {
169
            if (isset($params['ActiveRecordType']) && class_exists($params['ActiveRecordType'])) {
170
                $record = new $params['ActiveRecordType'];
171
            } else {
172
                $record = new Article();
173
            }
174
175
            try {
176
                if (isset($params['title'])) {
177
                    $title = str_replace($config->get('cms.url.title.separator'), ' ', $params['title']);
178
                    $record->loadByAttribute('title', $title);
179
                } else {
180
                    $record->load($params['ActiveRecordID']);
181
                }
182
            } catch (RecordNotFoundException $e) {
183
                self::$logger->warn($e->getMessage());
184
                $body .= View::renderErrorPage(404, 'Failed to find the requested article!');
185
186
                return new Response(404, $body, array('Content-Type' => 'text/html'));
187
            }
188
189
            ActiveRecord::disconnect();
190
191
            $this->record = $record;
192
            $view = View::getInstance($record);
193
194
            // set up the title and meta details
195
            $this->setTitle($record->get('title').' (editing)');
196
            $this->setDescription('Page to edit '.$record->get('title').'.');
197
            $this->setKeywords('edit,article');
198
199
            $body .= View::displayPageHead($this);
200
201
            $message = $this->getStatusMessage();
202
            if (!empty($message)) {
203
                $body .= $message;
204
            }
205
206
            $body .= $view->editView(array('URI' => $request->getURI()));
207
            $body .= View::renderDeleteForm($request->getURI());
208
209
            $body .= View::displayPageFoot($this);
210
            self::$logger->debug('<<doGET');
211
212
            return new Response(200, $body, array('Content-Type' => 'text/html'));
213
        }
214
215
        // handle requests for viewing articles
216
        if (isset($params['title']) || isset($params['ActiveRecordID'])) {
217
            $KDP = new KPI('viewarticle');
218
            if (isset($params['ActiveRecordType']) && class_exists($params['ActiveRecordType'])) {
219
                $record = new $params['ActiveRecordType'];
220
            } else {
221
                $record = new Article();
222
            }
223
224
            try {
225
                if (isset($params['title'])) {
226
                    $title = str_replace($config->get('cms.url.title.separator'), ' ', $params['title']);
227
228
                    $record->loadByAttribute('title', $title, false, array('ID', 'version_num', 'created_ts', 'updated_ts', 'title', 'author', 'published', 'content', 'headerContent'));
229
                } else {
230
                    $record->load($params['ActiveRecordID']);
231
                }
232
233
                if (!$record->get('published')) {
234
                    throw new RecordNotFoundException('Attempted to load an article which is not published yet');
235
                }
236
237
                $record->set('tags', $record->getID());
238
            } catch (IllegalArguementException $e) {
239
                self::$logger->warn($e->getMessage());
240
                throw new ResourceNotFoundException('The file that you have requested cannot be found!');
241
            } catch (RecordNotFoundException $e) {
242
                self::$logger->warn($e->getMessage());
243
                throw new ResourceNotFoundException('The article that you have requested cannot be found!');
244
            }
245
246
            $this->record = $record;
247
            $this->setTitle($record->get('title'));
248
            $this->setDescription($record->get('description'));
249
250
            $recordView = View::getInstance($record);
251
252
            $body .= View::displayPageHead($this);
253
254
            $message = $this->getStatusMessage();
255
            if (!empty($message)) {
256
                $body .= $message;
257
            }
258
259
            $body .= $recordView->markdownView();
260
261
            $body .= View::displayPageFoot($this);
262
263
            $KDP->log();
264
265
            return new Response(200, $body, array('Content-Type' => 'text/html'));
266
        }
267
268
        // handle requests to view an article stored in a file
269
        if (isset($params['file'])) {
270
            try {
271
                $record = new Article();
272
273
                // just checking to see if the file path is absolute or not
274
                if (mb_substr($params['file'], 0, 1) == '/') {
275
                    $record->loadContentFromFile($params['file']);
276
                } else {
277
                    $record->loadContentFromFile($config->get('app.root').'docs/'.$params['file']);
278
                }
279
            } catch (IllegalArguementException $e) {
280
                self::$logger->error($e->getMessage());
281
                throw new ResourceNotFoundException($e->getMessage());
282
            } catch (FileNotFoundException $e) {
283
                self::$logger->warn($e->getMessage().' File path is ['.$params['file'].']');
284
                throw new ResourceNotFoundException('Failed to load the requested article from the file system!');
285
            }
286
287
            $this->record = $record;
288
            $this->setTitle($record->get('title'));
289
290
            $recordView = View::getInstance($record);
291
292
            $body .= View::displayPageHead($this, false);
0 ignored issues
show
Unused Code introduced by
The call to View::displayPageHead() has too many arguments starting with false.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
293
294
            $body .= $recordView->markdownView();
295
296
            $body .= View::displayPageFoot($this);
297
298
            return new Response(200, $body, array('Content-Type' => 'text/html'));
299
        }
300
301
        // handle requests to view a list of articles
302
        if (isset($params['start'])) {
303
            return parent::doGET($request);
304
        }
305
306
        // create a new article requests
307
        $record = new Article();
308
        $view = View::getInstance($record);
309
310
        // set up the title and meta details
311
        $this->setTitle('Creating article');
312
        $this->setDescription('Page to create a new article.');
313
        $this->setKeywords('create,article');
314
315
        $body .= View::displayPageHead($this);
316
317
        $message = $this->getStatusMessage();
318
        if (!empty($message)) {
319
            $body .= $message;
320
        }
321
322
        $fields = array('formAction' => $this->request->getURI());
323
        $body .= $view->createView($fields);
324
325
        $body .= View::displayPageFoot($this);
326
        self::$logger->debug('<<doGET');
327
328
        return new Response(200, $body, array('Content-Type' => 'text/html'));
329
    }
330
331
    /**
332
     * Method to handle PUT requests.
333
     *
334
     * @param \Alpha\Util\Http\Request
335
     *
336
     * @return \Alpha\Util\Http\Response
337
     *
338
     * @since 1.0
339
     */
340
    public function doPUT($request)
341
    {
342
        self::$logger->debug('>>doPUT($request=['.var_export($request, true).'])');
343
344
        $config = ConfigProvider::getInstance();
345
346
        $params = $request->getParams();
347
348
        $record = null;
349
350
        try {
351
            // check the hidden security fields before accepting the form POST data
352
            if (!$this->checkSecurityFields()) {
353
                self::$logger->debug('<<doPUT');
354
                throw new SecurityException('This page cannot accept post data from remote servers!');
355
            }
356
357
            if (isset($params['markdownTextBoxRows']) && $params['markdownTextBoxRows'] != '') {
358
                $viewState = ViewState::getInstance();
359
                $viewState->set('markdownTextBoxRows', $params['markdownTextBoxRows']);
360
            }
361
362
            if (isset($params['title']) || isset($params['ActiveRecordID'])) {
363
                if (isset($params['ActiveRecordType']) && class_exists($params['ActiveRecordType'])) {
364
                    $record = new $params['ActiveRecordType'];
365
                } else {
366
                    $record = new Article();
367
                }
368
369
                if (isset($params['title'])) {
370
                    $title = str_replace($config->get('cms.url.title.separator'), ' ', $params['title']);
371
372
                    $record->loadByAttribute('title', $title, false, array('ID', 'version_num', 'created_ts', 'updated_ts', 'title', 'author', 'published', 'content', 'headerContent'));
373
                } else {
374
                    $record->load($params['ActiveRecordID']);
375
                }
376
377
                // uploading an article attachment
378
                if (isset($params['uploadBut'])) {
379
                    $source = $request->getFile('userfile')['tmp_name'];
380
                    $dest = $record->getAttachmentsLocation().'/'.$request->getFile('userfile')['name'];
381
382
                    // upload the file to the attachments directory
383
                    FileUtils::copy($source, $dest);
384
385
                    if (!file_exists($dest)) {
386
                        throw new AlphaException('Could not move the uploaded file ['.$request->getFile('userfile')['name'].']');
387
                    }
388
389
                    // set read/write permissions on the file
390
                    $success = chmod($dest, 0666);
391
392
                    if (!$success) {
393
                        throw new AlphaException('Unable to set read/write permissions on the uploaded file ['.$dest.'].');
394
                    }
395
396
                    if ($success) {
397
                        self::$logger->action('File '.$source.' uploaded to '.$dest);
398
                        $this->setStatusMessage(View::displayUpdateMessage('File '.$source.' uploaded to '.$dest));
399
                    }
400
                } elseif (isset($params['deletefile']) && $params['deletefile'] != '') {
401
                    $success = unlink($record->getAttachmentsLocation().'/'.$params['deletefile']);
402
403
                    if (!$success) {
404
                        throw new AlphaException('Could not delete the file ['.$params['deletefile'].']');
405
                    }
406
407
                    if ($success) {
408
                        self::$logger->action('File '.$record->getAttachmentsLocation().'/'.$params['deletefile'].' deleted');
409
                        $this->setStatusMessage(View::displayUpdateMessage('File '.$record->getAttachmentsLocation().'/'.$params['deletefile'].' deleted'));
410
                    }
411
                } else {
412
                    self::$logger->debug('<<doPUT');
413
414
                    return parent::doPUT($request);
415
                }
416
            } else {
417
                throw new IllegalArguementException('No valid article ID provided!');
418
            }
419
        } catch (SecurityException $e) {
420
            $this->setStatusMessage(View::displayErrorMessage($e->getMessage()));
421
            self::$logger->warn($e->getMessage());
422
        } catch (IllegalArguementException $e) {
423
            $this->setStatusMessage(View::displayErrorMessage($e->getMessage()));
424
            self::$logger->error($e->getMessage());
425
        } catch (RecordNotFoundException $e) {
426
            self::$logger->warn($e->getMessage());
427
            $this->setStatusMessage(View::displayErrorMessage('Failed to load the requested article from the database!'));
428
        } catch (AlphaException $e) {
429
            $this->setStatusMessage(View::displayErrorMessage($e->getMessage()));
430
            self::$logger->error($e->getMessage());
431
        }
432
433
        $response = new Response(301);
434
435
        if ($this->getNextJob() != '') {
436
            $response->redirect($this->getNextJob());
437
        } else {
438
            if ($this->request->isSecureURI()) {
439
                $response->redirect(FrontController::generateSecureURL('act=Alpha\\Controller\\ActiveRecordController&ActiveRecordType=Alpha\Model\Article&ActiveRecordID='.$record->getID().'&view=edit'));
440
            } else {
441
                $title = str_replace(' ', $config->get('cms.url.title.separator'), $record->get('title'));
442
                $response->redirect($config->get('app.url').'/a/'.$title.'/edit');
443
            }
444
        }
445
446
        self::$logger->debug('<<doPUT');
447
448
        return $response;
449
    }
450
451
    /**
452
     * Method to handle DELETE requests.
453
     *
454
     * @param \Alpha\Util\Http\Request
455
     *
456
     * @return \Alpha\Util\Http\Response
457
     *
458
     * @since 2.0
459
     */
460
    public function doDELETE($request)
461
    {
462
        self::$logger->debug('>>doDELETE($request=['.var_export($request, true).'])');
463
464
        $this->setUnitOfWork(array());
465
466
        self::$logger->debug('<<doDELETE');
467
468
        return parent::doDELETE($request);
469
    }
470
471
    /**
472
     * Renders custom HTML header content.
473
     *
474
     * @return string
475
     *
476
     * @since 1.0
477
     */
478
    public function during_displayPageHead_callback()
479
    {
480
        $config = ConfigProvider::getInstance();
481
482
        $params = $this->request->getParams();
483
484
        $html = '';
485
486
        if ($config->get('cms.highlight.provider.name') == 'Alpha\Util\Code\Highlight\HighlightProviderLuminous') {
487
            $html .= '<link rel="StyleSheet" type="text/css" href="'.$config->get('app.url').'/css/luminous.css">';
488
            $html .= '<link rel="StyleSheet" type="text/css" href="'.$config->get('app.url').'/css/luminous_light.css">';
489
        }
490
491
        if ((isset($params['view']) && ($params['view'] == 'edit' || $params['view'] == 'create')) || (isset($params['ActiveRecordType']) && !isset($params['ActiveRecordID']))) {
492
            $fieldid = ($config->get('security.encrypt.http.fieldnames') ? 'text_field_'.base64_encode(SecurityUtils::encrypt('content')).'_0' : 'text_field_content_0');
493
494
            $html .= '
495
                <script type="text/javascript">
496
                $(document).ready(function() {
497
                    $(\'[id="'.$fieldid.'"]\').pagedownBootstrap({
498
                        \'sanatize\': false
499
                    });
500
                });
501
                </script>';
502
        } elseif (isset($params['view']) && $params['view'] == 'print') {
503
            $html .= '<link rel="StyleSheet" type="text/css" href="'.$config->get('app.url').'/css/print.css">';
504
        }
505
506
        if ($this->record instanceof Article) {
507
            $headerContent = $this->record->get('headerContent');
508
            if ($headerContent != '') {
509
                $html .= $headerContent;
510
            }
511
        }
512
513
        return $html;
514
    }
515
516
    /**
517
     * Callback that inserts the CMS level header.
518
     *
519
     * @return string
520
     *
521
     * @since 1.0
522
     */
523
    public function insert_CMSDisplayStandardHeader_callback()
524
    {
525
        if ($this->request->getParam('token') != null) {
526
            return '';
527
        }
528
529
        if (!$this->record instanceof Article) {
530
            return '';
531
        }
532
533
        $config = ConfigProvider::getInstance();
534
535
        $html = '';
536
537
        if ($config->get('cms.display.standard.header')) {
538
            $html .= '<p><a href="'.$config->get('app.url').'">'.$config->get('app.title').'</a> &nbsp; &nbsp;';
539
            $html .= 'Date Added: <em>'.$this->record->getCreateTS()->getDate().'</em> &nbsp; &nbsp;';
540
            $html .= 'Last Updated: <em>'.$this->record->getUpdateTS()->getDate().'</em> &nbsp; &nbsp;';
541
            $html .= 'Revision: <em>'.$this->record->getVersion().'</em></p>';
542
        }
543
544
        $html .= $config->get('cms.header');
545
546
        return $html;
547
    }
548
549
    /**
550
     * Callback used to render footer content, including comments, votes and print/PDF buttons when
551
     * enabled to do so.
552
     *
553
     * @return string
554
     *
555
     * @since 1.0
556
     */
557
    public function before_displayPageFoot_callback()
558
    {
559
        $config = ConfigProvider::getInstance();
560
        $sessionProvider = $config->get('session.provider.name');
561
        $session = SessionProviderFactory::getInstance($sessionProvider);
562
563
        $html = '';
564
        $params = $this->request->getParams();
565
566
        // this will ensure that direct requests to ActiveRecordController will be re-directed here.
567
        if (isset($this->record) && !$this->record->isTransient()) {
568
            $this->setName($config->get('app.url').$this->request->getURI());
569
            $this->setUnitOfWork(array($config->get('app.url').$this->request->getURI(), $config->get('app.url').$this->request->getURI()));
570
        } else {
571
            $this->setUnitOfWork(array());
572
        }
573
574
        if ($this->record != null) {
575
            if (isset($params['view']) && $params['view'] == 'detailed') {
576
                if ($config->get('cms.display.comments')) {
577
                    $html .= $this->renderComments();
578
                }
579
580
                if ($config->get('cms.display.tags')) {
581
                    $html .= $this->renderTags();
582
                }
583
584
                if ($config->get('cms.display.votes')) {
585
                    $rating = $this->record->getArticleScore();
586
                    $votes = $this->record->getArticleVotes();
587
                    $html .= '<p>Average Article User Rating: <strong>'.$rating.'</strong> out of 10 (based on <strong>'.count($votes).'</strong> votes)</p>';
588
                }
589
590
                if (!$this->record->checkUserVoted() && $config->get('cms.voting.allowed')) {
591
                    $html .= $this->renderVotes();
592
                }
593
594
                ActiveRecord::disconnect();
595
596
                if ($config->get('cms.allow.print.versions')) {
597
                    $html .= '&nbsp;&nbsp;';
598
                    $temp = new Button("window.open('".$this->record->get('printURL')."')", 'Open Printer Version', 'printBut');
599
                    $html .= $temp->render();
600
                }
601
602
                $html .= '&nbsp;&nbsp;';
603
                if ($config->get('cms.allow.pdf.versions')) {
604
                    $html .= '&nbsp;&nbsp;';
605
                    $temp = new Button("document.location = '".FrontController::generateSecureURL("act=Alpha\Controller\ArticleController&mode=pdf&title=".$this->record->get('title'))."';", 'Open PDF Version', 'pdfBut');
606
                    $html .= $temp->render();
607
                }
608
609
                // render edit button for admins only
610
                if ($session->get('currentUser') instanceof \Alpha\Model\Person && $session->get('currentUser')->inGroup('Admin')) {
611
                    $html .= '&nbsp;&nbsp;';
612
                    $button = new Button("document.location = '".FrontController::generateSecureURL('act=Alpha\Controller\ArticleController&mode=edit&ActiveRecordID='.$this->record->getID())."'", 'Edit', 'editBut');
613
                    $html .= $button->render();
614
                }
615
            }
616
617
            if ($config->get('cms.display.standard.footer')) {
618
                $html .= $this->renderStandardFooter();
619
            }
620
        }
621
622
        $html .= $config->get('cms.footer');
623
624
        return $html;
625
    }
626
627
    /**
628
     * Method for displaying the user comments for the article.
629
     *
630
     * @return string
631
     *
632
     * @since 1.0
633
     */
634
    private function renderComments()
635
    {
636
        $config = ConfigProvider::getInstance();
637
        $sessionProvider = $config->get('session.provider.name');
638
        $session = SessionProviderFactory::getInstance($sessionProvider);
639
640
        $html = '';
641
642
        $comments = $this->record->getArticleComments();
643
        $commentsCount = count($comments);
644
645
        $URL = FrontController::generateSecureURL('act=Alpha\Controller\ActiveRecordController&ActiveRecordType=Alpha\Model\ArticleComment');
646
647
        $fields = array('formAction' => $URL);
648
649
        if ($config->get('cms.display.comments') && $commentsCount > 0) {
650
            $html .= '<h2>There are ['.$commentsCount.'] user comments for this article</h2>';
651
652
            for ($i = 0; $i < $commentsCount; ++$i) {
653
                $view = View::getInstance($comments[$i]);
654
                $html .= $view->markdownView($fields);
655
            }
656
        }
657
658
        if ($session->get('currentUser') != null && $config->get('cms.comments.allowed')) {
659
            $comment = new ArticleComment();
660
            $comment->set('articleID', $this->record->getID());
661
662
            $view = View::getInstance($comment);
663
            $html .= $view->createView($fields);
664
        }
665
666
        return $html;
667
    }
668
669
    /**
670
     * Method for displaying the tags for the article.
671
     *
672
     * @return string
673
     *
674
     * @since 3.0
675
     */
676
    private function renderTags()
677
    {
678
        $config = ConfigProvider::getInstance();
679
        $relation = $this->record->getPropObject('tags');
680
681
        $html = '';
682
683
        if ($relation instanceof Relation) {
684
            $tags = $relation->getRelatedObjects();
685
686
            if (count($tags) > 0) {
687
                $html .= '<p>Tags:';
688
689
                foreach ($tags as $tag) {
690
                    $html .= ' <a href="'.$config->get('app.url').'/search/'.$tag->get('content').'">'.$tag->get('content').'</a>';
691
                }
692
                $html .= '</p>';
693
            }
694
        }
695
696
        return $html;
697
    }
698
699
    /**
700
     * Method for displaying the votes for the article.
701
     *
702
     * @return string
703
     *
704
     * @since 3.0
705
     */
706
    private function renderVotes()
707
    {
708
        $config = ConfigProvider::getInstance();
709
        $sessionProvider = $config->get('session.provider.name');
710
        $session = SessionProviderFactory::getInstance($sessionProvider);
711
712
        $URL = FrontController::generateSecureURL('act=Alpha\Controller\ActiveRecordController&ActiveRecordType=Alpha\Model\ArticleVote');
713
        $html = '<form action="'.$URL.'" method="post" accept-charset="UTF-8">';
714
        $fieldname = ($config->get('security.encrypt.http.fieldnames') ? base64_encode(SecurityUtils::encrypt('score')) : 'score');
715
        $html .= '<p>Please rate this article from 1-10 (10 being the best):'.
716
                '<select name="'.$fieldname.'">'.
717
                '<option value="1">1'.
718
                '<option value="2">2'.
719
                '<option value="3">3'.
720
                '<option value="4">4'.
721
                '<option value="5">5'.
722
                '<option value="6">6'.
723
                '<option value="7">7'.
724
                '<option value="8">8'.
725
                '<option value="9">9'.
726
                '<option value="10">10'.
727
                '</select></p>&nbsp;&nbsp;';
728
729
        $fieldname = ($config->get('security.encrypt.http.fieldnames') ? base64_encode(SecurityUtils::encrypt('articleID')) : 'articleID');
730
        $html .= '<input type="hidden" name="'.$fieldname.'" value="'.$this->record->getID().'"/>';
731
732
        $fieldname = ($config->get('security.encrypt.http.fieldnames') ? base64_encode(SecurityUtils::encrypt('personID')) : 'personID');
733
        $html .= '<input type="hidden" name="'.$fieldname.'" value="'.$session->get('currentUser')->getID().'"/>';
734
735
        $fieldname = ($config->get('security.encrypt.http.fieldnames') ? base64_encode(SecurityUtils::encrypt('statusMessage')) : 'statusMessage');
736
        $html .= '<input type="hidden" name="'.$fieldname.'" value="Thank you for rating this article!"/>';
737
738
        $temp = new Button('submit', 'Vote!', 'voteBut');
739
        $html .= $temp->render();
740
741
        $html .= View::renderSecurityFields();
742
        $html .= '<form>';
743
744
        return $html;
745
    }
746
747
    /**
748
     * Method for displaying the standard CMS footer for the article.
749
     *
750
     * @return string
751
     *
752
     * @since 3.0
753
     */
754
    private function renderStandardFooter()
755
    {
756
        $html = '<p>Article URL: <a href="'.$this->record->get('URL').'">'.$this->record->get('URL').'</a><br>';
757
        $html .= 'Title: '.$this->record->get('title').'<br>';
758
        $html .= 'Author: '.$this->record->get('author').'</p>';
759
760
        return $html;
761
    }
762
}
763