ld-quiz-pro.php 70.7 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 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106
<?php
/**
 * Extends WP Pro Quiz functionality to meet needs of LearnDash
 *
 * @since 2.1.0
 *
 * @package LearnDash\Quiz
 */

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

/**
 * Include WP Pro Quiz Plugin
 */
//require_once dirname( dirname( __FILE__ ) ) . '/vendor/wp-pro-quiz/wp-pro-quiz.php';
require_once LEARNDASH_LMS_LIBRARY_DIR . '/wp-pro-quiz/wp-pro-quiz.php';

/**
 * LearnDash QuizPro class
 *
 * @since 2.1.0
 */
class LD_QuizPro {

	public $debug = false;

	/**
	 * LD_QuizPro constructor
	 *
	 * @since 2.1.0
	 */
	public function __construct() {

		//add_action( 'wp_head', array( $this, 'certificate_details' ) );
		add_action( 'wp_pro_quiz_completed_quiz', array( $this, 'wp_pro_quiz_completed' ) );
		//add_action( 'save_post', array( $this, 'edit_process' ), 2000 );
		add_action( 'plugins_loaded', array( $this, 'quiz_edit_redirect' ), 1 );

		add_filter( 'ldadvquiz_the_content', 'wptexturize' );
		add_filter( 'ldadvquiz_the_content', 'convert_smilies' );
		add_filter( 'ldadvquiz_the_content', 'convert_chars' );
		add_filter( 'ldadvquiz_the_content', 'wpautop' );
		add_filter( 'ldadvquiz_the_content', 'shortcode_unautop' );
		add_filter( 'ldadvquiz_the_content', 'prepend_attachment' );

		add_filter( 'learndash_quiz_content', array( $this, 'learndash_quiz_content' ), 1, 2 );

		//add_action("the_content", array( $this, 'certificate_link' ));
		if ( ! empty( $_GET['ld_fix_permissions'] ) ) {
			$role = get_role( 'administrator' );
			if ( ( $role ) && ( $role instanceof WP_Role ) ) {

				$role->add_cap( 'wpProQuiz_show' );
				$role->add_cap( 'wpProQuiz_add_quiz' );
				$role->add_cap( 'wpProQuiz_edit_quiz' );
				$role->add_cap( 'wpProQuiz_delete_quiz' );
				$role->add_cap( 'wpProQuiz_show_statistics' );
				$role->add_cap( 'wpProQuiz_reset_statistics' );
				$role->add_cap( 'wpProQuiz_import' );
				$role->add_cap( 'wpProQuiz_export' );
				$role->add_cap( 'wpProQuiz_change_settings' );
				$role->add_cap( 'wpProQuiz_toplist_edit' );
				$role->add_cap( 'wpProQuiz_toplist_edit' );
			}
		}

		add_action( 'wp_ajax_ld_adv_quiz_pro_ajax', array( $this, 'ld_adv_quiz_pro_ajax' ) );
		add_action( 'wp_ajax_nopriv_ld_adv_quiz_pro_ajax', array( $this, 'ld_adv_quiz_pro_ajax' ) );

		add_action( 'learndash_quiz_submitted', array( $this, 'set_quiz_status_meta' ), 1, 2 );
	}

	/**
	 * Submit quiz and echo JSON representation of the checked quiz answers
	 *
	 * @since 2.1.0
	 */
	public function ld_adv_quiz_pro_ajax() {

		// First we unpack the $_POST['results'] string
		if ( ( isset( $_POST['data']['responses'] ) ) && ( ! empty( $_POST['data']['responses'] ) ) && ( is_string( $_POST['data']['responses'] ) ) ) {
			$_POST['data']['responses'] = json_decode( stripslashes( $_POST['data']['responses'] ), true );
		}

		$func = isset( $_POST['func'] ) ? $_POST['func'] : '';
		$data = isset( $_POST['data'] ) ? (array) $_POST['data'] : null;

		switch ( $func ) {
			case 'checkAnswers':
				echo $this->checkAnswers( $data );
				break;
		}

		exit; // We need to exit as this is the AJAX handler and should not return control back to WP.
	}

