aboutsummaryrefslogtreecommitdiff
path: root/bootstrap/comments/api/backend/latest-ajax.php
blob: 964fe3464096371dd9f12003603cc7890c70d2cf (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
<?php namespace HashOver;

// Copyright (C) 2018 Jacob Barkdull
// This file is part of HashOver.
//
// HashOver is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// HashOver is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with HashOver.  If not, see <http://www.gnu.org/licenses/>.


// Change to the HashOver directory
chdir (realpath ('../../'));

// Check if request is for JSONP
if (isset ($_GET['jsonp'])) {
	// If so, setup HashOver for JavaScript
	require ('backend/javascript-setup.php');
} else {
	// If not, setup HashOver for JSON
	require ('backend/json-setup.php');
}

try {
	// Instantiate HashOver class
	$hashover = new \HashOver ('json', 'api');
	$hashover->setup->setThreadName ('request');
	$hashover->initiate ();
	$hashover->finalize ();

	// Throw exception if the "Latest Comments" API is disabled
	if ($hashover->setup->apiStatus ('latest') === 'disabled') {
		throw new \Exception ('This API is not enabled.');
	}

	// Comments and statistics response array
	$data = array ();

	// Add locales to data
	$data['locale'] = array (
		'date-time'		=> $hashover->locale->text['date-time'],
		'dislike'		=> $hashover->locale->text['dislike'],
		'external-image-tip'	=> $hashover->locale->text['external-image-tip'],
		'like'			=> $hashover->locale->text['like'],
		'today'			=> $hashover->locale->text['date-today'],
		'commenter-tip'		=> $hashover->locale->text['commenter-tip'],
		'subscribed-tip'	=> $hashover->locale->text['subscribed-tip'],
		'unsubscribed-tip'	=> $hashover->locale->text['unsubscribed-tip'],
		'replies'		=> $hashover->locale->text['replies'],
		'reply'			=> $hashover->locale->text['reply'],
		'loading'		=> $hashover->locale->text['loading'],
		'click-to-close'	=> $hashover->locale->text['click-to-close'],
		'day-names'		=> $hashover->locale->text['date-day-names'],
		'month-names'		=> $hashover->locale->text['date-month-names']
	);

	// Add setup information to data
	$data['setup'] = array (
		'server-eol'		=> PHP_EOL,
		'default-name'		=> $hashover->setup->defaultName,
		'user-is-logged-in'	=> $hashover->login->userIsLoggedIn,
		'time-format'		=> $hashover->setup->timeFormat,
		'image-extensions'	=> $hashover->setup->imageTypes,
		'image-placeholder'	=> $hashover->setup->getImagePath ('place-holder'),
		'theme-css'		=> $hashover->setup->getThemePath ('latest.css'),
		'device-type'		=> ($hashover->setup->isMobile === true) ? 'mobile' : 'desktop',
		'uses-user-timezone'	=> $hashover->setup->usesUserTimezone,
		'uses-short-dates'	=> $hashover->setup->usesShortDates,
		'allows-images'		=> $hashover->setup->allowsImages,
		'uses-markdown'		=> $hashover->setup->usesMarkdown
	);

	// Add UI HTML to data
	$data['ui'] = array (
		'user-avatar'		=> $hashover->ui->userAvatar (),
		'name-link'		=> $hashover->ui->nameElement ('a'),
		'name-span'		=> $hashover->ui->nameElement ('span'),
		'thread-link'		=> $hashover->ui->threadLink (),
		'reply-link'		=> $hashover->ui->formLink ('{{href}}', 'reply'),
		'like-count'		=> $hashover->ui->likeCount ('likes'),
		'dislike-count'		=> $hashover->ui->likeCount ('dislikes'),
		'name-wrapper'		=> $hashover->ui->nameWrapper (),
		'date-link'		=> $hashover->ui->dateLink (),
		'comment-wrapper'	=> $hashover->ui->commentWrapper (),
		'theme'			=> $hashover->templater->parseTheme ('latest.html')
	);

	// Attempt to get comment thread from GET/POST data
	$get_thread = $hashover->setup->getRequest ('thread', 'auto');

	// Check if we're getting metadata for a specific thread
	if ($get_thread !== 'auto') {
		// If so, attempt to read thread-specific latest comments metadata
		$latest = $hashover->thread->data->readMeta ('latest-comments', $get_thread);
	} else {
		// If not, attempt to read global latest comments metadata
		$latest = $hashover->thread->data->readMeta ('latest-comments', 'auto', true);
	}

	// Check if the latest comments read successfully
	if ($latest !== false) {
		// If so, reduce number of latest comments to configured limit
		$latest = array_slice ($latest, 0, $hashover->setup->latestMax);
	} else {
		// If not, set to empty array
		$latest = array ();
	}

	// Latest comments
	$comments = array ();

	// Run through the latest comments
	foreach ($latest as $item) {
		// Get comment key
		$key = basename ($item);
		$key_parts = explode ('-', $key);

		// Decide proper thread
		$thread = ($get_thread === 'auto') ? dirname ($item) : $get_thread;

		// Attempt to read page information metadata
		$page_info = $hashover->thread->data->readMeta ('page-info', $thread);

		// Attempt to read comment
		$raw = $hashover->thread->data->read ($key, $thread);

		// Skip failed or unapproved comments or missing metadata
		if ((!empty ($raw['status']) and $raw['status'] !== 'approved')
		    or ($raw and $page_info) === false)
		{
			continue;
		}

		// Parse comment
		$comment = $hashover->commentParser->parse ($raw, $key, $key_parts);

		// Merge comment with page metadata
		$comment = array_merge ($page_info, $comment);

		// Trim comment body to configurable length
		if ($hashover->setup->latestTrimWidth > 0) {
			// Instantiate WriteComments
			//
			// TODO: Split WriteComments into multiple classes so we
			// can instantiate only the functionality that we need
			//
			$write_comments = new WriteComments (
				$hashover->setup,
				$hashover->thread
			);

			// Shorthands
			$trim_length = $hashover->setup->latestTrimWidth;
			$close_tags = $write_comments->closeTags;

			// Add <code> to list of tags to close
			$write_comments->closeTags[] = 'code';

			// Trim the comment to configurable length
			$body = rtrim (mb_strimwidth ($comment['body'], 0, $trim_length, '...'));

			// Close any tags that may have had their endings trimmed off
			$body = $write_comments->tagCloser ($close_tags, $body);

			// Escape any HTML tags that may have been trimmed in half
			$body = $write_comments->htmlSelectiveEscape ($body);

			// Update the comment
			$comment['body'] = $body;
		}

		// Add comment to response array
		$comments[] = $comment;
	}

	// HashOver instance information
	$data['instance'] = array (
		'comments' => array ('primary' => $comments),
		'total-count' => count ($comments)
	);

	// Generate statistics
	$hashover->statistics->executionEnd ();

	// HashOver statistics
	$data['statistics'] = array (
		'execution-time'	=> $hashover->statistics->executionTime,
		'script-memory'		=> $hashover->statistics->scriptMemory,
		'system-memory'		=> $hashover->statistics->systemMemory
	);

	// Encode JSON data
	echo $hashover->misc->jsonData ($data);

} catch (\Exception $error) {
	$misc = new Misc ('json');
	$message = $error->getMessage ();
	$misc->displayError ($message);
}