/**
     * Create a new WordPress Archive.
     *
     * If the query mode is set to "layouts-loop", also automatically create new Loop template.
     *
     * @param string $title New WPA title. Must be unique and valid (see validate_title()).
     * @param array $args (
     *          @type array $view_settings View settings that should override the default ones. Optional.
     *          @type array $loop_settings Loop settings that should override the default ones. Optional.
     *          @type bool $forbid_loop_template Never create a Loop template for this View. Optional, default is false.
     *     )
     *
     * @return WPV_WordPress_Archive New WPA object.
     *
     * @throws InvalidArgumentException
     * @throws RuntimeException
     * @throws WPV_RuntimeExceptionWithMessage
     *
     * @note overriding default Views settings and layout settings must provide complete data when the element is an
     * array, because it overrides them all. For example, $args['settings']['pagination'] can not override just the
     * "postsper page" options: it must provide a complete pagination implementation. This might change and be corrected
     * in the future, keeping backwards compatibility.
     *
     * @since 1.10
     */
    public static function create( $title, $args ) {

        $wpa_id = WPV_View_Base::create_post( $title );

        $wpa = new WPV_WordPress_Archive( $wpa_id );

        $wpa->defer_after_update_actions();

        // Construct default View settings and Loop settings
        $view_settings = wpv_getarr( $args, 'view_settings', array() );

        $query_mode = wpv_getarr( $view_settings, WPV_View_Base::VIEW_SETTINGS_QUERY_MODE, 'archive', array( 'archive', 'layouts-loop' ) );
        $view_settings[ WPV_View_Base::VIEW_SETTINGS_QUERY_MODE ] = $query_mode;
        $is_layouts_loop = ( 'layouts-loop' == $query_mode );

        $view_settings_default = wpv_wordpress_archives_defaults( 'view_settings' );
        $view_settings = wp_parse_args( $view_settings, $view_settings_default );

        $wpa->update_postmeta( WPV_View_Base::POSTMETA_VIEW_SETTINGS, $view_settings );

        $loop_settings_default = wpv_wordpress_archives_defaults( 'view_layout_settings' );

        // Modify default loop output for Layouts loop
        if ( $is_layouts_loop ) {
            $loop_settings_default[ WPV_View_Base::LOOP_SETTINGS_META_HTML ] = str_replace(
                "[/wpv-items-found]",
                "[wpv-archive-pager-prev-page]\n"
                . "\t\t[wpml-string context=\"wpv-views\"]Older posts[/wpml-string]\n"
                . "\t[/wpv-archive-pager-prev-page]\n"
                . "\t[wpv-archive-pager-next-page]\n"
                . "\t\t[wpml-string context=\"wpv-views\"]Newer posts[/wpml-string]\n"
                . "\t[/wpv-archive-pager-next-page]\n"
                . "\t[/wpv-items-found]",
                $loop_settings_default[ WPV_View_Base::LOOP_SETTINGS_META_HTML ]
            );
        }

        $loop_settings = wpv_getarr( $args, 'loop_settings', array() );
        $loop_settings = wp_parse_args( $loop_settings, $loop_settings_default );

        $wpa->update_postmeta( WPV_View_Base::POSTMETA_LOOP_SETTINGS, $loop_settings );

        // Create Loop template for Layouts loop
        $forbid_loop_template = wpv_getarr( $args, 'forbid_loop_template', false );
        if( ! $forbid_loop_template && $is_layouts_loop ) {

            $ct_title = sprintf( '%s - %s', $title, __( 'loop item', 'wpv-views' ) );
            $ct_content = sprintf(
                "<h1>[wpv-post-title]</h1>\n[wpv-post-body view_template=\"None\"]\n[wpv-post-featured-image]\n%s",
                sprintf(__('Posted by %s on %s', 'wpv-views'), '[wpv-post-author]', '[wpv-post-date]' )
            );
            $wpa->create_loop_template( $ct_title, $ct_content );
        }


        $wpa->resume_after_update_actions();

        return $wpa;
    }
