function wpv_create_layout_content_template()
{
    if (!current_user_can('manage_options')) {
        $data = array('type' => 'capability', 'message' => __('You do not have permissions for that.', 'wpv-views'));
        wp_send_json_error($data);
    }
    if (!isset($_POST["wpnonce"]) || !wp_verify_nonce($_POST["wpnonce"], 'layout_wizard_nonce')) {
        $data = array('type' => 'nonce', 'message' => __('Your security credentials have expired. Please reload the page to get new ones.', 'wpv-views'));
        wp_send_json_error($data);
    }
    if (!isset($_POST["view_id"]) || !is_numeric($_POST["view_id"]) || intval($_POST['view_id']) < 1) {
        $data = array('type' => 'id', 'message' => __('Wrong or missing ID.', 'wpv-views'));
        wp_send_json_error($data);
    }
    $template = wpv_create_content_template('Loop item in ' . $_POST['view_name']);
    $view_id = $_POST['view_id'];
    if (isset($template['success'])) {
        update_post_meta($view_id, '_view_loop_template', $template['success']);
        update_post_meta($template['success'], '_view_loop_id', $view_id);
        $ct_post_id = $template['success'];
        $data = array('id' => $view_id, 'message' => __('Content Template for this Loop Output created', 'wpv-views'), 'template_id' => $ct_post_id, 'template_title' => $template['title']);
        $post = get_post($ct_post_id);
        $meta = get_post_meta($view_id, '_wpv_layout_settings', true);
        $reg_templates = array();
        if (isset($meta['included_ct_ids'])) {
            $reg_templates = explode(',', $meta['included_ct_ids']);
        }
        if (!in_array($ct_post_id, $reg_templates)) {
            array_unshift($reg_templates, $ct_post_id);
            $meta['included_ct_ids'] = implode(',', $reg_templates);
            update_post_meta($view_id, '_wpv_layout_settings', $meta);
            ob_start();
            wpv_list_view_ct_item($post, $ct_post_id, $view_id, true);
            $data['template_html'] = ob_get_clean();
        }
        do_action('wpv_action_wpv_save_item', $view_id);
        wp_send_json_success($data);
    } else {
        $data = array('type' => 'error', 'message' => __('Could not create a Content Template for this Loop Output. Please reload the page and try again.', 'wpv-views'));
        wp_send_json_error($data);
    }
}
function wpv_add_view_template_callback()
{
    if (!current_user_can('manage_options')) {
        die("Security check");
    }
    if (!isset($_POST["wpnonce"]) || !wp_verify_nonce($_POST["wpnonce"], 'wpv_inline_content_template') && !wp_verify_nonce($_POST["wpnonce"], 'wpv-ct-inline-edit')) {
        die("Security check");
    }
    if (!isset($_POST['view_id']) || !is_numeric($_POST["view_id"]) || intval($_POST['view_id']) < 1) {
        echo 'error';
        die;
    }
    $ct_post_id = 0;
    $view_id = sanitize_text_field($_POST['view_id']);
    if (isset($_POST['template_name'])) {
        // We need to create a new Content Template based on the POSTed template_name
        $template_name = sanitize_text_field($_POST['template_name']);
        $response = wpv_create_content_template($template_name, '', false, '');
        if (isset($response['error'])) {
            // Another Content Template with that title or name already exists
            echo 'error_name';
            die;
        } else {
            if (isset($response['success'])) {
                // Everything went well
                $ct_post_id = $response['success'];
            }
        }
    } else {
        if (isset($_POST['template_id'])) {
            $ct_post_id = sanitize_text_field($_POST['template_id']);
        }
    }
    $ct_post_object = get_post($ct_post_id);
    if (!is_object($ct_post_object)) {
        echo 'error';
        die;
    }
    $meta = get_post_meta($view_id, '_wpv_layout_settings', true);
    $reg_templates = array();
    if (isset($meta['included_ct_ids'])) {
        $reg_templates = explode(',', $meta['included_ct_ids']);
    }
    if (in_array($ct_post_id, $reg_templates)) {
        // The Content Template was already on the inline list
        echo 'wp_success';
    } else {
        // Add the Content Template to the inline list and save it
        $reg_templates[] = $ct_post_id;
        $meta['included_ct_ids'] = implode(',', $reg_templates);
        update_post_meta($view_id, '_wpv_layout_settings', $meta);
        do_action('wpv_action_wpv_save_item', $view_id);
        wpv_list_view_ct_item($ct_post_object, $ct_post_id, $view_id, true);
    }
    die;
}
function wpv_ct_create_new_save_callback()
{
    if ( ! current_user_can( 'manage_options' ) ) {
        die( "Untrusted user" );
    }
    if (
        ! isset( $_POST["wpnonce"] )
        || ! wp_verify_nonce( $_POST["wpnonce"], 'work_view_template' )
    ) {
        die( "Undefined Nonce" );
    }
    $title = '';
    if ( isset( $_POST['title'] ) ) {
        $title = sanitize_text_field( $_POST['title'] );
    }
    if ( empty( $title ) ) {
        print json_encode( array( 'error', __( 'You can not create a Content Template with an empty name.', 'wpv-views' ) ) );
        die();
    }
    if ( ! isset( $_POST['type'] ) ) {
        $_POST['type'] = array( 0 );
    }
    $type = $_POST['type'];
    $create_template = wpv_create_content_template( $title, '', false, '' );
    if ( isset( $create_template['error'] ) ) {
        print json_encode( array( 'error', __( 'A Content Template with that name already exists. Please use another name.', 'wpv-views' ) ) );
        die();
    }
    if ( isset( $create_template['success'] ) ) {
        if ( $type[0] != '0' ) {
            global $WPV_settings;
            foreach ( $type as $type_to_save ) {
                $type_to_save = sanitize_text_field( $type_to_save );
                $WPV_settings[ $type_to_save ] = $create_template['success'];
            }
            $WPV_settings->save();
        }
        print json_encode( array( $create_template['success'] ) );
    } else {
        print json_encode( array( 'error', __( 'An unexpected error happened.', 'wpv-views' ) ) );
    }
    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 ddl_add_view_template_callback()
{
    global $wpdb;
    if (WPDD_Utils::user_not_admin()) {
        die(__("You don't have permission to perform this action!", 'ddl-layouts'));
    }
    //add new content template
    if (!isset($_POST["wpnonce"]) || !wp_verify_nonce($_POST["wpnonce"], 'wpv-ct-inline-edit')) {
        die("Undefined Nonce.");
    }
    $template_content = '';
    // Prevent backwards compatibility issues
    if (function_exists('wpv_create_content_template')) {
        // set the template title
        // empty suffix - Layouts handles the need of ta suffix and adds it automatically to the passed title
        // no need to force - Layouts handles the uniqueness of the title
        // set the template content
        $content_template = wpv_create_content_template($_POST['ct_name'], '', true, $template_content);
        $ct_post_id = $content_template['success'];
    } else {
        $new_template = array('post_title' => $_POST['ct_name'], 'post_type' => 'view-template', 'post_status' => 'publish', 'post_content' => $template_content);
        $ct_post_id = wp_insert_post($new_template);
        update_post_meta($ct_post_id, '_wpv_view_template_mode', 'raw_mode');
        update_post_meta($ct_post_id, '_wpv-content-template-decription', '');
    }
    echo wp_json_encode(array('id' => $ct_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;
}