class-metabox.php 71.8 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 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905
<?php
/**
 * @package Admin
 *
 * This code generates the metabox on the edit post / page as well as contains all page analysis functionality.
 */

if ( ! defined( 'WPSEO_VERSION' ) ) {
	header( 'HTTP/1.0 403 Forbidden' );
	die;
}

/**
 * class WPSEO_Metabox
 *
 * The class that generates the metabox on the edit post / page as well as contains all page analysis functionality.
 */
class WPSEO_Metabox {

	/**
	 * @var int $meta_length Allowed length of the meta description.
	 */
	var $meta_length = 156;

	/**
	 * @var string $meta_length_reason Reason the meta description is not the default length.
	 */
	var $meta_length_reason = '';

	/**
	 * Class constructor
	 */
	function __construct() {
		if ( ! class_exists( 'Yoast_TextStatistics' ) && apply_filters( 'wpseo_use_page_analysis', true ) === true )
			require_once( WPSEO_PATH . 'admin/TextStatistics.php' );

		add_action( 'add_meta_boxes', array( $this, 'add_meta_box' ) );
		add_action( 'admin_print_styles-post-new.php', array( $this, 'enqueue' ) );
		add_action( 'admin_print_styles-post.php', array( $this, 'enqueue' ) );
		add_action( 'admin_print_styles-edit.php', array( $this, 'enqueue' ) );
		add_action( 'admin_head', array( $this, 'script' ) );
		add_action( 'wp_insert_post', array( $this, 'save_postdata' ) );
		add_action( 'edit_attachment', array( $this, 'save_postdata' ) );
		add_action( 'add_attachment', array( $this, 'save_postdata' ) );
		add_action( 'admin_init', array( $this, 'setup_page_analysis' ) );
	}

	/**
	 * Sets up all the functionality related to the prominence of the page analysis functionality.
	 */
	public function setup_page_analysis() {

		if ( apply_filters( 'wpseo_use_page_analysis', true ) === true ) {

			$options = get_wpseo_options();

			foreach ( get_post_types( array( 'public' => true ), 'names' ) as $pt ) {
				if ( isset( $options['hideeditbox-' . $pt] ) && $options['hideeditbox-' . $pt] )
					continue;
				add_filter( 'manage_' . $pt . '_posts_columns', array( $this, 'column_heading' ), 10, 1 );
				add_action( 'manage_' . $pt . '_posts_custom_column', array( $this, 'column_content' ), 10, 2 );
				add_action( 'manage_edit-' . $pt . '_sortable_columns', array( $this, 'column_sort' ), 10, 2 );
			}
			add_filter( 'request', array( $this, 'column_sort_orderby' ) );

			add_action( 'restrict_manage_posts', array( $this, 'posts_filter_dropdown' ) );
			add_action( 'post_submitbox_misc_actions', array( $this, 'publish_box' ) );
		}

	}

	/**
	 * Lowercase a sentence while preserving "weird" characters.
	 *
	 * This should work with Greek, Russian, Polish & French amongst other languages...
	 *
	 * @param string $string String to lowercase
	 *
	 * @return string
	 */
	public function strtolower_utf8( $string ) {
		$convert_to   = array(
			"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u",
			"v", "w", "x", "y", "z", "à", "á", "â", "ã", "ä", "å", "æ", "ç", "è", "é", "ê", "ë", "ì", "í", "î", "ï",
			"ð", "ñ", "ò", "ó", "ô", "õ", "ö", "ø", "ù", "ú", "û", "ü", "ý", "а", "б", "в", "г", "д", "е", "ё", "ж",
			"з", "и", "й", "к", "л", "м", "н", "о", "п", "р", "с", "т", "у", "ф", "х", "ц", "ч", "ш", "щ", "ъ", "ы",
			"ь", "э", "ю", "я", "ą", "ć", "ę", "ł", "ń", "ó", "ś", "ź", "ż"
		);
		$convert_from = array(
			"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U",
			"V", "W", "X", "Y", "Z", "À", "Á", "Â", "Ã", "Ä", "Å", "Æ", "Ç", "È", "É", "Ê", "Ë", "Ì", "Í", "Î", "Ï",
			"Ð", "Ñ", "Ò", "Ó", "Ô", "Õ", "Ö", "Ø", "Ù", "Ú", "Û", "Ü", "Ý", "А", "Б", "В", "Г", "Д", "Е", "Ё", "Ж",
			"З", "И", "Й", "К", "Л", "М", "Н", "О", "П", "Р", "С", "Т", "У", "Ф", "Х", "Ц", "Ч", "Ш", "Щ", "Ъ", "Ъ",
			"Ь", "Э", "Ю", "Я", "Ą", "Ć", "Ę", "Ł", "Ń", "Ó", "Ś", "Ź", "Ż"
		);

		return str_replace( $convert_from, $convert_to, $string );
	}

	/**
	 * Outputs the page analysis score in the Publish Box.
	 */
	public function publish_box() {
		echo '<div class="misc-pub-section misc-yoast misc-pub-section-last">';

		if ( (int) wpseo_get_value( 'meta-robots-noindex' ) === 1 ) {
			$score_label = 'noindex';
			$title       = __( 'Post is set to noindex.', 'wordpress-seo' );
		}
		else {
			$score = wpseo_get_value( 'linkdex' );
			if ( $score ) {
				$score = round( $score / 10 );
				if ( $score < 1 )
					$score = 1;
				$score_label = wpseo_translate_score( $score );
			}
			else {
				if ( isset( $_GET['post'] ) ) {
					$post_id = (int) $_GET['post'];
					$post    = get_post( $post_id );
				}
				else {
					global $post;
				}

				$this->calculate_results( $post );
				$score = wpseo_get_value( 'linkdex' );
				if ( ! $score || empty( $score ) ) {
					$score_label = 'na';
					$title       = __( 'No focus keyword set.', 'wordpress-seo' );
				}
				else {
					$score_label = wpseo_translate_score( $score );
				}
			}
		}
		if ( ! isset( $title ) )
			$title = wpseo_translate_score( $score, $css = false );

		$result = '<div title="' . esc_attr( $title ) . '" alt="' . esc_attr( $title ) . '" class="wpseo_score_img ' . $score_label . '"></div>';

		echo __( 'SEO: ', 'wordpress-seo' ) . $result . ' <a class="wpseo_tablink scroll" href="#wpseo_linkdex">' . __( 'Check', 'wordpress-seo' ) . '</a>';

		echo '</div>';
	}

	/**
	 * Adds the WordPress SEO meta box to the edit boxes in the post / page / cpt edit page.
	 */
	public function add_meta_box() {
		$options = get_wpseo_options();

		foreach ( get_post_types( array( 'public' => true ) ) as $posttype ) {
			if ( isset( $options['hideeditbox-' . $posttype] ) && $options['hideeditbox-' . $posttype] )
				continue;
			add_meta_box( 'wpseo_meta', __( 'WordPress SEO by Yoast', 'wordpress-seo' ), array( $this, 'meta_box' ), $posttype, 'normal', apply_filters( 'wpseo_metabox_prio', 'high' ) );
		}
	}

	/**
	 * Adds the WordPress SEO box
	 *
	 * @deprecated 1.4.23
	 * @deprecated use WPSEO_Metabox::add_meta_box()
	 * @see WPSEO_Metabox::add_meta_box()
	 */
	public function add_custom_box() {
		_deprecated_function( __FUNCTION__, 'WPSEO 1.5.0', 'WPSEO_Metabox::add_meta_box()' );
		$this->add_meta_box();
	}
	
	
	/**
	 * Outputs the scripts needed for the edit / post page overview, snippet preview, etc.
	 */
	public function script() {
		if ( isset( $_GET['post'] ) ) {
			$post_id = (int) $_GET['post'];
			$post    = get_post( $post_id );
		}
		else {
			global $post;
		}

		if ( ! isset( $post ) )
			return;

		$options = get_wpseo_options();

		$date = '';
		if ( isset( $options['showdate-' . $post->post_type] ) && $options['showdate-' . $post->post_type] ) {
			$date = $this->get_post_date( $post );

			$this->meta_length        = $this->meta_length - ( strlen( $date ) + 5 );
			$this->meta_length_reason = __( ' (because of date display)', 'wordpress-seo' );
		}

		$this->meta_length_reason = apply_filters( 'wpseo_metadesc_length_reason', $this->meta_length_reason, $post );
		$this->meta_length        = apply_filters( 'wpseo_metadesc_length', $this->meta_length, $post );

		unset( $date );

		$title_template = '';
		if ( isset( $options['title-' . $post->post_type] ) )
			$title_template = $options['title-' . $post->post_type];

		// If there's no title template set, use the default, otherwise title preview won't work.
		if ( $title_template == '' )
			$title_template = '%%title%% - %%sitename%%';
		$title_template = wpseo_replace_vars( $title_template, $post, array( '%%title%%' ) );

		$metadesc_template = '';
		if ( isset( $options['metadesc-' . $post->post_type] ) )
			$metadesc_template = wpseo_replace_vars( $options['metadesc-' . $post->post_type], $post, array( '%%excerpt%%', '%%excerpt_only%%' ) );

		$sample_permalink = get_sample_permalink( $post->ID );
		$sample_permalink = str_replace( '%page', '%post', $sample_permalink[0] );
		?>
		<script type="text/javascript">
			var wpseo_lang = '<?php echo substr( get_locale(), 0, 2 ); ?>';
			var wpseo_meta_desc_length = '<?php echo $this->meta_length; ?>';
			var wpseo_title_template = '<?php echo esc_attr( $title_template ); ?>';
			var wpseo_metadesc_template = '<?php echo esc_attr( $metadesc_template ); ?>';
			var wpseo_permalink_template = '<?php echo esc_url( $sample_permalink ); ?>';
			var wpseo_keyword_suggest_nonce = '<?php echo wp_create_nonce( 'wpseo-get-suggest' ); ?>';
		</script>
	<?php
	}


	/**
	 * Output a tab in the WP SEO Metabox
	 *
	 * @param string $id      CSS ID of the tab.
	 * @param string $heading Heading for the tab.
	 * @param string $content Content of the tab. This content should be escaped.
	 */
	public function do_tab( $id, $heading, $content ) {
		?>
		<div class="wpseotab <?php echo esc_attr( $id ) ?>">
			<h4 class="wpseo-heading"><?php echo esc_html( $heading ); ?></h4>
			<table class="form-table">
				<?php echo $content ?>
			</table>
		</div>
	<?php
	}