	/**
	 * Check answers for submitted quiz
	 *
	 * @since 2.1.0
	 *
	 * @param  array $data Quiz information and answers to be checked
	 *
	 * @return string  JSON representation of checked answers
	 */
	public function checkAnswers( $data ) {
		if ( is_user_logged_in() ) {
			$user_id = get_current_user_id();
		} else {
			$user_id = 0;
		}

		if ( isset( $data['quizId'] ) ) {
			$id = absint( $data['quizId'] );
		} else {
			$id = 0;
		}

		if ( isset( $data['quiz'] ) ) {
			$quiz_post_id = absint( $data['quiz'] );
		} else {
			$quiz_post_id = 0;
		}

		if ( ( ! isset( $data['quiz_nonce'] ) ) || ( ! wp_verify_nonce( $data['quiz_nonce'], 'sfwd-quiz-nonce-' . $quiz_post_id . '-' . $id . '-' . $user_id ) ) ) {
			//wp_send_json_error();
			die();
		}

		learndash_quiz_debug_log_init( $quiz_post_id );
		learndash_quiz_debug_log_message( 'Browser version: ' . $_SERVER['HTTP_USER_AGENT'] );
		learndash_quiz_debug_log_message( '---------------------------------' );
		learndash_quiz_debug_log_message( 'in ' . __FUNCTION__ );
		learndash_quiz_debug_log_message( '_POST<pre>' . print_r( $_POST, true ) . '</pre>' );

		learndash_quiz_debug_log_message( 'user_id ' . $user_id );
		learndash_quiz_debug_log_message( 'quiz id ' . $id );
		learndash_quiz_debug_log_message( 'quiz_post_id ' . $quiz_post_id );

		if ( defined( 'LEARNDASH_QUIZ_DEBUG' ) && LEARNDASH_QUIZ_DEBUG ) {
			/**
			 * Filters quiz user responses.
			 *
			 * @since 4.3.0
			 *
			 * @param array $data         User Quiz response array.
			 * @param int   $user_id      User ID.
			 * @param int   $quiz_post_id Quiz Post ID.
			 *
			 */
			$data = apply_filters( 'learndash_quiz_check_answers_data', $data, $user_id, $quiz_post_id );

			learndash_quiz_debug_log_message( 'after filter: learndash_quiz_check_answers_data: data: ' . print_r( $data, true ) );
		}

		$quiz_post = get_post( $quiz_post_id );

		$view       = new WpProQuiz_View_FrontQuiz();
		$quizMapper = new WpProQuiz_Model_QuizMapper();
		$quiz       = $quizMapper->fetch( $id );
		if ( $quiz_post_id !== absint( $quiz->getPostId() ) ) {
			$quiz->setPostId( $quiz_post_id );
		}

		$questionMapper = new WpProQuiz_Model_QuestionMapper();
		$categoryMapper = new WpProQuiz_Model_CategoryMapper();
		$formMapper     = new WpProQuiz_Model_FormMapper();

		$questionModels = $questionMapper->fetchAll( $quiz );

		$view->quiz     = $quiz;
		$view->question = $questionModels;
		$view->category = $categoryMapper->fetchByQuiz( $quiz );

		$question_count = count( $questionModels );
		ob_start();
		$quizData = $view->showQuizBox( $question_count );
		ob_get_clean();

		$json           = $quizData['json'];
		$results        = array();
		$question_index = 0;

		foreach ( $data['responses'] as $question_id => $info ) {
			if ( isset( $questionModel ) ) {
				unset( $questionModel );
			}

			foreach ( $questionModels as $questionModel ) {
				if ( $questionModel->getId() == intval( $question_id ) ) {

					$userResponse = $info['response'];

					$questionData           = $json[ $question_id ];
					$correct                = false;
					$points                 = 0;
					$statisticsData         = new stdClass();
					$extra                  = array();
					$extra['type']          = $questionData['type'];
					$questionData['points'] = isset( $questionData['points'] ) ? $questionData['points'] : $questionData['globalPoints'];

					$question_index++;
					$answer_pointed_activated = $questionModel->isAnswerPointsActivated();

					/**
					 * Filters whether use the legacy sanitize user response question.
					 *
					 * @since 4.3.0
					 *
					 * @param boolean $use_legacy   Whether to use legacy sanitize scheme. Default false.
					 * @param mixed   $userResponse User question response data.
					 * @param object  $questionData WpProQuiz_Model_Question Question Model instance.
					 *
					*/
					$question_legacy_sanitize_scheme = apply_filters( 'learndash_quiz_question_legacy_sanitize_scheme', false, $userResponse, $questionData );

					switch ( $questionData['type'] ) {
						case 'free_answer':

							if ( ! $question_legacy_sanitize_scheme ) {
								$userResponse          = esc_attr( wp_unslash( trim( $userResponse ) ) );
								$userResponse_filtered = $userResponse;
							} else {
								$userResponse = stripslashes( trim( $userResponse ) );
								$userResponse = $userResponse_filtered;
							}
							$correct = false;
							$points  = 0;

							if ( ( ! empty( $questionData['correct'] ) ) && ( '' !== $userResponse_filtered ) ) {

								/**
								 * The default value is based on the opposite of the legacy sanitize var value.
								 *
								 * If the legacy var is 'false' then we probably want to set this var as true since we do
								 * want to format the correct answers.
								 */
								$format_correct = ! $question_legacy_sanitize_scheme;

								/**
								 * Filters whether to format the question correct answers.
								 *
								 * This might mean converting HTML to entities, removing some HTML tags, etc.
								 *
								 * @since 4.4.0
								 *
								 * @param boolean                  $format_correct  Whether to format the question correct answers.
								 * @param array                    $questionData    Array of question data.
								 * @param WpProQuiz_Model_Question $question_model  Question model object.
								 */
								$format_correct = apply_filters( 'learndash_quiz_format_correct_answer', $format_correct, $questionData, $questionModel );

								foreach ( $questionData['correct'] as $questionData_idx => $questionData_correct ) {
									if ( $format_correct ) {
										$questionData_correct_filtered = esc_attr( trim( $questionData_correct ) );
									} else {
										$questionData_correct_filtered = stripslashes( trim( $questionData_correct ) );
									}

									/**
									 * Filters whether to convert quiz question free to lowercase or not.
									 *
									 * @since 3.5.0
									 *
									 * @param boolean $convert_to_lower Whether to convert quiz question free to lower case.
									 * @param object  $question         WpProQuiz_Model_Question Question Model instance.
									*/
									if ( apply_filters( 'learndash_quiz_question_free_answers_to_lowercase', true, $questionModel ) ) {
										if ( function_exists( 'mb_strtolower' ) ) {
											$userResponse_filtered         = mb_strtolower( $userResponse_filtered );
											$questionData_correct_filtered = mb_strtolower( $questionData_correct_filtered );
										} else {
											$userResponse_filtered         = strtolower( $userResponse_filtered );
											$questionData_correct_filtered = strtolower( $questionData_correct_filtered );
										}
									}

									if ( $userResponse_filtered == $questionData_correct_filtered ) {
										$correct = true;
										if ( $questionModel->isAnswerPointsActivated() ) {
											if ( isset( $questionData['points'][ $questionData_idx ] ) ) {
												$points = (int) $questionData['points'][ $questionData_idx ];
											} else {
												$points = 1;
											}
										} else {
											$points = $questionModel->getPoints();
										}
										break;
									}
								}
							}

							/**
							 * Filters answer points for free question type.
							 *
							 * @param int   $points        Points for the question.
							 * @param array $question_data An array of question data.
							 * @param array $user_response An array of user response data.
							 */
							$points = apply_filters( 'learndash_ques_free_answer_pts', $points, $questionData, $userResponse );

							/**
							 * Filters whether the answer is correct or not for a free question type.
							 *
							 * @param boolean $correct       Whether the answer is correct or not.
							 * @param array   $question_data An array of question data.
							 * @param array   $user_response An array of user response data.
							 */
							$correct = apply_filters( 'learndash_ques_free_answer_correct', $correct, $questionData, $userResponse );

							$extra['r'] = $userResponse;
							if ( ! $quiz->isDisabledAnswerMark() && empty( $questionData['disCorrect'] ) ) {
								if ( isset( $questionData['correct'] ) ) {
									$extra['c'] = $questionData['correct'];
								} else {
									$extra['c'] = array();
								}
							}

							break;

						case 'multiple':
							// Normalize the user response/answers.
							if ( ( is_array( $userResponse ) ) && ( ! empty( $userResponse ) ) ) {
								foreach ( $userResponse as $key => $value ) {
									if ( ( $value != 0 ) && ( $value != 1 ) ) { // phpcs:ignore WordPress.PHP.StrictComparisons.LooseComparison -- Strict compare causes failure. Need to rework logic.
										if ( $value === 'true' ) {
											$userResponse[ $key ] = true;
										} else {
											$userResponse[ $key ] = false;
										}
									}
								}
							}

							$correct = true;
							$r       = array();
							if ( ! empty( $questionData['correct'] ) ) {
								foreach ( $questionData['correct'] as $answerIndex => $correctAnswer ) {
									if ( $answer_pointed_activated ) {
										if ( ( isset( $userResponse[ $answerIndex ] ) ) && ( $userResponse[ $answerIndex ] == $correctAnswer ) ) {
											$r[ $answerIndex ] = $userResponse[ $answerIndex ];
											$correct_this_item = true;

											if ( $userResponse[ $answerIndex ] == true ) {
												$points += $questionData['points'][ $answerIndex ];
											}
										} else {
											$r[ $answerIndex ] = false;
											$correct_this_item = false;
										}

										if ( has_filter( 'learndash_ques_multiple_answer_pts_each' ) ) {
											/**
											 * Filters the points of each answer for multiple answer type question.
											 *
											 * @param int        $point          Points for the question.
											 * @param int|string $answer_index   Index of the answer.
											 * @param array      $question_data  An array of question data.
											 * @param mixed      $correct_answer Correct answer for the question.
											 * @param array      $user_response  An array of user response data.
											 */
											$points = apply_filters( 'learndash_ques_multiple_answer_pts_each', $points, $questionData, $answerIndex, $correctAnswer, $userResponse );
										} else {
											/**
											 * Added logic to subtract points on selected incorrect answers.
											 *
											 * @since 2.5.7
											 */
											if ( $questionData['correct'][ $answerIndex ] == 0 ) {
												if ( $correct_this_item == false ) {
													if ( intval( $questionData['points'][ $answerIndex ] ) > 0 ) {
														$points -= intval( $questionData['points'][ $answerIndex ] );
													}
												}

												end( $questionData['correct'] );
											}
										}

										/**
										 * Filters whether to correct the answer for a multiple answer type question or not.
										 *
										 * @param boolean    $correct_item   Whether to correct the answer or not.
										 * @param array      $question_data  An array of question data.
										 * @param int|string $answer_index   Index of the answer.
										 * @param mixed      $correct_answer Correct answer for the question.
										 * @param array      $user_response  An array of user response data.
										 */
										$correct_this_item = apply_filters( 'learndash_ques_multiple_answer_correct_each', $correct_this_item, $questionData, $answerIndex, $correctAnswer, $userResponse );
										if ( ( $correct_this_item != true ) && ( $correct == true ) ) {
											$correct = false;
										}
									} else {

										/**
										 * Points are allocated for the entire question if the user selects all the correct answers and none of
										 * the incorrect answers
										 *
										 * if the user selects an answer that is marked as correct, mark the question true and let the
										 * foreach loop check the next answer
										 *
										 * if they select an incorrect answer, or fail to select a correct answer, mark it false and break
										 * the foreach
										 *
										 * we don't want to break the foreach if the user did not select an incorrect answer
										 */
										if ( ! empty( $correctAnswer ) && ! empty( $userResponse[ $answerIndex ] ) ) {
											$correct           = true;
											$r[ $answerIndex ] = true;
											$points            = $questionData['points'];
										} elseif ( empty( $correctAnswer ) && ! empty( $userResponse[ $answerIndex ] ) ) {
											$correct           = false;
											$r[ $answerIndex ] = false;
											$points            = 0;
											break;
										} elseif ( ! empty( $correctAnswer ) && empty( $userResponse[ $answerIndex ] ) ) {
											$correct           = false;
											$r[ $answerIndex ] = false;
											$points            = 0;
											break;
										}

										// See https://developers.learndash.com/hook/learndash_ques_multiple_answer_pts_whole/ for examples of this filter.
										/**
										 * Filters points awarded for a multiple answer type question.
										 *
										 * LearnDash multiple answer question, allow points to be allocated for not marking an incorrect answer.
										 * LearnDash Core loops over all the answers in a multiple answer question. If the user does not mark an incorrect answer,
										 * allow the possibility of giving them points.
										 *
										 * @param int        $points         Points awarded to quiz
										 * @param array      $question_data  An array of question data.
										 * @param int|string $answer_index   Index of the answer.
										 * @param mixed      $correct_answer Correct answer for the question.
										 * @param array      $user_response  An array of user response data.
										 */
										$points = apply_filters( 'learndash_ques_multiple_answer_pts_whole', $points, $questionData, $answerIndex, $correctAnswer, $userResponse );

										/**
										 * Filters whether the answer to the multiple type question is correct or not.
										 *
										 * @param boolean    $correct        Whether the answer is correct or not.
										 * @param array      $question_data  An array of question data.
										 * @param int|string $answer_index   Index of the answer.
										 * @param mixed      $correct_answer Correct answer for the question.
										 * @param array      $user_response  An array of user response data.
										 */
										$correct = apply_filters( 'learndash_ques_multiple_answer_correct_whole', $correct, $questionData, $answerIndex, $correctAnswer, $userResponse );

									}
								}
							}

							// If total question points are less than zero.
							if ( $points < 0 ) {
								$points = 0;
							}

							$extra['r'] = $userResponse;

							if ( ! $quiz->isDisabledAnswerMark() ) {
								$extra['c'] = $questionData['correct'];
							}

							break;

						case 'single':
							// Normalize the user response/answers.
							if ( ( is_array( $userResponse ) ) && ( ! empty( $userResponse ) ) ) {
								foreach ( $userResponse as $key => $value ) {
									if ( ( $value != 0 ) && ( $value != 1 ) ) { // phpcs:ignore WordPress.PHP.StrictComparisons.LooseComparison -- Strict compare causes failure. Need to rework logic.
										if ( $value === 'true' ) {
											$userResponse[ $key ] = true;
										} else {
											$userResponse[ $key ] = false;
										}
									}
								}
							}

							if ( ! empty( $questionData['correct'] ) ) {
								foreach ( $questionData['correct'] as $answerIndex => $correctAnswer ) {
									if ( $userResponse[ $answerIndex ] === true ) {

										if ( ( ( isset( $questionData['diffMode'] ) ) && ( ! empty( $questionData['diffMode'] ) ) ) || ( ! empty( $correctAnswer ) ) ) {
											//DiffMode or Correct
											if ( is_array( $questionData['points'] ) ) {
												$points = $questionData['points'][ $answerIndex ];
											} else {
												$points = $questionData['points'];
											}
										}

										if ( ! empty( $correctAnswer ) || ! empty( $questionData['disCorrect'] ) ) {
											//Correct
											$correct = true;
										}

										// See https://developers.learndash.com/hook/learndash_ques_single_answer_pts/ for examples of this filter.
										/**
										 * Filters points awarded for a single answer type question.
										 *
										 * LearnDash single answer question, allow points to be allocated for not marking an incorrect answer.
										 * Allow all possibility of given answer to be correct answer.
										 *
										 * @param integer    $points         Points awarded to quiz
										 * @param array      $question_data  An array of question data.
										 * @param int|string $answer_index   Index of the answer.
										 * @param mixed      $correct_answer Correct answer for the question.
										 * @param array      $user_response  An array of user response data.
										 */
										$points = apply_filters( 'learndash_ques_single_answer_pts', $points, $questionData, $answerIndex, $correctAnswer, $userResponse );
										/**
										 * Filters whether the answer to the single type question is correct or not.
										 *
										 * @param boolean    $correct        Whether the answer is correct or not.
										 * @param array      $question_data  An array of question data.
										 * @param int|string $answer_index   Index of the answer.
										 * @param mixed      $correct_answer Correct answer for the question.
										 * @param array      $user_response  An array of user response data.
										 */
										$correct = apply_filters( 'learndash_ques_single_answer_correct', $correct, $questionData, $answerIndex, $correctAnswer, $userResponse );
									}
								}
							}

							$extra['r'] = $userResponse;

							if ( ! $quiz->isDisabledAnswerMark() && empty( $questionData['disCorrect'] ) ) {
								if ( ! empty( $questionData['correct'] ) ) {
									$extra['c'] = $questionData['correct'];
								}
							}
							break;

						case 'sort_answer':
						case 'matrix_sort_answer':
							$correct                 = true;
							$questionData['correct'] = self::datapos_array( $question_id, count( $questionData['correct'] ) );

							// Normalize the user response/answers.
							if ( ( is_array( $userResponse ) ) && ( ! empty( $userResponse ) ) ) {
								foreach ( $userResponse as $key => &$value ) {
									$value = sanitize_text_field( wp_unslash( trim( $value ) ) );
								}
								unset( $value );
							}

							if ( ! empty( $questionData['correct'] ) ) {
								foreach ( $questionData['correct'] as $answerIndex => $answer ) {
									if ( ! isset( $userResponse[ $answerIndex ] ) || $userResponse[ $answerIndex ] != $answer ) {
										$correct = false;
									} else {
										if ( is_array( $questionData['points'] ) ) {
											$points += $questionData['points'][ $answerIndex ];
										}
									}
									if ( isset( $userResponse[ $answerIndex ] ) ) {
										$statisticsData->{$answerIndex} = $userResponse[ $answerIndex ];
									} else {
										$statisticsData->{$answerIndex} = '';
									}
								}
							}

							if ( $correct ) {
								if ( ! is_array( $questionData['points'] ) ) {
									$points = $questionData['points'];
								}
							} else {
								$statisticsData = new stdClass();
							}

							$extra['r'] = $userResponse;

							if ( ! $quiz->isDisabledAnswerMark() && empty( $questionData['disCorrect'] ) ) {
								$extra['c'] = $questionData['correct'];
							} else {
								$statisticsData = new stdClass();
							}

							break;

						case 'cloze_answer':
							$answerData = array();

							// Normalize the user response/answers.
							if ( ( is_array( $userResponse ) ) && ( ! empty( $userResponse ) ) ) {
								foreach ( $userResponse as $key => &$value ) {
									if ( ! $question_legacy_sanitize_scheme ) {
										$value = esc_attr( wp_unslash( trim( $value ) ) );
									} else {
										$value = stripslashes( trim( $value ) );
									}
								}
								unset( $value );
							}

							if ( ! empty( $questionData['correct'] ) ) {
								foreach ( $questionData['correct'] as $answerIndex => $correctArray ) {
									$answerData[ $answerIndex ] = false;

									if ( ! isset( $userResponse[ $answerIndex ] ) ) {
										$answerData[ $answerIndex ] = false;
									}

									/**
									 * The default value is based on the opposite of the legacy sanitize var value.
									 *
									 * If the legacy var is 'false' then we probably want to set this var as true since we do
									 * want to format the correct answers.
									 */
									$format_correct = ! $question_legacy_sanitize_scheme;

									/** This filter is documented in includes/quiz/ld-quiz-pro.php */
									$format_correct = apply_filters( 'learndash_quiz_format_correct_answer', $format_correct, $questionData, $questionModel );
									if ( $format_correct ) {
										foreach ( $correctArray as $key => &$value ) {
											$value = esc_attr( wp_unslash( trim( $value ) ) );
										}
										unset( $value );
									}

									/** This filter is documented in includes/lib/wp-pro-quiz/wp-pro-quiz.php */
									if ( apply_filters( 'learndash_quiz_question_cloze_answers_to_lowercase', true ) ) {
										if ( function_exists( 'mb_strtolower' ) ) {
											$user_answer_formatted = mb_strtolower( $userResponse[ $answerIndex ] );
										} else {
											$user_answer_formatted = strtolower( $userResponse[ $answerIndex ] );
										}
									} else {
										$user_answer_formatted = $userResponse[ $answerIndex ];
									}

									$correct_idx = array_search( $user_answer_formatted, $correctArray );
									if ( false !== $correct_idx ) {
										$answerData[ $answerIndex ] = true;
									}

									/**
									 * Filters whether to check the answer of cloze type question.
									 *
									 * @param boolean                  $check_answer    Whether to check the answer.
									 * @param string                   $question_type   Type of the question.
									 * @param string                   $answer          The answer given by user for the question.
									 * @param array                    $correct_answers An array of correct answers for the question.
									 * @param WpProQuiz_Model_Question $question_model  Question model object.
									 */
									$answerData[ $answerIndex ]     = apply_filters( 'learndash_quiz_check_answer', $answerData[ $answerIndex ], $questionData['type'], $userResponse[ $answerIndex ], $correctArray, $answerIndex, $questionModel );
									$statisticsData->{$answerIndex} = $answerData[ $answerIndex ];

									if ( $answerData[ $answerIndex ] === true ) {
										if ( ! isset( $questionData['points'] ) ) {
											$questionData['points'] = 1;
										}
										if ( $questionModel->isAnswerPointsActivated() ) {
											if ( ( is_array( $questionData['points'] ) ) && ( isset( $questionData['points'][ $answerIndex ][ $correct_idx ] ) ) ) {
												$points += (int) $questionData['points'][ $answerIndex ][ $correct_idx ];
											} else {
												$points = $questionData['points'];
											}
										} else {
											$points = $questionData['points'];
										}
									}
								}
							}

							// If we have one wrong answer
							if ( in_array( false, $answerData ) === true ) {
								$correct = false;

								// If we are NOT using individual points and there is at least one wrong answer
								// then we clear the points.
								if ( ! $questionModel->isAnswerPointsActivated() ) {
									$points = 0;
								}
							} else {
								// If all the fields are correct then the points stand and we set the correct to true
								$correct = true;
							}

							$extra['r'] = $userResponse;

							if ( ! $quiz->isDisabledAnswerMark() && empty( $questionData['disCorrect'] ) ) {
								$extra['c'] = $questionData['correct'];
							}
							break;

						case 'assessment_answer':
							// Normalize the user response/answers.
							$userResponse = absint( $userResponse );

							$correct = false;
							$points  = 0;

							if ( ( ! empty( $userResponse ) ) && ( isset( $questionData['correct'][ $userResponse-1 ] ) ) ) {
								$correct = true;
								if ( isset( $questionData['points'][ $userResponse-1 ] ) ) {
									$points = $questionData['points'][ $userResponse-1 ];
								} else {
									$points = 1;
								}
							}

							$extra['r'] = $userResponse;

							break;

						case 'essay':
							if ( ! empty( $userResponse ) ) {
								$essay_data = $questionModel->getAnswerData();

								$essay_data = array_shift( $essay_data );

								switch ( $essay_data->getGradingProgression() ) {
									case '':
									case 'not-graded-none':
										$points                 = 0;
										$correct                = false;
										$extra['graded_status'] = 'not_graded';
										break;

									case 'not-graded-full':
										$points                 = $essay_data->getPoints();
										$correct                = false;
										$extra['graded_status'] = 'not_graded';
										break;

									case 'graded-full':
										$points                 = $essay_data->getPoints();
										$correct                = true;
										$extra['graded_status'] = 'graded';
										break;

									default:
										$points                 = 0;
										$correct                = false;
										$extra['graded_status'] = 'not_graded';
								}

								$essay_id           = learndash_add_new_essay_response( $userResponse, $questionModel, $quiz, $data );
								$extra['graded_id'] = $essay_id;
							} else {
								$points                 = 0;
								$correct                = false;
								$extra['graded_status'] = 'not_graded';
								$extra['graded_id']     = 0;

							}
							break;

						default:
							break;
					}

					if ( ! $quiz->isHideAnswerMessageBox() ) {
						foreach ( $questionModels as $key => $value ) {
							if ( $value->getId() == $question_id ) {
								if ( $correct || $value->isCorrectSameText() ) {
									$extra['AnswerMessage'] = do_shortcode( learndash_the_content( $value->getCorrectMsg(), __FUNCTION__ ) );
								} else {
									$extra['AnswerMessage'] = do_shortcode( learndash_the_content( $value->getIncorrectMsg(), __FUNCTION__ ) );
								}

								break;
							}
						}
					}

					$extra['possiblePoints'] = $questionModel->getPoints();

					$results[ $question_id ] = array(
						'c' => $correct,
						'p' => $points,
						's' => $statisticsData,
						'e' => $extra,
					);

					break;
				}
			}
		}

		/**
		 * Fires after a quiz question is answered.
		 *
		 * @param array                $results         An array of quiz results data.
		 * @param WpProQuiz_Model_Quiz $quiz            WpProQuiz_Model_Quiz object.
		 * @param array                $question_models An array of question model objects.
		 */
		do_action( 'ldadvquiz_answered', $results, $quiz, $questionModels );

		$total_points = 0;

		foreach ( $results as $r_idx => $result ) {

			if ( ( isset( $result['e'] ) ) && ( ! empty( $result['e'] ) ) ) {
				if ( ( isset( $result['e']['type'] ) ) && ( ! empty( $result['e']['type'] ) ) ) {
					$response_str = '';

					switch ( $result['e']['type'] ) {
						case 'essay':
							if ( ( isset( $result['e']['graded_id'] ) ) && ( ! empty( $result['e']['graded_id'] ) ) ) {
								$response_str = maybe_serialize( array( 'graded_id' => $result['e']['graded_id'] ) );
							}
							break;

						case 'free_answer':
							if ( ( isset( $result['e']['r'] ) ) && ( '' !== $result['e']['r'] ) ) {

								$response_str = maybe_serialize( array( trim( $result['e']['r'] ) ) );
							}
							break;

						case 'assessment_answer':
							if ( ( isset( $result['e']['r'] ) ) && ( ! empty( $result['e']['r'] ) ) ) {
								$response_str = maybe_serialize( array( (string) $result['e']['r'] ) );
							}
							break;

						case 'multiple':
						case 'single':
						default:
							if ( ( isset( $result['e']['r'] ) ) && ( ! empty( $result['e']['r'] ) ) ) {
								$result_array = array();
								foreach ( $result['e']['r'] as $ri_idx => $ri ) {
									if ( $ri === true ) {
										$ri = 1;
									} elseif ( $ri === false ) {
										$ri = 0;
									}

									$result_array[ $ri_idx ] = $ri;
								}
								$response_str = maybe_serialize( $result_array );
							}
							break;

							break;
					}

					if ( ! empty( $response_str ) ) {
						$answers_nonce                = wp_create_nonce( 'ld_quiz_anonce' . $user_id . '_' . $id . '_' . $quiz_post_id . '_' . $r_idx . '_' . $response_str );
						$results[ $r_idx ]['a_nonce'] = $answers_nonce;
					}
				}
			}

			$points_array = array(
				'points'         => intval( $result['p'] ),
				'correct'        => intval( $result['c'] ),
				'possiblePoints' => intval( $result['e']['possiblePoints'] ),
			);
			if ( $points_array['correct'] === false ) {
				$points_array['correct'] = 0;
			} elseif ( $points_array['correct'] === true ) {
				$points_array['correct'] = 1;
			}
			$points_str                   = maybe_serialize( $points_array );
			$points_nonce                 = wp_create_nonce( 'ld_quiz_pnonce' . $user_id . '_' . $id . '_' . $quiz_post_id . '_' . $r_idx . '_' . $points_str );
			$results[ $r_idx ]['p_nonce'] = $points_nonce;
		}


		learndash_quiz_debug_log_message( __FUNCTION__ . ': results: ' . print_r( $results, true ) );

		return json_encode( $results );
	}

