my-calendar-templates.php 69.3 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877
<?php
/**
 * Draw templates for My Calendar events.
 *
 * @category Calendar
 * @package  My Calendar
 * @author   Joe Dolson
 * @license  GPLv2 or later
 * @link     https://www.joedolson.com/my-calendar/
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Draw array of information into a template with {$key} formatted tags
 *
 * @param array       $array associative array of information intended to be parsed.
 * @param string      $template template containing braced tags (e.g. `{title}`) using keys of passed array.
 * @param string      $type my calendar needs to render a different link for list versions and other views.
 * @param object|bool $event Event object. Optional.
 *
 * @return string HTML output of template.
 */
function mc_draw_template( $array, $template, $type = 'list', $event = false ) {
	if ( is_object( $event ) ) {
		$description_fields = array( 'excerpt', 'description', 'description_raw', 'description_stripped', 'ical_excerpt', 'shortdesc', 'shortdesc_raw', 'shortdesc_stripped', 'ical_desc' );
		/**
		 * Filter fields that `mc_inner_content` runs on in templates.
		 *
		 * @hook mc_inner_content_template_fields
		 *
		 * @param {array}  $description_fields Array of template tags containing event description data.
		 * @param {object} $event Event object.
		 *
		 * @return {array}
		 */
		$description_fields = apply_filters( 'mc_inner_content_template_fields', $description_fields, $event );
		foreach ( $description_fields as $field ) {
			if ( isset( $array[ $field ] ) ) {
				/**
				 * Filter event content inside wrapper.
				 *
				 * @hook mc_inner_content
				 *
				 * @param {string} $detail Event details.
				 * @param {object} $event My Calendar event object.
				 * @param {string} $type View type.
				 * @param {string} $time View timeframe. Empty when run as a pre-templating filter.
				 *
				 * @return {string} Returning any non-empty string will shortcircuit template drawing.
				 */
				$array[ $field ] = apply_filters( 'mc_inner_content', $array[ $field ], $event, $type, '' );
			}
		}
	}
	$template = stripcslashes( $template );
	// If there are no brace characters, there is nothing to replace.
	if ( strpos( $template, '{' ) === false ) {
		return trim( $template );
	}
	// If the data passed is not an array or is empty, return empty string.
	if ( ! is_array( $array ) || empty( $array ) ) {
		return '';
	}
	foreach ( $array as $key => $value ) {
		if ( is_object( $value ) ) {
			// If a value is an object, ignore it.
		} else {
			if ( strpos( $template, '{' . $key ) !== false ) {
				if ( 'list' !== $type ) {
					if ( 'link' === $key && '' === $value ) {
						$value = mc_get_uri( false, $array );
					}
					if ( 'guid' !== $key ) {
						$value = htmlentities( $value );
					}
				}
				if ( strpos( $template, '{' . $key . ' ' ) !== false ) {
					// only do preg_match if appropriate.
					preg_match_all( '/{' . $key . '\b(?>\s+(?:before="([^"]*)"|after="([^"]*)"|format="([^"]*)")|[^\s]+|\s+){0,3}}/', $template, $matches, PREG_PATTERN_ORDER );
					if ( $matches ) {
						$number = count( $matches[0] );
						for ( $i = 0; $i < $number; $i ++ ) {
							$orig   = $value;
							$before = $matches[1][ $i ];
							$after  = $matches[2][ $i ];
							$format = $matches[3][ $i ];
							if ( '' !== $format ) {
								$value = date_i18n( stripslashes( $format ), strtotime( stripslashes( $value ) ) );
							}
							$value    = ( '' === (string) trim( $value ) ) ? '' : $before . $value . $after;
							$search   = $matches[0][ $i ];
							$template = str_replace( $search, $value, $template );
							$value    = $orig;
						}
					}
				} else {
					// don't do preg match for simple templates.
					$template = stripcslashes( str_replace( '{' . $key . '}', $value, $template ) );
				}
			}
			// End {$key check.
		}
	}
	/**
	 * Filter a rendered My Calendar template after parsing.
	 *
	 * @hook mc_template
	 *
	 * @param {string} $template Formatted HTML output of a template.
	 * @param {array}  $array Array of arguments passed to template.
	 * @param {string} $type Type of view being rendered.
	 * @param {object} $event Event object.
	 *
	 * @return {string} Formatted HTML.
	 */
	$template = apply_filters( 'mc_template', $template, $array, $type, $event );

	return stripslashes( trim( $template ) );
}

/**
 * Setup string version of address data
 *
 * @param object $event object containing location properties.
 * @param string $source event or location.
 *
 * @return string stringified address info
 */
function mc_map_string( $event, $source = 'event' ) {
	if ( ! is_object( $event ) ) {
		return '';
	}
	if ( 'event' === $source ) {
		$map_string = $event->event_street . ' ' . $event->event_street2 . ' ' . $event->event_city . ' ' . $event->event_state . ' ' . $event->event_postcode . ' ' . $event->event_country;
	} else {
		$map_string = $event->location_street . ' ' . $event->location_street2 . ' ' . $event->location_city . ' ' . $event->location_state . ' ' . $event->location_postcode . ' ' . $event->location_country;
	}

	return $map_string;
}

/**
 * Set up link to Mapping service.
 *
 * @param object $event object containing location properties.
 * @param string $request source of request.
 * @param string $source event/location.
 *
 * @return string URL or link depending on request
 */
function mc_maplink( $event, $request = 'map', $source = 'event' ) {
	$map_string = mc_map_string( $event, $source );
	// If the string is empty, then exit.
	if ( '' === $map_string ) {
		return '';
	}
	$map_target = mc_get_option( 'map_service' );
	if ( 'event' === $source ) {
		if ( 'gcal' === $request ) {
			return $map_string;
		}
		$zoom       = ( '0' !== $event->event_zoom ) ? $event->event_zoom : '15';
		$url        = $event->event_url;
		$map_label  = strip_tags( stripslashes( ( '' !== trim( $event->event_label ) ) ? $event->event_label : $event->event_title ), mc_strip_tags() );
		$map_string = str_replace( ' ', '+', $map_string );
		if ( '0.000000' !== $event->event_longitude && '0.000000' !== $event->event_latitude && 'mapquest' !== $map_target ) {
			$dir_lat    = ( $event->event_latitude > 0 ) ? 'N' : 'S';
			$latitude   = abs( $event->event_latitude );
			$dir_long   = ( $event->event_longitude > 0 ) ? 'E' : 'W';
			$longitude  = abs( $event->event_longitude );
			$map_string = $latitude . $dir_lat . ',' . $longitude . $dir_long;
		}
	} else {
		$url        = $event->location_url;
		$map_label  = strip_tags( stripslashes( ( '' !== trim( $event->location_label ) ) ? $event->location_label : '' ), mc_strip_tags() );
		$zoom       = ( '0' !== $event->location_zoom ) ? $event->location_zoom : '15';
		$map_string = str_replace( ' ', '+', $map_string );
		if ( '0.000000' !== $event->location_longitude && '0.000000' !== $event->location_latitude && 'mapquest' !== $map_target ) {
			$dir_lat    = ( $event->location_latitude > 0 ) ? 'N' : 'S';
			$latitude   = abs( $event->location_latitude );
			$dir_long   = ( $event->location_longitude > 0 ) ? 'E' : 'W';
			$longitude  = abs( $event->location_longitude );
			$map_string = $latitude . $dir_lat . ',' . $longitude . $dir_long;
		}
	}
	// Translators: Name of location.
	$label = sprintf( __( 'Map<span> to %s</span>', 'my-calendar' ), $map_label );
	/**
	 * Label for link to Maps for event location.
	 *
	 * @hook mc_map_label
	 *
	 * @param {string} $label Map to {event name}.
	 * @param {string} $map_label Location name.
	 *
	 * @return {string} Label used inside map link.
	 */
	$label = apply_filters( 'mc_map_label', $label, $map_label );
	if ( strlen( trim( $map_string ) ) > 6 ) {
		switch ( $map_target ) {
			case 'bing':
				$map_url = "https://bing.com/maps/?level=$zoom&amp;where1=$map_string";
				break;
			case 'mapquest':
				$map_url = "https://mapquest.com/search/$map_string?zoom=$zoom&amp;center=$map_string";
				break;
			case 'none':
				$map_url = '';
				break;
			default:
				$map_url = "https://maps.google.com/maps?z=$zoom&amp;daddr=$map_string";
				break;
		}
		/**
		 * Google maps URL.
		 *
		 * @hook mc_map_url
		 *
		 * @param {string} $url Link to event location on Google Maps.
		 * @param {object} $event Event object.
		 *
		 * @return {string} Link.
		 */
		$map_url = apply_filters( 'mc_map_url', $map_url, $event );
		$map     = '<a href="' . esc_url( $map_url ) . '" class="map-link external">' . $label . '</a>';
	} elseif ( esc_url( $url ) ) {
		$map_url = $url;
		$map     = "<a href=\"$map_url\" class='map-link external map-url'>" . $label . '</a>';
	} else {
		$map_url = '';
		$map     = '';
	}
	if ( 'url' === $request || 'location' === $source ) {
		return $map_url;
	} else {
		return $map;
	}
}

/**
 * Set up link to push events into Google Calendar.
 *
 * @param string $dtstart date begin.
 * @param string $dtend date end.
 * @param string $url link to event.
 * @param string $title Title of event.
 * @param string $location string version of location.
 * @param string $description info about event.
 *
 * @return string Google add to cal url
 */