	/**
	 * Retrieve the meta boxes for the given post type.
	 *
	 * @param string $post_type
	 *
	 * @return array
	 */
	public function get_meta_boxes( $post_type = 'post' ) {
		$options = get_wpseo_options();

		$mbs                   = array();
		$mbs['snippetpreview'] = array(
			"name"  => "snippetpreview",
			"type"  => "snippetpreview",
			"title" => __( "Snippet Preview", 'wordpress-seo' ),
		);
		$mbs['focuskw']        = array(
			"name"         => "focuskw",
			"std"          => "",
			"type"         => "text",
			"title"        => __( 'Focus Keyword', 'wordpress-seo' ),
			"autocomplete" => "off",
			"help"         => sprintf( __( "Pick the main keyword or keyphrase that this post/page is about.<br/><br/>Read %sthis post%s for more info.", 'wordpress-seo' ), "<a href='http://yoast.com/focus-keyword/#utm_source=wordpress-seo-metabox&utm_medium=inline-help&utm_campaign=focus-keyword'>", '</a>' ),
			"description"  => "<div id='focuskwresults'></div>",
		);
		$mbs['title']          = array(
			"name"        => "title",
			"std"         => "",
			"type"        => "text",
			"title"       => __( "SEO Title", 'wordpress-seo' ),
			"description" => sprintf( __( "Title display in search engines is limited to 70 chars, %s chars left.", 'wordpress-seo' ), "<span id='yoast_wpseo_title-length'></span>" ),
			"help"        => __( "The SEO Title defaults to what is generated based on this sites title template for this posttype.", 'wordpress-seo' )
		);
		$mbs['metadesc']       = array(
			"name"        => "metadesc",
			"std"         => "",
			"class"       => "metadesc",
			"type"        => "textarea",
			"title"       => __( "Meta Description", 'wordpress-seo' ),
			"rows"        => 2,
			"richedit"    => false,
			"description" => sprintf( __( "The <code>meta</code> description will be limited to %s chars%s, %s chars left.", 'wordpress-seo' ), $this->meta_length, $this->meta_length_reason, "<span id='yoast_wpseo_metadesc-length'></span>" ) . " <div id='yoast_wpseo_metadesc_notice'></div>",
			"help"        => __( "If the meta description is empty, the snippet preview above shows what is generated based on this sites meta description template.", 'wordpress-seo' ),
		);
		if ( isset( $options['usemetakeywords'] ) && $options['usemetakeywords'] ) {
			$mbs['metakeywords'] = array(
				"name"        => "metakeywords",
				"std"         => "",
				"class"       => "metakeywords",
				"type"        => "text",
				"title"       => __( "Meta Keywords", 'wordpress-seo' ),
				"description" => sprintf( __( "If you type something above it will override your %smeta keywords template%s.", 'wordpress-seo' ), "<a target='_blank' href='" . admin_url( 'admin.php?page=wpseo_titles#' . esc_url( $post_type ) ) . "'>", "</a>" )
			);
		}

		// Apply filters before entering the advanced section
		$mbs = apply_filters( 'wpseo_metabox_entries', $mbs );

		return $mbs;
	}

	/**
	 * Retrieve the meta boxes for the advanced tab.
	 *
	 * @return array
	 */
	function get_advanced_meta_boxes() {
		global $post;

		$post_type = '';
		if ( isset( $post->post_type ) )
			$post_type = $post->post_type;
		else if ( ! isset( $post->post_type ) && isset( $_GET['post_type'] ) )
			$post_type = $_GET['post_type'];

		$options = get_wpseo_options();

		$mbs = array();

		$mbs['meta-robots-noindex']  = array(
			"name"    => "meta-robots-noindex",
			"std"     => "-",
			"title"   => __( "Meta Robots Index", 'wordpress-seo' ),
			"type"    => "select",
			"options" => array(
				"0" => sprintf( __( "Default for post type, currently: %s", 'wordpress-seo' ), ( isset( $options['noindex-' . $post_type] ) && $options['noindex-' . $post_type] ) ? 'noindex' : 'index' ),
				"2" => __( "index", 'wordpress-seo' ),
				"1" => __( "noindex", 'wordpress-seo' ),
			),
		);
		$mbs['meta-robots-nofollow'] = array(
			"name"    => "meta-robots-nofollow",
			"std"     => "follow",
			"title"   => __( "Meta Robots Follow", 'wordpress-seo' ),
			"type"    => "radio",
			"options" => array(
				"0" => __( "Follow", 'wordpress-seo' ),
				"1" => __( "Nofollow", 'wordpress-seo' ),
			),
		);
		$mbs['meta-robots-adv']      = array(
			"name"        => "meta-robots-adv",
			"std"         => "none",
			"type"        => "multiselect",
			"title"       => __( "Meta Robots Advanced", 'wordpress-seo' ),
			"description" => __( "Advanced <code>meta</code> robots settings for this page.", 'wordpress-seo' ),
			"options"     => array(
				"noodp"     => __( "NO ODP", 'wordpress-seo' ),
				"noydir"    => __( "NO YDIR", 'wordpress-seo' ),
				"noarchive" => __( "No Archive", 'wordpress-seo' ),
				"nosnippet" => __( "No Snippet", 'wordpress-seo' ),
			),
		);
		if ( isset( $options['breadcrumbs-enable'] ) && $options['breadcrumbs-enable'] ) {
			$mbs['bctitle'] = array(
				"name"        => "bctitle",
				"std"         => "",
				"type"        => "text",
				"title"       => __( "Breadcrumbs title", 'wordpress-seo' ),
				"description" => __( "Title to use for this page in breadcrumb paths", 'wordpress-seo' ),
			);
		}
		if ( isset( $options['enablexmlsitemap'] ) && $options['enablexmlsitemap'] ) {
			$mbs['sitemap-include'] = array(
				"name"        => "sitemap-include",
				"std"         => "-",
				"type"        => "select",
				"title"       => __( "Include in Sitemap", 'wordpress-seo' ),
				"description" => __( "Should this page be in the XML Sitemap at all times, regardless of Robots Meta settings?", 'wordpress-seo' ),
				"options"     => array(
					"-"      => __( "Auto detect", 'wordpress-seo' ),
					"always" => __( "Always include", 'wordpress-seo' ),
					"never"  => __( "Never include", 'wordpress-seo' ),
				),
			);
			$mbs['sitemap-prio']    = array(
				"name"        => "sitemap-prio",
				"std"         => "-",
				"type"        => "select",
				"title"       => __( "Sitemap Priority", 'wordpress-seo' ),
				"description" => __( "The priority given to this page in the XML sitemap.", 'wordpress-seo' ),
				"options"     => array(
					"-"   => __( "Automatic prioritization", 'wordpress-seo' ),
					"1"   => __( "1 - Highest priority", 'wordpress-seo' ),
					"0.9" => "0.9",
					"0.8" => "0.8 - " . __( "Default for first tier pages", 'wordpress-seo' ),
					"0.7" => "0.7",
					"0.6" => "0.6 - " . __( "Default for second tier pages and posts", 'wordpress-seo' ),
					"0.5" => "0.5 - " . __( "Medium priority", 'wordpress-seo' ),
					"0.4" => "0.4",
					"0.3" => "0.3",
					"0.2" => "0.2",
					"0.1" => "0.1 - " . __( "Lowest priority", 'wordpress-seo' ),
				),
			);
		}
		$mbs['sitemap-html-include'] = array(
			"name"        => "sitemap-html-include",
			"std"         => "-",
			"type"        => "select",
			"title"       => __( "Include in HTML Sitemap", 'wordpress-seo' ),
			"description" => __( "Should this page be in the HTML Sitemap at all times, regardless of Robots Meta settings?", 'wordpress-seo' ),
			"options"     => array(
				"-"      => __( "Auto detect", 'wordpress-seo' ),
				"always" => __( "Always include", 'wordpress-seo' ),
				"never"  => __( "Never include", 'wordpress-seo' ),
			),
		);
		$mbs['canonical']            = array(
			"name"        => "canonical",
			"std"         => "",
			"type"        => "text",
			"title"       => __( "Canonical URL", 'wordpress-seo' ),
			"description" => sprintf( __( "The canonical URL that this page should point to, leave empty to default to permalink. %sCross domain canonical%s supported too.", 'wordpress-seo' ), "<a target='_blank' href='http://googlewebmastercentral.blogspot.com/2009/12/handling-legitimate-cross-domain.html'>", "</a>" )
		);
		$mbs['redirect']             = array(
			"name"        => "redirect",
			"std"         => "",
			"type"        => "text",
			"title"       => __( "301 Redirect", 'wordpress-seo' ),
			"description" => __( "The URL that this page should redirect to.", 'wordpress-seo' )
		);

		// Apply filters for in advanced section
		$mbs = apply_filters( 'wpseo_metabox_entries_advanced', $mbs );

		return $mbs;
	}

	/**
	 * Output the meta box
	 */
	function meta_box() {
		if ( isset( $_GET['post'] ) ) {
			$post_id = (int) $_GET['post'];
			$post    = get_post( $post_id );
		}
		else {
			global $post;
		}

		$options = get_wpseo_options();

		?>
		<div class="wpseo-metabox-tabs-div">
		<ul class="wpseo-metabox-tabs" id="wpseo-metabox-tabs">
			<li class="general"><a class="wpseo_tablink"
														 href="#wpseo_general"><?php _e( "General", 'wordpress-seo' ); ?></a></li>
			<li id="linkdex" class="linkdex"><a class="wpseo_tablink"
																					href="#wpseo_linkdex"><?php _e( "Page Analysis", 'wordpress-seo' ); ?></a>
			</li>
			<?php if ( current_user_can( 'manage_options' ) || ! isset( $options['disableadvanced_meta'] ) || ! $options['disableadvanced_meta'] ): ?>
				<li class="advanced"><a class="wpseo_tablink"
																href="#wpseo_advanced"><?php _e( "Advanced", 'wordpress-seo' ); ?></a></li>
			<?php endif; ?>
			<?php do_action( 'wpseo_tab_header' ); ?>
		</ul>
		<?php
		$content = '';
		foreach ( $this->get_meta_boxes( $post->post_type ) as $meta_box ) {
			$content .= $this->do_meta_box( $meta_box );
		}
		$this->do_tab( 'general', __( 'General', 'wordpress-seo' ), $content );

		$this->do_tab( 'linkdex', __( 'Page Analysis', 'wordpress-seo' ), $this->linkdex_output( $post ) );

		if ( current_user_can( 'manage_options' ) || ! isset( $options['disableadvanced_meta'] ) || ! $options['disableadvanced_meta'] ) {
			$content = '';
			foreach ( $this->get_advanced_meta_boxes() as $meta_box ) {
				$content .= $this->do_meta_box( $meta_box );
			}
			$this->do_tab( 'advanced', __( 'Advanced', 'wordpress-seo' ), $content );
		}

		do_action( 'wpseo_tab_content' );

		echo '</div>';
	}