	/**
	 * Redirect from the Advanced Quiz edit or add link to the Quiz edit or add link
	 *
	 * @since 2.1.0
	 */
	public function quiz_edit_redirect() {

		if ( ! empty( $_GET['page'] ) && $_GET['page'] == 'ldAdvQuiz' && empty( $_GET['module'] ) && ! empty( $_GET['action'] ) && $_GET['action'] == 'addEdit' ) {

			if ( ! empty( $_GET['post_id'] ) ) {
				header( 'Location: ' . admin_url( 'post.php?action=edit&post=' . absint( $_GET['post_id'] ) ) );
				exit;
			} elseif ( ! empty( $_GET['quizId'] ) ) {
				$post_id = learndash_get_quiz_id_by_pro_quiz_id( absint( $_GET['quizId'] ) );

				if ( ! empty( $post_id ) ) {
					header( 'Location: ' . admin_url( 'post.php?action=edit&post=' . absint( $post_id ) ) );
				} else {
					header( 'Location: ' . admin_url( 'edit.php?post_type=sfwd-quiz' ) );
				}

				exit;
			}

			header( 'Location: ' . admin_url( 'post-new.php?post_type=sfwd-quiz' ) );
			exit;
		}
	}



	/**
	 * Echoes quiz content
	 *
	 * @since 2.1.0
	 *
	 * @param  int $pro_quiz_id
	 */
	static function showQuizContent( $pro_quiz_id ) {
		global $post;

		if ( empty( $post ) || $post->post_type == 'sfwd-quiz' ) {
			return '';
		}

		echo self::get_description( $pro_quiz_id );
	}