function mc_google_cal( $dtstart, $dtend, $url, $title, $location, $description ) {
	$source = 'https://www.google.com/calendar/render?action=TEMPLATE';
	$base   = "&dates=$dtstart/$dtend";
	$base  .= '&sprop=website:' . $url;
	$base  .= '&text=' . urlencode( $title );
	/**
	 * Filter `location` parameter added to Google Calendar link. Default `&location=$location`. Return value needs to be URL encoded.
	 *
	 * @hook mc_gcal_location
	 *
	 * @param {string} $param Encoded parameter.
	 * @param {string} $location Unencoded original stringified location..
	 *
	 * @return {string} Encoded parameter.
	 */
	$base .= apply_filters( 'mc_gcal_location', '&location=' . urlencode( trim( $location ) ), $location );
	$base .= '&sprop=name:' . urlencode( get_bloginfo( 'name' ) );
	/**
	 * Filter `details` parameter added to Google Calendar link. Default `&details=$description`. Return value needs to be URL encoded.
	 *
	 * @hook mc_gcal_description
	 *
	 * @param {string} $param Encoded parameter.
	 * @param {string} $description Unencoded original description.
	 *
	 * @return {string} Encoded parameter.
	 */
	$base .= apply_filters( 'mc_gcal_description', '&details=' . urlencode( stripcslashes( trim( $description ) ) ), $description );
	$base .= '&sf=true&output=xml';

	return $source . $base;
}

/**
 * Format an hcard for event location
 *
 * @param object $event object with location properties.
 * @param string $address Whether to return the address.
 * @param string $map Whether to return the map.
 * @param string $source event/location.
 *
 * @return string hcard
 */
function mc_hcard( $event, $address = 'true', $map = 'true', $source = 'event' ) {
	if ( ! is_object( $event ) ) {
		return '';
	}
	if ( 'event' === $source && property_exists( $event, 'location' ) && is_object( $event->location ) ) {
		$event  = $event->location;
		$source = 'location';
	}
	$the_map = mc_maplink( $event, 'url', $source );
	$url     = ( 'event' === $source ) ? $event->event_url : $event->location_url;
	$url     = esc_url( $url );
	$label   = strip_tags( stripslashes( ( 'event' === $source ) ? $event->event_label : $event->location_label ), mc_strip_tags() );
	$street  = strip_tags( stripslashes( ( 'event' === $source ) ? $event->event_street : $event->location_street ), mc_strip_tags() );
	$street2 = strip_tags( stripslashes( ( 'event' === $source ) ? $event->event_street2 : $event->location_street2 ), mc_strip_tags() );
	$city    = strip_tags( stripslashes( ( 'event' === $source ) ? $event->event_city : $event->location_city ), mc_strip_tags() );
	$state   = strip_tags( stripslashes( ( 'event' === $source ) ? $event->event_state : $event->location_state ), mc_strip_tags() );
	$state   = strip_tags( stripslashes( ( 'event' === $source ) ? $event->event_state : $event->location_state ), mc_strip_tags() );
	$zip     = strip_tags( stripslashes( ( 'event' === $source ) ? $event->event_postcode : $event->location_postcode ), mc_strip_tags() );
	$zip     = strip_tags( stripslashes( ( 'event' === $source ) ? $event->event_postcode : $event->location_postcode ), mc_strip_tags() );
	$country = strip_tags( stripslashes( ( 'event' === $source ) ? $event->event_country : $event->location_country ), mc_strip_tags() );
	$country = strip_tags( stripslashes( ( 'event' === $source ) ? $event->event_country : $event->location_country ), mc_strip_tags() );
	$phone   = strip_tags( stripslashes( ( 'event' === $source ) ? $event->event_phone : $event->location_phone ), mc_strip_tags() );
	$loc_id  = absint( ( 'event' === $source ) ? false : $event->location_id );
	if ( ! $url && ! $label && ! $street && ! $street2 && ! $city && ! $state && ! $zip && ! $country && ! $phone ) {
		return '';
	}
	$distance = '';
	if ( property_exists( $event, 'distance_in_miles' ) ) {
		$dist     = ( 'en_US' === get_locale() ) ? $event->distance_in_miles : ( 1.60934 * $event->distance_in_miles );
		$unit     = ( 'en_US' === get_locale() ) ? ' miles' : ' km';
		$dist     = round( $dist, 1 ) . $unit;
		$distance = ' (' . $dist . ')';
	}
	if ( is_admin() && isset( $_GET['page'] ) && 'my-calendar-location-manager' === $_GET['page'] ) {
		$link = "<a href='" . add_query_arg( 'location_id', $loc_id, admin_url( 'admin.php?page=my-calendar-locations&mode=edit' ) ) . "' class='location-link edit p-name p-org u-url'><span class='dashicons dashicons-edit' aria-hidden='true'></span> <span id='location$event->location_id'>$label</span></a>";
	} else {
		$link = ( '' !== $url ) ? "<a href='$url' class='location-link external p-name p-org u-url'>$label</a>" : $label;
		$link = $link . $distance;
	}
	$post   = mc_get_location_post( $loc_id );
	$events = ( $post && ! is_single( $post ) && ! is_admin() && 'mc-locations' === get_post_type( $post ) ) ? '<a class="location-link" href="' . esc_url( get_the_permalink( $post ) ) . '">' . __( 'View Location', 'my-calendar' ) . '</a>' : '';
	/**
	 * Filter link to location-specific events in hcard.
	 *
	 * @hook mc_location_events_link
	 *
	 * @param {string} $events HTML link to location permalink.
	 * @param {object} $post Location post object.
	 * @param {object} $event Event object being mapped.
	 *
	 * @return {string} Link.
	 */
	$events = apply_filters( 'mc_location_events_link', $events, $post, $event );
	$hcard  = '<div class="address location vcard">';
	if ( 'true' === $address ) {
		$hcard .= '<div class="adr h-card">';
		$hcard .= ( '' !== $label ) ? '<div><strong class="location-link">' . $link . '</strong></div>' : '';
		$hcard .= ( '' === $street . $street2 . $city . $state . $zip . $country . $phone . $events ) ? '' : "<div class='sub-address'>";
		$hcard .= ( '' !== $street ) ? '<div class="street-address p-street-address">' . $street . '</div>' : '';
		$hcard .= ( '' !== $street2 ) ? '<div class="street-address p-extended-address">' . $street2 . '</div>' : '';
		$hcard .= ( '' !== $city . $state . $zip ) ? '<div>' : '';
		$hcard .= ( '' !== $city ) ? '<span class="locality p-locality">' . $city . '</span><span class="mc-sep">, </span>' : '';
		$hcard .= ( '' !== $state ) ? '<span class="region p-region">' . $state . '</span> ' : '';
		$hcard .= ( '' !== $zip ) ? ' <span class="postal-code p-postal-code">' . $zip . '</span>' : '';
		$hcard .= ( '' !== $city . $state . $zip ) ? '</div>' : '';
		$hcard .= ( '' !== $country ) ? '<div class="country-name p-country-name">' . $country . '</div>' : '';
		$hcard .= ( '' !== $phone ) ? '<div class="tel p-tel">' . $phone . '</div>' : '';
		$hcard .= ( '' !== $events ) ? '<div class="mc-events-link">' . $events . '</div>' : '';
		$hcard .= ( '' === $street . $street2 . $city . $state . $zip . $country . $phone . $events ) ? '' : '</div>';
		$hcard .= '</div>';
	}
	if ( 'true' === $map && false !== $the_map ) {
		$the_link = "<a href='$the_map' class='url external'>" . __( 'Map', 'my-calendar' ) . "<span class='screen-reader-text fn'> $label</span></a>";
		$hcard   .= ( '' !== $the_map ) ? "<div class='map'>$the_link</div>" : '';
	}
	$hcard .= '</div>';
	$hcard  = ( ( false !== $the_map && 'true' === $map ) || ( '' !== $link && 'true' === $address ) ) ? $hcard : '';

	/**
	 * Filter location hcard HTML output.
	 *
	 * @hook mc_hcard
	 *
	 * @param {string} $hcard Formatted HTML output.
	 * @param {object} $event Event or location object.
	 * @param {string} $address 'true' to include the location address on the card.
	 * @param {string} $map 'true' to include the map link on the card.
	 * @param {string} $source 'event' or 'location'.
	 *
	 * @return {string} Formatted HTML hcard.
	 */
	return apply_filters( 'mc_hcard', $hcard, $event, $address, $map, $source );
}

/**
 * Produces the array of event details used for drawing templates
 *
 * @param object $event Event object.
 * @param string $context Context being executed in.
 *
 * @return array event data
 */
