achievement-functions.php 52.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
<?php
/**
 * Achievement Functions.
 *
 * @package BadgeOS
 * @subpackage Achievements
 * @author LearningTimes, LLC
 * @license http://www.gnu.org/licenses/agpl.txt GNU AGPL v3.0
 * @link https://credly.com
 */

/**
 * Check if post is a registered BadgeOS achievement.
 *
 * @since  1.3.0
 *
 * @param  object|int $post Post object or ID.
 * @return bool             True if post is an achievement, otherwise false.
 */
function badgeos_is_achievement( $post = null ) {

	// Assume we are working with an achievment object.
	$return = true;

	// If post type is NOT a registered achievement type, it cannot be an achievement.
	if ( ! in_array( badgeos_utilities::get_post_type( $post ), badgeos_get_achievement_types_slugs(), true ) ) {
		$return = false;
	}

	// If we pass both previous tests, this is a valid achievement (with filter to override).
	return apply_filters( 'badgeos_is_achievement', $return, $post );
}

/**
 * Get an array of achievements i.e. id/title pair.
 *
 * @since  1.0.0
 * @param  array $args An array of our relevant arguments.
 * @return array       An array of the queried achievements.
 */
function badgeos_get_achievements_id_title_pair( $args = array() ) {

	// Setup our defaults
	$defaults = array(
		'post_type'                => badgeos_get_achievement_types_slugs(),
		'suppress_filters'         => false,
		'achievement_relationsihp' => 'any',
	);
	$args     = wp_parse_args( $args, $defaults );

	// Hook join functions for joining to P2P table to retrieve the parent of an acheivement.
	if ( isset( $args['parent_of'] ) ) {
		add_filter( 'posts_join', 'badgeos_get_achievements_parents_join' );
		add_filter( 'posts_where', 'badgeos_get_achievements_parents_where', 10, 2 );
	}

	// Hook join functions for joining to P2P table to retrieve the children of an acheivement.
	if ( isset( $args['children_of'] ) ) {
		add_filter( 'posts_join', 'badgeos_get_achievements_children_join', 10, 2 );
		add_filter( 'posts_where', 'badgeos_get_achievements_children_where', 10, 2 );
		add_filter( 'posts_orderby', 'badgeos_get_achievements_children_orderby' );
	}

	// Get our achievement posts.
	$achievements = get_posts( $args );
	$achs_array   = array();
	foreach ( $achievements as $achievement ) {
		$achs_array[ $achievement->ID ] = $achievement->post_title;
	}
	// Remove all our filters
	remove_filter( 'posts_join', 'badgeos_get_achievements_parents_join' );
	remove_filter( 'posts_where', 'badgeos_get_achievements_parents_where' );
	remove_filter( 'posts_join', 'badgeos_get_achievements_children_join' );
	remove_filter( 'posts_where', 'badgeos_get_achievements_children_where' );
	remove_filter( 'posts_orderby', 'badgeos_get_achievements_children_orderby' );

	return $achs_array;
}

/**
 * Get an array of achievements.
 *
 * @since  1.0.0
 * @param  array $args An array of our relevant arguments.
 * @return array       An array of the queried achievements.
 */
function badgeos_get_achievements( $args = array() ) {

	// Setup our defaults.
	$defaults = array(
		'post_type'                => badgeos_get_achievement_types_slugs(),
		'suppress_filters'         => false,
		'achievement_relationsihp' => 'any',
	);
	$args     = wp_parse_args( $args, $defaults );

	// Hook join functions for joining to P2P table to retrieve the parent of an acheivement.
	if ( isset( $args['parent_of'] ) ) {
		add_filter( 'posts_join', 'badgeos_get_achievements_parents_join' );
		add_filter( 'posts_where', 'badgeos_get_achievements_parents_where', 10, 2 );
	}

	// Hook join functions for joining to P2P table to retrieve the children of an acheivement.
	if ( isset( $args['children_of'] ) ) {
		add_filter( 'posts_join', 'badgeos_get_achievements_children_join', 10, 2 );
		add_filter( 'posts_where', 'badgeos_get_achievements_children_where', 10, 2 );
		add_filter( 'posts_orderby', 'badgeos_get_achievements_children_orderby' );
	}

	// Get our achievement posts.
	$achievements = get_posts( $args );

	// Remove all our filters
	remove_filter( 'posts_join', 'badgeos_get_achievements_parents_join' );
	remove_filter( 'posts_where', 'badgeos_get_achievements_parents_where' );
	remove_filter( 'posts_join', 'badgeos_get_achievements_children_join' );
	remove_filter( 'posts_where', 'badgeos_get_achievements_children_where' );
	remove_filter( 'posts_orderby', 'badgeos_get_achievements_children_orderby' );

	return $achievements;
}

/**
 * Modify the WP_Query Join filter for achievement children.
 *
 * @since  1.0.0
 * @param  string $join         The query "join" string.
 * @param  object $query_object The complete query object.
 * @return string               The updated "join" string.
 */
function badgeos_get_achievements_children_join( $join = '', $query_object = null ) {
	global $wpdb;
	$join .= " LEFT JOIN $wpdb->p2p AS p2p ON p2p.p2p_from = $wpdb->posts.ID";
	if ( isset( $query_object->query_vars['achievement_relationship'] ) && $query_object->query_vars['achievement_relationship'] !== 'any' ) {
		$join .= " LEFT JOIN $wpdb->p2pmeta AS p2pm1 ON p2pm1.p2p_id = p2p.p2p_id";
	}
	$join .= " LEFT JOIN $wpdb->p2pmeta AS p2pm2 ON p2pm2.p2p_id = p2p.p2p_id";
	return $join;
}

/**
 * Modify the WP_Query Where filter for achievement children.
 *
 * @since  1.0.0
 * @param  string $where        The query "where" string.
 * @param  object $query_object The complete query object.
 * @return string               The updated query "where" string.
 */
function badgeos_get_achievements_children_where( $where = '', $query_object = '' ) {
	global $wpdb;
	if ( isset( $query_object->query_vars['achievement_relationship'] ) && $query_object->query_vars['achievement_relationship'] === 'required' ) {
		$where .= " AND p2pm1.meta_key ='Required'";
	}

	if ( isset( $query_object->query_vars['achievement_relationship'] ) && $query_object->query_vars['achievement_relationship'] === 'optional' ) {
		$where .= " AND p2pm1.meta_key ='Optional'";
	}
	// ^^ TODO, add required and optional. right now just returns all achievemnts.
	$where .= " AND p2pm2.meta_key ='order'";
	$where .= $wpdb->prepare( ' AND p2p.p2p_to = %d', $query_object->query_vars['children_of'] );
	return $where;
}

/**
 * Modify the WP_Query OrderBy filter for achievement children.
 *
 * @since  1.0.0
 * @param  string $orderby The query "orderby" string.
 * @return string          The updated "orderby" string.
 */
function badgeos_get_achievements_children_orderby( $orderby = '' ) {
	return $orderby = 'p2pm2.meta_value ASC';
}

/**
 * Modify the WP_Query Join filter for achievement parents.
 *
 * @since  1.0.0
 * @param  string $join The query "join" string.
 * @return string       The updated "join" string.
 */
function badgeos_get_achievements_parents_join( $join = '' ) {
	global $wpdb;
	$join .= " LEFT JOIN $wpdb->p2p AS p2p ON p2p.p2p_to = $wpdb->posts.ID";
	return $join;
}

