Completed
Push — release-2.1 ( 8364ab...05f921 )
by Mathias
08:23
created
Sources/ManageMembers.php 1 patch
Braces   +158 added lines, -116 removed lines patch added patch discarded remove patch
@@ -13,8 +13,9 @@  discard block
 block discarded – undo
13 13
  * @version 2.1 Beta 3
14 14
  */
15 15
 
16
-if (!defined('SMF'))
16
+if (!defined('SMF')) {
17 17
 	die('No direct access...');
18
+}
18 19
 
19 20
 /**
20 21
  * The main entrance point for the Manage Members screen.
@@ -62,16 +63,18 @@  discard block
 block discarded – undo
62 63
 	$context['activation_numbers'] = array();
63 64
 	$context['awaiting_activation'] = 0;
64 65
 	$context['awaiting_approval'] = 0;
65
-	while ($row = $smcFunc['db_fetch_assoc']($request))
66
-		$context['activation_numbers'][$row['is_activated']] = $row['total_members'];
66
+	while ($row = $smcFunc['db_fetch_assoc']($request)) {
67
+			$context['activation_numbers'][$row['is_activated']] = $row['total_members'];
68
+	}
67 69
 	$smcFunc['db_free_result']($request);
68 70
 
69 71
 	foreach ($context['activation_numbers'] as $activation_type => $total_members)
70 72
 	{
71
-		if (in_array($activation_type, array(0, 2)))
72
-			$context['awaiting_activation'] += $total_members;
73
-		elseif (in_array($activation_type, array(3, 4, 5)))
74
-			$context['awaiting_approval'] += $total_members;
73
+		if (in_array($activation_type, array(0, 2))) {
74
+					$context['awaiting_activation'] += $total_members;
75
+		} elseif (in_array($activation_type, array(3, 4, 5))) {
76
+					$context['awaiting_approval'] += $total_members;
77
+		}
75 78
 	}
76 79
 
77 80
 	// For the page header... do we show activation?
@@ -124,8 +127,9 @@  discard block
 block discarded – undo
124 127
 	}
125 128
 	if (!$context['show_approve'] && ($_REQUEST['sa'] != 'browse' || $_REQUEST['type'] != 'approve'))
126 129
 	{
127
-		if (!$context['show_activate'] && ($_REQUEST['sa'] != 'browse' || $_REQUEST['type'] != 'activate'))
128
-			$context['tabs']['search']['is_last'] = true;
130
+		if (!$context['show_activate'] && ($_REQUEST['sa'] != 'browse' || $_REQUEST['type'] != 'activate')) {
131
+					$context['tabs']['search']['is_last'] = true;
132
+		}
129 133
 		unset($context['tabs']['approve']);
130 134
 	}
131 135
 
@@ -157,8 +161,9 @@  discard block
 block discarded – undo
157 161
 		foreach ($_POST['delete'] as $key => $value)
158 162
 		{
159 163
 			// Don't delete yourself, idiot.
160
-			if ($value != $user_info['id'])
161
-				$delete[$key] = (int) $value;
164
+			if ($value != $user_info['id']) {
165
+							$delete[$key] = (int) $value;
166
+			}
162 167
 		}
163 168
 
164 169
 		if (!empty($delete))
@@ -194,17 +199,18 @@  discard block
 block discarded – undo
194 199
 		);
195 200
 		while ($row = $smcFunc['db_fetch_assoc']($request))
196 201
 		{
197
-			if ($row['min_posts'] == -1)
198
-				$context['membergroups'][] = array(
202
+			if ($row['min_posts'] == -1) {
203
+							$context['membergroups'][] = array(
199 204
 					'id' => $row['id_group'],
200 205
 					'name' => $row['group_name'],
201 206
 					'can_be_additional' => true
202 207
 				);
203
-			else
204
-				$context['postgroups'][] = array(
208
+			} else {
209
+							$context['postgroups'][] = array(
205 210
 					'id' => $row['id_group'],
206 211
 					'name' => $row['group_name']
207 212
 				);
213
+			}
208 214
 		}
209 215
 		$smcFunc['db_free_result']($request);
210 216
 
@@ -268,14 +274,15 @@  discard block
 block discarded – undo
268 274
 		call_integration_hook('integrate_view_members_params', array(&$params));
269 275
 
270 276
 		$search_params = array();
271
-		if ($context['sub_action'] == 'query' && !empty($_REQUEST['params']) && empty($_POST['types']))
272
-			$search_params = smf_json_decode(base64_decode($_REQUEST['params']), true);
273
-		elseif (!empty($_POST))
277
+		if ($context['sub_action'] == 'query' && !empty($_REQUEST['params']) && empty($_POST['types'])) {
278
+					$search_params = smf_json_decode(base64_decode($_REQUEST['params']), true);
279
+		} elseif (!empty($_POST))
274 280
 		{
275 281
 			$search_params['types'] = $_POST['types'];
276
-			foreach ($params as $param_name => $param_info)
277
-				if (isset($_POST[$param_name]))
282
+			foreach ($params as $param_name => $param_info) {
283
+							if (isset($_POST[$param_name]))
278 284
 					$search_params[$param_name] = $_POST[$param_name];
285
+			}
279 286
 		}
280 287
 
281 288
 		$search_url_params = isset($search_params) ? base64_encode(json_encode($search_params)) : null;
@@ -288,18 +295,21 @@  discard block
 block discarded – undo
288 295
 		foreach ($params as $param_name => $param_info)
289 296
 		{
290 297
 			// Not filled in?
291
-			if (!isset($search_params[$param_name]) || $search_params[$param_name] === '')
292
-				continue;
298
+			if (!isset($search_params[$param_name]) || $search_params[$param_name] === '') {
299
+							continue;
300
+			}
293 301
 
294 302
 			// Make sure numeric values are really numeric.
295
-			if (in_array($param_info['type'], array('int', 'age')))
296
-				$search_params[$param_name] = (int) $search_params[$param_name];
303
+			if (in_array($param_info['type'], array('int', 'age'))) {
304
+							$search_params[$param_name] = (int) $search_params[$param_name];
305
+			}
297 306
 			// Date values have to match the specified format.
298 307
 			elseif ($param_info['type'] == 'date')
299 308
 			{
300 309
 				// Check if this date format is valid.
301
-				if (preg_match('/^\d{4}-\d{1,2}-\d{1,2}$/', $search_params[$param_name]) == 0)
302
-					continue;
310
+				if (preg_match('/^\d{4}-\d{1,2}-\d{1,2}$/', $search_params[$param_name]) == 0) {
311
+									continue;
312
+				}
303 313
 
304 314
 				$search_params[$param_name] = strtotime($search_params[$param_name]);
305 315
 			}
@@ -308,8 +318,9 @@  discard block
 block discarded – undo
308 318
 			if (!empty($param_info['range']))
309 319
 			{
310 320
 				// Default to '=', just in case...
311
-				if (empty($range_trans[$search_params['types'][$param_name]]))
312
-					$search_params['types'][$param_name] = '=';
321
+				if (empty($range_trans[$search_params['types'][$param_name]])) {
322
+									$search_params['types'][$param_name] = '=';
323
+				}
313 324
 
314 325
 				// Handle special case 'age'.
315 326
 				if ($param_info['type'] == 'age')
@@ -337,29 +348,30 @@  discard block
 block discarded – undo
337 348
 				elseif ($param_info['type'] == 'date' && $search_params['types'][$param_name] == '=')
338 349
 				{
339 350
 					$query_parts[] = $param_info['db_fields'][0] . ' > ' . $search_params[$param_name] . ' AND ' . $param_info['db_fields'][0] . ' < ' . ($search_params[$param_name] + 86400);
351
+				} else {
352
+									$query_parts[] = $param_info['db_fields'][0] . ' ' . $range_trans[$search_params['types'][$param_name]] . ' ' . $search_params[$param_name];
340 353
 				}
341
-				else
342
-					$query_parts[] = $param_info['db_fields'][0] . ' ' . $range_trans[$search_params['types'][$param_name]] . ' ' . $search_params[$param_name];
343 354
 			}
344 355
 			// Checkboxes.
345 356
 			elseif ($param_info['type'] == 'checkbox')
346 357
 			{
347 358
 				// Each checkbox or no checkbox at all is checked -> ignore.
348
-				if (!is_array($search_params[$param_name]) || count($search_params[$param_name]) == 0 || count($search_params[$param_name]) == count($param_info['values']))
349
-					continue;
359
+				if (!is_array($search_params[$param_name]) || count($search_params[$param_name]) == 0 || count($search_params[$param_name]) == count($param_info['values'])) {
360
+									continue;
361
+				}
350 362
 
351 363
 				$query_parts[] = ($param_info['db_fields'][0]) . ' IN ({array_string:' . $param_name . '_check})';
352 364
 				$where_params[$param_name . '_check'] = $search_params[$param_name];
353
-			}
354
-			else
365
+			} else
355 366
 			{
356 367
 				// Replace the wildcard characters ('*' and '?') into MySQL ones.
357 368
 				$parameter = strtolower(strtr($smcFunc['htmlspecialchars']($search_params[$param_name], ENT_QUOTES), array('%' => '\%', '_' => '\_', '*' => '%', '?' => '_')));
358 369
 
359
-				if ($smcFunc['db_case_sensitive'])
360
-					$query_parts[] = '(LOWER(' . implode(') LIKE {string:' . $param_name . '_normal} OR LOWER(', $param_info['db_fields']) . ') LIKE {string:' . $param_name . '_normal})';
361
-				else
362
-					$query_parts[] = '(' . implode(' LIKE {string:' . $param_name . '_normal} OR ', $param_info['db_fields']) . ' LIKE {string:' . $param_name . '_normal})';
370
+				if ($smcFunc['db_case_sensitive']) {
371
+									$query_parts[] = '(LOWER(' . implode(') LIKE {string:' . $param_name . '_normal} OR LOWER(', $param_info['db_fields']) . ') LIKE {string:' . $param_name . '_normal})';
372
+				} else {
373
+									$query_parts[] = '(' . implode(' LIKE {string:' . $param_name . '_normal} OR ', $param_info['db_fields']) . ' LIKE {string:' . $param_name . '_normal})';
374
+				}
363 375
 				$where_params[$param_name . '_normal'] = '%' . $parameter . '%';
364 376
 			}
365 377
 		}
@@ -375,16 +387,18 @@  discard block
 block discarded – undo
375 387
 		}
376 388
 
377 389
 		// Additional membergroups (these are only relevant if not all primary groups where selected!).
378
-		if (!empty($search_params['membergroups'][2]) && (empty($search_params['membergroups'][1]) || count($context['membergroups']) != count($search_params['membergroups'][1])))
379
-			foreach ($search_params['membergroups'][2] as $mg)
390
+		if (!empty($search_params['membergroups'][2]) && (empty($search_params['membergroups'][1]) || count($context['membergroups']) != count($search_params['membergroups'][1]))) {
391
+					foreach ($search_params['membergroups'][2] as $mg)
380 392
 			{
381 393
 				$mg_query_parts[] = 'FIND_IN_SET({int:add_group_' . $mg . '}, mem.additional_groups) != 0';
394
+		}
382 395
 				$where_params['add_group_' . $mg] = $mg;
383 396
 			}
384 397
 
385 398
 		// Combine the one or two membergroup parts into one query part linked with an OR.
386
-		if (!empty($mg_query_parts))
387
-			$query_parts[] = '(' . implode(' OR ', $mg_query_parts) . ')';
399
+		if (!empty($mg_query_parts)) {
400
+					$query_parts[] = '(' . implode(' OR ', $mg_query_parts) . ')';
401
+		}
388 402
 
389 403
 		// Get all selected post count related membergroups.
390 404
 		if (!empty($search_params['postgroups']) && count($search_params['postgroups']) != count($context['postgroups']))
@@ -396,9 +410,9 @@  discard block
 block discarded – undo
396 410
 		// Construct the where part of the query.
397 411
 		$where = empty($query_parts) ? '1=1' : implode('
398 412
 			AND ', $query_parts);
413
+	} else {
414
+			$search_url_params = null;
399 415
 	}
400
-	else
401
-		$search_url_params = null;
402 416
 
403 417
 	// Construct the additional URL part with the query info in it.
404 418
 	$context['params_url'] = $context['sub_action'] == 'query' ? ';sa=query;params=' . $search_url_params : '';
@@ -521,28 +535,32 @@  discard block
 block discarded – undo
521 535
 					'function' => function($rowData) use ($txt)
522 536
 					{
523 537
 						// Calculate number of days since last online.
524
-						if (empty($rowData['last_login']))
525
-							$difference = $txt['never'];
526
-						else
538
+						if (empty($rowData['last_login'])) {
539
+													$difference = $txt['never'];
540
+						} else
527 541
 						{
528 542
 							$num_days_difference = jeffsdatediff($rowData['last_login']);
529 543
 
530 544
 							// Today.
531
-							if (empty($num_days_difference))
532
-								$difference = $txt['viewmembers_today'];
545
+							if (empty($num_days_difference)) {
546
+															$difference = $txt['viewmembers_today'];
547
+							}
533 548
 
534 549
 							// Yesterday.
535
-							elseif ($num_days_difference == 1)
536
-								$difference = sprintf('1 %1$s', $txt['viewmembers_day_ago']);
550
+							elseif ($num_days_difference == 1) {
551
+															$difference = sprintf('1 %1$s', $txt['viewmembers_day_ago']);
552
+							}
537 553
 
538 554
 							// X days ago.
539
-							else
540
-								$difference = sprintf('%1$d %2$s', $num_days_difference, $txt['viewmembers_days_ago']);
555
+							else {
556
+															$difference = sprintf('%1$d %2$s', $num_days_difference, $txt['viewmembers_days_ago']);
557
+							}
541 558
 						}
542 559
 
543 560
 						// Show it in italics if they're not activated...
544
-						if ($rowData['is_activated'] % 10 != 1)
545
-							$difference = sprintf('<em title="%1$s">%2$s</em>', $txt['not_activated'], $difference);
561
+						if ($rowData['is_activated'] % 10 != 1) {
562
+													$difference = sprintf('<em title="%1$s">%2$s</em>', $txt['not_activated'], $difference);
563
+						}
546 564
 
547 565
 						return $difference;
548 566
 					},
@@ -594,8 +612,9 @@  discard block
 block discarded – undo
594 612
 	);
595 613
 
596 614
 	// Without enough permissions, don't show 'delete members' checkboxes.
597
-	if (!allowedTo('profile_remove_any'))
598
-		unset($listOptions['cols']['check'], $listOptions['form'], $listOptions['additional_rows']);
615
+	if (!allowedTo('profile_remove_any')) {
616
+			unset($listOptions['cols']['check'], $listOptions['form'], $listOptions['additional_rows']);
617
+	}
599 618
 
600 619
 	require_once($sourcedir . '/Subs-List.php');
601 620
 	createList($listOptions);
@@ -638,17 +657,18 @@  discard block
 block discarded – undo
638 657
 	);
639 658
 	while ($row = $smcFunc['db_fetch_assoc']($request))
640 659
 	{
641
-		if ($row['min_posts'] == -1)
642
-			$context['membergroups'][] = array(
660
+		if ($row['min_posts'] == -1) {
661
+					$context['membergroups'][] = array(
643 662
 				'id' => $row['id_group'],
644 663
 				'name' => $row['group_name'],
645 664
 				'can_be_additional' => true
646 665
 			);
647
-		else
648
-			$context['postgroups'][] = array(
666
+		} else {
667
+					$context['postgroups'][] = array(
649 668
 				'id' => $row['id_group'],
650 669
 				'name' => $row['group_name']
651 670
 			);
671
+		}
652 672
 	}
653 673
 	$smcFunc['db_free_result']($request);
654 674
 
@@ -675,8 +695,9 @@  discard block
 block discarded – undo
675 695
 	$context['page_title'] = $txt['admin_members'];
676 696
 	$context['sub_template'] = 'admin_browse';
677 697
 	$context['browse_type'] = isset($_REQUEST['type']) ? $_REQUEST['type'] : (!empty($modSettings['registration_method']) && $modSettings['registration_method'] == 1 ? 'activate' : 'approve');
678
-	if (isset($context['tabs'][$context['browse_type']]))
679
-		$context['tabs'][$context['browse_type']]['is_selected'] = true;
698
+	if (isset($context['tabs'][$context['browse_type']])) {
699
+			$context['tabs'][$context['browse_type']]['is_selected'] = true;
700
+	}
680 701
 
681 702
 	// Allowed filters are those we can have, in theory.
682 703
 	$context['allowed_filters'] = $context['browse_type'] == 'approve' ? array(3, 4, 5) : array(0, 2);
@@ -687,18 +708,20 @@  discard block
 block discarded – undo
687 708
 	foreach ($context['activation_numbers'] as $type => $amount)
688 709
 	{
689 710
 		// We have some of these...
690
-		if (in_array($type, $context['allowed_filters']) && $amount > 0)
691
-			$context['available_filters'][] = array(
711
+		if (in_array($type, $context['allowed_filters']) && $amount > 0) {
712
+					$context['available_filters'][] = array(
692 713
 				'type' => $type,
693 714
 				'amount' => $amount,
694 715
 				'desc' => isset($txt['admin_browse_filter_type_' . $type]) ? $txt['admin_browse_filter_type_' . $type] : '?',
695 716
 				'selected' => $type == $context['current_filter']
696 717
 			);
718
+		}
697 719
 	}
698 720
 
699 721
 	// If the filter was not sent, set it to whatever has people in it!
700
-	if ($context['current_filter'] == -1 && !empty($context['available_filters'][0]['amount']))
701
-		$context['current_filter'] = $context['available_filters'][0]['type'];
722
+	if ($context['current_filter'] == -1 && !empty($context['available_filters'][0]['amount'])) {
723
+			$context['current_filter'] = $context['available_filters'][0]['type'];
724
+	}
702 725
 
703 726
 	// This little variable is used to determine if we should flag where we are looking.
704 727
 	$context['show_filter'] = ($context['current_filter'] != 0 && $context['current_filter'] != 3) || count($context['available_filters']) > 1;
@@ -713,44 +736,47 @@  discard block
 block discarded – undo
713 736
 	);
714 737
 
715 738
 	// Are we showing duplicate information?
716
-	if (isset($_GET['showdupes']))
717
-		$_SESSION['showdupes'] = (int) $_GET['showdupes'];
739
+	if (isset($_GET['showdupes'])) {
740
+			$_SESSION['showdupes'] = (int) $_GET['showdupes'];
741
+	}
718 742
 	$context['show_duplicates'] = !empty($_SESSION['showdupes']);
719 743
 
720 744
 	// Determine which actions we should allow on this page.
721 745
 	if ($context['browse_type'] == 'approve')
722 746
 	{
723 747
 		// If we are approving deleted accounts we have a slightly different list... actually a mirror ;)
724
-		if ($context['current_filter'] == 4)
725
-			$context['allowed_actions'] = array(
748
+		if ($context['current_filter'] == 4) {
749
+					$context['allowed_actions'] = array(
726 750
 				'reject' => $txt['admin_browse_w_approve_deletion'],
727 751
 				'ok' => $txt['admin_browse_w_reject'],
728 752
 			);
729
-		else
730
-			$context['allowed_actions'] = array(
753
+		} else {
754
+					$context['allowed_actions'] = array(
731 755
 				'ok' => $txt['admin_browse_w_approve'],
732 756
 				'okemail' => $txt['admin_browse_w_approve'] . ' ' . $txt['admin_browse_w_email'],
733 757
 				'require_activation' => $txt['admin_browse_w_approve_require_activate'],
734 758
 				'reject' => $txt['admin_browse_w_reject'],
735 759
 				'rejectemail' => $txt['admin_browse_w_reject'] . ' ' . $txt['admin_browse_w_email'],
736 760
 			);
737
-	}
738
-	elseif ($context['browse_type'] == 'activate')
739
-		$context['allowed_actions'] = array(
761
+		}
762
+	} elseif ($context['browse_type'] == 'activate') {
763
+			$context['allowed_actions'] = array(
740 764
 			'ok' => $txt['admin_browse_w_activate'],
741 765
 			'okemail' => $txt['admin_browse_w_activate'] . ' ' . $txt['admin_browse_w_email'],
742 766
 			'delete' => $txt['admin_browse_w_delete'],
743 767
 			'deleteemail' => $txt['admin_browse_w_delete'] . ' ' . $txt['admin_browse_w_email'],
744 768
 			'remind' => $txt['admin_browse_w_remind'] . ' ' . $txt['admin_browse_w_email'],
745 769
 		);
770
+	}
746 771
 
747 772
 	// Create an option list for actions allowed to be done with selected members.
748 773
 	$allowed_actions = '
749 774
 			<option selected value="">' . $txt['admin_browse_with_selected'] . ':</option>
750 775
 			<option value="" disabled>-----------------------------</option>';
751
-	foreach ($context['allowed_actions'] as $key => $desc)
752
-		$allowed_actions .= '
776
+	foreach ($context['allowed_actions'] as $key => $desc) {
777
+			$allowed_actions .= '
753 778
 			<option value="' . $key . '">' . $desc . '</option>';
779
+	}
754 780
 
755 781
 	// Setup the Javascript function for selecting an action for the list.
756 782
 	$javascript = '
@@ -762,15 +788,16 @@  discard block
 block discarded – undo
762 788
 			var message = "";';
763 789
 
764 790
 	// We have special messages for approving deletion of accounts - it's surprisingly logical - honest.
765
-	if ($context['current_filter'] == 4)
766
-		$javascript .= '
791
+	if ($context['current_filter'] == 4) {
792
+			$javascript .= '
767 793
 			if (document.forms.postForm.todo.value.indexOf("reject") != -1)
768 794
 				message = "' . $txt['admin_browse_w_delete'] . '";
769 795
 			else
770 796
 				message = "' . $txt['admin_browse_w_reject'] . '";';
797
+	}
771 798
 	// Otherwise a nice standard message.
772
-	else
773
-		$javascript .= '
799
+	else {
800
+			$javascript .= '
774 801
 			if (document.forms.postForm.todo.value.indexOf("delete") != -1)
775 802
 				message = "' . $txt['admin_browse_w_delete'] . '";
776 803
 			else if (document.forms.postForm.todo.value.indexOf("reject") != -1)
@@ -779,6 +806,7 @@  discard block
 block discarded – undo
779 806
 				message = "' . $txt['admin_browse_w_remind'] . '";
780 807
 			else
781 808
 				message = "' . ($context['browse_type'] == 'approve' ? $txt['admin_browse_w_approve'] : $txt['admin_browse_w_activate']) . '";';
809
+	}
782 810
 	$javascript .= '
783 811
 			if (confirm(message + " ' . $txt['admin_browse_warn'] . '"))
784 812
 				document.forms.postForm.submit();
@@ -911,10 +939,11 @@  discard block
 block discarded – undo
911 939
 						$member_links = array();
912 940
 						foreach ($rowData['duplicate_members'] as $member)
913 941
 						{
914
-							if ($member['id'])
915
-								$member_links[] = '<a href="' . $scripturl . '?action=profile;u=' . $member['id'] . '" ' . (!empty($member['is_banned']) ? 'class="red"' : '') . '>' . $member['name'] . '</a>';
916
-							else
917
-								$member_links[] = $member['name'] . ' (' . $txt['guest'] . ')';
942
+							if ($member['id']) {
943
+															$member_links[] = '<a href="' . $scripturl . '?action=profile;u=' . $member['id'] . '" ' . (!empty($member['is_banned']) ? 'class="red"' : '') . '>' . $member['name'] . '</a>';
944
+							} else {
945
+															$member_links[] = $member['name'] . ' (' . $txt['guest'] . ')';
946
+							}
918 947
 						}
919 948
 						return implode(', ', $member_links);
920 949
 					},
@@ -963,14 +992,16 @@  discard block
 block discarded – undo
963 992
 	);
964 993
 
965 994
 	// Pick what column to actually include if we're showing duplicates.
966
-	if ($context['show_duplicates'])
967
-		unset($listOptions['columns']['email']);
968
-	else
969
-		unset($listOptions['columns']['duplicates']);
995
+	if ($context['show_duplicates']) {
996
+			unset($listOptions['columns']['email']);
997
+	} else {
998
+			unset($listOptions['columns']['duplicates']);
999
+	}
970 1000
 
971 1001
 	// Only show hostname on duplicates as it takes a lot of time.
972
-	if (!$context['show_duplicates'] || !empty($modSettings['disableHostnameLookup']))
973
-		unset($listOptions['columns']['hostname']);
1002
+	if (!$context['show_duplicates'] || !empty($modSettings['disableHostnameLookup'])) {
1003
+			unset($listOptions['columns']['hostname']);
1004
+	}
974 1005
 
975 1006
 	// Is there any need to show filters?
976 1007
 	if (isset($context['available_filters']) && count($context['available_filters']) > 1)
@@ -978,9 +1009,10 @@  discard block
 block discarded – undo
978 1009
 		$filterOptions = '
979 1010
 			<strong>' . $txt['admin_browse_filter_by'] . ':</strong>
980 1011
 			<select name="filter" onchange="this.form.submit();">';
981
-		foreach ($context['available_filters'] as $filter)
982
-			$filterOptions .= '
1012
+		foreach ($context['available_filters'] as $filter) {
1013
+					$filterOptions .= '
983 1014
 				<option value="' . $filter['type'] . '"' . ($filter['selected'] ? ' selected' : '') . '>' . $filter['desc'] . ' - ' . $filter['amount'] . ' ' . ($filter['amount'] == 1 ? $txt['user'] : $txt['users']) . '</option>';
1015
+		}
984 1016
 		$filterOptions .= '
985 1017
 			</select>
986 1018
 			<noscript><input type="submit" value="' . $txt['go'] . '" name="filter" class="button_submit"></noscript>';
@@ -992,12 +1024,13 @@  discard block
 block discarded – undo
992 1024
 	}
993 1025
 
994 1026
 	// What about if we only have one filter, but it's not the "standard" filter - show them what they are looking at.
995
-	if (!empty($context['show_filter']) && !empty($context['available_filters']))
996
-		$listOptions['additional_rows'][] = array(
1027
+	if (!empty($context['show_filter']) && !empty($context['available_filters'])) {
1028
+			$listOptions['additional_rows'][] = array(
997 1029
 			'position' => 'above_column_headers',
998 1030
 			'value' => '<strong>' . $txt['admin_browse_filter_show'] . ':</strong> ' . $context['available_filters'][0]['desc'],
999 1031
 			'class' => 'smalltext floatright',
1000 1032
 		);
1033
+	}
1001 1034
 
1002 1035
 	// Now that we have all the options, create the list.
1003 1036
 	require_once($sourcedir . '/Subs-List.php');
@@ -1027,12 +1060,14 @@  discard block
 block discarded – undo
1027 1060
 	$current_filter = (int) $_REQUEST['orig_filter'];
1028 1061
 
1029 1062
 	// If we are applying a filter do just that - then redirect.
1030
-	if (isset($_REQUEST['filter']) && $_REQUEST['filter'] != $_REQUEST['orig_filter'])
1031
-		redirectexit('action=admin;area=viewmembers;sa=browse;type=' . $_REQUEST['type'] . ';sort=' . $_REQUEST['sort'] . ';filter=' . $_REQUEST['filter'] . ';start=' . $_REQUEST['start']);
1063
+	if (isset($_REQUEST['filter']) && $_REQUEST['filter'] != $_REQUEST['orig_filter']) {
1064
+			redirectexit('action=admin;area=viewmembers;sa=browse;type=' . $_REQUEST['type'] . ';sort=' . $_REQUEST['sort'] . ';filter=' . $_REQUEST['filter'] . ';start=' . $_REQUEST['start']);
1065
+	}
1032 1066
 
1033 1067
 	// Nothing to do?
1034
-	if (!isset($_POST['todoAction']) && !isset($_POST['time_passed']))
1035
-		redirectexit('action=admin;area=viewmembers;sa=browse;type=' . $_REQUEST['type'] . ';sort=' . $_REQUEST['sort'] . ';filter=' . $current_filter . ';start=' . $_REQUEST['start']);
1068
+	if (!isset($_POST['todoAction']) && !isset($_POST['time_passed'])) {
1069
+			redirectexit('action=admin;area=viewmembers;sa=browse;type=' . $_REQUEST['type'] . ';sort=' . $_REQUEST['sort'] . ';filter=' . $current_filter . ';start=' . $_REQUEST['start']);
1070
+	}
1036 1071
 
1037 1072
 	// Are we dealing with members who have been waiting for > set amount of time?
1038 1073
 	if (isset($_POST['time_passed']))
@@ -1045,8 +1080,9 @@  discard block
 block discarded – undo
1045 1080
 	else
1046 1081
 	{
1047 1082
 		$members = array();
1048
-		foreach ($_POST['todoAction'] as $id)
1049
-			$members[] = (int) $id;
1083
+		foreach ($_POST['todoAction'] as $id) {
1084
+					$members[] = (int) $id;
1085
+		}
1050 1086
 		$condition = '
1051 1087
 			AND id_member IN ({array_int:members})';
1052 1088
 	}
@@ -1067,8 +1103,9 @@  discard block
 block discarded – undo
1067 1103
 	$member_count = $smcFunc['db_num_rows']($request);
1068 1104
 
1069 1105
 	// If no results then just return!
1070
-	if ($member_count == 0)
1071
-		redirectexit('action=admin;area=viewmembers;sa=browse;type=' . $_REQUEST['type'] . ';sort=' . $_REQUEST['sort'] . ';filter=' . $current_filter . ';start=' . $_REQUEST['start']);
1106
+	if ($member_count == 0) {
1107
+			redirectexit('action=admin;area=viewmembers;sa=browse;type=' . $_REQUEST['type'] . ';sort=' . $_REQUEST['sort'] . ';filter=' . $current_filter . ';start=' . $_REQUEST['start']);
1108
+	}
1072 1109
 
1073 1110
 	$member_info = array();
1074 1111
 	$members = array();
@@ -1107,8 +1144,9 @@  discard block
 block discarded – undo
1107 1144
 		// Do we have to let the integration code know about the activations?
1108 1145
 		if (!empty($modSettings['integrate_activate']))
1109 1146
 		{
1110
-			foreach ($member_info as $member)
1111
-				call_integration_hook('integrate_activate', array($member['username']));
1147
+			foreach ($member_info as $member) {
1148
+							call_integration_hook('integrate_activate', array($member['username']));
1149
+			}
1112 1150
 		}
1113 1151
 
1114 1152
 		// Check for email.
@@ -1238,20 +1276,23 @@  discard block
 block discarded – undo
1238 1276
 		$log_action = $_POST['todo'] == 'remind' ? 'remind_member' : 'approve_member';
1239 1277
 
1240 1278
 		require_once($sourcedir . '/Logging.php');
1241
-		foreach ($member_info as $member)
1242
-			logAction($log_action, array('member' => $member['id']), 'admin');
1279
+		foreach ($member_info as $member) {
1280
+					logAction($log_action, array('member' => $member['id']), 'admin');
1281
+		}
1243 1282
 	}
1244 1283
 
1245 1284
 	// Although updateStats *may* catch this, best to do it manually just in case (Doesn't always sort out unapprovedMembers).
1246
-	if (in_array($current_filter, array(3, 4, 5)))
1247
-		updateSettings(array('unapprovedMembers' => ($modSettings['unapprovedMembers'] > $member_count ? $modSettings['unapprovedMembers'] - $member_count : 0)));
1285
+	if (in_array($current_filter, array(3, 4, 5))) {
1286
+			updateSettings(array('unapprovedMembers' => ($modSettings['unapprovedMembers'] > $member_count ? $modSettings['unapprovedMembers'] - $member_count : 0)));
1287
+	}
1248 1288
 
1249 1289
 	// Update the member's stats. (but, we know the member didn't change their name.)
1250 1290
 	updateStats('member', false);
1251 1291
 
1252 1292
 	// If they haven't been deleted, update the post group statistics on them...
1253
-	if (!in_array($_POST['todo'], array('delete', 'deleteemail', 'reject', 'rejectemail', 'remind')))
1254
-		updateStats('postgroups', $members);
1293
+	if (!in_array($_POST['todo'], array('delete', 'deleteemail', 'reject', 'rejectemail', 'remind'))) {
1294
+			updateStats('postgroups', $members);
1295
+	}
1255 1296
 
1256 1297
 	redirectexit('action=admin;area=viewmembers;sa=browse;type=' . $_REQUEST['type'] . ';sort=' . $_REQUEST['sort'] . ';filter=' . $current_filter . ';start=' . $_REQUEST['start']);
1257 1298
 }
@@ -1276,10 +1317,11 @@  discard block
 block discarded – undo
1276 1317
 	$dis = time() - $old;
1277 1318
 
1278 1319
 	// Before midnight?
1279
-	if ($dis < $sinceMidnight)
1280
-		return 0;
1281
-	else
1282
-		$dis -= $sinceMidnight;
1320
+	if ($dis < $sinceMidnight) {
1321
+			return 0;
1322
+	} else {
1323
+			$dis -= $sinceMidnight;
1324
+	}
1283 1325
 
1284 1326
 	// Divide out the seconds in a day to get the number of days.
1285 1327
 	return ceil($dis / (24 * 60 * 60));
Please login to merge, or discard this patch.
Sources/Likes.php 1 patch
Braces   +106 added lines, -77 removed lines patch added patch discarded remove patch
@@ -13,8 +13,9 @@  discard block
 block discarded – undo
13 13
  * @version 2.1 Beta 3
14 14
  */
