clone-posts-pages-learn-dash-contents.php 25.6 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
<?php

namespace uncanny_pro_toolkit;

use uncanny_learndash_toolkit as toolkit;

if ( ! defined( 'WPINC' ) ) {
	die;
}


/**
 * Class ClonePostsPagesLearnDashContents
 *
 * @package uncanny_pro_toolkit
 */
class ClonePostsPagesLearnDashContents extends toolkit\Config implements toolkit\RequiredFunctions {
	/**
	 * Class constructor
	 */
	public function __construct() {
		add_action( 'plugins_loaded', array( __CLASS__, 'run_frontend_hooks' ) );
	}

	/*
	 * Initialize frontend actions and filters
	 */
	public static function run_frontend_hooks() {

		if ( true === self::dependants_exist() ) {

			/* ADD FILTERS ACTIONS FUNCTION */
			add_filter( 'post_row_actions', array( __CLASS__, 'add_clone_to_action_rows' ), 10, 2 );
			add_filter( 'page_row_actions', array( __CLASS__, 'add_clone_to_action_rows' ), 10, 2 );
			add_action( 'post_submitbox_misc_actions', array( __CLASS__, 'uncanny_clone_post_publish_box' ) );
			add_action( 'admin_action_clone_learndash_quiz_contents', array( __CLASS__, 'uncanny_clone_quiz' ) );
			add_action( 'admin_action_clone_post_contents', array( __CLASS__, 'uncanny_clone_contents' ) );
			/* ADD DEFAULT SETTINGS*/
			self::default_settings();
		}

	}

	/**
	 * Does the plugin rely on another function or plugin
	 *
	 * @return boolean || string Return either true or name of function or plugin
	 */
	public static function dependants_exist() {

		/* Checks for LearnDash */
		global $learndash_post_types;
		if ( ! isset( $learndash_post_types ) ) {
			return 'Plugin: LearnDash';
		}

		// Return true if no dependency or dependency is available
		return true;

	}

	/**
	 * Add Default settings for exiting installs
	 */
	public static function default_settings() {
		// get module settings key
		$class              = stripslashes( __CLASS__ );
		$default_post_types = array(
			'post',
			'page',
			'sfwd-courses',
			'sfwd-lessons',
			'sfwd-topic',
			'sfwd-quiz',
			'sfwd-question',
		);
		// Get all module settings
		$options = get_option( $class, '' );
		// Check and add default settings
		if ( empty( $options ) ) {
			$default_options = array();
			foreach ( $default_post_types as $post_type ) {
				$default_options[] = array(
					'name'  => 'uncanny-learndash-posttype-' . $post_type,
					'value' => 'on',
				);
			}
			update_option( $class, $default_options );
		}
	}

	/**
	 * Description of class in Admin View
	 *
	 * @return array
	 */
	public static function get_details() {
		$module_id = 'duplicate-pages-posts';

		$class_title = esc_html__( 'Duplicate Pages & Posts', 'uncanny-pro-toolkit' );

		$kb_link = 'http://www.uncannyowl.com/knowledge-base/duplicate-pages-posts/';

		/* Sample Simple Description with shortcode */
		$class_description = esc_html__( 'Easily clone pages, posts, LearnDash courses, lessons, topics, quizzes and more. This plugin handles quiz duplication properly.', 'uncanny-pro-toolkit' );

		/* Icon as fontawesome icon */
		$class_icon = '<i class="uo_icon_pro_fa uo_icon_fa fa fa-clone"></i><span class="uo_pro_text">PRO</span>';

		$category = 'WordPress';
		$type     = 'pro';

		return array(
			'id'               => $module_id,
			'title'            => $class_title,
			'type'             => $type,
			'category'         => $category,
			'kb_link'          => $kb_link, // OR set as null not to display
			'description'      => $class_description,
			'dependants_exist' => self::dependants_exist(),
			//'settings'         => false, // OR
			'settings'         => self::get_class_settings( $class_title ),
			'icon'             => $class_icon,
		);

	}