/**
 * Modify the WP_Query Where filter for achievement parents.
 *
 * @since  1.0.0
 * @param  string $where The query "where" string.
 * @param  object $query_object The complete query object.
 * @return string        appended sql where statement.
 */
function badgeos_get_achievements_parents_where( $where = '', $query_object = null ) {
	global $wpdb;
	$where .= $wpdb->prepare( ' AND p2p.p2p_from = %d', $query_object->query_vars['parent_of'] );
	return $where;
}

/**
 * Get BadgeOS Achievement Types.
 *
 * Returns a multidimensional array of slug, single name and.
 * plural name for all achievement types.
 *
 * @since  1.0.0
 * @return array An array of our registered achievement types.
 */
function badgeos_get_achievement_types() {
	return $GLOBALS['badgeos']->achievement_types;
}

/**
 * Get BadgeOS Achievement Type Slugs.
 *
 * @since  1.0.0
 * @return array An array of all our registered achievement type slugs (empty array if none).
 */
function badgeos_get_achievement_types_slugs() {

	// Assume we have no registered achievement types.
	$achievement_type_slugs = array();

	// If we do have any achievement types, loop through each and add their slug to our array.
	if ( isset( $GLOBALS['badgeos']->achievement_types ) && ! empty( $GLOBALS['badgeos']->achievement_types ) ) {
		foreach ( $GLOBALS['badgeos']->achievement_types as $slug => $data ) {
			$achievement_type_slugs[] = $slug;
		}
	}

	// Finally, return our data.
	return $achievement_type_slugs;
}

/**
 * Get an achievement's parent posts.
 *
 * @since  1.0.0
 * @param  integer $achievement_id The given achievment's post ID.
 * @return object|bool                 The post object of the achievement's parent, or false if none.
 */
function badgeos_get_parent_of_achievement( $achievement_id = 0 ) {

	// Grab the current post ID if no achievement_id was specified.
	if ( ! $achievement_id ) {
		global $post;

		if ( ! $post ) {
			return false; }
		$achievement_id = $post->ID;
	}

	// Grab our achievement's parent.
	$parents = badgeos_get_achievements( array( 'parent_of' => $achievement_id ) );

	// If it has a parent, return it, otherwise return false.
	if ( ! empty( $parents ) ) {
		return $parents[0];
	} else {
		return false;
	}
}

/**
 * Get an achievement's children posts.
 *
 * @since  1.0.0
 * @param  integer $achievement_id The given achievment's post ID.
 * @return array                   An array of our achievment's children (empty if none).
 */
function badgeos_get_children_of_achievement( $achievement_id = 0 ) {

	// Grab the current post ID if no achievement_id was specified.
	if ( ! $achievement_id ) {
		global $post;
		$achievement_id = $post->ID;
	}

	// Grab and return our achievement's children.
	return badgeos_get_achievements( array( 'children_of' => $achievement_id ) );
}

/**
 * Check if the achievement's child achievements must be earned sequentially.
 *
 * @since  1.0.0
 * @param  integer $achievement_id The given achievment's post ID.
 * @return bool                    True if steps are sequential, false otherwise.
 */
function badgeos_is_achievement_sequential( $achievement_id = 0 ) {

	// Grab the current post ID if no achievement_id was specified.
	if ( ! $achievement_id ) {
		global $post;
		$achievement_id = $post->ID;
	}

	// If our achievement requires sequential steps, return true, otherwise false.
	if ( badgeos_utilities::get_post_meta( $achievement_id, '_badgeos_sequential', true ) ) {
		return true;
	} else {
		return false;
	}
}

/**
 * Check if user has already earned an achievement the maximum number of times.
 *
 * @since  1.0.0
 * @param  integer $user_id        The given user's ID.
 * @param  integer $achievement_id The given achievement's post ID.
 * @return bool                    True if we've exceed the max possible earnings, false if we're still eligable.
 */
function badgeos_achievement_user_exceeded_max_earnings( $user_id = 0, $achievement_id = 0 ) {

	$max_earnings = badgeos_utilities::get_post_meta( $achievement_id, '_badgeos_maximum_earnings', true );

	// Infinite maximum earnings check.
	if ( $max_earnings === '-1' ) {
		return false;
	}

	// If the badge has an earning limit, and we've earned it bdfore...
	if ( $max_earnings && $user_has_badge = badgeos_get_user_achievements(
		array(
			'user_id'        => absint( $user_id ),
			'achievement_id' => absint( $achievement_id ),
		)
	) ) {
		// If we've earned it as many (or more) times than allowed,.
		// then we have exceeded maximum earnings, thus true.
		if ( count( $user_has_badge ) >= $max_earnings ) {
			return true;
		}
	}

	// The post has no limit, or we're under it.
	return false;
}

/**
 * Helper function for building an object for our achievement.
 *
 * @since  1.0.0
 * @param  integer $achievement_id The given achievement's post ID.
 * @param  string  $context        The context in which we're creating this object.
 * @return object                  Our object containing only the relevant bits of information we want.
 */
function badgeos_build_achievement_object( $achievement_id = 0, $context = 'earned', $trigger = '', $image = '', $rec_type = 'normal' ) {

	// Grab the new achievement's $post data, and bail if it doesn't exist.
	$achievement = badgeos_utilities::badgeos_get_post( $achievement_id );
	if ( is_null( $achievement ) ) {
		return false;
	}

	// Setup a new object for the achievement.
	$achievement_object              = new stdClass();
	$achievement_object->ID          = $achievement_id;
	$achievement_object->title       = $achievement->post_title;
	$achievement_object->the_trigger = $trigger;
	$achievement_object->post_type   = $achievement->post_type;
	$achievement_object->image       = $image;
	$achievement_object->rec_type    = $rec_type;

	$points = badgeos_utilities::get_post_meta( $achievement_id, '_badgeos_points', true );
	if ( isset( $points ) && is_array( $points ) && count( $points ) > 0 ) {
		$point_value                    = $points['_badgeos_points'];
		$points_type                    = $points['_badgeos_points_type'];
		$achievement_object->points     = $point_value;
		$achievement_object->point_type = $points_type;
	} else {
		$achievement_object->points     = 0;
		$achievement_object->point_type = '';
	}

	if ( ! empty( $trigger ) ) {
		$achievement_object->trigger = $trigger;
	} else {
		$achievement_object->trigger = '';
	}

	// Store the current timestamp differently based on context.
	if ( 'earned' === $context ) {
		$achievement_object->date_earned = time();
	} elseif ( 'started' === $context ) {
		$achievement_object->date_started = $achievement_object->last_activity_date = time();
	}

	// Return our achievement object, available filter so we can extend it elsewhere.
	return apply_filters( 'achievement_object', $achievement_object, $achievement_id, $context );

}

/**
 * Get an array of post IDs for achievements that are marked as "hidden".
 *
 * @since  1.0.0
 * @param  string $achievement_type Limit the array to a specific type of achievement.
 * @return array                    An array of hidden achievement post IDs.
 */
function badgeos_get_hidden_achievement_ids( $achievement_type = '' ) {

	// Assume we have no hidden achievements.
	$hidden_ids = array();

	$args = array(
		'post_status'    => 'publish',
		'posts_per_page' => -1,
		'meta_key'       => '_badgeos_hidden',
		'meta_value'     => 'hidden',
	);

	if ( ! empty( $achievement_type ) ) {
		$args['post_type'] = $achievement_type;
	}

	// Grab our hidden achievements
	$hidden_achievements = get_posts( $args );

	foreach ( $hidden_achievements as $achievement ) {
		$hidden_ids[] = $achievement->ID;
	}

	// Return our results.
	return $hidden_ids;
}