15 15
 
16
-if (!defined('SMF'))
16
+if (!defined('SMF')) {
17 17
 	die('No direct access...');
18
+}
18 19
 
19 20
 /**
20 21
  * Class Likes
@@ -108,8 +109,9 @@  discard block
 block discarded – undo
108 109
 		$this->_extra = isset($_GET['extra']) ? $_GET['extra'] : false;
109 110
 
110 111
 		// We do not want to output debug information here.
111
-		if ($this->_js)
112
-			$db_show_debug = false;
112
+		if ($this->_js) {
113
+					$db_show_debug = false;
114
+		}
113 115
 	}
114 116
 
115 117
 	/**
@@ -143,8 +145,9 @@  discard block
 block discarded – undo
143 145
 			$call = $this->_sa;
144 146
 
145 147
 			// Guest can only view likes.
146
-			if ($call != 'view')
147
-				is_not_guest();
148
+			if ($call != 'view') {
149
+							is_not_guest();
150
+			}
148 151
 
149 152
 			checkSession('get');
150 153
 
@@ -182,15 +185,17 @@  discard block
 block discarded – undo
182 185
 		global $smcFunc, $modSettings;
183 186
 
184 187
 		// This feature is currently disable.
185
-		if (empty($modSettings['enable_likes']))
186
-			return $this->_error = 'like_disable';
188
+		if (empty($modSettings['enable_likes'])) {
189
+					return $this->_error = 'like_disable';
190
+		}
187 191
 
188 192
 		// Zerothly, they did indicate some kind of content to like, right?
189 193
 		preg_match('~^([a-z0-9\-\_]{1,6})~i', $this->_type, $matches);
190 194
 		$this->_type = isset($matches[1]) ? $matches[1] : '';
191 195
 
192
-		if ($this->_type == '' || $this->_content <= 0)
193
-			return $this->_error = 'cannot_';
196
+		if ($this->_type == '' || $this->_content <= 0) {
197
+					return $this->_error = 'cannot_';
198
+		}
194 199
 
195 200
 		// First we need to verify if the user can see the type of content or not. This is set up to be extensible,
196 201
 		// so we'll check for the one type we do know about, and if it's not that, we'll defer to any hooks.
@@ -209,12 +214,14 @@  discard block
 block discarded – undo
209 214
 					'msg' => $this->_content,
210 215
 				)
211 216
 			);
212
-			if ($smcFunc['db_num_rows']($request) == 1)
213
-				list ($this->_idTopic, $topicOwner) = $smcFunc['db_fetch_row']($request);
217
+			if ($smcFunc['db_num_rows']($request) == 1) {
218
+							list ($this->_idTopic, $topicOwner) = $smcFunc['db_fetch_row']($request);
219
+			}
214 220
 
215 221
 			$smcFunc['db_free_result']($request);
216
-			if (empty($this->_idTopic))
217
-				return $this->_error = 'cannot_';
222
+			if (empty($this->_idTopic)) {
223
+							return $this->_error = 'cannot_';
224
+			}
218 225
 
219 226
 			// So we know what topic it's in and more importantly we know the user can see it.
220 227
 			// If we're not viewing, we need some info set up.
@@ -224,9 +231,7 @@  discard block
 block discarded – undo
224 231
 			$this->_validLikes['can_see'] = allowedTo('likes_view') ? true : 'cannot_view_likes';
225 232
 
226 233
 			$this->_validLikes['can_like'] = ($this->_user['id'] == $topicOwner ? 'cannot_like_content' : (allowedTo('likes_like') ? true : 'cannot_like_content'));
227
-		}
228
-
229
-		else
234
+		} else
230 235
 		{
231 236
 			// Modders: This will give you whatever the user offers up in terms of liking, e.g. $this->_type=msg, $this->_content=1
232 237
 			// When you hook this, check $this->_type first. If it is not something your mod worries about, return false.
@@ -244,8 +249,9 @@  discard block
 block discarded – undo
244 249
 					if ($result !== false)
245 250
 					{
246 251
 						// Match the type with what we already have.
247
-						if (!isset($result['type']) || $result['type'] != $this->_type)
248
-							return $this->_error = 'not_valid_like_type';
252
+						if (!isset($result['type']) || $result['type'] != $this->_type) {
253
+													return $this->_error = 'not_valid_like_type';
254
+						}
249 255
 
250 256
 						// Fill out the rest.
251 257
 						$this->_type = $result['type'];
@@ -256,17 +262,20 @@  discard block
 block discarded – undo
256 262
 				}
257 263
 			}
258 264
 
259
-			if (!$found)
260
-				return $this->_error = 'cannot_';
265
+			if (!$found) {
266
+							return $this->_error = 'cannot_';
267
+			}
261 268
 		}
262 269
 
263 270
 		// Does the user can see this?
264
-		if (isset($this->_validLikes['can_see']) && is_string($this->_validLikes['can_see']))
265
-			return $this->_error = $this->_validLikes['can_see'];
271
+		if (isset($this->_validLikes['can_see']) && is_string($this->_validLikes['can_see'])) {
272
+					return $this->_error = $this->_validLikes['can_see'];
273
+		}
266 274
 
267 275
 		// Does the user can like this? Viewing a list of likes doesn't require this permission.
268
-			if ($this->_sa != 'view' && isset($this->_validLikes['can_like']) && is_string($this->_validLikes['can_like']))
269
-				return $this->_error = $this->_validLikes['can_like'];
276
+			if ($this->_sa != 'view' && isset($this->_validLikes['can_like']) && is_string($this->_validLikes['can_like'])) {
277
+							return $this->_error = $this->_validLikes['can_like'];
278
+			}
270 279
 	}
271 280
 
272 281
 	/**
@@ -291,8 +300,9 @@  discard block
 block discarded – undo
291 300
 		);
292 301
 
293 302
 		// Are we calling this directly? if so, set a proper data for the response. Do note that __METHOD__ returns both the class name and the function name.
294
-		if ($this->_sa == __FUNCTION__)
295
-			$this->_data = __FUNCTION__;
303
+		if ($this->_sa == __FUNCTION__) {
304
+					$this->_data = __FUNCTION__;
305
+		}
296 306
 	}
297 307
 
298 308
 	/**
@@ -322,8 +332,8 @@  discard block
 block discarded – undo
322 332
 
323 333
 		// Add a background task to process sending alerts.
324 334
 		// Mod author, you can add your own background task for your own custom like event using the "integrate_issue_like" hook or your callback, both are immediately called after this.
325
-		if ($this->_type == 'msg')
326
-			$smcFunc['db_insert']('insert',
335
+		if ($this->_type == 'msg') {
336
+					$smcFunc['db_insert']('insert',
327 337
 				'{db_prefix}background_tasks',
328 338
 				array('task_file' => 'string', 'task_class' => 'string', 'task_data' => 'string', 'claimed_time' => 'int'),
329 339
 				array('$sourcedir/tasks/Likes-Notify.php', 'Likes_Notify_Background', json_encode(array(
@@ -335,10 +345,12 @@  discard block
 block discarded – undo
335 345
 				)), 0),
336 346
 				array('id_task')
337 347
 			);
348
+		}
338 349
 
339 350
 		// Are we calling this directly? if so, set a proper data for the response. Do note that __METHOD__ returns both the class name and the function name.
340
-		if ($this->_sa == __FUNCTION__)
341
-			$this->_data = __FUNCTION__;
351
+		if ($this->_sa == __FUNCTION__) {
352
+					$this->_data = __FUNCTION__;
353
+		}
342 354
 	}
343 355
 
344 356
 	/**
@@ -364,8 +376,9 @@  discard block
 block discarded – undo
364 376
 		$smcFunc['db_free_result']($request);
365 377
 
366 378
 		// If you want to call this directly, fill out _data property too.
367
-		if ($this->_sa == __FUNCTION__)
368
-			$this->_data = $this->_numLikes;
379
+		if ($this->_sa == __FUNCTION__) {
380
+					$this->_data = $this->_numLikes;
381
+		}
369 382
 	}
370 383
 
371 384
 	/**
@@ -378,8 +391,9 @@  discard block
 block discarded – undo
378 391
 		global $smcFunc;
379 392
 
380 393
 		// Safety first!
381
-		if (empty($this->_type) || empty($this->_content))
382
-			return $this->_error = 'cannot_';
394
+		if (empty($this->_type) || empty($this->_content)) {
395
+					return $this->_error = 'cannot_';
396
+		}
383 397
 
384 398
 		// Do we already like this?
385 399
 		$request = $smcFunc['db_query']('', '
@@ -397,26 +411,28 @@  discard block
 block discarded – undo
397 411
 		$this->_alreadyLiked = (bool) $smcFunc['db_num_rows']($request) != 0;
398 412
 		$smcFunc['db_free_result']($request);
399 413
 
400
-		if ($this->_alreadyLiked)
401
-			$this->delete();
402
-
403
-		else
404
-			$this->insert();
414
+		if ($this->_alreadyLiked) {
415
+					$this->delete();
416
+		} else {
417
+					$this->insert();
418
+		}
405 419
 
406 420
 		// Now, how many people like this content now? We *could* just +1 / -1 the relevant container but that has proven to become unstable.
407 421
 		$this->_count();
408 422
 
409 423
 		// Update the likes count for messages.
410
-		if ($this->_type == 'msg')
411
-			$this->msgIssueLike();
424
+		if ($this->_type == 'msg') {
425
+					$this->msgIssueLike();
426
+		}
412 427
 
413 428
 		// Any callbacks?
414 429
 		elseif (!empty($this->_validLikes['callback']))
415 430
 		{
416 431
 			$call = call_helper($this->_validLikes['callback'], true);
417 432
 
418
-			if (!empty($call))
419
-				call_user_func_array($call, array($this));
433
+			if (!empty($call)) {
434
+							call_user_func_array($call, array($this));
435
+			}
420 436
 		}
421 437
 
422 438
 		// Sometimes there might be other things that need updating after we do this like.
@@ -425,8 +441,9 @@  discard block
 block discarded – undo
425 441
 		// Now some clean up. This is provided here for any like handlers that want to do any cache flushing.
426 442
 		// This way a like handler doesn't need to explicitly declare anything in integrate_issue_like, but do so
427 443
 		// in integrate_valid_likes where it absolutely has to exist.
428
-		if (!empty($this->_validLikes['flush_cache']))
429
-			cache_put_data($this->_validLikes['flush_cache'], null);
444
+		if (!empty($this->_validLikes['flush_cache'])) {
445
+					cache_put_data($this->_validLikes['flush_cache'], null);
446
+		}
430 447
 
431 448
 		// All done, start building the data to pass as response.
432 449
 		$this->_data = array(
@@ -450,8 +467,9 @@  discard block
 block discarded – undo
450 467
 	{
451 468
 		global $smcFunc;
452 469
 
453
-		if ($this->_type !== 'msg')
454
-			return;
470
+		if ($this->_type !== 'msg') {
471
+					return;
472
+		}
455 473
 
456 474
 		$smcFunc['db_query']('', '
457 475
 			UPDATE {db_prefix}messages
@@ -492,8 +510,9 @@  discard block
 block discarded – undo
492 510
 				'like_type' => $this->_type,
493 511
 			)
494 512
 		);
495
-		while ($row = $smcFunc['db_fetch_assoc']($request))
496
-			$context['likers'][$row['id_member']] = array('timestamp' => $row['like_time']);
513
+		while ($row = $smcFunc['db_fetch_assoc']($request)) {
514
+					$context['likers'][$row['id_member']] = array('timestamp' => $row['like_time']);
515
+		}
497 516
 
498 517
 		// Now to get member data, including avatars and so on.
499 518
 		$members = array_keys($context['likers']);
@@ -501,8 +520,9 @@  discard block
 block discarded – undo
501 520
 		if (count($loaded) != count($members))
502 521
 		{
503 522
 			$members = array_diff($members, $loaded);
504
-			foreach ($members as $not_loaded)
505
-				unset ($context['likers'][$not_loaded]);
523
+			foreach ($members as $not_loaded) {
524
+							unset ($context['likers'][$not_loaded]);
525
+			}
506 526
 		}
507 527
 
508 528
 		foreach ($context['likers'] as $liker => $dummy)
@@ -544,12 +564,14 @@  discard block
 block discarded – undo
544 564
 		global $context, $txt;
545 565
 
546 566
 		// Don't do anything if someone else has already take care of the response.
547
-		if (!$this->_setResponse)
548
-			return;
567
+		if (!$this->_setResponse) {
568
+					return;
569
+		}
549 570
 
550 571
 		// Want a json response huh?
551
-		if ($this->_validLikes['json'])
552
-			return $this->jsonResponse();
572
+		if ($this->_validLikes['json']) {
573
+					return $this->jsonResponse();
574
+		}
553 575
 
554 576
 		// Set everything up for display.
555 577
 		loadTemplate('Likes');
@@ -559,8 +581,9 @@  discard block
 block discarded – undo
559 581
 		if ($this->_error)
560 582
 		{
561 583
 			// If this is a generic error, set it up good.
562
-			if ($this->_error == 'cannot_')
563
-				$this->_error = $this->_sa == 'view' ? 'cannot_view_likes' : 'cannot_like_content';
584
+			if ($this->_error == 'cannot_') {
585
+							$this->_error = $this->_sa == 'view' ? 'cannot_view_likes' : 'cannot_like_content';
586
+			}
564 587
 
565 588
 			// Is this request coming from an ajax call?
566 589
 			if ($this->_js)
@@ -570,8 +593,9 @@  discard block
 block discarded – undo
570 593
 			}
571 594
 
572 595
 			// Nope?  then just do a redirect to whatever URL was provided.
573
-			else
574
-				redirectexit(!empty($this->_validLikes['redirect']) ? $this->_validLikes['redirect'] . ';error=' . $this->_error : '');
596
+			else {
597
+							redirectexit(!empty($this->_validLikes['redirect']) ? $this->_validLikes['redirect'] . ';error=' . $this->_error : '');
598
+			}
575 599
 
576 600
 			return;
577 601
 		}
@@ -580,8 +604,9 @@  discard block
 block discarded – undo
580 604
 		else
581 605
 		{
582 606
 			// Not an ajax request so send the user back to the previous location or the main page.
583
-			if (!$this->_js)
584
-				redirectexit(!empty($this->_validLikes['redirect']) ? $this->_validLikes['redirect'] : '');
607
+			if (!$this->_js) {
608
+							redirectexit(!empty($this->_validLikes['redirect']) ? $this->_validLikes['redirect'] : '');
609
+			}
585 610
 
586 611
 			// These fine gentlemen all share the same template.
587 612
 			$generic = array('delete', 'insert', '_count');
@@ -612,8 +637,9 @@  discard block
 block discarded – undo
612 637
 		// If there is an error, send it.
613 638
 		if ($this->_error)
614 639
 		{
615
-			if ($this->_error == 'cannot_')
616
-				$this->_error = $this->_sa == 'view' ? 'cannot_view_likes' : 'cannot_like_content';
640
+			if ($this->_error == 'cannot_') {
641
+							$this->_error = $this->_sa == 'view' ? 'cannot_view_likes' : 'cannot_like_content';
642
+			}
617 643
 
618 644
 			$print['error'] = $this->_error;
619 645
 		}
@@ -649,33 +675,36 @@  discard block
 block discarded – undo
649 675
 	<body style="background-color: #444455; color: white; font-style: italic; font-family: serif;">
650 676
 		<div style="margin-top: 12%; font-size: 1.1em; line-height: 1.4; text-align: center;">';
651 677
 
652
-	if (!isset($_GET['verse']) || ($_GET['verse'] != '2:18' && $_GET['verse'] != '22:1-2'))
653
-		$_GET['verse'] = '4:16';
678
+	if (!isset($_GET['verse']) || ($_GET['verse'] != '2:18' && $_GET['verse'] != '22:1-2')) {
679
+			$_GET['verse'] = '4:16';
680
+	}
654 681
 
655
-	if ($_GET['verse'] == '2:18')
656
-		echo '
682
+	if ($_GET['verse'] == '2:18') {
683
+			echo '
657 684
 			Woe, it was that his name wasn\'t <em>known</em>, that he came in mystery, and was recognized by none.&nbsp;And it became to be in those days <em>something</em>.&nbsp; Something not yet <em id="unknown" name="[Unknown]">unknown</em> to mankind.&nbsp; And thus what was to be known the <em>secret project</em> began into its existence.&nbsp; Henceforth the opposition was only <em>weary</em> and <em>fearful</em>, for now their match was at arms against them.';
658
-	elseif ($_GET['verse'] == '4:16')
659
-		echo '
685
+	} elseif ($_GET['verse'] == '4:16') {
686
+			echo '
660 687
 			And it came to pass that the <em>unbelievers</em> dwindled in number and saw rise of many <em>proselytizers</em>, and the opposition found fear in the face of the <em>x</em> and the <em>j</em> while those who stood with the <em>something</em> grew stronger and came together.&nbsp; Still, this was only the <em>beginning</em>, and what lay in the future was <em id="unknown" name="[Unknown]">unknown</em> to all, even those on the right side.';
661
-	elseif ($_GET['verse'] == '22:1-2')
662
-		echo '
688
+	} elseif ($_GET['verse'] == '22:1-2') {
689
+			echo '
663 690
 			<p>Now <em>behold</em>, that which was once the secret project was <em id="unknown" name="[Unknown]">unknown</em> no longer.&nbsp; Alas, it needed more than <em>only one</em>, but yet even thought otherwise.&nbsp; It became that the opposition <em>rumored</em> and lied, but still to no avail.&nbsp; Their match, though not <em>perfect</em>, had them outdone.</p>
664 691
 			<p style="margin: 2ex 1ex 0 1ex; font-size: 1.05em; line-height: 1.5; text-align: center;">Let it continue.&nbsp; <em>The end</em>.</p>';
692
+	}
665 693
 
666 694
 	echo '
667 695
 		</div>
668 696
 		<div style="margin-top: 2ex; font-size: 2em; text-align: right;">';
669 697
 
670
-	if ($_GET['verse'] == '2:18')
671
-		echo '
698
+	if ($_GET['verse'] == '2:18') {
699
+			echo '
672 700
 			from <span style="font-family: Georgia, serif;"><strong><a href="', $scripturl, '?action=about:unknown;verse=4:16" style="color: white; text-decoration: none; cursor: text;">The Book of Unknown</a></strong>, 2:18</span>';
673
-	elseif ($_GET['verse'] == '4:16')
674
-		echo '
701
+	} elseif ($_GET['verse'] == '4:16') {
702
+			echo '
675 703
 			from <span style="font-family: Georgia, serif;"><strong><a href="', $scripturl, '?action=about:unknown;verse=22:1-2" style="color: white; text-decoration: none; cursor: text;">The Book of Unknown</a></strong>, 4:16</span>';
676
-	elseif ($_GET['verse'] == '22:1-2')
677
-		echo '
704
+	} elseif ($_GET['verse'] == '22:1-2') {
705
+			echo '
678 706
 			from <span style="font-family: Georgia, serif;"><strong>The Book of Unknown</strong>, 22:1-2</span>';
707
+	}
679 708
 
680 709
 	echo '
681 710
 		</div>
Please login to merge, or discard this patch.
Sources/Session.php 1 patch
Braces   +31 added lines, -21 removed lines patch added patch discarded remove patch
@@ -17,8 +17,9 @@  discard block
 block discarded – undo
17 17
  * @version 2.1 Beta 3
18 18
  */
19 19
 
20
-if (!defined('SMF'))
20
+if (!defined('SMF')) {
21 21
 	die('No direct access...');
22
+}
22 23
 
23 24
 /**
24 25
  * Attempt to start the session, unless it already has been.
@@ -38,8 +39,9 @@  discard block
 block discarded – undo
38 39
 	{
39 40
 		$parsed_url = parse_url($boardurl);
40 41
 
41
-		if (preg_match('~^\d{1,3}(\.\d{1,3}){3}$~', $parsed_url['host']) == 0 && preg_match('~(?:[^\.]+\.)?([^\.]{2,}\..+)\z~i', $parsed_url['host'], $parts) == 1)
42
-			@ini_set('session.cookie_domain', '.' . $parts[1]);
42
+		if (preg_match('~^\d{1,3}(\.\d{1,3}){3}$~', $parsed_url['host']) == 0 && preg_match('~(?:[^\.]+\.)?([^\.]{2,}\..+)\z~i', $parsed_url['host'], $parts) == 1) {
43
+					@ini_set('session.cookie_domain', '.' . $parts[1]);
44
+		}
43 45
 	}
44 46
 	// @todo Set the session cookie path?
45 47
 
@@ -47,8 +49,9 @@  discard block
 block discarded – undo
47 49
 	if ((ini_get('session.auto_start') == 1 && !empty($modSettings['databaseSession_enable'])) || session_id() == '')
48 50
 	{
49 51
 		// Attempt to end the already-started session.
50
-		if (ini_get('session.auto_start') == 1)
51
-			session_write_close();
52
+		if (ini_get('session.auto_start') == 1) {
53
+					session_write_close();
54
+		}
52 55
 
53 56
 		// This is here to stop people from using bad junky PHPSESSIDs.
54 57
 		if (isset($_REQUEST[session_name()]) && preg_match('~^[A-Za-z0-9,-]{16,64}$~', $_REQUEST[session_name()]) == 0 && !isset($_COOKIE[session_name()]))
@@ -65,19 +68,21 @@  discard block
 block discarded – undo
65 68
 			@ini_set('session.serialize_handler', 'php');
66 69
 			session_set_save_handler('sessionOpen', 'sessionClose', 'sessionRead', 'sessionWrite', 'sessionDestroy', 'sessionGC');
67 70
 			@ini_set('session.gc_probability', '1');
71
+		} elseif (ini_get('session.gc_maxlifetime') <= 1440 && !empty($modSettings['databaseSession_lifetime'])) {
72
+					@ini_set('session.gc_maxlifetime', max($modSettings['databaseSession_lifetime'], 60));
68 73
 		}
69
-		elseif (ini_get('session.gc_maxlifetime') <= 1440 && !empty($modSettings['databaseSession_lifetime']))
70
-			@ini_set('session.gc_maxlifetime', max($modSettings['databaseSession_lifetime'], 60));
71 74
 
72 75
 		// Use cache setting sessions?
73
-		if (empty($modSettings['databaseSession_enable']) && !empty($modSettings['cache_enable']) && php_sapi_name() != 'cli')
74
-			call_integration_hook('integrate_session_handlers');
76
+		if (empty($modSettings['databaseSession_enable']) && !empty($modSettings['cache_enable']) && php_sapi_name() != 'cli') {
77
+					call_integration_hook('integrate_session_handlers');
78
+		}
75 79
 
76 80
 		session_start();
77 81
 
78 82
 		// Change it so the cache settings are a little looser than default.
79
-		if (!empty($modSettings['databaseSession_loose']))
80
-			header('Cache-Control: private');
83
+		if (!empty($modSettings['databaseSession_loose'])) {
84
+					header('Cache-Control: private');
85
+		}
81 86
 	}
82 87
 
83 88
 	// Set the randomly generated code.
@@ -123,8 +128,9 @@  discard block
 block discarded – undo
123 128
 {
124 129
 	global $smcFunc;
125 130
 
126
-	if (preg_match('~^[A-Za-z0-9,-]{16,64}$~', $session_id) == 0)
127
-		return '';
131
+	if (preg_match('~^[A-Za-z0-9,-]{16,64}$~', $session_id) == 0) {
132
+			return '';
133
+	}
128 134
 
129 135
 	// Look for it in the database.
130 136
 	$result = $smcFunc['db_query']('', '
@@ -153,8 +159,9 @@  discard block
 block discarded – undo
153 159
 {
154 160
 	global $smcFunc;
155 161
 
156
-	if (preg_match('~^[A-Za-z0-9,-]{16,64}$~', $session_id) == 0)
157
-		return false;
162
+	if (preg_match('~^[A-Za-z0-9,-]{16,64}$~', $session_id) == 0) {
163
+			return false;
164
+	}
158 165
 
159 166
 	// First try to update an existing row...
160 167
 	$smcFunc['db_query']('', '
@@ -169,13 +176,14 @@  discard block
 block discarded – undo
169 176
 	);
170 177
 
171 178
 	// If that didn't work, try inserting a new one.
172
-	if ($smcFunc['db_affected_rows']() == 0)
173
-		$smcFunc['db_insert']('ignore',
179
+	if ($smcFunc['db_affected_rows']() == 0) {
180
+			$smcFunc['db_insert']('ignore',
174 181
 			'{db_prefix}sessions',
175 182
 			array('session_id' => 'string', 'data' => 'string', 'last_update' => 'int'),
176 183
 			array($session_id, $data, time()),
177 184
 			array('session_id')
178 185
 		);
186
+	}
179 187
 
180 188
 	return ($smcFunc['db_affected_rows']() == 0 ? false : true);
181 189
 }
@@ -190,8 +198,9 @@  discard block
 block discarded – undo
190 198
 {
191 199
 	global $smcFunc;
192 200
 
193
-	if (preg_match('~^[A-Za-z0-9,-]{16,64}$~', $session_id) == 0)
194
-		return false;
201
+	if (preg_match('~^[A-Za-z0-9,-]{16,64}$~', $session_id) == 0) {
202
+			return false;
203
+	}
195 204
 
196 205
 	// Just delete the row...
197 206
 	$smcFunc['db_query']('', '
@@ -217,8 +226,9 @@  discard block
 block discarded – undo
217 226
 	global $modSettings, $smcFunc;
218 227
 
219 228
 	// Just set to the default or lower?  Ignore it for a higher value. (hopefully)
220
-	if (!empty($modSettings['databaseSession_lifetime']) && ($max_lifetime <= 1440 || $modSettings['databaseSession_lifetime'] > $max_lifetime))
221
-		$max_lifetime = max($modSettings['databaseSession_lifetime'], 60);
229
+	if (!empty($modSettings['databaseSession_lifetime']) && ($max_lifetime <= 1440 || $modSettings['databaseSession_lifetime'] > $max_lifetime)) {
230
+			$max_lifetime = max($modSettings['databaseSession_lifetime'], 60);
231
+	}
222 232
 
223 233
 	// Clean up after yerself ;).
224 234
 	$smcFunc['db_query']('', '
Please login to merge, or discard this patch.
Sources/ManageMembergroups.php 1 patch
Braces   +128 added lines, -88 removed lines patch added patch discarded remove patch
@@ -13,8 +13,9 @@  discard block
 block discarded – undo
13 13
  * @version 2.1 Beta 3
14 14
  */