	/**
	 * HTML for modal to create settings
	 *
	 * @static
	 *
	 * @param $class_title
	 *
	 * @return array
	 */
	public static function get_class_settings( $class_title ) {

		// Create options
		$options      = array();
		$type_options = array();
		$post_types   = get_post_types( array(), 'objects' );
		if ( ! empty( $post_types ) ) {
			foreach ( $post_types as $post_type ) {
				$type_options[ $post_type->name ] = $post_type->labels->name;
			}
		}
		asort( $type_options );

		$options[] = array(
			'type'       => 'html',
			'inner_html' => sprintf(
				'<h4 style="margin:0">%s</h4>',
				__( 'Enable duplication on:', 'uncanny-pro-toolkit' )
			),
		);

		if ( ! empty( $type_options ) ) {
			foreach ( $type_options as $post_type => $name ) {
				$options[] = array(
					'type'        => 'checkbox',
					'label'       => esc_html__( $name, 'uncanny-pro-toolkit' ),
					'option_name' => 'uncanny-learndash-posttype-' . $post_type,
				);
			}
		}

		$options[] = array(
			'type'       => 'html',
			'inner_html' => sprintf(
				'<h4 style="margin:0">%s</h4>',
				__( 'Note: Duplication may not work correctly with some post types.', 'uncanny-pro-toolkit' )
			),
		);

		// Build html
		$html = self::settings_output(
			array(
				'class'   => __CLASS__,
				'title'   => $class_title,
				'options' => $options,
			)
		);

		return $html;
	}