	/**
	 * Adds a line in the meta box
	 *
	 * @param array $meta_box Contains the vars based on which output is generated.
	 *
	 * @return string
	 */
	function do_meta_box( $meta_box ) {
		$content        = '';
		$meta_box_value = '';

		if ( ! isset( $meta_box['name'] ) ) {
			$meta_box['name'] = '';
		}
		else {
			if ( wpseo_get_value( $meta_box['name'] ) !== false ) {
				$meta_box_value = wpseo_get_value( $meta_box['name'] );
			}
			else if ( isset( $meta_box['std'] ) ) {
				$meta_box_value = $meta_box['std'];
			}
			$meta_box['name'] = esc_attr( $meta_box['name'] );
		}

		$class = '';
		if ( ! empty( $meta_box['class'] ) )
			$class = ' ' . $meta_box['class'];

		$placeholder = '';
		if ( isset( $meta_box['placeholder'] ) && ! empty( $meta_box['placeholder'] ) )
			$placeholder = $meta_box['placeholder'];

		$help = '';
		if ( isset( $meta_box['help'] ) && $meta_box['help'] )
			$help = '<img src="' . plugins_url( 'images/question-mark.png', dirname( __FILE__ ) ) . '" class="alignright yoast_help" id="' . $meta_box['name'] . 'help" alt="' . esc_attr( $meta_box['help'] ) . '" />';

		$content .= '<tr>';
		$content .= '<th scope="row"><label for="yoast_wpseo_' . $meta_box['name'] . '">' . $meta_box['title'] . ':</label>' . $help . '</th>';
		$content .= '<td>';

		switch ( $meta_box['type'] ) {
			case "snippetpreview":
				$content .= $this->snippet();
				break;
			case "text":
				$ac = '';
				if ( isset( $meta_box['autocomplete'] ) && $meta_box['autocomplete'] == 'off' )
					$ac = 'autocomplete="off" ';
				$content .= '<input type="text" placeholder="' . esc_attr( $placeholder ) . '" id="yoast_wpseo_' . $meta_box['name'] . '" ' . $ac . 'name="yoast_wpseo_' . $meta_box['name'] . '" value="' . esc_attr( $meta_box_value ) . '" class="large-text"/><br />';
				break;
			case "textarea":
				$content .= '<textarea class="large-text" rows="3" id="yoast_wpseo_' . $meta_box['name'] . '" name="yoast_wpseo_' . $meta_box['name'] . '">' . esc_textarea( $meta_box_value ) . '</textarea>';
				break;
			case "select":
				$content .= '<select name="yoast_wpseo_' . $meta_box['name'] . '" id="yoast_wpseo_' . $meta_box['name'] . '" class="yoast' . $class . '">';
				foreach ( $meta_box['options'] as $val => $option ) {
					$selected = '';
					if ( $meta_box_value == $val )
						$selected = 'selected="selected"';
					$content .= '<option ' . $selected . ' value="' . esc_attr( $val ) . '">' . esc_html( $option ) . '</option>';
				}
				$content .= '</select>';
				break;
			case "multiselect":
				$selectedarr         = explode( ',', $meta_box_value );
				$meta_box['options'] = array( 'none' => 'None' ) + $meta_box['options'];
				$content .= '<select multiple="multiple" size="' . count( $meta_box['options'] ) . '" style="height: ' . ( count( $meta_box['options'] ) * 16 ) . 'px;" name="yoast_wpseo_' . $meta_box['name'] . '[]" id="yoast_wpseo_' . $meta_box['name'] . '" class="yoast' . $class . '">';
				foreach ( $meta_box['options'] as $val => $option ) {
					$selected = '';
					if ( in_array( $val, $selectedarr ) )
						$selected = 'selected="selected"';
					$content .= '<option ' . $selected . ' value="' . esc_attr( $val ) . '">' . esc_html( $option ) . '</option>';
				}
				$content .= '</select>';
				break;
			case "checkbox":
				$checked = '';
				if ( $meta_box_value == 'on' || $meta_box_value == true )
					$checked = 'checked="checked"';
				$expl = ( isset( $meta_box['expl'] ) ) ? esc_html( $meta_box['expl'] ) : '';
				$content .= '<input type="checkbox" id="yoast_wpseo_' . $meta_box['name'] . '" name="yoast_wpseo_' . $meta_box['name'] . '" ' . $checked . ' class="yoast' . $class . '"/> ' . $expl . '<br />';
				break;
			case "radio":
				if ( $meta_box_value == '' )
					$meta_box_value = $meta_box['std'];
				foreach ( $meta_box['options'] as $val => $option ) {
					$selected = '';
					if ( $meta_box_value == $val )
						$selected = 'checked="checked"';
					$content .= '<input type="radio" ' . $selected . ' id="yoast_wpseo_' . $meta_box['name'] . '_' . esc_attr( $val ) . '" name="yoast_wpseo_' . $meta_box['name'] . '" value="' . esc_attr( $val ) . '"/> <label for="yoast_wpseo_' . $meta_box['name'] . '_' . $val . '">' . $option . '</label> ';
				}
				break;
			case "upload":
				if ( $meta_box_value == '' )
					$meta_box_value = $meta_box['std'];
				$content .= '<label for="upload_image">';
				$content .= '<input id="yoast_wpseo_'.$meta_box['name'].'" type="text" size="36" name="yoast_wpseo_'.$meta_box['name'].'" value="' . $meta_box_value . '" />';
				$content .= '<input id="yoast_wpseo_'.$meta_box['name'].'_button" class="wpseo_image_upload_button button" type="button" value="Upload Image" />';
				$content .= '</label>';
				break;
			case "divtext":
				$content .= '<p>' . $meta_box['description'] . '</p>';
		}

		if ( isset( $meta_box['description'] ) )
			$content .= '<p>' . $meta_box['description'] . '</p>';

		$content .= '</td>';
		$content .= '</tr>';

		return $content;
	}

	/**
	 * Retrieve a post date when post is published, or return current date when it's not.
	 *
	 * @param object $post Post to retrieve the date for.
	 *
	 * @return string
	 */
	function get_post_date( $post ) {
		if ( isset( $post->post_date ) && $post->post_status == 'publish' )
			$date = date( 'j M Y', strtotime( $post->post_date ) );
		else
			$date = date( 'j M Y' );
		return $date;
	}

	/**
	 * Generate a snippet preview.
	 *
	 * @return string
	 */
	function snippet() {
		if ( isset( $_GET['post'] ) ) {
			$post_id = (int) $_GET['post'];
			$post    = get_post( $post_id );
		}
		else {
			global $post;
		}

		$options = get_wpseo_options();

		$date = '';
		if ( isset( $options['showdate-' . $post->post_type] ) && $options['showdate-' . $post->post_type] )
			$date = $this->get_post_date( $post );

		$title = wpseo_get_value( 'title' );
		$desc  = wpseo_get_value( 'metadesc' );

		$slug = $post->post_name;
		if ( empty( $slug ) )
			$slug = sanitize_title( $title );

		if ( ! empty( $date ) )
			$datestr = '<span style="color: #666;">' . $date . '</span> – ';
		else
			$datestr = '';
		$content = '<div id="wpseosnippet">
			<a class="title" href="#">' . esc_html( $title ) . '</a><br/>';

//		if ( isset( $options['breadcrumbs-enable'] ) && $options['breadcrumbs-enable'] == 'on' ) {
//			require_once( WPSEO_PATH . 'frontend/class-breadcrumbs.php' );
//			$content .= '<span href="#" style="font-size: 13px; color: #282; line-height: 15px;" class="breadcrumb">' . yoast_breadcrumb('','',false) . '</span>';
//		} else {
		$content .= '<a href="#" style="font-size: 13px; color: #282; line-height: 15px;" class="url">' . str_replace( 'http://', '', get_bloginfo( 'url' ) ) . '/' . esc_html( $slug ) . '/</a>';
//		}
//		if ( $gplus = $this->get_gplus_data( $post->post_author ) ) {
//			//		$content .= '<a href="https://profiles.google.com/' . $gplus->id . '" style="text-decoration:none;line-height:15px;font-size:13px;font-family:arial,sans-serif">';
//			$content .= '<div style="margin-top: 5px; position: relative;"><img style="float: left; margin-right:8px;" src="' . str_replace( 'sz=50', 'sz=44', $gplus->image->url ) . '"/>';
//			$content .= '<p class="desc" style="width: 460px; float: left; font-size: 13px; color: #000; line-height: 15px;">';
//			$content .= '<span style="color: #666;">by ' . $gplus->displayName . ' - in 12,345 circles - More by ' . $gplus->displayName . '</span><br/>';
//			$content .= $datestr . '<span class="content">' . $desc . '</span></p>';
//			$content .= '<div style="clear:both;"></div>';
////		$content .= '<div class="f" style="display:inline;margin-top:-10px;padding:2px 0;color:#666;font-size:13px">by ' . $gplus->displayName . ' - More by ' . $gplus->displayName . '</div></a>';
////		$content .= '</div>';
//
////		echo '<pre>'.print_r($gplus,1).'</pre>';
//
//		} else {
		$content .= '<p class="desc" style="font-size: 13px; color: #000; line-height: 15px;">' . $datestr . '<span class="content">' . esc_html( $desc ) . '</span></p>';
//		}
		$content .= '</div>';

//		$content .= '<pre>' . print_r( $gplus, 1 ) . '</pre>';

		$content = apply_filters( 'wpseo_snippet', $content, $post, compact( 'title', 'desc', 'date', 'slug' ) );

		return $content;
	}