function wp_ajax_wpv_create_wpa_for_archive_loop_callback() {
	wpv_ajax_authenticate( 'work_views_listing', array( 'parameter_source' => 'post', 'type_of_death' => 'data' ) );
	
	global $wpdb, $WPV_view_archive_loop;
	$existing = $wpdb->get_var(
		$wpdb->prepare(
			"SELECT ID FROM {$wpdb->posts} 
			WHERE ( post_title = %s OR post_name = %s ) 
			AND post_type = 'view' 
			LIMIT 1",
			$_POST["title"],
			$_POST["title"]
		)
	);
	if ( $existing ) {
		$data = array(
			'message'	=> __( 'A WordPress Archive with that name already exists. Please use another name.', 'wpv-views' )
		);
		wp_send_json_error( $data );
	}
	$new_archive = array(
		'post_title'    => sanitize_text_field( $_POST["title"] ),
		'post_type'     => 'view',
		'post_content'  => "[wpv-layout-meta-html]",
		'post_status'   => 'publish',
		'post_author'   => get_current_user_id(),
		'comment_status' => 'closed'
	);
	$post_id = wp_insert_post( $new_archive );
	$archive_defaults = wpv_wordpress_archives_defaults( 'view_settings' );
	$archive_layout_defaults = wpv_wordpress_archives_defaults( 'view_layout_settings' );
	update_post_meta( $post_id, '_wpv_settings', $archive_defaults );
	update_post_meta( $post_id, '_wpv_layout_settings', $archive_layout_defaults );
	
	$form_data = array(
		sanitize_text_field( $_POST['loop'] ) => $post_id
	);
	$WPV_view_archive_loop->update_view_archive_settings( $post_id, $form_data );
	$data = array(
		'id' => $post_id
	);
	wp_send_json_success( $data );
}
function wp_ajax_wpv_create_usage_archive_view_callback()
{
    $nonce = $_POST["wpnonce"];
    if (!wp_verify_nonce($nonce, 'work_views_listing')) {
        die("Security check");
    }
    global $wpdb, $WPV_view_archive_loop;
    parse_str($_POST['form'], $form_data);
    // Create archive
    $postid = $wpdb->get_var("SELECT ID FROM {$wpdb->posts} WHERE post_title = '" . $form_data["wpv-new-archive-name"] . "' AND post_type='view'");
    if (!empty($postid)) {
        echo 'error';
        die;
    }
    $new_archive = array('post_title' => $form_data["wpv-new-archive-name"], 'post_type' => 'view', 'post_content' => "[wpv-layout-meta-html]", 'post_status' => 'publish', 'post_author' => get_current_user_id(), 'comment_status' => 'closed');
    $post_id = wp_insert_post($new_archive);
    $archive_defaults = wpv_wordpress_archives_defaults('view_settings');
    $archive_layout_defaults = wpv_wordpress_archives_defaults('view_layout_settings');
    update_post_meta($post_id, '_wpv_settings', $archive_defaults);
    update_post_meta($post_id, '_wpv_layout_settings', $archive_layout_defaults);
    $WPV_view_archive_loop->update_view_archive_settings($post_id, $form_data);
    echo $post_id;
    die;
}
    /**
     * Creates a Content Template for WordPress Archive for a Post Type, 
     * Taxonomy or WordPress Page with default settings and assigns it to the
     * right item.
     * 
     * Used by Toolset_Admin_Bar_Menu.
     * 
     * Expected $_GET parameters
     * type: post type, taxonomy or special wordpress archive
     * class: is it an archive page or a content template page
     * post: post_id or empty
     * 
     */
    public function create_ct_or_wpa_auto() {
        
        // verify permissions
        if( ! current_user_can( 'manage_options' ) ) {
            die( __( 'Untrusted user', 'wpv-views' ) );
        }
        
        // verify nonce
        check_admin_referer( 'create_auto' );
        
        // validate parameters
        $b_type = isset( $_GET['type'] ) && preg_match( '/^([-a-z0-9_]+)$/', $_GET['type'] );
        $b_class = isset( $_GET['class'] ) && preg_match( '/^(archive|page)$/', $_GET['class'] );
        $b_post_id = isset( $_GET['post'] ) && (int) $_GET['post'] >= 0;

        // validate request
        if( ! ( $b_type && $b_class && $b_post_id ) ) {
            die( __( 'Invalid parameters', 'wpv-views' ) );
        }
        
        // get parameters
        $type = $_GET['type'];
        $class = $_GET['class'];
        $post_id = (int) $_GET['post'];
        
        // enforce rules
        $b_page_archive = 'page' === $type && 'archive' === $class;
        $b_404 = '404' === $type;
        if( $b_page_archive || $b_404 ) {
            die( __( 'Not allowed', 'wpv-views' ) );
        }
        
        // prepare processing
        if( $post_id === 0 ) {
            $post_id = null;
        }
        
        $wpa_id = 0;
        $ct_id = 0;
        
        global $WPV_settings;
        global $toolset_admin_bar_menu;
        $post_title = $toolset_admin_bar_menu->get_name_auto( 'views', $type, $class, $post_id );
        $title = sanitize_text_field( $post_title );
        
        $taxonomy = get_taxonomy( $type );
        $is_tax = $taxonomy !== false;

        $post_type_object = get_post_type_object( $type );
        $is_cpt = $post_type_object != null;
        
        // route request
        if( 'archive' === $class ) {
            
            // Create a new WordPress Archive
            global $wpdb, $WPV_view_archive_loop;
            
            // Is there another WordPress Archive with the same name?
            $already_exists = $wpdb->get_var(
                $wpdb->prepare(
                    "SELECT ID FROM {$wpdb->posts} 
                    WHERE ( post_title = %s OR post_name = %s ) 
                    AND post_type = 'view' 
                    LIMIT 1",
                    $title,
                    $title
                )
            );
            if( $already_exists ) {
                die( __( 'A WordPress Archive with that name already exists. Please use another name.', 'wpv-views' ) );
            }
            
            $args = array(
                'post_title'    => $title,
                'post_type'      => 'view',
                'post_content'  => "[wpv-layout-meta-html]",
                'post_status'   => 'publish',
                'post_author'   => get_current_user_id(),
                'comment_status' => 'closed'
            );
            $wpa_id = wp_insert_post( $args );
            $wpa_type = '';
            
            if( in_array( $type, Toolset_Admin_Bar_Menu::$default_wordpress_archives )  ) {
                
                // Create a new WordPress Archive for X archives
                
                /* assign WordPress Archive to X archives */
                $wpa_type = sprintf( 'wpv-view-loop-%s-page', $type );
                
            } else if( $is_tax ) {
                
                // Create a new WordPress Archive for Ys
                
                /* assign WordPress Archive to Y */
                $wpa_type = sprintf( 'wpv-view-taxonomy-loop-%s', $type );
                
            } else if( $is_cpt ) {
                
                // Create a new WordPress Archive for Zs
                
                /* assign WordPress Archive to Z */
                $wpa_type = sprintf( 'wpv-view-loop-cpt_%s', $type );
                
            } else {
                die( __( 'An unexpected error happened.', 'wpv-views' ) );
            }
            
            $archive_defaults = wpv_wordpress_archives_defaults( 'view_settings' );
            $archive_layout_defaults = wpv_wordpress_archives_defaults( 'view_layout_settings' );
            update_post_meta( $wpa_id, '_wpv_settings', $archive_defaults );
            update_post_meta( $wpa_id, '_wpv_layout_settings', $archive_layout_defaults );
            
            $data = array( $wpa_type => 'on' );
            $WPV_view_archive_loop->update_view_archive_settings( $wpa_id, $data );
            
        } else if( 'page' === $class ) {
            
            // Create a new Content Template
            $create_template = wpv_create_content_template( $title, '', true, '' );
            if ( isset( $create_template['error'] ) ) {
                die( __( 'A Content Template with that name already exists. Please use another name.', 'wpv-views' ) );
            }
            
            if( ! isset( $create_template['success'] ) || (int) $create_template['success'] == 0 ) {
                die( __( 'An unexpected error happened.', 'wpv-views' ) );
            }
            
            $ct_id = $create_template['success'];
            $ct_type = '';
            
            if( 'page' === $type ) {
                
                // Create a new Content Template for 'Page Title'
                
                /* assign Content Template to Page */
                update_post_meta( $post_id, '_views_template', $ct_id );
                
            } else if( $is_cpt ) {
                
                // Create a new Content Template for Ys
                
                /* assign Content Template to Y */
                $ct_type = sanitize_text_field( sprintf( 'views_template_for_%s', $type ) );
                $WPV_settings[$ct_type] = $ct_id;
                
            } else {
                die( __( 'An unexpected error happened.', 'wpv-views' ) );
            }
            
        }
        
        // update changes
        $WPV_settings->save();
        
        // redirect to editor or die
        $template_id = max( array( $wpa_id, $ct_id ) );
        
        if( $template_id === 0 ) {
            die( __( 'Unexpected error. Nothing was changed.', 'wpv-views' ) );
        }
        
        // redirect to editor (headers already sent)
        $edit_link = $toolset_admin_bar_menu->get_edit_link( 'views', false, $type, $class, $template_id );
        $exit_string = '<script type="text/javascript">'.'window.location = "' . $edit_link . '";'.'</script>';
        exit( $exit_string );
    }
