Completed
Push — develop ( ada86c...9cfff8 )
by John
04:02
created

ArticleController::doPUT()   B

Complexity

Conditions 5
Paths 6

Size

Total Lines 82
Code Lines 21

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 82
rs 8.3768
cc 5
eloc 21
nc 6
nop 1

How to fix   Long Method   

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\Service\ServiceFactory;
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;
0 ignored issues
show
Unused Code Comprehensibility introduced by
63% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
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['ActiveRecordID'])) {
370
                    $record->load($params['ActiveRecordID']);
371
                } else {
372
                    $title = str_replace($config->get('cms.url.title.separator'), ' ', $params['title']);
373
374
                    $record->loadByAttribute('title', $title, false, array('ID', 'version_num', 'created_ts', 'updated_ts', 'title', 'author', 'published', 'content', 'headerContent'));
375
                }
376
377
                self::$logger->debug('<<doPUT');
378
379
                return parent::doPUT($request);
380
            } else {
381
                throw new IllegalArguementException('No valid article ID provided!');
382
            }
383
        } catch (SecurityException $e) {
384
            $this->setStatusMessage(View::displayErrorMessage($e->getMessage()));
385
            self::$logger->warn($e->getMessage());
386
        } catch (IllegalArguementException $e) {
387
            $this->setStatusMessage(View::displayErrorMessage($e->getMessage()));
388
            self::$logger->error($e->getMessage());
389
        } catch (RecordNotFoundException $e) {
390
            self::$logger->warn($e->getMessage());
391
            $this->setStatusMessage(View::displayErrorMessage('Failed to load the requested article from the database!'));
392
        } catch (AlphaException $e) {
393
            $this->setStatusMessage(View::displayErrorMessage($e->getMessage()));
394
            self::$logger->error($e->getMessage());
395
        }
396
397
        $response = new Response(301);*/
398
        if (!isset($params['ActiveRecordID']) && isset($params['title'])) {
399
            $title = str_replace($config->get('cms.url.title.separator'), ' ', $params['title']);
400
            $record = new Article();
401
            $record->loadByAttribute('title', $title);
402
            $params['ActiveRecordID'] = $record->getID();
403
        }
404
        $request->addParams(array('ActiveRecordType' => 'Alpha\Model\Article', 'ActiveRecordID' => isset($params['ActiveRecordID'])));
405
        $response = parent::doPUT($request);
406
407
        if ($this->getNextJob() != '') {
408
            $response->redirect($this->getNextJob());
409
        } else {
410
            if ($this->request->isSecureURI()) {
411
                $response->redirect(FrontController::generateSecureURL('act=Alpha\\Controller\\ActiveRecordController&ActiveRecordType=Alpha\Model\Article&ActiveRecordID='.$this->record->getID().'&view=edit'));
412
            } else {
413
                $title = str_replace(' ', $config->get('cms.url.title.separator'), $this->record->get('title'));
414
                $response->redirect($config->get('app.url').'/a/'.$title.'/edit');
415
            }
416
        }
417
418
        self::$logger->debug('<<doPUT');
419
420
        return $response;
421
    }
422
423
    /**
424
     * Method to handle DELETE requests.
425
     *
426
     * @param \Alpha\Util\Http\Request
427
     *
428
     * @return \Alpha\Util\Http\Response
429
     *
430
     * @since 2.0
431
     */
432
    public function doDELETE($request)
433
    {
434
        self::$logger->debug('>>doDELETE($request=['.var_export($request, true).'])');
435
436
        $this->setUnitOfWork(array());
437
438
        self::$logger->debug('<<doDELETE');
439
440
        return parent::doDELETE($request);
441
    }
442
443
    /**
444
     * Renders custom HTML header content.
445
     *
446
     * @return string
447
     *
448
     * @since 1.0
449
     */
450
    public function during_displayPageHead_callback()
451
    {
452
        $config = ConfigProvider::getInstance();
453
454
        $params = $this->request->getParams();
455
456
        $html = '';
457
458
        if ($config->get('cms.highlight.provider.name') == 'Alpha\Util\Code\Highlight\HighlightProviderLuminous') {
459
            $html .= '<link rel="StyleSheet" type="text/css" href="'.$config->get('app.url').'/css/luminous.css">';
460
            $html .= '<link rel="StyleSheet" type="text/css" href="'.$config->get('app.url').'/css/luminous_light.css">';
461
        }
462
463
        if ((isset($params['view']) && ($params['view'] == 'edit' || $params['view'] == 'create')) || (isset($params['ActiveRecordType']) && !isset($params['ActiveRecordID']))) {
464
            $fieldid = ($config->get('security.encrypt.http.fieldnames') ? 'text_field_'.base64_encode(SecurityUtils::encrypt('content')).'_0' : 'text_field_content_0');
465
466
            $html .= '
467
                <script type="text/javascript">
468
                $(document).ready(function() {
469
                    $(\'[id="'.$fieldid.'"]\').pagedownBootstrap({
470
                        \'sanatize\': false
471
                    });
472
                });
473
                </script>';
474
        } elseif (isset($params['view']) && $params['view'] == 'print') {
475
            $html .= '<link rel="StyleSheet" type="text/css" href="'.$config->get('app.url').'/css/print.css">';
476
        }