/**
 * Get an array of post IDs for achievements that are marked as "hidden".
 *
 * @since  1.0.0
 * @param  integer $achievement_id Limit the array to a specific id of achievement.
 * @return array  An array of hidden achievement post IDs.
 */

function badgeos_get_hidden_achievement_by_id( $achievement_id ) {

	// Grab our hidden achievements.
	global $wpdb;

	$hidden_achievements = $wpdb->get_results(
		$wpdb->prepare(
			"SELECT * FROM $wpdb->posts AS p
                                 JOIN $wpdb->postmeta AS pm
                                 ON p.ID = pm.post_id
                                 WHERE p.ID = %d
                                 AND pm.meta_key = '_badgeos_hidden'
                                 AND pm.meta_value = 'hidden'
                                 ",
			$achievement_id
		)
	);

	// Return our results.
	return $hidden_achievements;
}

/**
 * Get an array of post IDs for a user's earned achievements.
 *
 * @since  1.0.0
 * @param  integer $user_id          The given user's ID.
 * @param  string  $achievement_type Limit the array to a specific type of achievement.
 * @return array                     Our user's array of earned achievement post IDs.
 */
function badgeos_get_user_earned_achievement_ids( $user_id = 0, $achievement_type = '' ) {

	// Assume we have no earned achievements.
	$earned_ids = array();

	// Grab our earned achievements
	$earned_achievements = badgeos_get_user_achievements(
		array(
			'user_id'          => $user_id,
			'achievement_type' => $achievement_type,
			'display'          => true,
		)
	);

	if ( $earned_achievements ) {
		foreach ( $earned_achievements as $achievement ) {
			$earned_ids[] = $achievement->ID;
		}
	}

	return $earned_ids;

}

/**
 * Get an array of unique achievement types a user has earned.
 *
 * @since  1.0.1
 *
 * @param  int $user_id The ID of the user earning the achievement.
 * @return array         The array of achievements the user has earned.
 */
function badgeos_get_user_earned_achievement_types( $user_id = 0 ) {

	$achievements = badgeos_get_user_achievements( array( 'user_id' => $user_id ) );

	if ( $achievements ) {
		$achievement_types = wp_list_pluck( $achievements, 'post_type' );
		return array_unique( $achievement_types );
	} else {
		return false;
	}
}

/**
 * Returns achievements that may be earned when the given achievement is earned.
 *
 * @since  1.0.0
 * @param  integer $achievement_id The given achievement's post ID.
 * @return array                   An array of achievements that are dependent on the given achievement.
 */
function badgeos_get_dependent_achievements( $achievement_id = 0, $user_id = 0 ) {
	global $wpdb;

	// Grab the current achievement ID if none specified.
	if ( ! $achievement_id ) {
		global $post;
		$achievement_id = $post->ID;
	}

	// Grab posts that can be earned by unlocking the given achievement.
	$specific_achievements = $wpdb->get_results(
		$wpdb->prepare(
			"
		SELECT *
		FROM   $wpdb->posts as posts,
		       $wpdb->p2p as p2p
		WHERE  posts.ID = p2p.p2p_to
		       AND p2p.p2p_from = %d
		",
			$achievement_id
		)
	);

	// Grab posts triggered by unlocking any/all of the given achievement's type.
	$type_achievements = $wpdb->get_results(
		$wpdb->prepare(
			"
		SELECT *
		FROM   $wpdb->posts as posts,
		       $wpdb->postmeta as meta
		WHERE  posts.ID = meta.post_id
		       AND meta.meta_key = '_badgeos_achievement_type'
		       AND meta.meta_value = %s
		",
			badgeos_utilities::get_post_type( $achievement_id )
		)
	);

	$new_type_achivements = array();
	foreach ( $type_achievements as $ach ) {
		$post_id = $ach->ID;
		$trigger = badgeos_utilities::get_post_meta( $post_id, '_badgeos_trigger_type', true );
		if ( $trigger !== 'specific-achievement' ) {
			$new_type_achivements[] = $ach;
		} else {

			$achievement_post = badgeos_utilities::get_post_meta( $post_id, '_badgeos_achievement_post', true );
			$badgeos_count    = badgeos_utilities::get_post_meta( $post_id, '_badgeos_count', true );

			$dest_achievements = badgeos_get_user_achievements(
				array(
					'user_id'        => absint( $user_id ),
					'achievement_id' => $achievement_post,
				)
			);
			$dest_total        = count( $dest_achievements );

			$parent_post = $post_id;
			$parents     = badgeos_get_achievements( array( 'parent_of' => $post_id ) );
			if ( count( $parents ) > 0 ) {
				if ( $parents[0]->post_status === 'publish' ) {
					$parent_post = $parents[0]->ID;
				}
			}

			$source_achievements = badgeos_get_user_achievements(
				array(
					'user_id'        => absint( $user_id ),
					'achievement_id' => $parent_post,
				)
			);
			$source_total        = count( $source_achievements );

			$dest_remaind_value   = $dest_total * $badgeos_count;
			$source_remaind_value = $source_total * $badgeos_count;

			$allowed_limit = $dest_remaind_value - $source_remaind_value;

			// $dest_remaind_value . ' - ' . $source_remaind_value . '<br>';

			// $allowed_limit . ' >= ' . $badgeos_count;
			if ( $allowed_limit > 0 && $allowed_limit >= $badgeos_count ) {
				$new_type_achivements[] = $ach;
			}
		}
	}

	// Merge our dependent achievements together.
	$achievements = array_merge( $specific_achievements, $new_type_achivements );

	if ( ! is_array( $GLOBALS['badgeos']->award_ids ) || count( $GLOBALS['badgeos']->award_ids ) === 0 ) {
		$GLOBALS['badgeos']->award_ids = array();
	}

	$new_list = array();
	foreach ( $achievements as $achievement ) {
		if ( ! in_array( $achievement->ID, $GLOBALS['badgeos']->award_ids ) ) {
			$new_list[] = $achievement;
		}
	}

	// Available filter to modify an achievement's dependents.
	return apply_filters( 'badgeos_dependent_achievements', $new_list, $achievement_id );
}

/**
 * Returns achievements that must be earned to earn given achievement.
 *
 * @since  1.0.0
 * @param  integer $achievement_id The given achievement's post ID.
 * @return array                   An array of achievements that are dependent on the given achievement.
 */
function badgeos_get_required_achievements_for_achievement( $achievement_id = 0 ) {
	global $wpdb;

	// Grab the current achievement ID if none specified.
	if ( ! $achievement_id ) {
		global $post;
		$achievement_id = $post->ID;
	}

	// Don't retrieve requirements if achievement is not earned by steps.
	if ( badgeos_utilities::get_post_meta( $achievement_id, '_badgeos_earned_by', true ) !== 'triggers' ) {
		return false;
	}

	// Grab our requirements for this achievement.
	$requirements = $wpdb->get_results(
		$wpdb->prepare(
			"SELECT   *
		FROM     $wpdb->posts as posts
		         LEFT JOIN $wpdb->p2p as p2p
		                   ON p2p.p2p_from = posts.ID
		         LEFT JOIN $wpdb->p2pmeta AS p2pmeta
		                   ON p2p.p2p_id = p2pmeta.p2p_id
		WHERE    p2p.p2p_to = %d
		         AND p2pmeta.meta_key = %s
		ORDER BY CAST( p2pmeta.meta_value as SIGNED ) ASC",
			$achievement_id,
			'order'
		)
	);

	return $requirements;
}