function wp_ajax_wpv_create_usage_archive_view_callback()
{
    if (!current_user_can('manage_options')) {
        die("Untrusted user");
    }
    if (!wp_verify_nonce($_POST["wpnonce"], 'work_views_listing')) {
        die("Security check");
    }
    if (!isset($_POST["form"])) {
        die("Untrusted data");
    }
    global $wpdb, $WPV_view_archive_loop;
    parse_str($_POST['form'], $form_data);
    // Create archive
    $existing = $wpdb->get_var($wpdb->prepare("SELECT ID FROM {$wpdb->posts} \n\t\t\tWHERE ( post_title = %s OR post_name = %s ) \n\t\t\tAND post_type = 'view' \n\t\t\tLIMIT 1", $form_data["wpv-new-archive-name"], $form_data["wpv-new-archive-name"]));
    if ($existing) {
        echo 'error';
        die;
    }
    $new_archive = array('post_title' => $form_data["wpv-new-archive-name"], 'post_type' => 'view', 'post_content' => "[wpv-layout-meta-html]", 'post_status' => 'publish', 'post_author' => get_current_user_id(), 'comment_status' => 'closed');
    $post_id = wp_insert_post($new_archive);
    $archive_defaults = wpv_wordpress_archives_defaults('view_settings');
    $archive_layout_defaults = wpv_wordpress_archives_defaults('view_layout_settings');
    update_post_meta($post_id, '_wpv_settings', $archive_defaults);
    update_post_meta($post_id, '_wpv_layout_settings', $archive_layout_defaults);
    $WPV_view_archive_loop->update_view_archive_settings($post_id, $form_data);
    echo $post_id;
    die;
}
/**
* wpv_create_view
*
* API function to create a new View
*
* @param $args (array) set of arguments for the new View
*    'title' (string) (semi-mandatory) Title for the View
*    'settings' (array) (optional) Array compatible with the View settings to override the defaults
*    'layout_settings' (array) (optional) Array compatible with the View layout settings to override the defaults
*
* @return (array) response of the operation, one of the following
*    $return['success] = View ID
*    $return['error'] = 'Error message'
*
* @since 1.6.0
*
* @note overriding default Views settings and layout settings must provide complete data when the element is an array, because it overrides them all.
*    For example, $args['settings']['pagination'] can not override just the "postsper page" options: it must provide a complete pagination implementation.
*    This might change and be corrected in the future, keeping backwards compatibility.
*
* @todo once we create a default layout for a View, we need to make sure that:
* - the _view_loop_template postmeat is created and updated - DONE
* - the fields added to that loop Template are stored in the layout settings - PENDING
* - check how Layouts can apply this all to their Views, to create a Bootstrap loop by default - PENDING
*/
function wpv_create_view($args)
{
    global $wpdb;
    $return = array();
    // First, set the title
    if (!isset($args["title"]) || $args["title"] == '') {
        $args["title"] = __('Unnamed View', 'wp-views');
    }
    // Check for already existing Views with that title
    $existing = $wpdb->get_var($wpdb->prepare("SELECT ID FROM {$wpdb->posts} \n\t\t\tWHERE ( post_title = %s OR post_name = %s ) \n\t\t\tAND post_type = 'view' \n\t\t\tLIMIT 1", $args["title"], $args["title"]));
    if ($existing) {
        $return['error'] = __('A View with that name already exists. Please use another name.', 'wpv-views');
        return $return;
    }
    // Compose the $post to be created
    $post = array('post_type' => 'view', 'post_title' => $args["title"], 'post_status' => 'publish', 'post_content' => "[wpv-filter-meta-html]\n[wpv-layout-meta-html]");
    $id = wp_insert_post($post);
    if (0 != $id) {
        if (!isset($args['settings']) || !is_array($args['settings'])) {
            $args['settings'] = array();
        }
        if (!isset($args['layout_settings']) || !is_array($args['layout_settings'])) {
            $args['layout_settings'] = array();
        }
        if (!isset($args['settings']["view-query-mode"])) {
            $args['settings']["view-query-mode"] = 'normal';
            // TODO check if view-query-mode is needed anymore, see below
        }
        if (!isset($args['settings']["view_purpose"])) {
            $args['settings']["view_purpose"] = 'full';
        }
        $create_loop_template = false;
        $create_loop_template_suffix = '';
        $create_loop_template_content = '';
        $create_loop_template_layout = '';
        $add_archive_pagination = false;
        switch ($args['settings']["view-query-mode"]) {
            case 'archive':
                $view_normal_defaults = wpv_wordpress_archives_defaults('view_settings');
                $view_normal_layout_defaults = wpv_wordpress_archives_defaults('view_layout_settings');
                break;
            case 'layouts-loop':
                $view_normal_defaults = wpv_wordpress_archives_defaults('view_settings');
                $view_normal_layout_defaults = wpv_wordpress_archives_defaults('view_layout_settings');
                $create_loop_template = true;
                $create_loop_template_suffix = __('loop item', 'wpv-views');
                $create_loop_template_content = "<h1>[wpv-post-title]</h1>\n[wpv-post-body view_template=\"None\"]\n[wpv-post-featured-image]\n" . sprintf(__('Posted by %s on %s', 'wpv-views'), '[wpv-post-author]', '[wpv-post-date]');
                $add_archive_pagination = true;
                break;
            default:
                $view_normal_defaults = wpv_view_defaults('view_settings', $args['settings']["view_purpose"]);
                $view_normal_layout_defaults = wpv_view_defaults('view_layout_settings', $args['settings']["view_purpose"]);
                if ($args['settings']["view_purpose"] == 'slider') {
                    $create_loop_template = true;
                    $create_loop_template_suffix = __('slide', 'wpv-views');
                    $create_loop_template_content = '[wpv-post-link]';
                } else {
                    if ($args['settings']["view_purpose"] == 'bootstrap-grid') {
                        // Deprecated in Views 1.7, keep for backwards compatibility
                        $args['settings']["view_purpose"] = 'full';
                    }
                }
                break;
        }
        if ($create_loop_template) {
            // @todo review
            // This creates the Template, but it does not adjust the Layout Wizard settings to use it, in case someone touches it
            $template = wpv_create_content_template($args["title"], $create_loop_template_suffix, true, $create_loop_template_content);
            if (isset($template['success'])) {
                $template_id = $template['success'];
                if (isset($template['title'])) {
                    $template_title = $template['title'];
                } else {
                    $template_object = get_post($template_id);
                    $template_title = $template_object->post_title;
                }
                // @todo here we should create the layout acordingly to the $create_loop_template_layout value
                $view_normal_layout_defaults['layout_meta_html'] = str_replace("<wpv-loop>", "<wpv-loop>\n\t\t\t[wpv-post-body view_template=\"" . $template_title . "\"]", $view_normal_layout_defaults['layout_meta_html']);
                $view_normal_layout_defaults['included_ct_ids'] = $template_id;
                update_post_meta($id, '_view_loop_template', $template_id);
                update_post_meta($template_id, '_view_loop_id', $id);
                // @todo
                // I really hate this solution
                update_post_meta($id, '_wpv_first_time_load', 'on');
            }
        }
        if ($add_archive_pagination) {
            $view_normal_layout_defaults['layout_meta_html'] = str_replace("[/wpv-items-found]", "[wpv-archive-pager-prev-page]\n\t\t[wpml-string context=\"wpv-views\"]Older posts[/wpml-string]\n\t[/wpv-archive-pager-prev-page]\n\t[wpv-archive-pager-next-page]\n\t\t[wpml-string context=\"wpv-views\"]Newer posts[/wpml-string]\n\t[/wpv-archive-pager-next-page]\n\t[/wpv-items-found]", $view_normal_layout_defaults['layout_meta_html']);
        }
        // Override the settings with our own
        foreach ($args['settings'] as $key => $value) {
            $view_normal_defaults[$key] = $args['settings'][$key];
        }
        // Override the layout settings with our own
        foreach ($args['layout_settings'] as $key => $value) {
            $view_normal_layout_defaults[$key] = $args['layout_settings'][$key];
        }
        // Set the whole View settings
        update_post_meta($id, '_wpv_settings', $view_normal_defaults);
        update_post_meta($id, '_wpv_layout_settings', $view_normal_layout_defaults);
        $return['success'] = $id;
    } else {
        $return['error'] = __('The View could not be created.', 'wpv-views');
        return $return;
    }
    return $return;
}