function mc_create_tags( $event, $context = 'filters' ) {
	if ( ! is_object( $event ) ) {
		return array();
	}
	/**
	 * Execute action before tags are created.
	 *
	 * @hook mc_tags_created
	 *
	 * @param {object} $object Event object.
	 * @param {string} $context Current execution context.
	 */
	do_action( 'mc_create_tags', $event, $context );
	$calendar_id = '';
	if ( 'filters' !== $context && 'related' !== $context ) {
		$calendar_id = $context;
	}
	$site        = ( isset( $event->site_id ) ) ? $event->site_id : false;
	$e           = array();
	$e['post']   = $event->event_post;
	$date_format = mc_date_format();
	/**
	 * Filter template tag array and add author data. Runs before other template tags are created. Use `mc_filter_shortcodes` to modify existing template tags.
	 *
	 * @hook mc_insert_author_data
	 *
	 * @param {array}  $e Array to hold event template tags.
	 * @param {object} $event Event object.
	 *
	 * @return {array} Template tag array.
	 */
	$e = apply_filters( 'mc_insert_author_data', $e, $event );
	/**
	 * Filter template tag array and add image data. Runs before other template tags are created. Use `mc_filter_shortcodes` to modify existing template tags.
	 *
	 * @hook mc_filter_image_data
	 *
	 * @param {array}  $e Array to hold event template tags.
	 * @param {object} $event Event object.
	 *
	 * @return {array} Template tag array.
	 */
	$e             = apply_filters( 'mc_filter_image_data', $e, $event );
	$sitelink_html = "<div class='url link'><a href='" . esc_url( $event->event_url ) . "' class='location-link external'>";

	// Translators: Location name.
	$sitelink_html     .= sprintf( __( 'Visit web site<span class="screen-reader-text">: %s</span>', 'my-calendar' ), $event->event_label );
	$sitelink_html     .= '</a></div>';
	$e['sitelink_html'] = $sitelink_html;
	$e['sitelink']      = $event->event_url;
	$e['access']        = mc_expand( get_post_meta( $event->event_post, '_mc_event_access', true ) );

	// Date & time fields.
	$real_end_date   = ( isset( $event->occur_end ) ) ? $event->occur_end : $event->event_end . ' ' . $event->event_endtime;
	$real_begin_date = ( isset( $event->occur_begin ) ) ? $event->occur_begin : $event->event_begin . ' ' . $event->event_time;
	$dtstart         = mc_format_timestamp( strtotime( $real_begin_date ), $context );
	$dtend           = mc_format_timestamp( strtotime( $real_end_date ), $context );
	$recur_start     = mc_format_timestamp( strtotime( $event->event_begin . ' ' . $event->event_time ), $context );
	$recur_end       = mc_format_timestamp( strtotime( $event->event_end . ' ' . $event->event_endtime ), $context );
	/**
	 * Start date format used in 'date_utc'. Default from My Calendar settings.
	 *
	 * @hook mc_date_format
	 *
	 * @param {string} $format Date Format in PHP date format.
	 * @param {string} $context 'template_begin_ts'.
	 *
	 * @return {string} Date format.
	 */
	$e['date_utc'] = date_i18n( apply_filters( 'mc_date_format', $date_format, 'template_begin_ts' ), $event->ts_occur_begin );
	/**
	 * End date format used in 'date_end_utc'. Default from My Calendar settings.
	 *
	 * @hook mc_date_format
	 *
	 * @param {string} $format Date Format in PHP date format.
	 * @param {string} $context 'template_end_ts'.
	 *
	 * @return {string} Date format.
	 */
	$e['date_end_utc'] = date_i18n( apply_filters( 'mc_date_format', $date_format, 'template_end_ts' ), $event->ts_occur_end );
	$notime            = esc_html( mc_notime_label( $event ) );
	$e['time']         = ( '00:00:00' === mc_date( 'H:i:s', strtotime( $real_begin_date ), false ) ) ? $notime : mc_date( mc_time_format(), strtotime( $real_begin_date ), false );
	$e['time24']       = ( '00:00' === mc_date( 'G:i', strtotime( $real_begin_date ), false ) ) ? $notime : mc_date( mc_time_format(), strtotime( $real_begin_date ), false );
	$endtime           = ( '23:59:59' === $event->event_end ) ? '00:00:00' : mc_date( 'H:i:s', strtotime( $real_end_date ), false );
	$e['endtime']      = ( $real_end_date === $real_begin_date || '1' === $event->event_hide_end || '23:59:59' === mc_date( 'H:i:s', strtotime( $real_end_date ), false ) ) ? '' : date_i18n( mc_time_format(), strtotime( $endtime ) );
	$e['runtime']      = mc_runtime( $event->ts_occur_begin, $event->ts_occur_end, $event );
	$e['duration']     = mc_duration( $event );
	$e['dtstart']      = mc_date( 'Y-m-d\TH:i:s', strtotime( $real_begin_date ), false );  // Date: hcal formatted.
	$e['dtend']        = mc_date( 'Y-m-d\TH:i:s', strtotime( $real_end_date ), false );    // Date: hcal formatted end.
	$e['userstart']    = '<time class="mc-user-time" data-label="' . __( 'Local time:', 'my-calendar' ) . '">' . mc_date( 'Y-m-d\TH:i:s\Z', $event->ts_occur_begin, false ) . '</time>';
	$e['userend']      = '<time class="mc-user-time" data-label="' . __( 'Local time:', 'my-calendar' ) . '">' . mc_date( 'Y-m-d\TH:i:s\Z', $event->ts_occur_end, false ) . '</time>';
	/**
	 * Start date format used in 'date' and 'daterange' template tags. Fallback value for `datespan`. Default from My Calendar settings.
	 *
	 * @hook mc_date_format
	 *
	 * @param {string} $format Date Format in PHP date format.
	 * @param {string} $context 'template_begin'.
	 *
	 * @return {string} Date format.
	 */
	$date = date_i18n( apply_filters( 'mc_date_format', $date_format, 'template_begin' ), strtotime( $real_begin_date ) );
	/**
	 * End date format used in 'enddate' and 'daterange' template tags. Default from My Calendar settings.
	 *
	 * @hook mc_date_format
	 *
	 * @param {string} $format Date Format in PHP date format.
	 * @param {string} $context 'template_end'.
	 *
	 * @return {string} Date format.
	 */
	$date_end = date_i18n( apply_filters( 'mc_date_format', $date_format, 'template_end' ), strtotime( $real_end_date ) );
	$date_arr = array(
		'occur_begin' => $real_begin_date,
		'occur_end'   => $real_end_date,
	);
	$date_obj = (object) $date_arr;
	if ( '1' === $event->event_span ) {
		$dates = mc_event_date_span( $event->event_group_id, $event->event_span, array( 0 => $date_obj ) );
	} else {
		$dates = array();
	}
	$e['datetime']  = mc_time_html( $event, 'grid' );
	$e['date']      = ( '1' !== $event->event_span ) ? $date : mc_format_date_span( $dates, 'simple', $date );
	$e['enddate']   = $date_end;
	$e['daterange'] = ( $date === $date_end ) ? "<span class='mc_db'>$date</span>" : "<span class='mc_db'>$date</span> <span>&ndash;</span> <span class='mc_de'>$date_end</span>";
	$e['timerange'] = ( ( $e['time'] === $e['endtime'] ) || 1 === (int) $event->event_hide_end || '23:59:59' === mc_date( 'H:i:s', strtotime( $real_end_date ), false ) ) ? $e['time'] : "<span class='mc_tb'>" . $e['time'] . "</span> <span>&ndash;</span> <span class='mc_te'>" . $e['endtime'] . '</span>';
	$e['datespan']  = ( 1 === (int) $event->event_span || ( $e['date'] !== $e['enddate'] ) ) ? mc_format_date_span( $dates ) : $date;
	$e['multidate'] = mc_format_date_span( $dates, 'complex', "<span class='fallback-date'>$date</span><span class='separator'>,</span> <span class='fallback-time'>$e[time]</span>&ndash;<span class='fallback-endtime'>$e[endtime]</span>" );
	$e['began']     = $event->event_begin; // returns date of first occurrence of an event.
	$e['recurs']    = mc_event_recur_string( $event, $real_begin_date );
	$e['repeats']   = $event->event_repeats;

	// Category fields.
	$e['cat_id']          = $event->event_category;
	$e['category_id']     = $event->event_category;
	$e['category']        = stripslashes( $event->category_name );
	$e['ical_category']   = strip_tags( stripslashes( $event->category_name ) );
	$e['categories']      = ( property_exists( $event, 'categories' ) ) ? mc_categories_html( $event->categories, $event->event_category ) : mc_get_categories( $event, 'html' );
	$e['ical_categories'] = ( property_exists( $event, 'categories' ) ) ? mc_categories_html( $event->categories, $event->event_category, 'text' ) : mc_get_categories( $event, 'text' );
	$e['term']            = intval( $event->category_term );
	$e['icon']            = mc_category_icon( $event, 'img' );
	$e['icon_html']       = mc_category_icon( $event );
	$e['color']           = $event->category_color;

	$hex          = ( strpos( $event->category_color, '#' ) !== 0 ) ? '#' : '';
	$color        = $hex . $event->category_color;
	$inverse      = mc_inverse_color( $color );
	$e['inverse'] = $inverse;

	// This is because widgets now strip out style attributes.
	$e['color_css']       = "<span style='background-color: $event->category_color; color: $inverse'>";
	$e['close_color_css'] = '</span>';

	// Special.
	$e['skip_holiday'] = ( 0 === (int) $event->event_holiday ) ? 'false' : 'true';
	$e['event_status'] = ( 1 === (int) $event->event_approved ) ? __( 'Published', 'my-calendar' ) : __( 'Draft', 'my-calendar' );

	// General text fields.
	$title                     = mc_search_highlight( $event->event_title );
	$e['title']                = stripslashes( $title );
	$e['description']          = wpautop( stripslashes( $event->event_desc ) );
	$e['description_raw']      = stripslashes( $event->event_desc );
	$e['description_stripped'] = strip_tags( stripslashes( $event->event_desc ) );
	$e['shortdesc']            = wpautop( stripslashes( $event->event_short ) );
	$e['shortdesc_raw']        = stripslashes( $event->event_short );
	$e['shortdesc_stripped']   = strip_tags( stripslashes( $event->event_short ) );

	// Registration fields.
	$e['event_tickets']      = $event->event_tickets;
	$e['event_registration'] = stripslashes( wp_kses_data( $event->event_registration ) );

	// Links.
	$templates  = mc_get_option( 'templates' );
	$e_template = ( ! empty( $templates['label'] ) ) ? stripcslashes( $templates['label'] ) : __( 'Details about', 'my-calendar' ) . ' {title}';
	/**
	 * Filter template for the `{details}` output. Default: `Details about {title}`.
	 *
	 * @hook mc_details_template
	 *
	 * @param {string} $e_template String with template tags.
	 * @param {object} $event Event object.
	 *
	 * @return {string} Unparsed template.
	 */
	$e_template   = apply_filters( 'mc_details_template', $e_template, $event );
	$tags         = array( '{title}', '{location}', '{color}', '{icon}', '{date}', '{time}' );
	$replacements = array(
		stripslashes( $e['title'] ),
		stripslashes( $event->event_label ),
		$event->category_color,
		$event->category_icon,
		$e['date'],
		$e['time'],
	);

	$classes   = mc_event_classes( $event, 'template' );
	$nofollow  = ( stripos( $classes, 'past-event' ) !== false ) ? 'rel="nofollow"' : '';
	$e_label   = str_replace( $tags, $replacements, $e_template );
	$e_link    = mc_get_details_link( $event );
	$e['link'] = mc_event_link( $event );
	if ( $e['link'] ) {
		$e['link_image'] = str_replace( "alt=''", "alt='" . esc_attr( $e['title'] ) . "'", "<a href='" . esc_url( $e['link'] ) . "' $nofollow>" . $e['image'] . '</a>' );
		$e['link_title'] = "<a href='" . esc_url( $event->event_link ) . "' $nofollow>" . $e['title'] . '</a>';
	} else {
		$e['link_image'] = $e['image'];
		$e['link_title'] = $e['title'];
	}

	$e['details_link'] = $e_link;
	$e['details_ical'] = remove_query_arg( 'mc_id', $e_link ); // In ical series exports, it's impossible to get the actual details link.
	$e['details']      = "<a href='" . esc_url( $e_link ) . "' class='mc-details' $nofollow>$e_label</a>";
	$e['linking']      = ( '' !== $e['link'] ) ? $event->event_link : $e_link;

	$rel = $nofollow;
	if ( mc_external_link( $e['linking'] ) ) {
		if ( $rel ) {
			$rel = 'rel="external nofollow"';
		} else {
			$rel = 'rel="external"';
		}
	}
	$e['linking_title'] = ( '' !== $e['linking'] ) ? "<a href='" . esc_url( $e['linking'] ) . "' $rel>" . $e['title'] . '</a>' : $e['title'];

	if ( 'related' !== $context && ( mc_is_single_event() ) ) {
		/**
		 * HTML format for displaying related events on a single event view. Default `{date}, {time}`.
		 *
		 * @hook mc_related_template
		 *
		 * @param {string} $template Template to use to draw a related event.
		 * @param {object} $event Event object.
		 *
		 * @return {string} Unparsed template.
		 */
		$related_template = apply_filters( 'mc_related_template', '{date}, {time}', $event );
		$e['related']     = '<ul class="related-events">' . mc_list_group( $event->event_group_id, $event->event_id, $related_template ) . '</ul>';
	} else {
		$e['related'] = '';
	}

	// location fields.
	$e['location_source'] = $event->event_location;
	$map_gcal             = '';
	if ( property_exists( $event, 'location' ) ) {
		$location = $event->location;
		if ( is_object( $location ) ) {
			$map           = mc_maplink( $location, 'map', 'location' );
			$map_url       = mc_maplink( $location, 'url', 'location' );
			$map_gcal      = mc_maplink( $location, 'gcal', 'location' );
			$e['location'] = stripslashes( $location->location_label );
			$e['street']   = stripslashes( $location->location_street );
			$e['street2']  = stripslashes( $location->location_street2 );
			/**
			 * Format a phone number for display in template tags.
			 *
			 * @hook mc_phone_format
			 *
			 * @param {string} $number Phone number as saved in `$location->location_phone`.
			 * @param {string} $context 'phone'.
			 *
			 * @return {string} Formatted number.
			 */
			$e['phone'] = apply_filters( 'mc_phone_format', stripslashes( $location->location_phone ), 'phone' );
			/**
			 * Format a phone number for display in template tags.
			 *
			 * @hook mc_phone_format
			 *
			 * @param {string} $number Phone number as saved in `$location->location_phone`.
			 * @param {string} $context 'phone2'.
			 *
			 * @return {string} Formatted number.
			 */
			$e['phone2']          = apply_filters( 'mc_phone_format', stripslashes( $location->location_phone2 ), 'phone2' );
			$e['city']            = stripslashes( $location->location_city );
			$e['state']           = stripslashes( $location->location_state );
			$e['postcode']        = stripslashes( $location->location_postcode );
			$e['country']         = stripslashes( $location->location_country );
			$e['region']          = $location->location_region;
			$e['hcard']           = stripslashes( mc_hcard( $location, 'true', 'true', 'location' ) );
			$e['link_map']        = $map;
			$e['map_url']         = $map_url;
			$e['map']             = mc_generate_map( $location, 'location' );
			$e['location_access'] = mc_expand( unserialize( $location->location_access ) );
			$e['ical_location']   = trim( $location->location_label . ' ' . $location->location_street . ' ' . $location->location_street2 . ' ' . $location->location_city . ' ' . $location->location_state . ' ' . $location->location_postcode );
		}
	} else {
		$map           = mc_maplink( $event );
		$map_url       = mc_maplink( $event, 'url' );
		$map_gcal      = mc_maplink( $event, 'gcal' );
		$e['location'] = stripslashes( $event->event_label );
		$e['street']   = stripslashes( $event->event_street );
		$e['street2']  = stripslashes( $event->event_street2 );
		/**
		 * Format a phone number for display in template tags.
		 *
		 * @hook mc_phone_format
		 *
		 * @param {string} $number Phone number as saved in `$event->event_phone`.
		 * @param {stirng} $context 'phone'.
		 *
		 * @return {string} Formatted number.
		 */
		$e['phone'] = apply_filters( 'mc_phone_format', stripslashes( $event->event_phone ), 'phone' );
		/**
		 * Format a phone number for display in template tags.
		 *
		 * @hook mc_phone_format
		 *
		 * @param {string} $number Phone number as saved in `$event->event_phone2`.
		 * @param {string} $context 'phone2'.
		 *
		 * @return {string} Formatted number.
		 */
		$e['phone2']          = apply_filters( 'mc_phone_format', stripslashes( $event->event_phone2 ), 'phone2' );
		$e['city']            = stripslashes( $event->event_city );
		$e['state']           = stripslashes( $event->event_state );
		$e['postcode']        = stripslashes( $event->event_postcode );
		$e['country']         = stripslashes( $event->event_country );
		$e['region']          = $event->event_region;
		$e['hcard']           = stripslashes( mc_hcard( $event ) );
		$e['link_map']        = $map;
		$e['map_url']         = $map_url;
		$e['map']             = mc_generate_map( $event );
		$location_access      = mc_location_data( 'location_access', $event->event_location );
		$e['location_access'] = ( is_string( $location_access ) && '' !== $location_access ) ? mc_expand( unserialize( $location_access ) ) : '';
		$e['ical_location']   = trim( $event->event_label . ' ' . $event->event_street . ' ' . $event->event_street2 . ' ' . $event->event_city . ' ' . $event->event_state . ' ' . $event->event_postcode );
	}

	$strip_desc     = mc_newline_replace( strip_tags( $event->event_desc ) ) . ' ' . $e['link'];
	$e['gcal']      = mc_google_cal( $dtstart, $dtend, $e_link, stripcslashes( $e['title'] ), $map_gcal, $strip_desc );
	$e['gcal_link'] = "<a href='" . esc_url( $e['gcal'] ) . "' class='gcal external' rel='nofollow' aria-describedby='mc_$event->occur_id-title-$calendar_id'>" . __( 'Google Calendar', 'my-calendar' ) . '</a>';

	// IDs.
	$e['dateid']     = $event->occur_id; // Unique ID for this date of this event.
	$e['id']         = $event->event_id;
	$e['group']      = $event->event_group_id;
	$e['event_span'] = $event->event_span;

	// ICAL.
	$e['ical_desc']       = $strip_desc;
	$e['ical_start']      = ( mc_is_all_day( $event ) ) ? mc_date( 'Ymd', strtotime( $recur_start ) ) : $recur_start;
	$e['ical_end']        = ( mc_is_all_day( $event ) ) ? mc_date( 'Ymd', strtotime( $recur_end ) + 60, false ) : $recur_end;
	$e['ical_date_start'] = ( mc_is_all_day( $event ) ) ? mc_date( 'Ymd', strtotime( $dtstart ) ) : $dtstart;
	$e['ical_date_end']   = ( mc_is_all_day( $event ) ) ? mc_date( 'Ymd', strtotime( $dtend ) + 60, false ) : $dtend;
	$e['ical_recur']      = mc_generate_rrule( $event );
	$ical_link            = mc_build_url(
		array( 'vcal' => $event->occur_id ),
		array(
			'month',
			'dy',
			'yr',
			'ltype',
			'loc',
			'mcat',
			'format',
			'time',
		),
		mc_get_uri( $event )
	);
	$e['ical']            = $ical_link;
	$e['ical_html']       = "<a class='ical' rel='nofollow' href='" . esc_url( $ical_link ) . "' aria-describedby='mc_$event->occur_id-title-$calendar_id'>" . __( 'iCal', 'my-calendar' ) . '</a>';

	/**
	 * Filter all template tags after generation.
	 *
	 * @hook mc_filter_shortcodes
	 *
	 * @param {array}  $e Array of values to be used in template tags.
	 * @param {object} $event Event object.
	 *
	 * @return {array} Array of template tags.
	 */
	$e = apply_filters( 'mc_filter_shortcodes', $e, $event );
	/**
	 * Execute action when tags are created.
	 *
	 * @hook mc_tags_created
	 *
	 * @param {object} $object Event object.
	 * @param {string} $context Current execution context.
	 */
	do_action( 'mc_tags_created', $event, $context );

	return $e;
}