	/**
	 * Grab a users G+ data
	 *
	 * @since 1.2.9
	 *
	 * @param int $user_id The ID of the user to retrieve the data for.
	 *
	 * @return object $gplus An object with the users Google+ data.
	 */
	function get_gplus_data( $user_id ) {
		if ( $gplus = get_transient( 'gplus_' . $user_id ) )
			return $gplus;

		$gplus_profile = get_the_author_meta( 'googleplus', $user_id );

		if ( empty( $gplus_profile ) )
			return false;
		if ( preg_match( '`u/0/([^/]+)/`', $gplus_profile, $match ) )
			$gplus_id = $match[1];
		else if ( preg_match( '`\.com/(\d+)`', $gplus_profile, $match ) )
			$gplus_id = $match[1];
		else
			return false;

		$args = array(
			'headers' => array(
				'Referer' => 'http://yoast.com/wp-admin/',
			),
		);

		$resp = wp_remote_get( 'https://www.googleapis.com/plus/v1/people/' . $gplus_id . '?key=AIzaSyBLYmCW10gzW63ob8NYIPTneph1arsxqWs', $args );
		if ( ! is_wp_error( $resp ) ) {
			$gplus = json_decode( $resp['body'] );

			set_transient( 'gplus_' . $user_id, $gplus, ( 7 * 24 * 60 * 60 ) );

			return $gplus;
		}
		else {
			return false;
		}

	}

	/**
	 * Save the WP SEO metadata for posts.
	 *
	 * @param int $post_id
	 *
	 * @return mixed
	 */
	function save_postdata( $post_id ) {

		if ( $post_id == null )
			return false;

		if ( wp_is_post_revision( $post_id ) )
			$post_id = wp_is_post_revision( $post_id );

		clean_post_cache( $post_id );
		$post = get_post( $post_id );

		$metaboxes = array_merge( $this->get_meta_boxes( $post->post_type ), $this->get_advanced_meta_boxes() );

		$metaboxes = apply_filters( 'wpseo_save_metaboxes', $metaboxes );

		foreach ( $metaboxes as $meta_box ) {
			if ( ! isset( $meta_box['name'] ) )
				continue;

			if ( 'checkbox' == $meta_box['type'] ) {
				if ( isset( $_POST['yoast_wpseo_' . $meta_box['name']] ) )
					$data = 'on';
				else
					$data = 'off';
			}
			else if ( 'multiselect' == $meta_box['type'] ) {
				if ( isset( $_POST['yoast_wpseo_' . $meta_box['name']] ) ) {
					if ( is_array( $_POST['yoast_wpseo_' . $meta_box['name']] ) )
						$data = implode( ",", $_POST['yoast_wpseo_' . $meta_box['name']] );
					else
						$data = $_POST['yoast_wpseo_' . $meta_box['name']];
				}
				else {
					continue;
				}
			}
			else {
				if ( isset( $_POST['yoast_wpseo_' . $meta_box['name']] ) )
					$data = $_POST['yoast_wpseo_' . $meta_box['name']];
				else
					continue;
			}

			// Prevent saving "empty" values.
			if ( ! in_array( $data, array( '', '0', 'none', '-', 'index,follow' ) ) ) {
				wpseo_set_value( $meta_box['name'], sanitize_text_field( $data ), $post_id );
			} else if ( $data == '' ) {
				// If we don't do this, we prevent people from reverting to the default title or description.
				delete_post_meta( $post_id, '_yoast_wpseo_' . $meta_box['name'] );
			}
		}

		$this->calculate_results( $post );

		do_action( 'wpseo_saved_postdata' );
	}

	/**
	 * Enqueues all the needed JS and CSS.
	 * @todo create css/metabox-mp6.css file and add it to the below allowed colors array when done
	 */
	public function enqueue() {
		$color = get_user_meta( get_current_user_id(), 'admin_color', true );
		if ( '' == $color || in_array( $color, array( 'classic', 'fresh' ), true ) === false )
			$color = 'fresh';

		global $pagenow;
		if ( $pagenow == 'edit.php' ) {
			wp_enqueue_style( 'edit-page', plugins_url( 'css/edit-page.css', dirname( __FILE__ ) ), array(), WPSEO_VERSION );
		}
		else {
			wp_enqueue_style( 'metabox-tabs', plugins_url( 'css/metabox-tabs.css', dirname( __FILE__ ) ), array(), WPSEO_VERSION );
			wp_enqueue_style( "metabox-$color", plugins_url( 'css/metabox-' . esc_attr( $color ) . '.css', dirname( __FILE__ ) ), array(), WPSEO_VERSION );

			wp_enqueue_script( 'jquery-ui-autocomplete' );

			wp_enqueue_script( 'jquery-qtip', plugins_url( 'js/jquery.qtip.min.js', dirname( __FILE__ ) ), array( 'jquery' ), '1.0.0-RC3', true );
			wp_enqueue_script( 'wp-seo-metabox', plugins_url( 'js/wp-seo-metabox.js', dirname( __FILE__ ) ), array( 'jquery', 'jquery-ui-core', 'jquery-ui-autocomplete' ), WPSEO_VERSION, true );

			// Text strings to pass to metabox for keyword analysis
			wp_localize_script( 'wp-seo-metabox', 'wpseoMetaboxL10n', array(
				'keyword_header'        => __( 'Your focus keyword was found in:', 'wordpress-seo' ),
				'article_header_text'   => __( 'Article Heading: ', 'wordpress-seo' ),
				'page_title_text'       => __( 'Page title: ', 'wordpress-seo' ),
				'page_url_text'         => __( 'Page URL: ', 'wordpress-seo' ),
				'content_text'          => __( 'Content: ', 'wordpress-seo' ),
				'meta_description_text' => __( 'Meta description: ', 'wordpress-seo' ),
				'choose_image'          => __( 'Use Image', 'wordpress-seo' )
			) );
		}
	}

	/**
	 * Adds a dropdown that allows filtering on the posts SEO Quality.
	 *
	 * @return bool
	 */
	function posts_filter_dropdown() {
		global $pagenow;
		if ( $pagenow == 'upload.php' )
			return false;

		echo '<select name="seo_filter">';
		echo '<option value="">' . __( "All SEO Scores", 'wordpress-seo' ) . '</option>';
		foreach ( array(
								'na'      => __( 'SEO: No Focus Keyword', 'wordpress-seo' ),
								'bad'     => __( 'SEO: Bad', 'wordpress-seo' ),
								'poor'    => __( 'SEO: Poor', 'wordpress-seo' ),
								'ok'      => __( 'SEO: OK', 'wordpress-seo' ),
								'good'    => __( 'SEO: Good', 'wordpress-seo' ),
								'noindex' => __( 'SEO: Post Noindexed', 'wordpress-seo' )
							) as $val => $text ) {
			$sel = '';
			if ( isset( $_GET['seo_filter'] ) && $_GET['seo_filter'] == $val )
				$sel = 'selected ';
			echo '<option ' . $sel . 'value="' . $val . '">' . $text . '</option>';
		}
		echo '</select>';
	}

	/**
	 * Adds the column headings for the SEO plugin for edit posts / pages overview
	 *
	 * @param array $columns Already existing columns.
	 *
	 * @return array
	 */
	function column_heading( $columns ) {
		return array_merge( $columns, array( 'wpseo-score' => __( 'SEO', 'wordpress-seo' ), 'wpseo-title' => __( 'SEO Title', 'wordpress-seo' ), 'wpseo-metadesc' => __( 'Meta Desc.', 'wordpress-seo' ), 'wpseo-focuskw' => __( 'Focus KW', 'wordpress-seo' ) ) );
	}

	/**
	 * Display the column content for the given column
	 *
	 * @param string $column_name Column to display the content for.
	 * @param int    $post_id     Post to display the column content for.
	 */
	function column_content( $column_name, $post_id ) {
		if ( $column_name == 'wpseo-score' ) {
			if ( (int) wpseo_get_value( 'meta-robots-noindex', $post_id ) === 1 ) {
				$score_label = 'noindex';
				$title       = __( 'Post is set to noindex.', 'wordpress-seo' );
				wpseo_set_value( 'linkdex', 0, $post_id );
			}
			else if ( $score = wpseo_get_value( 'linkdex', $post_id ) ) {
				$score_label = wpseo_translate_score( round( $score / 10 ) );
				$title       = wpseo_translate_score( round( $score / 10 ), $css = false );
			}
			else {
				$this->calculate_results( get_post( $post_id ) );
				$score = wpseo_get_value( 'linkdex', $post_id );
				if ( ! $score || empty( $score ) ) {
					$score_label = 'na';
					$title       = __( 'Focus keyword not set.', 'wordpress-seo' );
				}
				else {
					$score_label = wpseo_translate_score( $score );
					$title       = wpseo_translate_score( $score, $css = false );
				}
			}

			echo '<div title="' . esc_attr( $title ) . '" alt="' . esc_attr( $title ) . '" class="wpseo_score_img ' . esc_attr( $score_label ) . '"></div>';
		}
		if ( $column_name == 'wpseo-title' ) {
			echo esc_html( apply_filters( 'wpseo_title', $this->page_title( $post_id ) ) );
		}
		if ( $column_name == 'wpseo-metadesc' ) {
			echo esc_html( apply_filters( 'wpseo_metadesc', wpseo_get_value( 'metadesc', $post_id ) ) );
		}
		if ( $column_name == 'wpseo-focuskw' ) {
			$focuskw = wpseo_get_value( 'focuskw', $post_id );
			echo esc_html( $focuskw );
		}
	}

	/**
	 * Indicate which of the SEO columns are sortable.
	 *
	 * @param array $columns appended with their orderby variable.
	 *
	 * @return array
	 */
	function column_sort( $columns ) {
		$columns['wpseo-score']    = 'wpseo-score';
		$columns['wpseo-metadesc'] = 'wpseo-metadesc';
		$columns['wpseo-focuskw']  = 'wpseo-focuskw';
		return $columns;
	}