15 15
 
16
-if (!defined('SMF'))
16
+if (!defined('SMF')) {
17 17
 	die('No direct access...');
18
+}
18 19
 
19 20
 
20 21
 /**
@@ -44,8 +45,9 @@  discard block
 block discarded – undo
44 45
 	$_REQUEST['sa'] = isset($_REQUEST['sa']) && isset($subActions[$_REQUEST['sa']]) ? $_REQUEST['sa'] : (allowedTo('manage_membergroups') ? 'index' : 'settings');
45 46
 
46 47
 	// Is it elsewhere?
47
-	if (isset($subActions[$_REQUEST['sa']][2]))
48
-		require_once($sourcedir . '/' . $subActions[$_REQUEST['sa']][2]);
48
+	if (isset($subActions[$_REQUEST['sa']][2])) {
49
+			require_once($sourcedir . '/' . $subActions[$_REQUEST['sa']][2]);
50
+	}
49 51
 
50 52
 	// Do the permission check, you might not be allowed her.
51 53
 	isAllowedTo($subActions[$_REQUEST['sa']][1]);
@@ -104,19 +106,20 @@  discard block
 block discarded – undo
104 106
 					'function' => function($rowData) use ($scripturl)
105 107
 					{
106 108
 						// Since the moderator group has no explicit members, no link is needed.
107
-						if ($rowData['id_group'] == 3)
108
-							$group_name = $rowData['group_name'];
109
-						else
109
+						if ($rowData['id_group'] == 3) {
110
+													$group_name = $rowData['group_name'];
111
+						} else
110 112
 						{
111 113
 							$color_style = empty($rowData['online_color']) ? '' : sprintf(' style="color: %1$s;"', $rowData['online_color']);
112 114
 							$group_name = sprintf('<a href="%1$s?action=admin;area=membergroups;sa=members;group=%2$d"%3$s>%4$s</a>', $scripturl, $rowData['id_group'], $color_style, $rowData['group_name']);
113 115
 						}
114 116
 
115 117
 						// Add a help option for moderator and administrator.
116
-						if ($rowData['id_group'] == 1)
117
-							$group_name .= sprintf(' (<a href="%1$s?action=helpadmin;help=membergroup_administrator" onclick="return reqOverlayDiv(this.href);">?</a>)', $scripturl);
118
-						elseif ($rowData['id_group'] == 3)
119
-							$group_name .= sprintf(' (<a href="%1$s?action=helpadmin;help=membergroup_moderator" onclick="return reqOverlayDiv(this.href);">?</a>)', $scripturl);
118
+						if ($rowData['id_group'] == 1) {
119
+													$group_name .= sprintf(' (<a href="%1$s?action=helpadmin;help=membergroup_administrator" onclick="return reqOverlayDiv(this.href);">?</a>)', $scripturl);
120
+						} elseif ($rowData['id_group'] == 3) {
121
+													$group_name .= sprintf(' (<a href="%1$s?action=helpadmin;help=membergroup_moderator" onclick="return reqOverlayDiv(this.href);">?</a>)', $scripturl);
122
+						}
120 123
 
121 124
 						return $group_name;
122 125
 					},
@@ -330,12 +333,14 @@  discard block
 block discarded – undo
330 333
 		call_integration_hook('integrate_add_membergroup', array($id_group, $postCountBasedGroup));
331 334
 
332 335
 		// Update the post groups now, if this is a post group!
333
-		if (isset($_POST['min_posts']))
334
-			updateStats('postgroups');
336
+		if (isset($_POST['min_posts'])) {
337
+					updateStats('postgroups');
338
+		}
335 339
 
336 340
 		// You cannot set permissions for post groups if they are disabled.
337
-		if ($postCountBasedGroup && empty($modSettings['permission_enable_postgroups']))
338
-			$_POST['perm_type'] = '';
341
+		if ($postCountBasedGroup && empty($modSettings['permission_enable_postgroups'])) {
342
+					$_POST['perm_type'] = '';
343
+		}
339 344
 
340 345
 		if ($_POST['perm_type'] == 'predefined')
341 346
 		{
@@ -365,8 +370,9 @@  discard block
 block discarded – undo
365 370
 				$smcFunc['db_free_result']($request);
366 371
 
367 372
 				// Protected groups are... well, protected!
368
-				if ($copy_type == 1)
369
-					fatal_lang_error('membergroup_does_not_exist');
373
+				if ($copy_type == 1) {
374
+									fatal_lang_error('membergroup_does_not_exist');
375
+				}
370 376
 			}
371 377
 
372 378
 			// Don't allow copying of a real priviledged person!
@@ -384,18 +390,20 @@  discard block
 block discarded – undo
384 390
 			$inserts = array();
385 391
 			while ($row = $smcFunc['db_fetch_assoc']($request))
386 392
 			{
387
-				if (empty($context['illegal_permissions']) || !in_array($row['permission'], $context['illegal_permissions']))
388
-					$inserts[] = array($id_group, $row['permission'], $row['add_deny']);
393
+				if (empty($context['illegal_permissions']) || !in_array($row['permission'], $context['illegal_permissions'])) {
394
+									$inserts[] = array($id_group, $row['permission'], $row['add_deny']);
395
+				}
389 396
 			}
390 397
 			$smcFunc['db_free_result']($request);
391 398
 
392
-			if (!empty($inserts))
393
-				$smcFunc['db_insert']('insert',
399
+			if (!empty($inserts)) {
400
+							$smcFunc['db_insert']('insert',
394 401
 					'{db_prefix}permissions',
395 402
 					array('id_group' => 'int', 'permission' => 'string', 'add_deny' => 'int'),
396 403
 					$inserts,
397 404
 					array('id_group', 'permission')
398 405
 				);
406
+			}
399 407
 
400 408
 			$request = $smcFunc['db_query']('', '
401 409
 				SELECT id_profile, permission, add_deny
@@ -406,17 +414,19 @@  discard block
 block discarded – undo
406 414
 				)
407 415
 			);
408 416
 			$inserts = array();
409
-			while ($row = $smcFunc['db_fetch_assoc']($request))
410
-				$inserts[] = array($id_group, $row['id_profile'], $row['permission'], $row['add_deny']);
417
+			while ($row = $smcFunc['db_fetch_assoc']($request)) {
418
+							$inserts[] = array($id_group, $row['id_profile'], $row['permission'], $row['add_deny']);
419
+			}
411 420
 			$smcFunc['db_free_result']($request);
412 421
 
413
-			if (!empty($inserts))
414
-				$smcFunc['db_insert']('insert',
422
+			if (!empty($inserts)) {
423
+							$smcFunc['db_insert']('insert',
415 424
 					'{db_prefix}board_permissions',
416 425
 					array('id_group' => 'int', 'id_profile' => 'int', 'permission' => 'string', 'add_deny' => 'int'),
417 426
 					$inserts,
418 427
 					array('id_group', 'id_profile', 'permission')
419 428
 				);
429
+			}
420 430
 
421 431
 			// Also get some membergroup information if we're copying and not copying from guests...
422 432
 			if ($copy_id > 0 && $_POST['perm_type'] == 'copy')
@@ -469,14 +479,15 @@  discard block
 block discarded – undo
469 479
 		$changed_boards['allow'] = array();
470 480
 		$changed_boards['deny'] = array();
471 481
 		$changed_boards['ignore'] = array();
472
-		foreach ($accesses as $group_id => $action)
473
-			$changed_boards[$action][] = (int) $group_id;
482
+		foreach ($accesses as $group_id => $action) {
483
+					$changed_boards[$action][] = (int) $group_id;
484
+		}
474 485
 
475 486
 		foreach (array('allow', 'deny') as $board_action)
476 487
 		{
477 488
 			// Only do this if they have special access requirements.
478
-			if (!empty($changed_boards[$board_action]))
479
-				$smcFunc['db_query']('', '
489
+			if (!empty($changed_boards[$board_action])) {
490
+							$smcFunc['db_query']('', '
480 491
 					UPDATE {db_prefix}boards
481 492
 					SET {raw:column} = CASE WHEN {raw:column} = {string:blank_string} THEN {string:group_id_string} ELSE CONCAT({raw:column}, {string:comma_group}) END
482 493
 					WHERE id_board IN ({array_int:board_list})',
@@ -488,11 +499,13 @@  discard block
 block discarded – undo
488 499
 						'column' => $board_action == 'allow' ? 'member_groups' : 'deny_member_groups',
489 500
 					)
490 501
 				);
502
+			}
491 503
 		}
492 504
 
493 505
 		// If this is joinable then set it to show group membership in people's profiles.
494
-		if (empty($modSettings['show_group_membership']) && $_POST['group_type'] > 1)
495
-			updateSettings(array('show_group_membership' => 1));
506
+		if (empty($modSettings['show_group_membership']) && $_POST['group_type'] > 1) {
507
+					updateSettings(array('show_group_membership' => 1));
508
+		}
496 509
 
497 510
 		// Rebuild the group cache.
498 511
 		updateSettings(array(
@@ -513,8 +526,9 @@  discard block
 block discarded – undo
513 526
 	$context['undefined_group'] = !isset($_REQUEST['postgroup']) && !isset($_REQUEST['generalgroup']);
514 527
 	$context['allow_protected'] = allowedTo('admin_forum');
515 528
 
516
-	if (!empty($modSettings['deny_boards_access']))
517
-		loadLanguage('ManagePermissions');
529
+	if (!empty($modSettings['deny_boards_access'])) {
530
+			loadLanguage('ManagePermissions');
531
+	}
518 532
 
519 533
 	$result = $smcFunc['db_query']('', '
520 534
 		SELECT id_group, group_name
@@ -531,11 +545,12 @@  discard block
 block discarded – undo
531 545
 		)
532 546
 	);
533 547
 	$context['groups'] = array();
534
-	while ($row = $smcFunc['db_fetch_assoc']($result))
535
-		$context['groups'][] = array(
548
+	while ($row = $smcFunc['db_fetch_assoc']($result)) {
549
+			$context['groups'][] = array(
536 550
 			'id' => $row['id_group'],
537 551
 			'name' => $row['group_name']
538 552
 		);
553
+	}
539 554
 	$smcFunc['db_free_result']($result);
540 555
 
541 556
 	$request = $smcFunc['db_query']('', '
@@ -552,12 +567,13 @@  discard block
 block discarded – undo
552 567
 	while ($row = $smcFunc['db_fetch_assoc']($request))
553 568
 	{
554 569
 		// This category hasn't been set up yet..
555
-		if (!isset($context['categories'][$row['id_cat']]))
556
-			$context['categories'][$row['id_cat']] = array(
570
+		if (!isset($context['categories'][$row['id_cat']])) {
571
+					$context['categories'][$row['id_cat']] = array(
557 572
 				'id' => $row['id_cat'],
558 573
 				'name' => $row['cat_name'],
559 574
 				'boards' => array()
560 575
 			);
576
+		}
561 577
 
562 578
 		// Set this board up, and let the template know when it's a child.  (indent them..)
563 579
 		$context['categories'][$row['id_cat']]['boards'][$row['id_board']] = array(
@@ -605,8 +621,9 @@  discard block
 block discarded – undo
605 621
 	require_once($sourcedir . '/Subs-Membergroups.php');
606 622
 	$result = deleteMembergroups((int) $_REQUEST['group']);
607 623
 	// Need to throw a warning if it went wrong, but this is the only one we have a message for...
608
-	if ($result === 'group_cannot_delete_sub')
609
-		fatal_lang_error('membergroups_cannot_delete_paid', false);
624
+	if ($result === 'group_cannot_delete_sub') {
625
+			fatal_lang_error('membergroups_cannot_delete_paid', false);
626
+	}
610 627
 
611 628
 	// Go back to the membergroup index.
612 629
 	redirectexit('action=admin;area=membergroups;');
@@ -628,8 +645,9 @@  discard block
 block discarded – undo
628 645
 
629 646
 	$_REQUEST['group'] = isset($_REQUEST['group']) && $_REQUEST['group'] > 0 ? (int) $_REQUEST['group'] : 0;
630 647
 
631
-	if (!empty($modSettings['deny_boards_access']))
632
-		loadLanguage('ManagePermissions');
648
+	if (!empty($modSettings['deny_boards_access'])) {
649
+			loadLanguage('ManagePermissions');
650
+	}
633 651
 
634 652
 	// Make sure this group is editable.
635 653
 	if (!empty($_REQUEST['group']))
@@ -651,8 +669,9 @@  discard block
 block discarded – undo
651 669
 	}
652 670
 
653 671
 	// Now, do we have a valid id?
654
-	if (empty($_REQUEST['group']))
655
-		fatal_lang_error('membergroup_does_not_exist', false);
672
+	if (empty($_REQUEST['group'])) {
673
+			fatal_lang_error('membergroup_does_not_exist', false);
674
+	}
656 675
 
657 676
 	// People who can manage boards are a bit special.
658 677
 	require_once($sourcedir . '/Subs-Members.php');
@@ -683,8 +702,9 @@  discard block
 block discarded – undo
683 702
 		require_once($sourcedir . '/Subs-Membergroups.php');
684 703
 		$result = deleteMembergroups($_REQUEST['group']);
685 704
 		// Need to throw a warning if it went wrong, but this is the only one we have a message for...
686
-		if ($result === 'group_cannot_delete_sub')
687
-			fatal_lang_error('membergroups_cannot_delete_paid', false);
705
+		if ($result === 'group_cannot_delete_sub') {
706
+					fatal_lang_error('membergroups_cannot_delete_paid', false);
707
+		}
688 708
 
689 709
 		redirectexit('action=admin;area=membergroups;');
690 710
 	}
@@ -761,16 +781,18 @@  discard block
 block discarded – undo
761 781
 				$request = $smcFunc['db_query']('', '
762 782
 					SELECT id_board
763 783
 					FROM {db_prefix}boards');
764
-				while ($row = $smcFunc['db_fetch_assoc']($request))
765
-					$accesses[(int) $row['id_board']] = 'allow';
784
+				while ($row = $smcFunc['db_fetch_assoc']($request)) {
785
+									$accesses[(int) $row['id_board']] = 'allow';
786
+				}
766 787
 				$smcFunc['db_free_result']($request);
767 788
 			}
768 789
 
769 790
 			$changed_boards['allow'] = array();
770 791
 			$changed_boards['deny'] = array();
771 792
 			$changed_boards['ignore'] = array();
772
-			foreach ($accesses as $group_id => $action)
773
-				$changed_boards[$action][] = (int) $group_id;
793
+			foreach ($accesses as $group_id => $action) {
794
+							$changed_boards[$action][] = (int) $group_id;
795
+			}
774 796
 
775 797
 			foreach (array('allow', 'deny') as $board_action)
776 798
 			{
@@ -786,8 +808,8 @@  discard block
 block discarded – undo
786 808
 						'column' => $board_action == 'allow' ? 'member_groups' : 'deny_member_groups',
787 809
 					)
788 810
 				);
789
-				while ($row = $smcFunc['db_fetch_assoc']($request))
790
-					$smcFunc['db_query']('', '
811
+				while ($row = $smcFunc['db_fetch_assoc']($request)) {
812
+									$smcFunc['db_query']('', '
791 813
 						UPDATE {db_prefix}boards
792 814
 						SET {raw:column} = {string:member_group_access}
793 815
 						WHERE id_board = {int:current_board}',
@@ -797,11 +819,12 @@  discard block
 block discarded – undo
797 819
 							'column' => $board_action == 'allow' ? 'member_groups' : 'deny_member_groups',
798 820
 						)
799 821
 					);
822
+				}
800 823
 				$smcFunc['db_free_result']($request);
801 824
 
802 825
 				// Add the membergroup to all boards that hadn't been set yet.
803
-				if (!empty($changed_boards[$board_action]))
804
-					$smcFunc['db_query']('', '
826
+				if (!empty($changed_boards[$board_action])) {
827
+									$smcFunc['db_query']('', '
805 828
 						UPDATE {db_prefix}boards
806 829
 						SET {raw:column} = CASE WHEN {raw:column} = {string:blank_string} THEN {string:group_id_string} ELSE CONCAT({raw:column}, {string:comma_group}) END
807 830
 						WHERE id_board IN ({array_int:board_list})
@@ -815,6 +838,7 @@  discard block
 block discarded – undo
815 838
 							'column' => $board_action == 'allow' ? 'member_groups' : 'deny_member_groups',
816 839
 						)
817 840
 					);
841
+				}
818 842
 			}
819 843
 		}
820 844
 
@@ -840,12 +864,14 @@  discard block
 block discarded – undo
840 864
 				)
841 865
 			);
842 866
 			$updates = array();
843
-			while ($row = $smcFunc['db_fetch_assoc']($request))
844
-				$updates[$row['additional_groups']][] = $row['id_member'];
867
+			while ($row = $smcFunc['db_fetch_assoc']($request)) {
868
+							$updates[$row['additional_groups']][] = $row['id_member'];
869
+			}
845 870
 			$smcFunc['db_free_result']($request);
846 871
 
847
-			foreach ($updates as $additional_groups => $memberArray)
848
-				updateMemberData($memberArray, array('additional_groups' => implode(',', array_diff(explode(',', $additional_groups), array((int) $_REQUEST['group'])))));
872
+			foreach ($updates as $additional_groups => $memberArray) {
873
+							updateMemberData($memberArray, array('additional_groups' => implode(',', array_diff(explode(',', $additional_groups), array((int) $_REQUEST['group'])))));
874
+			}
849 875
 
850 876
 			// Sorry, but post groups can't moderate boards
851 877
 			$smcFunc['db_query']('', '
@@ -855,8 +881,7 @@  discard block
 block discarded – undo
855 881
 					'current_group' => (int) $_REQUEST['group'],
856 882
 				)
857 883
 			);
858
-		}
859
-		elseif ($_REQUEST['group'] != 3)
884
+		} elseif ($_REQUEST['group'] != 3)
860 885
 		{
861 886
 			// Making it a hidden group? If so remove everyone with it as primary group (Actually, just make them additional).
862 887
 			if ($_POST['group_hidden'] == 2)
@@ -871,8 +896,9 @@  discard block
 block discarded – undo
871 896
 					)
872 897
 				);
873 898
 				$updates = array();
874
-				while ($row = $smcFunc['db_fetch_assoc']($request))
875
-					$updates[$row['additional_groups']][] = $row['id_member'];
899
+				while ($row = $smcFunc['db_fetch_assoc']($request)) {
900
+									$updates[$row['additional_groups']][] = $row['id_member'];
901
+				}
876 902
 				$smcFunc['db_free_result']($request);
877 903
 
878 904
 				foreach ($updates as $additional_groups => $memberArray)
@@ -914,8 +940,9 @@  discard block
 block discarded – undo
914 940
 			$smcFunc['db_free_result']($request);
915 941
 
916 942
 			// Do we need to update the setting?
917
-			if ((empty($modSettings['show_group_membership']) && $have_joinable) || (!empty($modSettings['show_group_membership']) && !$have_joinable))
918
-				updateSettings(array('show_group_membership' => $have_joinable ? 1 : 0));
943
+			if ((empty($modSettings['show_group_membership']) && $have_joinable) || (!empty($modSettings['show_group_membership']) && !$have_joinable)) {
944
+							updateSettings(array('show_group_membership' => $have_joinable ? 1 : 0));
945
+			}
919 946
 		}
920 947
 
921 948
 		// Do we need to set inherited permissions?
@@ -948,8 +975,9 @@  discard block
 block discarded – undo
948 975
 				{
949 976
 					$moderators[$k] = trim($moderators[$k]);
950 977
 
951
-					if (strlen($moderators[$k]) == 0)
952
-						unset($moderators[$k]);
978
+					if (strlen($moderators[$k]) == 0) {
979
+											unset($moderators[$k]);
980
+					}
953 981
 				}
954 982
 
955 983
 				// Find all the id_member's for the member_name's in the list.
@@ -965,8 +993,9 @@  discard block
 block discarded – undo
965 993
 							'count' => count($moderators),
966 994
 						)
967 995
 					);
968
-					while ($row = $smcFunc['db_fetch_assoc']($request))
969
-						$group_moderators[] = $row['id_member'];
996
+					while ($row = $smcFunc['db_fetch_assoc']($request)) {
997
+											$group_moderators[] = $row['id_member'];
998
+					}
970 999
 					$smcFunc['db_free_result']($request);
971 1000
 				}
972 1001
 			}
@@ -974,8 +1003,9 @@  discard block
 block discarded – undo
974 1003
 			if (!empty($_POST['moderator_list']))
975 1004
 			{
976 1005
 				$moderators = array();
977
-				foreach ($_POST['moderator_list'] as $moderator)
978
-					$moderators[] = (int) $moderator;
1006
+				foreach ($_POST['moderator_list'] as $moderator) {
1007
+									$moderators[] = (int) $moderator;
1008
+				}
979 1009
 
980 1010
 				if (!empty($moderators))
981 1011
 				{
@@ -989,8 +1019,9 @@  discard block
 block discarded – undo
989 1019
 							'num_moderators' => count($moderators),
990 1020
 						)
991 1021
 					);
992
-					while ($row = $smcFunc['db_fetch_assoc']($request))
993
-						$group_moderators[] = $row['id_member'];
1022
+					while ($row = $smcFunc['db_fetch_assoc']($request)) {
1023
+											$group_moderators[] = $row['id_member'];
1024
+					}
994 1025
 					$smcFunc['db_free_result']($request);
995 1026
 				}
996 1027
 			}
@@ -1002,8 +1033,9 @@  discard block
 block discarded – undo
1002 1033
 			if (!empty($group_moderators))
1003 1034
 			{
1004 1035
 				$mod_insert = array();
1005
-				foreach ($group_moderators as $moderator)
1006
-					$mod_insert[] = array($_REQUEST['group'], $moderator);
1036
+				foreach ($group_moderators as $moderator) {
1037
+									$mod_insert[] = array($_REQUEST['group'], $moderator);
1038
+				}
1007 1039
 
1008 1040
 				$smcFunc['db_insert']('insert',
1009 1041
 					'{db_prefix}group_moderators',
@@ -1037,8 +1069,9 @@  discard block
 block discarded – undo
1037 1069
 			'current_group' => (int) $_REQUEST['group'],
1038 1070
 		)
1039 1071
 	);
1040
-	if ($smcFunc['db_num_rows']($request) == 0)
1041
-		fatal_lang_error('membergroup_does_not_exist', false);
1072
+	if ($smcFunc['db_num_rows']($request) == 0) {
1073
+			fatal_lang_error('membergroup_does_not_exist', false);
1074
+	}
1042 1075
 	$row = $smcFunc['db_fetch_assoc']($request);
1043 1076
 	$smcFunc['db_free_result']($request);
1044 1077
 
@@ -1075,14 +1108,16 @@  discard block
 block discarded – undo
1075 1108
 		)
1076 1109
 	);
1077 1110
 	$context['group']['moderators'] = array();
1078
-	while ($row = $smcFunc['db_fetch_assoc']($request))
1079
-		$context['group']['moderators'][$row['id_member']] = $row['real_name'];
1111
+	while ($row = $smcFunc['db_fetch_assoc']($request)) {
1112
+			$context['group']['moderators'][$row['id_member']] = $row['real_name'];
1113
+	}
1080 1114
 	$smcFunc['db_free_result']($request);
1081 1115
 
1082 1116
 	$context['group']['moderator_list'] = empty($context['group']['moderators']) ? '' : '&quot;' . implode('&quot;, &quot;', $context['group']['moderators']) . '&quot;';
1083 1117
 
1084
-	if (!empty($context['group']['moderators']))
1085
-		list ($context['group']['last_moderator_id']) = array_slice(array_keys($context['group']['moderators']), -1);
1118
+	if (!empty($context['group']['moderators'])) {
1119
+			list ($context['group']['last_moderator_id']) = array_slice(array_keys($context['group']['moderators']), -1);
1120
+	}
1086 1121
 
1087 1122
 	// Get a list of boards this membergroup is allowed to see.
1088 1123
 	$context['boards'] = array();
@@ -1102,12 +1137,13 @@  discard block
 block discarded – undo
1102 1137
 		while ($row = $smcFunc['db_fetch_assoc']($request))
1103 1138
 		{
1104 1139
 			// This category hasn't been set up yet..
1105
-			if (!isset($context['categories'][$row['id_cat']]))
1106
-				$context['categories'][$row['id_cat']] = array(
1140
+			if (!isset($context['categories'][$row['id_cat']])) {
1141
+							$context['categories'][$row['id_cat']] = array(
1107 1142
 					'id' => $row['id_cat'],
1108 1143
 					'name' => $row['cat_name'],
1109 1144
 					'boards' => array()
1110 1145
 				);
1146
+			}
1111 1147
 
1112 1148
 			// Set this board up, and let the template know when it's a child.  (indent them..)
1113 1149
 			$context['categories'][$row['id_cat']]['boards'][$row['id_board']] = array(
@@ -1155,19 +1191,22 @@  discard block
 block discarded – undo
1155 1191
 				$image_info = getimagesize($settings['default_theme_dir'] . '/images/membericons/' . $value);
1156 1192
 
1157 1193
 				// If this is bigger than 128 in width or 32 in height, skip this one.
1158
-				if ($image_info == false || $image_info[0] > 128 || $image_info[1] > 32)
1159
-					continue;
1194
+				if ($image_info == false || $image_info[0] > 128 || $image_info[1] > 32) {
1195
+									continue;
1196
+				}
1160 1197
 
1161 1198
 				// Else it's valid. Add it in.
1162
-				else
1163
-					$context['possible_icons'][] = $value;
1199
+				else {
1200
+									$context['possible_icons'][] = $value;
1201
+				}
1164 1202
 			}
1165 1203
 		}
1166 1204
 	}
1167 1205
 
1168 1206
 	// Insert our JS, if we have possible icons.
1169
-	if (!empty($context['possible_icons']))
1170
-		loadJavaScriptFile('icondropdown.js', array('validate' => true), 'smf_icondropdown');
1207
+	if (!empty($context['possible_icons'])) {
1208
+			loadJavaScriptFile('icondropdown.js', array('validate' => true), 'smf_icondropdown');
1209
+	}
1171 1210
 
1172 1211
 		loadJavaScriptFile('suggest.js', array('defer' => false), 'smf_suggest');
1173 1212
 
@@ -1189,8 +1228,9 @@  discard block
 block discarded – undo
1189 1228
 		)
1190 1229
 	);
1191 1230
 	$context['inheritable_groups'] = array();
1192
-	while ($row = $smcFunc['db_fetch_assoc']($request))
1193
-		$context['inheritable_groups'][$row['id_group']] = $row['group_name'];
1231
+	while ($row = $smcFunc['db_fetch_assoc']($request)) {
1232
+			$context['inheritable_groups'][$row['id_group']] = $row['group_name'];
1233
+	}
1194 1234
 	$smcFunc['db_free_result']($request);
1195 1235
 
1196 1236
 	call_integration_hook('integrate_view_membergroup');
Please login to merge, or discard this patch.
Sources/MessageIndex.php 1 patch
Braces   +264 added lines, -197 removed lines patch added patch discarded remove patch
@@ -14,8 +14,9 @@  discard block
 block discarded – undo
14 14
  * @version 2.1 Beta 3
15 15
  */
16 16
 
17
-if (!defined('SMF'))
17
+if (!defined('SMF')) {
18 18
 	die('No direct access...');
19
+}
19 20
 