477
478
        if ($this->record instanceof Article) {
479
            $headerContent = $this->record->get('headerContent');
480
            if ($headerContent != '') {
481
                $html .= $headerContent;
482
            }
483
        }
484
485
        return $html;
486
    }
487
488
    /**
489
     * Callback that inserts the CMS level header.
490
     *
491
     * @return string
492
     *
493
     * @since 1.0
494
     */
495
    public function insert_CMSDisplayStandardHeader_callback()
496
    {
497
        if ($this->request->getParam('token') != null) {
498
            return '';
499
        }
500
501
        if (!$this->record instanceof Article) {
502
            return '';
503
        }
504
505
        $config = ConfigProvider::getInstance();
506
507
        $html = '';
508
509
        if ($config->get('cms.display.standard.header')) {
510
            $html .= '<p><a href="'.$config->get('app.url').'">'.$config->get('app.title').'</a> &nbsp; &nbsp;';
511
            $html .= 'Date Added: <em>'.$this->record->getCreateTS()->getDate().'</em> &nbsp; &nbsp;';
512
            $html .= 'Last Updated: <em>'.$this->record->getUpdateTS()->getDate().'</em> &nbsp; &nbsp;';
513
            $html .= 'Revision: <em>'.$this->record->getVersion().'</em></p>';
514
        }
515
516
        $html .= $config->get('cms.header');
517
518
        return $html;
519
    }
520
521
    /**
522
     * Callback used to render footer content, including comments, votes and print/PDF buttons when
523
     * enabled to do so.
524
     *
525
     * @return string
526
     *
527
     * @since 1.0
528
     */
529
    public function before_displayPageFoot_callback()
530
    {
531
        $config = ConfigProvider::getInstance();
532
        $sessionProvider = $config->get('session.provider.name');
533
        $session = ServiceFactory::getInstance($sessionProvider, 'Alpha\Util\Http\Session\SessionProviderInterface');
534
535
        $html = '';
536
        $params = $this->request->getParams();
537
538
        // this will ensure that direct requests to ActiveRecordController will be re-directed here.
539
        if (isset($this->record) && !$this->record->isTransient()) {
540
            $this->setName($config->get('app.url').$this->request->getURI());
541
            $this->setUnitOfWork(array($config->get('app.url').$this->request->getURI(), $config->get('app.url').$this->request->getURI()));
542
        } else {
543
            $this->setUnitOfWork(array());
544
        }
545
546
        if ($this->record != null) {
547
            if (isset($params['view']) && $params['view'] == 'detailed') {
548
                if ($config->get('cms.display.comments')) {
549
                    $html .= $this->renderComments();
550
                }
551
552
                if ($config->get('cms.display.tags')) {
553
                    $html .= $this->renderTags();
554
                }
555
556
                if ($config->get('cms.display.votes')) {
557
                    $rating = $this->record->getArticleScore();
558
                    $votes = $this->record->getArticleVotes();
559
                    $html .= '<p>Average Article User Rating: <strong>'.$rating.'</strong> out of 10 (based on <strong>'.count($votes).'</strong> votes)</p>';
560
                }
561
562
                if (!$this->record->checkUserVoted() && $config->get('cms.voting.allowed')) {
563
                    $html .= $this->renderVotes();
564
                }
565
566
                ActiveRecord::disconnect();
567
568
                if ($config->get('cms.allow.print.versions')) {
569
                    $html .= '&nbsp;&nbsp;';
570
                    $temp = new Button("window.open('".$this->record->get('printURL')."')", 'Open Printer Version', 'printBut');
571
                    $html .= $temp->render();
572
                }
573
574
                $html .= '&nbsp;&nbsp;';
575
                if ($config->get('cms.allow.pdf.versions')) {
576
                    $html .= '&nbsp;&nbsp;';
577
                    $temp = new Button("document.location = '".FrontController::generateSecureURL("act=Alpha\Controller\ArticleController&mode=pdf&title=".$this->record->get('title'))."';", 'Open PDF Version', 'pdfBut');
578
                    $html .= $temp->render();
579
                }
580
581
                // render edit button for admins only
582
                if ($session->get('currentUser') instanceof \Alpha\Model\Person && $session->get('currentUser')->inGroup('Admin')) {
583
                    $html .= '&nbsp;&nbsp;';
584
                    $button = new Button("document.location = '".FrontController::generateSecureURL('act=Alpha\Controller\ArticleController&mode=edit&ActiveRecordID='.$this->record->getID())."'", 'Edit', 'editBut');
585
                    $html .= $button->render();
586
                }
587
            }
588
589
            if ($config->get('cms.display.standard.footer')) {
590
                $html .= $this->renderStandardFooter();
591
            }
592
        }
593
594
        $html .= $config->get('cms.footer');
595
596
        return $html;
597
    }
598
599
    /**
600
     * Method for displaying the user comments for the article.
601
     *
602
     * @return string
603
     *
604
     * @since 1.0
605
     */
606
    private function renderComments()
