Passed
Pull Request — release-2.1 (#6101)
by Jon
04:53
created

export_load_css_js()   F

Complexity

Conditions 41
Paths > 20000

Size

Total Lines 180
Code Lines 98

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 41
eloc 98
c 1
b 0
f 0
nc 1152000
nop 0
dl 0
loc 180
rs 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
/**
4
 * This file contains functions to export a member's profile data to a
5
 * downloadable file.
6
 *
7
 * Simple Machines Forum (SMF)
8
 *
9
 * @package SMF
10
 * @author Simple Machines https://www.simplemachines.org
11
 * @copyright 2020 Simple Machines and individual contributors
12
 * @license https://www.simplemachines.org/about/smf/license.php BSD
13
 *
14
 * @version 2.1 RC2
15
 */
16
17
if (!defined('SMF'))
18
	die('No direct access...');
19
20
21
/**
22
 * Initiates exports a member's profile, posts, and personal messages to a file.
23
 *
24
 * @todo Add CSV, JSON as other possible export formats besides XML and HTML?
25
 *
26
 * @param int $uid The ID of the member whose data we're exporting.
27
 */
28
function export_profile_data($uid)
29
{
30
	global $context, $smcFunc, $txt, $modSettings, $sourcedir, $scripturl;
31
	global $query_this_board;
32
33
	if (!isset($context['token_check']))
34
		$context['token_check'] = 'profile-ex' . $uid;
35
36
	$context['export_formats'] = get_export_formats();
37
38
	if (!isset($_POST['format']) || !isset($context['export_formats'][$_POST['format']]))
39
		unset($_POST['format'], $_POST['delete'], $_POST['export_begin']);
40
41
	// This lists the types of data we can export and info for doing so.
42
	$context['export_datatypes'] = array(
43
		'profile' => array(
44
			'label' => null,
45
			'total' => 0,
46
			'latest' => 1,
47
			// Instructions to pass to ExportProfileData background task:
48
			'XML' => array(
49
				'func' => 'getXmlProfile',
50
				'langfile' => 'Profile',
51
			),
52
			'HTML' => array(
53
				'func' => 'getXmlProfile',
54
				'langfile' => 'Profile',
55
			),
56
			'XML_XSLT' => array(
57
				'func' => 'getXmlProfile',
58
				'langfile' => 'Profile',
59
			),
60
			// 'CSV' => array(),
61
			// 'JSON' => array(),
62
		),
63
		'posts' => array(
64
			'label' => $txt['export_include_posts'],
65
			'total' => $context['member']['real_posts'],
66
			'latest' => function($uid)
67
			{
68
				global $smcFunc, $modSettings;
69
70
				static $latest_post;
71
72
				if (isset($latest_post))
73
					return $latest_post;
74
75
				$query_this_board = !empty($modSettings['recycle_enable']) && $modSettings['recycle_board'] > 0 ? 'b.id_board != ' . $modSettings['recycle_board'] : '1=1';
76
77
				$request = $smcFunc['db_query']('', '
78
					SELECT m.id_msg
79
					FROM {db_prefix}messages as m
80
						INNER JOIN {db_prefix}boards AS b ON (b.id_board = m.id_board)
81
					WHERE id_member = {int:uid}
82
						AND ' . $query_this_board . '
83
					ORDER BY id_msg DESC
84
					LIMIT {int:limit}',
85
					array(
86
						'limit' => 1,
87
						'uid' => $uid,
88
					)
89
				);
90
				list($latest_post) = $smcFunc['db_fetch_row']($request);
91
				$smcFunc['db_free_result']($request);
92
93
				return $latest_post;
94
			},
95
			// Instructions to pass to ExportProfileData background task:
96
			'XML' => array(
97
				'func' => 'getXmlPosts',
98
				'langfile' => 'Post',
99
			),
100
			'HTML' => array(
101
				'func' => 'getXmlPosts',
102
				'langfile' => 'Post',
103
			),
104
			'XML_XSLT' => array(
105
				'func' => 'getXmlPosts',
106
				'langfile' => 'Post',
107
			),
108
			// 'CSV' => array(),
109
			// 'JSON' => array(),
110
		),
111
		'personal_messages' => array(
112
			'label' => $txt['export_include_personal_messages'],
113
			'total' => function($uid)
114
			{
115
				global $smcFunc;
116
117
				static $total_pms;
118
119
				if (isset($total_pms))
120
					return $total_pms;
121
122
				$request = $smcFunc['db_query']('', '
123
					SELECT COUNT(*)
124
					FROM {db_prefix}personal_messages AS pm
125
						INNER JOIN {db_prefix}pm_recipients AS pmr ON (pm.id_pm = pmr.id_pm)
126
					WHERE (pm.id_member_from = {int:uid} AND pm.deleted_by_sender = {int:not_deleted})
127
						OR (pmr.id_member = {int:uid} AND pmr.deleted = {int:not_deleted})',
128
					array(
129
						'uid' => $uid,
130
						'not_deleted' => 0,
131
					)
132
				);
133
				list($total_pms) = $smcFunc['db_fetch_row']($request);
134
				$smcFunc['db_free_result']($request);
135
136
				return $total_pms;
137
			},
138
			'latest' => function($uid)
139
			{
140
				global $smcFunc;
141
142
				static $latest_pm;
143
144
				if (isset($latest_pm))
145
					return $latest_pm;
146
147
				$request = $smcFunc['db_query']('', '
148
					SELECT pm.id_pm
149
					FROM {db_prefix}personal_messages AS pm
150
						INNER JOIN {db_prefix}pm_recipients AS pmr ON (pm.id_pm = pmr.id_pm)
151
					WHERE (pm.id_member_from = {int:uid} AND pm.deleted_by_sender = {int:not_deleted})
152
						OR (pmr.id_member = {int:uid} AND pmr.deleted = {int:not_deleted})
153
					ORDER BY pm.id_pm DESC
154
					LIMIT {int:limit}',
155
					array(
156
						'limit' => 1,
157
						'uid' => $uid,
158
						'not_deleted' => 0,
159
					)
160
				);
161
				list($latest_pm) = $smcFunc['db_fetch_row']($request);
162
				$smcFunc['db_free_result']($request);
163
164
				return $latest_pm;
165
			},
166
			// Instructions to pass to ExportProfileData background task:
167
			'XML' => array(
168
				'func' => 'getXmlPMs',
169
				'langfile' => 'PersonalMessage',
170
			),
171
			'HTML' => array(
172
				'func' => 'getXmlPMs',
173
				'langfile' => 'PersonalMessage',
174
			),
175
			'XML_XSLT' => array(
176
				'func' => 'getXmlPMs',
177
				'langfile' => 'PersonalMessage',
178
			),
179
			// 'CSV' => array(),
180
			// 'JSON' => array(),
181
		),
182
	);
183
184
	if (empty($modSettings['export_dir']) || !file_exists($modSettings['export_dir']))
185
		create_export_dir();
186
187
	$export_dir_slash = $modSettings['export_dir'] . DIRECTORY_SEPARATOR;
188
189
	$idhash = hash_hmac('sha1', $uid, get_auth_secret());
190
	$dltoken = hash_hmac('sha1', $idhash, get_auth_secret());
191
192
	$query_this_board = !empty($modSettings['recycle_enable']) && $modSettings['recycle_board'] > 0 ? 'b.id_board != ' . $modSettings['recycle_board'] : '1=1';
193
194
	$context['completed_exports'] = array();
195
	$context['active_exports'] = array();
196
	$existing_export_formats = array();
197
	$latest = array();
198
199
	foreach ($context['export_formats'] as $format => $format_settings)
200
	{
201
		$idhash_ext = $idhash . '.' . $format_settings['extension'];
202
203
		$done = null;
204
		$context['outdated_exports'][$idhash_ext] = array();
205
206
		// $realfile needs to be the highest numbered one, or 1_*** if none exist.
207
		$filenum = 1;
208
		$realfile = $export_dir_slash . $filenum . '_' . $idhash_ext;
209
		while (file_exists($export_dir_slash . ($filenum + 1) . '_' . $idhash_ext))
210
			$realfile = $export_dir_slash . ++$filenum . '_' . $idhash_ext;
211
212
		$tempfile = $export_dir_slash . $idhash_ext . '.tmp';
213
		$progressfile = $export_dir_slash . $idhash_ext . '.progress.json';
214
215
		// If requested by the user, delete any existing export files and background tasks.
216
		if (isset($_POST['delete']) && isset($_POST['format']) && $_POST['format'] === $format && isset($_POST['t']) && $_POST['t'] === $dltoken)
217
		{
218
			$smcFunc['db_query']('', '
219
				DELETE FROM {db_prefix}background_tasks
220
				WHERE task_class = {string:class}
221
					AND task_data LIKE {string:details}',
222
				array(
223
					'class' => 'ExportProfileData_Background',
224
					'details' => substr($smcFunc['json_encode'](array('format' => $format, 'uid' => $uid)), 0, -1) . ',%',
225
				)
226
			);
227
228
			foreach (glob($export_dir_slash . '*' . $idhash_ext . '*') as $fpath)
229
				@unlink($fpath);
230
231
			if (empty($_POST['export_begin']))
232
				redirectexit('action=profile;area=getprofiledata;u=' . $uid);
233
		}
234
235
		$progress = file_exists($progressfile) ? $smcFunc['json_decode'](file_get_contents($progressfile), true) : array();
236
237
		if (!empty($progress))
238
			$included = array_keys($progress);
239
		else
240
			$included = array_intersect(array_keys($context['export_datatypes']), array_keys($_POST));
241
242
		// If we're starting a new export in this format, we're done here.
243
		if (!empty($_POST['export_begin']) && isset($_POST['format']) && $_POST['format'] === $format)
244
			break;
245
246
		// The rest of this loop deals with current exports, if any.
247
248
		$included_desc = array();
249
		foreach ($included as $datatype)
250
			$included_desc[] = $txt[$datatype];
251
252
		$dlfilename = array_merge(array($context['forum_name'], $context['member']['username']), $included_desc);
253
		$dlfilename = preg_replace('/[^\p{L}\p{M}\p{N}_]+/u', '-', str_replace('"', '', un_htmlspecialchars(strip_tags(implode('_', $dlfilename)))));
254
255
		if (file_exists($tempfile) && file_exists($progressfile))
256
		{
257
			$done = false;
258
		}
259
		elseif (file_exists($realfile))
260
		{
261
			// It looks like we're done.
262
			$done = true;
263
264
			// But let's check whether it's outdated.
265
			foreach ($context['export_datatypes'] as $datatype => $datatype_settings)
266
			{
267
				if (!isset($progress[$datatype]))
268
					continue;
269
270
				if (!isset($latest[$datatype]))
271
					$latest[$datatype] = is_callable($datatype_settings['latest']) ? $datatype_settings['latest']($uid) : $datatype_settings['latest'];
272
273
				if ($latest[$datatype] > $progress[$datatype])
274
					$context['outdated_exports'][$idhash_ext][] = $datatype;
275
			}
276
		}
277
278
		if ($done === true)
279
		{
280
			$exportfilepaths = glob($export_dir_slash . '*_' . $idhash_ext);
281
282
			foreach ($exportfilepaths as $exportfilepath)
283
			{
284
				$exportbasename = basename($exportfilepath);
285
286
				$part = substr($exportbasename, 0, strcspn($exportbasename, '_'));
287
				$suffix = count($exportfilepaths) == 1 ? '' : '_' . $part;
288
289
				$size = filesize($exportfilepath) / 1024;
290
				$units = array('KB', 'MB', 'GB', 'TB');
291
				$unitkey = 0;
292
				while ($size > 1024)
293
				{
294
					$size = $size / 1024;
295
					$unitkey++;
296
				}
297
				$size = round($size, 2) . $units[$unitkey];
298
299
				$context['completed_exports'][$idhash_ext][$part] = array(
300
					'realname' => $exportbasename,
301
					'dlbasename' => $dlfilename . $suffix . '.' . $format_settings['extension'],
302
					'dltoken' => $dltoken,
303
					'included' => $included,
304
					'included_desc' => sentence_list($included_desc),
305
					'format' => $format,
306
					'mtime' => timeformat(filemtime($exportfilepath)),
307
					'size' => $size,
308
				);
309
			}
310
311
			ksort($context['completed_exports'][$idhash_ext], SORT_NUMERIC);
312
313
			$existing_export_formats[] = $format;
314
		}
315
		elseif ($done === false)
316
		{
317
			$context['active_exports'][$idhash_ext] = array(
318
				'dltoken' => $dltoken,
319
				'included' => $included,
320
				'included_desc' => sentence_list($included_desc),
321
				'format' => $format,
322
			);
323
324
			$existing_export_formats[] = $format;
325
		}
326
	}
327
328
	if (!empty($_POST['export_begin']))
329
	{
330
		checkSession();
331
		validateToken($context['token_check'], 'post');
332
333
		$format = isset($_POST['format']) && isset($context['export_formats'][$_POST['format']]) ? $_POST['format'] : 'XML';
334
335
		$included = array();
336
		$included_desc = array();
337
		foreach ($context['export_datatypes'] as $datatype => $datatype_settings)
338
		{
339
			if ($datatype == 'profile' || !empty($_POST[$datatype]))
340
			{
341
				$included[$datatype] = $datatype_settings[$format];
342
				$included_desc[] = $txt[$datatype];
343
344
				$start[$datatype] = !empty($start[$datatype]) ? $start[$datatype] : 0;
345
346
				if (!isset($latest[$datatype]))
347
					$latest[$datatype] = is_callable($datatype_settings['latest']) ? $datatype_settings['latest']($uid) : $datatype_settings['latest'];
348
349
				if (!isset($total[$datatype]))
350
					$total[$datatype] = is_callable($datatype_settings['total']) ? $datatype_settings['total']($uid) : $datatype_settings['total'];
351
			}
352
		}
353
354
		$dlfilename = array_merge(array($context['forum_name'], $context['member']['username']), $included_desc);
355
		$dlfilename = preg_replace('/[^\p{L}\p{M}\p{N}_]+/u', '-', str_replace('"', '', un_htmlspecialchars(strip_tags(implode('_', $dlfilename)))));
356
357
		$last_page = ceil(array_sum($total) / $context['export_formats'][$format]['per_page']);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $total does not seem to be defined for all execution paths leading up to this point.
Loading history...
358
359
		$data = $smcFunc['json_encode'](array(
360
			'format' => $format,
361
			'uid' => $uid,
362
			'lang' => $context['member']['language'],
363
			'included' => $included,
364
			'start' => $start,
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $start does not seem to be defined for all execution paths leading up to this point.
Loading history...
365
			'latest' => $latest,
366
			'datatype' => isset($current_datatype) ? $current_datatype : key($included),
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $current_datatype seems to never exist and therefore isset should always be false.
Loading history...
367
			'format_settings' => $context['export_formats'][$format],
368
			'last_page' => $last_page,
369
			'dlfilename' => $dlfilename,
370
		));
371
372
		$smcFunc['db_insert']('insert', '{db_prefix}background_tasks',
373
			array('task_file' => 'string-255', 'task_class' => 'string-255', 'task_data' => 'string', 'claimed_time' => 'int'),
374
			array('$sourcedir/tasks/ExportProfileData.php', 'ExportProfileData_Background', $data, 0),
375
			array()
376
		);
377
378
		// So the user can see that we've started.
379
		if (!file_exists($tempfile))
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $tempfile seems to be defined by a foreach iteration on line 199. Are you sure the iterator is never empty, otherwise this variable is not defined?
Loading history...
380
			touch($tempfile);
381
		if (!file_exists($progressfile))
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $progressfile seems to be defined by a foreach iteration on line 199. Are you sure the iterator is never empty, otherwise this variable is not defined?
Loading history...
382
			file_put_contents($progressfile, $smcFunc['json_encode'](array_fill_keys(array_keys($included), 0)));
383
384
		redirectexit('action=profile;area=getprofiledata;u=' . $uid);
385
	}
386
387
	createToken($context['token_check'], 'post');
388
389
	$context['page_title'] = $txt['export_profile_data'];
390
391
	if (empty($modSettings['export_expiry']))
392
		unset($txt['export_profile_data_desc_list']['expiry']);
393
	else
394
		$txt['export_profile_data_desc_list']['expiry'] = sprintf($txt['export_profile_data_desc_list']['expiry'], $modSettings['export_expiry']);
395
396
	$context['export_profile_data_desc'] = sprintf($txt['export_profile_data_desc'], '<li>' . implode('</li><li>', $txt['export_profile_data_desc_list']) . '</li>');
397
398
	addJavaScriptVar('completed_formats', '[\'' . implode('\', \'', array_unique($existing_export_formats)) . '\']', false);
399
}
400
401
/**
402
 * Downloads exported profile data file.
403
 *
404
 * @param int $uid The ID of the member whose data we're exporting.
405
 */
406
function download_export_file($uid)
407
{
408
	global $modSettings, $maintenance, $context, $txt, $smcFunc;
409
410
	$export_formats = get_export_formats();
411
412
	// This is done to clear any output that was made before now.
413
	ob_end_clean();
414
415
	if (!empty($modSettings['enableCompressedOutput']) && !headers_sent() && ob_get_length() == 0)
416
	{
417
		if (@ini_get('zlib.output_compression') == '1' || @ini_get('output_handler') == 'ob_gzhandler')
418
			$modSettings['enableCompressedOutput'] = 0;
419
420
		else
421
			ob_start('ob_gzhandler');
422
	}
423
424
	if (empty($modSettings['enableCompressedOutput']))
425
	{
426
		ob_start();
427
		header('content-encoding: none');
428
	}
429
430
	// No access in strict maintenance mode.
431
	if (!empty($maintenance) && $maintenance == 2)
432
	{
433
		send_http_status(404);
434
		exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
435
	}
436
437
	// We can't give them anything without these.
438
	if (empty($_GET['t']) || empty($_GET['format']) || !isset($export_formats[$_GET['format']]))
439
	{
440
		send_http_status(400);
441
		exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
442
	}
443
444
	$export_dir_slash = $modSettings['export_dir'] . DIRECTORY_SEPARATOR;
445
446
	$idhash = hash_hmac('sha1', $uid, get_auth_secret());
447
	$part = isset($_GET['part']) ? (int) $_GET['part'] : 1;
448
	$extension = $export_formats[$_GET['format']]['extension'];
449
450
	$filepath = $export_dir_slash . $part . '_' . $idhash . '.' . $extension;
451
	$progressfile = $export_dir_slash . $idhash . '.' . $extension . '.progress.json';
452
453
	// Make sure they gave the correct authentication token.
454
	// We use these tokens so the user can download without logging in, as required by the GDPR.
455
	$dltoken = hash_hmac('sha1', $idhash, get_auth_secret());
456
	if ($_GET['t'] !== $dltoken)
457
	{
458
		send_http_status(403);
459
		exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
460
	}
461
462
	// Obviously we can't give what we don't have.
463
	if (empty($modSettings['export_dir']) || !file_exists($filepath))
464
	{
465
		send_http_status(404);
466
		exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
467
	}
468
469
	// Figure out the filename we'll tell the browser.
470
	$datatypes = file_exists($progressfile) ? array_keys($smcFunc['json_decode'](file_get_contents($progressfile), true)) : array('profile');
471
	$included_desc = array_map(function ($datatype) use ($txt) { return $txt[$datatype]; }, $datatypes);
472
473
	$dlfilename = array_merge(array($context['forum_name'], $context['member']['username']), $included_desc);
474
	$dlfilename = preg_replace('/[^\p{L}\p{M}\p{N}_]+/u', '-', str_replace('"', '', un_htmlspecialchars(strip_tags(implode('_', $dlfilename)))));
475
476
	$suffix = ($part > 1 || file_exists($export_dir_slash . '2_' . $idhash . '.' . $extension)) ? '_' . $part : '';
477
478
	$dlbasename = $dlfilename . $suffix . '.' . $extension;
479
480
	$mtime = filemtime($filepath);
481
	$size = filesize($filepath);
482
483
	// If it hasn't been modified since the last time it was retrieved, there's no need to serve it again.
484
	if (!empty($_SERVER['HTTP_IF_MODIFIED_SINCE']))
485
	{
486
		list($modified_since) = explode(';', $_SERVER['HTTP_IF_MODIFIED_SINCE']);
487
		if (strtotime($modified_since) >= $mtime)
488
		{
489
			ob_end_clean();
490
491
			// Answer the question - no, it hasn't been modified ;).
492
			send_http_status(304);
493
			exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
494
		}
495
	}
496
497
	// Check whether the ETag was sent back, and cache based on that...
498
	$eTag = md5(implode(' ', array($dlbasename, $size, $mtime)));
499
	if (!empty($_SERVER['HTTP_IF_NONE_MATCH']) && strpos($_SERVER['HTTP_IF_NONE_MATCH'], $eTag) !== false)
500
	{
501
		ob_end_clean();
502
503
		send_http_status(304);
504
		exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
505
	}
506
507
	// If this is a partial download, we need to determine what data range to send
508
	$range = 0;
509
	if (isset($_SERVER['HTTP_RANGE']))
510
	{
511
		list($a, $range) = explode("=", $_SERVER['HTTP_RANGE'], 2);
512
		list($range) = explode(",", $range, 2);
513
		list($range, $range_end) = explode("-", $range);
514
		$range = intval($range);
515
		$range_end = !$range_end ? $size - 1 : intval($range_end);
516
		$new_length = $range_end - $range + 1;
517
	}
518
519
	header('pragma: ');
520
521
	if (!isBrowser('gecko'))
522
		header('content-transfer-encoding: binary');
523
524
	header('expires: ' . gmdate('D, d M Y H:i:s', time() + 525600 * 60) . ' GMT');
525
	header('last-modified: ' . gmdate('D, d M Y H:i:s', $mtime) . ' GMT');
526
	header('accept-ranges: bytes');
527
	header('connection: close');
528
	header('etag: ' . $eTag);
529
	header('content-type: ' . $export_formats[$_GET['format']]['mime']);
530
531
	// Convert the file to UTF-8, cuz most browsers dig that.
532
	$utf8name = !$context['utf8'] && function_exists('iconv') ? iconv($context['character_set'], 'UTF-8', $dlbasename) : (!$context['utf8'] && function_exists('mb_convert_encoding') ? mb_convert_encoding($dlbasename, 'UTF-8', $context['character_set']) : $dlbasename);
533
534
	// Different browsers like different standards...
535
	if (isBrowser('firefox'))
536
		header('content-disposition: attachment; filename*=UTF-8\'\'' . rawurlencode(preg_replace_callback('~&#(\d{3,8});~', 'fixchar__callback', $utf8name)));
537
538
	elseif (isBrowser('opera'))
539
		header('content-disposition: attachment; filename="' . preg_replace_callback('~&#(\d{3,8});~', 'fixchar__callback', $utf8name) . '"');
540
541
	elseif (isBrowser('ie'))
542
		header('content-disposition: attachment; filename="' . urlencode(preg_replace_callback('~&#(\d{3,8});~', 'fixchar__callback', $utf8name)) . '"');
543
544
	else
545
		header('content-disposition: attachment; filename="' . $utf8name . '"');
546
547
	header('cache-control: max-age=' . (525600 * 60) . ', private');
548
549
	// Multipart and resuming support
550
	if (isset($_SERVER['HTTP_RANGE']))
551
	{
552
		send_http_status(206);
553
		header("content-length: $new_length");
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $new_length does not seem to be defined for all execution paths leading up to this point.
Loading history...
554
		header("content-range: bytes $range-$range_end/$size");
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $range_end does not seem to be defined for all execution paths leading up to this point.
Loading history...
555
	}
556
	else
557
		header("content-length: $size");
558
559
	// Try to buy some time...
560
	@set_time_limit(600);
561
562
	// For multipart/resumable downloads, send the requested chunk(s) of the file
563
	if (isset($_SERVER['HTTP_RANGE']))
564
	{
565
		while (@ob_get_level() > 0)
566
			@ob_end_clean();
567
568
		// 40 kilobytes is a good-ish amount
569
		$chunksize = 40 * 1024;
570
		$bytes_sent = 0;
571
572
		$fp = fopen($filepath, 'rb');
573
574
		fseek($fp, $range);
0 ignored issues
show
Bug introduced by
It seems like $fp can also be of type false; however, parameter $handle of fseek() does only seem to accept resource, 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

574
		fseek(/** @scrutinizer ignore-type */ $fp, $range);
Loading history...
575
576
		while (!feof($fp) && (!connection_aborted()) && ($bytes_sent < $new_length))
0 ignored issues
show
Bug introduced by
It seems like $fp can also be of type false; however, parameter $handle of feof() does only seem to accept resource, 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

576
		while (!feof(/** @scrutinizer ignore-type */ $fp) && (!connection_aborted()) && ($bytes_sent < $new_length))
Loading history...
577
		{
578
			$buffer = fread($fp, $chunksize);
0 ignored issues
show
Bug introduced by
It seems like $fp can also be of type false; however, parameter $handle of fread() does only seem to accept resource, 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

578
			$buffer = fread(/** @scrutinizer ignore-type */ $fp, $chunksize);
Loading history...
579
			echo($buffer);
580
			flush();
581
			$bytes_sent += strlen($buffer);
582
		}
583
		fclose($fp);
0 ignored issues
show
Bug introduced by
It seems like $fp can also be of type false; however, parameter $handle of fclose() does only seem to accept resource, 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

583
		fclose(/** @scrutinizer ignore-type */ $fp);
Loading history...
584
	}
585
586
	// Since we don't do output compression for files this large...
587
	elseif ($size > 4194304)
588
	{
589
		// Forcibly end any output buffering going on.
590
		while (@ob_get_level() > 0)
591
			@ob_end_clean();
592
593
		$fp = fopen($filepath, 'rb');
594
		while (!feof($fp))
595
		{
596
			echo fread($fp, 8192);
597
			flush();
598
		}
599
		fclose($fp);
600
	}
601
602
	// On some of the less-bright hosts, readfile() is disabled.  It's just a faster, more byte safe, version of what's in the if.
603
	elseif (@readfile($filepath) === null)
604
		echo file_get_contents($filepath);
605
606
	exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
607
}
608
609
/**
610
 * Allows a member to export their attachments.
611
 * Mostly just a wrapper for showAttachment() but with a few tweaks.
612
 *
613
 * @param int $uid The ID of the member whose data we're exporting.
614
 */
615
function export_attachment($uid)
616
{
617
	global $sourcedir, $context, $smcFunc;
618
619
	$idhash = hash_hmac('sha1', $uid, get_auth_secret());
620
	$dltoken = hash_hmac('sha1', $idhash, get_auth_secret());
621
	if (!isset($_GET['t']) || $_GET['t'] !== $dltoken)
622
	{
623
		send_http_status(403);
624
		exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
625
	}
626
627
	$attachId = isset($_REQUEST['attach']) ? (int) $_REQUEST['attach'] : 0;
628
	if (empty($attachId))
629
	{
630
		send_http_status(404, 'File Not Found');
631
		die('404 File Not Found');
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
632
	}
633
634
	// Does this attachment belong to this member?
635
	$request = $smcFunc['db_query']('', '
636
		SELECT m.id_topic
637
		FROM {db_prefix}messages AS m
638
			INNER JOIN {db_prefix}attachments AS a ON (m.id_msg = a.id_msg)
639
		WHERE m.id_member = {int:uid}
640
			AND a.id_attach = {int:attachId}',
641
		array(
642
			'uid' => $uid,
643
			'attachId' => $attachId,
644
		)
645
	);
646
	if ($smcFunc['db_num_rows']($request) == 0)
647
	{
648
		$smcFunc['db_free_result']($request);
649
		send_http_status(403);
650
		exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
651
	}
652
653
	// We need the topic.
654
	list ($_REQUEST['topic']) = $smcFunc['db_fetch_row']($request);
655
	$smcFunc['db_free_result']($request);
656
657
	// This doesn't count as a normal download.
658
	$context['skip_downloads_increment'] = true;
659
660
	// Try to avoid collisons when attachment names are not unique.
661
	$context['prepend_attachment_id'] = true;
662
663
	// We should now have what we need to serve the file.
664
	require_once($sourcedir . DIRECTORY_SEPARATOR . 'ShowAttachments.php');
665
	showAttachment();
666
}
667
668
/**
669
 * Helper function that defines data export formats in a single location.
670
 *
671
 * @return array Information about supported data formats for profile exports.
672
 */
673
function get_export_formats()
674
{
675
	global $txt;
676
677
	$export_formats = array(
678
		'XML_XSLT' => array(
679
			'extension' => 'styled.xml',
680
			'mime' => 'text/xml',
681
			'description' => $txt['export_format_xml_xslt'],
682
			'per_page' => 500,
683
		),
684
		'HTML' => array(
685
			'extension' => 'html',
686
			'mime' => 'text/html',
687
			'description' => $txt['export_format_html'],
688
			'per_page' => 500,
689
		),
690
		'XML' => array(
691
			'extension' => 'xml',
692
			'mime' => 'text/xml',
693
			'description' => $txt['export_format_xml'],
694
			'per_page' => 2000,
695
		),
696
		// 'CSV' => array(
697
		// 	'extension' => 'csv',
698
		// 	'mime' => 'text/csv',
699
		// 	'description' => $txt['export_format_csv'],
700
		//	'per_page' => 2000,
701
		// ),
702
		// 'JSON' => array(
703
		// 	'extension' => 'json',
704
		// 	'mime' => 'application/json',
705
		// 	'description' => $txt['export_format_json'],
706
		//	'per_page' => 2000,
707
		// ),
708
	);
709
710
	// If these are missing, we can't transform the XML on the server.
711
	if (!class_exists('DOMDocument') || !class_exists('XSLTProcessor'))
712
		unset($export_formats['HTML']);
713
714
	return $export_formats;
715
}
716
717
/**
718
 * Returns the path to a secure directory for storing exported profile data.
719
 *
720
 * The directory is created if it does not yet exist, and is secured using the
721
 * same method that we use to secure attachment directories. Files in this
722
 * directory can only be downloaded via the download_export_file() function.
723
 *
724
 * @return string|bool The path to the directory, or false on error.
725
 */
726
function create_export_dir($fallback = '')
727
{
728
	global $boarddir, $modSettings;
729
730
	// No supplied fallback, so use the default location.
731
	if (empty($fallback))
732
		$fallback = $boarddir . DIRECTORY_SEPARATOR . 'exports';
733
734
	// Automatically set it to the fallback if it is missing.
735
	if (empty($modSettings['export_dir']))
736
		updateSettings(array('export_dir' => $fallback));
737
738
	// Make sure the directory exists.
739
	if (!file_exists($modSettings['export_dir']))
740
		@mkdir($modSettings['export_dir'], null, true);
741
742
	// Make sure the directory has the correct permissions.
743
	if (!is_dir($modSettings['export_dir']) || !smf_chmod($modSettings['export_dir']))
744
	{
745
		loadLanguage('Errors');
746
747
		// Try again at the fallback location.
748
		if ($modSettings['export_dir'] != $fallback)
749
		{
750
			log_error($txt['export_dir_forced_change'], $modSettings['export_dir'], $fallback);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $txt seems to be never defined.
Loading history...
751
			updateSettings(array('export_dir' => $fallback));
752
753
			// Secondary fallback will be the default location, so no parameter this time.
754
			create_export_dir();
755
		}
756
		// Uh-oh. Even the default location failed.
757
		else
758
		{
759
			log_error($txt['export_dir_not_writable']);
760
			return false;
761
		}
762
	}
763
764
	return secureDirectory(array($modSettings['export_dir']), true);
765
}
766
767
/**
768
 * Provides an XSLT stylesheet to transform an XML-based profile export file
769
 * into the desired output format.
770
 *
771
 * @param string $format The desired output format. Currently accepts 'HTML' and 'XML_XSLT'.
772
 * @param int $uid The ID of the member whose data we're exporting.
773
 * @return array The XSLT stylesheet and a (possibly empty) DTD to insert into the XML document.
774
 */
775
function get_xslt_stylesheet($format, $uid)
776
{
777
	global $context, $txt, $settings, $modSettings, $sourcedir, $forum_copyright, $scripturl, $smcFunc;
778
779
	static $xslts = array();
780
781
	$doctype = '';
782
	$stylesheet = array();
783
	$xslt_variables = array();
784
785
	// Do not change any of these to HTTPS URLs. For explanation, see comments in the buildXmlFeed() function.
786
	$smf_ns = 'htt'.'p:/'.'/ww'.'w.simple'.'machines.o'.'rg/xml/profile';
787
	$xslt_ns = 'htt'.'p:/'.'/ww'.'w.w3.o'.'rg/1999/XSL/Transform';
788
	$html_ns = 'htt'.'p:/'.'/ww'.'w.w3.o'.'rg/1999/xhtml';
789
790
	require_once($sourcedir . DIRECTORY_SEPARATOR . 'News.php');
791
792
	if (in_array($format, array('HTML', 'XML_XSLT')))
793
	{
794
		if (!class_exists('DOMDocument') || !class_exists('XSLTProcessor'))
795
			$format = 'XML_XSLT';
796
797
		$export_formats = get_export_formats();
798
799
		/* Notes:
800
		 * 1. The 'value' can be one of the following:
801
		 *    - an integer or string
802
		 *    - an XPath expression
803
		 *    - raw XML, which may or not not include other XSLT statements.
804
		 *
805
		 * 2. Always set 'no_cdata_parse' to true when the value is raw XML.
806
		 *
807
		 * 3. Set 'xpath' to true if the value is an XPath expression. When this
808
		 *    is true, the value will be placed in the 'select' attribute of the
809
		 *    <xsl:variable> element rather than in a child node.
810
		 *
811
		 * 4. Set 'param' to true in order to create an <xsl:param> instead
812
		 *    of an <xsl:variable>.
813
		 *
814
		 * A word to PHP coders: Do not let the term "variable" mislead you.
815
		 * XSLT variables are roughly equivalent to PHP constants rather
816
		 * than PHP variables; once the value has been set, it is immutable.
817
		 * Keeping this in mind may spare you from some confusion and
818
		 * frustration while working with XSLT.
819
		 */
820
		$xslt_variables = array(
821
			'scripturl' => array(
822
				'value' => $scripturl,
823
			),
824
			'themeurl' => array(
825
				'value' => $settings['default_theme_url'],
826
			),
827
			'member_id' => array(
828
				'value' => $uid,
829
			),
830
			'last_page' => array(
831
				'param' => true,
832
				'value' => !empty($context['export_last_page']) ? $context['export_last_page'] : 1,
833
				'xpath' => true,
834
			),
835
			'dlfilename' => array(
836
				'param' => true,
837
				'value' => !empty($context['export_dlfilename']) ? $context['export_dlfilename'] : '',
838
			),
839
			'ext' => array(
840
				'value' => $export_formats[$format]['extension'],
841
			),
842
			'forum_copyright' => array(
843
				'value' => sprintf($forum_copyright, SMF_FULL_VERSION, SMF_SOFTWARE_YEAR, $scripturl),
844
			),
845
			'txt_summary_heading' => array(
846
				'value' => $txt['summary'],
847
			),
848
			'txt_posts_heading' => array(
849
				'value' => $txt['posts'],
850
			),
851
			'txt_personal_messages_heading' => array(
852
				'value' => $txt['personal_messages'],
853
			),
854
			'txt_view_source_button' => array(
855
				'value' => $txt['export_view_source_button'],
856
			),
857
			'txt_download_original' => array(
858
				'value' => $txt['export_download_original'],
859
			),
860
			'txt_help' => array(
861
				'value' => $txt['help'],
862
			),
863
			'txt_terms_rules' => array(
864
				'value' => $txt['terms_and_rules'],
865
			),
866
			'txt_go_up' => array(
867
				'value' => $txt['go_up'],
868
			),
869
			'txt_pages' => array(
870
				'value' => $txt['pages'],
871
			),
872
		);
873
874
		// Let mods adjust the XSLT variables.
875
		call_integration_hook('integrate_export_xslt_variables', array(&$xslt_variables, $format));
876
877
		$idhash = hash_hmac('sha1', $uid, get_auth_secret());
878
		$xslt_variables['dltoken'] = array(
879
			'value' => hash_hmac('sha1', $idhash, get_auth_secret())
880
		);
881
882
		// Efficiency = good.
883
		$xslt_key = $smcFunc['json_encode'](array($format, $uid, $xslt_variables));
884
		if (isset($xslts[$xslt_key]))
885
			return $xslts[$xslt_key];
886
887
		if ($format == 'XML_XSLT')
888
		{
889
			$doctype = implode("\n", array(
890
				'<!--',
891
				"\t" . $txt['export_open_in_browser'],
892
				'-->',
893
				'<?xml-stylesheet type="text/xsl" href="#stylesheet"?>',
894
				'<!DOCTYPE smf:xml-feed [',
895
				'<!ATTLIST xsl:stylesheet',
896
				'id ID #REQUIRED>',
897
				']>',
898
			));
899
900
			$stylesheet['header'] = "\n" . implode("\n", array(
901
				'',
902
				"\t" . '<xsl:stylesheet version="1.0" xmlns:xsl="' . $xslt_ns . '" xmlns:html="' . $html_ns . '" xmlns:smf="' . $smf_ns . '" exclude-result-prefixes="smf html" id="stylesheet">',
903
				'',
904
				"\t\t" . '<xsl:template match="xsl:stylesheet"/>',
905
				"\t\t" . '<xsl:template match="xsl:stylesheet" mode="detailedinfo"/>',
906
			));
907
		}
908
		else
909
		{
910
			$doctype = '';
911
			$stylesheet['header'] = implode("\n", array(
912
				'<?xml version="1.0" encoding="' . $context['character_set'] . '"?' . '>',
913
				'<xsl:stylesheet version="1.0" xmlns:xsl="' . $xslt_ns . '" xmlns:html="' . $html_ns . '" xmlns:smf="' . $smf_ns . '" exclude-result-prefixes="smf html">',
914
			));
915
		}
916
917
		// Output control settings.
918
		$stylesheet['output_control'] = '
919
		<xsl:output method="html" encoding="utf-8" indent="yes"/>
920
		<xsl:strip-space elements="*"/>';
921
922
		// Insert the XSLT variables.
923
		$stylesheet['variables'] = '';
924
925
		foreach ($xslt_variables as $name => $var)
926
		{
927
			$element = !empty($var['param']) ? 'param' : 'variable';
928
929
			$stylesheet['variables'] .= "\n\t\t" . '<xsl:' . $element . ' name="' . $name . '"';
930
931
			if (isset($var['xpath']))
932
				$stylesheet['variables'] .= ' select="' . $var['value'] . '"/>';
933
			else
934
				$stylesheet['variables'] .= '>' . (!empty($var['no_cdata_parse']) ? $var['value'] : cdata_parse($var['value'])) . '</xsl:' . $element . '>';
935
		}
936
937
		// The top-level template. Creates the shell of the HTML document.
938
		$stylesheet['html'] = '
939
		<xsl:template match="/*">
940
			<xsl:text disable-output-escaping="yes">&lt;!DOCTYPE html&gt;</xsl:text>
941
			<html>
942
				<head>
943
					<title>
944
						<xsl:value-of select="@title"/>
945
					</title>
946
					<xsl:call-template name="css_js"/>
947
				</head>
948
				<body>
949
					<div id="footerfix">
950
						<div id="header">
951
							<h1 class="forumtitle">
952
								<a id="top">
953
									<xsl:attribute name="href">
954
										<xsl:value-of select="$scripturl"/>
955
									</xsl:attribute>
956
									<xsl:value-of select="@forum-name"/>
957
								</a>
958
							</h1>
959
						</div>
960
						<div id="wrapper">
961
							<div id="upper_section">
962
								<div id="inner_section">
963
									<div id="inner_wrap">
964
										<div class="user">
965
											<time>
966
												<xsl:attribute name="datetime">
967
													<xsl:value-of select="@generated-date-UTC"/>
968
												</xsl:attribute>
969
												<xsl:value-of select="@generated-date-localized"/>
970
											</time>
971
										</div>
972
										<hr class="clear"/>
973
									</div>
974
								</div>
975
							</div>
976
977
							<xsl:call-template name="content_section"/>
978
979
						</div>
980
					</div>
981
					<div id="footer">
982
						<div class="inner_wrap">
983
							<ul>
984
								<li class="floatright">
985
									<a>
986
										<xsl:attribute name="href">
987
											<xsl:value-of select="concat($scripturl, \'?action=help\')"/>
988
										</xsl:attribute>
989
										<xsl:value-of select="$txt_help"/>
990
									</a>
991
									<xsl:text> | </xsl:text>
992
									<a>
993
										<xsl:attribute name="href">
994
											<xsl:value-of select="concat($scripturl, \'?action=help;sa=rules\')"/>
995
										</xsl:attribute>
996
										<xsl:value-of select="$txt_terms_rules"/>
997
									</a>
998
									<xsl:text> | </xsl:text>
999
									<a href="#top">
1000
										<xsl:value-of select="$txt_go_up"/>
1001
										<xsl:text> &#9650;</xsl:text>
1002
									</a>
1003
								</li>
1004
								<li class="copyright">
1005
									<xsl:value-of select="$forum_copyright" disable-output-escaping="yes"/>
1006
								</li>
1007
							</ul>
1008
						</div>
1009
					</div>
1010
				</body>
1011
			</html>
1012
		</xsl:template>';
1013
1014
		// Template to show the content of the export file.
1015
		$stylesheet['content_section'] = '
1016
		<xsl:template name="content_section">
1017
			<div id="content_section">
1018
				<div id="main_content_section">
1019
1020
					<div class="cat_bar">
1021
						<h3 class="catbg">
1022
							<xsl:value-of select="@title"/>
1023
						</h3>
1024
					</div>
1025
					<div class="information">
1026
						<h2 class="display_title">
1027
							<xsl:value-of select="@description"/>
1028
						</h2>
1029
					</div>
1030
1031
					<xsl:if test="username">
1032
						<div class="cat_bar">
1033
							<h3 class="catbg">
1034
								<xsl:value-of select="$txt_summary_heading"/>
1035
							</h3>
1036
						</div>
1037
						<div id="profileview" class="roundframe flow_auto noup">
1038
							<xsl:call-template name="summary"/>
1039
						</div>
1040
					</xsl:if>
1041
1042
					<xsl:call-template name="page_index"/>
1043
1044
					<xsl:if test="member_post">
1045
						<div class="cat_bar">
1046
							<h3 class="catbg">
1047
								<xsl:value-of select="$txt_posts_heading"/>
1048
							</h3>
1049
						</div>
1050
						<div id="posts" class="roundframe flow_auto noup">
1051
							<xsl:apply-templates select="member_post" mode="posts"/>
1052
						</div>
1053
					</xsl:if>
1054
1055
					<xsl:if test="personal_message">
1056
						<div class="cat_bar">
1057
							<h3 class="catbg">
1058
								<xsl:value-of select="$txt_personal_messages_heading"/>
1059
							</h3>
1060
						</div>
1061
						<div id="personal_messages" class="roundframe flow_auto noup">
1062
							<xsl:apply-templates select="personal_message" mode="pms"/>
1063
						</div>
1064
					</xsl:if>
1065
1066
					<xsl:call-template name="page_index"/>
1067
1068
				</div>
1069
			</div>
1070
		</xsl:template>';
1071
1072
		// Template for user profile summary
1073
		$stylesheet['summary'] = '
1074
		<xsl:template name="summary">
1075
			<div id="basicinfo">
1076
				<div class="username clear">
1077
					<h4>
1078
						<a>
1079
							<xsl:attribute name="href">
1080
								<xsl:value-of select="link"/>
1081
							</xsl:attribute>
1082
							<xsl:value-of select="name"/>
1083
						</a>
1084
						<xsl:text> </xsl:text>
1085
						<span class="position">
1086
							<xsl:choose>
1087
								<xsl:when test="position">
1088
									<xsl:value-of select="position"/>
1089
								</xsl:when>
1090
								<xsl:otherwise>
1091
									<xsl:value-of select="post_group"/>
1092
								</xsl:otherwise>
1093
							</xsl:choose>
1094
						</span>
1095
					</h4>
1096
				</div>
1097
				<img class="avatar">
1098
					<xsl:attribute name="src">
1099
						<xsl:value-of select="avatar"/>
1100
					</xsl:attribute>
1101
				</img>
1102
			</div>
1103
1104
			<div id="detailedinfo">
1105
				<dl class="settings noborder">
1106
					<xsl:apply-templates mode="detailedinfo"/>
1107
				</dl>
1108
			</div>
1109
		</xsl:template>';
1110
1111
		// Some helper templates for details inside the summary.
1112
		$stylesheet['detail_default'] = '
1113
		<xsl:template match="*" mode="detailedinfo">
1114
			<dt>
1115
				<xsl:value-of select="concat(@label, \':\')"/>
1116
			</dt>
1117
			<dd>
1118
				<xsl:value-of select="." disable-output-escaping="yes"/>
1119
			</dd>
1120
		</xsl:template>';
1121
1122
		$stylesheet['detail_email'] = '
1123
		<xsl:template match="email" mode="detailedinfo">
1124
			<dt>
1125
				<xsl:value-of select="concat(@label, \':\')"/>
1126
			</dt>
1127
			<dd>
1128
				<a>
1129
					<xsl:attribute name="href">
1130
						<xsl:text>mailto:</xsl:text>
1131
						<xsl:value-of select="."/>
1132
					</xsl:attribute>
1133
					<xsl:value-of select="."/>
1134
				</a>
1135
			</dd>
1136
		</xsl:template>';
1137
1138
		$stylesheet['detail_website'] = '
1139
		<xsl:template match="website" mode="detailedinfo">
1140
			<dt>
1141
				<xsl:value-of select="concat(@label, \':\')"/>
1142
			</dt>
1143
			<dd>
1144
				<a>
1145
					<xsl:attribute name="href">
1146
						<xsl:value-of select="link"/>
1147
					</xsl:attribute>
1148
					<xsl:value-of select="title"/>
1149
				</a>
1150
			</dd>
1151
		</xsl:template>';
1152
1153
		$stylesheet['detail_ip'] = '
1154
		<xsl:template match="ip_addresses" mode="detailedinfo">
1155
			<dt>
1156
				<xsl:value-of select="concat(@label, \':\')"/>
1157
			</dt>
1158
			<dd>
1159
				<ul class="nolist">
1160
					<xsl:apply-templates mode="ip_address"/>
1161
				</ul>
1162
			</dd>
1163
		</xsl:template>
1164
		<xsl:template match="*" mode="ip_address">
1165
			<li>
1166
				<xsl:value-of select="."/>
1167
				<xsl:if test="@label and following-sibling">
1168
					<xsl:text> </xsl:text>
1169
					<span>(<xsl:value-of select="@label"/>)</span>
1170
				</xsl:if>
1171
			</li>
1172
		</xsl:template>';
1173
1174
		$stylesheet['detail_not_included'] = '
1175
		<xsl:template match="name|link|avatar|online|member_post|personal_message" mode="detailedinfo"/>';
1176
1177
		// Template for printing a single post
1178
		$stylesheet['member_post'] = '
1179
		<xsl:template match="member_post" mode="posts">
1180
			<div>
1181
				<xsl:attribute name="id">
1182
					<xsl:value-of select="concat(\'member_post_\', id)"/>
1183
				</xsl:attribute>
1184
				<xsl:attribute name="class">
1185
					<xsl:choose>
1186
						<xsl:when test="approval_status = 1">
1187
							<xsl:text>windowbg</xsl:text>
1188
						</xsl:when>
1189
						<xsl:otherwise>
1190
							<xsl:text>approvebg</xsl:text>
1191
						</xsl:otherwise>
1192
					</xsl:choose>
1193
				</xsl:attribute>
1194
1195
				<div class="post_wrapper">
1196
					<div class="poster">
1197
						<h4>
1198
							<a>
1199
								<xsl:attribute name="href">
1200
									<xsl:value-of select="poster/link"/>
1201
								</xsl:attribute>
1202
								<xsl:value-of select="poster/name"/>
1203
							</a>
1204
						</h4>
1205
						<ul class="user_info">
1206
							<xsl:if test="poster/id = $member_id">
1207
								<xsl:call-template name="own_user_info"/>
1208
							</xsl:if>
1209
							<li>
1210
								<xsl:value-of select="poster/email"/>
1211
							</li>
1212
							<li class="poster_ip">
1213
								<xsl:value-of select="concat(poster/ip/@label, \': \')"/>
1214
								<xsl:value-of select="poster/ip"/>
1215
							</li>
1216
						</ul>
1217
					</div>
1218
1219
					<div class="postarea">
1220
						<div class="flow_hidden">
1221
1222
							<div class="keyinfo">
1223
								<h5>
1224
									<strong>
1225
										<a>
1226
											<xsl:attribute name="href">
1227
												<xsl:value-of select="board/link"/>
1228
											</xsl:attribute>
1229
											<xsl:value-of select="board/name"/>
1230
										</a>
1231
										<xsl:text> / </xsl:text>
1232
										<a>
1233
											<xsl:attribute name="href">
1234
												<xsl:value-of select="link"/>
1235
											</xsl:attribute>
1236
											<xsl:value-of select="subject"/>
1237
										</a>
1238
									</strong>
1239
								</h5>
1240
								<span class="smalltext"><xsl:value-of select="time"/></span>
1241
								<xsl:if test="modified_time">
1242
									<span class="smalltext modified floatright mvisible em">
1243
										<xsl:attribute name="id">
1244
											<xsl:value-of select="concat(\'modified_\', id)"/>
1245
										</xsl:attribute>
1246
										<span class="lastedit">
1247
											<xsl:value-of select="modified_time/@label"/>
1248
										</span>
1249
										<xsl:text>: </xsl:text>
1250
										<xsl:value-of select="modified_time"/>
1251
										<xsl:text>. </xsl:text>
1252
										<xsl:value-of select="modified_by/@label"/>
1253
										<xsl:text>: </xsl:text>
1254
										<xsl:value-of select="modified_by"/>
1255
										<xsl:text>. </xsl:text>
1256
									</span>
1257
								</xsl:if>
1258
							</div>
1259
1260
							<div class="post">
1261
								<div class="inner">
1262
									<xsl:value-of select="body_html" disable-output-escaping="yes"/>
1263
								</div>
1264
								<div class="inner monospace" style="display:none;">
1265
									<xsl:choose>
1266
										<xsl:when test="contains(body/text(), \'[html]\')">
1267
											<xsl:call-template name="bbc_html_splitter">
1268
												<xsl:with-param name="bbc_string" select="body/text()"/>
1269
											</xsl:call-template>
1270
										</xsl:when>
1271
										<xsl:otherwise>
1272
											<xsl:value-of select="body" disable-output-escaping="yes"/>
1273
										</xsl:otherwise>
1274
									</xsl:choose>
1275
								</div>
1276
							</div>
1277
1278
							<xsl:apply-templates select="attachments">
1279
								<xsl:with-param name="post_id" select="id"/>
1280
							</xsl:apply-templates>
1281
1282
							<div class="under_message">
1283
								<ul class="floatleft">
1284
									<xsl:if test="likes > 0">
1285
										<li class="smflikebutton">
1286
											<xsl:attribute name="id">
1287
												<xsl:value-of select="concat(\'msg_\', id, \'_likes\')"/>
1288
											</xsl:attribute>
1289
											<span><span class="main_icons like"></span> <xsl:value-of select="likes"/></span>
1290
										</li>
1291
									</xsl:if>
1292
								</ul>
1293
								<xsl:call-template name="quickbuttons">
1294
									<xsl:with-param name="toggle_target" select="concat(\'member_post_\', id)"/>
1295
								</xsl:call-template>
1296
							</div>
1297
1298
						</div>
1299
					</div>
1300
1301
					<div class="moderatorbar">
1302
						<xsl:if test="poster/id = $member_id">
1303
							<xsl:call-template name="signature"/>
1304
						</xsl:if>
1305
					</div>
1306
1307
				</div>
1308
			</div>
1309
		</xsl:template>';
1310
1311
		// Template for printing a single PM
1312
		$stylesheet['personal_message'] = '
1313
		<xsl:template match="personal_message" mode="pms">
1314
			<div class="windowbg">
1315
				<xsl:attribute name="id">
1316
					<xsl:value-of select="concat(\'personal_message_\', id)"/>
1317
				</xsl:attribute>
1318
1319
				<div class="post_wrapper">
1320
					<div class="poster">
1321
						<h4>
1322
							<a>
1323
								<xsl:attribute name="href">
1324
									<xsl:value-of select="sender/link"/>
1325
								</xsl:attribute>
1326
								<xsl:value-of select="sender/name"/>
1327
							</a>
1328
						</h4>
1329
						<ul class="user_info">
1330
							<xsl:if test="sender/id = $member_id">
1331
								<xsl:call-template name="own_user_info"/>
1332
							</xsl:if>
1333
						</ul>
1334
					</div>
1335
1336
					<div class="postarea">
1337
						<div class="flow_hidden">
1338
1339
							<div class="keyinfo">
1340
								<h5>
1341
									<xsl:attribute name="id">
1342
										<xsl:value-of select="concat(\'subject_\', id)"/>
1343
									</xsl:attribute>
1344
									<xsl:value-of select="subject"/>
1345
								</h5>
1346
								<span class="smalltext">
1347
									<strong>
1348
										<xsl:value-of select="concat(recipient[1]/@label, \': \')"/>
1349
									</strong>
1350
									<xsl:apply-templates select="recipient"/>
1351
								</span>
1352
								<br/>
1353
								<span class="smalltext">
1354
									<strong>
1355
										<xsl:value-of select="concat(sent_date/@label, \': \')"/>
1356
									</strong>
1357
									<time>
1358
										<xsl:attribute name="datetime">
1359
											<xsl:value-of select="sent_date/@UTC"/>
1360
										</xsl:attribute>
1361
										<xsl:value-of select="normalize-space(sent_date)"/>
1362
									</time>
1363
								</span>
1364
							</div>
1365
1366
							<div class="post">
1367
								<div class="inner">
1368
									<xsl:value-of select="body_html" disable-output-escaping="yes"/>
1369
								</div>
1370
								<div class="inner monospace" style="display:none;">
1371
									<xsl:call-template name="bbc_html_splitter">
1372
										<xsl:with-param name="bbc_string" select="body/text()"/>
1373
									</xsl:call-template>
1374
								</div>
1375
							</div>
1376
1377
							<div class="under_message">
1378
								<xsl:call-template name="quickbuttons">
1379
									<xsl:with-param name="toggle_target" select="concat(\'personal_message_\', id)"/>
1380
								</xsl:call-template>
1381
							</div>
1382
1383
						</div>
1384
					</div>
1385
1386
					<div class="moderatorbar">
1387
						<xsl:if test="sender/id = $member_id">
1388
							<xsl:call-template name="signature"/>
1389
						</xsl:if>
1390
					</div>
1391
1392
				</div>
1393
			</div>
1394
		</xsl:template>';
1395
1396
		// A couple of templates to handle attachments
1397
		$stylesheet['attachments'] = '
1398
		<xsl:template match="attachments">
1399
			<xsl:param name="post_id"/>
1400
			<xsl:if test="attachment">
1401
				<div class="attachments">
1402
					<xsl:attribute name="id">
1403
						<xsl:value-of select="concat(\'msg_\', $post_id, \'_footer\')"/>
1404
					</xsl:attribute>
1405
					<xsl:apply-templates/>
1406
				</div>
1407
			</xsl:if>
1408
		</xsl:template>
1409
		<xsl:template match="attachment">
1410
			<div class="attached">
1411
				<div class="attachments_bot">
1412
					<a>
1413
						<xsl:attribute name="href">
1414
							<xsl:value-of select="concat(id, \' - \', name)"/>
1415
						</xsl:attribute>
1416
						<img class="centericon" alt="*">
1417
							<xsl:attribute name="src">
1418
								<xsl:value-of select="concat($themeurl, \'/images/icons/clip.png\')"/>
1419
							</xsl:attribute>
1420
						</img>
1421
						<xsl:text> </xsl:text>
1422
						<xsl:value-of select="name"/>
1423
					</a>
1424
					<br/>
1425
					<xsl:text>(</xsl:text>
1426
					<a class="bbc_link">
1427
						<xsl:attribute name="href">
1428
							<xsl:value-of select="concat($scripturl, \'?action=profile;area=dlattach;u=\', $member_id, \';attach=\', id, \';t=\', $dltoken)"/>
1429
						</xsl:attribute>
1430
						<xsl:value-of select="$txt_download_original"/>
1431
					</a>
1432
					<xsl:text>)</xsl:text>
1433
					<br/>
1434
					<xsl:value-of select="size/@label"/>
1435
					<xsl:text>: </xsl:text>
1436
					<xsl:value-of select="size"/>
1437
					<br/>
1438
					<xsl:value-of select="downloads/@label"/>
1439
					<xsl:text>: </xsl:text>
1440
					<xsl:value-of select="downloads"/>
1441
				</div>
1442
			</div>
1443
		</xsl:template>';
1444
1445
		// Helper template for printing the user's own info next to the post or personal message.
1446
		$stylesheet['own_user_info'] = '
1447
		<xsl:template name="own_user_info">
1448
			<xsl:if test="/*/avatar">
1449
				<li class="avatar">
1450
					<a>
1451
						<xsl:attribute name="href">
1452
							<xsl:value-of select="/*/link"/>
1453
						</xsl:attribute>
1454
						<img class="avatar">
1455
							<xsl:attribute name="src">
1456
								<xsl:value-of select="/*/avatar"/>
1457
							</xsl:attribute>
1458
						</img>
1459
					</a>
1460
				</li>
1461
			</xsl:if>
1462
			<li class="membergroup">
1463
				<xsl:value-of select="/*/position"/>
1464
			</li>
1465
			<xsl:if test="/*/title">
1466
				<li class="title">
1467
					<xsl:value-of select="/*/title"/>
1468
				</li>
1469
			</xsl:if>
1470
			<li class="postgroup">
1471
				<xsl:value-of select="/*/post_group"/>
1472
			</li>
1473
			<li class="postcount">
1474
				<xsl:value-of select="concat(/*/posts/@label, \': \')"/>
1475
				<xsl:value-of select="/*/posts"/>
1476
			</li>
1477
			<xsl:if test="/*/blurb">
1478
				<li class="blurb">
1479
					<xsl:value-of select="/*/blurb"/>
1480
				</li>
1481
			</xsl:if>
1482
		</xsl:template>';
1483
1484
		// Helper template for printing the quickbuttons
1485
		$stylesheet['quickbuttons'] = '
1486
		<xsl:template name="quickbuttons">
1487
			<xsl:param name="toggle_target"/>
1488
			<ul class="quickbuttons quickbuttons_post sf-js-enabled sf-arrows" style="touch-action: pan-y;">
1489
				<li>
1490
					<a>
1491
						<xsl:attribute name="onclick">
1492
							<xsl:text>$(\'#</xsl:text>
1493
							<xsl:value-of select="$toggle_target"/>
1494
							<xsl:text> .inner\').toggle();</xsl:text>
1495
						</xsl:attribute>
1496
						<xsl:value-of select="$txt_view_source_button"/>
1497
					</a>
1498
				</li>
1499
			</ul>
1500
		</xsl:template>';
1501
1502
		// Helper template for printing a signature
1503
		$stylesheet['signature'] = '
1504
		<xsl:template name="signature">
1505
			<xsl:if test="/*/signature">
1506
				<div class="signature">
1507
					<xsl:value-of select="/*/signature" disable-output-escaping="yes"/>
1508
				</div>
1509
			</xsl:if>
1510
		</xsl:template>';
1511
1512
		// Helper template for printing a list of PM recipients
1513
		$stylesheet['recipient'] = '
1514
		<xsl:template match="recipient">
1515
			<a>
1516
				<xsl:attribute name="href">
1517
					<xsl:value-of select="link"/>
1518
				</xsl:attribute>
1519
				<xsl:value-of select="name"/>
1520
			</a>
1521
			<xsl:choose>
1522
				<xsl:when test="following-sibling::recipient">
1523
					<xsl:text>, </xsl:text>
1524
				</xsl:when>
1525
				<xsl:otherwise>
1526
					<xsl:text>. </xsl:text>
1527
				</xsl:otherwise>
1528
			</xsl:choose>
1529
		</xsl:template>';
1530
1531
		// Helper template for special handling of the contents of the [html] BBCode
1532
		$stylesheet['bbc_html'] = '
1533
		<xsl:template name="bbc_html_splitter">
1534
			<xsl:param name="bbc_string"/>
1535
			<xsl:param name="inside_outside" select="outside"/>
1536
			<xsl:choose>
1537
				<xsl:when test="$inside_outside = \'outside\'">
1538
					<xsl:choose>
1539
						<xsl:when test="contains($bbc_string, \'[html]\')">
1540
							<xsl:variable name="following_string">
1541
								<xsl:value-of select="substring-after($bbc_string, \'[html]\')" disable-output-escaping="yes"/>
1542
							</xsl:variable>
1543
							<xsl:value-of select="substring-before($bbc_string, \'[html]\')" disable-output-escaping="yes"/>
1544
							<xsl:text>[html]</xsl:text>
1545
							<xsl:call-template name="bbc_html_splitter">
1546
								<xsl:with-param name="bbc_string" select="$following_string"/>
1547
								<xsl:with-param name="inside_outside" select="inside"/>
1548
							</xsl:call-template>
1549
						</xsl:when>
1550
						<xsl:otherwise>
1551
							<xsl:value-of select="$bbc_string" disable-output-escaping="yes"/>
1552
						</xsl:otherwise>
1553
					</xsl:choose>
1554
				</xsl:when>
1555
				<xsl:otherwise>
1556
					<xsl:choose>
1557
						<xsl:when test="contains($bbc_string, \'[/html]\')">
1558
							<xsl:variable name="following_string">
1559
								<xsl:value-of select="substring-after($bbc_string, \'[/html]\')" disable-output-escaping="yes"/>
1560
							</xsl:variable>
1561
							<xsl:value-of select="substring-before($bbc_string, \'[/html]\')" disable-output-escaping="no"/>
1562
							<xsl:text>[/html]</xsl:text>
1563
							<xsl:call-template name="bbc_html_splitter">
1564
								<xsl:with-param name="bbc_string" select="$following_string"/>
1565
								<xsl:with-param name="inside_outside" select="outside"/>
1566
							</xsl:call-template>
1567
						</xsl:when>
1568
						<xsl:otherwise>
1569
							<xsl:value-of select="$bbc_string" disable-output-escaping="no"/>
1570
						</xsl:otherwise>
1571
					</xsl:choose>
1572
				</xsl:otherwise>
1573
			</xsl:choose>
1574
		</xsl:template>';
1575
1576
		// Helper templates to build a page index
1577
		$stylesheet['page_index'] = '
1578
		<xsl:template name="page_index">
1579
			<xsl:variable name="current_page" select="/*/@page"/>
1580
			<xsl:variable name="prev_page" select="/*/@page - 1"/>
1581
			<xsl:variable name="next_page" select="/*/@page + 1"/>
1582
1583
			<div class="pagesection">
1584
				<div class="pagelinks floatleft">
1585
1586
					<span class="pages">
1587
						<xsl:value-of select="$txt_pages"/>
1588
					</span>
1589
1590
					<xsl:if test="$current_page &gt; 1">
1591
						<a class="nav_page">
1592
							<xsl:attribute name="href">
1593
								<xsl:value-of select="concat($dlfilename, \'_\', $prev_page, \'.\', $ext)"/>
1594
							</xsl:attribute>
1595
							<span class="main_icons previous_page"></span>
1596
						</a>
1597
					</xsl:if>
1598
1599
					<xsl:call-template name="page_links"/>
1600
1601
					<xsl:if test="$current_page &lt; $last_page">
1602
						<a class="nav_page">
1603
							<xsl:attribute name="href">
1604
								<xsl:value-of select="concat($dlfilename, \'_\', $next_page, \'.\', $ext)"/>
1605
							</xsl:attribute>
1606
							<span class="main_icons next_page"></span>
1607
						</a>
1608
					</xsl:if>
1609
				</div>
1610
			</div>
1611
		</xsl:template>
1612
1613
		<xsl:template name="page_links">
1614
			<xsl:param name="page_num" select="1"/>
1615
			<xsl:variable name="current_page" select="/*/@page"/>
1616
			<xsl:variable name="prev_page" select="/*/@page - 1"/>
1617
			<xsl:variable name="next_page" select="/*/@page + 1"/>
1618
1619
			<xsl:choose>
1620
				<xsl:when test="$page_num = $current_page">
1621
					<span class="current_page">
1622
						<xsl:value-of select="$page_num"/>
1623
					</span>
1624
				</xsl:when>
1625
				<xsl:when test="$page_num = 1 or $page_num = ($current_page - 1) or $page_num = ($current_page + 1) or $page_num = $last_page">
1626
					<a class="nav_page">
1627
						<xsl:attribute name="href">
1628
							<xsl:value-of select="concat($dlfilename, \'_\', $page_num, \'.\', $ext)"/>
1629
						</xsl:attribute>
1630
						<xsl:value-of select="$page_num"/>
1631
					</a>
1632
				</xsl:when>
1633
				<xsl:when test="$page_num = 2 or $page_num = ($current_page + 2)">
1634
					<span class="expand_pages" onclick="$(\'.nav_page\').removeClass(\'hidden\'); $(\'.expand_pages\').hide();"> ... </span>
1635
					<a class="nav_page hidden">
1636
						<xsl:attribute name="href">
1637
							<xsl:value-of select="concat($dlfilename, \'_\', $page_num, \'.\', $ext)"/>
1638
						</xsl:attribute>
1639
						<xsl:value-of select="$page_num"/>
1640
					</a>
1641
				</xsl:when>
1642
				<xsl:otherwise>
1643
					<a class="nav_page hidden">
1644
						<xsl:attribute name="href">
1645
							<xsl:value-of select="concat($dlfilename, \'_\', $page_num, \'.\', $ext)"/>
1646
						</xsl:attribute>
1647
						<xsl:value-of select="$page_num"/>
1648
					</a>
1649
				</xsl:otherwise>
1650
			</xsl:choose>
1651
1652
			<xsl:text> </xsl:text>
1653
1654
			<xsl:if test="$page_num &lt; $last_page">
1655
				<xsl:call-template name="page_links">
1656
					<xsl:with-param name="page_num" select="$page_num + 1"/>
1657
				</xsl:call-template>
1658
			</xsl:if>
1659
		</xsl:template>';
1660
1661
		// Template to insert CSS and JavaScript
1662
		$stylesheet['css_js'] = '
1663
		<xsl:template name="css_js">';
1664
1665
		export_load_css_js();
1666
1667
		if (!empty($context['export_css_files']))
1668
		{
1669
			foreach ($context['export_css_files'] as $css_file)
1670
			{
1671
				$stylesheet['css_js'] .= '
1672
				<link rel="stylesheet">
1673
					<xsl:attribute name="href">
1674
						<xsl:text>' . $css_file['fileUrl'] . '</xsl:text>
1675
					</xsl:attribute>';
1676
1677
				if (!empty($css_file['options']['attributes']))
1678
				{
1679
					foreach ($css_file['options']['attributes'] as $key => $value)
1680
						$stylesheet['css_js'] .= '
1681
					<xsl:attribute name="' . $key . '">
1682
						<xsl:text>' . (is_bool($value) ? $key : $value) . '</xsl:text>
1683
					</xsl:attribute>';
1684
				}
1685
1686
				$stylesheet['css_js'] .= '
1687
				</link>';
1688
			}
1689
		}
1690
1691
		if (!empty($context['export_css_header']))
1692
		{
1693
			$stylesheet['css_js'] .=  '
1694
			<style><![CDATA[' . "\n" . implode("\n", $context['export_css_header']) . "\n" . ']]>
1695
			</style>';
1696
		}
1697
1698
		if (!empty($context['export_javascript_vars']))
1699
		{
1700
			$stylesheet['css_js'] .=  '
1701
			<script><![CDATA[';
1702
1703
			foreach ($context['export_javascript_vars'] as $var => $val)
1704
				$stylesheet['css_js'] .= "\nvar " . $var . (!empty($val) ? ' = ' . $val : '') . ';';
1705
1706
			$stylesheet['css_js'] .= "\n" . ']]>
1707
			</script>';
1708
		}
1709
1710
		if (!empty($context['export_javascript_files']))
1711
		{
1712
			foreach ($context['export_javascript_files'] as $js_file)
1713
			{
1714
				$stylesheet['css_js'] .= '
1715
				<script>
1716
					<xsl:attribute name="src">
1717
						<xsl:text>' . $js_file['fileUrl'] . '</xsl:text>
1718
					</xsl:attribute>';
1719
1720
				if (!empty($js_file['options']['attributes']))
1721
				{
1722
					foreach ($js_file['options']['attributes'] as $key => $value)
1723
						$stylesheet['css_js'] .= '
1724
					<xsl:attribute name="' . $key . '">
1725
						<xsl:text>' . (is_bool($value) ? $key : $value) . '</xsl:text>
1726
					</xsl:attribute>';
1727
				}
1728
1729
				$stylesheet['css_js'] .= '
1730
				</script>';
1731
			}
1732
		}
1733
1734
		if (!empty($context['export_javascript_inline']['standard']))
1735
		{
1736
			$stylesheet['css_js'] .=  '
1737
			<script><![CDATA[' . "\n" . implode("\n", $context['export_javascript_inline']['standard']) . "\n" . ']]>
1738
			</script>';
1739
		}
1740
1741
		if (!empty($context['export_javascript_inline']['defer']))
1742
		{
1743
			$stylesheet['css_js'] .= '
1744
			<script><![CDATA[' . "\n" . 'window.addEventListener("DOMContentLoaded", function() {';
1745
1746
			$stylesheet['css_js'] .= "\n\t" . str_replace("\n", "\n\t", implode("\n", $context['export_javascript_inline']['defer']));
1747
1748
			$stylesheet['css_js'] .= "\n" . '});'. "\n" . ']]>
1749
			</script>';
1750
		}
1751
1752
		$stylesheet['css_js'] .= '
1753
		</xsl:template>';
1754
1755
		// End of the XSLT stylesheet
1756
		$stylesheet['footer'] = ($format == 'XML_XSLT' ? "\t" : '') . '</xsl:stylesheet>';
1757
	}
1758
1759
	// Let mods adjust the XSLT stylesheet.
1760
	call_integration_hook('integrate_export_xslt_stylesheet', array(&$stylesheet, $format));
1761
1762
	// Remember for later.
1763
	$xslt_key = isset($xslt_key) ? $xslt_key : $smcFunc['json_encode'](array($format, $uid, $xslt_variables));
1764
	$xslts[$xslt_key] = array('stylesheet' => implode("\n", (array) $stylesheet), 'doctype' => $doctype);
1765
1766
	return $xslts[$xslt_key];
1767
}
1768
1769
/**
1770
 * Loads and prepares CSS and JavaScript for insertion into an XSLT stylesheet.
1771
 */
1772
function export_load_css_js()
1773
{
1774
	global $context, $modSettings, $sourcedir, $smcFunc, $user_info;
1775
1776
	// If we're not running a background task, we need to preserve any existing CSS and JavaScript.
1777
	if (SMF != 'BACKGROUND')
0 ignored issues
show
introduced by
The condition SMF != 'BACKGROUND' is always true.
Loading history...
1778
	{
1779
		foreach (array('css_files', 'css_header', 'javascript_vars', 'javascript_files', 'javascript_inline') as $var)
1780
		{
1781
			if (isset($context[$var]))
1782
				$context['real_' . $var] = $context[$var];
1783
1784
			if ($var == 'javascript_inline')
1785
			{
1786
				foreach ($context[$var] as $key => $value)
1787
					$context[$var][$key] = array();
1788
			}
1789
			else
1790
				$context[$var] = array();
1791
		}
1792
	}
1793
	// Autoloading is unavailable for background tasks, so we have to do things the hard way...
1794
	else
1795
	{
1796
		if (!empty($modSettings['minimize_files']) && (!class_exists('MatthiasMullie\\Minify\\CSS') || !class_exists('MatthiasMullie\\Minify\\JS')))
1797
		{
1798
			// Include, not require, because minimization is nice to have but not vital here.
1799
			include_once(implode(DIRECTORY_SEPARATOR, array($sourcedir, 'minify', 'src', 'Exception.php')));
1800
			include_once(implode(DIRECTORY_SEPARATOR, array($sourcedir, 'minify', 'src', 'Exceptions', 'BasicException.php')));
1801
			include_once(implode(DIRECTORY_SEPARATOR, array($sourcedir, 'minify', 'src', 'Exceptions', 'FileImportException.php')));
1802
			include_once(implode(DIRECTORY_SEPARATOR, array($sourcedir, 'minify', 'src', 'Exceptions', 'IOException.php')));
1803
1804
			include_once(implode(DIRECTORY_SEPARATOR, array($sourcedir, 'minify', 'src', 'Minify.php')));
1805
			include_once(implode(DIRECTORY_SEPARATOR, array($sourcedir, 'minify', 'path-converter', 'src', 'Converter.php')));
1806
1807
			include_once(implode(DIRECTORY_SEPARATOR, array($sourcedir, 'minify', 'src', 'CSS.php')));
1808
			include_once(implode(DIRECTORY_SEPARATOR, array($sourcedir, 'minify', 'src', 'JS.php')));
1809
1810
			if (!class_exists('MatthiasMullie\\Minify\\CSS') || !class_exists('MatthiasMullie\\Minify\\JS'))
1811
				$modSettings['minimize_files'] = false;
1812
		}
1813
	}
1814
1815
	// Load our standard CSS files.
1816
	loadCSSFile('index.css', array('minimize' => true, 'order_pos' => 1), 'smf_index');
1817
	loadCSSFile('responsive.css', array('force_current' => false, 'validate' => true, 'minimize' => true, 'order_pos' => 9000), 'smf_responsive');
1818
1819
	if ($context['right_to_left'])
1820
		loadCSSFile('rtl.css', array('order_pos' => 4000), 'smf_rtl');
1821
1822
	// In case any mods added relevant CSS.
1823
	call_integration_hook('integrate_pre_css_output');
1824
1825
	// This next chunk mimics some of template_css()
1826
	$css_to_minify = array();
1827
	$normal_css_files = array();
1828
1829
	usort($context['css_files'], function ($a, $b)
1830
	{
1831
		return $a['options']['order_pos'] < $b['options']['order_pos'] ? -1 : ($a['options']['order_pos'] > $b['options']['order_pos'] ? 1 : 0);
1832
	});
1833
	foreach ($context['css_files'] as $css_file)
1834
	{
1835
		if (!isset($css_file['options']['minimize']))
1836
			$css_file['options']['minimize'] = true;
1837
1838
		if (!empty($css_file['options']['minimize']) && !empty($modSettings['minimize_files']))
1839
			$css_to_minify[] = $css_file;
1840
		else
1841
			$normal_css_files[] = $css_file;
1842
	}
1843
1844
	$minified_css_files = !empty($css_to_minify) ? custMinify($css_to_minify, 'css') : array();
1845
1846
	$context['css_files'] = array();
1847
	foreach (array_merge($minified_css_files, $normal_css_files) as $css_file)
1848
	{
1849
		// Embed the CSS in a <style> element if possible, since exports are supposed to be standalone files.
1850
		if (file_exists($css_file['filePath']))
1851
			$context['css_header'][] = file_get_contents($css_file['filePath']);
1852
1853
		elseif (!empty($css_file['fileUrl']))
1854
			$context['css_files'][] = $css_file;
1855
	}
1856
1857
	// Next, we need to do for JavaScript what we just did for CSS.
1858
	loadJavaScriptFile('https://ajax.googleapis.com/ajax/libs/jquery/' . JQUERY_VERSION . '/jquery.min.js', array('external' => true), 'smf_jquery');
1859
1860
	// There might be JavaScript that we need to add in order to support custom BBC or something.
1861
	call_integration_hook('integrate_pre_javascript_output', array(false));
1862
	call_integration_hook('integrate_pre_javascript_output', array(true));
1863
1864
	$js_to_minify = array();
1865
	$all_js_files = array();
1866
1867
	foreach ($context['javascript_files'] as $js_file)
1868
	{
1869
		if (!empty($js_file['options']['minimize']) && !empty($modSettings['minimize_files']))
1870
		{
1871
			if (!empty($js_file['options']['async']))
1872
				$js_to_minify['async'][] = $js_file;
1873
1874
			elseif (!empty($js_file['options']['defer']))
1875
				$js_to_minify['defer'][] = $js_file;
1876
1877
			else
1878
				$js_to_minify['standard'][] = $js_file;
1879
		}
1880
		else
1881
			$all_js_files[] = $js_file;
1882
	}
1883
1884
	$context['javascript_files'] = array();
1885
	foreach ($js_to_minify as $type => $js_files)
1886
	{
1887
		if (!empty($js_files))
1888
		{
1889
			$minified_js_files = custMinify($js_files, 'js');
1890
			$all_js_files = array_merge($all_js_files, $minified_js_files);
1891
		}
1892
	}
1893
1894
	foreach ($all_js_files as $js_file)
1895
	{
1896
		// As with the CSS, embed whatever JavaScript we can.
1897
		if (file_exists($js_file['filePath']))
1898
			$context['javascript_inline'][(!empty($js_file['options']['defer']) ? 'defer' : 'standard')][] = file_get_contents($js_file['filePath']);
1899
1900
		elseif (!empty($js_file['fileUrl']))
1901
			$context['javascript_files'][] = $js_file;
1902
	}
1903
1904
	// We need to embed the smiley images, too. To save space, we store the image data in JS variables.
1905
	$smiley_mimetypes = array(
1906
		'gif' => 'image/gif',
1907
		'png' => 'image/png',
1908
		'jpg' => 'image/jpeg',
1909
		'jpeg' => 'image/jpeg',
1910
		'tiff' => 'image/tiff',
1911
		'svg' => 'image/svg+xml',
1912
	);
1913
1914
	foreach (glob(implode(DIRECTORY_SEPARATOR, array($modSettings['smileys_dir'], $user_info['smiley_set'], '*.*'))) as $smiley_file)
1915
	{
1916
		$pathinfo = pathinfo($smiley_file);
1917
1918
		if (!isset($smiley_mimetypes[$pathinfo['extension']]))
1919
			continue;
1920
1921
		$var = implode('_', array('smf', 'smiley', $pathinfo['filename'], $pathinfo['extension']));
1922
1923
		if (!isset($context['javascript_vars'][$var]))
1924
			$context['javascript_vars'][$var] = '\'data:' . $smiley_mimetypes[$pathinfo['extension']] . ';base64,' . base64_encode(file_get_contents($smiley_file)) . '\'';
1925
	}
1926
1927
	$context['javascript_inline']['defer'][] = implode("\n", array(
1928
		'$("img.smiley").each(function() {',
1929
		'	var data_uri_var = $(this).attr("src").replace(/.*\/(\w+)\.(\w+)$/, "smf_smiley_$1_$2");',
1930
		'	$(this).attr("src", window[data_uri_var]);',
1931
		'});',
1932
	));
1933
1934
	// Now move everything to the special export version of these arrays.
1935
	foreach (array('css_files', 'css_header', 'javascript_vars', 'javascript_files', 'javascript_inline') as $var)
1936
	{
1937
		if (isset($context[$var]))
1938
			$context['export_' . $var] = $context[$var];
1939
1940
		unset($context[$var]);
1941
	}
1942
1943
	// Finally, restore the real values.
1944
	if (SMF !== 'BACKGROUND')
0 ignored issues
show
introduced by
The condition SMF !== 'BACKGROUND' is always true.
Loading history...
1945
	{
1946
		foreach (array('css_files', 'css_header', 'javascript_vars', 'javascript_files', 'javascript_inline') as $var)
1947
		{
1948
			if (isset($context['real_' . $var]))
1949
				$context[$var] = $context['real_' . $var];
1950
1951
			unset($context['real_' . $var]);
1952
		}
1953
	}
1954
}
1955
1956
?>