/**
 * Get the label for all day events.
 *
 * @param object $event Event object.
 *
 * @return string.
 */
function mc_notime_label( $event ) {
	$notime  = '';
	$default = mc_get_option( 'notime_text' );
	if ( is_object( $event ) && property_exists( $event, 'event_post' ) ) {
		$notime  = get_post_meta( $event->event_post, '_event_time_label', true );
		$default = ( metadata_exists( 'post', $event->event_post, '_event_time_label' ) ) ? '' : $default;
	}
	$notime = ( '' !== $notime ) ? $notime : $default;

	/**
	 * Label to use in place of time for an event with no fixed time.
	 *
	 * @hook mc_notime_label
	 *
	 * @param {string} $notime Default value from settings or event post meta.
	 * @param {object} $event Event object.
	 *
	 * @return {string} Text describing when the event occurs. E.g. 'all day' or 'to be determined'.
	 */
	return apply_filters( 'mc_notime_label', $notime, $event );
}

/**
 * Get link to event's details page.
 *
 * @param object|int $event Full event object or event occurrence ID.
 *
 * @return string URL.
 */
function mc_get_details_link( $event ) {
	if ( is_numeric( $event ) ) {
		$event = mc_get_event( $event );
	}
	if ( ! is_object( $event ) ) {
		return '';
	}
	$restore = false;
	if ( is_multisite() && property_exists( $event, 'site_id' ) && get_current_blog_id() !== $event->site_id ) {
		switch_to_blog( $event->site_id );
		$restore = true;
	}
	$uri = mc_get_uri( $event );

	/**
	 * Check whether permalinks are enabled.
	 *
	 * @hook mc_use_permalinks
	 *
	 * @param {string} $option Value of mc_use_permalinks setting.
	 *
	 * @return {bool} True value if permalinks are enabled.
	 */
	$permalinks   = apply_filters( 'mc_use_permalinks', mc_get_option( 'use_permalinks' ) );
	$permalinks   = ( 1 === $permalinks || true === $permalinks || 'true' === $permalinks ) ? true : false;
	$details_link = mc_event_link( $event );
	if ( 0 !== (int) $event->event_post && 'true' !== mc_get_option( 'remote' ) && $permalinks ) {
		$details_link = add_query_arg( 'mc_id', $event->occur_id, get_permalink( $event->event_post ) );
	} else {
		if ( mc_get_uri( 'boolean' ) ) {
			$details_link = mc_build_url(
				array( 'mc_id' => $event->occur_id ),
				array(
					'month',
					'dy',
					'yr',
					'ltype',
					'loc',
					'mcat',
					'format',
					'feed',
					'page_id',
					'p',
					'mcs',
					'time',
					'page',
					'mode',
					'event_id',
				),
				$uri
			);
		}
	}
	/**
	 * URL to an event's permalink page.
	 *
	 * @hook mc_customize_details_link
	 *
	 * @param {string} $details_link Link to event details page/permalink.
	 * @param {object} $event Event object.
	 *
	 * @return {string} URL.
	 */
	$details_link = apply_filters( 'mc_customize_details_link', $details_link, $event );

	if ( $restore ) {
		restore_current_blog();
	}

	return $details_link;
}