607
    {
608
        $config = ConfigProvider::getInstance();
609
        $sessionProvider = $config->get('session.provider.name');
610
        $session = ServiceFactory::getInstance($sessionProvider, 'Alpha\Util\Http\Session\SessionProviderInterface');
611
612
        $html = '';
613
614
        $comments = $this->record->getArticleComments();
615
        $commentsCount = count($comments);
616
617
        $URL = FrontController::generateSecureURL('act=Alpha\Controller\ActiveRecordController&ActiveRecordType=Alpha\Model\ArticleComment');
618
619
        $fields = array('formAction' => $URL);
620
621
        if ($config->get('cms.display.comments') && $commentsCount > 0) {
622
            $html .= '<h2>There are ['.$commentsCount.'] user comments for this article</h2>';
623
624
            for ($i = 0; $i < $commentsCount; ++$i) {
625
                $view = View::getInstance($comments[$i]);
626
                $html .= $view->markdownView($fields);
627
            }
628
        }
629
630
        if ($session->get('currentUser') != null && $config->get('cms.comments.allowed')) {
631
            $comment = new ArticleComment();
632
            $comment->set('articleID', $this->record->getID());
633
634
            $view = View::getInstance($comment);
635
            $html .= $view->createView($fields);
636
        }
637
638
        return $html;
639
    }
640
641
    /**
642
     * Method for displaying the tags for the article.
643
     *
644
     * @return string
645
     *
646
     * @since 3.0
647
     */
648
    private function renderTags()
649
    {
650
        $config = ConfigProvider::getInstance();
651
        $relation = $this->record->getPropObject('tags');
652
653
        $html = '';
654
655
        if ($relation instanceof Relation) {
656
            $tags = $relation->getRelated();
657
658
            if (count($tags) > 0) {
659
                $html .= '<p>Tags:';
660
661
                foreach ($tags as $tag) {
662
                    $html .= ' <a href="'.$config->get('app.url').'/search/'.$tag->get('content').'">'.$tag->get('content').'</a>';
663
                }
664
                $html .= '</p>';
665
            }
666
        }
667
668
        return $html;
669
    }
670
671
    /**
672
     * Method for displaying the votes for the article.
673
     *
674
     * @return string
675
     *
676
     * @since 3.0
677
     */
678
    private function renderVotes()
679
    {
680
        $config = ConfigProvider::getInstance();
681
        $sessionProvider = $config->get('session.provider.name');
682
        $session = ServiceFactory::getInstance($sessionProvider, 'Alpha\Util\Http\Session\SessionProviderInterface');
683
684
        $URL = FrontController::generateSecureURL('act=Alpha\Controller\ActiveRecordController&ActiveRecordType=Alpha\Model\ArticleVote');
685
        $html = '<form action="'.$URL.'" method="post" accept-charset="UTF-8">';
686
        $fieldname = ($config->get('security.encrypt.http.fieldnames') ? base64_encode(SecurityUtils::encrypt('score')) : 'score');
687
        $html .= '<p>Please rate this article from 1-10 (10 being the best):'.
688
                '<select name="'.$fieldname.'">'.
689
                '<option value="1">1'.
690
                '<option value="2">2'.
691
                '<option value="3">3'.
692
                '<option value="4">4'.
693
                '<option value="5">5'.
694
                '<option value="6">6'.
695
                '<option value="7">7'.
696
                '<option value="8">8'.
697
                '<option value="9">9'.
698
                '<option value="10">10'.
699
                '</select></p>&nbsp;&nbsp;';
700
701
        $fieldname = ($config->get('security.encrypt.http.fieldnames') ? base64_encode(SecurityUtils::encrypt('articleID')) : 'articleID');
702
        $html .= '<input type="hidden" name="'.$fieldname.'" value="'.$this->record->getID().'"/>';
703
704
        $fieldname = ($config->get('security.encrypt.http.fieldnames') ? base64_encode(SecurityUtils::encrypt('personID')) : 'personID');
705
        $html .= '<input type="hidden" name="'.$fieldname.'" value="'.$session->get('currentUser')->getID().'"/>';
706
707
        $fieldname = ($config->get('security.encrypt.http.fieldnames') ? base64_encode(SecurityUtils::encrypt('statusMessage')) : 'statusMessage');
708
        $html .= '<input type="hidden" name="'.$fieldname.'" value="Thank you for rating this article!"/>';
709
710
        $temp = new Button('submit', 'Vote!', 'voteBut');
711
        $html .= $temp->render();
712
713
        $html .= View::renderSecurityFields();
714
        $html .= '<form>';
715
716
        return $html;
717
    }
718
719
    /**
720
     * Method for displaying the standard CMS footer for the article.
721
     *
722
     * @return string
723
     *
724
     * @since 3.0
725
     */
726
    private function renderStandardFooter()
727
    {
728
        $html = '<p>Article URL: <a href="'.$this->record->get('URL').'">'.$this->record->get('URL').'</a><br>';
729
        $html .= 'Title: '.$this->record->get('title').'<br>';
730
        $html .= 'Author: '.$this->record->get('author').'</p>';
731
732
        return $html;
733
    }
734
}
735