	/**
	 * Modify the query based on the seo_filter variable in $_GET
	 *
	 * @param array $vars Query variables.
	 *
	 * @return array
	 */
	function column_sort_orderby( $vars ) {
		if ( isset( $_GET['seo_filter'] ) ) {
			$noindex = false;
			$high    = false;
			switch ( $_GET['seo_filter'] ) {
				case 'noindex':
					$low     = false;
					$noindex = true;
					break;
				case 'na':
					$low  = 0;
					$high = 0;
					break;
				case 'bad':
					$low  = 1;
					$high = 34;
					break;
				case 'poor':
					$low  = 35;
					$high = 54;
					break;
				case 'ok':
					$low  = 55;
					$high = 74;
					break;
				case 'good':
					$low  = 75;
					$high = 100;
					break;
				default:
					$low     = false;
					$high    = false;
					$noindex = false;
					break;
			}
			if ( $low !== false ) {
				$vars = array_merge(
					$vars,
					array(
						'meta_query' => array(
							'relation' => 'AND',
							array(
								'key'     => '_yoast_wpseo_meta-robots-noindex',
								'value'   => 1,
								'compare' => '!='
							),
							array(
								'key'     => '_yoast_wpseo_linkdex',
								'value'   => array( $low, $high ),
								'type'    => 'numeric',
								'compare' => 'BETWEEN'
							)
						)
					)
				);
			}
			else if ( $noindex ) {
				$vars = array_merge(
					$vars,
					array(
						'meta_query' => array(
							'relation' => 'AND',
							array(
								'key'     => '_yoast_wpseo_meta-robots-noindex',
								'value'   => 1,
								'compare' => '='
							),
						)
					)
				);
			}
		}
		if ( isset( $_GET['seo_kw_filter'] ) ) {
			$vars = array_merge( $vars, array(
				'post_type'  => 'any',
				'meta_key'   => '_yoast_wpseo_focuskw',
				'meta_value' => $_GET['seo_kw_filter'],
			) );
		}
		if ( isset( $vars['orderby'] ) && 'wpseo-score' == $vars['orderby'] ) {
			$vars = array_merge( $vars, array(
				'meta_key' => '_yoast_wpseo_linkdex',
				'orderby'  => 'meta_value_num'
			) );
		}
		if ( isset( $vars['orderby'] ) && 'wpseo-metadesc' == $vars['orderby'] ) {
			$vars = array_merge( $vars, array(
				'meta_key' => '_yoast_wpseo_metadesc',
				'orderby'  => 'meta_value'
			) );
		}
		if ( isset( $vars['orderby'] ) && 'wpseo-focuskw' == $vars['orderby'] ) {
			$vars = array_merge( $vars, array(
				'meta_key' => '_yoast_wpseo_focuskw',
				'orderby'  => 'meta_value'
			) );
		}

		return $vars;
	}

	/**
	 * Retrieve the page title.
	 *
	 * @param int $post_id Post to retrieve the title for.
	 *
	 * @return string
	 */
	function page_title( $post_id ) {
		$fixed_title = wpseo_get_value( 'title', $post_id );
		if ( $fixed_title ) {
			return $fixed_title;
		}
		else {
			$post    = get_post( $post_id );
			$options = get_wpseo_options();
			if ( isset( $options['title-' . $post->post_type] ) && ! empty( $options['title-' . $post->post_type] ) ) {
				$title_template = $options['title-' . $post->post_type];
				$title_template = str_replace( ' %%page%% ', ' ', $title_template );
				return wpseo_replace_vars( $title_template, (array) $post );
			}
			else {
				return wpseo_replace_vars( '%%title%%', (array) $post );
			}
		}
	}

	/**
	 * Sort an array by a given key.
	 *
	 * @param array  $array Array to sort, array is returned sorted.
	 * @param string $key   Key to sort array by.
	 */
	function aasort( &$array, $key ) {
		$sorter = array();
		$ret    = array();
		reset( $array );
		foreach ( $array as $ii => $va ) {
			$sorter[$ii] = $va[$key];
		}
		asort( $sorter );
		foreach ( $sorter as $ii => $va ) {
			$ret[$ii] = $array[$ii];
		}
		$array = $ret;
	}

	/**
	 * Output the page analysis results.
	 *
	 * @param object $post Post to output the page analysis results for.
	 *
	 * @return string
	 */
	function linkdex_output( $post ) {
		$results = $this->calculate_results( $post );

		if ( is_wp_error( $results ) ) {
			$error = $results->get_error_messages();
			return '<div class="wpseo_msg"><p><strong>' . esc_html( $error[0] ) . '</strong></p></div>';
		}

		$output = '<table class="wpseoanalysis">';

		$perc_score = absint( wpseo_get_value( 'linkdex' ) );

		foreach ( $results as $result ) {
			$score = wpseo_translate_score( $result['val'] );
			$output .= '<tr><td class="score"><div class="wpseo_score_img ' . esc_attr( $score ) . '"></div></td><td>' . $result['msg'] . '</td></tr>';
		}
		$output .= '</table>';

		if ( WP_DEBUG )
			$output .= '<p><small>(' . $perc_score . '%)</small></p>';

		$output = '<div class="wpseo_msg"><p>' . __( 'To update this page analysis, save as draft or update and check this tab again', 'wordpress-seo' ) . '.</p></div>' . $output;

		unset( $results );

		return $output;
	}

	/**
	 * Calculate the page analysis results for post.
	 *
	 * @param object $post Post to calculate the results for.
	 *
	 * @return array
	 */
	function calculate_results( $post ) {
		$options = get_wpseo_options();

		if ( ! class_exists( 'DOMDocument' ) ) {
			$result = new WP_Error( 'no-domdocument', sprintf( __( "Your hosting environment does not support PHP's %sDocument Object Model%s.", 'wordpress-seo' ), '<a href="http://php.net/manual/en/book.dom.php">', '</a>' ) . ' ' . __( "To enjoy all the benefits of the page analysis feature, you'll need to (get your host to) install it.", 'wordpress-seo' ) );
			return $result;
		}

		if ( ! wpseo_get_value( 'focuskw', $post->ID ) ) {
			$result = new WP_Error( 'no-focuskw', sprintf( __( 'No focus keyword was set for this %s. If you do not set a focus keyword, no score can be calculated.', 'wordpress-seo' ), $post->post_type ) );

			wpseo_set_value( 'linkdex', 0, $post->ID );

			return $result;

		}
		elseif ( apply_filters( 'wpseo_use_page_analysis', true ) !== true ) {
			$result = new WP_Error( 'page-analysis-disabled', sprintf( __( 'Page Analysis has been disabled.', 'wordpress-seo' ), $post->post_type ) );

			return $result;
		}

		$results = array();
		$job     = array();

		$sampleurl             = get_sample_permalink( $post );
		$job["pageUrl"]        = preg_replace( '`%(?:post|page)name%`', $sampleurl[1], $sampleurl[0] );
		$job["pageSlug"]       = urldecode( $post->post_name );
		$job["keyword"]        = trim( wpseo_get_value( 'focuskw' ) );
		$job["keyword_folded"] = $this->strip_separators_and_fold( $job["keyword"] );
		$job["post_id"]        = $post->ID;
		$job["post_type"]      = $post->post_type;

		$dom                      = new domDocument;
		$dom->strictErrorChecking = false;
		$dom->preserveWhiteSpace  = false;
		@$dom->loadHTML( apply_filters( 'wpseo_pre_analysis_post_content', $post->post_content, $post ) );
		$xpath = new DOMXPath( $dom );

		global $statistics;
		$statistics = new Yoast_TextStatistics;

		// Check if this focus keyword has been used already.
		$this->check_double_focus_keyword( $job, $results );

		// Keyword
		$this->score_keyword( $job['keyword'], $results );

		// Title
		if ( wpseo_get_value( 'title' ) ) {
			$job['title'] = wpseo_get_value( 'title' );
		}
		else {
			if ( isset( $options['title-' . $post->post_type] ) && $options['title-' . $post->post_type] != '' )
				$title_template = $options['title-' . $post->post_type];
			else
				$title_template = '%%title%% - %%sitename%%';
			$job['title'] = wpseo_replace_vars( $title_template, (array) $post );
		}
		$this->score_title( $job, $results );

		// Meta description
		$description = '';
		if ( wpseo_get_value( 'metadesc' ) ) {
			$description = wpseo_get_value( 'metadesc' );
		}
		else {
			if ( isset( $options['metadesc-' . $post->post_type] ) && ! empty( $options['metadesc-' . $post->post_type] ) )
				$description = wpseo_replace_vars( $options['metadesc-' . $post->post_type], (array) $post );
		}

		$meta_length = apply_filters( 'wpseo_metadesc_length', 156, $post );

		$this->score_description( $job, $results, $description, $meta_length );
		unset( $description );

		// Body
		$body   = $this->get_body( $post );
		$firstp = $this->get_first_paragraph( $body );
		$this->score_body( $job, $results, $body, $firstp );
		unset( $firstp );

		// URL
		$this->score_url( $job, $results );

		// Headings
		$headings = $this->get_headings( $body );
		$this->score_headings( $job, $results, $headings );
		unset( $headings );

		// Images
		$imgs          = array();
		$imgs['count'] = substr_count( $body, '<img' );
		$imgs          = $this->get_images_alt_text( $post->ID, $body, $imgs );

		// Check featured image
		if ( has_post_thumbnail() ) {
			$imgs['count'] += 1;

			if ( empty( $imgs['alts'] ) ) {
				$imgs['alts'] = array();
			}

			$feature_image = get_the_post_thumbnail( $post->ID );
			if ( preg_match( '`alt=(["\'])(.*?)\1`', $feature_image, $alt ) && isset( $alt[2] ) ) {
				$imgs['alts'][] = $this->strtolower_utf8( $alt[2] );
			}
		}
		
		$this->score_images_alt_text( $job, $results, $imgs );
		unset( $imgs );
		unset( $body );

		// Anchors
		$anchors = $this->get_anchor_texts( $xpath );
		$count   = $this->get_anchor_count( $xpath );
		$this->score_anchor_texts( $job, $results, $anchors, $count );
		unset( $anchors, $count, $dom );

		$results = apply_filters( 'wpseo_linkdex_results', $results, $job, $post );

		$this->aasort( $results, 'val' );

		$overall     = 0;
		$overall_max = 0;

		foreach ( $results as $result ) {
			$overall += $result['val'];
			$overall_max += 9;
		}

		if ( $overall < 1 )
			$overall = 1;
		$score = round( ( $overall / $overall_max ) * 100 );

		wpseo_set_value( 'linkdex', absint( $score ), $post->ID );

		return $results;
	}