/**
 * Get primary My Calendar URI from settings.
 *
 * @param object|string|bool $event Event object, string requesting boolean result, or boolean false.
 * @param array              $args  Any arguments passed.
 *
 * @uses filter 'mc_get_uri'
 *
 * @return mixed string/boolean URL
 */
function mc_get_uri( $event = false, $args = array() ) {
	// For a brief period of time, mc_uri was a post ID.
	// Convert mc_uri to mc_uri_id.
	$mc_uri = mc_get_option( 'uri' );
	$mc_id  = mc_get_option( 'uri_id' );
	if ( is_numeric( $mc_uri ) && ! $mc_id ) {
		mc_update_option( 'uri_id', $mc_uri );
		mc_update_option( 'uri', get_permalink( $mc_id ) );
	}
	$mc_uri = mc_get_option( 'uri' );
	$mc_id  = mc_get_option( 'uri_id' );

	$uri = ( get_permalink( $mc_id ) !== mc_get_option( 'uri' ) ) ? mc_get_option( 'uri' ) : get_permalink( $mc_id );

	if ( 'boolean' === $event ) {
		if ( ! _mc_is_url( $uri ) ) {
			return false;
		} else {
			return true;
		}
	}

	if ( ! $uri ) {
		$uri = home_url();
	}
	/**
	 * Link to the My Calendar main calendar view.
	 *
	 * @hook mc_get_uri
	 *
	 * @param {string}             $link String to return if event link is expired.
	 * @param {object|string|bool} $event Event object, string requesting boolean result, or boolean false.
	 * @param {array}              $args Current view arguments. (Optional).
	 *
	 * @return {string} URL.
	 */
	return apply_filters( 'mc_get_uri', $uri, $event, $args );
}

/**
 * Get the templated label for a details link
 *
 * @param object $event event.
 * @param array  $e tags array.
 *
 * @return string label
 */
function mc_get_details_label( $event, $e ) {
	$templates  = mc_get_option( 'templates' );
	$e_template = ( ! empty( $templates['label'] ) ) ? stripcslashes( $templates['label'] ) : __( 'Read more', 'my-calendar' );
	$e_label    = wp_kses(
		mc_draw_template( $e, $e_template ),
		array(
			'span' => array(
				'class' => array(
					'screen-reader-text',
				),
			),
			'em',
			'strong',
		)
	);

	return $e_label;
}

/**
 * Format a timestamp for use in ical
 *
 * @param integer $os timestamp.
 * @param string  $source google or outlook.
 *
 * @return string formatted time
 */
function mc_format_timestamp( $os, $source ) {
	if ( isset( $_GET['outlook'] ) || 'outlook' === $source ) {
		// Should iCal be in UTC or in current timezone.
		$timezone_string = get_option( 'timezone_string' );
		if ( ! $timezone_string ) {
			// Multiply gmt_offset by -1 because POSIX has it reversed.
			// See: http://stackoverflow.com/questions/20228224/php-timezone-issue.
			$timezone_string = sprintf( 'Etc/GMT%+d', -1 * get_option( 'gmt_offset' ) );
		}

		$timezone_object = timezone_open( $timezone_string );
		$date_object     = date_create( 'now', $timezone_object );

		$date_object->setTime( mc_date( 'H', $os, false ), mc_date( 'i', $os, false ) );
		$date_object->setDate( mc_date( 'Y', $os, false ), mc_date( 'm', $os, false ), mc_date( 'd', $os, false ) );

		$timestamp = $date_object->getTimestamp();
		$time      = gmdate( 'Ymd\THi00', $timestamp ) . 'Z';

	} else {
		$os_time = mktime( mc_date( 'H', $os, false ), mc_date( 'i', $os, false ), mc_date( 's', $os, false ), mc_date( 'm', $os, false ), mc_date( 'd', $os, false ), mc_date( 'Y', $os, false ) );
		$time    = mc_date( 'Ymd\THi00', $os_time, false );
	}

	return $time;
}

/**
 * Get a human-readable version of the duration of an event
 *
 * @param string $start start date/time.
 * @param string $end  end date/time.
 * @param object $event event object.
 *
 * @return string human readable time
 */
function mc_runtime( $start, $end, $event ) {
	$return = '';
	if ( ! ( $event->event_hide_end || $start === $end || '23:59:59' === mc_date( 'H:i:s', strtotime( $end ), false ) ) ) {
		$return = human_time_diff( $start, $end );
	}

	return $return;
}

/**
 * Return ISO8601 duration marker
 *
 * @param object $event event object.
 *
 * @return string ISO8601 duration format
 */
function mc_duration( $event ) {
	$start = $event->occur_begin;
	$end   = $event->occur_end;

	$datetime1 = new DateTime( $start );
	$datetime2 = new DateTime( $end );
	$interval  = $datetime1->diff( $datetime2 );

	$duration  = '';
	$duration .= ( 0 !== (int) $interval->y ) ? $interval->y . 'Y' : '';
	$duration .= ( 0 !== (int) $interval->m ) ? $interval->m . 'M' : '';
	if ( '23' === (string) $interval->h && '59' === (string) $interval->i ) {
		$d         = ( 0 === (int) $interval->d ) ? 1 : $interval->d + 1;
		$duration .= 'D' . $d;
		$duration .= 'TH0M0';
	} else {
		$duration .= ( 0 !== (int) $interval->d ) ? $interval->d . 'D' : '';
		$duration .= ( 0 !== (int) $interval->h ) ? 'T' . $interval->h . 'H' : '';
		$duration .= ( 0 !== (int) $interval->i ) ? $interval->i . 'M' : '';
	}
	$duration = 'P' . $duration;

	return $duration;
}