20 21
 /**
21 22
  * Show the list of topics in this board, along with any child boards.
@@ -56,8 +57,9 @@  discard block
 block discarded – undo
56 57
 
57 58
 	$context['name'] = $board_info['name'];
58 59
 	$context['description'] = $board_info['description'];
59
-	if (!empty($board_info['description']))
60
-		$context['meta_description'] = strip_tags($board_info['description']);
60
+	if (!empty($board_info['description'])) {
61
+			$context['meta_description'] = strip_tags($board_info['description']);
62
+	}
61 63
 
62 64
 	// How many topics do we have in total?
63 65
 	$board_info['total_topics'] = allowedTo('approve_posts') ? $board_info['num_topics'] + $board_info['unapproved_topics'] : $board_info['num_topics'] + $board_info['unapproved_user_topics'];
@@ -73,12 +75,14 @@  discard block
 block discarded – undo
73 75
 		$session_name = session_name();
74 76
 		foreach ($_GET as $k => $v)
75 77
 		{
76
-			if (!in_array($k, array('board', 'start', $session_name)))
77
-				$context['robot_no_index'] = true;
78
+			if (!in_array($k, array('board', 'start', $session_name))) {
79
+							$context['robot_no_index'] = true;
80
+			}
78 81
 		}
79 82
 	}
80
-	if (!empty($_REQUEST['start']) && (!is_numeric($_REQUEST['start']) || $_REQUEST['start'] % $context['messages_per_page'] != 0))
81
-		$context['robot_no_index'] = true;
83
+	if (!empty($_REQUEST['start']) && (!is_numeric($_REQUEST['start']) || $_REQUEST['start'] % $context['messages_per_page'] != 0)) {
84
+			$context['robot_no_index'] = true;
85
+	}
82 86
 
83 87
 	// If we can view unapproved messages and there are some build up a list.
84 88
 	if (allowedTo('approve_posts') && ($board_info['unapproved_topics'] || $board_info['unapproved_posts']))
@@ -89,14 +93,16 @@  discard block
 block discarded – undo
89 93
 	}
90 94
 
91 95
 	// We only know these.
92
-	if (isset($_REQUEST['sort']) && !in_array($_REQUEST['sort'], array('subject', 'starter', 'last_poster', 'replies', 'views', 'first_post', 'last_post')))
93
-		$_REQUEST['sort'] = 'last_post';
96
+	if (isset($_REQUEST['sort']) && !in_array($_REQUEST['sort'], array('subject', 'starter', 'last_poster', 'replies', 'views', 'first_post', 'last_post'))) {
97
+			$_REQUEST['sort'] = 'last_post';
98
+	}
94 99
 
95 100
 	// Make sure the starting place makes sense and construct the page index.
96
-	if (isset($_REQUEST['sort']))
97
-		$context['page_index'] = constructPageIndex($scripturl . '?board=' . $board . '.%1$d;sort=' . $_REQUEST['sort'] . (isset($_REQUEST['desc']) ? ';desc' : ''), $_REQUEST['start'], $board_info['total_topics'], $maxindex, true);
98
-	else
99
-		$context['page_index'] = constructPageIndex($scripturl . '?board=' . $board . '.%1$d', $_REQUEST['start'], $board_info['total_topics'], $maxindex, true);
101
+	if (isset($_REQUEST['sort'])) {
102
+			$context['page_index'] = constructPageIndex($scripturl . '?board=' . $board . '.%1$d;sort=' . $_REQUEST['sort'] . (isset($_REQUEST['desc']) ? ';desc' : ''), $_REQUEST['start'], $board_info['total_topics'], $maxindex, true);
103
+	} else {
104
+			$context['page_index'] = constructPageIndex($scripturl . '?board=' . $board . '.%1$d', $_REQUEST['start'], $board_info['total_topics'], $maxindex, true);
105
+	}
100 106
 	$context['start'] = &$_REQUEST['start'];
101 107
 
102 108
 	// Set a canonical URL for this page.
@@ -132,14 +138,16 @@  discard block
 block discarded – undo
132 138
 	$context['link_moderators'] = array();
133 139
 	if (!empty($board_info['moderators']))
134 140
 	{
135
-		foreach ($board_info['moderators'] as $mod)
136
-			$context['link_moderators'][] = '<a href="' . $scripturl . '?action=profile;u=' . $mod['id'] . '" title="' . $txt['board_moderator'] . '">' . $mod['name'] . '</a>';
141
+		foreach ($board_info['moderators'] as $mod) {
142
+					$context['link_moderators'][] = '<a href="' . $scripturl . '?action=profile;u=' . $mod['id'] . '" title="' . $txt['board_moderator'] . '">' . $mod['name'] . '</a>';
143
+		}
137 144
 	}
138 145
 	if (!empty($board_info['moderator_groups']))
139 146
 	{
140 147
 		// By default just tack the moderator groups onto the end of the members
141
-		foreach ($board_info['moderator_groups'] as $mod_group)
142
-			$context['link_moderators'][] = '<a href="' . $scripturl . '?action=groups;sa=members;group=' . $mod_group['id'] . '" title="' . $txt['board_moderator'] . '">' . $mod_group['name'] . '</a>';
148
+		foreach ($board_info['moderator_groups'] as $mod_group) {
149
+					$context['link_moderators'][] = '<a href="' . $scripturl . '?action=groups;sa=members;group=' . $mod_group['id'] . '" title="' . $txt['board_moderator'] . '">' . $mod_group['name'] . '</a>';
150
+		}
143 151
 	}
144 152
 
145 153
 	// Now we tack the info onto the end of the linktree
@@ -191,20 +199,24 @@  discard block
 block discarded – undo
191 199
 		);
192 200
 		while ($row = $smcFunc['db_fetch_assoc']($request))
193 201
 		{
194
-			if (empty($row['id_member']))
195
-				continue;
202
+			if (empty($row['id_member'])) {
203
+							continue;
204
+			}
196 205
 
197
-			if (!empty($row['online_color']))
198
-				$link = '<a href="' . $scripturl . '?action=profile;u=' . $row['id_member'] . '" style="color: ' . $row['online_color'] . ';">' . $row['real_name'] . '</a>';
199
-			else
200
-				$link = '<a href="' . $scripturl . '?action=profile;u=' . $row['id_member'] . '">' . $row['real_name'] . '</a>';
206
+			if (!empty($row['online_color'])) {
207
+							$link = '<a href="' . $scripturl . '?action=profile;u=' . $row['id_member'] . '" style="color: ' . $row['online_color'] . ';">' . $row['real_name'] . '</a>';
208
+			} else {
209
+							$link = '<a href="' . $scripturl . '?action=profile;u=' . $row['id_member'] . '">' . $row['real_name'] . '</a>';
210
+			}
201 211
 
202 212
 			$is_buddy = in_array($row['id_member'], $user_info['buddies']);
203
-			if ($is_buddy)
204
-				$link = '<strong>' . $link . '</strong>';
213
+			if ($is_buddy) {
214
+							$link = '<strong>' . $link . '</strong>';
215
+			}
205 216
 
206
-			if (!empty($row['show_online']) || allowedTo('moderate_forum'))
207
-				$context['view_members_list'][$row['log_time'] . $row['member_name']] = empty($row['show_online']) ? '<em>' . $link . '</em>' : $link;
217
+			if (!empty($row['show_online']) || allowedTo('moderate_forum')) {
218
+							$context['view_members_list'][$row['log_time'] . $row['member_name']] = empty($row['show_online']) ? '<em>' . $link . '</em>' : $link;
219
+			}
208 220
 			// @todo why are we filling this array of data that are just counted (twice) and discarded? ???
209 221
 			$context['view_members'][$row['log_time'] . $row['member_name']] = array(
210 222
 				'id' => $row['id_member'],
@@ -217,8 +229,9 @@  discard block
 block discarded – undo
217 229
 				'hidden' => empty($row['show_online']),
218 230
 			);
219 231
 
220
-			if (empty($row['show_online']))
221
-				$context['view_num_hidden']++;
232
+			if (empty($row['show_online'])) {
233
+							$context['view_num_hidden']++;
234
+			}
222 235
 		}
223 236
 		$context['view_num_guests'] = $smcFunc['db_num_rows']($request) - count($context['view_members']);
224 237
 		$smcFunc['db_free_result']($request);
@@ -257,8 +270,9 @@  discard block
 block discarded – undo
257 270
 	$context['sort_direction'] = $ascending ? 'up' : 'down';
258 271
 	$txt['starter'] = $txt['started_by'];
259 272
 
260
-	foreach ($sort_methods as $key => $val)
261
-		$context['topics_headers'][$key] = '<a href="' . $scripturl . '?board=' . $context['current_board'] . '.' . $context['start'] . ';sort=' . $key . ($context['sort_by'] == $key && $context['sort_direction'] == 'up' ? ';desc' : '') . '">' . $txt[$key] . ($context['sort_by'] == $key ? '<span class="sort sort_' . $context['sort_direction'] . '"></span>' : '') . '</a>';
273
+	foreach ($sort_methods as $key => $val) {
274
+			$context['topics_headers'][$key] = '<a href="' . $scripturl . '?board=' . $context['current_board'] . '.' . $context['start'] . ';sort=' . $key . ($context['sort_by'] == $key && $context['sort_direction'] == 'up' ? ';desc' : '') . '">' . $txt[$key] . ($context['sort_by'] == $key ? '<span class="sort sort_' . $context['sort_direction'] . '"></span>' : '') . '</a>';
275
+	}
262 276
 
263 277
 	// Calculate the fastest way to get the topics.
264 278
 	$start = (int) $_REQUEST['start'];
@@ -268,14 +282,15 @@  discard block
 block discarded – undo
268 282
 		$fake_ascending = true;
269 283
 		$maxindex = $board_info['total_topics'] < $start + $maxindex + 1 ? $board_info['total_topics'] - $start : $maxindex;
270 284
 		$start = $board_info['total_topics'] < $start + $maxindex + 1 ? 0 : $board_info['total_topics'] - $start - $maxindex;
285
+	} else {
286
+			$fake_ascending = false;
271 287
 	}
272
-	else
273
-		$fake_ascending = false;
274 288
 
275 289
 	// Setup the default topic icons...
276 290
 	$context['icon_sources'] = array();
277
-	foreach ($context['stable_icons'] as $icon)
278
-		$context['icon_sources'][$icon] = 'images_url';
291
+	foreach ($context['stable_icons'] as $icon) {
292
+			$context['icon_sources'][$icon] = 'images_url';
293
+	}
279 294
 
280 295
 	$topic_ids = array();
281 296
 	$context['topics'] = array();
@@ -306,8 +321,9 @@  discard block
 block discarded – undo
306 321
 			)
307 322
 		);
308 323
 		$topic_ids = array();
309
-		while ($row = $smcFunc['db_fetch_assoc']($request))
310
-			$topic_ids[] = $row['id_topic'];
324
+		while ($row = $smcFunc['db_fetch_assoc']($request)) {
325
+					$topic_ids[] = $row['id_topic'];
326
+		}
311 327
 	}
312 328
 
313 329
 	// Grab the appropriate topic information...
@@ -363,11 +379,13 @@  discard block
 block discarded – undo
363 379
 		// Begin 'printing' the message index for current board.
364 380
 		while ($row = $smcFunc['db_fetch_assoc']($result))
365 381
 		{
366
-			if ($row['id_poll'] > 0 && $modSettings['pollMode'] == '0')
367
-				continue;
382
+			if ($row['id_poll'] > 0 && $modSettings['pollMode'] == '0') {
383
+							continue;
384
+			}
368 385
 
369
-			if (!$pre_query)
370
-				$topic_ids[] = $row['id_topic'];
386
+			if (!$pre_query) {
387
+							$topic_ids[] = $row['id_topic'];
388
+			}
371 389
 
372 390
 			// Reference the main color class.
373 391
 			$colorClass = 'windowbg';
@@ -377,8 +395,9 @@  discard block
 block discarded – undo
377 395
 			{
378 396
 				// Limit them to $modSettings['preview_characters'] characters
379 397
 				$row['first_body'] = strip_tags(strtr(parse_bbc($row['first_body'], $row['first_smileys'], $row['id_first_msg']), array('<br>' => '&#10;')));
380
-				if ($smcFunc['strlen']($row['first_body']) > $modSettings['preview_characters'])
381
-					$row['first_body'] = $smcFunc['substr']($row['first_body'], 0, $modSettings['preview_characters']) . '...';
398
+				if ($smcFunc['strlen']($row['first_body']) > $modSettings['preview_characters']) {
399
+									$row['first_body'] = $smcFunc['substr']($row['first_body'], 0, $modSettings['preview_characters']) . '...';
400
+				}
382 401
 
383 402
 				// Censor the subject and message preview.
384 403
 				censorText($row['first_subject']);
@@ -389,27 +408,27 @@  discard block
 block discarded – undo
389 408
 				{
390 409
 					$row['last_subject'] = $row['first_subject'];
391 410
 					$row['last_body'] = $row['first_body'];
392
-				}
393
-				else
411
+				} else
394 412
 				{
395 413
 					$row['last_body'] = strip_tags(strtr(parse_bbc($row['last_body'], $row['last_smileys'], $row['id_last_msg']), array('<br>' => '&#10;')));
396
-					if ($smcFunc['strlen']($row['last_body']) > $modSettings['preview_characters'])
397
-						$row['last_body'] = $smcFunc['substr']($row['last_body'], 0, $modSettings['preview_characters']) . '...';
414
+					if ($smcFunc['strlen']($row['last_body']) > $modSettings['preview_characters']) {
415
+											$row['last_body'] = $smcFunc['substr']($row['last_body'], 0, $modSettings['preview_characters']) . '...';
416
+					}
398 417
 
399 418
 					censorText($row['last_subject']);
400 419
 					censorText($row['last_body']);
401 420
 				}
402
-			}
403
-			else
421
+			} else
404 422
 			{
405 423
 				$row['first_body'] = '';
406 424
 				$row['last_body'] = '';
407 425
 				censorText($row['first_subject']);
408 426
 
409
-				if ($row['id_first_msg'] == $row['id_last_msg'])
410
-					$row['last_subject'] = $row['first_subject'];
411
-				else
412
-					censorText($row['last_subject']);
427
+				if ($row['id_first_msg'] == $row['id_last_msg']) {
428
+									$row['last_subject'] = $row['first_subject'];
429
+				} else {
430
+									censorText($row['last_subject']);
431
+				}
413 432
 			}
414 433
 
415 434
 			// Decide how many pages the topic should have.
@@ -420,42 +439,50 @@  discard block
 block discarded – undo
420 439
 				$pages = constructPageIndex($scripturl . '?topic=' . $row['id_topic'] . '.%1$d', $start, $row['num_replies'] + 1, $context['messages_per_page'], true, false);
421 440
 
422 441
 				// If we can use all, show all.
423
-				if (!empty($modSettings['enableAllMessages']) && $row['num_replies'] + 1 < $modSettings['enableAllMessages'])
424
-					$pages .= ' &nbsp;<a href="' . $scripturl . '?topic=' . $row['id_topic'] . '.0;all">' . $txt['all'] . '</a>';
442
+				if (!empty($modSettings['enableAllMessages']) && $row['num_replies'] + 1 < $modSettings['enableAllMessages']) {
443
+									$pages .= ' &nbsp;<a href="' . $scripturl . '?topic=' . $row['id_topic'] . '.0;all">' . $txt['all'] . '</a>';
444
+				}
445
+			} else {
446
+							$pages = '';
425 447
 			}
426
-			else
427
-				$pages = '';
428 448
 
429 449
 			// We need to check the topic icons exist...
430 450
 			if (!empty($modSettings['messageIconChecks_enable']))
431 451
 			{
432
-				if (!isset($context['icon_sources'][$row['first_icon']]))
433
-					$context['icon_sources'][$row['first_icon']] = file_exists($settings['theme_dir'] . '/images/post/' . $row['first_icon'] . '.png') ? 'images_url' : 'default_images_url';
434
-				if (!isset($context['icon_sources'][$row['last_icon']]))
435
-					$context['icon_sources'][$row['last_icon']] = file_exists($settings['theme_dir'] . '/images/post/' . $row['last_icon'] . '.png') ? 'images_url' : 'default_images_url';
436
-			}
437
-			else
452
+				if (!isset($context['icon_sources'][$row['first_icon']])) {
453
+									$context['icon_sources'][$row['first_icon']] = file_exists($settings['theme_dir'] . '/images/post/' . $row['first_icon'] . '.png') ? 'images_url' : 'default_images_url';
454
+				}
455
+				if (!isset($context['icon_sources'][$row['last_icon']])) {
456
+									$context['icon_sources'][$row['last_icon']] = file_exists($settings['theme_dir'] . '/images/post/' . $row['last_icon'] . '.png') ? 'images_url' : 'default_images_url';
457
+				}
458
+			} else
438 459
 			{
439
-				if (!isset($context['icon_sources'][$row['first_icon']]))
440
-					$context['icon_sources'][$row['first_icon']] = 'images_url';
441
-				if (!isset($context['icon_sources'][$row['last_icon']]))
442
-					$context['icon_sources'][$row['last_icon']] = 'images_url';
460
+				if (!isset($context['icon_sources'][$row['first_icon']])) {
461
+									$context['icon_sources'][$row['first_icon']] = 'images_url';
462
+				}
463
+				if (!isset($context['icon_sources'][$row['last_icon']])) {
464
+									$context['icon_sources'][$row['last_icon']] = 'images_url';
465
+				}
443 466
 			}
444 467
 
445
-			if (!empty($board_info['recycle']))
446
-				$row['first_icon'] = 'recycled';
468
+			if (!empty($board_info['recycle'])) {
469
+							$row['first_icon'] = 'recycled';
470
+			}
447 471
 
448 472
 			// Is this topic pending approval, or does it have any posts pending approval?
449
-			if ($context['can_approve_posts'] && $row['unapproved_posts'])
450
-				$colorClass .= (!$row['approved'] ? ' approvetopic' : ' approvepost');
473
+			if ($context['can_approve_posts'] && $row['unapproved_posts']) {
474
+							$colorClass .= (!$row['approved'] ? ' approvetopic' : ' approvepost');
475
+			}
451 476
 
452 477
 			// Sticky topics should get a different color, too.
453
-			if ($row['is_sticky'])
454
-				$colorClass .= ' sticky';
478
+			if ($row['is_sticky']) {
479
+							$colorClass .= ' sticky';
480
+			}
455 481
 
456 482
 			// Locked topics get special treatment as well.
457
-			if ($row['locked'])
458
-				$colorClass .= ' locked';
483
+			if ($row['locked']) {
484
+							$colorClass .= ' locked';
485
+			}
459 486
 
460 487
 			// 'Print' the topic info.
461 488
 			$context['topics'][$row['id_topic']] = array_merge($row, array(
@@ -536,8 +563,9 @@  discard block
 block discarded – undo
536 563
 		$smcFunc['db_free_result']($result);
537 564
 
538 565
 		// Fix the sequence of topics if they were retrieved in the wrong order. (for speed reasons...)
539
-		if ($fake_ascending)
540
-			$context['topics'] = array_reverse($context['topics'], true);
566
+		if ($fake_ascending) {
567
+					$context['topics'] = array_reverse($context['topics'], true);
568
+		}
541 569
 
542 570
 		if (!empty($modSettings['enableParticipation']) && !$user_info['is_guest'] && !empty($topic_ids))
543 571
 		{
@@ -554,8 +582,9 @@  discard block
 block discarded – undo
554 582
 					'limit' => count($topic_ids),
555 583
 				)
556 584
 			);
557
-			while ($row = $smcFunc['db_fetch_assoc']($result))
558
-				$context['topics'][$row['id_topic']]['is_posted_in'] = true;
585
+			while ($row = $smcFunc['db_fetch_assoc']($result)) {
586
+							$context['topics'][$row['id_topic']]['is_posted_in'] = true;
587
+			}
559 588
 			$smcFunc['db_free_result']($result);
560 589
 		}
561 590
 	}
@@ -580,9 +609,9 @@  discard block
 block discarded – undo
580 609
 		// Can we restore topics?
581 610
 		$context['can_restore'] = allowedTo('move_any') && !empty($board_info['recycle']);
582 611
 
583
-		if ($user_info['is_admin'] || $modSettings['topic_move_any'])
584
-			$context['can_move_any'] = true;
585
-		else
612
+		if ($user_info['is_admin'] || $modSettings['topic_move_any']) {
613
+					$context['can_move_any'] = true;
614
+		} else
586 615
 		{
587 616
 			// We'll use this in a minute
588 617
 			$boards_allowed = boardsAllowedTo('post_new');
@@ -609,11 +638,13 @@  discard block
 block discarded – undo
609 638
 		}
610 639
 
611 640
 		// Can we use quick moderation checkboxes?
612
-		if ($options['display_quick_mod'] == 1)
613
-			$context['can_quick_mod'] = $context['user']['is_logged'] || $context['can_approve'] || $context['can_remove'] || $context['can_lock'] || $context['can_sticky'] || $context['can_move'] || $context['can_merge'] || $context['can_restore'];
641
+		if ($options['display_quick_mod'] == 1) {
642
+					$context['can_quick_mod'] = $context['user']['is_logged'] || $context['can_approve'] || $context['can_remove'] || $context['can_lock'] || $context['can_sticky'] || $context['can_move'] || $context['can_merge'] || $context['can_restore'];
643
+		}
614 644
 		// Or the icons?
615
-		else
616
-			$context['can_quick_mod'] = $context['can_remove'] || $context['can_lock'] || $context['can_sticky'] || $context['can_move'];
645
+		else {
646
+					$context['can_quick_mod'] = $context['can_remove'] || $context['can_lock'] || $context['can_sticky'] || $context['can_move'];
647
+		}
617 648
 	}
618 649
 
619 650
 	if (!empty($context['can_quick_mod']) && $options['display_quick_mod'] == 1)
@@ -647,13 +678,15 @@  discard block
 block discarded – undo
647 678
 			);
648 679
 
649 680
 			// We've seen all these boards now!
650
-			foreach ($board_info['parent_boards'] as $k => $dummy)
651
-				if (isset($_SESSION['topicseen_cache'][$k]))
681
+			foreach ($board_info['parent_boards'] as $k => $dummy) {
682
+							if (isset($_SESSION['topicseen_cache'][$k]))
652 683
 					unset($_SESSION['topicseen_cache'][$k]);
684
+			}
653 685
 		}
654 686
 
655
-		if (isset($_SESSION['topicseen_cache'][$board]))
656
-			unset($_SESSION['topicseen_cache'][$board]);
687
+		if (isset($_SESSION['topicseen_cache'][$board])) {
688
+					unset($_SESSION['topicseen_cache'][$board]);
689
+		}
657 690
 
658 691
 		$request = $smcFunc['db_query']('', '
659 692
 			SELECT id_topic, id_board, sent
@@ -674,8 +707,9 @@  discard block
 block discarded – undo
674 707
 				$context['is_marked_notify'] = true;
675 708
 				$board_sent = $row['sent'];
676 709
 			}
677
-			if (!empty($row['id_topic']))
678
-				$context['topics'][$row['id_topic']]['is_watched'] = true;
710
+			if (!empty($row['id_topic'])) {
711
+							$context['topics'][$row['id_topic']]['is_watched'] = true;
712
+			}
679 713
 		}
680 714
 		$smcFunc['db_free_result']($request);
681 715
 
@@ -699,8 +733,7 @@  discard block
 block discarded – undo
699 733
 		$pref = !empty($pref[$user_info['id']]) ? $pref[$user_info['id']] : array();
700 734
 		$pref = isset($pref['board_notify_' . $board]) ? $pref['board_notify_' . $board] : (!empty($pref['board_notify']) ? $pref['board_notify'] : 0);
701 735
 		$context['board_notification_mode'] = !$context['is_marked_notify'] ? 1 : ($pref & 0x02 ? 3 : ($pref & 0x01 ? 2 : 1));
702
-	}
703
-	else
736
+	} else
704 737
 	{
705 738
 		$context['is_marked_notify'] = false;
706 739
 		$context['board_notification_mode'] = 1;
@@ -713,23 +746,27 @@  discard block
 block discarded – undo
713 746
 	$context['becomesUnapproved'] = !empty($_SESSION['becomesUnapproved']) ? true : false;
714 747
 
715 748
 	// Don't want to show this forever...
716
-	if ($context['becomesUnapproved'])
717
-		unset($_SESSION['becomesUnapproved']);
749
+	if ($context['becomesUnapproved']) {
750
+			unset($_SESSION['becomesUnapproved']);
751
+	}
718 752
 
719 753
 	// Build the message index button array.
720 754
 	$context['normal_buttons'] = array();
721 755
 	
722
-	if ($context['can_post_new'])
723
-		$context['normal_buttons']['new_topic'] = array('text' => 'new_topic', 'image' => 'new_topic.png', 'lang' => true, 'url' => $scripturl . '?action=post;board=' . $context['current_board'] . '.0', 'active' => true);
756
+	if ($context['can_post_new']) {
757
+			$context['normal_buttons']['new_topic'] = array('text' => 'new_topic', 'image' => 'new_topic.png', 'lang' => true, 'url' => $scripturl . '?action=post;board=' . $context['current_board'] . '.0', 'active' => true);
758
+	}
724 759
 	
725
-	if ($context['can_post_poll'])
726
-		$context['normal_buttons']['post_poll'] = array('text' => 'new_poll', 'image' => 'new_poll.png', 'lang' => true, 'url' => $scripturl . '?action=post;board=' . $context['current_board'] . '.0;poll');
760
+	if ($context['can_post_poll']) {
761
+			$context['normal_buttons']['post_poll'] = array('text' => 'new_poll', 'image' => 'new_poll.png', 'lang' => true, 'url' => $scripturl . '?action=post;board=' . $context['current_board'] . '.0;poll');
762
+	}
727 763
 	
728
-	if (!$context['user']['is_logged'])
729
-		$context['normal_buttons']['markread'] = array('text' => 'mark_read_short', 'image' => 'markread.png', 'lang' => true, 'custom' => 'data-confirm="' . $txt['are_sure_mark_read'] . '"', 'class' => 'you_sure', 'url' => $scripturl . '?action=markasread;sa=board;board=' . $context['current_board'] . '.0;' . $context['session_var'] . '=' . $context['session_id']);
764
+	if (!$context['user']['is_logged']) {
765
+			$context['normal_buttons']['markread'] = array('text' => 'mark_read_short', 'image' => 'markread.png', 'lang' => true, 'custom' => 'data-confirm="' . $txt['are_sure_mark_read'] . '"', 'class' => 'you_sure', 'url' => $scripturl . '?action=markasread;sa=board;board=' . $context['current_board'] . '.0;' . $context['session_var'] . '=' . $context['session_id']);
766
+	}
730 767
 
731
-	if ($context['can_mark_notify'])
732
-		$context['normal_buttons']['notify'] = array(
768
+	if ($context['can_mark_notify']) {
769
+			$context['normal_buttons']['notify'] = array(
733 770
 			'lang' => true,
734 771
 			'text' => 'notify_board_' . $context['board_notification_mode'],
735 772
 			'sub_buttons' => array(
@@ -747,6 +784,7 @@  discard block
 block discarded – undo
747 784
 				),
748 785
 			),
749 786
 		);
787
+	}
750 788
 
751 789
 	// Javascript for inline editing.
752 790
 	loadJavaScriptFile('topic.js', array('defer' => false), 'smf_topic');
@@ -768,18 +806,21 @@  discard block
 block discarded – undo
768 806
 	checkSession('request');
769 807
 
770 808
 	// Lets go straight to the restore area.
771
-	if (isset($_REQUEST['qaction']) && $_REQUEST['qaction'] == 'restore' && !empty($_REQUEST['topics']))
772
-		redirectexit('action=restoretopic;topics=' . implode(',', $_REQUEST['topics']) . ';' . $context['session_var'] . '=' . $context['session_id']);
809
+	if (isset($_REQUEST['qaction']) && $_REQUEST['qaction'] == 'restore' && !empty($_REQUEST['topics'])) {
810
+			redirectexit('action=restoretopic;topics=' . implode(',', $_REQUEST['topics']) . ';' . $context['session_var'] . '=' . $context['session_id']);
811
+	}
773 812
 
774
-	if (isset($_SESSION['topicseen_cache']))
775
-		$_SESSION['topicseen_cache'] = array();
813
+	if (isset($_SESSION['topicseen_cache'])) {
814
+			$_SESSION['topicseen_cache'] = array();
815
+	}
776 816
 
777 817
 	// This is going to be needed to send off the notifications and for updateLastMessages().
778 818
 	require_once($sourcedir . '/Subs-Post.php');
779 819
 
780 820
 	// Remember the last board they moved things to.
781
-	if (isset($_REQUEST['move_to']))
782
-		$_SESSION['move_to_topic'] = $_REQUEST['move_to'];
821
+	if (isset($_REQUEST['move_to'])) {
822
+			$_SESSION['move_to_topic'] = $_REQUEST['move_to'];
823
+	}
783 824
 
784 825
 	// Only a few possible actions.
785 826
 	$possibleActions = array();
@@ -799,8 +840,7 @@  discard block
 block discarded – undo
799 840
 		);
800 841
 
801 842
 		$redirect_url = 'board=' . $board . '.' . $_REQUEST['start'];
802
-	}
803
-	else
843
+	} else
804 844
 	{
805 845
 		/**
806 846
 		 * @todo Ugly. There's no getting around this, is there?
@@ -818,8 +858,7 @@  discard block
 block discarded – undo
818 858
 		if (!empty($board))
819 859
 		{
820 860
 			$boards_can['post_new'] = array_diff(boardsAllowedTo('post_new'), array($board));
821
-		}
822
-		else
861
+		} else
823 862
 		{
824 863
 			$boards_can['post_new'] = boardsAllowedTo('post_new');
825 864
 		}
@@ -830,55 +869,67 @@  discard block
 block discarded – undo
830 869
 		}
831 870
 	}
832 871
 
833
-	if (!$user_info['is_guest'])
834
-		$possibleActions[] = 'markread';
835
-	if (!empty($boards_can['make_sticky']))
836
-		$possibleActions[] = 'sticky';
837
-	if (!empty($boards_can['move_any']) || !empty($boards_can['move_own']))
838
-		$possibleActions[] = 'move';
839
-	if (!empty($boards_can['remove_any']) || !empty($boards_can['remove_own']))
840
-		$possibleActions[] = 'remove';
841
-	if (!empty($boards_can['lock_any']) || !empty($boards_can['lock_own']))
842
-		$possibleActions[] = 'lock';
843
-	if (!empty($boards_can['merge_any']))
844
-		$possibleActions[] = 'merge';
845
-	if (!empty($boards_can['approve_posts']))
846
-		$possibleActions[] = 'approve';
872
+	if (!$user_info['is_guest']) {
873
+			$possibleActions[] = 'markread';
874
+	}
875
+	if (!empty($boards_can['make_sticky'])) {
876
+			$possibleActions[] = 'sticky';
877
+	}
878
+	if (!empty($boards_can['move_any']) || !empty($boards_can['move_own'])) {
879
+			$possibleActions[] = 'move';
880
+	}
881
+	if (!empty($boards_can['remove_any']) || !empty($boards_can['remove_own'])) {
882
+			$possibleActions[] = 'remove';
883
+	}
884
+	if (!empty($boards_can['lock_any']) || !empty($boards_can['lock_own'])) {
885
+			$possibleActions[] = 'lock';
886
+	}
887
+	if (!empty($boards_can['merge_any'])) {
888
+			$possibleActions[] = 'merge';
889
+	}
890
+	if (!empty($boards_can['approve_posts'])) {
891
+			$possibleActions[] = 'approve';
892
+	}
847 893
 
848 894
 	// Two methods: $_REQUEST['actions'] (id_topic => action), and $_REQUEST['topics'] and $_REQUEST['qaction'].
849 895
 	// (if action is 'move', $_REQUEST['move_to'] or $_REQUEST['move_tos'][$topic] is used.)
850 896
 	if (!empty($_REQUEST['topics']))
851 897
 	{
852 898
 		// If the action isn't valid, just quit now.
853
-		if (empty($_REQUEST['qaction']) || !in_array($_REQUEST['qaction'], $possibleActions))
854
-			redirectexit($redirect_url);
899
+		if (empty($_REQUEST['qaction']) || !in_array($_REQUEST['qaction'], $possibleActions)) {
900
+					redirectexit($redirect_url);
901
+		}
855 902
 
856 903
 		// Merge requires all topics as one parameter and can be done at once.
857 904
 		if ($_REQUEST['qaction'] == 'merge')
858 905
 		{
859 906
 			// Merge requires at least two topics.
860
-			if (empty($_REQUEST['topics']) || count($_REQUEST['topics']) < 2)
861
-				redirectexit($redirect_url);
907
+			if (empty($_REQUEST['topics']) || count($_REQUEST['topics']) < 2) {
908
+							redirectexit($redirect_url);
909
+			}
862 910
 
863 911
 			require_once($sourcedir . '/SplitTopics.php');
864 912
 			return MergeExecute($_REQUEST['topics']);
865 913
 		}
866 914
 
867 915
 		// Just convert to the other method, to make it easier.
868
-		foreach ($_REQUEST['topics'] as $topic)
869
-			$_REQUEST['actions'][(int) $topic] = $_REQUEST['qaction'];
916
+		foreach ($_REQUEST['topics'] as $topic) {
917
+					$_REQUEST['actions'][(int) $topic] = $_REQUEST['qaction'];
918
+		}
870 919
 	}
871 920
 
872 921
 	// Weird... how'd you get here?
873
-	if (empty($_REQUEST['actions']))
874
-		redirectexit($redirect_url);
922
+	if (empty($_REQUEST['actions'])) {
923
+			redirectexit($redirect_url);
924
+	}
875 925
 
876 926
 	// Validate each action.
877 927
 	$temp = array();
878 928
 	foreach ($_REQUEST['actions'] as $topic => $action)
879 929
 	{
880
-		if (in_array($action, $possibleActions))
881
-			$temp[(int) $topic] = $action;
930
+		if (in_array($action, $possibleActions)) {
931
+					$temp[(int) $topic] = $action;
932
+		}
882 933
 	}
883 934
 	$_REQUEST['actions'] = $temp;
884 935
 
@@ -899,27 +950,31 @@  discard block
 block discarded – undo
899 950
 		{
900 951
 			if (!empty($board))
901 952
 			{
902
-				if ($row['id_board'] != $board || ($modSettings['postmod_active'] && !$row['approved'] && !allowedTo('approve_posts')))
903
-					unset($_REQUEST['actions'][$row['id_topic']]);
904
-			}
905
-			else
953
+				if ($row['id_board'] != $board || ($modSettings['postmod_active'] && !$row['approved'] && !allowedTo('approve_posts'))) {
954
+									unset($_REQUEST['actions'][$row['id_topic']]);
955
+				}
956
+			} else
906 957
 			{
907 958
 				// Don't allow them to act on unapproved posts they can't see...
908
-				if ($modSettings['postmod_active'] && !$row['approved'] && !in_array(0, $boards_can['approve_posts']) && !in_array($row['id_board'], $boards_can['approve_posts']))
909
-					unset($_REQUEST['actions'][$row['id_topic']]);
959
+				if ($modSettings['postmod_active'] && !$row['approved'] && !in_array(0, $boards_can['approve_posts']) && !in_array($row['id_board'], $boards_can['approve_posts'])) {
960
+									unset($_REQUEST['actions'][$row['id_topic']]);
961
+				}
910 962
 				// Goodness, this is fun.  We need to validate the action.
911
-				elseif ($_REQUEST['actions'][$row['id_topic']] == 'sticky' && !in_array(0, $boards_can['make_sticky']) && !in_array($row['id_board'], $boards_can['make_sticky']))
912
-					unset($_REQUEST['actions'][$row['id_topic']]);
913
-				elseif ($_REQUEST['actions'][$row['id_topic']] == 'move' && !in_array(0, $boards_can['move_any']) && !in_array($row['id_board'], $boards_can['move_any']) && ($row['id_member_started'] != $user_info['id'] || (!in_array(0, $boards_can['move_own']) && !in_array($row['id_board'], $boards_can['move_own']))))
914
-					unset($_REQUEST['actions'][$row['id_topic']]);
915
-				elseif ($_REQUEST['actions'][$row['id_topic']] == 'remove' && !in_array(0, $boards_can['remove_any']) && !in_array($row['id_board'], $boards_can['remove_any']) && ($row['id_member_started'] != $user_info['id'] || (!in_array(0, $boards_can['remove_own']) && !in_array($row['id_board'], $boards_can['remove_own']))))
916
-					unset($_REQUEST['actions'][$row['id_topic']]);
963
+				elseif ($_REQUEST['actions'][$row['id_topic']] == 'sticky' && !in_array(0, $boards_can['make_sticky']) && !in_array($row['id_board'], $boards_can['make_sticky'])) {
964
+									unset($_REQUEST['actions'][$row['id_topic']]);
965
+				} elseif ($_REQUEST['actions'][$row['id_topic']] == 'move' && !in_array(0, $boards_can['move_any']) && !in_array($row['id_board'], $boards_can['move_any']) && ($row['id_member_started'] != $user_info['id'] || (!in_array(0, $boards_can['move_own']) && !in_array($row['id_board'], $boards_can['move_own'])))) {
966
+									unset($_REQUEST['actions'][$row['id_topic']]);
967
+				} elseif ($_REQUEST['actions'][$row['id_topic']] == 'remove' && !in_array(0, $boards_can['remove_any']) && !in_array($row['id_board'], $boards_can['remove_any']) && ($row['id_member_started'] != $user_info['id'] || (!in_array(0, $boards_can['remove_own']) && !in_array($row['id_board'], $boards_can['remove_own'])))) {
968
+									unset($_REQUEST['actions'][$row['id_topic']]);
969
+				}
917 970
 				// @todo $locked is not set, what are you trying to do? (taking the change it is supposed to be $row['locked'])
918
-				elseif ($_REQUEST['actions'][$row['id_topic']] == 'lock' && !in_array(0, $boards_can['lock_any']) && !in_array($row['id_board'], $boards_can['lock_any']) && ($row['id_member_started'] != $user_info['id'] || $row['locked'] == 1 || (!in_array(0, $boards_can['lock_own']) && !in_array($row['id_board'], $boards_can['lock_own']))))
919
-					unset($_REQUEST['actions'][$row['id_topic']]);
971
+				elseif ($_REQUEST['actions'][$row['id_topic']] == 'lock' && !in_array(0, $boards_can['lock_any']) && !in_array($row['id_board'], $boards_can['lock_any']) && ($row['id_member_started'] != $user_info['id'] || $row['locked'] == 1 || (!in_array(0, $boards_can['lock_own']) && !in_array($row['id_board'], $boards_can['lock_own'])))) {
972
+									unset($_REQUEST['actions'][$row['id_topic']]);
973
+				}
920 974
 				// If the topic is approved then you need permission to approve the posts within.
921
-				elseif ($_REQUEST['actions'][$row['id_topic']] == 'approve' && (!$row['unapproved_posts'] || (!in_array(0, $boards_can['approve_posts']) && !in_array($row['id_board'], $boards_can['approve_posts']))))
922
-					unset($_REQUEST['actions'][$row['id_topic']]);
975
+				elseif ($_REQUEST['actions'][$row['id_topic']] == 'approve' && (!$row['unapproved_posts'] || (!in_array(0, $boards_can['approve_posts']) && !in_array($row['id_board'], $boards_can['approve_posts'])))) {
976
+									unset($_REQUEST['actions'][$row['id_topic']]);
977
+				}
923 978
 			}
924 979
 		}
925 980
 		$smcFunc['db_free_result']($request);
@@ -937,11 +992,11 @@  discard block
 block discarded – undo
937 992
 	{
938 993
 		$topic = (int) $topic;
939 994
 
940
-		if ($action == 'markread')
941
-			$markCache[] = $topic;
942
-		elseif ($action == 'sticky')
943
-			$stickyCache[] = $topic;
944
-		elseif ($action == 'move')
995
+		if ($action == 'markread') {
996
+					$markCache[] = $topic;
997
+		} elseif ($action == 'sticky') {
998
+					$stickyCache[] = $topic;
999
+		} elseif ($action == 'move')
945 1000
 		{
946 1001
 			require_once($sourcedir . '/MoveTopic.php');
947 1002
 			moveTopicConcurrence();
@@ -949,23 +1004,25 @@  discard block
 block discarded – undo
949 1004
 			// $moveCache[0] is the topic, $moveCache[1] is the board to move to.
950 1005
 			$moveCache[1][$topic] = (int) (isset($_REQUEST['move_tos'][$topic]) ? $_REQUEST['move_tos'][$topic] : $_REQUEST['move_to']);
951 1006
 
952
-			if (empty($moveCache[1][$topic]))
953
-				continue;
1007
+			if (empty($moveCache[1][$topic])) {
1008
+							continue;
1009
+			}
954 1010
 
955 1011
 			$moveCache[0][] = $topic;
1012
+		} elseif ($action == 'remove') {
1013
+					$removeCache[] = $topic;
1014
+		} elseif ($action == 'lock') {
1015
+					$lockCache[] = $topic;
1016
+		} elseif ($action == 'approve') {
1017
+					$approveCache[] = $topic;
956 1018
 		}
957
-		elseif ($action == 'remove')
958
-			$removeCache[] = $topic;
959
-		elseif ($action == 'lock')
960
-			$lockCache[] = $topic;
961
-		elseif ($action == 'approve')
962
-			$approveCache[] = $topic;
963 1019
 	}
964 1020
 
965
-	if (empty($board))
966
-		$affectedBoards = array();
967
-	else
968
-		$affectedBoards = array($board => array(0, 0));
1021
+	if (empty($board)) {
1022
+			$affectedBoards = array();
1023
+	} else {
1024
+			$affectedBoards = array($board => array(0, 0));
1025
+	}
969 1026
 
970 1027
 	// Do all the stickies...
971 1028
 	if (!empty($stickyCache))
@@ -1025,14 +1082,16 @@  discard block
 block discarded – undo
1025 1082
 		{
1026 1083
 			$to = $moveCache[1][$row['id_topic']];
1027 1084
 
1028
-			if (empty($to))
1029
-				continue;
1085
+			if (empty($to)) {
1086
+							continue;
1087
+			}
1030 1088
 
1031 1089
 			// Does this topic's board count the posts or not?
1032 1090
 			$countPosts[$row['id_topic']] = empty($row['count_posts']);
1033 1091
 
1034
-			if (!isset($moveTos[$to]))
1035
-				$moveTos[$to] = array();
1092
+			if (!isset($moveTos[$to])) {
1093
+							$moveTos[$to] = array();
1094
+			}
1036 1095
 
1037 1096
 			$moveTos[$to][] = $row['id_topic'];
1038 1097
 
@@ -1046,8 +1105,9 @@  discard block
 block discarded – undo
1046 1105
 		require_once($sourcedir . '/MoveTopic.php');
1047 1106
 
1048 1107
 		// Do the actual moves...
1049
-		foreach ($moveTos as $to => $topics)
1050
-			moveTopics($topics, $to);
1108
+		foreach ($moveTos as $to => $topics) {
1109
+					moveTopics($topics, $to);
1110
+		}
1051 1111
 
1052 1112
 		// Does the post counts need to be updated?
1053 1113
 		if (!empty($moveTos))
@@ -1096,20 +1156,23 @@  discard block
 block discarded – undo
1096 1156
 
1097 1157
 				while ($row = $smcFunc['db_fetch_assoc']($request))
1098 1158
 				{
1099
-					if (!isset($members[$row['id_member']]))
1100
-						$members[$row['id_member']] = 0;
1159
+					if (!isset($members[$row['id_member']])) {
1160
+											$members[$row['id_member']] = 0;
1161
+					}
1101 1162
 
1102
-					if ($topicRecounts[$row['id_topic']] === '+')
1103
-						$members[$row['id_member']] += 1;
1104
-					else
1105
-						$members[$row['id_member']] -= 1;
1163
+					if ($topicRecounts[$row['id_topic']] === '+') {
1164
+											$members[$row['id_member']] += 1;
1165
+					} else {
1166
+											$members[$row['id_member']] -= 1;
1167
+					}
1106 1168
 				}
1107 1169
 
1108 1170
 				$smcFunc['db_free_result']($request);
1109 1171
 
1110 1172
 				// And now update them member's post counts
1111
-				foreach ($members as $id_member => $post_adj)
1112
-					updateMemberData($id_member, array('posts' => 'posts + ' . $post_adj));
1173
+				foreach ($members as $id_member => $post_adj) {
1174
+									updateMemberData($id_member, array('posts' => 'posts + ' . $post_adj));
1175
+				}
1113 1176
 
1114 1177
 			}
1115 1178
 		}
@@ -1189,8 +1252,9 @@  discard block
 block discarded – undo
1189 1252
 			approveTopics($approveCache);
1190 1253
 
1191 1254
 			// Time for some logging!
1192
-			foreach ($approveCache as $topic)
1193
-				logAction('approve_topic', array('topic' => $topic, 'member' => $approveCacheMembers[$topic]));
1255
+			foreach ($approveCache as $topic) {
1256
+							logAction('approve_topic', array('topic' => $topic, 'member' => $approveCacheMembers[$topic]));
1257
+			}
1194 1258
 		}
1195 1259
 	}
1196 1260
 
@@ -1225,8 +1289,7 @@  discard block
 block discarded – undo
1225 1289
 				$lockStatus[$row['id_topic']] = empty($row['locked']);
1226 1290
 			}
1227 1291
 			$smcFunc['db_free_result']($result);
1228
-		}
1229
-		else
1292
+		} else
1230 1293
 		{
1231 1294
 			$result = $smcFunc['db_query']('', '
1232 1295
 				SELECT id_topic, locked, id_board
@@ -1276,13 +1339,15 @@  discard block
 block discarded – undo
1276 1339
 			)
1277 1340
 		);
1278 1341
 		$logged_topics = array();
1279
-		while ($row = $smcFunc['db_fetch_assoc']($request))
1280
-			$logged_topics[$row['id_topic']] = $row['unwatched'];
1342
+		while ($row = $smcFunc['db_fetch_assoc']($request)) {
1343
+					$logged_topics[$row['id_topic']] = $row['unwatched'];
1344
+		}
1281 1345
 		$smcFunc['db_free_result']($request);
1282 1346
 
1283 1347
 		$markArray = array();
1284
-		foreach ($markCache as $topic)
1285
-			$markArray[] = array($modSettings['maxMsgID'], $user_info['id'], $topic, (isset($logged_topics[$topic]) ? $logged_topics[$topic] : 0));
1348
+		foreach ($markCache as $topic) {
1349
+					$markArray[] = array($modSettings['maxMsgID'], $user_info['id'], $topic, (isset($logged_topics[$topic]) ? $logged_topics[$topic] : 0));
1350
+		}
1286 1351
 
1287 1352
 		$smcFunc['db_insert']('replace',
1288 1353
 			'{db_prefix}log_topics',
@@ -1295,8 +1360,9 @@  discard block
 block discarded – undo
1295 1360
 	foreach ($moveCache as $topic)
1296 1361
 	{
1297 1362
 		// Didn't actually move anything!
1298
-		if (!isset($topic[0]))
1299
-			break;
1363
+		if (!isset($topic[0])) {
1364
+					break;
1365
+		}
1300 1366
 
1301 1367
 		logAction('move', array('topic' => $topic[0], 'board_from' => $topic[1], 'board_to' => $topic[2]));
1302 1368
 		sendNotifications($topic[0], 'move');
@@ -1318,8 +1384,9 @@  discard block
 block discarded – undo
1318 1384
 		'calendar_updated' => time(),
1319 1385
 	));
1320 1386
 
1321
-	if (!empty($affectedBoards))
1322
-		updateLastMessages(array_keys($affectedBoards));
1387
+	if (!empty($affectedBoards)) {
1388
+			updateLastMessages(array_keys($affectedBoards));
1389
+	}
1323 1390
 
1324 1391
 	redirectexit($redirect_url);
1325 1392
 }
Please login to merge, or discard this patch.
index.php 2 patches
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -104,7 +104,7 @@
 block discarded – undo
104 104
  *
105 105
  * @param string $class The fully-qualified class name.
106 106
  */
