Issues (1014)

Sources/News.php (11 issues)

1
<?php
2
3
/**
4
 * This file contains the files necessary to display news as an XML feed.
5
 *
6
 * Simple Machines Forum (SMF)
7
 *
8
 * @package SMF
9
 * @author Simple Machines https://www.simplemachines.org
10
 * @copyright 2022 Simple Machines and individual contributors
11
 * @license https://www.simplemachines.org/about/smf/license.php BSD
12
 *
13
 * @version 2.1.2
14
 */
15
16
if (!defined('SMF'))
17
	die('No direct access...');
18
19
/**
20
 * Outputs xml data representing recent information or a profile.
21
 *
22
 * Can be passed subactions which decide what is output:
23
 *  'recent' for recent posts,
24
 *  'news' for news topics,
25
 *  'members' for recently registered members,
26
 *  'profile' for a member's profile.
27
 *  'posts' for a member's posts.
28
 *  'personal_messages' for a member's personal messages.
29
 *
30
 * When displaying a member's profile or posts, the u parameter identifies which member. Defaults
31
 * to the current user's id.
32
 * To display a member's personal messages, the u parameter must match the id of the current user.
33
 *
34
 * Outputs can be in RSS 0.92, RSS 2, Atom, RDF, or our own custom XML format. Default is RSS 2.
35
 *
36
 * Accessed via ?action=.xml.
37
 *
38
 * Does not use any templates, sub templates, or template layers.
39
 *
40
 * Uses Stats, Profile, Post, and PersonalMessage language files.
41
 */