	/**
	 * Add Clone link to Publish Box of WordPress Edit screen
	 */
	public static function uncanny_clone_post_publish_box() {
		if ( ! isset( $_GET['post'] ) ) {
			return;
		}

		$post = get_post( absint( $_GET['post'] ) );
		if ( 'sfwd-assignment' === $post->post_type || ( in_array( 'woocommerce/woocommerce.php', apply_filters( 'active_plugins', get_option( 'active_plugins' ) ) ) && 'product' === $post->post_type ) ) {
			return;
		}

		?>
		<div class="misc-pub-section misc-pub-clone" id="Clone">
			<?php
			if ( 'sfwd-quiz' === $post->post_type ) {
				$action = '?action=clone_learndash_quiz_contents&return_to_post=true&post=' . $post->ID;
			} else {
				$action = '?action=clone_post_contents&return_to_post=true&post=' . $post->ID;
			}
			$post_type_object = get_post_type_object( $post->post_type );

			?>
			<style>
				.misc-pub-clone #post-clone-display::before {
					content: "\f105";
					font: 400 20px/1 dashicons;
					speak: none;
					display: inline-block;
					padding: 0 2px 0 0;
					top: 0;
					left: -1px;
					position: relative;
					vertical-align: top;
					-webkit-font-smoothing: antialiased;
					-moz-osx-font-smoothing: grayscale;
					text-decoration: none !important;
					color: #82878c;
				}
			</style>
			<span id="post-clone-display"><strong>Action:</strong> </span>
			<a href="<?php echo $action; ?>" class="edit-visibility hide-if-no-js"><span
						aria-hidden="true">Clone this <?php echo $post_type_object->labels->singular_name; ?></span></a>
		</div>
		<?php
	}

	/**
	 * @param $actions
	 * @param $post
	 *
	 * @return mixed
	 */
	public static function add_clone_to_action_rows( $actions, $post ) {
		//Don't add Clone link if its not enabled in settings
		if ( 'on' !== self::get_settings_value( 'uncanny-learndash-posttype-' . $post->post_type, __CLASS__ ) ) {
			return $actions;
		}

		//Don't add Clone link to Woocommerce, or Products post type of woocommerce
		if ( 'sfwd-assignment' === $post->post_type || ( in_array( 'woocommerce/woocommerce.php', apply_filters( 'active_plugins', get_option( 'active_plugins' ) ) ) && 'product' === $post->post_type ) ) {
			return $actions;
		}
		if ( 'sfwd-quiz' === $post->post_type ) {
			$action = '?action=clone_learndash_quiz_contents&post=' . $post->ID;
		} else {
			$action = '?action=clone_post_contents&post=' . $post->ID;
		}
		$post_type_object = get_post_type_object( $post->post_type );
		$can_edit_post    = current_user_can( $post_type_object->cap->edit_post, $post->ID );
		if ( $can_edit_post ) {
			$actions['uncanny_clone'] = '<a href="' . $action . '" title="' .
										esc_attr( sprintf( esc_attr__( 'Clone this %s', 'uncanny-pro-toolkit' ), $post_type_object->labels->singular_name ) ) . '">' .
										sprintf( esc_attr__( 'Clone this %s', 'uncanny-pro-toolkit' ), $post_type_object->labels->singular_name ) .
										'</a>';
		}

		return $actions;
	}

	/**
	 *
	 */
	public static function uncanny_clone_quiz() {

		if ( ! ( isset( $_GET['post'] ) || isset( $_POST['post'] ) || ( isset( $_REQUEST['action'] ) && 'clone_learndash_quiz_contents' === $_REQUEST['action'] ) ) ) {
			wp_die( esc_attr__( 'No quiz to duplicate has been supplied!', 'uncanny-pro-toolkit' ) );
		}

		// Get the original post
		$id   = ( isset( $_GET['post'] ) ? $_GET['post'] : $_POST['post'] );
		$post = get_post( absint( $id ) );

		// Copy the post and insert it
		if ( isset( $post ) && $post != null ) {
			self::duplicate_quiz_create_duplicate( $post );

			wp_redirect( admin_url( 'edit.php?post_type=' . $post->post_type ) );
			exit;

		} else {
			wp_die( esc_attr( esc_attr__( 'Copy creation failed, could not find original:', 'uncanny-pro-toolkit' ) ) . ' ' . htmlspecialchars( $id ) );
		}

	}

	/**
	 * @param        $post
	 * @param string $status
	 * @param string $parent_id
	 *
	 * @return int|\WP_Error
	 */
	public static function duplicate_quiz_create_duplicate( $post, $status = '', $parent_id = '' ) {
		global $wpdb;
		// We don't want to clone revisions
		if ( 'revision' === $post->post_type ) {
			return false;
		}

		if ( 'attachment' !== $post->post_type ) {
			$status = 'draft';
		}

		$new_post_author = wp_get_current_user();

		$new_post = array(
			'menu_order'     => $post->menu_order,
			'comment_status' => $post->comment_status,
			'ping_status'    => $post->ping_status,
			'post_author'    => $new_post_author->ID,
			'post_content'   => $post->post_content,
			'post_excerpt'   => $post->post_excerpt,
			'post_mime_type' => $post->post_mime_type,
			'post_parent'    => $new_post_parent = empty( $parent_id ) ? $post->post_parent : $parent_id,
			'post_password'  => $post->post_password,
			'post_status'    => $new_post_status = ( empty( $status ) ) ? $post->post_status : $status,
			'post_title'     => $post->post_title . ' (Duplicate Quiz)',
			'post_type'      => $post->post_type,
		);
		$new_post['post_date']     = $new_post_date = $post->post_date;
		$new_post['post_date_gmt'] = get_gmt_from_date( $new_post_date );

		$new_post_id = wp_insert_post( $new_post );

		// add taxonomies
		$categories = wp_get_post_terms( $post->ID, 'category' );
		$tags       = wp_get_post_terms( $post->ID, 'post_tag' );

		$all_categories = array();
		foreach ( $categories as $category ) {
			$all_categories[] = $category->term_id;
		}

		$all_tags = array();
		foreach ( $tags as $tag ) {
			$all_tags[] = $tag->term_id;
		}

		if ( ! empty( ( $all_categories ) ) ) {
			wp_set_object_terms( $new_post_id, $all_categories, 'category' );
		}

		if ( ! empty( ( $all_tags ) ) ) {
			wp_set_object_terms( $new_post_id, $all_tags, 'post_tag' );
		}

		// If the copy is published or scheduled, we have to set a proper slug.
		if ( $new_post_status == 'publish' || $new_post_status == 'future' ) {
			$post_name = wp_unique_post_slug( $post->post_name, $new_post_id, $new_post_status, $post->post_type, $new_post_parent );

			$new_post              = array();
			$new_post['ID']        = $new_post_id;
			$new_post['post_name'] = $post_name;

			// Update the post into the database
			wp_update_post( $new_post );
		}

		$current_quiz_id = get_post_meta( $post->ID, 'quiz_pro_id', true );

		if ( class_exists( '\LDLMS_DB' ) ) {
			$pro_quiz_master   = \LDLMS_DB::get_table_name( 'quiz_master' );
			$pro_quiz_question = \LDLMS_DB::get_table_name( 'quiz_question' );
		} else {
			$pro_quiz_master   = $wpdb->prefix . 'learndash_pro_quiz_master';
			$pro_quiz_question = $wpdb->prefix . 'learndash_pro_quiz_question';
		}

		//Clone quiz settings for new quiz
		$wpdb->query( "CREATE TEMPORARY TABLE tmpQuizPro SELECT * FROM $pro_quiz_master WHERE id = $current_quiz_id;" );
		$wpdb->query( "UPDATE tmpQuizPro SET id = NULL WHERE id = $current_quiz_id;" );
		$wpdb->query( "INSERT INTO  $pro_quiz_master  SELECT * FROM tmpQuizPro ;" );
		//Get new Quiz ID
		$new_quiz_id = $wpdb->insert_id;
		$wpdb->query( 'DROP TEMPORARY TABLE IF EXISTS tmpQuizPro;' );

		//Clone existing post meta & update quiz ID to new clone quiz
		$current_post_meta = get_post_meta( $post->ID );

		foreach ( $current_post_meta as $key => $value ) {
			$val = maybe_unserialize( $value[0] );
			switch ( $key ) :
				case 'quiz_pro_id':
					update_post_meta( $new_post_id, $key, $new_quiz_id );
					break;
				case 'quiz_pro_id_' . $current_quiz_id:
					update_post_meta( $new_post_id, 'quiz_pro_id_' . $new_quiz_id, $new_quiz_id );
					break;
				case 'quiz_pro_primary_' . $current_quiz_id:
					update_post_meta( $new_post_id, 'quiz_pro_primary_' . $new_quiz_id, $new_quiz_id );
					break;
				case '_sfwd-quiz':
					if ( is_array( $val ) ) {
						$sfwd_quiz = array();
						foreach ( $val as $qKey => $qVal ) {
							if ( 'sfwd-quiz_quiz_pro' === $qKey ) {
								$sfwd_quiz['sfwd-quiz_quiz_pro'] = $new_quiz_id;
							} else {
								$sfwd_quiz[ $qKey ] = $qVal;
							}
						}
						update_post_meta( $new_post_id, $key, $sfwd_quiz );
					}
					break;
				default:
					$key = str_replace( "_$current_quiz_id", "_$new_quiz_id", $key );
					$val = str_replace( $current_quiz_id, $new_quiz_id, $val );
					update_post_meta( $new_post_id, $key, $val );
			endswitch;

		}

		if ( (string) \LearnDash_Settings_Section::get_section_setting( 'LearnDash_Settings_Quizzes_Builder', 'shared_questions' ) === 'yes' ) {
			//$quiz_sharing enabled; we don't need to create new questions, just assign previous questions
			$ld_questions = get_post_meta( $post->ID, 'ld_quiz_questions', true );
			update_post_meta( $new_post_id, 'ld_quiz_questions', $ld_questions );
		} else {
			$ld_questions = get_post_meta( $post->ID, 'ld_quiz_questions', true );
			if ( $ld_questions ) {
				$new_ld_questions = array();
				foreach ( $ld_questions as $question_post_id => $quiz_pro_ques_id ) {
					if ( ! empty( $question_post_id ) ) {
						//Clone Question & Answers for new quiz in new LD post type for questions
						$wpdb->query( 'CREATE TEMPORARY TABLE tmpQuizProQuestion SELECT * FROM ' . $wpdb->posts . " WHERE ID = $question_post_id;" );
						$wpdb->query( "UPDATE tmpQuizProQuestion SET ID = NULL WHERE ID = $question_post_id;" );
						$wpdb->query( 'INSERT INTO  ' . $wpdb->posts . '  SELECT * FROM tmpQuizProQuestion;' );
						$new_ques_id = $wpdb->insert_id;
						$wpdb->query( 'DROP TEMPORARY TABLE IF EXISTS tmpQuizProQuestion;' );

						//Clone Questions for new quiz question in new LD post type for questions
						$wpdb->query( 'CREATE TEMPORARY TABLE tmpQuizProQuestionMeta SELECT * FROM ' . $wpdb->postmeta . " WHERE post_id = $question_post_id;" );
						$wpdb->query( "UPDATE tmpQuizProQuestionMeta SET meta_id = NULL, post_id = $new_ques_id WHERE post_id = $question_post_id;" );
						$wpdb->query( 'INSERT INTO  ' . $wpdb->postmeta . '  SELECT * FROM tmpQuizProQuestionMeta;' );
						$wpdb->query( 'DROP TEMPORARY TABLE IF EXISTS tmpQuizProQuestionMeta;' );
						$wpdb->query( "DELETE FROM $wpdb->postmeta WHERE post_id = $new_ques_id AND meta_key LIKE 'ld_quiz_%'" );

						//Clone Questions in Quiz Pro
						$wpdb->query( "CREATE TEMPORARY TABLE tmpQuizProQuestionMeta SELECT * FROM $pro_quiz_question WHERE id = $quiz_pro_ques_id;" );
						$wpdb->query( "UPDATE tmpQuizProQuestionMeta SET id = NULL, quiz_id = $new_quiz_id WHERE id = $quiz_pro_ques_id;" );
						$wpdb->query( "INSERT INTO  $pro_quiz_question  SELECT * FROM tmpQuizProQuestionMeta;" );
						$new_pro_ques_id = $wpdb->insert_id;
						$wpdb->query( 'DROP TEMPORARY TABLE IF EXISTS tmpQuizProQuestionMeta;' );

						update_post_meta( $new_ques_id, 'ld_quiz_' . $new_post_id, $new_post_id );
						update_post_meta( $new_ques_id, 'question_pro_id', $new_pro_ques_id );
						update_post_meta( $new_ques_id, 'quiz_id', $new_post_id );
						update_post_meta(
							$new_ques_id,
							'_sfwd-question',
							array(
								'0'                  => '',
								'sfwd-question_quiz' => $new_post_id,
							)
						);

						$new_ld_questions[ $new_ques_id ] = $new_pro_ques_id;
					}
				}
				//update new quiz with question ids
				update_post_meta( $new_post_id, 'ld_quiz_questions', $new_ld_questions );
			} else {
				//Clone Question & Answers for new quiz
				$wpdb->query( "CREATE TEMPORARY TABLE tmpQuizPro SELECT * FROM $pro_quiz_question WHERE quiz_id = $current_quiz_id;" );
				$wpdb->query( "UPDATE tmpQuizPro SET id = NULL, quiz_id = $new_quiz_id WHERE quiz_id = $current_quiz_id;" );
				$wpdb->query( "INSERT INTO  $pro_quiz_question  SELECT * FROM tmpQuizPro ;" );
				$wpdb->query( 'DROP TEMPORARY TABLE IF EXISTS tmpQuizPro;' );
			}
		}

		return $new_post_id;
	}

	/**
	 *
	 */
	public static function uncanny_clone_contents() {

		if ( ! ( isset( $_GET['post'] ) || isset( $_POST['post'] ) || ( isset( $_REQUEST['action'] ) && 'clone_post_contents' === $_REQUEST['action'] ) ) ) {
			wp_die( esc_attr__( 'No quiz to duplicate has been supplied!', 'uncanny-pro-toolkit' ) );
		}

		// Get the original post
		$id   = ( isset( $_GET['post'] ) ? $_GET['post'] : $_POST['post'] );
		$post = get_post( absint( $id ) );

		// Copy the post and insert it
		if ( isset( $post ) && $post != null ) {
			$new_id = self::duplicate_contents_create_duplicate( $post, 'draft', $post->post_parent );
			if ( isset( $_GET['return_to_post'] ) ) {
				wp_redirect( admin_url( 'post.php?post=' . $new_id . '&action=edit' ) );
			} else {
				wp_redirect( admin_url( 'edit.php?post_type=' . $post->post_type ) );
			}
			exit;

		} else {
			wp_die( esc_attr( esc_attr__( 'Copy creation failed, could not find original:', 'uncanny-pro-toolkit' ) ) . ' ' . htmlspecialchars( $id ) );
		}

	}

	/**
	 * @param        $post
	 * @param string $status
	 * @param string $parent_id
	 *
	 * @return int|\WP_Error
	 */
	public static function duplicate_contents_create_duplicate( $post, $status = '', $parent_id = '' ) {
		global $wpdb;
		// We don't want to clone revisions
		if ( 'revision' === $post->post_type ) {
			return false;
		}

		if ( 'attachment' !== $post->post_type ) {
			$status = 'draft';
		}

		// Get the shared steps settings.
		$course_settings_key = 'learndash_settings_courses_management_display';

		$original_settings = get_option( $course_settings_key );

		// Set 'course_builder_shared_steps' to yes.
		$temporary_settings                                = $original_settings;
		$temporary_settings['course_builder_shared_steps'] = 'yes';

		// LearnDash hooked on 'pre_update_option_{$this->setting_option_key}' to verify the nonce metabox. See verify_metabox_nonce_field().
		// We need to pass a correct nonce field to $_POST 'learndash_settings_courses_management_display_nonce' to change the 'course_builder_shared_steps' and to pass the nonce check.
		$_POST['learndash_settings_courses_management_display_nonce'] = wp_create_nonce( 'learndash_settings_courses_management_display' );

		// Update the shared steps settings temporarity.
		$is_updated = update_option( $course_settings_key, $temporary_settings );

		$new_post_author = wp_get_current_user();

		$new_post = array(
			'menu_order'     => $post->menu_order,
			'comment_status' => $post->comment_status,
			'ping_status'    => $post->ping_status,
			'post_author'    => $new_post_author->ID,
			'post_content'   => $post->post_content,
			'post_excerpt'   => $post->post_excerpt,
			'post_mime_type' => $post->post_mime_type,
			'post_parent'    => $new_post_parent = empty( $parent_id ) ? $post->post_parent : $parent_id,
			'post_password'  => $post->post_password,
			'post_status'    => $new_post_status = ( empty( $status ) ) ? $post->post_status : $status,
			'post_title'     => $post->post_title . ' (Duplicate)',
			'post_type'      => $post->post_type,
			'post_date'      => $post->post_date,
			'post_date_gmt'  => get_gmt_from_date( $post->post_date ),
		);

		$new_post_id = wp_insert_post( $new_post );

		// If the copy is published or scheduled, we have to set a proper slug.
		if ( 'publish' === $new_post_status || 'future' === $new_post_status ) {
			$post_name = wp_unique_post_slug( $post->post_name, $new_post_id, $new_post_status, $post->post_type, $new_post_parent );

			$new_post              = array();
			$new_post['ID']        = $new_post_id;
			$new_post['post_name'] = $post_name;

			// Update the post into the database
			wp_update_post( $new_post );
		}

		//Clone existing post meta & update quiz ID to new post / page / custom post type
		$current_post_meta = get_post_meta( $post->ID );

		if ( 'groups' === $post->post_type ) {
			//copy courses from cloned group
			if ( function_exists( 'learndash_group_enrolled_courses' ) ) {
				$courses = learndash_group_enrolled_courses( $post->ID );
				if ( ! empty( $courses ) ) {
					learndash_set_group_enrolled_courses( $new_post_id, $courses );
				}
			}
			//copy group leaders from cloned group
			if ( function_exists( 'learndash_get_groups_administrator_ids' ) ) {
				$group_leaders = learndash_get_groups_administrator_ids( $post->ID, true );
				if ( ! empty( $group_leaders ) ) {
					learndash_set_groups_administrators( $new_post_id, $group_leaders );
				}
			}
		}

		foreach ( $current_post_meta as $key => $value ) {
			$val = maybe_unserialize( $value[0] );
			// Dont set enrolled users
			if ( 'course_access_list' === $key ) {
				continue;
			}

			if ( '_sfwd-courses' === $key ) {
				if ( isset( $val['sfwd-courses_course_access_list'] ) ) {
					$val['sfwd-courses_course_access_list'] = '';
				}
			}

			switch ( $key ) :
				/**
				 * Changes if Groups plugin is active!
				 * Sept 25,2019, issue happened on PE Club site
				 */
				case '_ulgm_code_group_id':
					$code_group_id = $val;
					if ( class_exists( 'uncanny_learndash_groups\\InitializePlugin' ) ) {
						if ( ! class_exists( 'uncanny_learndash_groups\\Database' ) ) {
							include_once \uncanny_learndash_groups\Utilities::get_include( 'database.php' );
						}
						$codes_group_tbl = \uncanny_learndash_groups\SharedFunctions::$db_group_tbl;
						//Copy code group details
						$new_order_id      = \uncanny_learndash_groups\Database::get_random_order_number();
						$number_of_codes   = get_post_meta( $post->ID, '_ulgm_total_seats', true );
						$codes             = \uncanny_learndash_groups\SharedFunctions::generate_random_codes( $number_of_codes );
						$results           = $wpdb->get_row( "SELECT * FROM {$wpdb->prefix}$codes_group_tbl WHERE ID = $code_group_id" );
						$attr              = array(
							'user_id'    => $results->user_id,
							'order_id'   => $new_order_id,
							'group_id'   => $new_post_id,
							'group_name' => $post->post_title,
							'qty'        => $number_of_codes,
						);
						$new_code_group_id = \uncanny_learndash_groups\Database::add_codes( $attr, $codes );
						update_post_meta( $new_post_id, $key, $new_code_group_id );
						update_post_meta( $new_post_id, '_ulgm_is_custom_group_created', 'yes' );

						//Fix if group leader is part of group and/or takes up seat
						$group_leaders = learndash_get_groups_administrator_ids( $new_post_id, true );
						if ( count( $group_leaders ) ) {
							foreach ( $group_leaders as $group_leader ) {
								$rest_api  = new \uncanny_learndash_groups\RestApiEndPoints();
								$user      = get_user_by( 'ID', $group_leader );
								$user_data = array(
									'user_email' => $user->user_email,
									'user_id'    => $user->ID,
								);

								$status = 'redeemed';

								$is_member = \uncanny_learndash_groups\SharedFunctions::is_user_already_member_of_group( $user->ID, $new_post_id );
								if ( 'yes' !== get_option( 'do_not_add_group_leader_as_member', 'no' ) && 'no' === $is_member ) {
									$rest_api->add_existing_user( $user_data, true, $new_post_id, $new_order_id, $status, false );
								}
							}
						}
						//
					}
					break;
				case '_elementor_data':
					$meta = get_post_meta( $post->ID, $key, true );

					if ( is_string( $meta ) && ! empty( $meta ) ) {
						$meta = json_decode( $meta, true );
					} else {
						$meta = array();
					}
					$json_value = wp_slash( wp_json_encode( $meta ) );
					update_metadata( 'post', $new_post_id, $key, $json_value );
					break;
				default:
					update_post_meta( $new_post_id, $key, $val );
			endswitch;
		}

		$get_tags_terms_cats = $wpdb->get_var( "SELECT COUNT(object_id) AS total FROM $wpdb->term_relationships WHERE object_id = " . $post->ID );
		if ( $get_tags_terms_cats > 0 ) {
			//Clone quiz settings for new quiz
			$wpdb->query( 'DELETE FROM  ' . $wpdb->term_relationships . " WHERE object_id = $new_post_id;" );
			$wpdb->query( 'CREATE TEMPORARY TABLE tmpCopyCats SELECT * FROM ' . $wpdb->term_relationships . ' WHERE object_id = ' . $post->ID . ';' );
			$wpdb->query( "UPDATE tmpCopyCats SET object_id = $new_post_id WHERE object_id = $post->ID;" );
			$wpdb->query( 'INSERT INTO  ' . $wpdb->term_relationships . '  SELECT * FROM tmpCopyCats ;' );
			$wpdb->query( 'DROP TEMPORARY TABLE IF EXISTS tmpCopyCats;' );

		}

		if ( 'sfwd-question' === $post->post_type ) {
			$quiz_pro_ques_id = reset( $current_post_meta['question_pro_id'] );

			if ( class_exists( '\LDLMS_DB' ) ) {
				$pro_quiz_question = \LDLMS_DB::get_table_name( 'quiz_question' );
			} else {
				$pro_quiz_question = $wpdb->prefix . 'learndash_pro_quiz_question';
			}
			//Clone Questions in Quiz Pro
			$wpdb->query( "CREATE TEMPORARY TABLE tmpQuizProQuestionMeta SELECT * FROM {$pro_quiz_question} WHERE id = $quiz_pro_ques_id;" );
			$wpdb->query( "UPDATE tmpQuizProQuestionMeta SET id = NULL WHERE id = $quiz_pro_ques_id;" );
			$wpdb->query( "INSERT INTO  $pro_quiz_question  SELECT * FROM tmpQuizProQuestionMeta;" );
			$new_pro_ques_id = $wpdb->insert_id;
			$wpdb->query( 'DROP TEMPORARY TABLE IF EXISTS tmpQuizProQuestionMeta;' );

			update_post_meta( $new_post_id, 'question_pro_id', $new_pro_ques_id );
		}

		if ( class_exists( 'LDLMS_Course_Steps' ) ) {
			if ( \LearnDash_Settings_Section::get_section_setting( 'LearnDash_Settings_Courses_Builder', 'enabled' ) == 'yes' ) {
				// Rebuild Course Steps
				$course_set = new \LDLMS_Course_Steps( $post->ID );
				$course_set->load_steps();
				$get_steps       = $course_set->get_steps();
				$course_set_orig = new \LDLMS_Course_Steps( $new_post_id );
				$course_set_orig->set_steps( $get_steps );
			}
		}

		// Restore the settings to original.
		update_option( $course_settings_key, $original_settings );

		return $new_post_id;

	}
}