/**
 * Returns achievements that may be earned when the given achievement is earned.
 *
 * @since  1.0.0
 * @return array An array of achievements that are dependent on the given achievement.
 */
function badgeos_get_points_based_achievements() {
	global $wpdb;

	$achievements = get_transient( 'badgeos_points_based_achievements' );

	if ( empty( $achievements ) ) {
		// Grab posts that can be earned by unlocking the given achievement.
		$achievements = $wpdb->get_results(
			"
			SELECT *
			FROM   $wpdb->posts as posts,
			       $wpdb->postmeta as meta
			WHERE  posts.ID = meta.post_id
			       AND meta.meta_key = '_badgeos_earned_by'
			       AND meta.meta_value = 'points'
			"
		);

		// Store these posts to a transient for 7 days.
		set_transient( 'badgeos_points_based_achievements', $achievements, 60 * 60 * 24 * 7 );
	}

	return (array) maybe_unserialize( $achievements );
}

/**
 * Destroy the points-based achievements transient if we edit a points-based achievement.
 *
 * @since 1.0.0
 * @param integer $post_id The given post's ID.
 */
function badgeos_bust_points_based_achievements_cache( $post_id ) {

	$post = badgeos_utilities::badgeos_get_post( $post_id );

	// If the post is one of our achievement types,.
	// and the achievement is awarded by minimum points.
	if (
		badgeos_is_achievement( $post )
		&& (
			'points' === badgeos_utilities::get_post_meta( $post_id, '_badgeos_earned_by', true )
			|| ( isset( $_POST['_badgeos_earned_by'] ) && 'points' === $_POST['_badgeos_earned_by'] )
		)
	) {
		delete_transient( 'badgeos_points_based_achievements' );
	}

}
add_action( 'save_post', 'badgeos_bust_points_based_achievements_cache' );
add_action( 'trash_post', 'badgeos_bust_points_based_achievements_cache' );

/**
 * Helper function to retrieve an achievement post thumbnail.
 *
 * Falls back first to parent achievement type's thumbnail,
 * and finally to a default BadgeOS.
 *
 * @since  1.0.0
 * @param  integer $post_id    The achievement's post ID.
 * @param  string  $image_size The name of a registered custom image size.
 * @param  string  $class      A custom class to use for the image tag.
 * @return string              Our formatted image tag.
 */
function badgeos_get_achievement_post_thumbnail( $post_id = 0, $image_size = '', $class = 'badgeos-item-thumbnail' ) {

	$badgeos_settings = ! empty( badgeos_utilities::get_option( 'badgeos_settings' ) ) ? badgeos_utilities::get_option( 'badgeos_settings' ) : array();

	$achievement_width           = '50';
	$achievement_height          = '50';
	$badgeos_not_earned_image_id = get_post_meta( $post_id, '_badgeos_not_earned_thumbnail', true );

	// Get our badge thumbnail
	if ( empty( $image_size ) ) {
		if ( isset( $badgeos_settings['badgeos_achievement_global_image_width'] ) && intval( $badgeos_settings['badgeos_achievement_global_image_width'] ) > 0 ) {
			$achievement_width = intval( $badgeos_settings['badgeos_achievement_global_image_width'] );
		}

		if ( isset( $badgeos_settings['badgeos_achievement_global_image_height'] ) && intval( $badgeos_settings['badgeos_achievement_global_image_height'] ) > 0 ) {
			$achievement_height = intval( $badgeos_settings['badgeos_achievement_global_image_height'] );
		}

		$image_size = array( $achievement_width, $achievement_height );
	}

	$image = get_the_post_thumbnail( $post_id, $image_size, array( 'class' => $class ) );

	if ( isset( $_GET['user_id'] ) ) {
		$user_id = absint( $_GET['user_id'] );
	} else {
		$user_id = 0;
	}

	// not earned post image.
	$achievements = badgeos_get_user_achievements(
		array(
			'achievement_id' => absint( $post_id ),
			'user_id'        => $user_id === 0 ? get_current_user_id() : $user_id,
		)
	);
	$class = ( count( $achievements ) > 0 ) ? ' earned' : '';
	if ( isset( $badgeos_settings['badgeos_not_earned_image'] ) && $badgeos_settings['badgeos_not_earned_image'] === 'enabled' ) {
		
		if ( ! empty( $badgeos_not_earned_image_id ) && 'earned' !== trim( $class ) ) {
			$image_url = wp_get_attachment_image_src( $badgeos_not_earned_image_id, $image_size )[0];
			$image     = '<img src="' . esc_url( $image_url ) . '" width="' . esc_attr( $achievement_width ) . '" height="' . esc_attr( $achievement_height ) . '" class="' . esc_attr( $class ) . '">';
		}

	}

	// If we don't have an image...
	if ( ! $image ) {

		// Grab our achievement type's post thumbnail
		$achievement = get_page_by_path( badgeos_utilities::get_post_type( $post_id ), OBJECT, $badgeos_settings['achievement_main_post_type'] );

		$image = is_object( $achievement ) ? get_the_post_thumbnail( $achievement->ID, $image_size, array( 'class' => $class ) ) : false;

		// If we still have no image.
		if ( ! $image ) {
			// Available filter: 'badgeos_default_achievement_post_thumbnail'.
			if ( ! empty( $image_size ) && is_array( $image_size ) ) {
				$achievement_width  = $image_size[0];
				$achievement_height = $image_size[1];
			}
			$directory_url = badgeos_get_directory_url();
			$thumbnail_url = $directory_url . 'images/default_badge.png';
			$image         = '<img src="' . apply_filters( 'badgeos_default_achievement_post_thumbnail', $thumbnail_url ) . '" width="' . $achievement_width . '" height="' . $achievement_height . '" class="' . $class . '">';
		}
	}

	// Finally, return our image tag.
	return $image;
}

/**
 * Get count of user earned achievement
 *
 * @since  3.7.1.2
 * @param  integer $achievement_id The given achievement's post ID.
 * @param  integer $user_id The given user's User ID.
 * @return array                   Array of user objects.
 */
function get_user_earned_achievement_count( $post_id, $user_id ) {

	global $wpdb;
	$table_name = $wpdb->prefix . 'badgeos_achievements';
	$count = $wpdb->get_var( 
		$wpdb->prepare( 
			'SELECT COUNT( "entry_id" ) FROM {$table_name} WHERE achievement_id = %d AND %d', $post_id, $user_id 
		)
	);
	return absint( $count );
}

/**
 * Get an array of all users who have earned a given achievement.
 *
 * @since  1.1.0
 * @param  integer $achievement_id The given achievement's post ID.
 * @return array                   Array of user objects.
 */