	/**
	 * Save the score result to the results array.
	 *
	 * @param array  $results      The results array used to store results.
	 * @param int    $scoreValue   The score value.
	 * @param string $scoreMessage The score message.
	 * @param string $scoreLabel   The label of the score to use in the results array.
	 * @param string $rawScore     The raw score, to be used by other filters.
	 */
	function save_score_result( &$results, $scoreValue, $scoreMessage, $scoreLabel, $rawScore = null ) {
		$score                = array(
			'val' => $scoreValue,
			'msg' => $scoreMessage,
			'raw' => $rawScore
		);
		$results[$scoreLabel] = $score;
	}

	/**
	 * Clean up the input string.
	 *
	 * @param string $inputString              String to clean up.
	 * @param bool   $removeOptionalCharacters Whether or not to do a cleanup of optional chars too.
	 *
	 * @return string
	 */
	function strip_separators_and_fold( $inputString, $removeOptionalCharacters = false ) {
		$keywordCharactersAlwaysReplacedBySpace = array( ",", "'", "\"", "?", "’", "“", "”", "|", "/" );
		$keywordCharactersRemovedOrReplaced     = array( "_", "-" );
		$keywordWordsRemoved                    = array( " a ", " in ", " an ", " on ", " for ", " the ", " and " );

		// lower
		$inputString = $this->strtolower_utf8( $inputString );

		// default characters replaced by space
		$inputString = str_replace( $keywordCharactersAlwaysReplacedBySpace, ' ', $inputString );

		// standardise whitespace
		$inputString = preg_replace( '`\s+`u', ' ', $inputString );

		// deal with the separators that can be either removed or replaced by space
		if ( $removeOptionalCharacters ) {
			// remove word separators with a space
			$inputString = str_replace( $keywordWordsRemoved, ' ', $inputString );

			$inputString = str_replace( $keywordCharactersRemovedOrReplaced, '', $inputString );
		}
		else {
			$inputString = str_replace( $keywordCharactersRemovedOrReplaced, ' ', $inputString );
		}

		// standardise whitespace again
		$inputString = preg_replace( '`\s+`u', ' ', $inputString );

		return trim( $inputString );
	}

	/**
	 * Check whether this focus keyword has been used for other posts before.
	 *
	 * @param array $job
	 * @param array $results
	 */
	function check_double_focus_keyword( $job, &$results ) {
		$posts = get_posts(
			array(
				'meta_key'    => '_yoast_wpseo_focuskw',
				'meta_value'  => $job['keyword'],
				'exclude'     => $job['post_id'],
				'fields'      => 'ids',
				'post_type'   => 'any',
				'numberposts' => - 1
			)
		);

		if ( count( $posts ) == 0 )
			$this->save_score_result( $results, 9, __( "You've never used this focus keyword before, very good.", 'wordpress-seo' ), 'keyword_overused' );
		else if ( count( $posts ) == 1 )
			$this->save_score_result( $results, 6, sprintf( __( 'You\'ve used this focus keyword %1$sonce before%2$s, be sure to make very clear which URL on your site is the most important for this keyword.', 'wordpress-seo' ), '<a href="' . admin_url( 'post.php?post=' . $posts[0] . '&action=edit' ) . '">', '</a>' ), 'keyword_overused' );
		else
			$this->save_score_result( $results, 1, sprintf( __( 'You\'ve used this focus keyword %3$s%4$d times before%2$s, it\'s probably a good idea to read %1$sthis post on cornerstone content%2$s and improve your keyword strategy.', 'wordpress-seo' ), '<a href="http://yoast.com/cornerstone-content-rank/">', '</a>', '<a href="' . admin_url( 'edit.php?seo_kw_filter=' . urlencode( $job['keyword'] ) ) . '">', count( $posts ) ), 'keyword_overused' );
	}

	/**
	 * Check whether the keyword contains stopwords.
	 *
	 * @param string $keyword The keyword to check for stopwords.
	 * @param array  $results The results array.
	 */
	function score_keyword( $keyword, &$results ) {
		global $wpseo_admin;

		$keywordStopWord = __( "The keyword for this page contains one or more %sstop words%s, consider removing them. Found '%s'.", 'wordpress-seo' );

		if ( $wpseo_admin->stopwords_check( $keyword ) !== false )
			$this->save_score_result( $results, 5, sprintf( $keywordStopWord, "<a href=\"http://en.wikipedia.org/wiki/Stop_words\">", "</a>", $wpseo_admin->stopwords_check( $keyword ) ), 'keyword_stopwords' );
	}

	/**
	 * Check whether the keyword is contained in the URL.
	 *
	 * @param array $job        The job array holding both the keyword and the URLs.
	 * @param array $results    The results array.
	 */
	function score_url( $job, &$results ) {
		global $statistics, $wpseo_admin;

		$urlGood      = __( "The keyword / phrase appears in the URL for this page.", 'wordpress-seo' );
		$urlMedium    = __( "The keyword / phrase does not appear in the URL for this page. If you decide to rename the URL be sure to check the old URL 301 redirects to the new one!", 'wordpress-seo' );
		$urlStopWords = __( "The slug for this page contains one or more <a href=\"http://en.wikipedia.org/wiki/Stop_words\">stop words</a>, consider removing them.", 'wordpress-seo' );
		$longSlug     = __( "The slug for this page is a bit long, consider shortening it.", 'wordpress-seo' );

		$needle    = $this->strip_separators_and_fold( $job["keyword"] );
		$haystack1 = $this->strip_separators_and_fold( $job["pageUrl"], true );
		$haystack2 = $this->strip_separators_and_fold( $job["pageUrl"], false );

		if ( stripos( $haystack1, $needle ) || stripos( $haystack2, $needle ) )
			$this->save_score_result( $results, 9, $urlGood, 'url_keyword' );
		else
			$this->save_score_result( $results, 6, $urlMedium, 'url_keyword' );

		// Check for Stop Words in the slug
		if ( $wpseo_admin->stopwords_check( $job["pageSlug"], true ) !== false )
			$this->save_score_result( $results, 5, $urlStopWords, 'url_stopword' );

		// Check if the slug isn't too long relative to the length of the keyword
		if ( ( $statistics->text_length( $job["keyword"] ) + 20 ) < $statistics->text_length( $job["pageSlug"] ) && 40 < $statistics->text_length( $job["pageSlug"] ) )
			$this->save_score_result( $results, 5, $longSlug, 'url_length' );
	}

	/**
	 * Check whether the keyword is contained in the title.
	 *
	 * @param array $job        The job array holding both the keyword versions.
	 * @param array $results    The results array.
	 */
	function score_title( $job, &$results ) {
		global $statistics;

		$scoreTitleMinLength    = 40;
		$scoreTitleMaxLength    = 70;
		$scoreTitleKeywordLimit = 0;

		$scoreTitleMissing          = __( "Please create a page title.", 'wordpress-seo' );
		$scoreTitleCorrectLength    = __( "The page title is more than 40 characters and less than the recommended 70 character limit.", 'wordpress-seo' );
		$scoreTitleTooShort         = __( "The page title contains %d characters, which is less than the recommended minimum of 40 characters. Use the space to add keyword variations or create compelling call-to-action copy.", 'wordpress-seo' );
		$scoreTitleTooLong          = __( "The page title contains %d characters, which is more than the viewable limit of 70 characters; some words will not be visible to users in your listing.", 'wordpress-seo' );
		$scoreTitleKeywordMissing   = __( "The keyword / phrase %s does not appear in the page title.", 'wordpress-seo' );
		$scoreTitleKeywordBeginning = __( "The page title contains keyword / phrase, at the beginning which is considered to improve rankings.", 'wordpress-seo' );
		$scoreTitleKeywordEnd       = __( "The page title contains keyword / phrase, but it does not appear at the beginning; try and move it to the beginning.", 'wordpress-seo' );

		if ( $job['title'] == "" ) {
			$this->save_score_result( $results, 1, $scoreTitleMissing, 'title' );
		}
		else {
			$length = $statistics->text_length( $job['title'] );
			if ( $length < $scoreTitleMinLength )
				$this->save_score_result( $results, 6, sprintf( $scoreTitleTooShort, $length ), 'title_length' );
			else if ( $length > $scoreTitleMaxLength )
				$this->save_score_result( $results, 6, sprintf( $scoreTitleTooLong, $length ), 'title_length' );
			else
				$this->save_score_result( $results, 9, $scoreTitleCorrectLength, 'title_length' );

			// TODO MA Keyword/Title matching is exact match with separators removed, but should extend to distributed match
			$needle_position = stripos( $job['title'], $job["keyword_folded"] );

			if ( $needle_position === false ) {
				$needle_position = stripos( $job['title'], $job["keyword"] );
			}

			if ( $needle_position === false )
				$this->save_score_result( $results, 2, sprintf( $scoreTitleKeywordMissing, $job["keyword_folded"] ), 'title_keyword' );
			else if ( $needle_position <= $scoreTitleKeywordLimit )
				$this->save_score_result( $results, 9, $scoreTitleKeywordBeginning, 'title_keyword' );
			else
				$this->save_score_result( $results, 6, $scoreTitleKeywordEnd, 'title_keyword' );
		}
	}

	/**
	 * Check whether the document contains outbound links and whether it's anchor text matches the keyword.
	 *
	 * @param array $job          The job array holding both the keyword versions.
	 * @param array $results      The results array.
	 * @param array $anchor_texts The array holding all anchors in the document.
	 * @param array $count        The number of anchors in the document, grouped by type.
	 */
	function score_anchor_texts( $job, &$results, $anchor_texts, $count ) {
		$scoreNoLinks               = __( "No outbound links appear in this page, consider adding some as appropriate.", 'wordpress-seo' );
		$scoreKeywordInOutboundLink = __( "You're linking to another page with the keyword you want this page to rank for, consider changing that if you truly want this page to rank.", 'wordpress-seo' );
		$scoreLinksDofollow         = __( "This page has %s outbound link(s).", 'wordpress-seo' );
		$scoreLinksNofollow         = __( "This page has %s outbound link(s), all nofollowed.", 'wordpress-seo' );
		$scoreLinks                 = __( "This page has %s nofollowed link(s) and %s normal outbound link(s).", 'wordpress-seo' );


		if ( $count['external']['nofollow'] == 0 && $count['external']['dofollow'] == 0 ) {
			$this->save_score_result( $results, 6, $scoreNoLinks, 'links' );
		}
		else {
			$found = false;
			foreach ( $anchor_texts as $anchor_text ) {
				if ( $this->strtolower_utf8( $anchor_text ) == $job["keyword_folded"] )
					$found = true;
			}
			if ( $found )
				$this->save_score_result( $results, 2, $scoreKeywordInOutboundLink, 'links_focus_keyword' );

			if ( $count['external']['nofollow'] == 0 && $count['external']['dofollow'] > 0 ) {
				$this->save_score_result( $results, 9, sprintf( $scoreLinksDofollow, $count['external']['dofollow'] ), 'links_number' );
			}
			else if ( $count['external']['nofollow'] > 0 && $count['external']['dofollow'] == 0 ) {
				$this->save_score_result( $results, 7, sprintf( $scoreLinksNofollow, $count['external']['nofollow'] ), 'links_number' );
			}
			else {
				$this->save_score_result( $results, 8, sprintf( $scoreLinks, $count['external']['nofollow'], $count['external']['dofollow'] ), 'links_number' );
			}
		}

	}