	/**
	 * Returns the HTML representation of the quiz description
	 *
	 * @since 2.1.0
	 *
	 * @param  int $pro_quiz_id
	 *
	 * @return string HTML representation of quiz description
	 */
	static function get_description( $pro_quiz_id ) {
		$post_id = learndash_get_quiz_id_by_pro_quiz_id( $pro_quiz_id );

		if ( empty( $post_id ) ) {
			return '';
		}

		$quiz = get_post( $post_id );

		if ( empty( $quiz->post_content ) ) {
			return '';
		}

		/**
		 * Filters the description of the quiz.
		 *
		 * @param string $quiz_description The quiz description.
		 */
		$content = apply_filters( 'ldadvquiz_the_content', $quiz->post_content );

		/**
		 * Added call to do_shortcode to process any shortcodes within the quiz content.
		 *
		 * @since 2.6.0
		 */
		$content = do_shortcode( $content );

		$content = str_replace( ']]>', ']]&gt;', $content );
		return "<div class='wpProQuiz_description'>" . $content . '</div>';
	}



	/**
	 * Outputs the debugging message to the error log file
	 *
	 * @since 2.1.0
	 *
	 * @param  string $msg Debugging message
	 */
	public function debug( $msg ) {
	}


	/**
	 * Does the list of questions for this quiz have a graded question in it
	 * Dataset used is not the quizdata saved to user meta, but follows the
	 * Question Model of WpProQuiz
	 *
	 * @since 2.1.0
	 *
	 * @param array $questions
	 *
	 * @return bool
	 */
	static function quiz_has_graded_question( $questions ) {
		$graded_question_types = array( 'essay' );

		foreach ( $questions as $question ) {
			if ( ! is_a( $question, 'WpProQuiz_Model_Question' ) ) {
				continue;
			}

			if ( in_array( $question->getAnswerType(), $graded_question_types ) ) {
				// found one! halt foreach and return true;
				return true;
			}
		}

		// foreach completed without finding any, return false
		return false;
	}



	/**
	 * Checks a users submitted quiz attempt to see if that quiz
	 * has graded questions and if all of them have been graded
	 *
	 * @since 2.2.0
	 *
	 * @param array $quiz_attempt Quiz Attempt data.
	 */
	static function quiz_attempt_has_ungraded_question( $quiz_attempt ) {
		if ( isset( $quiz_attempt['graded'] ) ) {
			foreach ( $quiz_attempt['graded'] as $graded ) {
				if ( 'not_graded' == $graded['status'] ) {
					return true;
				}
			}
		}
		return false;
	}

	/**
	 * This function runs when a quiz is started and is used to set the quiz start timestamp
	 *
	 * @since 2.3.0
	 *
	 * @param array  $quizdata Quiz data array
	 * @param object $user     WP_User object
	 */
	public function set_quiz_status_meta( $quizdata, $user ) {

		if ( empty( $quizdata ) ) {
			return;
		}
		if ( ! ( $user instanceof WP_User ) ) {
			return;
		}

		if ( isset( $quizdata['questions'] ) ) {
			unset( $quizdata['questions'] );
		}

		if ( ( isset( $quizdata['quiz'] ) ) && ( $quizdata['quiz'] instanceof WP_Post ) ) {
			$quiz_post = $quizdata['quiz'];
			unset( $quizdata['quiz'] );
			$quizdata['quiz'] = intval( $quiz_post->ID );
		}

		$course_id = 0;
		$lesson_id = 0;
		$topic_id  = 0;

		if ( ( isset( $quizdata['course'] ) ) && ( $quizdata['course'] instanceof WP_Post ) ) {
			$course_post = $quizdata['course'];
			unset( $quizdata['course'] );
			$quizdata['course'] = intval( $course_post->ID );
			$course_id          = $quizdata['course'];
		}
		if ( ( isset( $quizdata['lesson'] ) ) && ( $quizdata['lesson'] instanceof WP_Post ) ) {
			$lesson_post = $quizdata['lesson'];
			unset( $quizdata['lesson'] );
			$quizdata['lesson'] = intval( $lesson_post->ID );
			$lesson_id          = $quizdata['lesson'];
		}
		if ( ( isset( $quizdata['topic'] ) ) && ( $quizdata['topic'] instanceof WP_Post ) ) {
			$topic_post = $quizdata['topic'];
			unset( $quizdata['topic'] );
			$quizdata['topic'] = intval( $topic_post->ID );
			$topic_id          = $quizdata['topic'];
		}

		if ( ( isset( $quizdata['course'] ) ) && ( ! empty( $quizdata['course'] ) ) ) {
			// Update the Course if this quiz has.
			$course_start_time = learndash_activity_course_get_earliest_started( $user->ID, $quizdata['course'], $quizdata['started'] );
			$course_activity   = learndash_activity_start_course( $user->ID, $quizdata['course'], $course_start_time );
			if ( $course_activity ) {
				learndash_activity_update_meta_set(
					$course_activity->activity_id,
					array(
						'steps_completed' => learndash_course_get_completed_steps( $user->ID, $quizdata['course'] ),
						'steps_last_id'   => $quizdata['quiz'],
					)
				);
			}

			if ( ( isset( $quizdata['lesson'] ) ) && ( ! empty( $quizdata['lesson'] ) ) ) {
				learndash_activity_start_lesson( $user->ID, $quizdata['course'], $quizdata['lesson'], $quizdata['started'] );
			}
			if ( ( isset( $quizdata['topic'] ) ) && ( ! empty( $quizdata['topic'] ) ) ) {
				learndash_activity_start_topic( $user->ID, $quizdata['course'], $quizdata['topic'], $quizdata['started'] );
			}
		}

		LDLMS_User_Quiz_Resume::delete_user_quiz_resume_metadata( $user->ID, $quizdata['quiz'], $quizdata['course'], $quizdata['started'] );

		if ( ( isset( $quizdata['started'] ) ) && ( ! empty( $quizdata['started'] ) ) && ( isset( $quizdata['completed'] ) ) && ( ! empty( $quizdata['completed'] ) ) ) {

			if ( $quizdata['pass'] == true ) {
				$quizdata_pass = true;
			} else {
				$quizdata_pass = false;
			}

			$quiz_args     = array(
				'course_id'          => $quizdata['course'],
				'user_id'            => $user->ID,
				'post_id'            => $quizdata['quiz'],
				'activity_type'      => 'quiz',
				'activity_completed' => 0,
			);
			$quiz_activity = learndash_get_user_activity( $quiz_args );
			if ( ( is_object( $quiz_activity ) ) && ( property_exists( $quiz_activity, 'activity_id' ) ) && ( ! empty( $quiz_activity->activity_id ) ) ) {
				$activity_id = (int) $quiz_activity->activity_id;
			} else {
				$activity_id = 0;
			}
			learndash_update_user_activity(
				array(
					'activity_id'        => $activity_id,
					'course_id'          => absint( $quizdata['course'] ),
					'user_id'            => absint( $user->ID ),
					'post_id'            => absint( $quizdata['quiz'] ),
					'activity_type'      => 'quiz',
					'activity_status'    => $quizdata_pass,
					'activity_started'   => (int) $quizdata['started'],
					'activity_completed' => (int) $quizdata['completed'],
					'activity_meta'      => $quizdata,
				)
			);
		}
	}

