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