function badgeos_get_achievement_earners( $achievement_id = 0 ) {

	global $wpdb;

	$earned_users = array();
	$table_name   = $wpdb->prefix . 'badgeos_achievements';
	$table_exist  = $wpdb->get_var( $wpdb->prepare( 'show tables like %s', $table_name ) );
	if ( $table_exist === $table_name ) {
		$user_ids = $wpdb->get_results(
			$wpdb->prepare(
				"SELECT distinct( user_id ) as user_id FROM {$table_name} WHERE  ID = %d",
				absint( $achievement_id )
			)
		);
		foreach ( $user_ids as $rec ) {
			$earned_users[] = get_user_by( 'ID', $rec->user_id );
		}
	} else {

		$earners = new WP_User_Query(
			array(
				'meta_key'     => '_badgeos_achievements',
				'meta_value'   => $achievement_id,
				'meta_compare' => 'LIKE',
			)
		);

		foreach ( $earners->results as $earner ) {
			if ( badgeos_has_user_earned_achievement( $achievement_id, $earner->ID ) ) {
				$earned_users[] = $earner;
			}
		}
	}

	// Send back our query results.
	return $earned_users;
}

/**
 * Build an unordered list of users who have earned a given achievement.
 *
 * @since  1.1.0
 * @param  integer $achievement_id The given achievement's post ID.
 * @return string                  Concatenated markup.
 */
function badgeos_get_achievement_earners_list( $achievement_id = 0 ) {

	// Grab our users.
	$earners = badgeos_get_achievement_earners( $achievement_id );
	$output  = '';

	// Only generate output if we have earners.
	if ( ! empty( $earners ) ) {
		// Loop through each user and build our output.
		$output .= '<h4>' . apply_filters( 'badgeos_earners_heading', __( 'People who have earned this:', 'badgeos' ) ) . '</h4>';
		$output .= '<ul class="badgeos-achievement-earners-list achievement-' . $achievement_id . '-earners-list">';
		foreach ( $earners as $user ) {
			$user_content = '<li><a href="' . get_author_posts_url( $user->ID ) . '">' . get_avatar( $user->ID ) . '</a></li>';
			$output      .= apply_filters( 'badgeos_get_achievement_earners_list_user', $user_content, $achievement_id, $user->ID );
		}
		$output .= '</ul>';
	}

	// Return our concatenated output.
	return apply_filters( 'badgeos_get_achievement_earners_list', $output, $achievement_id, $earners );
}

/**
 * Check if admin settings are set to show all achievements across a multisite network.
 *
 * @since  1.2.0
 * @return boolean
 */
function badgeos_ms_show_all_achievements() {
	$ms_show_all_achievements = null;
	if ( is_multisite() ) {
		$badgeos_settings         = badgeos_utilities::get_option( 'badgeos_settings' );
		$ms_show_all_achievements = ( isset( $badgeos_settings['ms_show_all_achievements'] ) ) ? $badgeos_settings['ms_show_all_achievements'] : 'disabled';
		if ( 'enabled' === $ms_show_all_achievements ) {
			return true;
		}
	}
	return false;
}

/**
 * Create array of blog ids in the network if multisite setting is on.
 *
 * @since  1.2.0
 * @return array Array of blog_ids.
 */
function badgeos_get_network_site_ids() {
	global $wpdb;
	if ( badgeos_ms_show_all_achievements() ) {
		$blog_ids = $wpdb->get_results( 'SELECT blog_id FROM ' . $wpdb->base_prefix . 'blogs' );
		foreach ( $blog_ids as $key => $value ) {
			$sites[] = $value->blog_id;
		}
	} else {
		$sites[] = get_current_blog_id();
	}
	return $sites;
}

/**
 * Set default achievement image on achievement post save.
 *
 * @since 1.2.0
 * @param integer $post_id The post ID of the post being saved.
 * @return mixed    post ID if nothing to do, void otherwise.
 */
function badgeos_achievement_set_default_thumbnail( $post_id ) {
	global $pagenow;

	$badgeos_settings = ( $exists = badgeos_utilities::get_option( 'badgeos_settings' ) ) ? $exists : array();
	if (
		! (
			badgeos_is_achievement( $post_id )
			|| $badgeos_settings['achievement_main_post_type'] === badgeos_utilities::get_post_type( $post_id )
		)
		|| ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE )
		|| ! current_user_can( 'edit_post', $post_id )
		|| has_post_thumbnail( $post_id )
		|| 'post-new.php' === $pagenow
	) {
		return $post_id;
	}

	$thumbnail_id     = 0;
	$achievement_type = '';

	// Get the thumbnail of our parent achievement.
	if ( $badgeos_settings['achievement_main_post_type'] !== badgeos_utilities::get_post_type( $post_id ) ) {
		$achievement_type = get_page_by_path( badgeos_utilities::get_post_type( $post_id ), OBJECT, $badgeos_settings['achievement_main_post_type'] );

		if ( $achievement_type ) {
			$thumbnail_id = get_post_thumbnail_id( $achievement_type->ID );
		}
	}

	// If there is no thumbnail set, load in our default image.
	if ( empty( $thumbnail_id ) ) {
		global $wpdb;

		// Grab the default image.
		$directory_url = badgeos_get_directory_url();
		$thumbnail_url = $directory_url . 'images/default_badge.png';
		$file          = apply_filters( 'badgeos_default_achievement_post_thumbnail', $thumbnail_url );

		// Check for an existing copy of our default image
		$file_name  = 'af2e834c1e23ab30f1d672579d61c25a_15';
		$attachment = $wpdb->get_col(
			$wpdb->prepare(
				"SELECT ID FROM $wpdb->posts WHERE post_type = %s AND guid LIKE %s ",
				'attachment',
				'%%' . $file_name . '%%'
			)
		);

		if ( ! empty( $attachment[0] ) ) {
			$thumbnail_id = $attachment[0];
		} else {
			// Download file to temp location.
			$tmp = download_url( $file );

			// Set variables for storage.
			// fix file filename for query strings.
			preg_match( '/[^\?]+\.(jpe?g|jpe|gif|png)\b/i', $file, $matches );
			$file_array['name']     = basename( $matches[0] );
			$file_array['tmp_name'] = $tmp;

			// If error storing temporarily, unlink.
			if ( is_wp_error( $tmp ) ) {
				@unlink( $file_array['tmp_name'] );
				$file_array['tmp_name'] = '';
			}

			// Upload the image
			$thumbnail_id = media_handle_sideload( $file_array, $post_id );
		}
		// If upload errored, unlink the image file
		if ( empty( $thumbnail_id ) || is_wp_error( $thumbnail_id ) ) {
			@unlink( $file_array['tmp_name'] );

			// Otherwise, if the achievement type truly doesn't have.
			// a thumbnail already, set this as its thumbnail, too.
			// We do this so that WP won't upload a duplicate version.
			// of this image for every single achievement of this type.
		} elseif (
			badgeos_is_achievement( $post_id )
			&& is_object( $achievement_type )
			&& ! get_post_thumbnail_id( $achievement_type->ID )
		) {
			set_post_thumbnail( $achievement_type->ID, $thumbnail_id );
		}
	}

	// Finally, if we have an image, set the thumbnail for our achievement.
	if ( $thumbnail_id && ! is_wp_error( $thumbnail_id ) ) {
		set_post_thumbnail( $post_id, $thumbnail_id );
	}

}
add_action( 'save_post', 'badgeos_achievement_set_default_thumbnail' );

/**
 * Flush rewrite rules whenever an achievement type is published.
 *
 * @since 1.4.0
 *
 * @param string $new_status New status.
 * @param string $old_status Old status.
 * @param object $post       Post object.
 */