	/**
	 * This function runs when a quiz is completed, and does the action 'wp_pro_quiz_completed_quiz'
	 *
	 * @since 2.1.0
	 *
	 * @param integer $statistic_ref_id Quiz Statistics Ref ID.
	 */
	function wp_pro_quiz_completed( $statistic_ref_id = 0 ) {

		learndash_quiz_debug_log_message( 'in ' . __FUNCTION__ );
		learndash_quiz_debug_log_message( 'statistic_ref_id ' . $statistic_ref_id );

		//error_log('_POST<pre>'. print_r($_POST, true) .'</pre>');

		$results      = array();
		$quiz_pro_id  = isset( $_POST['quizId'] ) ? absint( $_POST['quizId'] ) : null;
		$quiz_post_id = isset( $_POST['quiz'] ) ? absint( $_POST['quiz'] ) : null;
		$score        = isset( $_POST['results']['comp']['correctQuestions'] ) ? $_POST['results']['comp']['correctQuestions'] : null;
		$points       = isset( $_POST['results']['comp']['points'] ) ? absint( $_POST['results']['comp']['points'] ) : null;
		$result       = isset( $_POST['results']['comp']['result'] ) ? $_POST['results']['comp']['result'] : null;
		$timespent    = isset( $_POST['timespent'] ) ? floatval( $_POST['timespent'] ) : null;

		if ( ( is_null( $quiz_post_id ) ) || ( is_null( $quiz_pro_id ) ) || ( is_null( $points ) ) ) {
			return json_encode( $results );
		}

		$course_id = ( ( isset( $_POST['course_id'] ) ) && ( intval( $_POST['course_id'] ) > 0 ) ) ? intval( $_POST['course_id'] ) : learndash_get_course_id( $quiz_post_id );
		$lesson_id = ( ( isset( $_POST['lesson_id'] ) ) && ( intval( $_POST['lesson_id'] ) > 0 ) ) ? intval( $_POST['lesson_id'] ) : 0;
		$topic_id  = ( ( isset( $_POST['topic_id'] ) ) && ( intval( $_POST['topic_id'] ) > 0 ) ) ? intval( $_POST['topic_id'] ) : 0;
		if ( is_user_logged_in() ) {
			$user_id = get_current_user_id();
		} else {
			$user_id = 0;
		}

		$quizMapper = new WpProQuiz_Model_QuizMapper();
		$quiz_pro   = $quizMapper->fetch( $quiz_pro_id );
		if ( ( ! $quiz_pro ) || ( ! is_a( $quiz_pro, 'WpProQuiz_Model_Quiz' ) ) ) {
			return json_encode( $results );
		}
		$quiz_pro->setPostId( $quiz_post_id );

		$questionMapper = new WpProQuiz_Model_QuestionMapper();
		$questions      = $questionMapper->fetchAll( $quiz_pro );
		if ( is_array( $questions ) ) {
			$questions_count = count( $questions );
		}

		// check if these set of questions has questions that need to be graded
		$has_graded = self::quiz_has_graded_question( $questions );

		// store the id's of the graded question to be saved in usermeta
		$graded = array();
		foreach ( $_POST['results'] as $question_id => $individual_result ) {
			if ( 'comp' == $question_id ) {
				continue;
			}

			if ( isset( $individual_result['graded_id'] ) && ! empty( $individual_result['graded_id'] ) ) {
				$graded[ $question_id ] = array(
					'post_id'        => intval( $individual_result['graded_id'] ),
					'status'         => esc_html( $individual_result['graded_status'] ),
					'points_awarded' => intval( $individual_result['points'] ),
				);
			}
		}

		if ( empty( $graded ) ) {
			$has_graded = false;
		}

		if ( empty( $result ) ) {
			$total_points = 0;

			//foreach ( $questions as $q ) {
			//	$q_points = $q->getPoints();
			//	error_log('q_points['. $q_points .']');
			//	$total_points += $q->getPoints();
			//}

			// Rewrote logic here to only count points for the questions shown to the user.
			// For example I might have a Quiz showing only 5 of 10 questions. In the above code
			// the points counted inlcude ALL 10 questions. Not correct.
			// Insead we do the logic below and only process the 5 shown questions.
			foreach ( $_POST['results'] as $question_id => $q_result ) {
				if ( 'comp' == $question_id ) {
					continue;
				}

				if ( ( isset( $q_result['possiblePoints'] ) ) && ( ! empty( $q_result['possiblePoints'] ) ) ) {
					$total_points += intval( $q_result['possiblePoints'] );
				}
			}
		} else {
			$total_points = round( $points * 100 / $result );
		}

		$questions_shown_count = count( $_POST['results'] ) - 1;

		if ( ( isset( $_POST['quiz_nonce'] ) ) && ( isset( $_POST['quizId'] ) ) && ( isset( $_POST['quizId'] ) ) ) {
			if ( ! wp_verify_nonce( $_POST['quiz_nonce'], 'sfwd-quiz-nonce-' . absint( $_POST['quiz'] ) . '-' . absint( $_POST['quizId'] ) . '-' . $user_id ) ) {
				return;
			}
		} elseif ( empty( $_SERVER['HTTP_REFERER'] ) ) {
			return;
		}

		$user_quiz_meta = array();
		if ( ! empty( $user_id ) ) {
			$user_quiz_meta = get_user_meta( $user_id, '_sfwd-quizzes', true );
			$user_quiz_meta = maybe_unserialize( $user_quiz_meta );

			if ( ! is_array( $user_quiz_meta ) ) {
				$user_quiz_meta = array();
			}
		}

		$quiz_post_settings = learndash_get_setting( $quiz_post_id );
		if ( ! is_array( $quiz_post_settings ) ) {
			$quiz_post_settings = array();
		}
		if ( ! isset( $quiz_post_settings['passingpercentage'] ) ) {
			$quiz_post_settings['passingpercentage'] = 0;
		}
		$passingpercentage = absint( $quiz_post_settings['passingpercentage'] );

		$pass      = ( $result >= $passingpercentage ) ? 1 : 0;
		$quiz_post = get_post( $quiz_post_id );

		$quizdata = array(
			'quiz'                => $quiz_post_id,
			'score'               => $score,
			'count'               => $questions_count,
			'question_show_count' => $questions_shown_count,
			'pass'                => $pass,
			'rank'                => '-',
			'time'                => time(),
			'pro_quizid'          => $quiz_pro_id,
			'course'              => $course_id,
			'lesson'              => $lesson_id,
			'topic'               => $topic_id,
			'points'              => absint( $points ),
			'total_points'        => absint( $total_points ),
			'percentage'          => $result,
			'timespent'           => $timespent,
			'has_graded'          => ( $has_graded ) ? true : false,
			'statistic_ref_id'    => absint( $statistic_ref_id ),
			'started'             => 0,
			'completed'           => 0,
		);

		//On the timestamps below we divide against 1000 because they were generated via JavaScript which uses milliseconds.
		if ( isset( $_POST['results']['comp']['quizStartTimestamp'] ) ) {
			$quizdata['started'] = intval( $_POST['results']['comp']['quizStartTimestamp'] / 1000 );
		}

		if ( isset( $_POST['results']['comp']['quizEndTimestamp'] ) ) {
			$quizdata['completed'] = intval( $_POST['results']['comp']['quizEndTimestamp'] / 1000 );
		}

		if ( ( isset( $quizdata['started'] ) ) && ( ! empty( $quizdata['started'] ) ) && ( isset( $quizdata['completed'] ) ) && ( ! empty( $quizdata['completed'] ) ) ) {
			$quiz_time_diff  = absint( $quizdata['completed'] ) - absint( $quizdata['started'] );
			$quiz_time_end   = time();
			$quiz_time_start = $quiz_time_end - $quiz_time_diff;

			$quizdata['started']   = $quiz_time_start;
			$quizdata['completed'] = $quiz_time_end;
		} else {
			$quizdata['started']   = 0;
			$quizdata['completed'] = 0;
		}

		if ( ! empty( $graded ) ) {
			$quizdata['graded'] = $graded;
		}

		$quizdata['ld_version'] = LEARNDASH_VERSION;

		$quizdata['quiz_key'] = $quizdata['completed'] . '_' . absint( $quiz_pro_id ) . '_' . absint( $quiz_post_id ) . '_' . absint( $course_id );

		if ( ! empty( $user_id ) ) {
			$user_quiz_meta[] = $quizdata;

			learndash_quiz_debug_log_message( 'calling update_user_meta()' );
			learndash_quiz_debug_log_message( 'quizdata<pre>' . print_r( $quizdata, true ) . '</pre>' );

			// Not sure why this is here.
			//$quizdata['quiz'] = $quiz_post;

			update_user_meta( $user_id, '_sfwd-quizzes', $user_quiz_meta );
		}

		if ( ! empty( $course_id ) ) {
			$quizdata['course'] = get_post( $course_id );
		} else {
			$quizdata['course'] = 0;
		}

		if ( ! empty( $lesson_id ) ) {
			$quizdata['lesson'] = get_post( $lesson_id );
		} else {
			$quizdata['lesson'] = 0;
		}

		if ( ! empty( $topic_id ) ) {
			$quizdata['topic'] = get_post( $topic_id );
		} else {
			$quizdata['topic'] = 0;
		}

		$quizdata['questions'] = $questions;

		if ( ! empty( $user_id ) ) {
			/**
			 * Fires after the quiz is submitted
			 *
			 * @since 3.0.0
			 *
			 * @param array   $quiz_data    An array of quiz data.
			 * @param WP_User $current_user Current user object.
			 */
			do_action( 'learndash_quiz_submitted', $quizdata, get_user_by( 'id', $user_id ) );

			/**
			 * Changed in 2.6.0. If the quiz has essay type questions that are not
			 * auto-graded we don't send out the 'learndash_quiz_completed' action.
			 */
			$send_quiz_completed = true;
			if ( ( isset( $quizdata['has_graded'] ) ) && ( true === $quizdata['has_graded'] ) ) {
				if ( ( isset( $quizdata['graded'] ) ) && ( ! empty( $quizdata['graded'] ) ) ) {
					foreach ( $quizdata['graded'] as $grade_item ) {
						if ( ( isset( $grade_item['status'] ) ) && ( $grade_item['status'] !== 'graded' ) ) {
							$send_quiz_completed = false;
						}
					}
				}
			}

			if ( true === $send_quiz_completed ) {
				if ( ! empty( $course_id ) ) {
					$quiz_parent_post_id = 0;
					if ( ! empty( $topic_id ) ) {
						$quiz_parent_post_id = $topic_id;
					} elseif ( ! empty( $lesson_id ) ) {
						$quiz_parent_post_id = $lesson_id;
					}

					if ( ! empty( $quiz_parent_post_id ) ) {

						/**
						 * Filter to set all parent steps completed.
						 *
						 * @since 4.2.0
						 *
						 * @param boolean $set_all_steps_completed Whether to set all steps completed.
						 * @param int     $quiz_post_id            Quiz post ID.
						 * @param int     $user_id                 User ID.
						 * @param int     $course_id               Course ID.
						 */
						if ( apply_filters( 'learndash_complete_all_parent_steps', true, $quiz_post_id, $user_id, $course_id ) ) {
							if ( ! empty( $topic_id ) ) {
								if ( learndash_can_complete_step( $user_id, $topic_id, $course_id ) ) {
									learndash_process_mark_complete( $user_id, $topic_id, false, $course_id );
								}
							}
							if ( ! empty( $lesson_id ) ) {
								if ( learndash_can_complete_step( $user_id, $lesson_id, $course_id ) ) {
									learndash_process_mark_complete( $user_id, $lesson_id, false, $course_id );
								}
							}
						} else {
							if ( learndash_can_complete_step( $user_id, $quiz_parent_post_id, $course_id ) ) {
								learndash_process_mark_complete( $user_id, $quiz_parent_post_id, false, $course_id );
							}
						}
					} else {
						$all_quizzes_complete = true;
						$quizzes              = learndash_get_global_quiz_list( $course_id );
						if ( ! empty( $quizzes ) ) {
							foreach ( $quizzes as $quiz ) {
								if ( learndash_is_quiz_notcomplete( $user_id, array( $quiz->ID => 1 ), false, $course_id ) ) {
									$all_quizzes_complete = false;
									break;
								}
							}
						}
						if ( true === $all_quizzes_complete ) {
							learndash_process_mark_complete( $user_id, $course_id, false, $course_id );
						}
					}
				}

				/** This action is documented in includes/ld-users.php */
				do_action( 'learndash_quiz_completed', $quizdata, get_user_by( 'id', $user_id ) );
			} elseif ( defined( 'LEARNDASH_QUIZ_ESSAY_SUBMIT_COMPLETED' ) && LEARNDASH_QUIZ_ESSAY_SUBMIT_COMPLETED === true ) {
				/** This action is documented in includes/ld-users.php */
				do_action( 'learndash_quiz_completed', $quizdata, get_user_by( 'id', $user_id ) );
			}
		}

		$results[ $quiz_pro_id ]['quiz_result_settings'] = array(
			'showAverageResult'      => $quiz_pro->isShowAverageResult() ? 1 : 0,
			'showCategoryScore'      => $quiz_pro->isShowCategoryScore() ? 1 : 0,
			'showRestartQuizButton'  => $quiz_pro->isBtnRestartQuizHidden() ? 0 : 1,
			'showResultPoints'       => $quiz_pro->isHideResultPoints() ? 0 : 1,
			//'showResultCorrectQuestion' => $quiz_pro->isHideResultCorrectQuestion() ? 0 : 1,
			'showResultQuizTime'     => $quiz_pro->isHideResultQuizTime() ? 0 : 1,
			//'showAnswerMessageBox'      => $quiz_pro->isHideAnswerMessageBox() ? 0 : 1,
			'showViewQuestionButton' => $quiz_pro->isBtnViewQuestionHidden() ? 0 : 1,
		);
		/** This filter is documented in includes/lib/wp-pro-quiz/lib/view/WpProQuiz_View_FrontQuiz.php */
		$results[ $quiz_pro_id ]['showContinueButton'] = apply_filters( 'show_quiz_continue_buttom_on_fail', false, $quizdata['quiz'] ) ? 1 : 0;

		/**
		 * Filters settings of the completed quiz results.
		 *
		 * @param array $quiz_result_settings An array of quiz result settings data.
		 * @param mixed $quiz_data            An array of quiz data.
		 */
		$results[ $quiz_pro_id ]['quiz_result_settings'] = apply_filters( 'learndash_quiz_completed_result_settings', $results[ $quiz_pro_id ]['quiz_result_settings'], $quizdata );

		//$results[ $quiz_pro_id ]['quiz_result_settings']['showViewQuestionButton'] = 0;
		//$results[ $quiz_pro_id ]['quiz_result_settings']['showRestartQuizButton'] = 0;
		//$results[ $quiz_pro_id ]['quiz_result_settings']['showContinueButton'] = 0;

		echo json_encode( $results );

		// We should not exit here. The calling action source needs to complete the processing and lock.
		//exit();
	}