107
-spl_autoload_register(function ($class) use ($sourcedir)
107
+spl_autoload_register(function($class) use ($sourcedir)
108 108
 {
109 109
 	$classMap = array(
110 110
 		'ReCaptcha\\' => 'ReCaptcha/',
Please login to merge, or discard this patch.
Braces   +35 added lines, -24 removed lines patch added patch discarded remove patch
@@ -32,16 +32,18 @@  discard block
 block discarded – undo
32 32
 ob_start();
33 33
 
34 34
 // Do some cleaning, just in case.
35
-foreach (array('db_character_set', 'cachedir') as $variable)
35
+foreach (array('db_character_set', 'cachedir') as $variable) {
36 36
 	if (isset($GLOBALS[$variable]))
37 37
 		unset($GLOBALS[$variable], $GLOBALS[$variable]);
38
+}
38 39
 
39 40
 // Load the settings...
40 41
 require_once(dirname(__FILE__) . '/Settings.php');
41 42
 
42 43
 // Make absolutely sure the cache directory is defined.
43
-if ((empty($cachedir) || !file_exists($cachedir)) && file_exists($boarddir . '/cache'))
44
+if ((empty($cachedir) || !file_exists($cachedir)) && file_exists($boarddir . '/cache')) {
44 45
 	$cachedir = $boarddir . '/cache';
46
+}
45 47
 
46 48
 // Without those we can't go anywhere
47 49
 require_once($sourcedir . '/QueryString.php');
@@ -51,8 +53,9 @@  discard block
 block discarded – undo
51 53
 require_once($sourcedir . '/Load.php');
52 54
 
53 55
 // If $maintenance is set specifically to 2, then we're upgrading or something.
54
-if (!empty($maintenance) && $maintenance == 2)
56
+if (!empty($maintenance) && $maintenance == 2) {
55 57
 	display_maintenance_message();
58
+}
56 59
 
57 60
 // Create a variable to store some SMF specific functions in.
58 61
 $smcFunc = array();
@@ -67,8 +70,9 @@  discard block
 block discarded – undo
67 70
 cleanRequest();
68 71
 
69 72
 // Seed the random generator.
70
-if (empty($modSettings['rand_seed']) || mt_rand(1, 250) == 69)
73
+if (empty($modSettings['rand_seed']) || mt_rand(1, 250) == 69) {
71 74
 	smf_seed_generator();
75
+}
72 76
 
73 77
 // Before we get carried away, are we doing a scheduled task? If so save CPU cycles by jumping out!
74 78
 if (isset($_GET['scheduled']))
@@ -88,9 +92,9 @@  discard block
 block discarded – undo
88 92
 if (!empty($modSettings['enableCompressedOutput']) && !headers_sent())
89 93
 {
90 94
 	// If zlib is being used, turn off output compression.
91
-	if (ini_get('zlib.output_compression') >= 1 || ini_get('output_handler') == 'ob_gzhandler')
92
-		$modSettings['enableCompressedOutput'] = '0';
93
-	else
95
+	if (ini_get('zlib.output_compression') >= 1 || ini_get('output_handler') == 'ob_gzhandler') {
96
+			$modSettings['enableCompressedOutput'] = '0';
97
+	} else
94 98
 	{
95 99
 		ob_end_clean();
96 100
 		ob_start('ob_gzhandler');
@@ -182,18 +186,21 @@  discard block
 block discarded – undo
182 186
 	loadPermissions();
183 187
 
184 188
 	// Attachments don't require the entire theme to be loaded.
185
-	if (isset($_REQUEST['action']) && $_REQUEST['action'] == 'dlattach')
186
-		detectBrowser();
189
+	if (isset($_REQUEST['action']) && $_REQUEST['action'] == 'dlattach') {
190
+			detectBrowser();
191
+	}
187 192
 	// Load the current theme.  (note that ?theme=1 will also work, may be used for guest theming.)
188
-	else
189
-		loadTheme();
193
+	else {
194
+			loadTheme();
195
+	}
190 196
 
191 197
 	// Check if the user should be disallowed access.
192 198
 	is_not_banned();
193 199
 
194 200
 	// If we are in a topic and don't have permission to approve it then duck out now.
195
-	if (!empty($topic) && empty($board_info['cur_topic_approved']) && !allowedTo('approve_posts') && ($user_info['id'] != $board_info['cur_topic_starter'] || $user_info['is_guest']))
196
-		fatal_lang_error('not_a_topic', false);
201
+	if (!empty($topic) && empty($board_info['cur_topic_approved']) && !allowedTo('approve_posts') && ($user_info['id'] != $board_info['cur_topic_starter'] || $user_info['is_guest'])) {
202
+			fatal_lang_error('not_a_topic', false);
203
+	}
197 204
 
198 205
 	$no_stat_actions = array('clock', 'dlattach', 'findmember', 'jsoption', 'likes', 'loadeditorlocale', 'modifycat', 'requestmembers', 'smstats', 'suggest', 'about:unknown', '.xml', 'xmlhttp', 'verificationcode', 'viewquery', 'viewsmfile');
199 206
 	call_integration_hook('integrate_pre_log_stats', array(&$no_stat_actions));
@@ -204,8 +211,9 @@  discard block
 block discarded – undo
204 211
 		writeLog();
205 212
 
206 213
 		// Track forum statistics and hits...?
207
-		if (!empty($modSettings['hitStats']))
208
-			trackStats(array('hits' => '+'));
214
+		if (!empty($modSettings['hitStats'])) {
215
+					trackStats(array('hits' => '+'));
216
+		}
209 217
 	}
210 218
 	unset($no_stat_actions);
211 219
 
@@ -219,13 +227,14 @@  discard block
 block discarded – undo
219 227
 			return ($_REQUEST['action'] == 'login2' ? 'Login2' : ($_REQUEST['action'] == 'logintfa' ? 'LoginTFA' : 'Logout'));
220 228
 		}
221 229
 		// Don't even try it, sonny.
222
-		else
223
-			return 'InMaintenance';
230
+		else {
231
+					return 'InMaintenance';
232
+		}
224 233
 	}
225 234
 	// If guest access is off, a guest can only do one of the very few following actions.
226
-	elseif (empty($modSettings['allow_guestAccess']) && $user_info['is_guest'] && (!isset($_REQUEST['action']) || !in_array($_REQUEST['action'], array('coppa', 'login', 'login2', 'logintfa', 'reminder', 'activate', 'help', 'helpadmin', 'smstats', 'verificationcode', 'signup', 'signup2'))))
227
-		return 'KickGuest';
228
-	elseif (empty($_REQUEST['action']))
235
+	elseif (empty($modSettings['allow_guestAccess']) && $user_info['is_guest'] && (!isset($_REQUEST['action']) || !in_array($_REQUEST['action'], array('coppa', 'login', 'login2', 'logintfa', 'reminder', 'activate', 'help', 'helpadmin', 'smstats', 'verificationcode', 'signup', 'signup2')))) {
236
+			return 'KickGuest';
237
+	} elseif (empty($_REQUEST['action']))
229 238
 	{
230 239
 		// Action and board are both empty... BoardIndex! Unless someone else wants to do something different.
231 240
 		if (empty($board) && empty($topic))
@@ -239,8 +248,9 @@  discard block
 block discarded – undo
239 248
 
240 249
 				$call = call_helper($defaultAction, true);
241 250
 
242
-				if (!empty($call))
243
-					return $call;
251
+				if (!empty($call)) {
252
+									return $call;
253
+				}
244 254
 			}
245 255
 
246 256
 			// No default action huh? then go to our good old BoardIndex.
@@ -370,8 +380,9 @@  discard block
 block discarded – undo
370 380
 
371 381
 			$call = call_helper($fallbackAction, true);
372 382
 
373
-			if (!empty($call))
374
-				return $call;
383
+			if (!empty($call)) {
384
+							return $call;
385
+			}
375 386
 		}
376 387
 
377 388
 		// No fallback action, huh?
Please login to merge, or discard this patch.
Sources/minify/path-converter/src/Converter.php 2 patches
Indentation   +169 added lines, -169 removed lines patch added patch discarded remove patch
@@ -18,178 +18,178 @@
 block discarded – undo
18 18
  */
19 19
 class Converter
20 20
 {
21
-    /**
22
-     * @var string
23
-     */
24
-    protected $from;
25
-
26
-    /**
27
-     * @var string
28
-     */
29
-    protected $to;
30
-
31
-    /**
32
-     * @param string $from The original base path (directory, not file!)
33
-     * @param string $to   The new base path (directory, not file!)
34
-     */
35
-    public function __construct($from, $to)
36
-    {
37
-        $shared = $this->shared($from, $to);
38
-        if ($shared === '') {
39
-            // when both paths have nothing in common, one of them is probably
40
-            // absolute while the other is relative
41
-            $cwd = getcwd();
42
-            $from = strpos($from, $cwd) === 0 ? $from : $cwd.'/'.$from;
43
-            $to = strpos($to, $cwd) === 0 ? $to : $cwd.'/'.$to;
44
-
45
-            // or traveling the tree via `..`
46
-            // attempt to resolve path, or assume it's fine if it doesn't exist
47
-            $from = realpath($from) ?: $from;
48
-            $to = realpath($to) ?: $to;
49
-        }
50
-
51
-        $from = $this->dirname($from);
52
-        $to = $this->dirname($to);
53
-
54
-        $from = $this->normalize($from);
55
-        $to = $this->normalize($to);
56
-
57
-        $this->from = $from;
58
-        $this->to = $to;
59
-    }
60
-
61
-    /**
62
-     * Normalize path.
63
-     *
64
-     * @param string $path
65
-     *
66
-     * @return string
67
-     */
68
-    protected function normalize($path)
69
-    {
70
-        // deal with different operating systems' directory structure
71
-        $path = rtrim(str_replace(DIRECTORY_SEPARATOR, '/', $path), '/');
72
-
73
-        /*
21
+	/**
22
+	 * @var string
23
+	 */
24
+	protected $from;
25
+
26
+	/**
27
+	 * @var string
28
+	 */
29
+	protected $to;
30
+
31
+	/**
32
+	 * @param string $from The original base path (directory, not file!)
33
+	 * @param string $to   The new base path (directory, not file!)
34
+	 */
35
+	public function __construct($from, $to)
36
+	{
37
+		$shared = $this->shared($from, $to);
38
+		if ($shared === '') {
39
+			// when both paths have nothing in common, one of them is probably
40
+			// absolute while the other is relative
41
+			$cwd = getcwd();
42
+			$from = strpos($from, $cwd) === 0 ? $from : $cwd.'/'.$from;
43
+			$to = strpos($to, $cwd) === 0 ? $to : $cwd.'/'.$to;
44
+
45
+			// or traveling the tree via `..`
46
+			// attempt to resolve path, or assume it's fine if it doesn't exist
47
+			$from = realpath($from) ?: $from;
48
+			$to = realpath($to) ?: $to;
49
+		}
50
+
51
+		$from = $this->dirname($from);
52
+		$to = $this->dirname($to);
53
+
54
+		$from = $this->normalize($from);
55
+		$to = $this->normalize($to);
56
+
57
+		$this->from = $from;
58
+		$this->to = $to;
59
+	}
60
+
61
+	/**
62
+	 * Normalize path.
63
+	 *
64
+	 * @param string $path
65
+	 *
66
+	 * @return string
67
+	 */
68
+	protected function normalize($path)
69
+	{
70
+		// deal with different operating systems' directory structure
71
+		$path = rtrim(str_replace(DIRECTORY_SEPARATOR, '/', $path), '/');
72
+
73
+		/*
74 74
          * Example:
75 75
          *     /home/forkcms/frontend/cache/compiled_templates/../../core/layout/css/../images/img.gif
76 76
          * to
77 77
          *     /home/forkcms/frontend/core/layout/images/img.gif
78 78
          */
79
-        do {
80
-            $path = preg_replace('/[^\/]+(?<!\.\.)\/\.\.\//', '', $path, -1, $count);
81
-        } while ($count);
82
-
83
-        return $path;
84
-    }
85
-
86
-    /**
87
-     * Figure out the shared path of 2 locations.
88
-     *
89
-     * Example:
90
-     *     /home/forkcms/frontend/core/layout/images/img.gif
91
-     * and
92
-     *     /home/forkcms/frontend/cache/minified_css
93
-     * share
94
-     *     /home/forkcms/frontend
95
-     *
96
-     * @param string $path1
97
-     * @param string $path2
98
-     *
99
-     * @return string
100
-     */
101
-    protected function shared($path1, $path2)
102
-    {
103
-        // $path could theoretically be empty (e.g. no path is given), in which
104
-        // case it shouldn't expand to array(''), which would compare to one's
105
-        // root /
106
-        $path1 = $path1 ? explode('/', $path1) : array();
107
-        $path2 = $path2 ? explode('/', $path2) : array();
108
-
109
-        $shared = array();
110
-
111
-        // compare paths & strip identical ancestors
112
-        foreach ($path1 as $i => $chunk) {
113
-            if (isset($path2[$i]) && $path1[$i] == $path2[$i]) {
114
-                $shared[] = $chunk;
115
-            } else {
116
-                break;
117
-            }
118
-        }
119
-
120
-        return implode('/', $shared);
121
-    }
122
-
123
-    /**
124
-     * Convert paths relative from 1 file to another.
125
-     *
126
-     * E.g.
127
-     *     ../images/img.gif relative to /home/forkcms/frontend/core/layout/css
128
-     * should become:
129
-     *     ../../core/layout/images/img.gif relative to
130
-     *     /home/forkcms/frontend/cache/minified_css
131
-     *
132
-     * @param string $path The relative path that needs to be converted.
133
-     *
134
-     * @return string The new relative path.
135
-     */
136
-    public function convert($path)
137
-    {
138
-        // quit early if conversion makes no sense
139
-        if ($this->from === $this->to) {
140
-            return $path;
141
-        }
142
-
143
-        $path = $this->normalize($path);
144
-        // if we're not dealing with a relative path, just return absolute
145
-        if (strpos($path, '/') === 0) {
146
-            return $path;
147
-        }
148
-
149
-        // normalize paths
150
-        $path = $this->normalize($this->from.'/'.$path);
151
-
152
-        // strip shared ancestor paths
153
-        $shared = $this->shared($path, $this->to);
154
-        $path = mb_substr($path, mb_strlen($shared));
155
-        $to = mb_substr($this->to, mb_strlen($shared));
156
-
157
-        // add .. for every directory that needs to be traversed to new path
158
-        $to = str_repeat('../', mb_substr_count($to, '/'));
159
-
160
-        return $to.ltrim($path, '/');
161
-    }
162
-
163
-    /**
164
-     * Attempt to get the directory name from a path.
165
-     *
166
-     * @param string $path
167
-     *
168
-     * @return string
169
-     */
170
-    public function dirname($path)
171
-    {
172
-        if (is_file($path)) {
173
-            return dirname($path);
174
-        }
175
-
176
-        if (is_dir($path)) {
177
-            return rtrim($path, '/');
178
-        }
179
-
180
-        // no known file/dir, start making assumptions
181
-
182
-        // ends in / = dir
183
-        if (mb_substr($path, -1) === '/') {
184
-            return rtrim($path, '/');
185
-        }
186
-
187
-        // has a dot in the name, likely a file
188
-        if (preg_match('/.*\..*$/', basename($path)) !== 0) {
189
-            return dirname($path);
190
-        }
191
-
192
-        // you're on your own here!
193
-        return $path;
194
-    }
79
+		do {
80
+			$path = preg_replace('/[^\/]+(?<!\.\.)\/\.\.\//', '', $path, -1, $count);
81
+		} while ($count);
82
+
83
+		return $path;
84
+	}
85
+
86
+	/**
87
+	 * Figure out the shared path of 2 locations.
88
+	 *
89
+	 * Example:
90
+	 *     /home/forkcms/frontend/core/layout/images/img.gif
91
+	 * and
92
+	 *     /home/forkcms/frontend/cache/minified_css
93
+	 * share
94
+	 *     /home/forkcms/frontend
95
+	 *
96
+	 * @param string $path1
97
+	 * @param string $path2
98
+	 *
99
+	 * @return string
100
+	 */
101
+	protected function shared($path1, $path2)
102
+	{
103
+		// $path could theoretically be empty (e.g. no path is given), in which
104
+		// case it shouldn't expand to array(''), which would compare to one's
105
+		// root /
106
+		$path1 = $path1 ? explode('/', $path1) : array();
107
+		$path2 = $path2 ? explode('/', $path2) : array();
108
+
109
+		$shared = array();
110
+
111
+		// compare paths & strip identical ancestors
112
+		foreach ($path1 as $i => $chunk) {
113
+			if (isset($path2[$i]) && $path1[$i] == $path2[$i]) {
114
+				$shared[] = $chunk;
115
+			} else {
116
+				break;
117
+			}
118
+		}
119
+
120
+		return implode('/', $shared);
121
+	}
122
+
123
+	/**
124
+	 * Convert paths relative from 1 file to another.
125
+	 *
126
+	 * E.g.
127
+	 *     ../images/img.gif relative to /home/forkcms/frontend/core/layout/css
128
+	 * should become:
129
+	 *     ../../core/layout/images/img.gif relative to
130
+	 *     /home/forkcms/frontend/cache/minified_css
131
+	 *
132
+	 * @param string $path The relative path that needs to be converted.
133
+	 *
134
+	 * @return string The new relative path.
135
+	 */
136
+	public function convert($path)
137
+	{
138
+		// quit early if conversion makes no sense
139
+		if ($this->from === $this->to) {
140
+			return $path;
141
+		}
142
+
143
+		$path = $this->normalize($path);
144
+		// if we're not dealing with a relative path, just return absolute
145
+		if (strpos($path, '/') === 0) {
146
+			return $path;
147
+		}
148
+
149
+		// normalize paths
150
+		$path = $this->normalize($this->from.'/'.$path);
151
+
152
+		// strip shared ancestor paths
153
+		$shared = $this->shared($path, $this->to);
154
+		$path = mb_substr($path, mb_strlen($shared));
155
+		$to = mb_substr($this->to, mb_strlen($shared));
156
+
157
+		// add .. for every directory that needs to be traversed to new path
158
+		$to = str_repeat('../', mb_substr_count($to, '/'));
159
+
160
+		return $to.ltrim($path, '/');
161
+	}
162
+
163
+	/**
164
+	 * Attempt to get the directory name from a path.
165
+	 *
166
+	 * @param string $path
167
+	 *
168
+	 * @return string
169
+	 */
170
+	public function dirname($path)
171
+	{
172
+		if (is_file($path)) {
173
+			return dirname($path);
174
+		}
175
+
176
+		if (is_dir($path)) {
177
+			return rtrim($path, '/');
178
+		}
179
+
180
+		// no known file/dir, start making assumptions
181
+
182
+		// ends in / = dir
183
+		if (mb_substr($path, -1) === '/') {
184
+			return rtrim($path, '/');
185
+		}
186
+
187
+		// has a dot in the name, likely a file
188
+		if (preg_match('/.*\..*$/', basename($path)) !== 0) {
189
+			return dirname($path);
190
+		}
191
+
192
+		// you're on your own here!
193
+		return $path;
194
+	}
195 195
 }
Please login to merge, or discard this patch.
Spacing   +4 added lines, -4 removed lines patch added patch discarded remove patch
@@ -39,8 +39,8 @@  discard block
 block discarded – undo
39 39
             // when both paths have nothing in common, one of them is probably
40 40
             // absolute while the other is relative
41 41
             $cwd = getcwd();
42
-            $from = strpos($from, $cwd) === 0 ? $from : $cwd.'/'.$from;
43
-            $to = strpos($to, $cwd) === 0 ? $to : $cwd.'/'.$to;
42
+            $from = strpos($from, $cwd) === 0 ? $from : $cwd . '/' . $from;
43
+            $to = strpos($to, $cwd) === 0 ? $to : $cwd . '/' . $to;
44 44
 
45 45
             // or traveling the tree via `..`
46 46
             // attempt to resolve path, or assume it's fine if it doesn't exist
@@ -147,7 +147,7 @@  discard block
 block discarded – undo
147 147
         }
148 148
 
149 149
         // normalize paths
150
-        $path = $this->normalize($this->from.'/'.$path);
150
+        $path = $this->normalize($this->from . '/' . $path);
151 151
 
152 152
         // strip shared ancestor paths
153 153
         $shared = $this->shared($path, $this->to);
@@ -157,7 +157,7 @@  discard block
 block discarded – undo
157 157
         // add .. for every directory that needs to be traversed to new path
158 158
         $to = str_repeat('../', mb_substr_count($to, '/'));
159 159
 
160
-        return $to.ltrim($path, '/');
160
+        return $to . ltrim($path, '/');
161 161
     }