/**
 * Get event link if not designated to expire & expired.
 *
 * @param object $event Event Object.
 *
 * @return string
 */
function mc_event_link( $event ) {
	$link = '';
	if ( ! is_object( $event ) ) {
		return $link;
	}
	$expired = mc_event_expired( $event );
	if ( 0 === (int) $event->event_link_expires ) {
		$link = esc_url( $event->event_link );
	} else {
		if ( $expired ) {
			/**
			 * Link to return if an event's link has expired. Default empty string.
			 *
			 * @hook mc_event_expired_link
			 *
			 * @param {string} $link String to return if event link is expired.
			 * @param {object} $event Event object.
			 *
			 * @return {string} Link or empty string.
			 */
			$link = apply_filters( 'mc_event_expired_link', '', $event );
		} else {
			$link = esc_url( $event->event_link );
		}
	}

	return $link;
}

/**
 * Test if event has already passed.
 *
 * @param object $event Event object.
 *
 * @return boolean
 */
function mc_event_expired( $event ) {
	if ( is_object( $event ) && property_exists( $event, 'occur_end' ) ) {
		if ( my_calendar_date_xcomp( $event->occur_end, current_time( 'Y-m-d' ) ) ) {
			/**
			 * Execute action once an event is over.
			 *
			 * @hook mc_event_expired
			 *
			 * @param {object} $object Event object.
			 */
			do_action( 'mc_event_expired', $event );

			return true;
		}
	}

	return false;
}

/**
 * Generate script and HTML for Google Maps embed if API key present
 *
 * @param object|array $event Object containing location parameters or array of objects.
 * @param string       $source event or location.
 * @param bool         $multiple True if event contains multiple locations.
 * @param bool         $geolocate True if map is generated from geolocation data.
 *
 * @return string HTML
 */
function mc_generate_map( $event, $source = 'event', $multiple = false, $geolocate = false ) {
	if ( ! is_object( $event ) && ! $multiple ) {
		return '';
	}
	if ( ! is_array( $event ) && $multiple ) {
		return '';
	}

	$id       = '0';
	$api_key  = mc_get_option( 'gmap_api_key' );
	$markers  = '';
	$loc_list = '';
	$out      = '';
	/**
	 * Default map width. Default value `100%`.
	 *
	 * @hook mc_map_width
	 *
	 * @param {string} $width Width parameter passed to map container style attribute.
	 * @param {object} $event Event or location object containing location information.
	 *
	 * @return {string} Value.
	 */
	$width = apply_filters( 'mc_map_width', '100%', $event );
	/**
	 * Default map height. Default value `300px`.
	 *
	 * @hook mc_map_height
	 *
	 * @param {string} $height Height parameter passed to map container style attribute.
	 * @param {object} $event Event or location object containing location information.
	 *
	 * @return {string} Value.
	 */
	$height = apply_filters( 'mc_map_height', '300px', $event );
	$styles = " style='width: $width;height: $height'";
	// This is an event with a location object property.
	if ( 'event' === $source && property_exists( $event, 'location' ) && is_object( $event->location ) ) {
		$event  = $event->location;
		$source = 'location';
	}
	// This is an event with a location ID, but no attached object.
	if ( 'event' === $source && $event->event_location ) {
		$event  = mc_get_location( $event->event_location );
		$source = 'location';
	}
	if ( $api_key ) {
		$locations = ( is_object( $event ) ) ? array( $event ) : $event;
		if ( is_array( $locations ) ) {
			$multiple = ( count( $locations ) > 1 ) ? true : false;
			foreach ( $locations as $location ) {
				$id     = rand();
				$loc_id = $location->{$source . '_id'};
				$source = ( 'event' === $source ) ? 'event' : 'location';
				/**
				 * URL to Google Map marker image.
				 *
				 * @hook mc_map_icon
				 *
				 * @param {string} $icon    Formatted HTML to be returned.
				 * @param {object} $location Event or location object containing location information.
				 * @param {string} $source Either 'event' or 'location' indicating type of object.
				 *
				 * @return {string} URL to icon.
				 */
				$category_icon = apply_filters( 'mc_map_icon', '//maps.google.com/mapfiles/marker_green.png', $location, $source );
				$address       = addslashes( mc_map_string( $location, $source ) );

				if ( '0.000000' !== $location->{$source . '_longitude'} && '0.000000' !== $location->{$source . '_latitude'} ) {
					$lat    = $location->{$source . '_latitude'};
					$lng    = $location->{$source . '_longitude'};
					$latlng = true;
				} else {
					$lat    = '';
					$lng    = '';
					$latlng = false;
				}

				if ( strlen( $address ) < 10 && ! $latlng ) {
					return '';
				}
				$hcard  = mc_hcard( $location, 'true', false, $source );
				$title  = esc_attr( $location->{$source . '_label'} );
				$marker = wp_kses(
					str_replace(
						array( '</div>', '<br />', '<br><br>' ),
						'<br>',
						$hcard
					),
					array(
						'br'     => array(),
						'strong' => array(),
					)
				);
				/**
				 * Source HTML for a single location marker.
				 *
				 * @hook mc_map_html
				 *
				 * @param {string} $marker Formatted HTML to be returned.
				 * @param {object} $location Event object containing location information.
				 *
				 * @return {string} Formatted HTML to be parsed by Google Maps JS.
				 */
				$html      = apply_filters( 'mc_map_html', $marker, $location );
				$markers  .= PHP_EOL . "<div class='marker' data-address='$address' data-title='$title' data-icon='$category_icon' data-lat='$lat' data-lng='$lng'>$html</div>" . PHP_EOL;
				$loc_list .= ( $multiple ) ? '<div class="mc-location-details" id="mc-location-' . $id . '-' . $loc_id . '">' . $hcard . '</div>' : '';
			}
			/**
			 * Source HTML for generating a map of calendar locations.
			 *
			 * @hook mc_gmap_html
			 *
			 * @param {string}       $output Formatted HTML to be returned.
			 * @param {object|array} $event Object or array of objects containing one or more objects with location information.
			 *
			 * @return {string} Formatted HTML to be parsed by Google Maps JS.
			 */
			$markers = apply_filters( 'mc_gmap_html', $markers, $event );
			$class   = ( $geolocate ) ? 'mc-geolocated' : 'mc-address';
			$map     = "<div class='mc-gmap-markers $class' id='mc_gmap_$id' $styles>" . $markers . '</div>';
			$locs    = ( $loc_list ) ? '<div class="mc-gmap-location-list"><h2 class="screen-reader-text">' . __( 'Locations', 'my-calendar' ) . '</h2>' . $loc_list . '</div>' : '';
			$out     = '<div class="mc-maps">' . $map . $locs . '</div>';
		}
	}

	return $out;
}

/**
 * Expand access data into a list of features.
 *
 * @param array $data Either event or location accessibility data.
 *
 * @return string list of features.
 */
function mc_expand( $data ) {
	$output = '';
	if ( is_array( $data ) ) {
		foreach ( $data as $key => $value ) {
			$class = ( isset( $value ) ) ? sanitize_html_class( $value ) : '';
			$label = ( isset( $value ) ) ? $value : false;
			if ( ! $label ) {
				continue;
			}
			$output .= "<li class='$class'><span>$label</span></li>\n";
		}
		$output = ( $output ) ? "<ul class='mc-access'>" . $output . '</ul>' : '';
	}

	/**
	 * HTML output from an internal data array, e.g. accessibility features.
	 *
	 * @hook mc_expand
	 *
	 * @param {string} $output Formatted HTML to be returned.
	 * @param {array} $data Array of data being parsed.
	 *
	 * @return {string} Formatted HTML.
	 */
	return apply_filters( 'mc_expand', $output, $data );
}

/**
 * Get the full date span of a set of events for display.
 *
 * @param int   $group_id Group ID.
 * @param int   $event_span Whether these events constitute one event.
 * @param array $dates Start and end dates of current event.
 *
 * @return array
 */