	/**
	 * Returns an array of quizes in the string format of "$quiz_id - $quiz_name"
	 *
	 * @since 2.1.0
	 *
	 * @return array  $list  String of $q->getId() . ' - ' . $q->getName()
	 */
	static function get_quiz_list() {
		$quizzes_list = array();

		global $wpdb;

		$quiz_items = $wpdb->get_results( $wpdb->prepare( 'SELECT id, name FROM ' . LDLMS_DB::get_table_name( 'quiz_master' ) . ' ORDER BY %s ', 'id' ) );
		if ( ! empty( $quiz_items ) ) {
			foreach ( $quiz_items as $q ) {
				$quizzes_list[ $q->id ] = $q->id . ' - ' . $q->name;
			}
		}
		return $quizzes_list;
	}



	/**
	 * Echoes the HTML with inline javascript that contains the JSON representation of the certificate details and continue link details
	 *
	 * @since 2.1.0
	 *
	 * @param int $pro_quiz_id WPProQuiz ID
	 */
	static function certificate_details( $pro_quiz_id = null ) {

		$quiz_post_id = 0;

		if ( is_null( $pro_quiz_id ) ) {
			global $post;
			if ( ( $post instanceof WP_Post ) && ( $post->post_type == 'sfwd-quiz' ) ) {
				$pro_quiz_id = $post->ID;
			}
		} else {
			if ( is_a( $pro_quiz_id, 'WpProQuiz_Model_Quiz' ) ) {
				$pro_quiz     = $pro_quiz_id;
				$pro_quiz_id  = $pro_quiz->getId();
				$quiz_post_id = $pro_quiz->getPostId();
			} else {
				$quiz_post_id = learndash_get_quiz_id_by_pro_quiz_id( $pro_quiz_id );
			}

			if ( ! empty( $quiz_post_id ) ) {
				$quiz_post = get_post( $quiz_post_id );
				if ( ( $quiz_post instanceof WP_Post ) && ( $quiz_post->post_type == 'sfwd-quiz' ) ) {
					$quiz_post_id = $quiz_post->ID;
				}
			}
		}

		if ( ! empty( $quiz_post_id ) ) {
			$continue_link = learndash_quiz_continue_link( $quiz_post_id );

			echo '<script>';
			echo 'var certificate_details = ' . json_encode( learndash_certificate_details( $quiz_post_id ) ) . ';';
			echo '</script>';

			echo '<script>';
			echo 'var certificate_pending = "' .
				SFWD_LMS::get_template(
					'learndash_quiz_messages',
					array(
						'quiz_post_id' => $quiz_post_id,
						'context'      => 'quiz_certificate_pending_message',
						'message'      => sprintf(
							// translators: questions
							esc_html_x( 'Certificate Pending - %s still need to be graded, please check your profile for the status', 'placeholder: questions', 'learndash' ),
							learndash_get_custom_label( 'questions' )
						),
					)
				) . '";';
			echo '</script>';

			/** Continue link will appear through javascript **/
			echo '<script>';
			echo "var continue_details ='" . $continue_link . "';";
			echo '</script>';
		}
	}