162 162
 
163 163
     /**
Please login to merge, or discard this patch.
Sources/minify/src/Minify.php 2 patches
Indentation   +392 added lines, -392 removed lines patch added patch discarded remove patch
@@ -16,335 +16,335 @@  discard block
 block discarded – undo
16 16
  */
17 17
 abstract class Minify
18 18
 {
19
-    /**
20
-     * The data to be minified.
21
-     *
22
-     * @var string[]
23
-     */
24
-    protected $data = array();
25
-
26
-    /**
27
-     * Array of patterns to match.
28
-     *
29
-     * @var string[]
30
-     */
31
-    protected $patterns = array();
32
-
33
-    /**
34
-     * This array will hold content of strings and regular expressions that have
35
-     * been extracted from the JS source code, so we can reliably match "code",
36
-     * without having to worry about potential "code-like" characters inside.
37
-     *
38
-     * @var string[]
39
-     */
40
-    public $extracted = array();
41
-
42
-    /**
43
-     * Init the minify class - optionally, code may be passed along already.
44
-     */
45
-    public function __construct(/* $data = null, ... */)
46
-    {
47
-        // it's possible to add the source through the constructor as well ;)
48
-        if (func_num_args()) {
49
-            call_user_func_array(array($this, 'add'), func_get_args());
50
-        }
51
-    }
52
-
53
-    /**
54
-     * Add a file or straight-up code to be minified.
55
-     *
56
-     * @param string|string[] $data
57
-     */
58
-    public function add($data /* $data = null, ... */)
59
-    {
60
-        // bogus "usage" of parameter $data: scrutinizer warns this variable is
61
-        // not used (we're using func_get_args instead to support overloading),
62
-        // but it still needs to be defined because it makes no sense to have
63
-        // this function without argument :)
64
-        $args = array($data) + func_get_args();
65
-
66
-        // this method can be overloaded
67
-        foreach ($args as $data) {
68
-            if (is_array($data)) {
69
-                call_user_func_array(array($this, 'add'), $data);
70
-                continue;
71
-            }
72
-
73
-            // redefine var
74
-            $data = (string) $data;
75
-
76
-            // load data
77
-            $value = $this->load($data);
78
-            $key = ($data != $value) ? $data : count($this->data);
79
-
80
-            // replace CR linefeeds etc.
81
-            // @see https://github.com/matthiasmullie/minify/pull/139
82
-            $value = str_replace(array("\r\n", "\r"), "\n", $value);
83
-
84
-            // store data
85
-            $this->data[$key] = $value;
86
-        }
87
-    }
88
-
89
-    /**
90
-     * Minify the data & (optionally) saves it to a file.
91
-     *
92
-     * @param string[optional] $path Path to write the data to
93
-     *
94
-     * @return string The minified data
95
-     */
96
-    public function minify($path = null)
97
-    {
98
-        $content = $this->execute($path);
99
-
100
-        // save to path
101
-        if ($path !== null) {
102
-            $this->save($content, $path);
103
-        }
104
-
105
-        return $content;
106
-    }
107
-
108
-    /**
109
-     * Minify & gzip the data & (optionally) saves it to a file.
110
-     *
111
-     * @param string[optional] $path  Path to write the data to
112
-     * @param int[optional]    $level Compression level, from 0 to 9
113
-     *
114
-     * @return string The minified & gzipped data
115
-     */
116
-    public function gzip($path = null, $level = 9)
117
-    {
118
-        $content = $this->execute($path);
119
-        $content = gzencode($content, $level, FORCE_GZIP);
120
-
121
-        // save to path
122
-        if ($path !== null) {
123
-            $this->save($content, $path);
124
-        }
125
-
126
-        return $content;
127
-    }
128
-
129
-    /**
130
-     * Minify the data & write it to a CacheItemInterface object.
131
-     *
132
-     * @param CacheItemInterface $item Cache item to write the data to
133
-     *
134
-     * @return CacheItemInterface Cache item with the minifier data
135
-     */
136
-    public function cache(CacheItemInterface $item)
137
-    {
138
-        $content = $this->execute();
139
-        $item->set($content);
140
-
141
-        return $item;
142
-    }
143
-
144
-    /**
145
-     * Minify the data.
146
-     *
147
-     * @param string[optional] $path Path to write the data to
148
-     *
149
-     * @return string The minified data
150
-     */
151
-    abstract public function execute($path = null);
152
-
153
-    /**
154
-     * Load data.
155
-     *
156
-     * @param string $data Either a path to a file or the content itself
157
-     *
158
-     * @return string
159
-     */
160
-    protected function load($data)
161
-    {
162
-        // check if the data is a file
163
-        if ($this->canImportFile($data)) {
164
-            $data = file_get_contents($data);
165
-
166
-            // strip BOM, if any
167
-            if (substr($data, 0, 3) == "\xef\xbb\xbf") {
168
-                $data = substr($data, 3);
169
-            }
170
-        }
171
-
172
-        return $data;
173
-    }
174
-
175
-    /**
176
-     * Save to file.
177
-     *
178
-     * @param string $content The minified data
179
-     * @param string $path    The path to save the minified data to
180
-     *
181
-     * @throws IOException
182
-     */
183
-    protected function save($content, $path)
184
-    {
185
-        $handler = $this->openFileForWriting($path);
186
-
187
-        $this->writeToFile($handler, $content);
188
-
189
-        @fclose($handler);
190
-    }
191
-
192
-    /**
193
-     * Register a pattern to execute against the source content.
194
-     *
195
-     * @param string          $pattern     PCRE pattern
196
-     * @param string|callable $replacement Replacement value for matched pattern
197
-     */
198
-    protected function registerPattern($pattern, $replacement = '')
199
-    {
200
-        // study the pattern, we'll execute it more than once
201
-        $pattern .= 'S';
202
-
203
-        $this->patterns[] = array($pattern, $replacement);
204
-    }
205
-
206
-    /**
207
-     * We can't "just" run some regular expressions against JavaScript: it's a
208
-     * complex language. E.g. having an occurrence of // xyz would be a comment,
209
-     * unless it's used within a string. Of you could have something that looks
210
-     * like a 'string', but inside a comment.
211
-     * The only way to accurately replace these pieces is to traverse the JS one
212
-     * character at a time and try to find whatever starts first.
213
-     *
214
-     * @param string $content The content to replace patterns in
215
-     *
216
-     * @return string The (manipulated) content
217
-     */
218
-    protected function replace($content)
219
-    {
220
-        $processed = '';
221
-        $positions = array_fill(0, count($this->patterns), -1);
222
-        $matches = array();
223
-
224
-        while ($content) {
225
-            // find first match for all patterns
226
-            foreach ($this->patterns as $i => $pattern) {
227
-                list($pattern, $replacement) = $pattern;
228
-
229
-                // no need to re-run matches that are still in the part of the
230
-                // content that hasn't been processed
231
-                if ($positions[$i] >= 0) {
232
-                    continue;
233
-                }
234
-
235
-                $match = null;
236
-                if (preg_match($pattern, $content, $match)) {
237
-                    $matches[$i] = $match;
238
-
239
-                    // we'll store the match position as well; that way, we
240
-                    // don't have to redo all preg_matches after changing only
241
-                    // the first (we'll still know where those others are)
242
-                    $positions[$i] = strpos($content, $match[0]);
243
-                } else {
244
-                    // if the pattern couldn't be matched, there's no point in
245
-                    // executing it again in later runs on this same content;
246
-                    // ignore this one until we reach end of content
247
-                    unset($matches[$i]);
248
-                    $positions[$i] = strlen($content);
249
-                }
250
-            }
251
-
252
-            // no more matches to find: everything's been processed, break out
253
-            if (!$matches) {
254
-                $processed .= $content;
255
-                break;
256
-            }
257
-
258
-            // see which of the patterns actually found the first thing (we'll
259
-            // only want to execute that one, since we're unsure if what the
260
-            // other found was not inside what the first found)
261
-            $discardLength = min($positions);
262
-            $firstPattern = array_search($discardLength, $positions);
263
-            $match = $matches[$firstPattern][0];
264
-
265
-            // execute the pattern that matches earliest in the content string
266
-            list($pattern, $replacement) = $this->patterns[$firstPattern];
267
-            $replacement = $this->replacePattern($pattern, $replacement, $content);
268
-
269
-            // figure out which part of the string was unmatched; that's the
270
-            // part we'll execute the patterns on again next
271
-            $content = substr($content, $discardLength);
272
-            $unmatched = (string) substr($content, strpos($content, $match) + strlen($match));
273
-
274
-            // move the replaced part to $processed and prepare $content to
275
-            // again match batch of patterns against
276
-            $processed .= substr($replacement, 0, strlen($replacement) - strlen($unmatched));
277
-            $content = $unmatched;
278
-
279
-            // first match has been replaced & that content is to be left alone,
280
-            // the next matches will start after this replacement, so we should
281
-            // fix their offsets
282
-            foreach ($positions as $i => $position) {
283
-                $positions[$i] -= $discardLength + strlen($match);
284
-            }
285
-        }
286
-
287
-        return $processed;
288
-    }
289
-
290
-    /**
291
-     * This is where a pattern is matched against $content and the matches
292
-     * are replaced by their respective value.
293
-     * This function will be called plenty of times, where $content will always
294
-     * move up 1 character.
295
-     *
296
-     * @param string          $pattern     Pattern to match
297
-     * @param string|callable $replacement Replacement value
298
-     * @param string          $content     Content to match pattern against
299
-     *
300
-     * @return string
301
-     */
302
-    protected function replacePattern($pattern, $replacement, $content)
303
-    {
304
-        if (is_callable($replacement)) {
305
-            return preg_replace_callback($pattern, $replacement, $content, 1, $count);
306
-        } else {
307
-            return preg_replace($pattern, $replacement, $content, 1, $count);
308
-        }
309
-    }
310
-
311
-    /**
312
-     * Strings are a pattern we need to match, in order to ignore potential
313
-     * code-like content inside them, but we just want all of the string
314
-     * content to remain untouched.
315
-     *
316
-     * This method will replace all string content with simple STRING#
317
-     * placeholder text, so we've rid all strings from characters that may be
318
-     * misinterpreted. Original string content will be saved in $this->extracted
319
-     * and after doing all other minifying, we can restore the original content
320
-     * via restoreStrings().
321
-     *
322
-     * @param string[optional] $chars
323
-     */
324
-    protected function extractStrings($chars = '\'"')
325
-    {
326
-        // PHP only supports $this inside anonymous functions since 5.4
327
-        $minifier = $this;
328
-        $callback = function ($match) use ($minifier) {
329
-            // check the second index here, because the first always contains a quote
330
-            if ($match[2] === '') {
331
-                /*
19
+	/**
20
+	 * The data to be minified.
21
+	 *
22
+	 * @var string[]
23
+	 */
24
+	protected $data = array();
25
+
26
+	/**
27
+	 * Array of patterns to match.
28
+	 *
29
+	 * @var string[]
30
+	 */
31
+	protected $patterns = array();
32
+
33
+	/**
34
+	 * This array will hold content of strings and regular expressions that have
35
+	 * been extracted from the JS source code, so we can reliably match "code",
36
+	 * without having to worry about potential "code-like" characters inside.
37
+	 *
38
+	 * @var string[]
39
+	 */
40
+	public $extracted = array();
41
+
42
+	/**
43
+	 * Init the minify class - optionally, code may be passed along already.
44
+	 */
45
+	public function __construct(/* $data = null, ... */)
46
+	{
47
+		// it's possible to add the source through the constructor as well ;)
48
+		if (func_num_args()) {
49
+			call_user_func_array(array($this, 'add'), func_get_args());
50
+		}
51
+	}
52
+
53
+	/**
54
+	 * Add a file or straight-up code to be minified.
55
+	 *
56
+	 * @param string|string[] $data
57
+	 */
58
+	public function add($data /* $data = null, ... */)
59
+	{
60
+		// bogus "usage" of parameter $data: scrutinizer warns this variable is
61
+		// not used (we're using func_get_args instead to support overloading),
62
+		// but it still needs to be defined because it makes no sense to have
63
+		// this function without argument :)
64
+		$args = array($data) + func_get_args();
65
+
66
+		// this method can be overloaded
67
+		foreach ($args as $data) {
68
+			if (is_array($data)) {
69
+				call_user_func_array(array($this, 'add'), $data);
70
+				continue;
71
+			}
72
+
73
+			// redefine var
74
+			$data = (string) $data;
75
+
76
+			// load data
77
+			$value = $this->load($data);
78
+			$key = ($data != $value) ? $data : count($this->data);
79
+
80
+			// replace CR linefeeds etc.
81
+			// @see https://github.com/matthiasmullie/minify/pull/139
82
+			$value = str_replace(array("\r\n", "\r"), "\n", $value);
83
+
84
+			// store data
85
+			$this->data[$key] = $value;
86
+		}
87
+	}
88
+
89
+	/**
90
+	 * Minify the data & (optionally) saves it to a file.
91
+	 *
92
+	 * @param string[optional] $path Path to write the data to
93
+	 *
94
+	 * @return string The minified data
95
+	 */
96
+	public function minify($path = null)
97
+	{
98
+		$content = $this->execute($path);
99
+
100
+		// save to path
101
+		if ($path !== null) {
102
+			$this->save($content, $path);
103
+		}
104
+
105
+		return $content;
106
+	}
107
+
108
+	/**
109
+	 * Minify & gzip the data & (optionally) saves it to a file.
110
+	 *
111
+	 * @param string[optional] $path  Path to write the data to
112
+	 * @param int[optional]    $level Compression level, from 0 to 9
113
+	 *
114
+	 * @return string The minified & gzipped data
115
+	 */
116
+	public function gzip($path = null, $level = 9)
117
+	{
118
+		$content = $this->execute($path);
119
+		$content = gzencode($content, $level, FORCE_GZIP);
120
+
121
+		// save to path
122
+		if ($path !== null) {
123
+			$this->save($content, $path);
124
+		}
125
+
126
+		return $content;
127
+	}
128
+
129
+	/**
130
+	 * Minify the data & write it to a CacheItemInterface object.
131
+	 *
132
+	 * @param CacheItemInterface $item Cache item to write the data to
133
+	 *
134
+	 * @return CacheItemInterface Cache item with the minifier data
135
+	 */
136
+	public function cache(CacheItemInterface $item)
137
+	{
138
+		$content = $this->execute();
139
+		$item->set($content);
140
+
141
+		return $item;
142
+	}
143
+
144
+	/**
145
+	 * Minify the data.
146
+	 *
147
+	 * @param string[optional] $path Path to write the data to
148
+	 *
149
+	 * @return string The minified data
150
+	 */
151
+	abstract public function execute($path = null);
152
+
153
+	/**
154
+	 * Load data.
155
+	 *
156
+	 * @param string $data Either a path to a file or the content itself
157
+	 *
158
+	 * @return string
159
+	 */
160
+	protected function load($data)
161
+	{
162
+		// check if the data is a file
163
+		if ($this->canImportFile($data)) {
164
+			$data = file_get_contents($data);
165
+
166
+			// strip BOM, if any
167
+			if (substr($data, 0, 3) == "\xef\xbb\xbf") {
168
+				$data = substr($data, 3);
169
+			}
170
+		}
171
+
172
+		return $data;
173
+	}
174
+
175
+	/**
176
+	 * Save to file.
177
+	 *
178
+	 * @param string $content The minified data
179
+	 * @param string $path    The path to save the minified data to
180
+	 *
181
+	 * @throws IOException
182
+	 */
183
+	protected function save($content, $path)
184
+	{
185
+		$handler = $this->openFileForWriting($path);
186
+
187
+		$this->writeToFile($handler, $content);
188
+
189
+		@fclose($handler);
190
+	}
191
+
192
+	/**
193
+	 * Register a pattern to execute against the source content.
194
+	 *
195
+	 * @param string          $pattern     PCRE pattern
196
+	 * @param string|callable $replacement Replacement value for matched pattern
197
+	 */
198
+	protected function registerPattern($pattern, $replacement = '')
199
+	{
200
+		// study the pattern, we'll execute it more than once
201
+		$pattern .= 'S';
202
+
203
+		$this->patterns[] = array($pattern, $replacement);
204
+	}
205
+
206
+	/**
207
+	 * We can't "just" run some regular expressions against JavaScript: it's a
208
+	 * complex language. E.g. having an occurrence of // xyz would be a comment,
209
+	 * unless it's used within a string. Of you could have something that looks
210
+	 * like a 'string', but inside a comment.
211
+	 * The only way to accurately replace these pieces is to traverse the JS one
212
+	 * character at a time and try to find whatever starts first.
213
+	 *
214
+	 * @param string $content The content to replace patterns in
215
+	 *
216
+	 * @return string The (manipulated) content
217
+	 */
218
+	protected function replace($content)
219
+	{
220
+		$processed = '';
221
+		$positions = array_fill(0, count($this->patterns), -1);
222
+		$matches = array();
223
+
224
+		while ($content) {
225
+			// find first match for all patterns
226
+			foreach ($this->patterns as $i => $pattern) {
227
+				list($pattern, $replacement) = $pattern;
228
+
229
+				// no need to re-run matches that are still in the part of the
230
+				// content that hasn't been processed
231
+				if ($positions[$i] >= 0) {
232
+					continue;
233
+				}
234
+
235
+				$match = null;
236
+				if (preg_match($pattern, $content, $match)) {
237
+					$matches[$i] = $match;
238
+
239
+					// we'll store the match position as well; that way, we
240
+					// don't have to redo all preg_matches after changing only
241
+					// the first (we'll still know where those others are)
242
+					$positions[$i] = strpos($content, $match[0]);
243
+				} else {
244
+					// if the pattern couldn't be matched, there's no point in
245
+					// executing it again in later runs on this same content;
246
+					// ignore this one until we reach end of content
247
+					unset($matches[$i]);
248
+					$positions[$i] = strlen($content);
249
+				}
250
+			}
251
+
252
+			// no more matches to find: everything's been processed, break out
253
+			if (!$matches) {
254
+				$processed .= $content;
255
+				break;
256
+			}
257
+
258
+			// see which of the patterns actually found the first thing (we'll
259
+			// only want to execute that one, since we're unsure if what the
260
+			// other found was not inside what the first found)
261
+			$discardLength = min($positions);
262
+			$firstPattern = array_search($discardLength, $positions);
263
+			$match = $matches[$firstPattern][0];
264
+
265
+			// execute the pattern that matches earliest in the content string
266
+			list($pattern, $replacement) = $this->patterns[$firstPattern];
267
+			$replacement = $this->replacePattern($pattern, $replacement, $content);
268
+
269
+			// figure out which part of the string was unmatched; that's the
270
+			// part we'll execute the patterns on again next
271
+			$content = substr($content, $discardLength);
272
+			$unmatched = (string) substr($content, strpos($content, $match) + strlen($match));
273
+
274
+			// move the replaced part to $processed and prepare $content to
275
+			// again match batch of patterns against
276
+			$processed .= substr($replacement, 0, strlen($replacement) - strlen($unmatched));
277
+			$content = $unmatched;
278
+
279
+			// first match has been replaced & that content is to be left alone,
280
+			// the next matches will start after this replacement, so we should
281
+			// fix their offsets
282
+			foreach ($positions as $i => $position) {
283
+				$positions[$i] -= $discardLength + strlen($match);
284
+			}
285
+		}
286
+
287
+		return $processed;
288
+	}
289
+
290
+	/**
291
+	 * This is where a pattern is matched against $content and the matches
292
+	 * are replaced by their respective value.
293
+	 * This function will be called plenty of times, where $content will always
294
+	 * move up 1 character.
295
+	 *
296
+	 * @param string          $pattern     Pattern to match
297
+	 * @param string|callable $replacement Replacement value
298
+	 * @param string          $content     Content to match pattern against
299
+	 *
300
+	 * @return string
301
+	 */
302
+	protected function replacePattern($pattern, $replacement, $content)
303
+	{
304
+		if (is_callable($replacement)) {
305
+			return preg_replace_callback($pattern, $replacement, $content, 1, $count);
306
+		} else {
307
+			return preg_replace($pattern, $replacement, $content, 1, $count);
308
+		}
309
+	}
310
+
311
+	/**
312
+	 * Strings are a pattern we need to match, in order to ignore potential
313
+	 * code-like content inside them, but we just want all of the string
314
+	 * content to remain untouched.
315
+	 *
316
+	 * This method will replace all string content with simple STRING#
317
+	 * placeholder text, so we've rid all strings from characters that may be
318
+	 * misinterpreted. Original string content will be saved in $this->extracted
319
+	 * and after doing all other minifying, we can restore the original content
320
+	 * via restoreStrings().
321
+	 *
322
+	 * @param string[optional] $chars
323
+	 */
324
+	protected function extractStrings($chars = '\'"')
325
+	{
326
+		// PHP only supports $this inside anonymous functions since 5.4
327
+		$minifier = $this;
328
+		$callback = function ($match) use ($minifier) {
329
+			// check the second index here, because the first always contains a quote
330
+			if ($match[2] === '') {
331
+				/*
332 332
                  * Empty strings need no placeholder; they can't be confused for
333 333
                  * anything else anyway.
334 334
                  * But we still needed to match them, for the extraction routine
335 335
                  * to skip over this particular string.
336 336
                  */
337
-                return $match[0];
338
-            }
337
+				return $match[0];
338
+			}
339 339
 
340
-            $count = count($minifier->extracted);
341
-            $placeholder = $match[1].$count.$match[1];
342
-            $minifier->extracted[$placeholder] = $match[1].$match[2].$match[1];
340
+			$count = count($minifier->extracted);
341
+			$placeholder = $match[1].$count.$match[1];
342
+			$minifier->extracted[$placeholder] = $match[1].$match[2].$match[1];
343 343
 
344
-            return $placeholder;
345
-        };
344
+			return $placeholder;
345
+		};
346 346
 
347
-        /*
347
+		/*
348 348
          * The \\ messiness explained:
349 349
          * * Don't count ' or " as end-of-string if it's escaped (has backslash
350 350
          * in front of it)
@@ -356,75 +356,75 @@  discard block
 block discarded – undo
356 356
          * considered as escape-char (times 2) and to get it in the regex,
357 357
          * escaped (times 2)
358 358
          */
359
-        $this->registerPattern('/(['.$chars.'])(.*?(?<!\\\\)(\\\\\\\\)*+)\\1/s', $callback);
360
-    }
361
-
362
-    /**
363
-     * This method will restore all extracted data (strings, regexes) that were
364
-     * replaced with placeholder text in extract*(). The original content was
365
-     * saved in $this->extracted.
366
-     *
367
-     * @param string $content
368
-     *
369
-     * @return string
370
-     */
371
-    protected function restoreExtractedData($content)
372
-    {
373
-        if (!$this->extracted) {
374
-            // nothing was extracted, nothing to restore
375
-            return $content;
376
-        }
377
-
378
-        $content = strtr($content, $this->extracted);
379
-
380
-        $this->extracted = array();
381
-
382
-        return $content;
383
-    }
384
-
385
-    /**
386
-     * Check if the path is a regular file and can be read.
387
-     *
388
-     * @param string $path
389
-     *
390
-     * @return bool
391
-     */
392
-    protected function canImportFile($path)
393
-    {
394
-        return strlen($path) < PHP_MAXPATHLEN && @is_file($path) && is_readable($path);
395
-    }
396
-
397
-    /**
398
-     * Attempts to open file specified by $path for writing.
399
-     *
400
-     * @param string $path The path to the file
401
-     *
402
-     * @return resource Specifier for the target file
403
-     *
404
-     * @throws IOException
405
-     */
406
-    protected function openFileForWriting($path)
407
-    {
408
-        if (($handler = @fopen($path, 'w')) === false) {
409
-            throw new IOException('The file "'.$path.'" could not be opened for writing. Check if PHP has enough permissions.');
410
-        }
411
-
412
-        return $handler;
413
-    }
414
-
415
-    /**
416
-     * Attempts to write $content to the file specified by $handler. $path is used for printing exceptions.
417
-     *
418
-     * @param resource $handler The resource to write to
419
-     * @param string   $content The content to write
420
-     * @param string   $path    The path to the file (for exception printing only)
421
-     *
422
-     * @throws IOException
423
-     */
424
-    protected function writeToFile($handler, $content, $path = '')
425
-    {
426
-        if (($result = @fwrite($handler, $content)) === false || ($result < strlen($content))) {
427
-            throw new IOException('The file "'.$path.'" could not be written to. Check your disk space and file permissions.');
428
-        }
429
-    }
359
+		$this->registerPattern('/(['.$chars.'])(.*?(?<!\\\\)(\\\\\\\\)*+)\\1/s', $callback);
360
+	}
361
+
362
+	/**
363
+	 * This method will restore all extracted data (strings, regexes) that were
364
+	 * replaced with placeholder text in extract*(). The original content was
365
+	 * saved in $this->extracted.
366
+	 *
367
+	 * @param string $content
368
+	 *
369
+	 * @return string
370
+	 */
371
+	protected function restoreExtractedData($content)
372
+	{
373
+		if (!$this->extracted) {
374
+			// nothing was extracted, nothing to restore
375
+			return $content;
376
+		}
377
+
378
+		$content = strtr($content, $this->extracted);
379
+
380
+		$this->extracted = array();
381
+
382
+		return $content;
383
+	}
384
+
385
+	/**
386
+	 * Check if the path is a regular file and can be read.
387
+	 *
388
+	 * @param string $path
389
+	 *
390
+	 * @return bool
391
+	 */
392
+	protected function canImportFile($path)
393
+	{
394
+		return strlen($path) < PHP_MAXPATHLEN && @is_file($path) && is_readable($path);
395
+	}
396
+
397
+	/**
398
+	 * Attempts to open file specified by $path for writing.
399
+	 *
400
+	 * @param string $path The path to the file
401
+	 *
402
+	 * @return resource Specifier for the target file
403
+	 *
404
+	 * @throws IOException
405
+	 */
406
+	protected function openFileForWriting($path)
407
+	{
408
+		if (($handler = @fopen($path, 'w')) === false) {
409
+			throw new IOException('The file "'.$path.'" could not be opened for writing. Check if PHP has enough permissions.');
410
+		}
411
+
412
+		return $handler;
413
+	}
414
+
415
+	/**
416
+	 * Attempts to write $content to the file specified by $handler. $path is used for printing exceptions.
417
+	 *
418
+	 * @param resource $handler The resource to write to
419
+	 * @param string   $content The content to write
420
+	 * @param string   $path    The path to the file (for exception printing only)
421
+	 *
422
+	 * @throws IOException
423
+	 */
424
+	protected function writeToFile($handler, $content, $path = '')
425
+	{
426
+		if (($result = @fwrite($handler, $content)) === false || ($result < strlen($content))) {
427
+			throw new IOException('The file "'.$path.'" could not be written to. Check your disk space and file permissions.');
428
+		}
429
+	}
430 430
 }