function badgeos_flush_rewrite_on_published_achievement( $new_status, $old_status, $post ) {
	$badgeos_settings = ( $exists = badgeos_utilities::get_option( 'badgeos_settings' ) ) ? $exists : array();
	if ( $badgeos_settings['achievement_main_post_type'] === $post->post_type && 'publish' === $new_status && 'publish' !== $old_status ) {

		badgeos_flush_rewrite_rules();
	}
}
add_action( 'transition_post_status', 'badgeos_flush_rewrite_on_published_achievement', 10, 3 );

/**
 * Register achievement types and flush rewrite rules.
 *
 * @since 1.4.0
 */
function badgeos_flush_rewrite_rules() {
	badgeos_register_post_types();
	badgeos_register_achievement_type_cpt();
	badgeos_register_ranks_post_types();
	badgeos_register_ranks_type_cpt();
	badgeos_register_points_post_types();
	flush_rewrite_rules();
}

/**
 * Update all dependent data if achievement type name has changed.
 *
 * @since  1.4.0
 *
 * @param  array $data      Post data.
 * @param  array $post_args Post args.
 * @return array            Updated post data.
 */
function badgeos_maybe_update_achievement_type( $data = array(), $post_args = array() ) {
	if ( badgeos_achievement_type_changed( $post_args ) ) {
		$original_type     = badgeos_utilities::badgeos_get_post( $post_args['ID'] )->post_name;
		$new_type          = wp_unique_post_slug( sanitize_title( $post_args['post_title'] ), $post_args['ID'], $post_args['post_status'], $post_args['post_type'], $post_args['post_parent'] );
		$data['post_name'] = badgeos_update_achievement_types( $original_type, $new_type );
		add_filter( 'redirect_post_location', 'badgeos_achievement_type_rename_redirect', 99 );
	}
	return $data;
}
add_filter( 'wp_insert_post_data', 'badgeos_maybe_update_achievement_type', '99', 2 );

/**
 * Check if an achievement type name has changed.
 *
 * @since  1.4.0
 *
 * @param  array $post_args Post args.
 * @return bool             True if name has changed, otherwise false.
 */
function badgeos_achievement_type_changed( $post_args = array() ) {
	if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
		return false;
	}

	$original_post = ( ! empty( $post_args['ID'] ) && isset( $post_args['ID'] ) ) ? badgeos_utilities::badgeos_get_post( $post_args['ID'] ) : null;
	$status        = false;
	if ( is_object( $original_post ) ) {
		$badgeos_settings = ( $exists = badgeos_utilities::get_option( 'badgeos_settings' ) ) ? $exists : array();
		if (
			$badgeos_settings['achievement_main_post_type'] === $post_args['post_type']
			&& $original_post->post_status !== 'auto-draft'
			&& ! empty( $original_post->post_name )
			&& $original_post->post_title !== $post_args['post_title']
		) {
			$status = true;
		}
	}

	return $status;
}

/**
 * Replace all instances of one achievement type with another.
 *
 * @since  1.4.0
 *
 * @param  string $original_type Original achievement type.
 * @param  string $new_type      New achievement type.
 * @return string                New achievement type.
 */
function badgeos_update_achievement_types( $original_type = '', $new_type = '' ) {

	// Sanity check to prevent alterating core posts
	if ( empty( $original_type ) || in_array( $original_type, array( 'post', 'page', 'attachment', 'revision', 'nav_menu_item' ) ) ) {
		return $new_type;
	}

	badgeos_update_achievements_achievement_types( $original_type, $new_type );
	badgeos_update_p2p_achievement_types( $original_type, $new_type );
	badgeos_update_earned_meta_achievement_types( $original_type, $new_type );
	badgeos_update_active_meta_achievement_types( $original_type, $new_type );
	badgeos_flush_rewrite_rules();
	return $new_type;
}

/**
 * Change all achievements of one type to a new type.
 *
 * @since 1.4.0
 *
 * @param string $original_type Original achievement type.
 * @param string $new_type      New achievement type.
 */
function badgeos_update_achievements_achievement_types( $original_type = '', $new_type = '' ) {
	$items = get_posts(
		array(
			'posts_per_page' => -1,
			'post_status'    => 'any',
			'post_type'      => $original_type,
			'fields'         => 'id',
		)
	);
	foreach ( $items as $item ) {
		set_post_type( $item->ID, $new_type );
	}
}

/**
 * Change all p2p connections of one achievement type to a new type.
 *
 * @since 1.4.0
 *
 * @param string $original_type Original achievement type.
 * @param string $new_type      New achievement type.
 */
function badgeos_update_p2p_achievement_types( $original_type = '', $new_type = '' ) {
	global $wpdb;
	$badgeos_settings  = ( $exists = badgeos_utilities::get_option( 'badgeos_settings' ) ) ? $exists : array();
	$p2p_relationships = array(
		trim( $badgeos_settings['achievement_step_post_type'] ) . "-to-{$original_type}" => trim( $badgeos_settings['achievement_step_post_type'] ) . "-to-{$new_type}",
		"{$original_type}-to-" . trim( $badgeos_settings['achievement_step_post_type'] ) => "{$new_type}-to-" . trim( $badgeos_settings['achievement_step_post_type'] ),
	);
	foreach ( $p2p_relationships as $old => $new ) {
		$wpdb->query( $wpdb->prepare( "UPDATE $wpdb->p2p SET p2p_type = %s WHERE p2p_type = %s", $new, $old ) );
	}
}

/**
 * Change all earned meta from one achievement type to another.
 *
 * @since 1.4.0
 *
 * @param string $original_type Original achievement type.
 * @param string $new_type      New achievement type.
 */
function badgeos_update_earned_meta_achievement_types( $original_type = '', $new_type = '' ) {

	global $wpdb;

	$metas = badgeos_get_unserialized_achievement_metas( '_badgeos_achievements', $original_type );
	if ( ! empty( $metas ) ) {
		foreach ( $metas as $meta ) {
			foreach ( $meta->meta_value as $site_id => $achievements ) {
				$meta->meta_value[ $site_id ] = badgeos_update_meta_achievement_types( $achievements, $original_type, $new_type );
			}
			badgeos_utilities::update_user_meta( $meta->user_id, $meta->meta_key, $meta->meta_value );
		}
	}

	$table_name  = $wpdb->prefix . 'badgeos_achievements';
	$table_exist = $wpdb->get_var( $wpdb->prepare( 'show tables like %s', $table_name ) );
	if ( $table_exist === $table_name ) {
		$wpdb->update( $table_name, array( 'post_type' => $new_type ), array( 'post_type' => $original_type ), array( '%s' ), array( '%s' ) );
	}
}

/**
 * Change all active meta from one achievement type to another.
 *
 * @since 1.4.0
 *
 * @param string $original_type Original achievement type.
 * @param string $new_type      New achievement type.
 */
function badgeos_update_active_meta_achievement_types( $original_type = '', $new_type = '' ) {
	$metas = badgeos_get_unserialized_achievement_metas( '_badgeos_active_achievements', $original_type );
	if ( ! empty( $metas ) ) {
		foreach ( $metas as $meta ) {
			$meta->meta_value = badgeos_update_meta_achievement_types( $meta->meta_value, $original_type, $new_type );
			badgeos_utilities::update_user_meta( $meta->user_id, $meta->meta_key, $meta->meta_value );
		}
	}
}