	/**
	 * Returns the certificate link appended to input HTML content if the Post ID is set, else it only returns the input HTML content
	 *
	 * @since 2.1.0
	 *
	 * @param  string $content HTML
	 * @param  mixed  $pro_quiz (integer) WPProQuixz ID, (object) WpProQuiz_Model_Quiz
	 *
	 * @return string HTML $content or $content concatenated with the certificate link
	 */
	static function certificate_link( $content, $pro_quiz = null ) {
		$quiz_post_id = null;
		$pro_quiz_id  = null;

		if ( ! is_null( $pro_quiz ) ) {
			if ( is_a( $pro_quiz, 'WpProQuiz_Model_Quiz' ) ) {
				$pro_quiz_id  = $pro_quiz->getId();
				$quiz_post_id = $pro_quiz->getPostId();
			} else {
				$pro_quiz_id = absint( $pro_quiz );
			}
		}

		if ( empty( $quiz_post_id ) ) {
			if ( empty( $pro_quiz_id ) ) {
				//global $post;
				//if ( ( $post instanceof WP_Post ) && ( $post->post_type == 'sfwd-quiz' ) ) {
				//	$quiz_post_id = $post->ID;
				//}

				$post_id = get_the_ID();
				if ( ! empty( $post_id ) ) {
					$quiz_post = get_post( $post_id );
					if ( ( $quiz_post instanceof WP_Post ) && ( $quiz_post->post_type == 'sfwd-quiz' ) ) {
						$quiz_post_id = $quiz_post->ID;
					}
				}
			}

			if ( empty( $quiz_post_id ) ) {
				$quiz_post_id = learndash_get_quiz_id_by_pro_quiz_id( $pro_quiz_id );
				if ( ! empty( $quiz_post_id ) ) {
					$quiz_post = get_post( $quiz_post_id );
					if ( ( $quiz_post instanceof WP_Post ) && ( $quiz_post->post_type == 'sfwd-quiz' ) ) {
						$quiz_post_id = $quiz_post->ID;
					}
				}
			}
		} else {
			$quiz_post = get_post( $quiz_post_id );
			if ( ( $quiz_post instanceof WP_Post ) && ( $quiz_post->post_type == 'sfwd-quiz' ) ) {
				$quiz_post_id = $quiz_post->ID;
			} else {
				$quiz_post_id = 0;
			}
		}

		if ( ! empty( $quiz_post_id ) ) {
			$cd = learndash_certificate_details( $quiz_post_id );
			if ( ( ! empty( $cd ) ) && ( isset( $cd['certificateLink'] ) ) && ( ! empty( $cd['certificateLink'] ) ) ) {
				$user_id = get_current_user_id();
				/** This filter is documented in includes/ld-certificates.php */
				$ret      = "<a class='btn-blue' href='" . $cd['certificateLink'] . "' target='_blank'>" . apply_filters(
					'ld_certificate_link_label',
					SFWD_LMS::get_template(
						'learndash_quiz_messages',
						array(
							'quiz_post_id' => $quiz_post_id,
							'context'      => 'quiz_certificate_button_label',
							'message'      => esc_html__( 'PRINT YOUR CERTIFICATE', 'learndash' ),
						)
					),
					$user_id,
					$quiz_post_id
				) . '</a>';
				$content .= $ret;
			}
		}

		return $content;
	}



	/**
	 * Returns the HTML of the add or edit page for the current quiz.  If advanced quizes are disabled, it returns an empty string.
	 *
	 * @since 2.1.0
	 *
	 * @return string
	 */
	static function edithtml() {
		global $pagenow, $post;
		$_post = array( '1' );

		if ( ! empty( $_GET['templateLoadId'] ) ) {
			$_post = $_GET;
		}

		if ( $pagenow == 'post-new.php' && @$_GET['post_type'] == 'sfwd-quiz' || $pagenow == 'post.php' && ! empty( $_GET['post'] ) && @get_post( $_GET['post'] )->post_type == 'sfwd-quiz' ) {
			//To fix issues with plugins using get_current_screen
			$screen_file = ABSPATH . '/wp-admin/includes/screen.php';
			require_once $screen_file;
			//To fix issues with plugins using get_current_screen

			$quizId  = 0;
			$post_id = 0;
			if ( ! empty( $_GET['post'] ) ) {
				$post_id = intval( $_GET['post'] );
				$quizId  = intval( learndash_get_setting( $post_id, 'quiz_pro', true ) );

				/** This filter is documented in includes/admin/classes-posts-edits/class-learndash-admin-quiz-edit.php */
				if ( apply_filters( 'learndash_disable_advance_quiz', false, $post_id ) ) {
					return '';
				}
			} else {
				global $post;
				if ( ( is_a( $post, 'WP_Post' ) ) && ( $post->post_type == 'sfwd-quiz' ) ) {
					//error_log('post<pre>'. print_r($post, true) .'</pre>');
					$post_id = $post->ID;
				}
			}

			$pro_quiz = new WpProQuiz_Controller_Quiz();

			ob_start();
			$pro_quiz->route(
				array(
					'action'  => 'addEdit',
					'quizId'  => $quizId,
					'post_id' => $post_id,
				),
				$_post
			);
			$return = ob_get_clean();

			return $return;
		}
	}



	/**
	 * Routes to the WpProQuiz_Controller_Quiz controller to output the add or edit page for quizes if not autosaving, post id is set,
	 *   and the current user has permissions to add or edit quizes.  If there is an available template to load, WordPress redirects to
	 *   the proper URL.
	 *
	 * @since 2.1.0
	 *
	 * @param int $post_id Post ID
	 */
	static function edit_process( $post_id ) {
		if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
			return;
		}

		if ( empty( $post_id ) || empty( $_POST['post_type'] ) ) {
			return '';
		}

		// Check permissions
		if ( 'page' == $_POST['post_type'] ) {
			if ( ! current_user_can( 'edit_page', $post_id ) ) {
				return;
			}
		} else {
			if ( ! current_user_can( 'edit_post', $post_id ) ) {
				return;
			}
		}

		$post = get_post( $post_id );

		/** This filter is documented in includes/admin/classes-posts-edits/class-learndash-admin-quiz-edit.php */
		if ( 'sfwd-quiz' != $post->post_type || empty( $_POST['form'] ) || ! empty( $_POST['disable_advance_quiz_save'] ) || apply_filters( 'learndash_disable_advance_quiz', false, $post ) ) {
			return;
		}

		$quizId   = intval( learndash_get_setting( $post_id, 'quiz_pro', true ) );
		$pro_quiz = new WpProQuiz_Controller_Quiz();
		//ob_start();
		//$pro_quiz->route( array( 'action' => 'addEdit', 'quizId' => $quizId, 'post_id' => $post_id) );
		//ob_get_clean();
		$pro_quiz->route(
			array(
				'action'  => 'addUpdateQuiz',
				'quizId'  => $quizId,
				'post_id' => $post_id,
			)
		);

		if ( ! empty( $_POST['templateLoad'] ) && ! empty( $_POST['templateLoadId'] ) ) {
			$url = admin_url( 'post.php?post=' . $post_id . '&action=edit' ) . '&templateLoad=' . rawurlencode( $_POST['templateLoad'] ) . '&templateLoadId=' . $_POST['templateLoadId'];
			learndash_safe_redirect( $url );
		}
	}



	/**
	 * Returns a MD5 checksum on a concatenated string comprised of user id, question id, and pos
	 *
	 * @since 2.1.0
	 *
	 * @param int $question_id Question ID
	 * @param int $pos         Postiion
	 *
	 * @return string   MD5 Checksum
	 */
	static function datapos( $question_id, $pos ) {
		$pos = intval( $pos );

		return md5( get_current_user_id() . $question_id . $pos );
	}



	/**
	 * Returns an array of MD5 Checksums on a concatenated string comprised of user id, question id, and i, where the array size is count and i is incremented from 0 for each array element
	 *
	 * @since 2.1.0
	 *
	 * @param  int      $question_id Question ID
	 * @param  int      $count       Count
	 *
	 * @return array    Array of MD5 checksum strings
	 */
	static function datapos_array( $question_id, $count ) {
		$datapos_array = array();
		$user_id       = get_current_user_id();

		for ( $i = 0; $i < $count; $i++ ) {
			$datapos_array[ $i ] = md5( $user_id . $question_id . $i );
		}

		return $datapos_array;
	}

	/**
	 * Show Modal Window
	 *
	 * @since 2.3.0
	 */
	static function showModalWindow() {
		static $show_only_once = false;

		/**
		 * Added for LEARNDASH-2754 to prevent loading the inline CSS when inside
		 * the Gutenberg editor publish/update. Need a better way to handle this.
		 */
		if ( defined( 'REST_REQUEST' ) && REST_REQUEST ) {
			return false;
		}

		if ( ! $show_only_once ) {
			$show_only_once = true;
			?>
			<style>
			.wpProQuiz_blueBox {
				padding: 20px;
				background-color: rgb(223, 238, 255);
				border: 1px dotted;
				margin-top: 10px;
			}
			.categoryTr th {
				background-color: #F1F1F1;
			}
			.wpProQuiz_modal_backdrop {
				background: #000;
				opacity: 0.7;
				top: 0;
				bottom: 0;
				right: 0;
				left: 0;
				position: fixed;
				z-index: 159900;
			}
			.wpProQuiz_modal_window {
				position: fixed;
				background: #FFF;
				top: 40px;
				bottom: 40px;
				left: 40px;
				right: 40px;
				z-index: 160000;
			}
			.wpProQuiz_actions {
				display: none;
				padding: 2px 0 0;
			}

			.mobile .wpProQuiz_actions {
				display: block;
			}

			tr:hover .wpProQuiz_actions {
				display: block;
			}
			</style>
			<div id="wpProQuiz_user_overlay" style="display: none;">
				<div class="wpProQuiz_modal_window" style="padding: 20px; overflow: scroll;">
					<input type="button" value="<?php esc_html_e( 'Close', 'learndash' ); ?>" class="button-primary" style=" position: fixed; top: 48px; right: 59px; z-index: 160001;" id="wpProQuiz_overlay_close">

					<div id="wpProQuiz_user_content" style="margin-top: 20px;"></div>

					<div id="wpProQuiz_loadUserData" class="wpProQuiz_blueBox" style="background-color: #F8F5A8; display: none; margin: 50px;">
						<img alt="load" src="<?php echo admin_url( '/images/wpspin_light.gif' ); ?>" />
						<?php esc_html_e( 'Loading', 'learndash' ); ?>
					</div>
				</div>
				<div class="wpProQuiz_modal_backdrop"></div>
			</div>
			<?php
		}
	}

	/**
	 * Quiz Content
	 *
	 * @since 2.3.0
	 *
	 * @param string $quiz_content Quiz Content.
	 * @param object $quiz_post    WP_Post Quiz object.
	 */
	function learndash_quiz_content( $quiz_content, WP_Post $quiz_post ) {
		return $quiz_content;

		//error_log('in '. __FUNCTION__ );
		//error_log('quiz_content['. $quiz_content .']');
		//error_log('post<pre>'. print_r($post, true) .'</pre>');

		//$user_quiz_progress = get_user_meta( 1, '_sfwd-quizzes', true);
		//error_log('user_quiz_progress<pre>'. print_r($user_quiz_progress, true) .'</pre>');

		// First we get the wp_pro_quiz_id from the post meta for this
		$wp_pro_quiz_id = get_post_meta( $quiz_post->ID, 'quiz_pro_id', true );
		//error_log('wp_pro_quiz_id['. $wp_pro_quiz_id .']');

		$user_id = get_current_user_id();

		if ( ( ! empty( $wp_pro_quiz_id ) ) && ( ! empty( $user_id ) ) ) {

			global $wpdb;
			$sql_str                       = $wpdb->prepare( 'SELECT statistic_ref_id FROM ' . LDLMS_DB::get_table_name( 'quiz_statistic_ref' ) . ' WHERE quiz_id=%d AND user_id=%d ORDER BY create_time DESC', $wp_pro_quiz_id, $user_id );
			$quiz_post_id_statistic_ref_id = $wpdb->get_var( $sql_str );
			if ( ! empty( $quiz_post_id_statistic_ref_id ) ) {
				$sql_str = $wpdb->prepare(
					'SELECT * FROM ' . LDLMS_DB::get_table_name( 'quiz_statistic' ) . ' WHERE statistic_ref_id=%d',
					$quiz_post_id_statistic_ref_id
				);
				//error_log('sql_str['. $sql_str .']');
				$quiz_post_id_statistics = $wpdb->get_results( $sql_str );
				//error_log('quiz_post_id_statistics<pre>'. print_r($quiz_post_id_statistics, true) .'</pre>');
				if ( ! empty( $quiz_post_id_statistics ) ) {
					$quiz_statistics_data           = array();
					$quiz_statistics_data['data']   = $quiz_post_id_statistics;
					$quiz_statistics_data['button'] = '<input type="button" name="viewStatistics" value="' . esc_html_x( 'View Previous Answers', 'Previous Quiz Button Label', 'learndash' ) . '" class="wpProQuiz_button">';
					$quiz_content                  .= '<div id="learndash-quiz-statistics" data="' . htmlspecialchars( json_encode( $quiz_statistics_data ) ) . '">';
				}
			}
		}

		return $quiz_content;
	}


}