42
function ShowXmlFeed()
43
{
44
	global $board, $board_info, $context, $scripturl, $boardurl, $txt, $modSettings, $user_info;
45
	global $query_this_board, $smcFunc, $forum_version, $settings, $cache_enable, $cachedir;
46
47
	// List all the different types of data they can pull.
48
	$subActions = array(
49
		'recent' => 'getXmlRecent',
50
		'news' => 'getXmlNews',
51
		'members' => 'getXmlMembers',
52
		'profile' => 'getXmlProfile',
53
		'posts' => 'getXmlPosts',
54
		'personal_messages' => 'getXmlPMs',
55
	);
56
57
	// Easy adding of sub actions
58
	call_integration_hook('integrate_xmlfeeds', array(&$subActions));
59
60
	$subaction = empty($_GET['sa']) || !isset($subActions[$_GET['sa']]) ? 'recent' : $_GET['sa'];
61
62
	// Make sure the id is a number and not "I like trying to hack the database".
63
	$context['xmlnews_uid'] = isset($_GET['u']) ? (int) $_GET['u'] : $user_info['id'];
64
65
	// Default to latest 5.  No more than 255, please.
66
	$context['xmlnews_limit'] = empty($_GET['limit']) || (int) $_GET['limit'] < 1 ? 5 : min((int) $_GET['limit'], 255);
67
68
	// Users can always export their own profile data
69
	if (in_array($subaction, array('profile', 'posts', 'personal_messages')) && !$user_info['is_guest'] && $context['xmlnews_uid'] == $user_info['id'])
70
		$modSettings['xmlnews_enable'] = true;
71
72
	// If it's not enabled, die.
73
	if (empty($modSettings['xmlnews_enable']))
74
		obExit(false);
75
76
	loadLanguage('Stats');
77
78
	// Show in rss or proprietary format?
79
	$xml_format = $_GET['type'] = isset($_GET['type']) && in_array($_GET['type'], array('smf', 'rss', 'rss2', 'atom', 'rdf')) ? $_GET['type'] : 'rss2';
80
81
	// Some general metadata for this feed. We'll change some of these values below.
82
	$feed_meta = array(
83
		'title' => '',
84
		'desc' => sprintf($txt['xml_rss_desc'], $context['forum_name']),
85
		'author' => $context['forum_name'],
86
		'source' => $scripturl,
87
		'rights' => '© ' . date('Y') . ' ' . $context['forum_name'],
88
		'icon' => !empty($settings['og_image']) ? $settings['og_image'] : $boardurl . '/favicon.ico',
89
		'language' => !empty($txt['lang_locale']) ? str_replace("_", "-", substr($txt['lang_locale'], 0, strcspn($txt['lang_locale'], "."))) : 'en',
90
		'self' => $scripturl,
91
	);
92
	foreach (array('action', 'sa', 'type', 'board', 'boards', 'c', 'u', 'limit', 'offset') as $var)
93
		if (isset($_GET[$var]))
94
			$feed_meta['self'] .= ($feed_meta['self'] === $scripturl ? '?' : ';' ) . $var . '=' . $_GET[$var];
95
96
	// Handle the cases where a board, boards, or category is asked for.
97
	$query_this_board = 1;
98
	$context['optimize_msg'] = array(
99
		'highest' => 'm.id_msg <= b.id_last_msg',
100
	);
101
	if (!empty($_GET['c']) && empty($board))
102
	{
103
		$_GET['c'] = explode(',', $_GET['c']);
104
		foreach ($_GET['c'] as $i => $c)
105
			$_GET['c'][$i] = (int) $c;
106
107
		if (count($_GET['c']) == 1)
108
		{
109
			$request = $smcFunc['db_query']('', '
110
				SELECT name
111
				FROM {db_prefix}categories
112
				WHERE id_cat = {int:current_category}',
113
				array(
114
					'current_category' => (int) $_GET['c'][0],
115
				)
116
			);
117
			list ($feed_meta['title']) = $smcFunc['db_fetch_row']($request);
118
			$smcFunc['db_free_result']($request);
119
		}
120
121
		$request = $smcFunc['db_query']('', '
122
			SELECT b.id_board, b.num_posts
123
			FROM {db_prefix}boards AS b
124
			WHERE b.id_cat IN ({array_int:current_category_list})
125
				AND {query_see_board}',
126
			array(
127
				'current_category_list' => $_GET['c'],
128
			)
129
		);
130
		$total_cat_posts = 0;
131
		$boards = array();
132
		while ($row = $smcFunc['db_fetch_assoc']($request))
133
		{
134
			$boards[] = $row['id_board'];
135
			$total_cat_posts += $row['num_posts'];
136
		}
137
		$smcFunc['db_free_result']($request);
138
139
		if (!empty($boards))
140
			$query_this_board = 'b.id_board IN (' . implode(', ', $boards) . ')';
141
142
		// Try to limit the number of messages we look through.
143
		if ($total_cat_posts > 100 && $total_cat_posts > $modSettings['totalMessages'] / 15)
144
			$context['optimize_msg']['lowest'] = 'm.id_msg >= ' . max(0, $modSettings['maxMsgID'] - 400 - $context['xmlnews_limit'] * 5);
145
	}
146
	elseif (!empty($_GET['boards']))
147
	{
148
		$_GET['boards'] = explode(',', $_GET['boards']);
149
		foreach ($_GET['boards'] as $i => $b)
150
			$_GET['boards'][$i] = (int) $b;
151
152
		$request = $smcFunc['db_query']('', '
153
			SELECT b.id_board, b.num_posts, b.name
154
			FROM {db_prefix}boards AS b
155
			WHERE b.id_board IN ({array_int:board_list})
156
				AND {query_see_board}
157
			LIMIT {int:limit}',
158
			array(
159
				'board_list' => $_GET['boards'],
160
				'limit' => count($_GET['boards']),
161
			)
162
		);
163
164
		// Either the board specified doesn't exist or you have no access.
165
		$num_boards = $smcFunc['db_num_rows']($request);
166
		if ($num_boards == 0)
167
			fatal_lang_error('no_board', false);
168
169
		$total_posts = 0;
170
		$boards = array();
171
		while ($row = $smcFunc['db_fetch_assoc']($request))
172
		{
173
			if ($num_boards == 1)
174
				$feed_meta['title'] = $row['name'];
175
176
			$boards[] = $row['id_board'];
177
			$total_posts += $row['num_posts'];
178
		}
179
		$smcFunc['db_free_result']($request);
180
181
		if (!empty($boards))
182
			$query_this_board = 'b.id_board IN (' . implode(', ', $boards) . ')';
183
184
		// The more boards, the more we're going to look through...
185
		if ($total_posts > 100 && $total_posts > $modSettings['totalMessages'] / 12)
186
			$context['optimize_msg']['lowest'] = 'm.id_msg >= ' . max(0, $modSettings['maxMsgID'] - 500 - $context['xmlnews_limit'] * 5);
187
	}
188
	elseif (!empty($board))
189
	{
190
		$request = $smcFunc['db_query']('', '
191
			SELECT num_posts
192
			FROM {db_prefix}boards AS b
193
			WHERE id_board = {int:current_board}
194
				AND {query_see_board}
195
			LIMIT 1',
196
			array(
197
				'current_board' => $board,
198
			)
199
		);
200
201
		if ($smcFunc['db_num_rows']($request) == 0)
202
			fatal_lang_error('no_board', false);
203
204
		list ($total_posts) = $smcFunc['db_fetch_row']($request);
205
		$smcFunc['db_free_result']($request);
206
207
		$feed_meta['title'] = $board_info['name'];
208
		$feed_meta['source'] .= '?board=' . $board . '.0';
209
210
		$query_this_board = 'b.id_board = ' . $board;
211
212
		// Try to look through just a few messages, if at all possible.
213
		if ($total_posts > 80 && $total_posts > $modSettings['totalMessages'] / 10)
214
			$context['optimize_msg']['lowest'] = 'm.id_msg >= ' . max(0, $modSettings['maxMsgID'] - 600 - $context['xmlnews_limit'] * 5);
215
	}
216
	else
217
	{
218
		$query_this_board = '{query_see_board}' . (!empty($modSettings['recycle_enable']) && $modSettings['recycle_board'] > 0 ? '
219
			AND b.id_board != ' . $modSettings['recycle_board'] : '');
220
		$context['optimize_msg']['lowest'] = 'm.id_msg >= ' . max(0, $modSettings['maxMsgID'] - 100 - $context['xmlnews_limit'] * 5);
221
	}
222
223
	$feed_meta['title'] .= (!empty($feed_meta['title']) ? ' - ' : '') . $context['forum_name'];
224
225
	// Sanitize feed metadata values
226
	foreach ($feed_meta as $mkey => $mvalue)
227
		$feed_meta[$mkey] = strip_tags($mvalue);
228
229
	// We only want some information, not all of it.
230
	$cachekey = array($xml_format, $_GET['action'], $context['xmlnews_limit'], $subaction);
231
	foreach (array('board', 'boards', 'c') as $var)
232
		if (isset($_GET[$var]))
233
			$cachekey[] = $var . '=' . implode(',', (array) $_GET[$var]);
234
	$cachekey = md5($smcFunc['json_encode']($cachekey) . (!empty($query_this_board) ? $query_this_board : ''));
235
	$cache_t = microtime(true);
236
237
	// Get the associative array representing the xml.
238
	if (!empty($cache_enable) && (!$user_info['is_guest'] || $cache_enable >= 3))
239
	{
240
		$xml_data = cache_get_data('xmlfeed-' . $xml_format . ':' . ($user_info['is_guest'] ? '' : $user_info['id'] . '-') . $cachekey, 240);
241
	}
242
	if (empty($xml_data))
243
	{
244
		$call = call_helper($subActions[$subaction], true);
245
246
		if (!empty($call))
247
			$xml_data = call_user_func($call, $xml_format);
0 ignored issues
show
It seems like $call can also be of type boolean; however, parameter $callback of call_user_func() does only seem to accept callable, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

247
			$xml_data = call_user_func(/** @scrutinizer ignore-type */ $call, $xml_format);
Loading history...
248
249
		if (!empty($cache_enable) && (($user_info['is_guest'] && $cache_enable >= 3)
250
		|| (!$user_info['is_guest'] && (microtime(true) - $cache_t > 0.2))))
251
			cache_put_data('xmlfeed-' . $xml_format . ':' . ($user_info['is_guest'] ? '' : $user_info['id'] . '-') . $cachekey, $xml_data, 240);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $xml_data does not seem to be defined for all execution paths leading up to this point.
Loading history...
252
	}
253
254
	buildXmlFeed($xml_format, $xml_data, $feed_meta, $subaction);
255
256
	// Descriptive filenames = good
257
	$filename[] = $feed_meta['title'];
0 ignored issues
show
Comprehensibility Best Practice introduced by
$filename was never initialized. Although not strictly required by PHP, it is generally a good practice to add $filename = array(); before regardless.
Loading history...
258
	$filename[] = $subaction;
259
	if (in_array($subaction, array('profile', 'posts', 'personal_messages')))
260
		$filename[] = 'u=' . $context['xmlnews_uid'];
261
	if (!empty($boards))
262
		$filename[] = 'boards=' . implode(',', $boards);
263
	elseif (!empty($board))
264
		$filename[] = 'board=' . $board;
265
	$filename[] = $xml_format;
266
	$filename = preg_replace($context['utf8'] ? '/[^\p{L}\p{M}\p{N}\-]+/u' : '/[\s_,.\/\\;:\'<>?|\[\]{}~!@#$%^&*()=+`]+/', '_', str_replace('"', '', un_htmlspecialchars(strip_tags(implode('-', $filename)))));
267
268
	// This is an xml file....
269
	ob_end_clean();
270
	if (!empty($modSettings['enableCompressedOutput']))
271
		@ob_start('ob_gzhandler');
272
	else
273
		ob_start();
274
275
	if ($xml_format == 'smf' || isset($_GET['debug']))
276
		header('content-type: text/xml; charset=' . (empty($context['character_set']) ? 'UTF-8' : $context['character_set']));
277
	elseif ($xml_format == 'rss' || $xml_format == 'rss2')
278
		header('content-type: application/rss+xml; charset=' . (empty($context['character_set']) ? 'UTF-8' : $context['character_set']));
279
	elseif ($xml_format == 'atom')
280
		header('content-type: application/atom+xml; charset=' . (empty($context['character_set']) ? 'UTF-8' : $context['character_set']));
281
	elseif ($xml_format == 'rdf')
282
		header('content-type: ' . (isBrowser('ie') ? 'text/xml' : 'application/rdf+xml') . '; charset=' . (empty($context['character_set']) ? 'UTF-8' : $context['character_set']));
283
284
	header('content-disposition: ' . (isset($_GET['download']) ? 'attachment' : 'inline') . '; filename="' . $filename . '.xml"');
285
286
	echo implode('', $context['feed']);
287
288
	obExit(false);
289
}
290
291
function buildXmlFeed($xml_format, $xml_data, $feed_meta, $subaction)
292
{
293
	global $context, $txt, $scripturl;
294
295
	/* Important: Do NOT change this to an HTTPS address!
296
	 *
297
	 * Why? Because XML namespace names must be both unique and invariant
298
	 * once defined. They look like URLs merely because that's a convenient
299
	 * way to ensure uniqueness, but they are not used as URLs. They are
300
	 * used as case-sensitive identifier strings. If the string changes in
301
	 * any way, XML processing software (including PHP's own XML functions)
302
	 * will interpret the two versions of the string as entirely different
303
	 * namespaces, which could cause it to mangle the XML horrifically
304
	 * during processing.
305
	 */
306
	$smf_ns = 'htt'.'p:/'.'/ww'.'w.simple'.'machines.o'.'rg/xml/' . $subaction;
307
308
	// Allow mods to add extra namespaces and tags to the feed/channel
309
	$namespaces = array(
310
		'rss' => array(),
311
		'rss2' => array('atom' => 'htt'.'p:/'.'/ww'.'w.w3.o'.'rg/2005/Atom'),
312
		'atom' => array('' => 'htt'.'p:/'.'/ww'.'w.w3.o'.'rg/2005/Atom'),
313
		'rdf' => array(
314
			'' => 'htt'.'p:/'.'/purl.o'.'rg/rss/1.0/',
315
			'rdf' => 'htt'.'p:/'.'/ww'.'w.w3.o'.'rg/1999/02/22-rdf-syntax-ns#',
316
			'dc' => 'htt'.'p:/'.'/purl.o'.'rg/dc/elements/1.1/',
317
		),
318
		'smf' => array(
319
			'smf' => $smf_ns,
320
		),
321
	);
322
	if (in_array($subaction, array('profile', 'posts', 'personal_messages')))
323
	{
324
		$namespaces['rss']['smf'] = $smf_ns;
325
		$namespaces['rss2']['smf'] = $smf_ns;
326
		$namespaces['atom']['smf'] = $smf_ns;
327
	}
328
329
	$extraFeedTags = array(
330
		'rss' => array(),
331
		'rss2' => array(),
332
		'atom' => array(),
333
		'rdf' => array(),
334
		'smf' => array(),
335
	);
336
337
	// Allow mods to specify any keys that need special handling
338
	$forceCdataKeys = array();
339
	$nsKeys = array();
340
341
	// Maybe someone needs to insert a DOCTYPE declaration?
342
	$doctype = '';
343
344
	// Remember this, just in case...
345
	$orig_feed_meta = $feed_meta;
346
347
	// If mods want to do somthing with this feed, let them do that now.
348
	// Provide the feed's data, metadata, namespaces, extra feed-level tags, keys that need special handling, the feed format, and the requested subaction
349
	call_integration_hook('integrate_xml_data', array(&$xml_data, &$feed_meta, &$namespaces, &$extraFeedTags, &$forceCdataKeys, &$nsKeys, $xml_format, $subaction, &$doctype));
350
351
	// These can't be empty
352
	foreach (array('title', 'desc', 'source', 'self') as $mkey)
353
		$feed_meta[$mkey] = !empty($feed_meta[$mkey]) ? $feed_meta[$mkey] : $orig_feed_meta[$mkey];
354
355
	// Sanitize feed metadata values
356
	foreach ($feed_meta as $mkey => $mvalue)
357
		$feed_meta[$mkey] = cdata_parse(fix_possible_url($mvalue));
358
359
	$ns_string = '';
360
	if (!empty($namespaces[$xml_format]))
361
	{
362
		foreach ($namespaces[$xml_format] as $nsprefix => $nsurl)
363
			$ns_string .= ' xmlns' . ($nsprefix !== '' ? ':' : '') . $nsprefix . '="' . $nsurl . '"';
364
	}
365
366
	$i = in_array($xml_format, array('atom', 'smf')) ? 1 : 2;
367
368
	$extraFeedTags_string = '';
369
	if (!empty($extraFeedTags[$xml_format]))
370
	{
371
		$indent = str_repeat("\t", $i);
372
		foreach ($extraFeedTags[$xml_format] as $extraTag)
373
			$extraFeedTags_string .= "\n" . $indent . $extraTag;
374
	}
375
376
	$context['feed'] = array();
377
378
	// First, output the xml header.
379
	$context['feed']['header'] = '<?xml version="1.0" encoding="' . $context['character_set'] . '"?' . '>' . ($doctype !== '' ? "\n" . trim($doctype) : '');
0 ignored issues
show
The condition $doctype !== '' is always false.
Loading history...
380
381
	// Are we outputting an rss feed or one with more information?
382
	if ($xml_format == 'rss' || $xml_format == 'rss2')
383
	{
384
		// Start with an RSS 2.0 header.
385
		$context['feed']['header'] .= '
386
<rss version=' . ($xml_format == 'rss2' ? '"2.0"' : '"0.92"') . ' xml:lang="' . strtr($txt['lang_locale'], '_', '-') . '"' . $ns_string . '>
387
	<channel>
388
		<title>' . $feed_meta['title'] . '</title>
389
		<link>' . $feed_meta['source'] . '</link>
390
		<description>' . $feed_meta['desc'] . '</description>';
391
392
		if (!empty($feed_meta['icon']))
393
			$context['feed']['header'] .= '
394
		<image>
395
			<url>' . $feed_meta['icon'] . '</url>
396
			<title>' . $feed_meta['title'] . '</title>
397
			<link>' . $feed_meta['source'] . '</link>
398
		</image>';
399
400
		if (!empty($feed_meta['rights']))
401
			$context['feed']['header'] .= '
402
		<copyright>' . $feed_meta['rights'] . '</copyright>';
403
404
		if (!empty($feed_meta['language']))
405
			$context['feed']['header'] .= '
406
		<language>' . $feed_meta['language'] . '</language>';
407
408
		// RSS2 calls for this.
409
		if ($xml_format == 'rss2')
410
			$context['feed']['header'] .= '
411
		<atom:link rel="self" type="application/rss+xml" href="' . $feed_meta['self'] . '" />';
412
413
		$context['feed']['header'] .= $extraFeedTags_string;
414
415
		// Write the data as an XML string to $context['feed']['items']
416
		dumpTags($xml_data, $i, $xml_format, $forceCdataKeys, $nsKeys);
417
418
		// Output the footer of the xml.
419
		$context['feed']['footer'] = '
420
	</channel>
421
</rss>';
422
	}
423
	elseif ($xml_format == 'atom')
424
	{
425
		$context['feed']['header'] .= '
426
<feed' . $ns_string . (!empty($feed_meta['language']) ? ' xml:lang="' . $feed_meta['language'] . '"' : '') . '>
427
	<title>' . $feed_meta['title'] . '</title>
428
	<link rel="alternate" type="text/html" href="' . $feed_meta['source'] . '" />
429
	<link rel="self" type="application/atom+xml" href="' . $feed_meta['self'] . '" />
430
	<updated>' . smf_gmstrftime('%Y-%m-%dT%H:%M:%SZ') . '</updated>
431
	<id>' . $feed_meta['source'] . '</id>
432
	<subtitle>' . $feed_meta['desc'] . '</subtitle>
433
	<generator uri="https://www.simplemachines.org" version="' . SMF_VERSION . '">SMF</generator>';
434
435
		if (!empty($feed_meta['icon']))
436
			$context['feed']['header'] .= '
437
	<icon>' . $feed_meta['icon'] . '</icon>';
438
439
		if (!empty($feed_meta['author']))
440
			$context['feed']['header'] .= '
441
	<author>
442
		<name>' . $feed_meta['author'] . '</name>
443
	</author>';
444
445
		if (!empty($feed_meta['rights']))
446
			$context['feed']['header'] .= '
447
	<rights>' . $feed_meta['rights'] . '</rights>';
448
449
		$context['feed']['header'] .= $extraFeedTags_string;
450
451
		dumpTags($xml_data, $i, $xml_format, $forceCdataKeys, $nsKeys);
452
453
		$context['feed']['footer'] = '
454
</feed>';
455
	}
456
	elseif ($xml_format == 'rdf')
457
	{
458
		$context['feed']['header'] .= '
459
<rdf:RDF' . $ns_string . '>
460
	<channel rdf:about="' . $scripturl . '">
461
		<title>' . $feed_meta['title'] . '</title>
462
		<link>' . $feed_meta['source'] . '</link>
463
		<description>' . $feed_meta['desc'] . '</description>';
464
465
		$context['feed']['header'] .= $extraFeedTags_string;
466
467
		$context['feed']['header'] .= '
468
		<items>
469
			<rdf:Seq>';
470
471
		foreach ($xml_data as $item)
472
		{
473
			$link = array_filter(
474
				$item['content'],
475
				function($e)
476
				{
477
					return ($e['tag'] == 'link');
478
				}
479
			);
480
			$link = array_pop($link);
481
482
			$context['feed']['header'] .= '
483
				<rdf:li rdf:resource="' . $link['content'] . '" />';
484
		}
485
486
		$context['feed']['header'] .= '
487
			</rdf:Seq>
488
		</items>
489
	</channel>';
490
491
		dumpTags($xml_data, $i, $xml_format, $forceCdataKeys, $nsKeys);
492
493
		$context['feed']['footer'] = '
494
</rdf:RDF>';
495
	}
496
	// Otherwise, we're using our proprietary formats - they give more data, though.
497
	else
498
	{
499
		$context['feed']['header'] .= '
500
<smf:xml-feed xml:lang="' . strtr($txt['lang_locale'], '_', '-') . '"' . $ns_string . ' version="' . SMF_VERSION . '" forum-name="' . $context['forum_name'] . '" forum-url="' . $scripturl . '"' . (!empty($feed_meta['title']) && $feed_meta['title'] != $context['forum_name'] ? ' title="' . $feed_meta['title'] . '"' : '') . (!empty($feed_meta['desc']) ? ' description="' . $feed_meta['desc'] . '"' : '') . ' source="' . $feed_meta['source'] . '" generated-date-localized="' . strip_tags(timeformat(time(), false, 'forum')) . '" generated-date-UTC="' . smf_gmstrftime('%F %T') . '"' . (!empty($feed_meta['page']) ? ' page="' . $feed_meta['page'] . '"' : '') . '>';
501
502
		// Hard to imagine anyone wanting to add these for the proprietary format, but just in case...
503
		$context['feed']['header'] .= $extraFeedTags_string;
504
505
		// Dump out that associative array.  Indent properly.... and use the right names for the base elements.
506
		dumpTags($xml_data, $i, $xml_format, $forceCdataKeys, $nsKeys);
507
508
		$context['feed']['footer'] = '
509
</smf:xml-feed>';
510
	}
511
}
512
513
/**
514
 * Called from dumpTags to convert data to xml
515
 * Finds urls for local site and sanitizes them
516
 *
517
 * @param string $val A string containing a possible URL
518
 * @return string $val The string with any possible URLs sanitized
519
 */
520
function fix_possible_url($val)
521
{
522
	global $modSettings, $context, $scripturl;
523
524
	if (substr($val, 0, strlen($scripturl)) != $scripturl)
525
		return $val;
526
527
	call_integration_hook('integrate_fix_url', array(&$val));
528
529
	if (empty($modSettings['queryless_urls']) || ($context['server']['is_cgi'] && ini_get('cgi.fix_pathinfo') == 0 && @get_cfg_var('cgi.fix_pathinfo') == 0) || (!$context['server']['is_apache'] && !$context['server']['is_lighttpd']))
530
		return $val;
531
532
	$val = preg_replace_callback(
533
		'~\b' . preg_quote($scripturl, '~') . '\?((?:board|topic)=[^#"]+)(#[^"]*)?$~',
534
		function($m) use ($scripturl)
535
		{
536
			return $scripturl . '/' . strtr("$m[1]", '&;=', '//,') . '.html' . (isset($m[2]) ? $m[2] : "");
537
		},
538
		$val
539
	);
540
	return $val;
541
}
542
543
/**
544
 * Ensures supplied data is properly encapsulated in cdata xml tags
545
 * Called from getXmlProfile in News.php
546
 *
547
 * @param string $data XML data
548
 * @param string $ns A namespace prefix for the XML data elements (used by mods, maybe)
549
 * @param boolean $force If true, enclose the XML data in cdata tags no matter what (used by mods, maybe)
550
 * @return string The XML data enclosed in cdata tags when necessary
551
 */
552
function cdata_parse($data, $ns = '', $force = false)
553
{
554
	global $smcFunc;
555
556
	// Do we even need to do this?
557
	if (strpbrk($data, '<>&') == false && $force !== true)
0 ignored issues
show
Bug Best Practice introduced by
It seems like you are loosely comparing strpbrk($data, '<>&') of type string to the boolean false. If you are specifically checking for an empty string, consider using the more explicit === '' instead.
Loading history...
558
		return $data;
559
560
	$cdata = '<![CDATA[';
561
562
	// @todo If we drop the obsolete $ns parameter, this whole loop could be replaced with a simple `str_replace(']]>', ']]]]><[CDATA[>', $data)`
563
564
	for ($pos = 0, $n = strlen($data); $pos < $n; null)
565
	{
566
		$positions = array(
567
			strpos($data, ']]>', $pos),
568
		);
569
		if ($ns != '')
570
			$positions[] = strpos($data, '<', $pos);
571
		foreach ($positions as $k => $dummy)
572
		{
573
			if ($dummy === false)
574
				unset($positions[$k]);
575
		}
576
577
		$old = $pos;
578
		$pos = empty($positions) ? $n : min($positions);
579
580
		if ($pos - $old > 0)
581
			$cdata .= substr($data, $old, $pos - $old);
582
		if ($pos >= $n)
583
			break;
584
585
		if (substr($data, $pos, 1) == '<')
586
		{
587
			$pos2 = strpos($data, '>', $pos);
588
			if ($pos2 === false)
589
				$pos2 = $n;
590
			if (substr($data, $pos + 1, 1) == '/')
591
				$cdata .= ']]></' . $ns . ':' . substr($data, $pos + 2, $pos2 - $pos - 1) . '<![CDATA[';
592
			else
593
				$cdata .= ']]><' . $ns . ':' . substr($data, $pos + 1, $pos2 - $pos) . '<![CDATA[';
594
			$pos = $pos2 + 1;
595
		}
596
		elseif (substr($data, $pos, 3) == ']]>')
597
		{
598
			$cdata .= ']]]]><![CDATA[>';
599
			$pos = $pos + 3;
600
		}
601
	}
602
603
	$cdata .= ']]>';
604
605
	return strtr($cdata, array('<![CDATA[]]>' => ''));
606
}
607
608
/**
609
 * Formats data retrieved in other functions into xml format.
610
 * Additionally formats data based on the specific format passed.
611
 * This function is recursively called to handle sub arrays of data.
612
 *
613
 * @param array $data The array to output as xml data
614
 * @param int $i The amount of indentation to use.
615
 * @param string $xml_format The format to use ('atom', 'rss', 'rss2' or empty for plain XML)
616
 * @param array $forceCdataKeys A list of keys on which to force cdata wrapping (used by mods, maybe)
617
 * @param array $nsKeys Key-value pairs of namespace prefixes to pass to cdata_parse() (used by mods, maybe)
618
 */
619
function dumpTags($data, $i, $xml_format = '', $forceCdataKeys = array(), $nsKeys = array())
620
{
621
	global $context;
622
623
	if (empty($context['feed']['items']))
624
		$context['feed']['items'] = '';
625
626
	// For every array in the data...
627
	foreach ($data as $element)
628
	{
629
		$key = isset($element['tag']) ? $element['tag'] : null;
630
		$val = isset($element['content']) ? $element['content'] : null;
631
		$attrs = isset($element['attributes']) ? $element['attributes'] : null;
632
633
		// Skip it, it's been set to null.
634
		if ($key === null || ($val === null && $attrs === null))
635
			continue;
636
637
		$forceCdata = in_array($key, $forceCdataKeys);
638
		$ns = !empty($nsKeys[$key]) ? $nsKeys[$key] : '';
639
640
		// First let's indent!
641
		$context['feed']['items'] .= "\n" . str_repeat("\t", $i);
642
643
		// Beginning tag.
644
		$context['feed']['items'] .= '<' . $key;
645
646
		if (!empty($attrs))
647
		{
648
			foreach ($attrs as $attr_key => $attr_value)
649
				$context['feed']['items'] .= ' ' . $attr_key . '="' . fix_possible_url($attr_value) . '"';
650
		}
651
652
		// If it's empty, simply output an empty element.
653
		if (empty($val) && $val !== '0' && $val !== 0)
654
		{
655
			$context['feed']['items'] .= ' />';
656
		}
657
		else
658
		{
659
			$context['feed']['items'] .= '>';
660
661
			// The element's value.
662
			if (is_array($val))
663
			{
664
				// An array.  Dump it, and then indent the tag.
665
				dumpTags($val, $i + 1, $xml_format, $forceCdataKeys, $nsKeys);
666
				$context['feed']['items'] .= "\n" . str_repeat("\t", $i);
667
			}
668
			// A string with returns in it.... show this as a multiline element.
669
			elseif (strpos($val, "\n") !== false)
670
				$context['feed']['items'] .= "\n" . (!empty($element['cdata']) || $forceCdata ? cdata_parse(fix_possible_url($val), $ns, $forceCdata) : fix_possible_url($val)) . "\n" . str_repeat("\t", $i);
671
			// A simple string.
672
			else
673
				$context['feed']['items'] .= !empty($element['cdata']) || $forceCdata ? cdata_parse(fix_possible_url($val), $ns, $forceCdata) : fix_possible_url($val);
674
675
			// Ending tag.
676
			$context['feed']['items'] .= '</' . $key . '>';
677
		}
678
	}
679
}
680
681
/**
682
 * Retrieve the list of members from database.
683
 * The array will be generated to match the format.
684
 *
685
 * @todo get the list of members from Subs-Members.
686
 *
687
 * @param string $xml_format The format to use. Can be 'atom', 'rdf', 'rss', 'rss2' or 'smf'
688
 * @param bool $ascending If true, get the earliest members first. Default false.
689
 * @return array An array of arrays of feed items. Each array has keys corresponding to the appropriate tags for the specified format.
690
 */
691
function getXmlMembers($xml_format, $ascending = false)
692
{
693
	global $scripturl, $smcFunc, $txt, $context;
694
695
	if (!allowedTo('view_mlist'))
696
		return array();
697
698
	loadLanguage('Profile');
699
700
	// Find the most (or least) recent members.
701
	$request = $smcFunc['db_query']('', '
702
		SELECT id_member, member_name, real_name, date_registered, last_login
703
		FROM {db_prefix}members
704
		ORDER BY id_member {raw:ascdesc}
705
		LIMIT {int:limit}',
706
		array(
707
			'limit' => $context['xmlnews_limit'],
708
			'ascdesc' => !empty($ascending) ? 'ASC' : 'DESC',
709
		)
710
	);
711
	$data = array();
712
	while ($row = $smcFunc['db_fetch_assoc']($request))
713
	{
714
		// If any control characters slipped in somehow, kill the evil things
715
		$row = filter_var($row, FILTER_CALLBACK, array('options' => 'cleanXml'));
716
717
		// Create a GUID for each member using the tag URI scheme
718
		$guid = 'tag:' . parse_iri($scripturl, PHP_URL_HOST) . ',' . gmdate('Y-m-d', $row['date_registered']) . ':member=' . $row['id_member'];
719
720
		// Make the data look rss-ish.
721
		if ($xml_format == 'rss' || $xml_format == 'rss2')
722
			$data[] = array(
723
				'tag' => 'item',
724
				'content' => array(
725
					array(
726
						'tag' => 'title',
727
						'content' => $row['real_name'],
728
						'cdata' => true,
729
					),
730
					array(
731
						'tag' => 'link',
732
						'content' => $scripturl . '?action=profile;u=' . $row['id_member'],
733
					),
734
					array(
735
						'tag' => 'comments',
736
						'content' => $scripturl . '?action=pm;sa=send;u=' . $row['id_member'],
737
					),
738
					array(
739
						'tag' => 'pubDate',
740
						'content' => gmdate('D, d M Y H:i:s \G\M\T', $row['date_registered']),
741
					),
742
					array(
743
						'tag' => 'guid',
744
						'content' => $guid,
745
						'attributes' => array(
746
							'isPermaLink' => 'false',
747
						),
748
					),
749
				),
750
			);
751
		elseif ($xml_format == 'rdf')
752
			$data[] = array(
753
				'tag' => 'item',
754
				'attributes' => array('rdf:about' => $scripturl . '?action=profile;u=' . $row['id_member']),
755
				'content' => array(
756
					array(
757
						'tag' => 'dc:format',
758
						'content' => 'text/html',
759
					),
760
					array(
761
						'tag' => 'title',
762
						'content' => $row['real_name'],
763
						'cdata' => true,
764
					),
765
					array(
766
						'tag' => 'link',
767
						'content' => $scripturl . '?action=profile;u=' . $row['id_member'],
768
					),
769
				),
770
			);
771
		elseif ($xml_format == 'atom')
772
			$data[] = array(
773
				'tag' => 'entry',
774
				'content' => array(
775
					array(
776
						'tag' => 'title',
777
						'content' => $row['real_name'],
778
						'cdata' => true,
779
					),
780
					array(
781
						'tag' => 'link',
782
						'attributes' => array(
783
							'rel' => 'alternate',
784
							'type' => 'text/html',
785
							'href' => $scripturl . '?action=profile;u=' . $row['id_member'],
786
						),
787
					),
788
					array(
789
						'tag' => 'published',
790
						'content' => smf_gmstrftime('%Y-%m-%dT%H:%M:%SZ', $row['date_registered']),
791
					),
792
					array(
793
						'tag' => 'updated',
794
						'content' => smf_gmstrftime('%Y-%m-%dT%H:%M:%SZ', $row['last_login']),
795
					),
796
					array(
797
						'tag' => 'id',
798
						'content' => $guid,
799
					),
800
				),
801
			);
802
		// More logical format for the data, but harder to apply.
803
		else
804
			$data[] = array(
805
				'tag' => 'member',
806
				'attributes' => array('label' => $txt['who_member']),
807
				'content' => array(
808
					array(
809
						'tag' => 'name',
810
						'attributes' => array('label' => $txt['name']),
811
						'content' => $row['real_name'],
812
						'cdata' => true,
813
					),
814
					array(
815
						'tag' => 'time',
816
						'attributes' => array('label' => $txt['date_registered'], 'UTC' => smf_gmstrftime('%F %T', $row['date_registered'])),
817
						'content' => $smcFunc['htmlspecialchars'](strip_tags(timeformat($row['date_registered'], false, 'forum'))),
818
					),
819
					array(
820
						'tag' => 'id',
821
						'content' => $row['id_member'],
822
					),
823
					array(
824
						'tag' => 'link',
825
						'attributes' => array('label' => $txt['url']),
826
						'content' => $scripturl . '?action=profile;u=' . $row['id_member'],
827
					),
828
				),
829
			);
830
	}
831
	$smcFunc['db_free_result']($request);
832
833
	return $data;
834
}
835
836
/**
837
 * Get the latest topics information from a specific board,
838
 * to display later.
839
 * The returned array will be generated to match the xml_format.
840
 *
841
 * @param string $xml_format The XML format. Can be 'atom', 'rdf', 'rss', 'rss2' or 'smf'.
842
 * @param bool $ascending If true, get the oldest topics first. Default false.
843
 * @return array An array of arrays of topic data for the feed. Each array has keys corresponding to the tags for the specified format.
844
 */
845
function getXmlNews($xml_format, $ascending = false)
846
{
847
	global $scripturl, $modSettings, $board, $user_info;
848
	global $query_this_board, $smcFunc, $context, $txt;
849
850
	/* Find the latest (or earliest) posts that:
851
		- are the first post in their topic.
852
		- are on an any board OR in a specified board.
853
		- can be seen by this user. */
854
855
	$done = false;
856
	$loops = 0;
857
	while (!$done)
858
	{
859
		$optimize_msg = implode(' AND ', $context['optimize_msg']);
860
		$request = $smcFunc['db_query']('', '
861
			SELECT
862
				m.smileys_enabled, m.poster_time, m.id_msg, m.subject, m.body, m.modified_time,
863
				m.icon, t.id_topic, t.id_board, t.num_replies,
864
				b.name AS bname,
865
				COALESCE(mem.id_member, 0) AS id_member,
866
				COALESCE(mem.email_address, m.poster_email) AS poster_email,
867
				COALESCE(mem.real_name, m.poster_name) AS poster_name
868
			FROM {db_prefix}topics AS t
869
				INNER JOIN {db_prefix}messages AS m ON (m.id_msg = t.id_first_msg)
870
				INNER JOIN {db_prefix}boards AS b ON (b.id_board = t.id_board)
871
				LEFT JOIN {db_prefix}members AS mem ON (mem.id_member = m.id_member)
872
			WHERE ' . $query_this_board . (empty($optimize_msg) ? '' : '
873
				AND {raw:optimize_msg}') . (empty($board) ? '' : '
874
				AND t.id_board = {int:current_board}') . ($modSettings['postmod_active'] ? '
875
				AND t.approved = {int:is_approved}' : '') . '
876
			ORDER BY t.id_first_msg {raw:ascdesc}
877
			LIMIT {int:limit}',
878
			array(
879
				'current_board' => $board,
880
				'is_approved' => 1,
881
				'limit' => $context['xmlnews_limit'],
882
				'optimize_msg' => $optimize_msg,
883
				'ascdesc' => !empty($ascending) ? 'ASC' : 'DESC',
884
			)
885
		);
886
		// If we don't have $context['xmlnews_limit'] results, try again with an unoptimized version covering all rows.
887
		if ($loops < 2 && $smcFunc['db_num_rows']($request) < $context['xmlnews_limit'])
888
		{
889
			$smcFunc['db_free_result']($request);
890
			if (empty($_GET['boards']) && empty($board))
891
				unset($context['optimize_msg']['lowest']);
892
			else
893
				$context['optimize_msg']['lowest'] = 'm.id_msg >= t.id_first_msg';
894
			$context['optimize_msg']['highest'] = 'm.id_msg <= t.id_last_msg';
895
			$loops++;
896
		}
897
		else
898
			$done = true;
899
	}
900
	$data = array();
901
	while ($row = $smcFunc['db_fetch_assoc']($request))
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $request does not seem to be defined for all execution paths leading up to this point.
Loading history...
902
	{
903
		// If any control characters slipped in somehow, kill the evil things
904
		$row = filter_var($row, FILTER_CALLBACK, array('options' => 'cleanXml'));
905
906
		// Limit the length of the message, if the option is set.
907
		if (!empty($modSettings['xmlnews_maxlen']) && $smcFunc['strlen'](str_replace('<br>', "\n", $row['body'])) > $modSettings['xmlnews_maxlen'])
908
			$row['body'] = strtr($smcFunc['substr'](str_replace('<br>', "\n", $row['body']), 0, $modSettings['xmlnews_maxlen'] - 3), array("\n" => '<br>')) . '...';
909
910
		$row['body'] = parse_bbc($row['body'], $row['smileys_enabled'], $row['id_msg']);
911
912
		censorText($row['body']);
913
		censorText($row['subject']);
914
915
		// Do we want to include any attachments?
916
		if (!empty($modSettings['attachmentEnable']) && !empty($modSettings['xmlnews_attachments']) && allowedTo('view_attachments', $row['id_board']))
917
		{
918
			$attach_request = $smcFunc['db_query']('', '
919
				SELECT
920
					a.id_attach, a.filename, COALESCE(a.size, 0) AS filesize, a.mime_type, a.downloads, a.approved, m.id_topic AS topic
921
				FROM {db_prefix}attachments AS a
922
					LEFT JOIN {db_prefix}messages AS m ON (m.id_msg = a.id_msg)
923
				WHERE a.attachment_type = {int:attachment_type}
924
					AND a.id_msg = {int:message_id}',
925
				array(
926
					'message_id' => $row['id_msg'],
927
					'attachment_type' => 0,
928
					'is_approved' => 1,
929
				)
930
			);
931
			$loaded_attachments = array();
932
			while ($attach = $smcFunc['db_fetch_assoc']($attach_request))
933
			{
934
				// Include approved attachments only
935
				if ($attach['approved'])
936
					$loaded_attachments['attachment_' . $attach['id_attach']] = $attach;
937
			}
938
			$smcFunc['db_free_result']($attach_request);
939
940
			// Sort the attachments by size to make things easier below
941
			if (!empty($loaded_attachments))
942
			{
943
				uasort(
944
					$loaded_attachments,
945
					function($a, $b)
946
					{
947
						if ($a['filesize'] == $b['filesize'])
948
							return 0;
949
950
						return ($a['filesize'] < $b['filesize']) ? -1 : 1;
951
					}
952
				);
953
			}
954
			else
955
				$loaded_attachments = null;
956
		}
957
		else
958
			$loaded_attachments = null;
959
960
		// Create a GUID for this topic using the tag URI scheme
961
		$guid = 'tag:' . parse_iri($scripturl, PHP_URL_HOST) . ',' . gmdate('Y-m-d', $row['poster_time']) . ':topic=' . $row['id_topic'];
962
963
		// Being news, this actually makes sense in rss format.
964
		if ($xml_format == 'rss' || $xml_format == 'rss2')
965
		{
966
			// Only one attachment allowed in RSS.
967
			if ($loaded_attachments !== null)
968
			{
969
				$attachment = array_pop($loaded_attachments);
0 ignored issues
show
$loaded_attachments of type null is incompatible with the type array expected by parameter $array of array_pop(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

969
				$attachment = array_pop(/** @scrutinizer ignore-type */ $loaded_attachments);
Loading history...
970
				$enclosure = array(
971
					'url' => fix_possible_url($scripturl . '?action=dlattach;topic=' . $attachment['topic'] . '.0;attach=' . $attachment['id_attach']),
972
					'length' => $attachment['filesize'],
973
					'type' => $attachment['mime_type'],
974
				);
975
			}
976
			else
977
				$enclosure = null;
978
979
			$data[] = array(
980
				'tag' => 'item',
981
				'content' => array(
982
					array(
983
						'tag' => 'title',
984
						'content' => $row['subject'],
985
						'cdata' => true,
986
					),
987
					array(
988
						'tag' => 'link',
989
						'content' => $scripturl . '?topic=' . $row['id_topic'] . '.0',
990
					),
991
					array(
992
						'tag' => 'description',
993
						'content' => $row['body'],
994
						'cdata' => true,
995
					),
996
					array(
997
						'tag' => 'author',
998
						'content' => (allowedTo('moderate_forum') || $row['id_member'] == $user_info['id']) ? $row['poster_email'] . ' (' . $row['poster_name'] . ')' : null,
999
						'cdata' => true,
1000
					),
1001
					array(
1002
						'tag' => 'comments',
1003
						'content' => $scripturl . '?action=post;topic=' . $row['id_topic'] . '.0',
1004
					),
1005
					array(
1006
						'tag' => 'category',
1007
						'content' => $row['bname'],
1008
						'cdata' => true,
1009
					),
1010
					array(
1011
						'tag' => 'pubDate',
1012
						'content' => gmdate('D, d M Y H:i:s \G\M\T', $row['poster_time']),
1013
					),
1014
					array(
1015
						'tag' => 'guid',
1016
						'content' => $guid,
1017
						'attributes' => array(
1018
							'isPermaLink' => 'false',
1019
						),
1020
					),
1021
					array(
1022
						'tag' => 'enclosure',
1023
						'attributes' => $enclosure,
1024
					),
1025
				),
1026
			);
1027
		}
1028
		elseif ($xml_format == 'rdf')
1029
		{
1030
			$data[] = array(
1031
				'tag' => 'item',
1032
				'attributes' => array('rdf:about' => $scripturl . '?topic=' . $row['id_topic'] . '.0'),
1033
				'content' => array(
1034
					array(
1035
						'tag' => 'dc:format',
1036
						'content' => 'text/html',
1037
					),
1038
					array(
1039
						'tag' => 'title',
1040
						'content' => $row['subject'],
1041
						'cdata' => true,
1042
					),
1043
					array(
1044
						'tag' => 'link',
1045
						'content' => $scripturl . '?topic=' . $row['id_topic'] . '.0',
1046
					),
1047
					array(
1048
						'tag' => 'description',
1049
						'content' => $row['body'],
1050
						'cdata' => true,
1051
					),
1052
				),
1053
			);
1054
		}
1055
		elseif ($xml_format == 'atom')
1056
		{
1057
			// Only one attachment allowed
1058
			if (!empty($loaded_attachments))
1059
			{
1060
				$attachment = array_pop($loaded_attachments);
1061
				$enclosure = array(
1062
					'rel' => 'enclosure',
1063
					'href' => fix_possible_url($scripturl . '?action=dlattach;topic=' . $attachment['topic'] . '.0;attach=' . $attachment['id_attach']),
1064
					'length' => $attachment['filesize'],
1065
					'type' => $attachment['mime_type'],
1066
				);
1067
			}
1068
			else
1069
				$enclosure = null;
1070
1071
			$data[] = array(
1072
				'tag' => 'entry',
1073
				'content' => array(
1074
					array(
1075
						'tag' => 'title',
1076
						'content' => $row['subject'],
1077
						'cdata' => true,
1078
					),
1079
					array(
1080
						'tag' => 'link',
1081
						'attributes' => array(
1082
							'rel' => 'alternate',
1083
							'type' => 'text/html',
1084
							'href' => $scripturl . '?topic=' . $row['id_topic'] . '.0',
1085
						),
1086
					),
1087
					array(
1088
						'tag' => 'summary',
1089
						'attributes' => array('type' => 'html'),
1090
						'content' => $row['body'],
1091
						'cdata' => true,
1092
					),
1093
					array(
1094
						'tag' => 'category',
1095
						'attributes' => array('term' => $row['bname']),
1096
						'cdata' => true,
1097
					),
1098
					array(
1099
						'tag' => 'author',
1100
						'content' => array(
1101
							array(
1102
								'tag' => 'name',
1103
								'content' => $row['poster_name'],
1104
								'cdata' => true,
1105
							),
1106
							array(
1107
								'tag' => 'email',
1108
								'content' => (allowedTo('moderate_forum') || $row['id_member'] == $user_info['id']) ? $row['poster_email'] : null,
1109
								'cdata' => true,
1110
							),
1111
							array(
1112
								'tag' => 'uri',
1113
								'content' => !empty($row['id_member']) ? $scripturl . '?action=profile;u=' . $row['id_member'] : null,
1114
							),
1115
						)
1116
					),
1117
					array(
1118
						'tag' => 'published',
1119
						'content' => smf_gmstrftime('%Y-%m-%dT%H:%M:%SZ', $row['poster_time']),
1120
					),
1121
					array(
1122
						'tag' => 'updated',
1123
						'content' => smf_gmstrftime('%Y-%m-%dT%H:%M:%SZ', empty($row['modified_time']) ? $row['poster_time'] : $row['modified_time']),
1124
					),
1125
					array(
1126
						'tag' => 'id',
1127
						'content' => $guid,
1128
					),
1129
					array(
1130
						'tag' => 'link',
1131
						'attributes' => $enclosure,
1132
					),
1133
				),
1134
			);
1135
		}
1136
		// The biggest difference here is more information.
1137
		else
1138
		{
1139
			loadLanguage('Post');
1140
1141
			$attachments = array();
1142
			if (!empty($loaded_attachments))
1143
			{
1144
				foreach ($loaded_attachments as $attachment)
1145
				{
1146
					$attachments[] = array(
1147
						'tag' => 'attachment',
1148
						'attributes' => array('label' => $txt['attachment']),
1149
						'content' => array(
1150
							array(
1151
								'tag' => 'id',
1152
								'content' => $attachment['id_attach'],
1153
							),
1154
							array(
1155
								'tag' => 'name',
1156
								'attributes' => array('label' => $txt['name']),
1157
								'content' => preg_replace('~&amp;#(\\d{1,7}|x[0-9a-fA-F]{1,6});~', '&#\\1;', $smcFunc['htmlspecialchars']($attachment['filename'])),
1158
							),
1159
							array(
1160
								'tag' => 'downloads',
1161
								'attributes' => array('label' => $txt['downloads']),
1162
								'content' => $attachment['downloads'],
1163
							),
1164
							array(
1165
								'tag' => 'size',
1166
								'attributes' => array('label' => $txt['filesize']),
1167
								'content' => ($attachment['filesize'] < 1024000) ? round($attachment['filesize'] / 1024, 2) . ' ' . $txt['kilobyte'] : round($attachment['filesize'] / 1024 / 1024, 2) . ' ' . $txt['megabyte'],
1168
							),
1169
							array(
1170
								'tag' => 'byte_size',
1171
								'attributes' => array('label' => $txt['filesize']),
1172
								'content' => $attachment['filesize'],
1173
							),
1174
							array(
1175
								'tag' => 'link',
1176
								'attributes' => array('label' => $txt['url']),
1177
								'content' => $scripturl . '?action=dlattach;topic=' . $attachment['topic'] . '.0;attach=' . $attachment['id_attach'],
1178
							),
1179
						)
1180
					);
1181
				}
1182
			}
1183
			else
1184
				$attachments = null;
1185
1186
			$data[] = array(
1187
				'tag' => 'article',
1188
				'attributes' => array('label' => $txt['news']),
1189
				'content' => array(
1190
					array(
1191
						'tag' => 'time',
1192
						'attributes' => array('label' => $txt['date'], 'UTC' => smf_gmstrftime('%F %T', $row['poster_time'])),
1193
						'content' => $smcFunc['htmlspecialchars'](strip_tags(timeformat($row['poster_time'], false, 'forum'))),
1194
					),
1195
					array(
1196
						'tag' => 'id',
1197
						'content' => $row['id_topic'],
1198
					),
1199
					array(
1200
						'tag' => 'subject',
1201
						'attributes' => array('label' => $txt['subject']),
1202
						'content' => $row['subject'],
1203
						'cdata' => true,
1204
					),
1205
					array(
1206
						'tag' => 'body',
1207
						'attributes' => array('label' => $txt['message']),
1208
						'content' => $row['body'],
1209
						'cdata' => true,
1210
					),
1211
					array(
1212
						'tag' => 'poster',
1213
						'attributes' => array('label' => $txt['author']),
1214
						'content' => array(
1215
							array(
1216
								'tag' => 'name',
1217
								'attributes' => array('label' => $txt['name']),
1218
								'content' => $row['poster_name'],
1219
								'cdata' => true,
1220
							),
1221
							array(
1222
								'tag' => 'id',
1223
								'content' => $row['id_member'],
1224
							),
1225
							array(
1226
								'tag' => 'link',
1227
								'attributes' => !empty($row['id_member']) ? array('label' => $txt['url']) : null,
1228
								'content' => !empty($row['id_member']) ? $scripturl . '?action=profile;u=' . $row['id_member'] : '',
1229
							),
1230
						)
1231
					),
1232
					array(
1233
						'tag' => 'topic',
1234
						'attributes' => array('label' => $txt['topic']),
1235
						'content' => $row['id_topic'],
1236
					),
1237
					array(
1238
						'tag' => 'board',
1239
						'attributes' => array('label' => $txt['board']),
1240
						'content' => array(
1241
							array(
1242
								'tag' => 'name',
1243
								'attributes' => array('label' => $txt['name']),
1244
								'content' => $row['bname'],
1245
								'cdata' => true,
1246
							),
1247
							array(
1248
								'tag' => 'id',
1249
								'content' => $row['id_board'],
1250
							),
1251
							array(
1252
								'tag' => 'link',
1253
								'attributes' => array('label' => $txt['url']),
1254
								'content' => $scripturl . '?board=' . $row['id_board'] . '.0',
1255
							),
1256
						),
1257
					),
1258
					array(
1259
						'tag' => 'link',
1260
						'attributes' => array('label' => $txt['url']),
1261
						'content' => $scripturl . '?topic=' . $row['id_topic'] . '.0',
1262
					),
1263
					array(
1264
						'tag' => 'attachments',
1265
						'attributes' => array('label' => $txt['attachments']),
1266
						'content' => $attachments,
1267
					),
1268
				),
1269
			);
1270
		}
1271
	}
1272
	$smcFunc['db_free_result']($request);
1273
1274
	return $data;
1275
}
1276
1277
/**
1278
 * Get the recent topics to display.
1279
 * The returned array will be generated to match the xml_format.
1280
 *
1281
 * @param string $xml_format The XML format. Can be 'atom', 'rdf', 'rss', 'rss2' or 'smf'
1282
 * @return array An array of arrays containing data for the feed. Each array has keys corresponding to the appropriate tags for the specified format.
1283
 */
1284
function getXmlRecent($xml_format)
1285
{
1286
	global $scripturl, $modSettings, $board, $txt;
1287
	global $query_this_board, $smcFunc, $context, $user_info, $sourcedir;
1288
1289
	require_once($sourcedir . '/Subs-Attachments.php');
1290
1291
	$done = false;
1292
	$loops = 0;
1293
	while (!$done)
1294
	{
1295
		$optimize_msg = implode(' AND ', $context['optimize_msg']);
1296
		$request = $smcFunc['db_query']('', '
1297
			SELECT m.id_msg
1298
			FROM {db_prefix}messages AS m
1299
				INNER JOIN {db_prefix}boards AS b ON (b.id_board = m.id_board)
1300
				INNER JOIN {db_prefix}topics AS t ON (t.id_topic = m.id_topic)
1301
			WHERE ' . $query_this_board . (empty($optimize_msg) ? '' : '
1302
				AND {raw:optimize_msg}') . (empty($board) ? '' : '
1303
				AND m.id_board = {int:current_board}') . ($modSettings['postmod_active'] ? '
1304
				AND m.approved = {int:is_approved}
1305
				AND t.approved = {int:is_approved}' : '') . '
1306
			ORDER BY m.id_msg DESC
1307
			LIMIT {int:limit}',
1308
			array(
1309
				'limit' => $context['xmlnews_limit'],
1310
				'current_board' => $board,
1311
				'is_approved' => 1,
1312
				'optimize_msg' => $optimize_msg,
1313
			)
1314
		);
1315
		// If we don't have $context['xmlnews_limit'] results, try again with an unoptimized version covering all rows.
1316
		if ($loops < 2 && $smcFunc['db_num_rows']($request) < $context['xmlnews_limit'])
1317
		{
1318
			$smcFunc['db_free_result']($request);
1319
			if (empty($_GET['boards']) && empty($board))
1320
				unset($context['optimize_msg']['lowest']);
1321
			else
1322
				$context['optimize_msg']['lowest'] = $loops ? 'm.id_msg >= t.id_first_msg' : 'm.id_msg >= (t.id_last_msg - t.id_first_msg) / 2';
1323
			$loops++;
1324
		}
1325
		else
1326
			$done = true;
1327
	}
1328
	$messages = array();
1329
	while ($row = $smcFunc['db_fetch_assoc']($request))
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $request does not seem to be defined for all execution paths leading up to this point.
Loading history...
1330
		$messages[] = $row['id_msg'];
1331
	$smcFunc['db_free_result']($request);
1332
1333
	if (empty($messages))
1334
		return array();
1335
1336
	// Find the most recent posts this user can see.
1337
	$request = $smcFunc['db_query']('', '
1338
		SELECT
1339
			m.smileys_enabled, m.poster_time, m.id_msg, m.subject, m.body, m.id_topic, t.id_board,
1340
			b.name AS bname, t.num_replies, m.id_member, m.icon, mf.id_member AS id_first_member,
1341
			COALESCE(mem.real_name, m.poster_name) AS poster_name, mf.subject AS first_subject,
1342
			COALESCE(memf.real_name, mf.poster_name) AS first_poster_name,
1343
			COALESCE(mem.email_address, m.poster_email) AS poster_email, m.modified_time
1344
		FROM {db_prefix}messages AS m
1345
			INNER JOIN {db_prefix}topics AS t ON (t.id_topic = m.id_topic)
1346
			INNER JOIN {db_prefix}messages AS mf ON (mf.id_msg = t.id_first_msg)
1347
			INNER JOIN {db_prefix}boards AS b ON (b.id_board = t.id_board)
1348
			LEFT JOIN {db_prefix}members AS mem ON (mem.id_member = m.id_member)
1349
			LEFT JOIN {db_prefix}members AS memf ON (memf.id_member = mf.id_member)
1350
		WHERE m.id_msg IN ({array_int:message_list})
1351
			' . (empty($board) ? '' : 'AND t.id_board = {int:current_board}') . '
1352
		ORDER BY m.id_msg DESC
1353
		LIMIT {int:limit}',
1354
		array(
1355
			'limit' => $context['xmlnews_limit'],
1356
			'current_board' => $board,
1357
			'message_list' => $messages,
1358
		)
1359
	);
1360
	$data = array();
1361
	while ($row = $smcFunc['db_fetch_assoc']($request))
1362
	{
1363
		// If any control characters slipped in somehow, kill the evil things
1364
		$row = filter_var($row, FILTER_CALLBACK, array('options' => 'cleanXml'));
1365
1366
		// Limit the length of the message, if the option is set.
1367
		if (!empty($modSettings['xmlnews_maxlen']) && $smcFunc['strlen'](str_replace('<br>', "\n", $row['body'])) > $modSettings['xmlnews_maxlen'])
1368
			$row['body'] = strtr($smcFunc['substr'](str_replace('<br>', "\n", $row['body']), 0, $modSettings['xmlnews_maxlen'] - 3), array("\n" => '<br>')) . '...';
1369
1370
		$row['body'] = parse_bbc($row['body'], $row['smileys_enabled'], $row['id_msg']);
1371
1372
		censorText($row['body']);
1373
		censorText($row['subject']);
1374
1375
		// Do we want to include any attachments?
1376
		if (!empty($modSettings['attachmentEnable']) && !empty($modSettings['xmlnews_attachments']) && allowedTo('view_attachments', $row['id_board']))
1377
		{
1378
			$attach_request = $smcFunc['db_query']('', '
1379
				SELECT
1380
					a.id_attach, a.filename, COALESCE(a.size, 0) AS filesize, a.mime_type, a.downloads, a.approved, m.id_topic AS topic
1381
				FROM {db_prefix}attachments AS a
1382
					LEFT JOIN {db_prefix}messages AS m ON (m.id_msg = a.id_msg)
1383
				WHERE a.attachment_type = {int:attachment_type}
1384
					AND a.id_msg = {int:message_id}',
1385
				array(
1386
					'message_id' => $row['id_msg'],
1387
					'attachment_type' => 0,
1388
					'is_approved' => 1,
1389
				)
1390
			);
1391
			$loaded_attachments = array();
1392
			while ($attach = $smcFunc['db_fetch_assoc']($attach_request))
1393
			{
1394
				// Include approved attachments only
1395
				if ($attach['approved'])
1396
					$loaded_attachments['attachment_' . $attach['id_attach']] = $attach;
1397
			}
1398
			$smcFunc['db_free_result']($attach_request);
1399
1400
			// Sort the attachments by size to make things easier below
1401
			if (!empty($loaded_attachments))
1402
			{
1403
				uasort(
1404
					$loaded_attachments,
1405
					function($a, $b)
1406
					{
1407
						if ($a['filesize'] == $b['filesize'])
1408
							return 0;
1409
1410
						return ($a['filesize'] < $b['filesize']) ? -1 : 1;
1411
					}
1412
				);
1413
			}
1414
			else
1415
				$loaded_attachments = null;
1416
		}
1417
		else
1418
			$loaded_attachments = null;
1419
1420
		// Create a GUID for this post using the tag URI scheme
1421
		$guid = 'tag:' . parse_iri($scripturl, PHP_URL_HOST) . ',' . gmdate('Y-m-d', $row['poster_time']) . ':msg=' . $row['id_msg'];
1422
1423
		// Doesn't work as well as news, but it kinda does..
1424
		if ($xml_format == 'rss' || $xml_format == 'rss2')
1425
		{
1426
			// Only one attachment allowed in RSS.
1427
			if ($loaded_attachments !== null)
1428
			{
1429
				$attachment = array_pop($loaded_attachments);
0 ignored issues
show
$loaded_attachments of type null is incompatible with the type array expected by parameter $array of array_pop(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

1429
				$attachment = array_pop(/** @scrutinizer ignore-type */ $loaded_attachments);
Loading history...
1430
				$enclosure = array(
1431
					'url' => fix_possible_url($scripturl . '?action=dlattach;topic=' . $attachment['topic'] . '.0;attach=' . $attachment['id_attach']),
1432
					'length' => $attachment['filesize'],
1433
					'type' => $attachment['mime_type'],
1434
				);
1435
			}
1436
			else
1437
				$enclosure = null;
1438
1439
			$data[] = array(
1440
				'tag' => 'item',
1441
				'content' => array(
1442
					array(
1443
						'tag' => 'title',
1444
						'content' => $row['subject'],
1445
						'cdata' => true,
1446
					),
1447
					array(
1448
						'tag' => 'link',
1449
						'content' => $scripturl . '?topic=' . $row['id_topic'] . '.msg' . $row['id_msg'] . '#msg' . $row['id_msg'],
1450
					),
1451
					array(
1452
						'tag' => 'description',
1453
						'content' => $row['body'],
1454
						'cdata' => true,
1455
					),
1456
					array(
1457
						'tag' => 'author',
1458
						'content' => (allowedTo('moderate_forum') || (!empty($row['id_member']) && $row['id_member'] == $user_info['id'])) ? $row['poster_email'] : null,
1459
						'cdata' => true,
1460
					),
1461
					array(
1462
						'tag' => 'category',
1463
						'content' => $row['bname'],
1464
						'cdata' => true,
1465
					),
1466
					array(
1467
						'tag' => 'comments',
1468
						'content' => $scripturl . '?action=post;topic=' . $row['id_topic'] . '.0',
1469
					),
1470
					array(
1471
						'tag' => 'pubDate',
1472
						'content' => gmdate('D, d M Y H:i:s \G\M\T', $row['poster_time']),
1473
					),
1474
					array(
1475
						'tag' => 'guid',
1476
						'content' => $guid,
1477
						'attributes' => array(
1478
							'isPermaLink' => 'false',
1479
						),
1480
					),
1481
					array(
1482
						'tag' => 'enclosure',
1483
						'attributes' => $enclosure,
1484
					),
1485
				),
1486
			);
1487
		}
1488
		elseif ($xml_format == 'rdf')
1489
		{
1490
			$data[] = array(
1491
				'tag' => 'item',
1492
				'attributes' => array('rdf:about' => $scripturl . '?topic=' . $row['id_topic'] . '.msg' . $row['id_msg'] . '#msg' . $row['id_msg']),
1493
				'content' => array(
1494
					array(
1495
						'tag' => 'dc:format',
1496
						'content' => 'text/html',
1497
					),
1498
					array(
1499
						'tag' => 'title',
1500
						'content' => $row['subject'],
1501
						'cdata' => true,
1502
					),
1503
					array(
1504
						'tag' => 'link',
1505
						'content' => $scripturl . '?topic=' . $row['id_topic'] . '.msg' . $row['id_msg'] . '#msg' . $row['id_msg'],
1506
					),
1507
					array(
1508
						'tag' => 'description',
1509
						'content' => $row['body'],
1510
						'cdata' => true,
1511
					),
1512
				),
1513
			);
1514
		}
1515
		elseif ($xml_format == 'atom')
1516
		{
1517
			// Only one attachment allowed
1518
			if (!empty($loaded_attachments))
1519
			{
1520
				$attachment = array_pop($loaded_attachments);
1521
				$enclosure = array(
1522
					'rel' => 'enclosure',
1523
					'href' => fix_possible_url($scripturl . '?action=dlattach;topic=' . $attachment['topic'] . '.0;attach=' . $attachment['id_attach']),
1524
					'length' => $attachment['filesize'],
1525
					'type' => $attachment['mime_type'],
1526
				);
1527
			}
1528
			else
1529
				$enclosure = null;
1530
1531
			$data[] = array(
1532
				'tag' => 'entry',
1533
				'content' => array(
1534
					array(
1535
						'tag' => 'title',
1536
						'content' => $row['subject'],
1537
						'cdata' => true,
1538
					),
1539
					array(
1540
						'tag' => 'link',
1541
						'attributes' => array(
1542
							'rel' => 'alternate',
1543
							'type' => 'text/html',
1544
							'href' => $scripturl . '?topic=' . $row['id_topic'] . '.msg' . $row['id_msg'] . '#msg' . $row['id_msg'],
1545
						),
1546
					),
1547
					array(
1548
						'tag' => 'summary',
1549
						'attributes' => array('type' => 'html'),
1550
						'content' => $row['body'],
1551
						'cdata' => true,
1552
					),
1553
					array(
1554
						'tag' => 'category',
1555
						'attributes' => array('term' => $row['bname']),
1556
						'cdata' => true,
1557
					),
1558
					array(
1559
						'tag' => 'author',
1560
						'content' => array(
1561
							array(
1562
								'tag' => 'name',
1563
								'content' => $row['poster_name'],
1564
								'cdata' => true,
1565
							),
1566
							array(
1567
								'tag' => 'email',
1568
								'content' => (allowedTo('moderate_forum') || (!empty($row['id_member']) && $row['id_member'] == $user_info['id'])) ? $row['poster_email'] : null,
1569
								'cdata' => true,
1570
							),
1571
							array(
1572
								'tag' => 'uri',
1573
								'content' => !empty($row['id_member']) ? $scripturl . '?action=profile;u=' . $row['id_member'] : null,
1574
							),
1575
						),
1576
					),
1577
					array(
1578
						'tag' => 'published',
1579
						'content' => smf_gmstrftime('%Y-%m-%dT%H:%M:%SZ', $row['poster_time']),
1580
					),
1581
					array(
1582
						'tag' => 'updated',
1583
						'content' => smf_gmstrftime('%Y-%m-%dT%H:%M:%SZ', empty($row['modified_time']) ? $row['poster_time'] : $row['modified_time']),
1584
					),
1585
					array(
1586
						'tag' => 'id',
1587
						'content' => $guid,
1588
					),
1589
					array(
1590
						'tag' => 'link',
1591
						'attributes' => $enclosure,
1592
					),
1593
				),
1594
			);
1595
		}
1596
		// A lot of information here.  Should be enough to please the rss-ers.
1597
		else
1598
		{
1599
			loadLanguage('Post');
1600
1601
			$attachments = array();
1602
			if (!empty($loaded_attachments))
1603
			{
1604
				foreach ($loaded_attachments as $attachment)
1605
				{
1606
					$attachments[] = array(
1607
						'tag' => 'attachment',
1608
						'attributes' => array('label' => $txt['attachment']),
1609
						'content' => array(
1610
							array(
1611
								'tag' => 'id',
1612
								'content' => $attachment['id_attach'],
1613
							),
1614
							array(
1615
								'tag' => 'name',
1616
								'attributes' => array('label' => $txt['name']),
1617
								'content' => preg_replace('~&amp;#(\\d{1,7}|x[0-9a-fA-F]{1,6});~', '&#\\1;', $smcFunc['htmlspecialchars']($attachment['filename'])),
1618
							),
1619
							array(
1620
								'tag' => 'downloads',
1621
								'attributes' => array('label' => $txt['downloads']),
1622
								'content' => $attachment['downloads'],
1623
							),
1624
							array(
1625
								'tag' => 'size',
1626
								'attributes' => array('label' => $txt['filesize']),
1627
								'content' => ($attachment['filesize'] < 1024000) ? round($attachment['filesize'] / 1024, 2) . ' ' . $txt['kilobyte'] : round($attachment['filesize'] / 1024 / 1024, 2) . ' ' . $txt['megabyte'],
1628
							),
1629
							array(
1630
								'tag' => 'byte_size',
1631
								'attributes' => array('label' => $txt['filesize']),
1632
								'content' => $attachment['filesize'],
1633
							),
1634
							array(
1635
								'tag' => 'link',
1636
								'attributes' => array('label' => $txt['url']),
1637
								'content' => $scripturl . '?action=dlattach;topic=' . $attachment['topic'] . '.0;attach=' . $attachment['id_attach'],
1638
							),
1639
						)
1640
					);
1641
				}
1642
			}
1643
			else
1644
				$attachments = null;
1645
1646
			$data[] = array(
1647
				'tag' => 'recent-post', // Hyphen rather than underscore for backward compatibility reasons
1648
				'attributes' => array('label' => $txt['post']),
1649
				'content' => array(
1650
					array(
1651
						'tag' => 'time',
1652
						'attributes' => array('label' => $txt['date'], 'UTC' => smf_gmstrftime('%F %T', $row['poster_time'])),
1653
						'content' => $smcFunc['htmlspecialchars'](strip_tags(timeformat($row['poster_time'], false, 'forum'))),
1654
					),
1655
					array(
1656
						'tag' => 'id',
1657
						'content' => $row['id_msg'],
1658
					),
1659
					array(
1660
						'tag' => 'subject',
1661
						'attributes' => array('label' => $txt['subject']),
1662
						'content' => $row['subject'],
1663
						'cdata' => true,
1664
					),
1665
					array(
1666
						'tag' => 'body',
1667
						'attributes' => array('label' => $txt['message']),
1668
						'content' => $row['body'],
1669
						'cdata' => true,
1670
					),
1671
					array(
1672
						'tag' => 'starter',
1673
						'attributes' => array('label' => $txt['topic_started']),
1674
						'content' => array(
1675
							array(
1676
								'tag' => 'name',
1677
								'attributes' => array('label' => $txt['name']),
1678
								'content' => $row['first_poster_name'],
1679
								'cdata' => true,
1680
							),
1681
							array(
1682
								'tag' => 'id',
1683
								'content' => $row['id_first_member'],
1684
							),
1685
							array(
1686
								'tag' => 'link',
1687
								'attributes' => !empty($row['id_first_member']) ? array('label' => $txt['url']) : null,
1688
								'content' => !empty($row['id_first_member']) ? $scripturl . '?action=profile;u=' . $row['id_first_member'] : '',
1689
							),
1690
						),
1691
					),
1692
					array(
1693
						'tag' => 'poster',
1694
						'attributes' => array('label' => $txt['author']),
1695
						'content' => array(
1696
							array(
1697
								'tag' => 'name',
1698
								'attributes' => array('label' => $txt['name']),
1699
								'content' => $row['poster_name'],
1700
								'cdata' => true,
1701
							),
1702
							array(
1703
								'tag' => 'id',
1704
								'content' => $row['id_member'],
1705
							),
1706
							array(
1707
								'tag' => 'link',
1708
								'attributes' => !empty($row['id_member']) ? array('label' => $txt['url']) : null,
1709
								'content' => !empty($row['id_member']) ? $scripturl . '?action=profile;u=' . $row['id_member'] : '',
1710
							),
1711
						),
1712
					),
1713
					array(
1714
						'tag' => 'topic',
1715
						'attributes' => array('label' => $txt['topic']),
1716
						'content' => array(
1717
							array(
1718
								'tag' => 'subject',
1719
								'attributes' => array('label' => $txt['subject']),
1720
								'content' => $row['first_subject'],
1721
								'cdata' => true,
1722
							),
1723
							array(
1724
								'tag' => 'id',
1725
								'content' => $row['id_topic'],
1726
							),
1727
							array(
1728
								'tag' => 'link',
1729
								'attributes' => array('label' => $txt['url']),
1730
								'content' => $scripturl . '?topic=' . $row['id_topic'] . '.new#new',
1731
							),
1732
						),
1733
					),
1734
					array(
1735
						'tag' => 'board',
1736
						'attributes' => array('label' => $txt['board']),
1737
						'content' => array(
1738
							array(
1739
								'tag' => 'name',
1740
								'attributes' => array('label' => $txt['name']),
1741
								'content' => $row['bname'],
1742
								'cdata' => true,
1743
							),
1744
							array(
1745
								'tag' => 'id',
1746
								'content' => $row['id_board'],
1747
							),
1748
							array(
1749
								'tag' => 'link',
1750
								'attributes' => array('label' => $txt['url']),
1751
								'content' => $scripturl . '?board=' . $row['id_board'] . '.0',
1752
							),
1753
						),
1754
					),
1755
					array(
1756
						'tag' => 'link',
1757
						'attributes' => array('label' => $txt['url']),
1758
						'content' => $scripturl . '?topic=' . $row['id_topic'] . '.msg' . $row['id_msg'] . '#msg' . $row['id_msg'],
1759
					),
1760
					array(
1761
						'tag' => 'attachments',
1762
						'attributes' => array('label' => $txt['attachments']),
1763
						'content' => $attachments,
1764
					),
1765
				),
1766
			);
1767
		}
1768
	}
1769
	$smcFunc['db_free_result']($request);
1770
1771
	return $data;
1772
}
1773
1774
/**
1775
 * Get the profile information for member into an array,
1776
 * which will be generated to match the xml_format.
1777
 *
1778
 * @param string $xml_format The XML format. Can be 'atom', 'rdf', 'rss', 'rss2' or 'smf'
1779
 * @return array An array profile data
1780
 */
1781
function getXmlProfile($xml_format)
1782
{
1783
	global $scripturl, $memberContext, $user_info, $txt, $context;
1784
1785
	// You must input a valid user, and you must be allowed to view that user's profile.
1786
	if (empty($context['xmlnews_uid']) || ($context['xmlnews_uid'] != $user_info['id'] && !allowedTo('profile_view')) || !loadMemberData($context['xmlnews_uid']))
1787
		return array();
1788
1789
	// Load the member's contextual information! (Including custom fields for our proprietary XML type)
1790
	if (!loadMemberContext($context['xmlnews_uid'], ($xml_format == 'smf')))
1791
		return array();
1792
1793
	$profile = &$memberContext[$context['xmlnews_uid']];
1794
1795
	// If any control characters slipped in somehow, kill the evil things
1796
	$profile = filter_var($profile, FILTER_CALLBACK, array('options' => 'cleanXml'));
1797
1798
	// Create a GUID for this member using the tag URI scheme
1799
	$guid = 'tag:' . parse_iri($scripturl, PHP_URL_HOST) . ',' . gmdate('Y-m-d', $profile['registered_timestamp']) . ':member=' . $profile['id'];
1800
1801
	if ($xml_format == 'rss' || $xml_format == 'rss2')
1802
	{
1803
		$data[] = array(
0 ignored issues
show
Comprehensibility Best Practice introduced by
$data was never initialized. Although not strictly required by PHP, it is generally a good practice to add $data = array(); before regardless.
Loading history...
1804
			'tag' => 'item',
1805
			'content' => array(
1806
				array(
1807
					'tag' => 'title',
1808
					'content' => $profile['name'],
1809
					'cdata' => true,
1810
				),
1811
				array(
1812
					'tag' => 'link',
1813
					'content' => $scripturl . '?action=profile;u=' . $profile['id'],
1814
				),
1815
				array(
1816
					'tag' => 'description',
1817
					'content' => isset($profile['group']) ? $profile['group'] : $profile['post_group'],
1818
					'cdata' => true,
1819
				),
1820
				array(
1821
					'tag' => 'comments',
1822
					'content' => $scripturl . '?action=pm;sa=send;u=' . $profile['id'],
1823
				),
1824
				array(
1825
					'tag' => 'pubDate',
1826
					'content' => gmdate('D, d M Y H:i:s \G\M\T', $profile['registered_timestamp']),
1827
				),
1828
				array(
1829
					'tag' => 'guid',
1830
					'content' => $guid,
1831
					'attributes' => array(
1832
						'isPermaLink' => 'false',
1833
					),
1834
				),
1835
			)
1836
		);
1837
	}
1838
	elseif ($xml_format == 'rdf')
1839
	{
1840
		$data[] = array(
1841
			'tag' => 'item',
1842
			'attributes' => array('rdf:about' => $scripturl . '?action=profile;u=' . $profile['id']),
1843
			'content' => array(
1844
				array(
1845
					'tag' => 'dc:format',
1846
					'content' => 'text/html',
1847
				),
1848
				array(
1849
					'tag' => 'title',
1850
					'content' => $profile['name'],
1851
					'cdata' => true,
1852
				),
1853
				array(
1854
					'tag' => 'link',
1855
					'content' => $scripturl . '?action=profile;u=' . $profile['id'],
1856
				),
1857
				array(
1858
					'tag' => 'description',
1859
					'content' => isset($profile['group']) ? $profile['group'] : $profile['post_group'],
1860
					'cdata' => true,
1861
				),
1862
			)
1863
		);
1864
	}
1865
	elseif ($xml_format == 'atom')
1866
	{
1867
		$data[] = array(
1868
			'tag' => 'entry',
1869
			'content' => array(
1870
				array(
1871
					'tag' => 'title',
1872
					'content' => $profile['name'],
1873
					'cdata' => true,
1874
				),
1875
				array(
1876
					'tag' => 'link',
1877
					'attributes' => array(
1878
						'rel' => 'alternate',
1879
						'type' => 'text/html',
1880
						'href' => $scripturl . '?action=profile;u=' . $profile['id'],
1881
					),
1882
				),
1883
				array(
1884
					'tag' => 'summary',
1885
					'attributes' => array('type' => 'html'),
1886
					'content' => isset($profile['group']) ? $profile['group'] : $profile['post_group'],
1887
					'cdata' => true,
1888
				),
1889
				array(
1890
					'tag' => 'author',
1891
					'content' => array(
1892
						array(
1893
							'tag' => 'name',
1894
							'content' => $profile['name'],
1895
							'cdata' => true,
1896
						),
1897
						array(
1898
							'tag' => 'email',
1899
							'content' => $profile['show_email'] ? $profile['email'] : null,
1900
							'cdata' => true,
1901
						),
1902
						array(
1903
							'tag' => 'uri',
1904
							'content' => !empty($profile['website']['url']) ? $profile['website']['url'] : $scripturl . '?action=profile;u=' . $profile['id_member'],
1905
							'cdata' => !empty($profile['website']['url']),
1906
						),
1907
					),
1908
				),
1909
				array(
1910
					'tag' => 'published',
1911
					'content' => smf_gmstrftime('%Y-%m-%dT%H:%M:%SZ', $profile['registered_timestamp']),
1912
				),
1913
				array(
1914
					'tag' => 'updated',
1915
					'content' => smf_gmstrftime('%Y-%m-%dT%H:%M:%SZ', $profile['last_login_timestamp']),
1916
				),
1917
				array(
1918
					'tag' => 'id',
1919
					'content' => $guid,
1920
				),
1921
			)
1922
		);
1923
	}
1924
	else
1925
	{
1926
		loadLanguage('Profile');
1927
1928
		$data = array(
1929
			array(
1930
				'tag' => 'username',
1931
				'attributes' => $user_info['is_admin'] || $user_info['id'] == $profile['id'] ? array('label' => $txt['username']) : null,
1932
				'content' => $user_info['is_admin'] || $user_info['id'] == $profile['id'] ? $profile['username'] : null,
1933
				'cdata' => true,
1934
			),
1935
			array(
1936
				'tag' => 'name',
1937
				'attributes' => array('label' => $txt['name']),
1938
				'content' => $profile['name'],
1939
				'cdata' => true,
1940
			),
1941
			array(
1942
				'tag' => 'link',
1943
				'attributes' => array('label' => $txt['url']),
1944
				'content' => $scripturl . '?action=profile;u=' . $profile['id'],
1945
			),
1946
			array(
1947
				'tag' => 'posts',
1948
				'attributes' => array('label' => $txt['member_postcount']),
1949
				'content' => $profile['posts'],
1950
			),
1951
			array(
1952
				'tag' => 'post-group',
1953
				'attributes' => array('label' => $txt['post_based_membergroup']),
1954
				'content' => $profile['post_group'],
1955
				'cdata' => true,
1956
			),
1957
			array(
1958
				'tag' => 'language',
1959
				'attributes' => array('label' => $txt['preferred_language']),
1960
				'content' => $profile['language'],
1961
				'cdata' => true,
1962
			),
1963
			array(
1964
				'tag' => 'last-login',
1965
				'attributes' => array('label' => $txt['lastLoggedIn'], 'UTC' => smf_gmstrftime('%F %T', $profile['last_login_timestamp'])),
1966
				'content' => timeformat($profile['last_login_timestamp'], false, 'forum'),
1967
			),
1968
			array(
1969
				'tag' => 'registered',
1970
				'attributes' => array('label' => $txt['date_registered'], 'UTC' => smf_gmstrftime('%F %T', $profile['registered_timestamp'])),
1971
				'content' => timeformat($profile['registered_timestamp'], false, 'forum'),
1972
			),
1973
			array(
1974
				'tag' => 'avatar',
1975
				'attributes' => !empty($profile['avatar']['url']) ? array('label' => $txt['personal_picture']) : null,
1976
				'content' => !empty($profile['avatar']['url']) ? $profile['avatar']['url'] : null,
1977
				'cdata' => true,
1978
			),
1979
			array(
1980
				'tag' => 'signature',
1981
				'attributes' => !empty($profile['signature']) ? array('label' => $txt['signature']) : null,
1982
				'content' => !empty($profile['signature']) ? $profile['signature'] : null,
1983
				'cdata' => true,
1984
			),
1985
			array(
1986
				'tag' => 'blurb',
1987
				'attributes' => !empty($profile['blurb']) ? array('label' => $txt['personal_text']) : null,
1988
				'content' => !empty($profile['blurb']) ? $profile['blurb'] : null,
1989
				'cdata' => true,
1990
			),
1991
			array(
1992
				'tag' => 'title',
1993
				'attributes' => !empty($profile['title']) ? array('label' => $txt['title']) : null,
1994
				'content' => !empty($profile['title']) ? $profile['title'] : null,
1995
				'cdata' => true,
1996
			),
1997
			array(
1998
				'tag' => 'position',
1999
				'attributes' => !empty($profile['group']) ? array('label' => $txt['position']) : null,
2000
				'content' => !empty($profile['group']) ? $profile['group'] : null,
2001
				'cdata' => true,
2002
			),
2003
			array(
2004
				'tag' => 'email',
2005
				'attributes' => !empty($profile['show_email']) || $user_info['is_admin'] || $user_info['id'] == $profile['id'] ? array('label' => $txt['user_email_address']) : null,
2006
				'content' => !empty($profile['show_email']) || $user_info['is_admin'] || $user_info['id'] == $profile['id'] ? $profile['email'] : null,
2007
				'cdata' => true,
2008
			),
2009
			array(
2010
				'tag' => 'website',
2011
				'attributes' => empty($profile['website']['url']) ? null : array('label' => $txt['website']),
2012
				'content' => empty($profile['website']['url']) ? null : array(
2013
					array(
2014
						'tag' => 'title',
2015
						'attributes' => !empty($profile['website']['title']) ? array('label' => $txt['website_title']) : null,
2016
						'content' => !empty($profile['website']['title']) ? $profile['website']['title'] : null,
2017
						'cdata' => true,
2018
					),
2019
					array(
2020
						'tag' => 'link',
2021
						'attributes' => array('label' => $txt['website_url']),
2022
						'content' => $profile['website']['url'],
2023
						'cdata' => true,
2024
					),
2025
				),
2026
			),
2027
			array(
2028
				'tag' => 'online',
2029
				'attributes' => !empty($profile['online']['is_online']) ? array('label' => $txt['online']) : null,
2030
				'content' => !empty($profile['online']['is_online']) ? 'true' : null,
2031
			),
2032
			array(
2033
				'tag' => 'ip_addresses',
2034
				'attributes' => array('label' => $txt['ip_address']),
2035
				'content' => allowedTo('moderate_forum') || $user_info['id'] == $profile['id'] ? array(
2036
					array(
2037
						'tag' => 'ip',
2038
						'attributes' => array('label' => $txt['most_recent_ip']),
2039
						'content' => $profile['ip'],
2040
					),
2041
					array(
2042
						'tag' => 'ip2',
2043
						'content' => $profile['ip'] != $profile['ip2'] ? $profile['ip2'] : null,
2044
					),
2045
				) : null,
2046
			),
2047
		);
2048
2049
		if (!empty($profile['birth_date']) && substr($profile['birth_date'], 0, 4) != '0000' && substr($profile['birth_date'], 0, 4) != '1004')
2050
		{
2051
			list ($birth_year, $birth_month, $birth_day) = sscanf($profile['birth_date'], '%d-%d-%d');
2052
			$datearray = getdate(time());
2053
			$age = $datearray['year'] - $birth_year - (($datearray['mon'] > $birth_month || ($datearray['mon'] == $birth_month && $datearray['mday'] >= $birth_day)) ? 0 : 1);
2054
2055
			$data[] = array(
2056
				'tag' => 'age',
2057
				'attributes' => array('label' => $txt['age']),
2058
				'content' => $age,
2059
			);
2060
			$data[] = array(
2061
				'tag' => 'birthdate',
2062
				'attributes' => array('label' => $txt['dob']),
2063
				'content' => $profile['birth_date'],
2064
			);
2065
		}
2066
2067
		if (!empty($profile['custom_fields']))
2068
		{
2069
			foreach ($profile['custom_fields'] as $custom_field)
2070
			{
2071
				$data[] = array(
2072
					'tag' => $custom_field['col_name'],
2073
					'attributes' => array('label' => $custom_field['title']),
2074
					'content' => $custom_field['simple'],
2075
					'cdata' => true,
2076
				);
2077
			}
2078
		}
2079
	}
2080
2081
	// Save some memory.
2082
	unset($profile, $memberContext[$context['xmlnews_uid']]);
2083
2084
	return $data;
2085
}
2086
2087
/**
2088
 * Get a user's posts.
2089
 * The returned array will be generated to match the xml_format.
2090
 *
2091
 * @param string $xml_format The XML format. Can be 'atom', 'rdf', 'rss', 'rss2' or 'smf'
2092
 * @param bool $ascending If true, get the oldest posts first. Default false.
2093
 * @return array An array of arrays containing data for the feed. Each array has keys corresponding to the appropriate tags for the specified format.
2094
 */
2095
function getXmlPosts($xml_format, $ascending = false)
2096
{
2097
	global $scripturl, $modSettings, $board, $txt, $context, $user_info;
2098
	global $query_this_board, $smcFunc, $sourcedir, $cachedir;
2099
2100
	if (empty($context['xmlnews_uid']) || ($context['xmlnews_uid'] != $user_info['id'] && !allowedTo('profile_view')))
2101
		return array();
2102
2103
	$show_all = !empty($user_info['is_admin']) || defined('EXPORTING');
2104
2105
	$query_this_message_board = str_replace(array('{query_see_board}', 'b.'), array('{query_see_message_board}', 'm.'), $query_this_board);
2106
2107
	require_once($sourcedir . '/Subs-Attachments.php');
2108
2109
	/* MySQL can choke if we use joins in the main query when the user has
2110
	 * massively long posts. To avoid that, we get the names of the boards
2111
	 * and the user's displayed name in separate queries.
2112
	 */
2113
	$boardnames = array();
2114
	$request = $smcFunc['db_query']('', '
2115
		SELECT id_board, name
2116
		FROM {db_prefix}boards',
2117
		array()
2118
	);
2119
	while ($row = $smcFunc['db_fetch_assoc']($request))
2120
		$boardnames[$row['id_board']] = $row['name'];
2121
	$smcFunc['db_free_result']($request);
2122
2123
	if ($context['xmlnews_uid'] == $user_info['id'])
2124
		$poster_name = $user_info['name'];
2125
	else
2126
	{
2127
		$request = $smcFunc['db_query']('', '
2128
			SELECT COALESCE(real_name, member_name) AS poster_name
2129
			FROM {db_prefix}members
2130
			WHERE id_member = {int:uid}',
2131
			array(
2132
				'uid' => $context['xmlnews_uid'],
2133
			)
2134
		);
2135
		list($poster_name) = $smcFunc['db_fetch_row']($request);
2136
		$smcFunc['db_free_result']($request);
2137
	}
2138
2139
	$request = $smcFunc['db_query']('', '
2140
		SELECT
2141
			m.id_msg, m.id_topic, m.id_board, m.id_member, m.poster_email, m.poster_ip,
2142
			m.poster_time, m.subject, m.modified_time, m.modified_name, m.modified_reason, m.body,
2143
			m.likes, m.approved, m.smileys_enabled
2144
		FROM {db_prefix}messages AS m' . ($modSettings['postmod_active'] && !$show_all ?'
2145
			INNER JOIN {db_prefix}topics AS t ON (t.id_topic = m.id_topic)' : '') . '
2146
		WHERE m.id_member = {int:uid}
2147
			AND m.id_msg > {int:start_after}
2148
			AND ' . $query_this_message_board . ($modSettings['postmod_active'] && !$show_all ? '
2149
			AND m.approved = {int:is_approved}
2150
			AND t.approved = {int:is_approved}' : '') . '
2151
		ORDER BY m.id_msg {raw:ascdesc}
2152
		LIMIT {int:limit}',
2153
		array(
2154
			'limit' => $context['xmlnews_limit'],
2155
			'start_after' => !empty($context['posts_start']) ? $context['posts_start'] : 0,
2156
			'uid' => $context['xmlnews_uid'],
2157
			'is_approved' => 1,
2158
			'ascdesc' => !empty($ascending) ? 'ASC' : 'DESC',
2159
		)
2160
	);
2161
	$data = array();
2162
	while ($row = $smcFunc['db_fetch_assoc']($request))
2163
	{
2164
		$context['last'] = $row['id_msg'];
2165
2166
		// We want a readable version of the IP address
2167
		$row['poster_ip'] = inet_dtop($row['poster_ip']);
2168
2169
		// If any control characters slipped in somehow, kill the evil things
2170
		$row = filter_var($row, FILTER_CALLBACK, array('options' => 'cleanXml'));
2171
2172
		// If using our own format, we want both the raw and the parsed content.
2173
		$row[$xml_format === 'smf' ? 'body_html' : 'body'] = parse_bbc($row['body'], $row['smileys_enabled'], $row['id_msg']);
2174
2175
		// Do we want to include any attachments?
2176
		if (!empty($modSettings['attachmentEnable']) && !empty($modSettings['xmlnews_attachments']))
2177
		{
2178
			$attach_request = $smcFunc['db_query']('', '
2179
				SELECT
2180
					a.id_attach, a.filename, COALESCE(a.size, 0) AS filesize, a.mime_type, a.downloads, a.approved, m.id_topic AS topic
2181
				FROM {db_prefix}attachments AS a
2182
					LEFT JOIN {db_prefix}messages AS m ON (m.id_msg = a.id_msg)
2183
				WHERE a.attachment_type = {int:attachment_type}
2184
					AND a.id_msg = {int:message_id}',
2185
				array(
2186
					'message_id' => $row['id_msg'],
2187
					'attachment_type' => 0,
2188
					'is_approved' => 1,
2189
				)
2190
			);
2191
			$loaded_attachments = array();
2192
			while ($attach = $smcFunc['db_fetch_assoc']($attach_request))
2193
			{
2194
				// Include approved attachments only, unless showing all.
2195
				if ($attach['approved'] || $show_all)
2196
					$loaded_attachments['attachment_' . $attach['id_attach']] = $attach;
2197
			}
2198
			$smcFunc['db_free_result']($attach_request);
2199
2200
			// Sort the attachments by size to make things easier below
2201
			if (!empty($loaded_attachments))
2202
			{
2203
				uasort(
2204
					$loaded_attachments,
2205
					function($a, $b)
2206
					{
2207
						if ($a['filesize'] == $b['filesize'])
2208
					        return 0;
2209
2210
						return ($a['filesize'] < $b['filesize']) ? -1 : 1;
2211
					}
2212
				);
2213
			}
2214
			else
2215
				$loaded_attachments = null;
2216
		}
2217
		else
2218
			$loaded_attachments = null;
2219
2220
		// Create a GUID for this post using the tag URI scheme
2221
		$guid = 'tag:' . parse_iri($scripturl, PHP_URL_HOST) . ',' . gmdate('Y-m-d', $row['poster_time']) . ':msg=' . $row['id_msg'];
2222
2223
		if ($xml_format == 'rss' || $xml_format == 'rss2')
2224
		{
2225
			// Only one attachment allowed in RSS.
2226
			if ($loaded_attachments !== null)
2227
			{
2228
				$attachment = array_pop($loaded_attachments);
0 ignored issues
show
$loaded_attachments of type null is incompatible with the type array expected by parameter $array of array_pop(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

2228
				$attachment = array_pop(/** @scrutinizer ignore-type */ $loaded_attachments);
Loading history...
2229
				$enclosure = array(
2230
					'url' => fix_possible_url($scripturl . '?action=dlattach;topic=' . $attachment['topic'] . '.0;attach=' . $attachment['id_attach']),
2231
					'length' => $attachment['filesize'],
2232
					'type' => $attachment['mime_type'],
2233
				);
2234
			}
2235
			else
2236
				$enclosure = null;
2237
2238
			$data[] = array(
2239
				'tag' => 'item',
2240
				'content' => array(
2241
					array(
2242
						'tag' => 'title',
2243
						'content' => $row['subject'],
2244
						'cdata' => true,
2245
					),
2246
					array(
2247
						'tag' => 'link',
2248
						'content' => $scripturl . '?msg=' . $row['id_msg'],
2249
					),
2250
					array(
2251
						'tag' => 'description',
2252
						'content' => $row['body'],
2253
						'cdata' => true,
2254
					),
2255
					array(
2256
						'tag' => 'author',
2257
						'content' => (allowedTo('moderate_forum') || ($row['id_member'] == $user_info['id'])) ? $row['poster_email'] : null,
2258
						'cdata' => true,
2259
					),
2260
					array(
2261
						'tag' => 'category',
2262
						'content' => $boardnames[$row['id_board']],
2263
						'cdata' => true,
2264
					),
2265
					array(
2266
						'tag' => 'comments',
2267
						'content' => $scripturl . '?action=post;topic=' . $row['id_topic'] . '.0',
2268
					),
2269
					array(
2270
						'tag' => 'pubDate',
2271
						'content' => gmdate('D, d M Y H:i:s \G\M\T', $row['poster_time']),
2272
					),
2273
					array(
2274
						'tag' => 'guid',
2275
						'content' => $guid,
2276
						'attributes' => array(
2277
							'isPermaLink' => 'false',
2278
						),
2279
					),
2280
					array(
2281
						'tag' => 'enclosure',
2282
						'attributes' => $enclosure,
2283
					),
2284
				),
2285
			);
2286
		}
2287
		elseif ($xml_format == 'rdf')
2288
		{
2289
			$data[] = array(
2290
				'tag' => 'item',
2291
				'attributes' => array('rdf:about' => $scripturl . '?topic=' . $row['id_topic'] . '.msg' . $row['id_msg'] . '#msg' . $row['id_msg']),
2292
				'content' => array(
2293
					array(
2294
						'tag' => 'dc:format',
2295
						'content' => 'text/html',
2296
					),
2297
					array(
2298
						'tag' => 'title',
2299
						'content' => $row['subject'],
2300
						'cdata' => true,
2301
					),
2302
					array(
2303
						'tag' => 'link',
2304
						'content' => $scripturl . '?msg=' . $row['id_msg'],
2305
					),
2306
					array(
2307
						'tag' => 'description',
2308
						'content' => $row['body'],
2309
						'cdata' => true,
2310
					),
2311
				),
2312
			);
2313
		}
2314
		elseif ($xml_format == 'atom')
2315
		{
2316
			// Only one attachment allowed
2317
			if (!empty($loaded_attachments))
2318
			{
2319
				$attachment = array_pop($loaded_attachments);
2320
				$enclosure = array(
2321
					'rel' => 'enclosure',
2322
					'href' => fix_possible_url($scripturl . '?action=dlattach;topic=' . $attachment['topic'] . '.0;attach=' . $attachment['id_attach']),
2323
					'length' => $attachment['filesize'],
2324
					'type' => $attachment['mime_type'],
2325
				);
2326
			}
2327
			else
2328
				$enclosure = null;
2329
2330
			$data[] = array(
2331
				'tag' => 'entry',
2332
				'content' => array(
2333
					array(
2334
						'tag' => 'title',
2335
						'content' => $row['subject'],
2336
						'cdata' => true,
2337
					),
2338
					array(
2339
						'tag' => 'link',
2340
						'attributes' => array(
2341
							'rel' => 'alternate',
2342
							'type' => 'text/html',
2343
							'href' => $scripturl . '?msg=' . $row['id_msg'],
2344
						),
2345
					),
2346
					array(
2347
						'tag' => 'summary',
2348
						'attributes' => array('type' => 'html'),
2349
						'content' => $row['body'],
2350
						'cdata' => true,
2351
					),
2352
					array(
2353
						'tag' => 'author',
2354
						'content' => array(
2355
							array(
2356
								'tag' => 'name',
2357
								'content' => $poster_name,
2358
								'cdata' => true,
2359
							),
2360
							array(
2361
								'tag' => 'email',
2362
								'content' => (allowedTo('moderate_forum') || ($row['id_member'] == $user_info['id'])) ? $row['poster_email'] : null,
2363
								'cdata' => true,
2364
							),
2365
							array(
2366
								'tag' => 'uri',
2367
								'content' => !empty($row['id_member']) ? $scripturl . '?action=profile;u=' . $row['id_member'] : null,
2368
							),
2369
						),
2370
					),
2371
					array(
2372
						'tag' => 'published',
2373
						'content' => smf_gmstrftime('%Y-%m-%dT%H:%M:%SZ', $row['poster_time']),
2374
					),
2375
					array(
2376
						'tag' => 'updated',
2377
						'content' => smf_gmstrftime('%Y-%m-%dT%H:%M:%SZ', empty($row['modified_time']) ? $row['poster_time'] : $row['modified_time']),
2378
					),
2379
					array(
2380
						'tag' => 'id',
2381
						'content' => $guid,
2382
					),
2383
					array(
2384
						'tag' => 'link',
2385
						'attributes' => $enclosure,
2386
					),
2387
				),
2388
			);
2389
		}
2390
		// A lot of information here.  Should be enough to please the rss-ers.
2391
		else
2392
		{
2393
			loadLanguage('Post');
2394
2395
			$attachments = array();
2396
			if (!empty($loaded_attachments))
2397
			{
2398
				foreach ($loaded_attachments as $attachment)
2399
				{
2400
					$attachments[] = array(
2401
						'tag' => 'attachment',
2402
						'attributes' => array('label' => $txt['attachment']),
2403
						'content' => array(
2404
							array(
2405
								'tag' => 'id',
2406
								'content' => $attachment['id_attach'],
2407
							),
2408
							array(
2409
								'tag' => 'name',
2410
								'attributes' => array('label' => $txt['name']),
2411
								'content' => preg_replace('~&amp;#(\\d{1,7}|x[0-9a-fA-F]{1,6});~', '&#\\1;', $smcFunc['htmlspecialchars']($attachment['filename'])),
2412
							),
2413
							array(
2414
								'tag' => 'downloads',
2415
								'attributes' => array('label' => $txt['downloads']),
2416
								'content' => $attachment['downloads'],
2417
							),
2418
							array(
2419
								'tag' => 'size',
2420
								'attributes' => array('label' => $txt['filesize']),
2421
								'content' => ($attachment['filesize'] < 1024000) ? round($attachment['filesize'] / 1024, 2) . ' ' . $txt['kilobyte'] : round($attachment['filesize'] / 1024 / 1024, 2) . ' ' . $txt['megabyte'],
2422
							),
2423
							array(
2424
								'tag' => 'byte_size',
2425
								'attributes' => array('label' => $txt['filesize']),
2426
								'content' => $attachment['filesize'],
2427
							),
2428
							array(
2429
								'tag' => 'link',
2430
								'attributes' => array('label' => $txt['url']),
2431
								'content' => $scripturl . '?action=dlattach;topic=' . $attachment['topic'] . '.0;attach=' . $attachment['id_attach'],
2432
							),
2433
							array(
2434
								'tag' => 'approval_status',
2435
								'attributes' => $show_all ? array('label' => $txt['approval_status']) : null,
2436
								'content' => $show_all ? $attachment['approved'] : null,
2437
							),
2438
						)
2439
					);
2440
				}
2441
			}
2442
			else
2443
				$attachments = null;
2444
2445
			$data[] = array(
2446
				'tag' => 'member_post',
2447
				'attributes' => array('label' => $txt['post']),
2448
				'content' => array(
2449
					array(
2450
						'tag' => 'id',
2451
						'content' => $row['id_msg'],
2452
					),
2453
					array(
2454
						'tag' => 'subject',
2455
						'attributes' => array('label' => $txt['subject']),
2456
						'content' => $row['subject'],
2457
						'cdata' => true,
2458
					),
2459
					array(
2460
						'tag' => 'body',
2461
						'attributes' => array('label' => $txt['message']),
2462
						'content' => $row['body'],
2463
						'cdata' => true,
2464
					),
2465
					array(
2466
						'tag' => 'body_html',
2467
						'attributes' => array('label' => $txt['html']),
2468
						'content' => $row['body_html'],
2469
						'cdata' => true,
2470
					),
2471
					array(
2472
						'tag' => 'poster',
2473
						'attributes' => array('label' => $txt['author']),
2474
						'content' => array(
2475
							array(
2476
								'tag' => 'name',
2477
								'attributes' => array('label' => $txt['name']),
2478
								'content' => $poster_name,
2479
								'cdata' => true,
2480
							),
2481
							array(
2482
								'tag' => 'id',
2483
								'content' => $row['id_member'],
2484
							),
2485
							array(
2486
								'tag' => 'link',
2487
								'attributes' => array('label' => $txt['url']),
2488
								'content' => $scripturl . '?action=profile;u=' . $row['id_member'],
2489
							),
2490
							array(
2491
								'tag' => 'email',
2492
								'attributes' => (allowedTo('moderate_forum') || $row['id_member'] == $user_info['id']) ? array('label' => $txt['user_email_address']) : null,
2493
								'content' => (allowedTo('moderate_forum') || $row['id_member'] == $user_info['id']) ? $row['poster_email'] : null,
2494
								'cdata' => true,
2495
							),
2496
							array(
2497
								'tag' => 'ip',
2498
								'attributes' => (allowedTo('moderate_forum') || $row['id_member'] == $user_info['id']) ? array('label' => $txt['ip']) : null,
2499
								'content' => (allowedTo('moderate_forum') || $row['id_member'] == $user_info['id']) ? $row['poster_ip'] : null,
2500
							),
2501
						),
2502
					),
2503
					array(
2504
						'tag' => 'topic',
2505
						'attributes' => array('label' => $txt['topic']),
2506
						'content' => array(
2507
							array(
2508
								'tag' => 'id',
2509
								'content' => $row['id_topic'],
2510
							),
2511
							array(
2512
								'tag' => 'link',
2513
								'attributes' => array('label' => $txt['url']),
2514
								'content' => $scripturl . '?topic=' . $row['id_topic'] . '.0',
2515
							),
2516
						),
2517
					),
2518
					array(
2519
						'tag' => 'board',
2520
						'attributes' => array('label' => $txt['board']),
2521
						'content' => array(
2522
							array(
2523
								'tag' => 'id',
2524
								'content' => $row['id_board'],
2525
							),
2526
							array(
2527
								'tag' => 'name',
2528
								'content' => $boardnames[$row['id_board']],
2529
								'cdata' => true,
2530
							),
2531
							array(
2532
								'tag' => 'link',
2533
								'attributes' => array('label' => $txt['url']),
2534
								'content' => $scripturl . '?board=' . $row['id_board'] . '.0',
2535
							),
2536
						),
2537
					),
2538
					array(
2539
						'tag' => 'link',
2540
						'attributes' => array('label' => $txt['url']),
2541
						'content' => $scripturl . '?msg=' . $row['id_msg'],
2542
					),
2543
					array(
2544
						'tag' => 'time',
2545
						'attributes' => array('label' => $txt['date'], 'UTC' => smf_gmstrftime('%F %T', $row['poster_time'])),
2546
						'content' => $smcFunc['htmlspecialchars'](strip_tags(timeformat($row['poster_time'], false, 'forum'))),
2547
					),
2548
					array(
2549
						'tag' => 'modified_time',
2550
						'attributes' => !empty($row['modified_time']) ? array('label' => $txt['modified_time'], 'UTC' => smf_gmstrftime('%F %T', $row['modified_time'])) : null,
2551
						'content' => !empty($row['modified_time']) ? $smcFunc['htmlspecialchars'](strip_tags(timeformat($row['modified_time'], false, 'forum'))) : null,
2552
					),
2553
					array(
2554
						'tag' => 'modified_by',
2555
						'attributes' => !empty($row['modified_name']) ? array('label' => $txt['modified_by']) : null,
2556
						'content' => !empty($row['modified_name']) ? $row['modified_name'] : null,
2557
						'cdata' => true,
2558
					),
2559
					array(
2560
						'tag' => 'modified_reason',
2561
						'attributes' => !empty($row['modified_reason']) ? array('label' => $txt['reason_for_edit']) : null,
2562
						'content' => !empty($row['modified_reason']) ? $row['modified_reason'] : null,
2563
						'cdata' => true,
2564
					),
2565
					array(
2566
						'tag' => 'likes',
2567
						'attributes' => array('label' => $txt['likes']),
2568
						'content' => $row['likes'],
2569
					),
2570
					array(
2571
						'tag' => 'approval_status',
2572
						'attributes' => $show_all ? array('label' => $txt['approval_status']) : null,
2573
						'content' => $show_all ? $row['approved'] : null,
2574
					),
2575
					array(
2576
						'tag' => 'attachments',
2577
						'attributes' => array('label' => $txt['attachments']),
2578
						'content' => $attachments,
2579
					),
2580
				),
2581
			);
2582
		}
2583
	}
2584
	$smcFunc['db_free_result']($request);
2585
2586
	return $data;
2587
}
2588
2589
/**
2590
 * Get a user's personal messages.
2591
 * Only the user can do this, and no one else -- not even the admin!
2592
 *
2593
 * @param string $xml_format The XML format. Can be 'atom', 'rdf', 'rss', 'rss2' or 'smf'
2594
 * @param bool $ascending If true, get the oldest PMs first. Default false.
2595
 * @return array An array of arrays containing data for the feed. Each array has keys corresponding to the appropriate tags for the specified format.
2596
 */
2597
function getXmlPMs($xml_format, $ascending = false)
2598
{
2599
	global $scripturl, $modSettings, $board, $txt, $context, $user_info;
2600
	global $smcFunc, $sourcedir, $cachedir;
2601
2602
	// Personal messages are supposed to be private
2603
	if (empty($context['xmlnews_uid']) || ($context['xmlnews_uid'] != $user_info['id']))
2604
		return array();
2605
2606
	$select_id_members_to = $smcFunc['db_title'] === POSTGRE_TITLE ? "string_agg(pmr.id_member::text, ',')" : 'GROUP_CONCAT(pmr.id_member)';
2607
2608
	$select_to_names = $smcFunc['db_title'] === POSTGRE_TITLE ? "string_agg(COALESCE(mem.real_name, mem.member_name), ',')" : 'GROUP_CONCAT(COALESCE(mem.real_name, mem.member_name))';
2609
2610
	$request = $smcFunc['db_query']('', '
2611
		SELECT pm.id_pm, pm.msgtime, pm.subject, pm.body, pm.id_member_from, nis.from_name, nis.id_members_to, nis.to_names
2612
		FROM {db_prefix}personal_messages AS pm
2613
		INNER JOIN
2614
		(
2615
			SELECT pm2.id_pm, COALESCE(memf.real_name, pm2.from_name) AS from_name, ' . $select_id_members_to . ' AS id_members_to, ' . $select_to_names . ' AS to_names
2616
			FROM {db_prefix}personal_messages AS pm2
2617
				INNER JOIN {db_prefix}pm_recipients AS pmr ON (pm2.id_pm = pmr.id_pm)
2618
				INNER JOIN {db_prefix}members AS mem ON (mem.id_member = pmr.id_member)
2619
				LEFT JOIN {db_prefix}members AS memf ON (memf.id_member = pm2.id_member_from)
2620
			WHERE pm2.id_pm > {int:start_after}
2621
				AND (
2622
					(pm2.id_member_from = {int:uid} AND pm2.deleted_by_sender = {int:not_deleted})
2623
					OR (pmr.id_member = {int:uid} AND pmr.deleted = {int:not_deleted})
2624
				)
2625
			GROUP BY pm2.id_pm, COALESCE(memf.real_name, pm2.from_name)
2626
			ORDER BY pm2.id_pm {raw:ascdesc}
2627
			LIMIT {int:limit}
2628
		) AS nis ON nis.id_pm = pm.id_pm
2629
		ORDER BY pm.id_pm {raw:ascdesc}',
2630
		array(
2631
			'limit' => $context['xmlnews_limit'],
2632
			'start_after' => !empty($context['personal_messages_start']) ? $context['personal_messages_start'] : 0,
2633
			'uid' => $context['xmlnews_uid'],
2634
			'not_deleted' => 0,
2635
			'ascdesc' => !empty($ascending) ? 'ASC' : 'DESC',
2636
		)
2637
	);
2638
	$data = array();
2639
	while ($row = $smcFunc['db_fetch_assoc']($request))
2640
	{
2641
		$context['personal_messages_start'] = $row['id_pm'];
2642
2643
		// If any control characters slipped in somehow, kill the evil things
2644
		$row = filter_var($row, FILTER_CALLBACK, array('options' => 'cleanXml'));
2645
2646
		// If using our own format, we want both the raw and the parsed content.
2647
		$row[$xml_format === 'smf' ? 'body_html' : 'body'] = parse_bbc($row['body']);
2648
2649
		$recipients = array_combine(explode(',', $row['id_members_to']), explode(',', $row['to_names']));
2650
2651
		// Create a GUID for this post using the tag URI scheme
2652
		$guid = 'tag:' . parse_iri($scripturl, PHP_URL_HOST) . ',' . gmdate('Y-m-d', $row['msgtime']) . ':pm=' . $row['id_pm'];
2653
2654
		if ($xml_format == 'rss' || $xml_format == 'rss2')
2655
		{
2656
			$item = array(
2657
				'tag' => 'item',
2658
				'content' => array(
2659
					array(
2660
						'tag' => 'guid',
2661
						'content' => $guid,
2662
						'attributes' => array(
2663
							'isPermaLink' => 'false',
2664
						),
2665
					),
2666
					array(
2667
						'tag' => 'pubDate',
2668
						'content' => gmdate('D, d M Y H:i:s \G\M\T', $row['msgtime']),
2669
					),
2670
					array(
2671
						'tag' => 'title',
2672
						'content' => $row['subject'],
2673
						'cdata' => true,
2674
					),
2675
					array(
2676
						'tag' => 'description',
2677
						'content' => $row['body'],
2678
						'cdata' => true,
2679
					),
2680
					array(
2681
						'tag' => 'smf:sender',
2682
						// This technically violates the RSS spec, but meh...
2683
						'content' => $row['from_name'],
2684
						'cdata' => true,
2685
					),
2686
				),
2687
			);
2688
2689
			foreach ($recipients as $recipient_id => $recipient_name)
2690
				$item['content'][] = array(
2691
					'tag' => 'smf:recipient',
2692
					'content' => $recipient_name,
2693
					'cdata' => true,
2694
				);
2695
2696
			$data[] = $item;
2697
		}
2698
		elseif ($xml_format == 'rdf')
2699
		{
2700
			$data[] = array(
2701
				'tag' => 'item',
2702
				'attributes' => array('rdf:about' => $scripturl . '?action=pm#msg' . $row['id_pm']),
2703
				'content' => array(
2704
					array(
2705
						'tag' => 'dc:format',
2706
						'content' => 'text/html',
2707
					),
2708
					array(
2709
						'tag' => 'title',
2710
						'content' => $row['subject'],
2711
						'cdata' => true,
2712
					),
2713
					array(
2714
						'tag' => 'link',
2715
						'content' => $scripturl . '?action=pm#msg' . $row['id_pm'],
2716
					),
2717
					array(
2718
						'tag' => 'description',
2719
						'content' => $row['body'],
2720
						'cdata' => true,
2721
					),
2722
				),
2723
			);
2724
		}
2725
		elseif ($xml_format == 'atom')
2726
		{
2727
			$item = array(
2728
				'tag' => 'entry',
2729
				'content' => array(
2730
					array(
2731
						'tag' => 'id',
2732
						'content' => $guid,
2733
					),
2734
					array(
2735
						'tag' => 'updated',
2736
						'content' => smf_gmstrftime('%Y-%m-%dT%H:%M:%SZ', $row['msgtime']),
2737
					),
2738
					array(
2739
						'tag' => 'title',
2740
						'content' => $row['subject'],
2741
						'cdata' => true,
2742
					),
2743
					array(
2744
						'tag' => 'content',
2745
						'attributes' => array('type' => 'html'),
2746
						'content' => $row['body'],
2747
						'cdata' => true,
2748
					),
2749
					array(
2750
						'tag' => 'author',
2751
						'content' => array(
2752
							array(
2753
								'tag' => 'name',
2754
								'content' => $row['from_name'],
2755
								'cdata' => true,
2756
							),
2757
						),
2758
					),
2759
				),
2760
			);
2761
2762
			foreach ($recipients as $recipient_id => $recipient_name)
2763
				$item['content'][] = array(
2764
					'tag' => 'contributor',
2765
					'content' => array(
2766
						array(
2767
							'tag' => 'smf:role',
2768
							'content' => 'recipient',
2769
						),
2770
						array(
2771
							'tag' => 'name',
2772
							'content' => $recipient_name,
2773
							'cdata' => true,
2774
						),
2775
					),
2776
				);
2777
2778
			$data[] = $item;
2779
		}
2780
		else
2781
		{
2782
			loadLanguage('PersonalMessage');
2783
2784
			$item = array(
2785
				'tag' => 'personal_message',
2786
				'attributes' => array('label' => $txt['pm']),
2787
				'content' => array(
2788
					array(
2789
						'tag' => 'id',
2790
						'content' => $row['id_pm'],
2791
					),
2792
					array(
2793
						'tag' => 'sent_date',
2794
						'attributes' => array('label' => $txt['date'], 'UTC' => smf_gmstrftime('%F %T', $row['msgtime'])),
2795
						'content' => $smcFunc['htmlspecialchars'](strip_tags(timeformat($row['msgtime'], false, 'forum'))),
2796
					),
2797
					array(
2798
						'tag' => 'subject',
2799
						'attributes' => array('label' => $txt['subject']),
2800
						'content' => $row['subject'],
2801
						'cdata' => true,
2802
					),
2803
					array(
2804
						'tag' => 'body',
2805
						'attributes' => array('label' => $txt['message']),
2806
						'content' => $row['body'],
2807
						'cdata' => true,
2808
					),
2809
					array(
2810
						'tag' => 'body_html',
2811
						'attributes' => array('label' => $txt['html']),
2812
						'content' => $row['body_html'],
2813
						'cdata' => true,
2814
					),
2815
					array(
2816
						'tag' => 'sender',
2817
						'attributes' => array('label' => $txt['author']),
2818
						'content' => array(
2819
							array(
2820
								'tag' => 'name',
2821
								'attributes' => array('label' => $txt['name']),
2822
								'content' => $row['from_name'],
2823
								'cdata' => true,
2824
							),
2825
							array(
2826
								'tag' => 'id',
2827
								'content' => $row['id_member_from'],
2828
							),
2829
							array(
2830
								'tag' => 'link',
2831
								'attributes' => array('label' => $txt['url']),
2832
								'content' => $scripturl . '?action=profile;u=' . $row['id_member_from'],
2833
							),
2834
						),
2835
					),
2836
				),
2837
			);
2838
2839
			foreach ($recipients as $recipient_id => $recipient_name)
2840
				$item['content'][] = array(
2841
					'tag' => 'recipient',
2842
					'attributes' => array('label' => $txt['recipient']),
2843
					'content' => array(
2844
						array(
2845
							'tag' => 'name',
2846
							'attributes' => array('label' => $txt['name']),
2847
							'content' => $recipient_name,
2848
							'cdata' => true,
2849
						),
2850
						array(
2851
							'tag' => 'id',
2852
							'content' => $recipient_id,
2853
						),
2854
						array(
2855
							'tag' => 'link',
2856
							'attributes' => array('label' => $txt['url']),
2857
							'content' => $scripturl . '?action=profile;u=' . $recipient_id,
2858
						),
2859
					),
2860
				);
2861
2862
			$data[] = $item;
2863
		}
2864
	}
2865
	$smcFunc['db_free_result']($request);
2866
2867
	return $data;
2868
}
2869
2870
?>