/**
 * Get unserialized user achievement metas.
 *
 * @since  1.4.0
 *
 * @param  string $meta_key      Meta key.
 * @param  string $original_type Achievement type.
 * @return array                 User achievement metas.
 */
function badgeos_get_unserialized_achievement_metas( $meta_key = '', $original_type = '' ) {
	$metas = badgeos_get_achievement_metas( $meta_key, $original_type );
	if ( ! empty( $metas ) ) {
		foreach ( $metas as $key => $meta ) {
			$metas[ $key ]->meta_value = maybe_unserialize( $meta->meta_value );
		}
	}
	return $metas;
}

/**
 * Get serialized user achievement metas.
 *
 * @since  1.4.0
 *
 * @param  string $meta_key      Meta key.
 * @param  string $original_type Achievement type.
 * @return array                 User achievement metas.
 */
function badgeos_get_achievement_metas( $meta_key = '', $original_type = '' ) {
	global $wpdb;
	return $wpdb->get_results(
		$wpdb->prepare(
			"
		SELECT *
		FROM   $wpdb->usermeta
		WHERE  meta_key = %s
		       AND meta_value LIKE %s
		",
			$meta_key,
			'%%' . $original_type . '%%'
		)
	);
}

/**
 * Change user achievement meta from one achievement type to another.
 *
 * @since 1.4.0
 *
 * @param array  $achievements  Array of achievements.
 * @param string $original_type Original achievement type.
 * @param string $new_type      New achievement type.
 *
 * @return array $achievements
 */
function badgeos_update_meta_achievement_types( $achievements = array(), $original_type = '', $new_type = '' ) {
	if ( is_array( $achievements ) && ! empty( $achievements ) ) {
		foreach ( $achievements as $key => $achievement ) {
			if ( $achievement->post_type === $original_type ) {
				$achievements[ $key ]->post_type = $new_type;
			}
		}
	}
	return $achievements;
}

/**
 * Redirect to inclue custom rename message.
 *
 * @since  1.4.0
 *
 * @param  string $location Original URI.
 * @return string           Updated URI.
 */
function badgeos_achievement_type_rename_redirect( $location = '' ) {
	remove_filter( 'redirect_post_location', __FUNCTION__, 99 );
	return add_query_arg( 'message', 99, $location );
}

/**
 * Filter the "post updated" messages to include support for achievement types.
 *
 * @since 1.4.0
 *
 * @param array $messages Array of messages to display.
 *
 * @return array $messages Compiled list of messages.
 */
function badgeos_achievement_type_update_messages( $messages ) {
	$badgeos_settings = ( $exists = badgeos_utilities::get_option( 'badgeos_settings' ) ) ? $exists : array();
	$messages[ trim( $badgeos_settings['achievement_main_post_type'] ) ]       = array_fill( 1, 10, __( 'Achievement Type saved successfully.', 'badgeos' ) );
	$messages[ trim( $badgeos_settings['achievement_main_post_type'] ) ]['99'] = sprintf( __( 'Achievement Type renamed successfully. <p>All achievements of this type, and all active and earned user achievements, have been updated <strong>automatically</strong>.</p> All shortcodes, %s, and URIs that reference the old achievement type slug must be updated <strong>manually</strong>.', 'badgeos' ), '<a href="' . esc_url( admin_url( 'widgets.php' ) ) . '">' . __( 'widgets', 'badgeos' ) . '</a>' );
	return $messages;
}
add_filter( 'post_updated_messages', 'badgeos_achievement_type_update_messages' );


/**
 * Add image not earned badge image metabox for achivement-types | rank-types.
 *
 * @since 3.6.8
 */
function badgeos_not_earned_image_add_metabox() {
	$badgeos_settings = ( $exists = badgeos_utilities::get_option( 'badgeos_settings' ) ) ? $exists : array();
	if ( ! isset( $badgeos_settings['badgeos_not_earned_image'] ) || $badgeos_settings['badgeos_not_earned_image'] == 'disabled' ) {
		return;
	}
	$achievement_main_post_type = $badgeos_settings['achievement_main_post_type'];
	$rank_main_post_type        = $badgeos_settings['ranks_main_post_type'];

	$achievements_post_type = array_merge( array( $achievement_main_post_type ), badgeos_get_achievement_types_slugs() );
	$ranks_post_type        = array_merge( array( $rank_main_post_type ), badgeos_get_rank_types_slugs() );
	$badgeos_post_types     = array_merge( $achievements_post_type, $ranks_post_type );

	add_meta_box(
		'not_earned_image_div',
		__( 'Not Earned Image', 'badgeos' ),
		'badgeos_not_earned_image_metabox_cb',
		$badgeos_post_types,
		'side',
		'low'
	);
}
add_action( 'add_meta_boxes', 'badgeos_not_earned_image_add_metabox' );

/**
 * Callback function for not earned badge image metabox for achivement-types | rank-types.
 *
 * @param integer $post_id The post ID of the post being saved
 * @since 3.6.8
 */
function badgeos_not_earned_image_metabox_cb( $post ) {
	$badgeos_settings = ( $exists = badgeos_utilities::get_option( 'badgeos_settings' ) ) ? $exists : array();

	if ( ! isset( $badgeos_settings['badgeos_not_earned_image'] ) || $badgeos_settings['badgeos_not_earned_image'] == 'disabled' ) {
		return;
	}

	global $content_width, $_wp_additional_image_sizes;
	$post_id = $post->ID;

	$old_content_width = $content_width;
	$content_width     = 254;

	$image_id         = get_post_meta( $post->ID, '_badgeos_not_earned_thumbnail', true );
	$achievement_type = '';
	// Get the thumbnail of our parent achievement
	if ( empty( $image_id ) && $badgeos_settings['achievement_main_post_type'] !== badgeos_utilities::get_post_type( $post_id ) ) {
		$achievement_type = get_page_by_path( badgeos_utilities::get_post_type( $post_id ), OBJECT, $badgeos_settings['achievement_main_post_type'] );

		if ( $achievement_type ) {
			$image_id = get_post_meta( $achievement_type->ID, '_badgeos_not_earned_thumbnail', true );
		}
	}

	// Get the thumbnail of our parent achievement
	if ( empty( $image_id ) && $badgeos_settings['ranks_main_post_type'] !== badgeos_utilities::get_post_type( $post_id ) ) {
		$achievement_type = get_page_by_path( badgeos_utilities::get_post_type( $post_id ), OBJECT, $badgeos_settings['ranks_main_post_type'] );

		if ( $achievement_type ) {
			$image_id = get_post_meta( $achievement_type->ID, '_badgeos_not_earned_thumbnail', true );
		}
	}

	if ( ! empty( $image_id ) ) {
		if ( ! isset( $_wp_additional_image_sizes['post-thumbnail'] ) ) {
			$thumbnail_html = wp_get_attachment_image( $image_id, array( $content_width, $content_width ) );
		} else {
			$thumbnail_html = wp_get_attachment_image( $image_id, 'post-thumbnail' );
		}
		if ( ! empty( $thumbnail_html ) ) {
			$content  = $thumbnail_html;
			$content .= '<p class="hide-if-no-js">';
			$content .= '<a href="javascript:;" id="remove_not_earned_image_button" >' . esc_html__( 'Remove image', 'badgeos' ) . '</a>';
			$content .= '</p>';
			$content .= '<input type="hidden" id="upload_not_earned_image" name="_badgeos_not_earned_thumbnail" value="' . esc_attr( $image_id ) . '" />';
		}
		$content_width = $old_content_width;
	} else {
		$content  = '<img src="" style="width:' . esc_attr( $content_width ) . 'px;height:auto;border:0;display:none;" />';
		$content .= '<p class="hide-if-no-js">';
		$content .= '<a title="' . esc_attr__( 'Set image', 'badgeos' ) . '" href="javascript:;" id="upload_not_earned_image_button" data-uploader_title="' . esc_attr__( 'Choose an image', 'badgeos' ) . '" data-uploader_button_text="' . esc_attr__( 'Set image', 'badgeos' ) . '">' . esc_html__( 'Set image', 'badgeos' ) . '</a>';
		$content .= '</p>';
		$content .= '<input type="hidden" id="upload_not_earned_image" name="_badgeos_not_earned_thumbnail" value="" />';

	}
	echo $content;
}