new LD_QuizPro();

/**
 * Gets the list of quizzes not associated with any course.
 *
 * This function will query and return all global.
 * A GLOBAL Quizzes is:
 * 1. Quizzes not associated with a Course.
 *
 * @global wpdb $wpdb WordPress database abstraction object.
 *
 * @since 2.6.0
 *
 * @param boolean $bypass_transient Optional. Whether to bypass the transient cache. Default false.
 *
 * @return array An array of quiz IDs.
 */
function learndash_get_non_course_qizzes( $bypass_transient = false ) {
	global $wpdb;

	$global_quiz_ids = array();

	$transient_key = 'learndash_global_quiz_ids';
	if ( ! $bypass_transient ) {
		$global_quiz_ids_transient = LDLMS_Transients::get( $transient_key );
	} else {
		$global_quiz_ids_transient = false;
	}

	if ( false === $global_quiz_ids_transient ) {

		$global_quiz_ids_query_str = "SELECT posts.ID FROM {$wpdb->posts} as posts
			LEFT JOIN {$wpdb->postmeta} as postmeta1 ON posts.ID = postmeta1.post_id AND postmeta1.meta_key LIKE 'ld_course%'
			LEFT JOIN {$wpdb->postmeta} as postmeta2 ON posts.ID = postmeta2.post_id AND postmeta2.meta_key = 'course_id'
			WHERE posts.post_type = 'sfwd-quiz'
				AND ( postmeta1.post_id IS NULL AND postmeta2.post_id IS NULL )";

		$global_quiz_ids = $wpdb->get_col( $global_quiz_ids_query_str );
		LDLMS_Transients::set( $transient_key, $global_quiz_ids, MINUTE_IN_SECONDS );
	} else {
		$global_quiz_ids = $global_quiz_ids_transient;
	}

	return $global_quiz_ids;
}

/**
 * Gets all the open quizzes.
 *
 * This function will query and return all open Quizzes.
 * An OPEN Quiz is:
 * 1. Not associated with a Course.
 * 2. The Quiz setting "Only registered users are allowed to start the quiz" is NOT set.
 *
 * @global wpdb $wpdb WordPress database abstraction object.
 *
 * @since 2.6.0
 *
 * @param boolean $bypass_transient Optional. Whether to bypass the transient cache. Default false.
 *
 * @return array An array of Quiz IDs.
 */
function learndash_get_open_quizzes( $bypass_transient = false ) {
	global $wpdb;

	$open_quiz_ids = array();

	$transient_key = 'learndash_global_quiz_ids';
	if ( ! $bypass_transient ) {
		$open_quiz_ids_transient = LDLMS_Transients::get( $transient_key );
	} else {
		$open_quiz_ids_transient = false;
	}

	if ( false === $open_quiz_ids_transient ) {

		$global_quiz_ids = learndash_get_non_course_qizzes();
		if ( ! empty( $global_quiz_ids ) ) {
			$open_quiz_ids_query_str = "SELECT posts.ID FROM {$wpdb->posts} as posts
				LEFT JOIN {$wpdb->postmeta} as postmeta1 ON posts.ID = postmeta1.post_id AND postmeta1.meta_key = 'quiz_pro_id'
				LEFT JOIN " . LDLMS_DB::get_table_name( 'quiz_master' ) . " as quiz_master ON postmeta1.meta_value = quiz_master.id
				WHERE posts.post_type = 'sfwd-quiz'
					AND posts.ID IN (" . implode( ',', $global_quiz_ids ) . ')
					AND quiz_master.start_only_registered_user = 0';

			$open_quiz_ids = $wpdb->get_col( $open_quiz_ids_query_str );
			LDLMS_Transients::set( $transient_key, $open_quiz_ids, MINUTE_IN_SECONDS );
		}
	} else {
		$open_quiz_ids = $open_quiz_ids_transient;
	}

	return $open_quiz_ids;
}


$quiz_debug_error_log_file = '';
global $quiz_debug_error_log_file;

/**
 * Quiz Debug Log Init
 *
 * @since 3.2.3
 *
 * @param integer $quiz_id Quiz ID
 */
function learndash_quiz_debug_log_init( $quiz_id = 0 ) {
	global $quiz_debug_error_log_file;

	if ( defined( 'LEARNDASH_QUIZ_DEBUG' ) && LEARNDASH_QUIZ_DEBUG ) {
		$user_id      = get_current_user_id();
		$ld_debug_dir = dirname( LEARNDASH_TEMPLATES_DIR ) . '/debug';

		if ( ! file_exists( $ld_debug_dir ) ) {
			if ( ! is_writable( dirname( $ld_debug_dir ) ) ) {
				return false;
			}

			if ( wp_mkdir_p( $ld_debug_dir ) === false ) {
				return false;
			}
		}

		learndash_put_directory_index_file( trailingslashit( $ld_debug_dir ) . 'index.php' );

		Learndash_Admin_File_Download_Handler::register_file_path(
			'learndash-debug',
			$ld_debug_dir
		);

		Learndash_Admin_File_Download_Handler::try_to_protect_file_path(
			$ld_debug_dir
		);

		$date_time                 = learndash_adjust_date_time_display( time(), 'Ymd' );
		$quiz_debug_error_log_file = trailingslashit( $ld_debug_dir ) . 'ld_debug_quiz_' . $date_time . '_' . absint( $user_id ) . '_' . absint( $quiz_id ) . '.log';
		return $quiz_debug_error_log_file;
	}
}

/**
 * Quiz Debug Log Message
 *
 * @since 3.2.3
 *
 * @param string $message Message
 */
function learndash_quiz_debug_log_message( $message = '' ) {
	global $quiz_debug_error_log_file;

	if ( defined( 'LEARNDASH_QUIZ_DEBUG' ) && LEARNDASH_QUIZ_DEBUG ) {
		if ( ( ! empty( $message ) ) && ( ! empty( $quiz_debug_error_log_file ) ) ) {
			if ( ! file_exists( $quiz_debug_error_log_file ) ) {
				if ( ! is_writable( dirname( $quiz_debug_error_log_file ) ) ) {
					return false;
				}
			} else {
				if ( ! is_writable( $quiz_debug_error_log_file ) ) {
					return false;
				}
			}

			$user_id   = get_current_user_id();
			$date_time = learndash_adjust_date_time_display( time(), 'Y-m-d H:i:s' );
			file_put_contents( $quiz_debug_error_log_file, $date_time . ' - ' . $user_id . ' - ' . $message . "\r\n", FILE_APPEND );
		}
	}
}


/**
 * Utility function to fetch the WPProQuiz Question from ID.
 *
 * @since 3.5.0
 * @param int $question_pro_id The WPProQuiz Question ID.
 * @return
 */
function fetchQuestionModel( $question_pro_id = 0 ) {
	if ( ! empty( $question_pro_id ) ) {
		$question_mapper = new WpProQuiz_Model_QuestionMapper();
		return $question_mapper->fetch( $question_pro_id );
	}
}