function mc_event_date_span( $group_id, $event_span, $dates = array() ) {
	$mcdb = mc_is_remote_db();
	// Cache as transient to save db queries.
	if ( get_transient( 'mc_event_date_span_' . $group_id . '_' . $event_span ) ) {
		return get_transient( 'mc_event_date_span_' . $group_id . '_' . $event_span );
	}
	$group_id = (int) $group_id;
	if ( 0 === (int) $group_id && 1 !== (int) $event_span ) {

		return $dates;
	} else {
		$dates = $mcdb->get_results( $mcdb->prepare( 'SELECT occur_begin, occur_end FROM ' . my_calendar_event_table() . ' WHERE occur_group_id = %d ORDER BY occur_begin ASC', $group_id ) ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
		set_transient( 'mc_event_date_span_' . $group_id . '_' . $event_span, $dates, HOUR_IN_SECONDS );

		return $dates;
	}
}

/**
 * Format a date span.
 *
 * @param array  $dates to format.
 * @param string $display type of display to use.
 * @param string $default value if no dates passed.
 *
 * @return string
 */
function mc_format_date_span( $dates, $display = 'simple', $default = '' ) {
	if ( ! $dates ) {
		return $default;
	}
	$count = count( $dates );
	$last  = $count - 1;
	if ( 'simple' === $display ) {
		$begin = $dates[0]->occur_begin;
		$end   = $dates[ $last ]->occur_end;

		/**
		 * Starting date format used in 'date', 'datespan', and 'multidate' template tags. Default from My Calendar settings.
		 *
		 * @hook mc_date_format
		 *
		 * @param {string} $format Date Format in PHP date format.
		 * @param {string} $context 'date_span_begin'.
		 *
		 * @return {string} Date format.
		 */
		$begin = date_i18n( apply_filters( 'mc_date_format', mc_date_format(), 'date_span_begin' ), strtotime( $begin ) );
		/**
		 * End date format used in 'date', 'datespan', and 'multidate' template tags. Default from My Calendar settings.
		 *
		 * @hook mc_date_format
		 *
		 * @param {string} $format Date Format in PHP date format.
		 * @param {string} $context 'date_span_end'.
		 *
		 * @return {string} Date format.
		 */
		$end    = date_i18n( apply_filters( 'mc_date_format', mc_date_format(), 'date_span_end' ), strtotime( $end ) );
		$return = $begin . ' <span>&ndash;</span> ' . $end;
	} else {
		$return = '<ul class="multidate">';
		foreach ( $dates as $date ) {
			$begin         = $date->occur_begin;
			$end           = $date->occur_end;
			$day_begin     = mc_date( 'Y-m-d', strtotime( $begin ), false );
			$day_end       = mc_date( 'Y-m-d', strtotime( $end ), false );
			$bformat       = '<span class="multidate-date">' . date_i18n( mc_date_format(), strtotime( $begin ) ) . "</span> <span class='multidate-time'>" . date_i18n( mc_time_format(), strtotime( $begin ) ) . '</span>';
			$endtimeformat = ( '00:00:00' === $date->occur_end ) ? '' : ' ' . mc_time_format();
			$eformat       = ( $day_begin !== $day_end ) ? mc_date_format() . $endtimeformat : $endtimeformat;
			$span          = ( '' !== $eformat ) ? " <span>&ndash;</span> <span class='multidate-end'>" : '';
			$endspan       = ( '' !== $eformat ) ? '</span>' : '';
			$return       .= "<li>$bformat" . $span . date_i18n( $eformat, strtotime( $end ) ) . "$endspan</li>";
		}
		$return .= '</ul>';
	}

	return $return;
}

add_filter( 'mc_insert_author_data', 'mc_author_data', 10, 2 );
/**
 * Include data about event author in event array.
 *
 * @param array  $e Array of event details.
 * @param object $event Event object.
 *
 * @return array $e
 */
function mc_author_data( $e, $event ) {
	if ( 0 !== (int) $event->event_author ) {
		$author = get_userdata( $event->event_author );
		$host   = get_userdata( $event->event_host );
		if ( $author ) {
			$e['author']       = $author->display_name;
			$e['gravatar']     = get_avatar( $author->user_email );
			$e['author_email'] = $author->user_email;
			$e['author_id']    = $event->event_author;
		}
		if ( $host ) {
			$e['host']          = ( '' === $host->display_name ) ? $author->display_name : $host->display_name;
			$e['host_id']       = $event->event_host;
			$e['host_email']    = ( '' === $host->user_email ) ? $author->user_email : $host->user_email;
			$e['host_gravatar'] = ( '' === $host->user_email ) ? $e['gravatar'] : get_avatar( $host->user_email );
		}
	} else {
		$e['author']        = 'Public Submitter';
		$e['host']          = 'Public Submitter';
		$e['host_email']    = '';
		$e['author_email']  = '';
		$e['gravatar']      = '';
		$e['host_gravatar'] = '';
		$e['author_id']     = false;
		$e['host_id']       = false;
	}

	return $e;
}

add_filter( 'mc_filter_shortcodes', 'mc_auto_excerpt', 10, 2 );
/**
 * Custom excerpt for use in templates.
 *
 * @param array  $e Array of event details.
 * @param object $event Event object.
 *
 * @return array $e
 */
function mc_auto_excerpt( $e, $event ) {
	$description = $e['description'];
	$shortdesc   = $e['shortdesc'];
	$excerpt     = '';
	if ( '' !== $description && '' === $shortdesc ) { // if description is empty, this won't work, so skip it.
		/**
		 * Length of My Calendar generated excerpts in words. Default 55.
		 *
		 * @hook mc_excerpt_length
		 *
		 * @param {int} $num_words Number of words to use.
		 *
		 * @return {int}
		 */
		$num_words = apply_filters( 'mc_excerpt_length', 55 );
		$excerpt   = wp_trim_words( $description, $num_words );
	} else {
		$excerpt = $shortdesc;
	}

	$e['search_excerpt'] = mc_search_highlight( $description, $shortdesc );
	$e['excerpt']        = $excerpt;
	$e['ical_excerpt']   = mc_newline_replace( strip_tags( $excerpt ) );

	return $e;
}

/**
 * Generate a string with highlighted search terms.
 *
 * @param string $string1 Default highlight text.
 * @param string $string2 Alternate text to use if first might be blank.
 * @param string $term Search term.
 *
 * @return string
 */
function mc_search_highlight( $string1, $string2 = '', $term = '' ) {
	$append = '';
	if ( '' !== $term ) {
		$append = ' ' . trim( $term );
	}
	if ( isset( $_REQUEST['mcs'] ) ) {
		$term = sanitize_text_field( trim( $_REQUEST['mcs'] ) ) . $append;
	} else {
		return $string1;
	}
	$terms = explode( ' ', $term );
	// If neither description nor short, return early.
	if ( '' === $string1 . $string2 ) {
		return '';
	}
	// If no full description, use short.
	if ( '' === $string1 ) {
		$use = $string2;
	} else {
		$use = $string1;
	}
	$use    = wp_strip_all_tags( $use );
	$length = strlen( $use );
	$start  = 0;
	if ( $length > 160 ) {
		foreach ( $terms as $t ) {
			$positions[] = stripos( $use, $t );
		}
		// Use the first term referenced for positioning.
		sort( $positions );
		$position = $positions[0];
		// Search term not found.
		if ( false === $position ) {
			return substr( $use, 0, 160 );
		}
		if ( 0 === $position ) {
			$start = 0;
		} else {
			$start = ( ( $position - 20 ) > 0 ) ? ( $position - 15 ) : 0;
		}
	}
	$extract  = substr( $use, $start, 160 );
	$ellipsis = '';
	if ( strlen( $extract ) < $length ) {
		$ellipsis = '...';
		// Remove first and last words, which are likely to be partial.
		$clean = explode( ' ', $extract );
		unset( $clean[0] );
		array_pop( $clean );
		$extract = implode( ' ', $clean );
	}

	foreach ( $terms as $t ) {
		$extract = mc_str_replace_word_i( $t, $extract );
	}

	$excerpt = $ellipsis . $extract . $ellipsis;

	return $excerpt;
}

/**
 * Search text and wrap search terms.
 *
 * @param string $needle Word to find.
 * @param string $haystack Source text.
 *
 * @return string
 */
function mc_str_replace_word_i( $needle, $haystack ) {
	$keyword  = $needle;
	$needle   = str_replace( '/', '\\/', preg_quote( $needle ) ); // allow '/' in keywords.
	$pattern  = "/\b$needle(?!([^<]+)?>)\b/i";
	$type     = 'all';
	$haystack = preg_replace_callback(
		$pattern,
		function( $m ) use ( $type, $keyword ) {
			return '<strong class="mc_search_term">' . $m[0] . '</strong>';
		},
		$haystack
	);

	return $haystack;
}

/**
 * Get template for a specific usage.
 *
 * @param string $template name of template.
 *
 * @return string Template HTML/tags
 */
function mc_get_template( $template ) {
	$templates = mc_get_option( 'templates' );
	$keys      = array( 'title', 'title_list', 'title_solo', 'link', 'mini', 'list', 'details', 'grid' );

	if ( ! in_array( $template, $keys, true ) ) {
		$template = '';
	} else {
		$template = ( isset( $templates[ $template ] ) ) ? $templates[ $template ] : '';
	}

	return trim( $template );
}

add_filter( 'mc_filter_image_data', 'mc_image_data', 10, 2 );
/**
 * Event image data.
 *
 * @param array  $e Array of event details.
 * @param object $event Event object.
 *
 * @return array $e
 */
function mc_image_data( $e, $event ) {
	/**
	 * Attributes added to My Calendar event images. Default `array( 'class' => 'mc-image' )`. See `get_the_post_thumbnail()` docs at WordPress.org.
	 *
	 * @hook mc_post_thumbnail_atts
	 *
	 * @param {array} $atts Array of image attributes.
	 *
	 * @return {array} Array of image attributes.
	 */
	$atts = apply_filters( 'mc_post_thumbnail_atts', array( 'class' => 'mc-image' ) );
	if ( isset( $event->event_post ) && is_numeric( $event->event_post ) && get_post_status( $event->event_post ) && has_post_thumbnail( $event->event_post ) ) {
		$e['full'] = get_the_post_thumbnail( $event->event_post );
		$sizes     = get_intermediate_image_sizes();
		$attach    = get_post_thumbnail_id( $event->event_post );
		foreach ( $sizes as $size ) {
			$src                 = wp_get_attachment_image_src( $attach, $size );
			$e[ $size ]          = get_the_post_thumbnail( $event->event_post, $size, $atts );
			$e[ $size . '_url' ] = $src[0];
		}
		if ( isset( $e['large'] ) && '' !== $e['large'] ) {
			$e['image_url'] = strip_tags( $e['large'] );
			$e['image']     = $e['large'];
		} else {
			/**
			 * Default image size used for event listings when 'large' image not available. Default 'thumbnail'.
			 *
			 * @hook mc_default_image_size
			 *
			 * @param {string} $size Default image size
			 *
			 * @return {string} Image size description key.
			 */
			$image_size     = apply_filters( 'mc_default_image_size', 'thumbnail' );
			$e['image_url'] = strip_tags( $e[ $image_size ] );
			$e['image']     = $e[ $image_size ];
		}
	} else {
		$sizes = get_intermediate_image_sizes();
		// create empty array values so that template tags will be removed even if post doesn't exist.
		foreach ( $sizes as $size ) {
			$e[ $size ]          = '';
			$e[ $size . '_url' ] = '';
		}
		$e['image_url'] = ( '' !== $event->event_image ) ? $event->event_image : '';
		$e['image']     = ( '' !== $event->event_image ) ? "<img src='$event->event_image' alt='' class='mc-image' />" : '';
	}

	return $e;
}

/**
 * Event recurrance string description.
 *
 * @param object $event Event Object.
 * @param string $begin Date event begins.
 *
 * @return string
 */
function mc_event_recur_string( $event, $begin ) {
	$recurs      = str_split( $event->event_recur, 1 );
	$recur       = $recurs[0];
	$every       = ( isset( $recurs[1] ) ) ? str_replace( $recurs[0], '', $event->event_recur ) : 1;
	$month_date  = mc_date( 'dS', strtotime( $begin ), false );
	$day_name    = date_i18n( 'l', strtotime( $begin ) );
	$week_number = mc_ordinal( mc_week_of_month( mc_date( 'j', strtotime( $begin ), false ) ) + 1 );
	switch ( $recur ) {
		case 'S':
			$event_recur = __( 'Does not recur', 'my-calendar' );
			break;
		case 'D':
			if ( 1 === (int) $every ) {
				$event_recur = __( 'Daily', 'my-calendar' );
			} else {
				// Translators: Number of days between recurrences.
				$event_recur = sprintf( __( 'Every %d days', 'my-calendar' ), $every );
			}
			break;
		case 'E':
			$event_recur = __( 'Daily, weekdays only', 'my-calendar' );
			break;
		case 'W':
			if ( 1 === (int) $every ) {
				$event_recur = __( 'Weekly', 'my-calendar' );
			} else {
				// Translators: Number of weeks between recurrences.
				$event_recur = sprintf( __( 'Every %d weeks', 'my-calendar' ), $every );
			}
			break;
		case 'B':
			$event_recur = __( 'Bi-weekly', 'my-calendar' );
			break;
		case 'M':
			if ( 1 === (int) $every ) {
				// Translators: The ordinal number of the month for the recurrence.
				$event_recur = sprintf( __( 'the %s of each month', 'my-calendar' ), $month_date );
			} else {
				// Translators: Ordinal number of each n months.
				$event_recur = sprintf( __( 'the %1$s of every %2$s months', 'my-calendar' ), $month_date, mc_ordinal( $every ) );
			}
			break;
		case 'U':
			// Translators: The {number} {day name} of each month.
			$event_recur = sprintf( __( 'the %1$s %2$s of each month', 'my-calendar' ), $week_number, $day_name );
			break;
		case 'Y':
			if ( 1 === (int) $every ) {
				$event_recur = __( 'Annually', 'my-calendar' );
			} else {
				// Translators: Number of years.
				$event_recur = sprintf( __( 'Every %d years', 'my-calendar' ), $every );
			}
			break;
		default:
			$event_recur = '';
	}

	/**
	 * Text representation of a recurring event pattern.
	 *
	 * @hook mc_event_recur_string
	 *
	 * @param {string} $event_recur Template HTML closing tag.
	 * @param {object} $event Event object.
	 *
	 * @return {string}
	 */
	return apply_filters( 'mc_event_recur_string', $event_recur, $event );
}

/**
 * Generate JSON/LD Schema for event.
 *
 * @param object $e Event object.
 * @param array  $tags Event tag array.
 *
 * @return array
 */
function mc_event_schema( $e, $tags = array() ) {
	$event   = ( empty( $tags ) ) ? mc_create_tags( $e ) : $tags;
	$wp_time = mc_ts( true );
	$wp_time = str_replace( array( ':30:00', ':00:00' ), array( ':30', ':00' ), $wp_time );
	$image   = ( $event['image_url'] ) ? $event['image_url'] : get_site_icon_url();
	$schema  = array(
		'@context'    => 'https://schema.org',
		'@type'       => 'Event',
		'name'        => $event['title'],
		'description' => $event['excerpt'],
		'image'       => $image,
		'url'         => $event['linking'],
		'startDate'   => $event['dtstart'] . $wp_time,
		'endDate'     => $event['dtend'] . $wp_time,
		'duration'    => $event['duration'],
	);
	if ( property_exists( $e, 'location' ) && is_object( $e->location ) ) {
		$location                      = $e->location;
		$loc                           = mc_location_schema( $location );
		$schema['eventAttendanceMode'] = 'https://schema.org/OfflineEventAttendanceMode';

	} else {
		// Location is a mandatory field for Google.
		$loc                           = array(
			'@type' => 'VirtualLocation',
			'url'   => $event['linking'],
		);
		$schema['eventAttendanceMode'] = 'https://schema.org/OnlineEventAttendanceMode';
	}
	$schema['location'] = $loc;
	/**
	 * Filter JSON/LD event schema data. https://schema.org/event.
	 *
	 * @hook mc_event_schema
	 *
	 * @param {array } $schema Schema data.
	 * @param {object} $e Event data.
	 * @param {array}  $event Event tag array.
	 *
	 * @return array
	 */
	return apply_filters( 'mc_event_schema', $schema, $e, $event );
}

/**
 * Generate JSON/LD Schema for location.
 *
 * @param object $location Location object.
 *
 * @return array
 */
function mc_location_schema( $location ) {
	$schema = array(
		'@context'    => 'https://schema.org',
		'@type'       => 'Place',
		'name'        => $location->location_label,
		'description' => '',
		'url'         => get_permalink( mc_get_location_post( $location->location_id ) ),
		'address'     => array(
			'@type'           => 'PostalAddress',
			'streetAddress'   => $location->location_street,
			'addressLocality' => $location->location_city,
			'addressRegion'   => $location->location_state,
			'postalCode'      => $location->location_postcode,
			'addressCountry'  => $location->location_country,
		),
		'telephone'   => ( $location->location_phone ) ? $location->location_phone : 'n/a',
		'sameAs'      => $location->location_url,
	);
	if ( ! empty( $location->location_latitude ) && 0 !== (int) $location->location_latitude ) {
		$schema['geo'] = array(
			'@type'     => 'GeoCoordinates',
			'latitude'  => $location->location_latitude,
			'longitude' => $location->location_longitude,
		);
	}
	/**
	 * Filter array used to generate location schema. See https://schema.org/location.
	 *
	 * @hook mc_location_schema
	 *
	 * @param {array}  $schema Schema data for an event venue.
	 * @param {object} $location My Calendar location object.
	 *
	 * @return array
	 */
	return apply_filters( 'mc_location_schema', $schema, $location );
}

/**
 * Get an author or host card for display on events.
 *
 * @param object $event Event object.
 * @param string $type Type of card.
 *
 * @return string
 */
function mc_template_user_card( $event, $type ) {
	/**
	 * Filter to enable or disable avatars.
	 *
	 * @hook mc_use_avatars
	 *
	 * @param {bool} $avatars false to disable avatars.
	 * @param {object} $event My Calendar event object.
	 *
	 * @return {bool}
	 */
	$avatars = apply_filters( 'mc_use_avatars', true, $event );
	$card    = '';
	$type    = ( 'author' === $type ) ? 'author' : 'host';
	$user    = ( 'author' === $type ) ? $event->event_author : $event->event_host;
	if ( 0 !== (int) $user && is_numeric( $user ) ) {
		$avatar = ( $avatars ) ? get_avatar( $user ) : '';
		$a      = get_userdata( $user );
		if ( $a ) {
			if ( 'author' === $type ) {
				$text = ( '' !== mc_get_option( 'posted_by' ) ) ? mc_get_option( 'posted_by' ) : __( 'Posted by', 'my-calendar' );
			} else {
				$text = ( '' !== mc_get_option( 'hosted_by' ) ) ? mc_get_option( 'hosted_by' ) : __( 'Hosted by', 'my-calendar' );
			}
			$card = $avatar . '<p class="event-' . $type . '"><span class="posted">' . $text . '</span> <span class="' . $type . '-name">' . $a->display_name . "</span></p>\n";
			if ( $avatars ) {
				$card = '	<div class="mc-' . $type . '-card">' . $card . '</div>';
			}
		}
	}

	return $card;
}

/**
 * Templating getter for new templating system.
 *
 * @param object $event Object containing event and view data.
 * @param string $key Array key for data to fetch.
 *
 * @return string
 */
function mc_get_template_tag( $event, $key ) {
	if ( ! empty( $event->tags ) ) {
		$data = $event->tags;
	} else {
		$data = mc_create_tags( $event->event );
	}
	$value = $data[ $key ];

	return $value;
}

/**
 * Print template values for new templating system.
 *
 * @param object $event Event.
 * @param string $key Array key for data to fetch.
 */
function mc_template_tag( $event, $key ) {
	echo mc_get_template_tag( $event, $key );
}