	/**
	 * Retrieve the anchor texts used in the current document.
	 *
	 * @param object $xpath An XPATH object of the current document.
	 *
	 * @return array
	 */
	function get_anchor_texts( &$xpath ) {
		$query        = "//a|//A";
		$dom_objects  = $xpath->query( $query );
		$anchor_texts = array();
		foreach ( $dom_objects as $dom_object ) {
			if ( $dom_object->attributes->getNamedItem( 'href' ) ) {
				$href = $dom_object->attributes->getNamedItem( 'href' )->textContent;
				if ( substr( $href, 0, 4 ) == 'http' )
					$anchor_texts['external'] = $dom_object->textContent;
			}
		}
		unset( $dom_objects );
		return $anchor_texts;
	}

	/**
	 * Count the number of anchors and group them by type.
	 *
	 * @param object $xpath An XPATH object of the current document.
	 *
	 * @return array
	 */
	function get_anchor_count( &$xpath ) {
		$query       = "//a|//A";
		$dom_objects = $xpath->query( $query );
		$count       = array(
			'total'    => 0,
			'internal' => array( 'nofollow' => 0, 'dofollow' => 0 ),
			'external' => array( 'nofollow' => 0, 'dofollow' => 0 ),
			'other'    => array( 'nofollow' => 0, 'dofollow' => 0 )
		);

		foreach ( $dom_objects as $dom_object ) {
			$count['total'] ++;
			if ( $dom_object->attributes->getNamedItem( 'href' ) ) {
				$href  = $dom_object->attributes->getNamedItem( 'href' )->textContent;
				$wpurl = get_bloginfo( 'url' );
				if ( substr( $href, 0, 1 ) == "/" || substr( $href, 0, strlen( $wpurl ) ) == $wpurl )
					$type = "internal";
				else if ( substr( $href, 0, 4 ) == 'http' )
					$type = "external";
				else
					$type = "other";
				if ( $dom_object->attributes->getNamedItem( 'rel' ) ) {
					$link_rel = $dom_object->attributes->getNamedItem( 'rel' )->textContent;
					if ( stripos( $link_rel, 'nofollow' ) !== false )
						$count[$type]['nofollow'] ++;
					else
						$count[$type]['dofollow'] ++;
				}
				else {
					$count[$type]['dofollow'] ++;
				}
			}
		}
		return $count;
	}

	/**
	 * Check whether the images alt texts contain the keyword.
	 *
	 * @param array $job     The job array holding both the keyword versions.
	 * @param array $results The results array.
	 * @param array $imgs    The array with images alt texts.
	 */
	function score_images_alt_text( $job, &$results, $imgs ) {
		$scoreImagesNoImages          = __( "No images appear in this page, consider adding some as appropriate.", 'wordpress-seo' );
		$scoreImagesNoAlt             = __( "The images on this page are missing alt tags.", 'wordpress-seo' );
		$scoreImagesAltKeywordIn      = __( "The images on this page contain alt tags with the target keyword / phrase.", 'wordpress-seo' );
		$scoreImagesAltKeywordMissing = __( "The images on this page do not have alt tags containing your keyword / phrase.", 'wordpress-seo' );

		if ( $imgs['count'] == 0 ) {
			$this->save_score_result( $results, 3, $scoreImagesNoImages, 'images_alt' );
		}
		else if ( count( $imgs['alts'] ) == 0 && $imgs['count'] != 0 ) {
			$this->save_score_result( $results, 5, $scoreImagesNoAlt, 'images_alt' );
		}
		else {
			$found = false;
			foreach ( $imgs['alts'] as $alt ) {
				$haystack1 = $this->strip_separators_and_fold( $alt, true );
				$haystack2 = $this->strip_separators_and_fold( $alt, false );
				if ( strrpos( $haystack1, $job["keyword_folded"] ) !== false )
					$found = true;
				else if ( strrpos( $haystack2, $job["keyword_folded"] ) !== false )
					$found = true;
			}
			if ( $found )
				$this->save_score_result( $results, 9, $scoreImagesAltKeywordIn, 'images_alt' );
			else
				$this->save_score_result( $results, 5, $scoreImagesAltKeywordMissing, 'images_alt' );
		}

	}

	/**
	 * Retrieve the alt texts from the images.
	 *
	 * @param int    $post_id The post to find images in.
	 * @param string $body    The post content to find images in.
	 * @param array  $imgs    The array holding the image information.
	 *
	 * @return array The updated images array.
	 */
	function get_images_alt_text( $post_id, $body, $imgs ) {
		preg_match_all( '`<img[^>]+>`im', $body, $matches );
		$imgs['alts'] = array();
		if ( is_array( $matches ) && count( $matches ) > 0 ) {
			foreach ( $matches[0] as $img ) {
				if ( preg_match( '`alt=(["\'])(.*?)\1`', $img, $alt ) && isset( $alt[2] ) )
					$imgs['alts'][] = $this->strtolower_utf8( $alt[2] );
			}
		}
		if ( strpos( $body, '[gallery' ) !== false ) {
			$attachments = get_children( array( 'post_parent' => $post_id, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'fields' => 'ids' ) );
			if ( is_array( $attachments ) && count( $attachments ) > 0 ) {
				foreach ( $attachments as $att_id ) {
					$alt = get_post_meta( $att_id, '_wp_attachment_image_alt', true );
					if ( $alt && ! empty( $alt ) )
						$imgs['alts'][] = $alt;
					$imgs['count'] ++;
				}
			}
		}
		return $imgs;
	}

	/**
	 * Score the headings for keyword appearance.
	 *
	 * @param array $job      The array holding the keywords.
	 * @param array $results  The results array.
	 * @param array $headings The headings found in the document.
	 */
	function score_headings( $job, &$results, $headings ) {
		$scoreHeadingsNone           = __( "No subheading tags (like an H2) appear in the copy.", 'wordpress-seo' );
		$scoreHeadingsKeywordIn      = __( "Keyword / keyphrase appears in %s (out of %s) subheadings in the copy. While not a major ranking factor, this is beneficial.", 'wordpress-seo' );
		$scoreHeadingsKeywordMissing = __( "You have not used your keyword / keyphrase in any subheading (such as an H2) in your copy.", 'wordpress-seo' );

		$headingCount = count( $headings );
		if ( $headingCount == 0 )
			$this->save_score_result( $results, 7, $scoreHeadingsNone, 'headings' );
		else {
			$found = 0;
			foreach ( $headings as $heading ) {
				$haystack1 = $this->strip_separators_and_fold( $heading, true );
				$haystack2 = $this->strip_separators_and_fold( $heading, false );

				if ( strrpos( $haystack1, $job["keyword_folded"] ) !== false )
					$found ++;
				else if ( strrpos( $haystack2, $job["keyword_folded"] ) !== false )
					$found ++;
			}
			if ( $found )
				$this->save_score_result( $results, 9, sprintf( $scoreHeadingsKeywordIn, $found, $headingCount ), 'headings' );
			else
				$this->save_score_result( $results, 3, $scoreHeadingsKeywordMissing, 'headings' );
		}
	}

	/**
	 * Fetch all headings and return their content.
	 *
	 * @param string $postcontent Post content to find headings in.
	 *
	 * @return array Array of heading texts.
	 */
	function get_headings( $postcontent ) {
		$headings = array();

		preg_match_all( '`<h([1-6])(?:[^>]+)?>(.*?)</h\\1>`i', $postcontent, $matches );
		if ( isset( $matches ) && isset( $matches[2] ) ) {
			foreach ( $matches[2] as $heading ) {
				$headings[] = $this->strtolower_utf8( $heading );
			}
		}

		return $headings;
	}

	/**
	 * Score the meta description for length and keyword appearance.
	 *
	 * @param array  $job         The array holding the keywords.
	 * @param array  $results     The results array.
	 * @param string $description The meta description.
	 * @param int    $maxlength   The maximum length of the meta description.
	 */
	function score_description( $job, &$results, $description, $maxlength = 155 ) {
		global $statistics;

		$scoreDescriptionMinLength      = 120;
		$scoreDescriptionCorrectLength  = __( "In the specified meta description, consider: How does it compare to the competition? Could it be made more appealing?", 'wordpress-seo' );
		$scoreDescriptionTooShort       = __( "The meta description is under 120 characters, however up to %s characters are available. %s", 'wordpress-seo' );
		$scoreDescriptionTooLong        = __( "The specified meta description is over %s characters, reducing it will ensure the entire description is visible. %s", 'wordpress-seo' );
		$scoreDescriptionMissing        = __( "No meta description has been specified, search engines will display copy from the page instead.", 'wordpress-seo' );
		$scoreDescriptionKeywordIn      = __( "The meta description contains the primary keyword / phrase.", 'wordpress-seo' );
		$scoreDescriptionKeywordMissing = __( "A meta description has been specified, but it does not contain the target keyword / phrase.", 'wordpress-seo' );

		$metaShorter = '';
		if ( $maxlength != 155 )
			$metaShorter = __( "The available space is shorter than the usual 155 characters because Google will also include the publication date in the snippet.", 'wordpress-seo' );

		if ( $description == "" ) {
			$this->save_score_result( $results, 1, $scoreDescriptionMissing, 'description_length' );
		}
		else {
			$length = $statistics->text_length( $description );

			if ( $length < $scoreDescriptionMinLength )
				$this->save_score_result( $results, 6, sprintf( $scoreDescriptionTooShort, $maxlength, $metaShorter ), 'description_length' );
			else if ( $length <= $maxlength )
				$this->save_score_result( $results, 9, $scoreDescriptionCorrectLength, 'description_length' );
			else
				$this->save_score_result( $results, 6, sprintf( $scoreDescriptionTooLong, $maxlength, $metaShorter ), 'description_length' );

			// TODO MA Keyword/Title matching is exact match with separators removed, but should extend to distributed match
			$haystack1 = $this->strip_separators_and_fold( $description, true );
			$haystack2 = $this->strip_separators_and_fold( $description, false );
			if ( strrpos( $haystack1, $job["keyword_folded"] ) === false && strrpos( $haystack2, $job["keyword_folded"] ) === false )
				$this->save_score_result( $results, 3, $scoreDescriptionKeywordMissing, 'description_keyword' );
			else
				$this->save_score_result( $results, 9, $scoreDescriptionKeywordIn, 'description_keyword' );
		}
	}