Please login to merge, or discard this patch.
Spacing   +6 added lines, -6 removed lines patch added patch discarded remove patch
@@ -325,7 +325,7 @@  discard block
 block discarded – undo
325 325
     {
326 326
         // PHP only supports $this inside anonymous functions since 5.4
327 327
         $minifier = $this;
328
-        $callback = function ($match) use ($minifier) {
328
+        $callback = function($match) use ($minifier) {
329 329
             // check the second index here, because the first always contains a quote
330 330
             if ($match[2] === '') {
331 331
                 /*
@@ -338,8 +338,8 @@  discard block
 block discarded – undo
338 338
             }
339 339
 
340 340
             $count = count($minifier->extracted);
341
-            $placeholder = $match[1].$count.$match[1];
342
-            $minifier->extracted[$placeholder] = $match[1].$match[2].$match[1];
341
+            $placeholder = $match[1] . $count . $match[1];
342
+            $minifier->extracted[$placeholder] = $match[1] . $match[2] . $match[1];
343 343
 
344 344
             return $placeholder;
345 345
         };
@@ -356,7 +356,7 @@  discard block
 block discarded – undo
356 356
          * considered as escape-char (times 2) and to get it in the regex,
357 357
          * escaped (times 2)
358 358
          */
359
-        $this->registerPattern('/(['.$chars.'])(.*?(?<!\\\\)(\\\\\\\\)*+)\\1/s', $callback);
359
+        $this->registerPattern('/([' . $chars . '])(.*?(?<!\\\\)(\\\\\\\\)*+)\\1/s', $callback);
360 360
     }
361 361
 
362 362
     /**
@@ -406,7 +406,7 @@  discard block
 block discarded – undo
406 406
     protected function openFileForWriting($path)
407 407
     {
408 408
         if (($handler = @fopen($path, 'w')) === false) {
409
-            throw new IOException('The file "'.$path.'" could not be opened for writing. Check if PHP has enough permissions.');
409
+            throw new IOException('The file "' . $path . '" could not be opened for writing. Check if PHP has enough permissions.');
410 410
         }
411 411
 
412 412
         return $handler;
@@ -424,7 +424,7 @@  discard block
 block discarded – undo
424 424
     protected function writeToFile($handler, $content, $path = '')
425 425
     {
426 426
         if (($result = @fwrite($handler, $content)) === false || ($result < strlen($content))) {
427
-            throw new IOException('The file "'.$path.'" could not be written to. Check your disk space and file permissions.');
427
+            throw new IOException('The file "' . $path . '" could not be written to. Check your disk space and file permissions.');
428 428
         }
429 429
     }
430 430
 }
Please login to merge, or discard this patch.
Sources/minify/src/CSS.php 2 patches
Indentation   +488 added lines, -488 removed lines patch added patch discarded remove patch
@@ -17,96 +17,96 @@  discard block
 block discarded – undo
17 17
  */
18 18
 class CSS extends Minify
19 19
 {
20
-    /**
21
-     * @var int
22
-     */
23
-    protected $maxImportSize = 5;
24
-
25
-    /**
26
-     * @var string[]
27
-     */
28
-    protected $importExtensions = array(
29
-        'gif' => 'data:image/gif',
30
-        'png' => 'data:image/png',
31
-        'jpe' => 'data:image/jpeg',
32
-        'jpg' => 'data:image/jpeg',
33
-        'jpeg' => 'data:image/jpeg',
34
-        'svg' => 'data:image/svg+xml',
35
-        'woff' => 'data:application/x-font-woff',
36
-        'tif' => 'image/tiff',
37
-        'tiff' => 'image/tiff',
38
-        'xbm' => 'image/x-xbitmap',
39
-    );
40
-
41
-    /**
42
-     * Set the maximum size if files to be imported.
43
-     *
44
-     * Files larger than this size (in kB) will not be imported into the CSS.
45
-     * Importing files into the CSS as data-uri will save you some connections,
46
-     * but we should only import relatively small decorative images so that our
47
-     * CSS file doesn't get too bulky.
48
-     *
49
-     * @param int $size Size in kB
50
-     */
51
-    public function setMaxImportSize($size)
52
-    {
53
-        $this->maxImportSize = $size;
54
-    }
55
-
56
-    /**
57
-     * Set the type of extensions to be imported into the CSS (to save network
58
-     * connections).
59
-     * Keys of the array should be the file extensions & respective values
60
-     * should be the data type.
61
-     *
62
-     * @param string[] $extensions Array of file extensions
63
-     */
64
-    public function setImportExtensions(array $extensions)
65
-    {
66
-        $this->importExtensions = $extensions;
67
-    }
68
-
69
-    /**
70
-     * Move any import statements to the top.
71
-     *
72
-     * @param string $content Nearly finished CSS content
73
-     *
74
-     * @return string
75
-     */
76
-    protected function moveImportsToTop($content)
77
-    {
78
-        if (preg_match_all('/@import[^;]+;/', $content, $matches)) {
79
-            // remove from content
80
-            foreach ($matches[0] as $import) {
81
-                $content = str_replace($import, '', $content);
82
-            }
83
-
84
-            // add to top
85
-            $content = implode('', $matches[0]).$content;
86
-        }
87
-
88
-        return $content;
89
-    }
90
-
91
-    /**
92
-     * Combine CSS from import statements.
93
-     *
94
-     * @import's will be loaded and their content merged into the original file,
95
-     * to save HTTP requests.
96
-     *
97
-     * @param string   $source  The file to combine imports for
98
-     * @param string   $content The CSS content to combine imports for
99
-     * @param string[] $parents Parent paths, for circular reference checks
100
-     *
101
-     * @return string
102
-     *
103
-     * @throws FileImportException
104
-     */
105
-    protected function combineImports($source, $content, $parents)
106
-    {
107
-        $importRegexes = array(
108
-            // @import url(xxx)
109
-            '/
20
+	/**
21
+	 * @var int
22
+	 */
23
+	protected $maxImportSize = 5;
24
+
25
+	/**
26
+	 * @var string[]
27
+	 */
28
+	protected $importExtensions = array(
29
+		'gif' => 'data:image/gif',
30
+		'png' => 'data:image/png',
31
+		'jpe' => 'data:image/jpeg',
32
+		'jpg' => 'data:image/jpeg',
33
+		'jpeg' => 'data:image/jpeg',
34
+		'svg' => 'data:image/svg+xml',
35
+		'woff' => 'data:application/x-font-woff',
36
+		'tif' => 'image/tiff',
37
+		'tiff' => 'image/tiff',
38
+		'xbm' => 'image/x-xbitmap',
39
+	);
40
+
41
+	/**
42
+	 * Set the maximum size if files to be imported.
43
+	 *
44
+	 * Files larger than this size (in kB) will not be imported into the CSS.
45
+	 * Importing files into the CSS as data-uri will save you some connections,
46
+	 * but we should only import relatively small decorative images so that our
47
+	 * CSS file doesn't get too bulky.
48
+	 *
49
+	 * @param int $size Size in kB
50
+	 */
51
+	public function setMaxImportSize($size)
52
+	{
53
+		$this->maxImportSize = $size;
54
+	}
55
+
56
+	/**
57
+	 * Set the type of extensions to be imported into the CSS (to save network
58
+	 * connections).
59
+	 * Keys of the array should be the file extensions & respective values
60
+	 * should be the data type.
61
+	 *
62
+	 * @param string[] $extensions Array of file extensions
63
+	 */
64
+	public function setImportExtensions(array $extensions)
65
+	{
66
+		$this->importExtensions = $extensions;
67
+	}
68
+
69
+	/**
70
+	 * Move any import statements to the top.
71
+	 *
72
+	 * @param string $content Nearly finished CSS content
73
+	 *
74
+	 * @return string
75
+	 */
76
+	protected function moveImportsToTop($content)
77
+	{
78
+		if (preg_match_all('/@import[^;]+;/', $content, $matches)) {
79
+			// remove from content
80
+			foreach ($matches[0] as $import) {
81
+				$content = str_replace($import, '', $content);
82
+			}
83
+
84
+			// add to top
85
+			$content = implode('', $matches[0]).$content;
86
+		}
87
+
88
+		return $content;
89
+	}
90
+
91
+	/**
92
+	 * Combine CSS from import statements.
93
+	 *
94
+	 * @import's will be loaded and their content merged into the original file,
95
+	 * to save HTTP requests.
96
+	 *
97
+	 * @param string   $source  The file to combine imports for
98
+	 * @param string   $content The CSS content to combine imports for
99
+	 * @param string[] $parents Parent paths, for circular reference checks
100
+	 *
101
+	 * @return string
102
+	 *
103
+	 * @throws FileImportException
104
+	 */
105
+	protected function combineImports($source, $content, $parents)
106
+	{
107
+		$importRegexes = array(
108
+			// @import url(xxx)
109
+			'/
110 110
             # import statement
111 111
             @import
112 112
 
@@ -151,8 +151,8 @@  discard block
 block discarded – undo
151 151
 
152 152
             /ix',
153 153
 
154
-            // @import 'xxx'
155
-            '/
154
+			// @import 'xxx'
155
+			'/
156 156
 
157 157
             # import statement
158 158
             @import
@@ -191,173 +191,173 @@  discard block
 block discarded – undo
191 191
             ;?
192 192
 
193 193
             /ix',
194
-        );
195
-
196
-        // find all relative imports in css
197
-        $matches = array();
198
-        foreach ($importRegexes as $importRegex) {
199
-            if (preg_match_all($importRegex, $content, $regexMatches, PREG_SET_ORDER)) {
200
-                $matches = array_merge($matches, $regexMatches);
201
-            }
202
-        }
203
-
204
-        $search = array();
205
-        $replace = array();
206
-
207
-        // loop the matches
208
-        foreach ($matches as $match) {
209
-            // get the path for the file that will be imported
210
-            $importPath = dirname($source).'/'.$match['path'];
211
-
212
-            // only replace the import with the content if we can grab the
213
-            // content of the file
214
-            if ($this->canImportFile($importPath)) {
215
-                // check if current file was not imported previously in the same
216
-                // import chain.
217
-                if (in_array($importPath, $parents)) {
218
-                    throw new FileImportException('Failed to import file "'.$importPath.'": circular reference detected.');
219
-                }
220
-
221
-                // grab referenced file & minify it (which may include importing
222
-                // yet other @import statements recursively)
223
-                $minifier = new static($importPath);
224
-                $importContent = $minifier->execute($source, $parents);
225
-
226
-                // check if this is only valid for certain media
227
-                if (!empty($match['media'])) {
228
-                    $importContent = '@media '.$match['media'].'{'.$importContent.'}';
229
-                }
230
-
231
-                // add to replacement array
232
-                $search[] = $match[0];
233
-                $replace[] = $importContent;
234
-            }
235
-        }
236
-
237
-        // replace the import statements
238
-        $content = str_replace($search, $replace, $content);
239
-
240
-        return $content;
241
-    }
242
-
243
-    /**
244
-     * Import files into the CSS, base64-ized.
245
-     *
246
-     * @url(image.jpg) images will be loaded and their content merged into the
247
-     * original file, to save HTTP requests.
248
-     *
249
-     * @param string $source  The file to import files for
250
-     * @param string $content The CSS content to import files for
251
-     *
252
-     * @return string
253
-     */
254
-    protected function importFiles($source, $content)
255
-    {
256
-        $extensions = array_keys($this->importExtensions);
257
-        $regex = '/url\((["\']?)((?!["\']?data:).*?\.('.implode('|', $extensions).'))\\1\)/i';
258
-        if ($extensions && preg_match_all($regex, $content, $matches, PREG_SET_ORDER)) {
259
-            $search = array();
260
-            $replace = array();
261
-
262
-            // loop the matches
263
-            foreach ($matches as $match) {
264
-                // get the path for the file that will be imported
265
-                $path = $match[2];
266
-                $path = dirname($source).'/'.$path;
267
-                $extension = $match[3];
268
-
269
-                // only replace the import with the content if we're able to get
270
-                // the content of the file, and it's relatively small
271
-                if ($this->canImportFile($path) && $this->canImportBySize($path)) {
272
-                    // grab content && base64-ize
273
-                    $importContent = $this->load($path);
274
-                    $importContent = base64_encode($importContent);
275
-
276
-                    // build replacement
277
-                    $search[] = $match[0];
278
-                    $replace[] = 'url('.$this->importExtensions[$extension].';base64,'.$importContent.')';
279
-                }
280
-            }
281
-
282
-            // replace the import statements
283
-            $content = str_replace($search, $replace, $content);
284
-        }
285
-
286
-        return $content;
287
-    }
288
-
289
-    /**
290
-     * Minify the data.
291
-     * Perform CSS optimizations.
292
-     *
293
-     * @param string[optional] $path    Path to write the data to
294
-     * @param string[]         $parents Parent paths, for circular reference checks
295
-     *
296
-     * @return string The minified data
297
-     */
298
-    public function execute($path = null, $parents = array())
299
-    {
300
-        $content = '';
301
-
302
-        // loop css data (raw data and files)
303
-        foreach ($this->data as $source => $css) {
304
-            /*
194
+		);
195
+
196
+		// find all relative imports in css
197
+		$matches = array();
198
+		foreach ($importRegexes as $importRegex) {
199
+			if (preg_match_all($importRegex, $content, $regexMatches, PREG_SET_ORDER)) {
200
+				$matches = array_merge($matches, $regexMatches);
201
+			}
202
+		}
203
+
204
+		$search = array();
205
+		$replace = array();
206
+
207
+		// loop the matches
208
+		foreach ($matches as $match) {
209
+			// get the path for the file that will be imported
210
+			$importPath = dirname($source).'/'.$match['path'];
211
+
212
+			// only replace the import with the content if we can grab the
213
+			// content of the file
214
+			if ($this->canImportFile($importPath)) {
215
+				// check if current file was not imported previously in the same
216
+				// import chain.
217
+				if (in_array($importPath, $parents)) {
218
+					throw new FileImportException('Failed to import file "'.$importPath.'": circular reference detected.');
219
+				}
220
+
221
+				// grab referenced file & minify it (which may include importing
222
+				// yet other @import statements recursively)
223
+				$minifier = new static($importPath);
224
+				$importContent = $minifier->execute($source, $parents);
225
+
226
+				// check if this is only valid for certain media
227
+				if (!empty($match['media'])) {
228
+					$importContent = '@media '.$match['media'].'{'.$importContent.'}';
229
+				}
230
+
231
+				// add to replacement array
232
+				$search[] = $match[0];
233
+				$replace[] = $importContent;
234
+			}
235
+		}
236
+
237
+		// replace the import statements
238
+		$content = str_replace($search, $replace, $content);
239
+
240
+		return $content;
241
+	}
242
+
243
+	/**
244
+	 * Import files into the CSS, base64-ized.
245
+	 *
246
+	 * @url(image.jpg) images will be loaded and their content merged into the
247
+	 * original file, to save HTTP requests.
248
+	 *
249
+	 * @param string $source  The file to import files for
250
+	 * @param string $content The CSS content to import files for
251
+	 *
252
+	 * @return string
253
+	 */
254
+	protected function importFiles($source, $content)
255
+	{
256
+		$extensions = array_keys($this->importExtensions);
257
+		$regex = '/url\((["\']?)((?!["\']?data:).*?\.('.implode('|', $extensions).'))\\1\)/i';
258
+		if ($extensions && preg_match_all($regex, $content, $matches, PREG_SET_ORDER)) {
259
+			$search = array();
260
+			$replace = array();
261
+
262
+			// loop the matches
263
+			foreach ($matches as $match) {
264
+				// get the path for the file that will be imported
265
+				$path = $match[2];
266
+				$path = dirname($source).'/'.$path;
267
+				$extension = $match[3];
268
+
269
+				// only replace the import with the content if we're able to get
270
+				// the content of the file, and it's relatively small
271
+				if ($this->canImportFile($path) && $this->canImportBySize($path)) {
272
+					// grab content && base64-ize
273
+					$importContent = $this->load($path);
274
+					$importContent = base64_encode($importContent);
275
+
276
+					// build replacement
277
+					$search[] = $match[0];
278
+					$replace[] = 'url('.$this->importExtensions[$extension].';base64,'.$importContent.')';
279
+				}
280
+			}
281
+
282
+			// replace the import statements
283
+			$content = str_replace($search, $replace, $content);
284
+		}
285
+
286
+		return $content;
287
+	}
288
+
289
+	/**
290
+	 * Minify the data.
291
+	 * Perform CSS optimizations.
292
+	 *
293
+	 * @param string[optional] $path    Path to write the data to
294
+	 * @param string[]         $parents Parent paths, for circular reference checks
295
+	 *
296
+	 * @return string The minified data
297
+	 */
298
+	public function execute($path = null, $parents = array())
299
+	{
300
+		$content = '';
301
+
302
+		// loop css data (raw data and files)
303
+		foreach ($this->data as $source => $css) {
304
+			/*
305 305
              * Let's first take out strings & comments, since we can't just remove
306 306
              * whitespace anywhere. If whitespace occurs inside a string, we should
307 307
              * leave it alone. E.g.:
308 308
              * p { content: "a   test" }
309 309
              */
310
-            $this->extractStrings();
311
-            $this->stripComments();
312
-            $css = $this->replace($css);
310
+			$this->extractStrings();
311
+			$this->stripComments();
312
+			$css = $this->replace($css);
313 313
 
314
-            $css = $this->stripWhitespace($css);
315
-            $css = $this->shortenHex($css);
316
-            $css = $this->shortenZeroes($css);
317
-            $css = $this->shortenFontWeights($css);
318
-            $css = $this->stripEmptyTags($css);
314
+			$css = $this->stripWhitespace($css);
315
+			$css = $this->shortenHex($css);
316
+			$css = $this->shortenZeroes($css);
317
+			$css = $this->shortenFontWeights($css);
318
+			$css = $this->stripEmptyTags($css);
319 319
 
320
-            // restore the string we've extracted earlier
321
-            $css = $this->restoreExtractedData($css);
320
+			// restore the string we've extracted earlier
321
+			$css = $this->restoreExtractedData($css);
322 322
 
323
-            $source = is_int($source) ? '' : $source;
324
-            $parents = $source ? array_merge($parents, array($source)) : $parents;
325
-            $css = $this->combineImports($source, $css, $parents);
326
-            $css = $this->importFiles($source, $css);
323
+			$source = is_int($source) ? '' : $source;
324
+			$parents = $source ? array_merge($parents, array($source)) : $parents;
325
+			$css = $this->combineImports($source, $css, $parents);
326
+			$css = $this->importFiles($source, $css);
327 327
 
328
-            /*
328
+			/*
329 329
              * If we'll save to a new path, we'll have to fix the relative paths
330 330
              * to be relative no longer to the source file, but to the new path.
331 331
              * If we don't write to a file, fall back to same path so no
332 332
              * conversion happens (because we still want it to go through most
333 333
              * of the move code...)
334 334
              */
335
-            $converter = new Converter($source, $path ?: $source);
336
-            $css = $this->move($converter, $css);
337
-
338
-            // combine css
339
-            $content .= $css;
340
-        }
341
-
342
-        $content = $this->moveImportsToTop($content);
343
-
344
-        return $content;
345
-    }
346
-
347
-    /**
348
-     * Moving a css file should update all relative urls.
349
-     * Relative references (e.g. ../images/image.gif) in a certain css file,
350
-     * will have to be updated when a file is being saved at another location
351
-     * (e.g. ../../images/image.gif, if the new CSS file is 1 folder deeper).
352
-     *
353
-     * @param Converter $converter Relative path converter
354
-     * @param string    $content   The CSS content to update relative urls for
355
-     *
356
-     * @return string
357
-     */
358
-    protected function move(Converter $converter, $content)
359
-    {
360
-        /*
335
+			$converter = new Converter($source, $path ?: $source);
336
+			$css = $this->move($converter, $css);
337
+
338
+			// combine css
339
+			$content .= $css;
340
+		}
341
+
342
+		$content = $this->moveImportsToTop($content);
343
+
344
+		return $content;
345
+	}
346
+
347
+	/**
348
+	 * Moving a css file should update all relative urls.
349
+	 * Relative references (e.g. ../images/image.gif) in a certain css file,
350
+	 * will have to be updated when a file is being saved at another location
351
+	 * (e.g. ../../images/image.gif, if the new CSS file is 1 folder deeper).
352
+	 *
353
+	 * @param Converter $converter Relative path converter
354
+	 * @param string    $content   The CSS content to update relative urls for
355
+	 *
356
+	 * @return string
357
+	 */
358
+	protected function move(Converter $converter, $content)
359
+	{
360
+		/*
361 361
          * Relative path references will usually be enclosed by url(). @import
362 362
          * is an exception, where url() is not necessary around the path (but is
363 363
          * allowed).
@@ -368,9 +368,9 @@  discard block
 block discarded – undo
368 368
          * recent PCRE version. That's why I'm doing 2 separate regular
369 369
          * expressions & combining the matches after executing of both.
370 370
          */
371
-        $relativeRegexes = array(
372
-            // url(xxx)
373
-            '/
371
+		$relativeRegexes = array(
372
+			// url(xxx)
373
+			'/
374 374
             # open url()
375 375
             url\(
376 376
 
@@ -402,8 +402,8 @@  discard block
 block discarded – undo
402 402
 
403 403
             /ix',
404 404
 
405
-            // @import "xxx"
406
-            '/
405
+			// @import "xxx"
406
+			'/
407 407
             # import statement
408 408
             @import
409 409
 
@@ -432,243 +432,243 @@  discard block
 block discarded – undo
432 432
                 (?P=quotes)
433 433
 
434 434
             /ix',
435
-        );
436
-
437
-        // find all relative urls in css
438
-        $matches = array();
439
-        foreach ($relativeRegexes as $relativeRegex) {
440
-            if (preg_match_all($relativeRegex, $content, $regexMatches, PREG_SET_ORDER)) {
441
-                $matches = array_merge($matches, $regexMatches);
442
-            }
443
-        }
444
-
445
-        $search = array();
446
-        $replace = array();
447
-
448
-        // loop all urls
449
-        foreach ($matches as $match) {
450
-            // determine if it's a url() or an @import match
451
-            $type = (strpos($match[0], '@import') === 0 ? 'import' : 'url');
452
-
453
-            // attempting to interpret GET-params makes no sense, so let's discard them for awhile
454
-            $params = strrchr($match['path'], '?');
455
-            $url = $params ? substr($match['path'], 0, -strlen($params)) : $match['path'];
456
-
457
-            // fix relative url
458
-            $url = $converter->convert($url);
459
-
460
-            // now that the path has been converted, re-apply GET-params
461
-            $url .= $params;
462
-
463
-            // build replacement
464
-            $search[] = $match[0];
465
-            if ($type == 'url') {
466
-                $replace[] = 'url('.$url.')';
467
-            } elseif ($type == 'import') {
468
-                $replace[] = '@import "'.$url.'"';
469
-            }
470
-        }
471
-
472
-        // replace urls
473
-        $content = str_replace($search, $replace, $content);
474
-
475
-        return $content;
476
-    }
477
-
478
-    /**
479
-     * Shorthand hex color codes.
480
-     * #FF0000 -> #F00.
481
-     *
482
-     * @param string $content The CSS content to shorten the hex color codes for
483
-     *
484
-     * @return string
485
-     */
486
-    protected function shortenHex($content)
487
-    {
488
-        $content = preg_replace('/(?<=[: ])#([0-9a-z])\\1([0-9a-z])\\2([0-9a-z])\\3(?=[; }])/i', '#$1$2$3', $content);
489
-
490
-        // we can shorten some even more by replacing them with their color name
491
-        $colors = array(
492
-            '#F0FFFF' => 'azure',
493
-            '#F5F5DC' => 'beige',
494
-            '#A52A2A' => 'brown',
495
-            '#FF7F50' => 'coral',
496
-            '#FFD700' => 'gold',
497
-            '#808080' => 'gray',
498
-            '#008000' => 'green',
499
-            '#4B0082' => 'indigo',
500
-            '#FFFFF0' => 'ivory',
501
-            '#F0E68C' => 'khaki',
502
-            '#FAF0E6' => 'linen',
503
-            '#800000' => 'maroon',
504
-            '#000080' => 'navy',
505
-            '#808000' => 'olive',
506
-            '#CD853F' => 'peru',
507
-            '#FFC0CB' => 'pink',
508
-            '#DDA0DD' => 'plum',
509
-            '#800080' => 'purple',
510
-            '#F00' => 'red',
511
-            '#FA8072' => 'salmon',
512
-            '#A0522D' => 'sienna',
513
-            '#C0C0C0' => 'silver',
514
-            '#FFFAFA' => 'snow',
515
-            '#D2B48C' => 'tan',
516
-            '#FF6347' => 'tomato',
517
-            '#EE82EE' => 'violet',
518
-            '#F5DEB3' => 'wheat',
519
-        );
520
-
521
-        return preg_replace_callback(
522
-            '/(?<=[: ])('.implode(array_keys($colors), '|').')(?=[; }])/i',
523
-            function ($match) use ($colors) {
524
-                return $colors[strtoupper($match[0])];
525
-            },
526
-            $content
527
-        );
528
-    }
529
-
530
-    /**
531
-     * Shorten CSS font weights.
532
-     *
533
-     * @param string $content The CSS content to shorten the font weights for
534
-     *
535
-     * @return string
536
-     */
537
-    protected function shortenFontWeights($content)
538
-    {
539
-        $weights = array(
540
-            'normal' => 400,
541
-            'bold' => 700,
542
-        );
543
-
544
-        $callback = function ($match) use ($weights) {
545
-            return $match[1].$weights[$match[2]];
546
-        };
547
-
548
-        return preg_replace_callback('/(font-weight\s*:\s*)('.implode('|', array_keys($weights)).')(?=[;}])/', $callback, $content);
549
-    }
550
-
551
-    /**
552
-     * Shorthand 0 values to plain 0, instead of e.g. -0em.
553
-     *
554
-     * @param string $content The CSS content to shorten the zero values for
555
-     *
556
-     * @return string
557
-     */
558
-    protected function shortenZeroes($content)
559
-    {
560
-        // reusable bits of code throughout these regexes:
561
-        // before & after are used to make sure we don't match lose unintended
562
-        // 0-like values (e.g. in #000, or in http://url/1.0)
563
-        // units can be stripped from 0 values, or used to recognize non 0
564
-        // values (where wa may be able to strip a .0 suffix)
565
-        $before = '(?<=[:(, ])';
566
-        $after = '(?=[ ,);}])';
567
-        $units = '(em|ex|%|px|cm|mm|in|pt|pc|ch|rem|vh|vw|vmin|vmax|vm)';
568
-
569
-        // strip units after zeroes (0px -> 0)
570
-        // NOTE: it should be safe to remove all units for a 0 value, but in
571
-        // practice, Webkit (especially Safari) seems to stumble over at least
572
-        // 0%, potentially other units as well. Only stripping 'px' for now.
573
-        // @see https://github.com/matthiasmullie/minify/issues/60
574
-        $content = preg_replace('/'.$before.'(-?0*(\.0+)?)(?<=0)px'.$after.'/', '\\1', $content);
575
-
576
-        // strip 0-digits (.0 -> 0)
577
-        $content = preg_replace('/'.$before.'\.0+'.$units.'?'.$after.'/', '0\\1', $content);
578
-        // strip trailing 0: 50.10 -> 50.1, 50.10px -> 50.1px
579
-        $content = preg_replace('/'.$before.'(-?[0-9]+\.[0-9]+)0+'.$units.'?'.$after.'/', '\\1\\2', $content);
580
-        // strip trailing 0: 50.00 -> 50, 50.00px -> 50px
581
-        $content = preg_replace('/'.$before.'(-?[0-9]+)\.0+'.$units.'?'.$after.'/', '\\1\\2', $content);
582
-        // strip leading 0: 0.1 -> .1, 01.1 -> 1.1
583
-        $content = preg_replace('/'.$before.'(-?)0+([0-9]*\.[0-9]+)'.$units.'?'.$after.'/', '\\1\\2\\3', $content);
584
-
585
-        // strip negative zeroes (-0 -> 0) & truncate zeroes (00 -> 0)
586
-        $content = preg_replace('/'.$before.'-?0+'.$units.'?'.$after.'/', '0\\1', $content);
587
-
588
-        // remove zeroes where they make no sense in calc: e.g. calc(100px - 0)
589
-        // the 0 doesn't have any effect, and this isn't even valid without unit
590
-        // strip all `+ 0` or `- 0` occurrences: calc(10% + 0) -> calc(10%)
591
-        // looped because there may be multiple 0s inside 1 group of parentheses
592
-        do {
593
-            $previous = $content;
594
-            $content = preg_replace('/\(([^\(\)]+)\s+[\+\-]\s+0(\s+[^\(\)]+)?\)/', '(\\1\\2)', $content);
595
-        } while ($content !== $previous);
596
-        // strip all `0 +` occurrences: calc(0 + 10%) -> calc(10%)
597
-        $content = preg_replace('/\(\s*0\s+\+\s+([^\(\)]+)\)/', '(\\1)', $content);
598
-        // strip all `0 -` occurrences: calc(0 - 10%) -> calc(-10%)
599
-        $content = preg_replace('/\(\s*0\s+\-\s+([^\(\)]+)\)/', '(-\\1)', $content);
600
-        // I'm not going to attempt to optimize away `x * 0` instances:
601
-        // it's dumb enough code already that it likely won't occur, and it's
602
-        // too complex to do right (order of operations would have to be
603
-        // respected etc)
604
-        // what I cared about most here was fixing incorrectly truncated units
605
-
606
-        return $content;
607
-    }
608
-
609
-    /**
610
-     * Strip comments from source code.
611
-     *
612
-     * @param string $content
613
-     *
614
-     * @return string
615
-     */
616
-    protected function stripEmptyTags($content)
617
-    {
618
-        return preg_replace('/(^|\}|;)[^\{\};]+\{\s*\}/', '\\1', $content);
619
-    }
620
-
621
-    /**
622
-     * Strip comments from source code.
623
-     */
624
-    protected function stripComments()
625
-    {
626
-        $this->registerPattern('/\/\*.*?\*\//s', '');
627
-    }
628
-
629
-    /**
630
-     * Strip whitespace.
631
-     *
632
-     * @param string $content The CSS content to strip the whitespace for
633
-     *
634
-     * @return string
635
-     */
636
-    protected function stripWhitespace($content)
637
-    {
638
-        // remove leading & trailing whitespace
639
-        $content = preg_replace('/^\s*/m', '', $content);
640
-        $content = preg_replace('/\s*$/m', '', $content);
641
-
642
-        // replace newlines with a single space
643
-        $content = preg_replace('/\s+/', ' ', $content);
644
-
645
-        // remove whitespace around meta characters
646
-        // inspired by stackoverflow.com/questions/15195750/minify-compress-css-with-regex
647
-        $content = preg_replace('/\s*([\*$~^|]?+=|[{};,>~]|!important\b)\s*/', '$1', $content);
648
-        $content = preg_replace('/([\[(:])\s+/', '$1', $content);
649
-        $content = preg_replace('/\s+([\]\)])/', '$1', $content);
650
-        $content = preg_replace('/\s+(:)(?![^\}]*\{)/', '$1', $content);
651
-
652
-        // whitespace around + and - can only be stripped in selectors, like
653
-        // :nth-child(3+2n), not in things like calc(3px + 2px) or shorthands
654
-        // like 3px -2px
655
-        $content = preg_replace('/\s*([+-])\s*(?=[^}]*{)/', '$1', $content);
656
-
657
-        // remove semicolon/whitespace followed by closing bracket
658
-        $content = str_replace(';}', '}', $content);
659
-
660
-        return trim($content);
661
-    }
662
-
663
-    /**
664
-     * Check if file is small enough to be imported.
665
-     *
666
-     * @param string $path The path to the file
667
-     *
668
-     * @return bool
669
-     */
670
-    protected function canImportBySize($path)
671
-    {
672
-        return ($size = @filesize($path)) && $size <= $this->maxImportSize * 1024;
673
-    }
435
+		);
436
+
437
+		// find all relative urls in css
438
+		$matches = array();
439
+		foreach ($relativeRegexes as $relativeRegex) {
440
+			if (preg_match_all($relativeRegex, $content, $regexMatches, PREG_SET_ORDER)) {
441
+				$matches = array_merge($matches, $regexMatches);
442
+			}
443
+		}
444
+
445
+		$search = array();
446
+		$replace = array();
447
+
448
+		// loop all urls
449
+		foreach ($matches as $match) {
450
+			// determine if it's a url() or an @import match
451
+			$type = (strpos($match[0], '@import') === 0 ? 'import' : 'url');
452
+
453
+			// attempting to interpret GET-params makes no sense, so let's discard them for awhile
454
+			$params = strrchr($match['path'], '?');
455
+			$url = $params ? substr($match['path'], 0, -strlen($params)) : $match['path'];
456
+
457
+			// fix relative url
458
+			$url = $converter->convert($url);
459
+
460
+			// now that the path has been converted, re-apply GET-params
461
+			$url .= $params;
462
+
463
+			// build replacement
464
+			$search[] = $match[0];
465
+			if ($type == 'url') {
466
+				$replace[] = 'url('.$url.')';
467
+			} elseif ($type == 'import') {
468
+				$replace[] = '@import "'.$url.'"';
469
+			}
470
+		}
471
+
472
+		// replace urls
473
+		$content = str_replace($search, $replace, $content);
474
+
475
+		return $content;
476
+	}
477
+
478
+	/**
479
+	 * Shorthand hex color codes.
480
+	 * #FF0000 -> #F00.
481
+	 *
482
+	 * @param string $content The CSS content to shorten the hex color codes for
483
+	 *
484
+	 * @return string
485
+	 */
486
+	protected function shortenHex($content)
487
+	{
488
+		$content = preg_replace('/(?<=[: ])#([0-9a-z])\\1([0-9a-z])\\2([0-9a-z])\\3(?=[; }])/i', '#$1$2$3', $content);
489
+
490
+		// we can shorten some even more by replacing them with their color name
491
+		$colors = array(
492
+			'#F0FFFF' => 'azure',
493
+			'#F5F5DC' => 'beige',
494
+			'#A52A2A' => 'brown',
495
+			'#FF7F50' => 'coral',
496
+			'#FFD700' => 'gold',
497
+			'#808080' => 'gray',
498
+			'#008000' => 'green',
499
+			'#4B0082' => 'indigo',
500
+			'#FFFFF0' => 'ivory',
501
+			'#F0E68C' => 'khaki',
502
+			'#FAF0E6' => 'linen',
503
+			'#800000' => 'maroon',
504
+			'#000080' => 'navy',
505
+			'#808000' => 'olive',
506
+			'#CD853F' => 'peru',
507
+			'#FFC0CB' => 'pink',
508
+			'#DDA0DD' => 'plum',
509
+			'#800080' => 'purple',
510
+			'#F00' => 'red',
511
+			'#FA8072' => 'salmon',
512
+			'#A0522D' => 'sienna',
513
+			'#C0C0C0' => 'silver',
514
+			'#FFFAFA' => 'snow',
515
+			'#D2B48C' => 'tan',
516
+			'#FF6347' => 'tomato',
517
+			'#EE82EE' => 'violet',
518
+			'#F5DEB3' => 'wheat',
519
+		);
520
+
521
+		return preg_replace_callback(
522
+			'/(?<=[: ])('.implode(array_keys($colors), '|').')(?=[; }])/i',
523
+			function ($match) use ($colors) {
524
+				return $colors[strtoupper($match[0])];
525
+			},
526
+			$content
527
+		);
528
+	}
529
+
530
+	/**
531
+	 * Shorten CSS font weights.
532
+	 *
533
+	 * @param string $content The CSS content to shorten the font weights for
534
+	 *
535
+	 * @return string
536
+	 */
537
+	protected function shortenFontWeights($content)
538
+	{
539
+		$weights = array(
540
+			'normal' => 400,
541
+			'bold' => 700,
542
+		);
543
+
544
+		$callback = function ($match) use ($weights) {
545
+			return $match[1].$weights[$match[2]];
546
+		};
547
+
548
+		return preg_replace_callback('/(font-weight\s*:\s*)('.implode('|', array_keys($weights)).')(?=[;}])/', $callback, $content);
549
+	}
550
+
551
+	/**
552
+	 * Shorthand 0 values to plain 0, instead of e.g. -0em.
553
+	 *
554
+	 * @param string $content The CSS content to shorten the zero values for
555
+	 *
556
+	 * @return string
557
+	 */
558
+	protected function shortenZeroes($content)
559
+	{
560
+		// reusable bits of code throughout these regexes:
561
+		// before & after are used to make sure we don't match lose unintended
562
+		// 0-like values (e.g. in #000, or in http://url/1.0)
563
+		// units can be stripped from 0 values, or used to recognize non 0
564
+		// values (where wa may be able to strip a .0 suffix)
565
+		$before = '(?<=[:(, ])';
566
+		$after = '(?=[ ,);}])';
567
+		$units = '(em|ex|%|px|cm|mm|in|pt|pc|ch|rem|vh|vw|vmin|vmax|vm)';
568
+
569
+		// strip units after zeroes (0px -> 0)
570
+		// NOTE: it should be safe to remove all units for a 0 value, but in
571
+		// practice, Webkit (especially Safari) seems to stumble over at least
572
+		// 0%, potentially other units as well. Only stripping 'px' for now.
573
+		// @see https://github.com/matthiasmullie/minify/issues/60
574
+		$content = preg_replace('/'.$before.'(-?0*(\.0+)?)(?<=0)px'.$after.'/', '\\1', $content);
575
+
576
+		// strip 0-digits (.0 -> 0)
577
+		$content = preg_replace('/'.$before.'\.0+'.$units.'?'.$after.'/', '0\\1', $content);
578
+		// strip trailing 0: 50.10 -> 50.1, 50.10px -> 50.1px
579
+		$content = preg_replace('/'.$before.'(-?[0-9]+\.[0-9]+)0+'.$units.'?'.$after.'/', '\\1\\2', $content);
580
+		// strip trailing 0: 50.00 -> 50, 50.00px -> 50px
581
+		$content = preg_replace('/'.$before.'(-?[0-9]+)\.0+'.$units.'?'.$after.'/', '\\1\\2', $content);
582
+		// strip leading 0: 0.1 -> .1, 01.1 -> 1.1
583
+		$content = preg_replace('/'.$before.'(-?)0+([0-9]*\.[0-9]+)'.$units.'?'.$after.'/', '\\1\\2\\3', $content);
584
+
585
+		// strip negative zeroes (-0 -> 0) & truncate zeroes (00 -> 0)
586
+		$content = preg_replace('/'.$before.'-?0+'.$units.'?'.$after.'/', '0\\1', $content);
587
+
588
+		// remove zeroes where they make no sense in calc: e.g. calc(100px - 0)
589
+		// the 0 doesn't have any effect, and this isn't even valid without unit
590
+		// strip all `+ 0` or `- 0` occurrences: calc(10% + 0) -> calc(10%)
591
+		// looped because there may be multiple 0s inside 1 group of parentheses
592
+		do {
593
+			$previous = $content;
594
+			$content = preg_replace('/\(([^\(\)]+)\s+[\+\-]\s+0(\s+[^\(\)]+)?\)/', '(\\1\\2)', $content);
595
+		} while ($content !== $previous);
596
+		// strip all `0 +` occurrences: calc(0 + 10%) -> calc(10%)
597
+		$content = preg_replace('/\(\s*0\s+\+\s+([^\(\)]+)\)/', '(\\1)', $content);
598
+		// strip all `0 -` occurrences: calc(0 - 10%) -> calc(-10%)
599
+		$content = preg_replace('/\(\s*0\s+\-\s+([^\(\)]+)\)/', '(-\\1)', $content);
600
+		// I'm not going to attempt to optimize away `x * 0` instances:
601
+		// it's dumb enough code already that it likely won't occur, and it's
602
+		// too complex to do right (order of operations would have to be
603
+		// respected etc)
604
+		// what I cared about most here was fixing incorrectly truncated units
605
+
606
+		return $content;
607
+	}
608
+
609
+	/**
610
+	 * Strip comments from source code.
611
+	 *
612
+	 * @param string $content
613
+	 *
614
+	 * @return string
615
+	 */
616
+	protected function stripEmptyTags($content)
617
+	{
618
+		return preg_replace('/(^|\}|;)[^\{\};]+\{\s*\}/', '\\1', $content);
619
+	}
620
+
621
+	/**
622
+	 * Strip comments from source code.
623
+	 */
624
+	protected function stripComments()
625
+	{
626
+		$this->registerPattern('/\/\*.*?\*\//s', '');
627
+	}
628
+
629
+	/**
630
+	 * Strip whitespace.
631
+	 *
632
+	 * @param string $content The CSS content to strip the whitespace for
633
+	 *
634
+	 * @return string
635
+	 */
636
+	protected function stripWhitespace($content)
637
+	{
638
+		// remove leading & trailing whitespace
639
+		$content = preg_replace('/^\s*/m', '', $content);
640
+		$content = preg_replace('/\s*$/m', '', $content);
641
+
642
+		// replace newlines with a single space
643
+		$content = preg_replace('/\s+/', ' ', $content);
644
+
645
+		// remove whitespace around meta characters
646
+		// inspired by stackoverflow.com/questions/15195750/minify-compress-css-with-regex
647
+		$content = preg_replace('/\s*([\*$~^|]?+=|[{};,>~]|!important\b)\s*/', '$1', $content);
648
+		$content = preg_replace('/([\[(:])\s+/', '$1', $content);
649
+		$content = preg_replace('/\s+([\]\)])/', '$1', $content);
650
+		$content = preg_replace('/\s+(:)(?![^\}]*\{)/', '$1', $content);
651
+
652
+		// whitespace around + and - can only be stripped in selectors, like
653
+		// :nth-child(3+2n), not in things like calc(3px + 2px) or shorthands
654
+		// like 3px -2px
655
+		$content = preg_replace('/\s*([+-])\s*(?=[^}]*{)/', '$1', $content);
656
+
657
+		// remove semicolon/whitespace followed by closing bracket
658
+		$content = str_replace(';}', '}', $content);
659
+
660
+		return trim($content);
661
+	}
662
+
663
+	/**
664
+	 * Check if file is small enough to be imported.
665
+	 *
666
+	 * @param string $path The path to the file
667
+	 *
668
+	 * @return bool
669
+	 */
670
+	protected function canImportBySize($path)
671
+	{
672
+		return ($size = @filesize($path)) && $size <= $this->maxImportSize * 1024;
673
+	}
674 674
 }
Please login to merge, or discard this patch.
Spacing   +20 added lines, -20 removed lines patch added patch discarded remove patch
@@ -82,7 +82,7 @@  discard block
 block discarded – undo
82 82
             }
83 83
 
84 84
             // add to top
85
-            $content = implode('', $matches[0]).$content;
85
+            $content = implode('', $matches[0]) . $content;
86 86
         }
87 87
 
88 88
         return $content;
@@ -207,7 +207,7 @@  discard block
 block discarded – undo
207 207
         // loop the matches
208 208
         foreach ($matches as $match) {
209 209
             // get the path for the file that will be imported
210
-            $importPath = dirname($source).'/'.$match['path'];
210
+            $importPath = dirname($source) . '/' . $match['path'];
211 211
 
212 212
             // only replace the import with the content if we can grab the
213 213
             // content of the file
@@ -215,7 +215,7 @@  discard block
 block discarded – undo
215 215
                 // check if current file was not imported previously in the same
216 216
                 // import chain.
217 217
                 if (in_array($importPath, $parents)) {
218
-                    throw new FileImportException('Failed to import file "'.$importPath.'": circular reference detected.');
218
+                    throw new FileImportException('Failed to import file "' . $importPath . '": circular reference detected.');
219 219
                 }
220 220
 
221 221
                 // grab referenced file & minify it (which may include importing
@@ -225,7 +225,7 @@  discard block
 block discarded – undo
225 225
 
226 226
                 // check if this is only valid for certain media
227 227
                 if (!empty($match['media'])) {
228
-                    $importContent = '@media '.$match['media'].'{'.$importContent.'}';
228
+                    $importContent = '@media ' . $match['media'] . '{' . $importContent . '}';
229 229
                 }
230 230
 
231 231
                 // add to replacement array
@@ -254,7 +254,7 @@  discard block
 block discarded – undo
254 254
     protected function importFiles($source, $content)
255 255
     {
256 256
         $extensions = array_keys($this->importExtensions);
257
-        $regex = '/url\((["\']?)((?!["\']?data:).*?\.('.implode('|', $extensions).'))\\1\)/i';
257
+        $regex = '/url\((["\']?)((?!["\']?data:).*?\.(' . implode('|', $extensions) . '))\\1\)/i';
258 258
         if ($extensions && preg_match_all($regex, $content, $matches, PREG_SET_ORDER)) {
259 259
             $search = array();
260 260
             $replace = array();
@@ -263,7 +263,7 @@  discard block
 block discarded – undo
263 263
             foreach ($matches as $match) {
264 264
                 // get the path for the file that will be imported
265 265
                 $path = $match[2];
266
-                $path = dirname($source).'/'.$path;
266
+                $path = dirname($source) . '/' . $path;
267 267
                 $extension = $match[3];
268 268
 
269 269
                 // only replace the import with the content if we're able to get
@@ -275,7 +275,7 @@  discard block
 block discarded – undo
275 275
 
276 276
                     // build replacement
277 277
                     $search[] = $match[0];
278
-                    $replace[] = 'url('.$this->importExtensions[$extension].';base64,'.$importContent.')';
278
+                    $replace[] = 'url(' . $this->importExtensions[$extension] . ';base64,' . $importContent . ')';
279 279
                 }
280 280
             }
281 281
 
@@ -463,9 +463,9 @@  discard block
 block discarded – undo
463 463
             // build replacement
464 464
             $search[] = $match[0];
465 465
             if ($type == 'url') {
466
-                $replace[] = 'url('.$url.')';
466
+                $replace[] = 'url(' . $url . ')';
467 467
             } elseif ($type == 'import') {
468
-                $replace[] = '@import "'.$url.'"';
468
+                $replace[] = '@import "' . $url . '"';
469 469
             }
470 470
         }
471 471
 
@@ -519,8 +519,8 @@  discard block
 block discarded – undo
519 519
         );
520 520
 
521 521
         return preg_replace_callback(
522
-            '/(?<=[: ])('.implode(array_keys($colors), '|').')(?=[; }])/i',
523
-            function ($match) use ($colors) {
522
+            '/(?<=[: ])(' . implode(array_keys($colors), '|') . ')(?=[; }])/i',
523
+            function($match) use ($colors) {
524 524
                 return $colors[strtoupper($match[0])];
525 525
             },
526 526
             $content
@@ -541,11 +541,11 @@  discard block
 block discarded – undo
541 541
             'bold' => 700,
542 542
         );
543 543
 
544
-        $callback = function ($match) use ($weights) {
545
-            return $match[1].$weights[$match[2]];
544
+        $callback = function($match) use ($weights) {
545
+            return $match[1] . $weights[$match[2]];
546 546
         };
547 547
 
548
-        return preg_replace_callback('/(font-weight\s*:\s*)('.implode('|', array_keys($weights)).')(?=[;}])/', $callback, $content);
548
+        return preg_replace_callback('/(font-weight\s*:\s*)(' . implode('|', array_keys($weights)) . ')(?=[;}])/', $callback, $content);
549 549
     }
550 550
 
551 551
     /**
@@ -571,19 +571,19 @@  discard block
 block discarded – undo
571 571
         // practice, Webkit (especially Safari) seems to stumble over at least
572 572
         // 0%, potentially other units as well. Only stripping 'px' for now.
573 573
         // @see https://github.com/matthiasmullie/minify/issues/60
574
-        $content = preg_replace('/'.$before.'(-?0*(\.0+)?)(?<=0)px'.$after.'/', '\\1', $content);
574
+        $content = preg_replace('/' . $before . '(-?0*(\.0+)?)(?<=0)px' . $after . '/', '\\1', $content);
575 575
 
576 576
         // strip 0-digits (.0 -> 0)
577
-        $content = preg_replace('/'.$before.'\.0+'.$units.'?'.$after.'/', '0\\1', $content);
577
+        $content = preg_replace('/' . $before . '\.0+' . $units . '?' . $after . '/', '0\\1', $content);
578 578
         // strip trailing 0: 50.10 -> 50.1, 50.10px -> 50.1px
579
-        $content = preg_replace('/'.$before.'(-?[0-9]+\.[0-9]+)0+'.$units.'?'.$after.'/', '\\1\\2', $content);
579
+        $content = preg_replace('/' . $before . '(-?[0-9]+\.[0-9]+)0+' . $units . '?' . $after . '/', '\\1\\2', $content);
580 580
         // strip trailing 0: 50.00 -> 50, 50.00px -> 50px
581
-        $content = preg_replace('/'.$before.'(-?[0-9]+)\.0+'.$units.'?'.$after.'/', '\\1\\2', $content);
581
+        $content = preg_replace('/' . $before . '(-?[0-9]+)\.0+' . $units . '?' . $after . '/', '\\1\\2', $content);
582 582
         // strip leading 0: 0.1 -> .1, 01.1 -> 1.1
583
-        $content = preg_replace('/'.$before.'(-?)0+([0-9]*\.[0-9]+)'.$units.'?'.$after.'/', '\\1\\2\\3', $content);
583
+        $content = preg_replace('/' . $before . '(-?)0+([0-9]*\.[0-9]+)' . $units . '?' . $after . '/', '\\1\\2\\3', $content);
584 584
 
585 585
         // strip negative zeroes (-0 -> 0) & truncate zeroes (00 -> 0)
586
-        $content = preg_replace('/'.$before.'-?0+'.$units.'?'.$after.'/', '0\\1', $content);
586
+        $content = preg_replace('/' . $before . '-?0+' . $units . '?' . $after . '/', '0\\1', $content);
587 587
 
588 588
         // remove zeroes where they make no sense in calc: e.g. calc(100px - 0)
589 589
         // the 0 doesn't have any effect, and this isn't even valid without unit
Please login to merge, or discard this patch.