/**
 * Set default not earned achievement image on achievement post save
 *
 * @since 3.6.8
 * @param integer $post_id The post ID of the post being saved
 * @return mixed    post ID if nothing to do, void otherwise.
 */
function badgeos_set_default_not_earned_image_thumbnail( $post_id ) {

	$badgeos_settings = ( $exists = badgeos_utilities::get_option( 'badgeos_settings' ) ) ? $exists : array();

	if ( ! isset( $badgeos_settings['badgeos_not_earned_image'] ) || $badgeos_settings['badgeos_not_earned_image'] == 'disabled' ) {
		return;
	}

	if ( isset( $_POST['_badgeos_not_earned_thumbnail'] ) ) {
		update_post_meta( $post_id, '_badgeos_not_earned_thumbnail', absint( $_POST['_badgeos_not_earned_thumbnail'] ) );
		return;
	}

	$thumbnail_id     = 0;
	$achievement_type = '';
	// Get the thumbnail of our parent achievement.
	if ( $badgeos_settings['achievement_main_post_type'] !== badgeos_utilities::get_post_type( $post_id ) ) {
		$achievement_type = get_page_by_path( badgeos_utilities::get_post_type( $post_id ), OBJECT, $badgeos_settings['achievement_main_post_type'] );

		if ( $achievement_type ) {
			$thumbnail_id = get_post_meta( $achievement_type->ID, '_badgeos_not_earned_thumbnail', true );
			update_post_meta( $post_id, '_badgeos_not_earned_thumbnail', $thumbnail_id );
		}
	}

	// Get the thumbnail of our parent achievement.
	if ( $badgeos_settings['ranks_main_post_type'] !== badgeos_utilities::get_post_type( $post_id ) ) {
		$achievement_type = get_page_by_path( badgeos_utilities::get_post_type( $post_id ), OBJECT, $badgeos_settings['ranks_main_post_type'] );

		if ( $achievement_type ) {
			$image_id = get_post_meta( $achievement_type->ID, '_badgeos_not_earned_thumbnail', true );
		}
	}

	// If there is no thumbnail set, load in our default image.
	if ( empty( $thumbnail_id ) ) {
		global $wpdb;
		// Grab the default image
		$thumbnail_id  = '';
		$directory_url = badgeos_get_directory_url();
		$file          = $directory_url . 'images/badgeos_question.png';
		$file_name     = 'badgeos_question';
		$attachment    = $wpdb->get_col(
			$wpdb->prepare(
				"SELECT ID FROM $wpdb->posts WHERE post_type = %s AND guid LIKE '%%badgeos_question%%' ",
				'attachment'
			)
		);

		if ( ! empty( $attachment[0] ) ) {
			$thumbnail_id = $attachment[0];
		} else {
			// Download file to temp location.
			require_once ABSPATH . 'wp-admin' . '/includes/image.php';
			require_once ABSPATH . 'wp-admin' . '/includes/file.php';
			require_once ABSPATH . 'wp-admin' . '/includes/media.php';
			$tmp = download_url( $file );

			// Set variables for storage.
			// fix file filename for query strings.
			preg_match( '/[^\?]+\.(jpe?g|jpe|gif|png)\b/i', $file, $matches );
			$file_array['name']     = basename( $matches[0] );
			$file_array['tmp_name'] = $tmp;

			// If error storing temporarily, unlink.
			if ( is_wp_error( $tmp ) ) {
				@unlink( $file_array['tmp_name'] );
				$file_array['tmp_name'] = '';
			}
			// Upload the image.
			$thumbnail_id = media_handle_sideload( $file_array, $post_id );
		}
		update_post_meta( $post_id, '_badgeos_not_earned_thumbnail', $thumbnail_id );
	}
}
add_action( 'save_post', 'badgeos_set_default_not_earned_image_thumbnail', 10, 1 );

/**
 * Revoke Badge on point loss.
 *
 * @since  3.6.12
 *
 * @param  string $location Original URI.
 * @return string           Updated URI.
 */

function revoke_badge_on_point_loss() {
	global $wpdb;
	$points_table_name = $wpdb->base_prefix . 'badgeos_points';
	$postmeta_table    = $wpdb->base_prefix . 'postmeta';

	$user_id         = get_current_user_id();
	$query           = $wpdb->get_col( "SELECT post_id FROM {$wpdb->postmeta} WHERE meta_key = '_badgeos_revoke_badge_point_loss' " );
	$achievement_ids = implode( ',', $query );

	if ( strlen( $achievement_ids ) > 0 ) {
		// Get awarded points by achievemet trigger.
		$last_points_awarded = $wpdb->get_results(
			$wpdb->prepare(
				"SELECT * FROM {$points_table_name} 
				WHERE type = 'Award' 
				AND user_id = %d 
				AND achievement_id IN (%s)
				ORDER BY `dateadded` DESC ",
				$user_id,
				$achievement_ids
			)
		);

		if ( ! empty( $last_points_awarded ) ) {
			foreach ( $last_points_awarded as $awarded_points ) {
				$total_deducted = total_deduct_points( $user_id, $awarded_points->credit_id );
				if ( $total_deducted >= (int) $awarded_points->credit ) {
					$is_revoked = badgeos_revoke_achievement_after_points_deduct( $awarded_points->achievement_id, $user_id );
				}
			}
		}
	}
}

add_action( 'admin_init', 'revoke_badge_on_point_loss' );

// Deduct after points are deducted.
function badgeos_revoke_achievement_after_points_deduct( $achievement_id, $user_id ) {
	global $wpdb;
	$achievements_table_name = $wpdb->base_prefix . 'badgeos_achievements';
	$result                  = $wpdb->get_results(
		$wpdb->prepare(
			"DELETE FROM {$achievements_table_name}
			WHERE user_id = %d 
			AND ID = %d",
			absint( $user_id ),
			absint( $achievement_id )
		)
	);

	if ( count( $result ) > 0 ) {
		return true;
	}
	return false;
}

// Total deducted points
function total_deduct_points( $user_id, $credit_id ) {
	global $wpdb;
	$points_table_name     = $wpdb->base_prefix . 'badgeos_points';
	$total_deducted_points = $wpdb->get_var(
		$wpdb->prepare(
			"SELECT SUM( credit ) FROM {$points_table_name} WHERE type = 'Deduct' AND user_id = %d AND credit_id = %d ORDER BY `dateadded` DESC ",
			absint( $user_id ),
			absint( $credit_id )
		)
	);
	return (int) $total_deducted_points;
}