	/**
	 * Score the body for length and keyword appearance.
	 *
	 * @param array  $job         The array holding the keywords.
	 * @param array  $results     The results array.
	 * @param string $body        The body.
	 * @param string $firstp      The first paragraph.
	 */
	function score_body( $job, &$results, $body, $firstp ) {
		global $statistics;

		$lengthScore = apply_filters( 'wpseo_body_length_score',
			array(
				'good' => 300,
				'ok'   => 250,
				'poor' => 200,
				'bad'  => 100
			),
			$job
		);

		$scoreBodyGoodLength = __( "There are %d words contained in the body copy, this is more than the %d word recommended minimum.", 'wordpress-seo' );
		$scoreBodyPoorLength = __( "There are %d words contained in the body copy, this is below the %d word recommended minimum. Add more useful content on this topic for readers.", 'wordpress-seo' );
		$scoreBodyOKLength   = __( "There are %d words contained in the body copy, this is slightly below the %d word recommended minimum, add a bit more copy.", 'wordpress-seo' );
		$scoreBodyBadLength  = __( "There are %d words contained in the body copy. This is far too low and should be increased.", 'wordpress-seo' );

		$scoreKeywordDensityLow  = __( "The keyword density is %s%%, which is a bit low, the keyword was found %s times.", 'wordpress-seo' );
		$scoreKeywordDensityHigh = __( "The keyword density is %s%%, which is over the advised 4.5%% maximum, the keyword was found %s times.", 'wordpress-seo' );
		$scoreKeywordDensityGood = __( "The keyword density is %s%%, which is great, the keyword was found %s times.", 'wordpress-seo' );

		$scoreFirstParagraphLow  = __( "The keyword doesn't appear in the first paragraph of the copy, make sure the topic is clear immediately.", 'wordpress-seo' );
		$scoreFirstParagraphHigh = __( "The keyword appears in the first paragraph of the copy.", 'wordpress-seo' );

		$fleschurl   = '<a href="http://en.wikipedia.org/wiki/Flesch-Kincaid_readability_test#Flesch_Reading_Ease">' . __( 'Flesch Reading Ease', 'wordpress-seo' ) . '</a>';
		$scoreFlesch = __( "The copy scores %s in the %s test, which is considered %s to read. %s", 'wordpress-seo' );

		// Replace images with their alt tags, then strip all tags
		$body = preg_replace( '`<img(?:[^>]+)?alt="([^"]+)"(?:[^>]+)>`', '$1', $body );
		$body = strip_tags( $body );

		// Copy length check
		$wordCount = $statistics->word_count( $body );

		if ( $wordCount < $lengthScore['bad'] )
			$this->save_score_result( $results, - 20, sprintf( $scoreBodyBadLength, $wordCount, $lengthScore['good'] ), 'body_length', $wordCount );
		else if ( $wordCount < $lengthScore['poor'] )
			$this->save_score_result( $results, - 10, sprintf( $scoreBodyPoorLength, $wordCount, $lengthScore['good'] ), 'body_length', $wordCount );
		else if ( $wordCount < $lengthScore['ok'] )
			$this->save_score_result( $results, 5, sprintf( $scoreBodyPoorLength, $wordCount, $lengthScore['good'] ), 'body_length', $wordCount );
		else if ( $wordCount < $lengthScore['good'] )
			$this->save_score_result( $results, 7, sprintf( $scoreBodyOKLength, $wordCount, $lengthScore['good'] ), 'body_length', $wordCount );
		else
			$this->save_score_result( $results, 9, sprintf( $scoreBodyGoodLength, $wordCount, $lengthScore['good'] ), 'body_length', $wordCount );

		$body           = $this->strtolower_utf8( $body );
		$job["keyword"] = $this->strtolower_utf8( $job["keyword"] );

		$keywordWordCount = str_word_count( $job["keyword"] );
		if ( $keywordWordCount > 10 ) {
			$this->save_score_result( $results, 0, __( 'Your keyphrase is over 10 words, a keyphrase should be shorter and there can be only one keyphrase.', 'wordpress-seo' ), 'focus_keyword_length' );
		}
		else {
			// Keyword Density check
			$keywordDensity = 0;
			if ( $wordCount > 100 ) {
				$keywordCount = preg_match_all( '`' . preg_quote( $job["keyword"], '`' ) . '`msiuU', $body, $res );
				if ( $keywordCount > 0 && $keywordWordCount > 0 )
					$keywordDensity = number_format( ( ( $keywordCount / ( $wordCount - ( ( $keywordWordCount - 1 ) * $keywordWordCount ) ) ) * 100 ), 2 );
				if ( $keywordDensity < 1 ) {
					$this->save_score_result( $results, 4, sprintf( $scoreKeywordDensityLow, $keywordDensity, $keywordCount ), 'keyword_density' );
				}
				else if ( $keywordDensity > 4.5 ) {
					$this->save_score_result( $results, - 50, sprintf( $scoreKeywordDensityHigh, $keywordDensity, $keywordCount ), 'keyword_density' );
				}
				else {
					$this->save_score_result( $results, 9, sprintf( $scoreKeywordDensityGood, $keywordDensity, $keywordCount ), 'keyword_density' );
				}
			}
		}

		$firstp = $this->strtolower_utf8( $firstp );

		// First Paragraph Test
		if ( ! preg_match( '`\b' . preg_quote( $job['keyword'], '`' ) . '\b`u', $firstp ) && ! preg_match( '`\b' . preg_quote( $job['keyword_folded'], '`' ) . '\b`u', $firstp ) ) {
			$this->save_score_result( $results, 3, $scoreFirstParagraphLow, 'keyword_first_paragraph' );
		}
		else {
			$this->save_score_result( $results, 9, $scoreFirstParagraphHigh, 'keyword_first_paragraph' );
		}

		$lang = get_bloginfo( 'language' );
		if ( substr( $lang, 0, 2 ) == 'en' && $wordCount > 100 ) {
			// Flesch Reading Ease check
			$flesch = $statistics->flesch_kincaid_reading_ease( $body );

			$note  = '';
			$level = '';
			$score = 1;
			if ( $flesch >= 90 ) {
				$level = __( 'very easy', 'wordpress-seo' );
				$score = 9;
			}
			else if ( $flesch >= 80 ) {
				$level = __( 'easy', 'wordpress-seo' );
				$score = 9;
			}
			else if ( $flesch >= 70 ) {
				$level = __( 'fairly easy', 'wordpress-seo' );
				$score = 8;
			}
			else if ( $flesch >= 60 ) {
				$level = __( 'OK', 'wordpress-seo' );
				$score = 7;
			}
			else if ( $flesch >= 50 ) {
				$level = __( 'fairly difficult', 'wordpress-seo' );
				$note  = __( 'Try to make shorter sentences to improve readability.', 'wordpress-seo' );
				$score = 6;
			}
			else if ( $flesch >= 30 ) {
				$level = __( 'difficult', 'wordpress-seo' );
				$note  = __( 'Try to make shorter sentences, using less difficult words to improve readability.', 'wordpress-seo' );
				$score = 5;
			}
			else if ( $flesch >= 0 ) {
				$level = __( 'very difficult', 'wordpress-seo' );
				$note  = __( 'Try to make shorter sentences, using less difficult words to improve readability.', 'wordpress-seo' );
				$score = 4;
			}
			$this->save_score_result( $results, $score, sprintf( $scoreFlesch, $flesch, $fleschurl, $level, $note ), 'flesch_kincaid' );
		}
	}

	/**
	 * Retrieve the body from the post.
	 *
	 * @param object $post The post object.
	 *
	 * @return string The post content.
	 */
	function get_body( $post ) {
		// This filter allows plugins to add their content to the content to be analyzed.
		$post_content = apply_filters( 'wpseo_pre_analysis_post_content', $post->post_content, $post );

		// Strip shortcodes, for obvious reasons, if plugins think their content should be in the analysis, they should
		// hook into the above filter.
		$post_content = wpseo_strip_shortcode( $post_content );

		if ( trim( $post_content ) == '' )
			return '';

		$htmdata2 = preg_replace( '`[\n\r]`', ' ', $post_content );
		if ( $htmdata2 == null )
			$htmdata2 = $post_content;
		else
			unset( $post_content );

		$htmdata3 = preg_replace( '`<(?:\x20*script|script).*?(?:/>|/script>)`', '', $htmdata2 );
		if ( $htmdata3 == null )
			$htmdata3 = $htmdata2;
		else
			unset( $htmdata2 );

		$htmdata4 = preg_replace( '`<!--.*?-->`', '', $htmdata3 );
		if ( $htmdata4 == null )
			$htmdata4 = $htmdata3;
		else
			unset( $htmdata3 );

		$htmdata5 = preg_replace( '`<(?:\x20*style|style).*?(?:/>|/style>)`', '', $htmdata4 );
		if ( $htmdata5 == null )
			$htmdata5 = $htmdata4;
		else
			unset( $htmdata4 );

		return $htmdata5;
	}

	/**
	 * Retrieve the first paragraph from the post.
	 *
	 * @param string $body The post content to retrieve the first paragraph from.
	 *
	 * @return string
	 */
	function get_first_paragraph( $body ) {
		// To determine the first paragraph we first need to autop the content, then match the first paragraph and return.
		$res = preg_match( '`<p[.]*?>(.*)</p>`', wpautop( strip_tags( $body ) ), $matches );
		if ( $res )
			return $matches[1];
		return false;
	}
}

global $wpseo_metabox;
$wpseo_metabox = new WPSEO_Metabox();