/**
 * Field pre-save filter.
 *
 * @param array $data
 * @return array
 */
function wpcf_cd_field_pre_save_filter($data)
{
    if (empty($data['conditional_display'])) {
        $data['conditional_display'] = array();
    } else {
        if (!empty($data['conditional_display']['conditions'])) {
            foreach ($data['conditional_display']['conditions'] as $k => $condition) {
                if (!array_key_exists('field', $condition)) {
                    continue;
                }
                $field = wpcf_admin_fields_get_field($condition['field']);
                if (!empty($field)) {
                    // Date conversions
                    if ($field['type'] == 'date' && isset($condition['date']) && isset($condition['month']) && isset($condition['year'])) {
                        $time = adodb_mktime(0, 0, 0, $condition['month'], $condition['date'], $condition['year']);
                        if (wpcf_fields_date_timestamp_is_valid($time)) {
                            $condition['value'] = $time;
                        }
                        /*
                                            $date = date( wpcf_get_date_format(), $time );
                                            if ( $date !== false ) {
                                                $condition['value'] = $date;
                                            }
                        */
                    }
                    if (isset($condition['date']) && isset($condition['month']) && isset($condition['year'])) {
                        unset($condition['date'], $condition['month'], $condition['year']);
                    }
                    $data['conditional_display']['conditions'][$k] = $condition;
                }
            }
        }
    }
    return $data;
}
Esempio n. 2
0
/**
 * Editor callback form submit.
 */
function wpcf_fields_checkboxes_editor_submit()
{
    $add = '';
    $field = wpcf_admin_fields_get_field($_GET['field_id']);
    $shortcode = '';
    if (!empty($field)) {
        if (!empty($_POST['options'])) {
            if ($_POST['display'] == 'display_all') {
                $separator = !empty($_POST['separator']) ? $_POST['separator'] : '';
                $shortcode .= '[types field="' . $field['slug'] . '" separator="' . $separator . '"]' . '[/types] ';
            } else {
                $i = 0;
                foreach ($_POST['options'] as $option_key => $option) {
                    if ($_POST['display'] == 'value') {
                        $shortcode .= '[types field="' . $field['slug'] . '" option="' . $i . '" state="checked"]' . $option['display_value_selected'] . '[/types] ';
                        $shortcode .= '[types field="' . $field['slug'] . '" option="' . $i . '" state="unchecked"]' . $option['display_value_not_selected'] . '[/types] ';
                    } else {
                        $add = ' option="' . $i . '"';
                        $shortcode .= wpcf_fields_get_shortcode($field, $add) . ' ';
                    }
                    $i++;
                }
            }
        }
        echo editor_admin_popup_insert_shortcode_js($shortcode);
        die;
    }
}
Esempio n. 3
0
/**
 * Gets field.
 *
 * @param string $field
 * @param string $meta_type
 * @return array
 */
function types_get_field($field, $meta_type = 'postmeta')
{
    static $cache = array();
    $cache_key = md5(strval($field) . strval($meta_type));
    if (isset($cache[$cache_key])) {
        return $cache[$cache_key];
    }
    WPCF_Loader::loadInclude('fields');
    $meta_type = $meta_type == 'usermeta' ? 'wpcf-usermeta' : 'wpcf-fields';
    $cache[$cache_key] = wpcf_admin_fields_get_field(strval($field), false, false, false, $meta_type);
    return $cache[$cache_key];
}
Esempio n. 4
0
/**
 * Editor callback form submit.
 */
function wpcf_fields_numeric_editor_submit()
{
    $add = '';
    if (!empty($_POST['format'])) {
        $add .= ' format="' . strval($_POST['format']) . '"';
    }
    $field = wpcf_admin_fields_get_field($_GET['field_id']);
    if (!empty($field)) {
        $shortcode = wpcf_fields_get_shortcode($field, $add);
        wpcf_admin_fields_save_field_last_settings($_GET['field_id'], array('format' => $_POST['format']));
        echo editor_admin_popup_insert_shortcode_js($shortcode);
        die;
    }
}
Esempio n. 5
0
/**
 * Editor callback form submit.
 */
function wpcf_fields_url_editor_submit()
{
    $add = '';
    if (!empty($_POST['title'])) {
        $add .= ' title="' . strval($_POST['title']) . '"';
    }
    $add .= ' class=""';
    $field = wpcf_admin_fields_get_field($_GET['field_id']);
    if (!empty($field)) {
        $shortcode = wpcf_fields_get_shortcode($field, $add);
        echo wpcf_admin_fields_popup_insert_shortcode_js($shortcode);
        die;
    }
}
Esempio n. 6
0
/**
 * Editor callback form submit.
 */
function wpcf_fields_email_editor_submit()
{
    $add = '';
    if (!empty($_POST['title'])) {
        $add = ' title="' . strval($_POST['title']) . '"';
    }
    $field = wpcf_admin_fields_get_field($_GET['field_id']);
    if (!empty($field)) {
        $shortcode = wpcf_fields_get_shortcode($field, $add);
        wpcf_admin_fields_save_field_last_settings($_GET['field_id'], $_POST);
        echo wpcf_admin_fields_popup_insert_shortcode_js($shortcode);
        die;
    }
}
Esempio n. 7
0
/**
 * Editor callback form submit.
 */
function wpcf_fields_checkbox_editor_submit()
{
    $add = '';
    $field = wpcf_admin_fields_get_field($_GET['field_id']);
    if (!empty($field)) {
        if ($_POST['display'] == 'value') {
            $shortcode = '[types field="' . $field['slug'] . '" state="checked"]' . $_POST['display_value_selected'] . '[/types] ';
            $shortcode .= '[types field="' . $field['slug'] . '" state="unchecked"]' . $_POST['display_value_not_selected'] . '[/types]';
        } else {
            $shortcode = wpcf_fields_get_shortcode($field, $add);
        }
        echo wpcf_admin_fields_popup_insert_shortcode_js($shortcode);
        die;
    }
}
Esempio n. 8
0
/**
 * Editor callback form submit.
 */
function wpcf_fields_radio_editor_submit()
{
    $add = '';
    $field = wpcf_admin_fields_get_field($_GET['field_id']);
    if (!empty($field)) {
        if ($_POST['display'] == 'value' && !empty($_POST['options'])) {
            $shortcode = '';
            foreach ($_POST['options'] as $option_id => $value) {
                $shortcode .= '[types field="' . $field['slug'] . '" option="' . $option_id . '"]' . $value . '[/types] ';
            }
        } else {
            $shortcode = wpcf_fields_get_shortcode($field, $add);
        }
        echo wpcf_admin_fields_popup_insert_shortcode_js($shortcode);
        die;
    }
}
Esempio n. 9
0
/**
 * All AJAX calls go here.
 */
function wpcf_ajax_embedded()
{
    if (!current_user_can('manage_options') || (!isset($_REQUEST['_wpnonce']) || !wp_verify_nonce($_REQUEST['_wpnonce'], $_REQUEST['wpcf_action']))) {
        die('Verification failed');
    }
    switch ($_REQUEST['wpcf_action']) {
        case 'editor_insert_date':
            require_once WPCF_EMBEDDED_INC_ABSPATH . '/fields/date.php';
            wpcf_fields_date_editor_form();
            break;
        case 'insert_skype_button':
            require_once WPCF_EMBEDDED_INC_ABSPATH . '/fields/skype.php';
            wpcf_fields_skype_meta_box_ajax();
            break;
        case 'editor_callback':
            require_once WPCF_EMBEDDED_INC_ABSPATH . '/fields.php';
            $field = wpcf_admin_fields_get_field($_GET['field_id']);
            if (!empty($field)) {
                // TODO Remove
                //                $file = WPCF_EMBEDDED_INC_ABSPATH . '/fields/' . $field['type'] . '.php';
                //                if (file_exists($file)) {
                //                    require_once $file;
                $function = 'wpcf_fields_' . $field['type'] . '_editor_callback';
                if (function_exists($function)) {
                    call_user_func($function);
                }
                //                }
            }
            break;
        case 'dismiss_message':
            if (isset($_GET['id'])) {
                $messages = get_option('wpcf_dismissed_messages', array());
                $messages[] = $_GET['id'];
                update_option('wpcf_dismissed_messages', $messages);
            }
            break;
        default:
            break;
    }
    if (function_exists('wpcf_ajax')) {
        wpcf_ajax();
    }
    die;
}
Esempio n. 10
0
 /**
  * Set current post and field.
  * 
  * @param type $post
  * @param type $cf 
  */
 function set($user_id, $cf)
 {
     global $wpcf;
     /*
      * 
      * Check if $cf is string
      */
     if (is_string($cf)) {
         WPCF_Loader::loadInclude('fields');
         $cf = wpcf_admin_fields_get_field($this->__get_slug_no_prefix($cf));
         if (empty($cf)) {
             $this->_reset();
             return false;
         }
     }
     $this->currentUID = $user_id;
     $this->ID = $cf['id'];
     $this->cf = $cf;
     $this->slug = wpcf_types_get_meta_prefix($this->cf) . $this->cf['slug'];
     $this->meta = $this->_get_meta();
     $this->config = $this->_get_config();
     $this->unique_id = wpcf_unique_id(serialize((array) $this));
     $this->cf['value'] = $this->meta;
     // Debug
     $wpcf->debug->fieds[$this->unique_id] = $this->cf;
     $wpcf->debug->meta[$this->slug][] = $this->meta;
     // Load files
     if (isset($this->cf['type'])) {
         $file = WPCF_EMBEDDED_INC_ABSPATH . '/fields/' . $this->cf['type'] . '.php';
         if (file_exists($file)) {
             include_once $file;
         }
         if (defined('WPCF_INC_ABSPATH')) {
             $file = WPCF_INC_ABSPATH . '/fields/' . $this->cf['type'] . '.php';
             if (file_exists($file)) {
                 include_once $file;
             }
         }
     }
 }
Esempio n. 11
0
/**
 * Gets field.
 *
 * @param string $field
 * @param string $meta_type
 * @return array
 */
function types_get_field($field, $meta_type = 'postmeta')
{
    static $cache = array();
    $cache_key = md5(strval($field) . strval($meta_type));
    if (isset($cache[$cache_key])) {
        return $cache[$cache_key];
    }
    WPCF_Loader::loadInclude('fields');
    switch ($meta_type) {
        case 'usermeta':
            $meta_type_key = 'wpcf-usermeta';
            break;
        case 'termmeta':
            $meta_type_key = 'wpcf-termmeta';
            break;
        default:
            $meta_type_key = 'wpcf-fields';
            break;
    }
    $cache[$cache_key] = wpcf_admin_fields_get_field(strval($field), false, false, false, $meta_type_key);
    return $cache[$cache_key];
}
Esempio n. 12
0
/**
 * Custom Conditinal Statement hook returns timestamp if array.
 * 
 * NOTE that $null is already filtered to use $_POST values
 * at priority 10.
 * 
 * @param type $null
 * @param type $object_id
 * @param type $meta_key
 * @param type $single
 * @return mixed timestamp or $null
 */
function wpcf_fields_date_custom_conditional_statement_filter($null, $object_id, $meta_key, $single)
{
    global $wpcf;
    $field = wpcf_admin_fields_get_field($wpcf->field->__get_slug_no_prefix($meta_key));
    if (!empty($null) && !empty($field) && isset($field['type']) && $field['type'] == 'date') {
        if (is_array($null) && !isset($null['datepicker'])) {
            $null = array_shift($null);
        }
        $null = wpcf_fields_date_value_get_filter($null, $field, 'timestamp');
        if (!is_numeric($null)) {
            $null = -1;
        }
        /**
         * be sure do not return string if array is expected!
         */
        if (!$single && !is_array($null)) {
            return array($null);
        }
    }
    return $null;
}
 /**
  * buildRawFieldToEdit function
  *
  * @param array $field
  * @param array $settings
  * @return array
  * @author Riccardo Strobbia
  **/
 private function buildRawFieldToEdit($field, $settings = array())
 {
     $opts = $settings ? $settings : get_post_meta($this->view_id, '_wpv_settings', true);
     $ret = array();
     $index = self::get_param_index_cmp($settings, $field);
     //print "index first method " . $index ."\n";
     //FIXME: fall back for retrocompatibility
     if ($index === -1) {
         //	$index = self::get_param_index($settings, $field);
     }
     $index = self::get_param_index($settings, $field);
     if ($index > -1) {
         $field['url_param'] = self::$tmp_settings['filter_controls_param'][$index];
         $field['can_force_zero'] = false;
         self::$tmp_settings = null;
         if (isset($field['taxonomy'])) {
             $name = $settings['filter_controls_field_name'][$index];
             $id = $name;
             $id = $settings['filter_controls_label'][$index];
             $ret['is_types'] = false;
             $ret['group'] = 'taxonomy';
             ///do processing for taxes and return
         } else {
             if (isset($field['field'])) {
                 $g = '';
                 $name = $field['field'];
                 $nice_name = explode('wpcf-', $name);
                 $id = isset($nice_name[1]) ? $nice_name[1] : $name;
                 $field_options = array();
                 if (function_exists('wpcf_admin_fields_get_groups_by_field')) {
                     $field_options = wpcf_admin_fields_get_field($id);
                     foreach (wpcf_admin_fields_get_groups_by_field($id) as $gs) {
                         $g = $gs['name'];
                     }
                 }
                 $ret['group'] = $g ? $g : "Custom fields";
                 $name = $g ? $name : $field['field'];
                 $ret['is_types'] = $g ? true : false;
                 if (!empty($field_options) && isset($field_options['meta_key'])) {
                     $name = $field_options['meta_key'];
                 }
                 if (!empty($field_options) && $field_options['type'] == 'checkbox' && $field_options['data']['save_empty'] == 'yes') {
                     $ret['can_force_zero'] = true;
                 }
                 $id = $g ? $id : $field['field'];
             } else {
                 if (isset($field['relationship'])) {
                     $name = 'relationship';
                     $id = __('Post relationship', 'wpv-views');
                     // TODO what are we doing here??
                     $id = $settings['filter_controls_label'][$index];
                     $ret['is_types'] = false;
                     $ret['group'] = 'basic_filters';
                     $ret['kind'] = 'relationship';
                     $ret['basic_filter_type'] = 'relationship';
                 } else {
                     $name = $settings['filter_controls_field_name'][$index];
                     $id = $name;
                     $ret['is_types'] = false;
                     $ret['group'] = 'Custom fields';
                 }
             }
         }
         //	print "\n'custom-field-'.$name.'_value'\n";
         //	print_r( $settings['custom-field-'.$name.'_value'] );
         $ret['field'] = $name;
         $ret['id'] = $id;
         if (isset($field['taxonomy'])) {
             $ret['kind'] = 'taxonomy';
             $ret['group'] = $ret['kind'];
             $ret['compare'] = isset($settings['taxonomy-' . $name . '-attribute-operator']) ? $settings['taxonomy-' . $name . '-attribute-operator'] : 'IN';
             //	$ret['hide_empty'] = isset( $field['hide_empty'] ) ? $field['hide_empty'] : 'false';
         } else {
             if (isset($field['relationship'])) {
                 $ret['group'] = 'basic_filters';
             } else {
                 $ret['compare'] = isset($settings['custom-field-' . $name . '_compare']) ? $settings['custom-field-' . $name . '_compare'] : '=';
                 $ret['data_type'] = isset($settings['custom-field-' . $name . '_type']) ? $settings['custom-field-' . $name . '_type'] : 'CHAR';
                 $ret['relation'] = isset($settings['custom-field-' . $name . '_relationship']) ? $settings['custom-field-' . $name . '_relationship'] : 'AND';
                 $ret['kind'] = 'field';
             }
         }
         $ret['name'] = $ret['is_types'] ? $settings['filter_controls_label'][$index] : $id;
         $ret['type'] = $settings['filter_controls_type'][$index];
         $ret['values'] = $settings['filter_controls_values'][$index];
         $ret['enabled'] = $settings['filter_controls_enable'][$index];
         $ret['index'] = $index;
         /*	$ret_aux = $settings['filter_controls_values'][$index];
         			$ret['taxonomy_order'] = isset( $ret_aux['taxonomy_order'] ) ? $ret_aux['taxonomy_order'] : 'ASC';
         			$ret['taxonomy_orderby'] = isset( $ret_aux['taxonomy_orderby'] ) ? $ret_aux['taxonomy_orderby'] : 'name';
         			$ret['hide_empty'] = isset( $ret_aux['hide_empty'] ) ? $ret_aux['hide_empty'] : 'false';*/
         //implement for tax
         return array_merge($field, $ret);
     } else {
         return array('error', __(sprintf('There is something wrong url parameter is missing %s', __METHOD__), 'wpv-views'));
     }
 }
Esempio n. 14
0
 /**
  * Set current post and field.
  *
  * @param type $post
  * @param type $cf
  */
 function set($post, $cf)
 {
     global $wpcf;
     /*
      *
      * Check if $cf is string
      */
     if (is_string($cf)) {
         WPCF_Loader::loadInclude('fields');
         $_cf = wpcf_admin_fields_get_field($this->__get_slug_no_prefix($cf));
         // Check if found without prefix
         if (empty($_cf)) {
             $_cf = wpcf_admin_fields_get_field($cf);
         }
         if (empty($_cf)) {
             /*
              * TODO Check what happens if field is not found
              */
             $this->_reset();
             return false;
         }
         $cf = $_cf;
     }
     $this->post = is_integer($post) ? get_post($post) : $post;
     // If empty post it is new
     if (empty($this->post->ID)) {
         $this->post = new stdClass();
         $this->post->ID = 0;
     }
     $this->ID = $cf['id'];
     $this->cf = $cf;
     $this->slug = wpcf_types_get_meta_prefix($this->cf) . $this->cf['slug'];
     $this->meta = $this->_get_meta();
     $this->config = $this->_get_config();
     $this->unique_id = wpcf_unique_id(serialize((array) $this));
     $this->cf['value'] = $this->meta;
     // Debug
     $wpcf->debug->fields[$this->unique_id] = $this->cf;
     $wpcf->debug->meta[$this->slug][] = $this->meta;
     // Load files
     $this->_include_file_by_field_type($this->cf['type']);
     if (defined('WPCF_INC_ABSPATH')) {
         $file = WPCF_INC_ABSPATH . '/fields/' . preg_replace('/[^\\w]+/', '', $this->cf['type']) . '.php';
         if (file_exists($file)) {
             include_once $file;
         }
     }
 }
Esempio n. 15
0
/**
 *
 * Only for attachments, only default checkboxes!
 *
 * @internal breakpoint
 * @param type $post_ID
 * @param type $post
 */
function wpcf_admin_post_add_attachment_hook($post_ID, $post)
{
    global $wpcf;
    /**
     * Basic check: only attachment
     */
    if ('attachment' != $post->post_type) {
        return false;
    }
    /**
     * Get all groups connected to this $post
     */
    $groups = wpcf_admin_post_get_post_groups_fields($post);
    if (empty($groups)) {
        return false;
    }
    $all_fields = array();
    $_not_valid = array();
    $_error = false;
    /**
     * Loop over each group
     *
     * TODO Document this
     * Connect 'wpcf-invalid-fields' with all fields
     */
    foreach ($groups as $group) {
        if (isset($group['fields'])) {
            // Process fields
            $fields = wpcf_admin_post_process_fields($post, $group['fields'], true, false, 'validation');
            // Validate fields
            $form = wpcf_form_simple_validate($fields);
            $all_fields = $all_fields + $fields;
            // Collect all not valid fields
            if ($form->isError()) {
                $_error = true;
                // Set error only to true
                $_not_valid = array_merge($_not_valid, (array) $form->get_not_valid());
            }
        }
    }
    // Set fields
    foreach ($all_fields as $k => $v) {
        // only Types field
        if (empty($v['wpcf-id'])) {
            continue;
        }
        $_temp = new WPCF_Field();
        $_temp->set($wpcf->post, $v['wpcf-id']);
        $all_fields[$k]['_field'] = $_temp;
    }
    foreach ($_not_valid as $k => $v) {
        // only Types field
        if (empty($v['wpcf-id'])) {
            continue;
        }
        $_temp = new WPCF_Field();
        $_temp->set($wpcf->post, $v['wpcf-id']);
        $_not_valid[$k]['_field'] = $_temp;
    }
    /**
     * Process all checkbox fields
     */
    foreach ($all_fields as $field) {
        /**
         * only checkbox
         */
        if (!isset($field['#type']) || 'checkbox' != $field['#type']) {
            continue;
        }
        $field_data = wpcf_admin_fields_get_field($field['wpcf-id']);
        /**
         * check is checked for new!
         */
        $checked = array_key_exists('checked', $field_data['data']) && $field_data['data']['checked'];
        /**
         * do not save empty and not checked? fine, go away...
         */
        if ('no' == $field_data['data']['save_empty'] && !$checked) {
            continue;
        }
        /**
         * all other just save...
         */
        $update_data = 0;
        if ($checked) {
            $update_data = $field_data['data']['set_value'];
        }
        add_post_meta($post_ID, wpcf_types_get_meta_prefix($field) . $field['wpcf-slug'], $update_data);
    }
    do_action('wpcf_attachement_add', $post_ID);
}
Esempio n. 16
0
/**
 * Dynamically adds existing field on AJAX call.
 * 
 * @param type $form_data 
 */
function wpcf_usermeta_insert_existing_ajax()
{
    $field = wpcf_admin_fields_get_field($_GET['field'], false, true, false, 'wpcf-usermeta');
    if (!empty($field)) {
        echo wpcf_fields_get_field_form($field['type'], $field);
    } else {
        echo '<div>' . __("Requested field don't exist", 'wpcf') . '</div>';
    }
}
Esempio n. 17
0
/**
 * Processes editor popup submit
 */
function wpcf_fields_google_map_editor_submit()
{
    // Get field
    $field = wpcf_admin_fields_get_field(strval($_GET['field_id']));
    if (!empty($field)) {
        $add = '';
        // Add parameters
        if (!empty($_POST['width'])) {
            $add .= ' width="' . strval($_POST['width']) . '"';
        }
        if (!empty($_POST['height'])) {
            $add .= ' height="' . strval($_POST['height']) . '"';
        }
        // Generate shortcode
        $shortcode = wpcf_fields_get_shortcode($field, $add);
        // Save settings
        wpcf_admin_fields_save_field_last_settings($_GET['field_id'], $_POST);
        // Trigger inserting shortcode in parent editor
        echo editor_admin_popup_insert_shortcode_js($shortcode);
    }
    die;
}
 /**
  * Summary.
  *
  * Description.
  *
  * @since x.x.x
  * @access (for functions: only use if private)
  *
  * @see Function/method/class relied on
  * @link URL
  * @global type $varname Description.
  * @global type $varname Description.
  *
  * @param type $var Description.
  * @param type $var Optional. Description.
  * @return type Description.
  */
 public function field_condition_get()
 {
     /**
      * check nonce
      */
     if (0 || !isset($_REQUEST['_wpnonce']) || !isset($_REQUEST['id']) || !wp_verify_nonce($_REQUEST['_wpnonce'], 'wpcf-conditional-get-' . $_REQUEST['id'])) {
         $this->verification_failed_and_die();
     }
     /**
      * get field definition
      */
     require_once WPCF_EMBEDDED_INC_ABSPATH . '/fields.php';
     $field = wpcf_admin_fields_get_field(sanitize_text_field($_REQUEST['id']), false, true);
     if (empty($field)) {
         __('Wrong field.', 'wpcf');
         die;
     }
     /**
      * define conditional
      */
     require_once WPCF_INC_ABSPATH . '/classes/class.types.fields.conditional.php';
     new Types_Fields_Conditional();
     /**
      * get form data
      */
     /**
      * Summary.
      *
      * Description.
      *
      * @since x.x.x
      *
      * @param type  $var Description.
      * @param array $args {
      *     Short description about this hash.
      *
      *     @type type $var Description.
      *     @type type $var Description.
      * }
      * @param type  $var Description.
      */
     $form = $this->get_field_conditionals(array(), $field);
     if (empty($form)) {
         __('Wrong field.', 'wpcf');
         die;
     }
     /**
      * produce form
      */
     echo wpcf_form_simple($form);
     die;
 }
Esempio n. 19
0
 /**
  * Checks if item exists.
  *
  * @param type $type
  * @param type $item_id
  * @return boolean
  */
 function item_exists($type, $item_id)
 {
     switch ($type) {
         case 'group':
             $check = wpcf_admin_fields_get_group($item_id);
             break;
         case 'field':
             $check = wpcf_admin_fields_get_field($item_id);
             break;
         case 'custom_post_type':
             $check = wpcf_get_custom_post_type_settings($item_id);
             break;
         case 'custom_taxonomy':
             $check = wpcf_get_custom_taxonomy_settings($item_id);
             break;
         default:
             return false;
             break;
     }
     return !empty($check);
 }
Esempio n. 20
0
function wpcf_admin_userprofilesave_init($user_id)
{
    if (defined('WPTOOLSET_FORMS_VERSION')) {
        global $wpcf;
        $errors = false;
        /**
         * check checkbox type fields to delete or save empty if needed
         */
        $groups = wpcf_admin_usermeta_get_groups_fields();
        foreach ($groups as $group) {
            if (!array_key_exists('fields', $group) || empty($group['fields'])) {
                continue;
            }
            foreach ($group['fields'] as $field) {
                switch ($field['type']) {
                    case 'checkboxes':
                        if (!array_key_exists('wpcf', $_POST) || !array_key_exists($field['slug'], $_POST['wpcf'])) {
                            delete_user_meta($user_id, $field['meta_key']);
                        }
                        break;
                    case 'checkbox':
                        if (!array_key_exists('wpcf', $_POST) || !array_key_exists($field['slug'], $_POST['wpcf'])) {
                            if ('yes' == $field['data']['save_empty']) {
                                $_POST['wpcf'][$field['slug']] = 0;
                            } else {
                                delete_user_meta($user_id, $field['meta_key']);
                            }
                        }
                        break;
                }
            }
        }
        // Save meta fields
        if (!empty($_POST['wpcf'])) {
            foreach ($_POST['wpcf'] as $field_slug => $field_value) {
                // Get field by slug
                $field = wpcf_fields_get_field_by_slug($field_slug, 'wpcf-usermeta');
                if (empty($field)) {
                    continue;
                }
                // Skip copied fields
                if (isset($_POST['wpcf_repetitive_copy'][$field['slug']])) {
                    continue;
                }
                $_field_value = !types_is_repetitive($field) ? array($field_value) : $field_value;
                // Set config
                $config = wptoolset_form_filter_types_field($field, $user_id);
                foreach ($_field_value as $_k => $_val) {
                    // Check if valid
                    $valid = wptoolset_form_validate_field('your-profile', $config, $_val);
                    if (is_wp_error($valid)) {
                        $errors = true;
                        $_errors = $valid->get_error_data();
                        $_msg = sprintf(__('Field "%s" not updated:', 'wpcf'), $field['name']);
                        wpcf_admin_message_store($_msg . ' ' . implode(', ', $_errors), 'error');
                        if (types_is_repetitive($field)) {
                            unset($field_value[$_k]);
                        } else {
                            break;
                        }
                    }
                }
                // Save field
                if (types_is_repetitive($field)) {
                    $wpcf->usermeta_repeater->set($user_id, $field);
                    $wpcf->usermeta_repeater->save($field_value);
                } else {
                    $wpcf->usermeta_field->set($user_id, $field);
                    $wpcf->usermeta_field->usermeta_save($field_value);
                }
                do_action('wpcf_user_field_saved', $user_id, $field);
                // TODO Move to checkboxes
                if ($field['type'] == 'checkboxes') {
                    $field_data = wpcf_admin_fields_get_field($field['id'], false, false, false, 'wpcf-usermeta');
                    if (!empty($field_data['data']['options'])) {
                        $update_data = array();
                        foreach ($field_data['data']['options'] as $option_id => $option_data) {
                            if (!isset($_POST['wpcf'][$field['id']][$option_id])) {
                                if (isset($field_data['data']['save_empty']) && $field_data['data']['save_empty'] == 'yes') {
                                    $update_data[$option_id] = 0;
                                }
                            } else {
                                $update_data[$option_id] = $_POST['wpcf'][$field['id']][$option_id];
                            }
                        }
                        update_user_meta($user_id, $field['meta_key'], $update_data);
                    }
                }
            }
        }
        if ($errors) {
            update_post_meta($user_id, '__wpcf-invalid-fields', true);
        }
        do_action('wpcf_user_saved', $user_id);
        return;
    }
    global $wpcf;
    $all_fields = array();
    $_not_valid = array();
    $_error = false;
    $error = '';
    $groups = $groups = wpcf_admin_usermeta_get_groups_fields();
    if (empty($groups)) {
        return false;
    }
    foreach ($groups as $group) {
        // Process fields
        $fields = wpcf_admin_usermeta_process_fields($user_id, $group['fields'], true, false, 'validation');
        // Validate fields
        $form = wpcf_form_simple_validate($fields);
        $all_fields = $all_fields + $fields;
        // Collect all not valid fields
        if ($form->isError()) {
            $_error = true;
            // Set error only to true
            $_not_valid = array_merge($_not_valid, (array) $form->get_not_valid());
        }
    }
    // Set fields
    foreach ($all_fields as $k => $v) {
        // only Types field
        if (empty($v['wpcf-id'])) {
            continue;
        }
        $_temp = new WPCF_Usermeta_Field();
        $_temp->set($user_id, $v['wpcf-id']);
        $all_fields[$k]['_field'] = $_temp;
    }
    foreach ($_not_valid as $k => $v) {
        // only Types field
        if (empty($v['wpcf-id'])) {
            continue;
        }
        $_temp = new WPCF_Usermeta_Field();
        $_temp->set($user_id, $v['wpcf-id']);
        $_not_valid[$k]['_field'] = $_temp;
    }
    $not_valid = apply_filters('wpcf_post_form_not_valid', $_not_valid, $_error, $all_fields);
    // Notify user about error
    if ($error) {
        wpcf_admin_message_store(__('Please check your input data', 'wpcf'), 'error');
    }
    /*
     * Save invalid elements so user can be informed after redirect.
     */
    if (!empty($not_valid)) {
        update_user_meta($user_id, 'wpcf-invalid-fields', $not_valid);
    }
    if (!empty($_POST['wpcf'])) {
        foreach ($_POST['wpcf'] as $field_slug => $field_value) {
            $field = wpcf_fields_get_field_by_slug($field_slug, 'wpcf-usermeta');
            if (empty($field)) {
                continue;
            }
            $wpcf->usermeta_field->set($user_id, $field);
            if (isset($_POST['wpcf_repetitive_copy'][$field['slug']])) {
                continue;
            }
            if (isset($_POST['__wpcf_repetitive'][$wpcf->usermeta_field->slug])) {
                $wpcf->usermeta_repeater->set($user_id, $field);
                $wpcf->usermeta_repeater->save();
            } else {
                $wpcf->usermeta_field->usermeta_save();
            }
            do_action('wpcf_post_field_saved', '', $field);
        }
        //end foreach
    }
    //end if
    foreach ($all_fields as $field) {
        if (!isset($field['#type'])) {
            continue;
        }
        if ($field['#type'] == 'checkbox') {
            $field_data = wpcf_admin_fields_get_field($field['wpcf-id'], false, false, false, 'wpcf-usermeta');
            if (!isset($_POST['wpcf'][$field['wpcf-slug']])) {
                if (isset($field_data['data']['save_empty']) && $field_data['data']['save_empty'] == 'yes') {
                    update_user_meta($user_id, wpcf_types_get_meta_prefix($field) . $field['wpcf-slug'], 0);
                } else {
                    delete_user_meta($user_id, wpcf_types_get_meta_prefix($field) . $field['wpcf-slug']);
                }
            }
        }
        if ($field['#type'] == 'checkboxes') {
            $field_data = wpcf_admin_fields_get_field($field['wpcf-id'], false, false, false, 'wpcf-usermeta');
            if (!empty($field_data['data']['options'])) {
                $update_data = array();
                foreach ($field_data['data']['options'] as $option_id => $option_data) {
                    if (!isset($_POST['wpcf'][$field['wpcf-slug']][$option_id])) {
                        if (isset($field_data['data']['save_empty']) && $field_data['data']['save_empty'] == 'yes') {
                            $update_data[$option_id] = 0;
                        }
                    } else {
                        $update_data[$option_id] = $_POST['wpcf'][$field['wpcf-slug']][$option_id];
                    }
                }
                update_user_meta($user_id, wpcf_types_get_meta_prefix($field) . $field['wpcf-slug'], $update_data);
            }
        }
    }
}
Esempio n. 21
0
/**
 * All AJAX calls go here.
 *
 * @global object $wpdb
 *
 */
function wpcf_ajax()
{
    if (!current_user_can('manage_options') || (!isset($_REQUEST['_wpnonce']) || !wp_verify_nonce($_REQUEST['_wpnonce'], $_REQUEST['wpcf_action']))) {
        die;
    }
    switch ($_REQUEST['wpcf_action']) {
        /* User meta actions*/
        case 'user_fields_control_bulk':
            require_once WPCF_INC_ABSPATH . '/fields.php';
            require_once WPCF_EMBEDDED_INC_ABSPATH . '/fields.php';
            require_once WPCF_INC_ABSPATH . '/fields-control.php';
            require_once WPCF_INC_ABSPATH . '/usermeta-control.php';
            wpcf_admin_user_fields_control_bulk_ajax();
            break;
        case 'usermeta_delete':
        case 'delete_usermeta':
            require_once WPCF_INC_ABSPATH . '/fields.php';
            if (isset($_GET['field_id'])) {
                $field_id = sanitize_text_field($_GET['field_id']);
                wpcf_admin_fields_delete_field($field_id, 'wp-types-user-group', 'wpcf-usermeta');
            }
            if (isset($_GET['field'])) {
                $field = sanitize_text_field($_GET['field']);
                wpcf_admin_fields_delete_field($field, 'wp-types-user-group', 'wpcf-usermeta');
            }
            echo json_encode(array('output' => ''));
            break;
        case 'remove_from_history2':
            require_once WPCF_INC_ABSPATH . '/fields.php';
            $fields = wpcf_admin_fields_get_fields(true, true, false, 'wpcf-usermeta');
            if (isset($_GET['field_id']) && isset($fields[$_GET['field_id']])) {
                $fields[$_GET['field_id']]['data']['removed_from_history'] = 1;
                wpcf_admin_fields_save_fields($fields, true, 'wpcf-usermeta');
            }
            echo json_encode(array('output' => ''));
            break;
        case 'deactivate_user_group':
            require_once WPCF_INC_ABSPATH . '/fields.php';
            require_once WPCF_INC_ABSPATH . '/usermeta.php';
            $success = wpcf_admin_fields_deactivate_group(intval($_GET['group_id']), 'wp-types-user-group');
            if ($success) {
                echo json_encode(array('output' => __('Group deactivated', 'wpcf'), 'execute' => 'location.reload();'));
            } else {
                echo json_encode(array('output' => __('Error occured', 'wpcf')));
            }
            break;
        case 'activate_user_group':
            require_once WPCF_INC_ABSPATH . '/fields.php';
            require_once WPCF_INC_ABSPATH . '/usermeta.php';
            $success = wpcf_admin_fields_activate_group(intval($_GET['group_id']), 'wp-types-user-group');
            if ($success) {
                echo json_encode(array('output' => __('Group activated', 'wpcf'), 'execute' => 'location.reload();'));
            } else {
                echo json_encode(array('output' => __('Error occured', 'wpcf')));
            }
            break;
        case 'delete_usermeta_group':
            require_once WPCF_INC_ABSPATH . '/fields.php';
            require_once WPCF_INC_ABSPATH . '/usermeta.php';
            wpcf_admin_fields_delete_group(intval($_GET['group_id']), 'wp-types-user-group');
            echo json_encode(array('output' => '', 'execute' => 'location.reload();'));
            break;
        case 'usermeta_insert_existing':
            require_once WPCF_INC_ABSPATH . '/fields.php';
            require_once WPCF_INC_ABSPATH . '/fields-form.php';
            require_once WPCF_INC_ABSPATH . '/usermeta-form.php';
            wpcf_usermeta_insert_existing_ajax();
            wpcf_form_render_js_validation();
            break;
            /* End Usertmeta actions*/
        /* End Usertmeta actions*/
        case 'fields_insert':
            require_once WPCF_INC_ABSPATH . '/fields.php';
            require_once WPCF_INC_ABSPATH . '/fields-form.php';
            wpcf_fields_insert_ajax();
            wpcf_form_render_js_validation();
            break;
        case 'fields_insert_existing':
            require_once WPCF_INC_ABSPATH . '/fields.php';
            require_once WPCF_INC_ABSPATH . '/fields-form.php';
            wpcf_fields_insert_existing_ajax();
            wpcf_form_render_js_validation();
            break;
        case 'remove_field_from_group':
            require_once WPCF_INC_ABSPATH . '/fields.php';
            if (isset($_GET['group_id']) && isset($_GET['field_id'])) {
                wpcf_admin_fields_remove_field_from_group(intval($_GET['group_id']), sanitize_text_field($_GET['field_id']));
            }
            break;
        case 'deactivate_group':
            require_once WPCF_INC_ABSPATH . '/fields.php';
            $success = wpcf_admin_fields_deactivate_group(intval($_GET['group_id']));
            if ($success) {
                echo json_encode(array('output' => __('Group deactivated', 'wpcf'), 'execute' => 'location.reload();'));
            } else {
                echo json_encode(array('output' => __('Error occured', 'wpcf')));
            }
            break;
        case 'activate_group':
            require_once WPCF_INC_ABSPATH . '/fields.php';
            $success = wpcf_admin_fields_activate_group(intval($_GET['group_id']));
            if ($success) {
                echo json_encode(array('output' => __('Group activated', 'wpcf'), 'execute' => 'location.reload();'));
            } else {
                echo json_encode(array('output' => __('Error occured', 'wpcf')));
            }
            break;
        case 'delete_group':
            require_once WPCF_INC_ABSPATH . '/fields.php';
            wpcf_admin_fields_delete_group(intval($_GET['group_id']));
            echo json_encode(array('output' => '', 'execute' => 'location.reload();'));
            break;
        case 'deactivate_post_type':
            if (!isset($_GET['wpcf-post-type'])) {
                die;
            }
            require_once WPCF_INC_ABSPATH . '/custom-types.php';
            $custom_types = get_option(WPCF_OPTION_NAME_CUSTOM_TYPES, array());
            if (isset($custom_types[$_GET['wpcf-post-type']])) {
                $custom_types[$_GET['wpcf-post-type']]['disabled'] = 1;
                $custom_types[$_GET['wpcf-post-type']][TOOLSET_EDIT_LAST] = time();
                update_option(WPCF_OPTION_NAME_CUSTOM_TYPES, $custom_types);
                echo json_encode(array('output' => __('Post type deactivated', 'wpcf'), 'execute' => 'location.reload();'));
            } else {
                echo json_encode(array('output' => __('Error occured', 'wpcf')));
            }
            break;
        case 'activate_post_type':
            if (!isset($_GET['wpcf-post-type'])) {
                die;
            }
            require_once WPCF_INC_ABSPATH . '/custom-types.php';
            $custom_types = get_option(WPCF_OPTION_NAME_CUSTOM_TYPES, array());
            if (isset($custom_types[$_GET['wpcf-post-type']])) {
                unset($custom_types[$_GET['wpcf-post-type']]['disabled']);
                $custom_types[$_GET['wpcf-post-type']][TOOLSET_EDIT_LAST] = time();
                update_option(WPCF_OPTION_NAME_CUSTOM_TYPES, $custom_types);
                echo json_encode(array('output' => __('Post type activated', 'wpcf'), 'execute' => 'location.reload();'));
            } else {
                echo json_encode(array('output' => __('Error occured', 'wpcf')));
            }
            break;
        case 'delete_post_type':
            if (!isset($_GET['wpcf-post-type'])) {
                die;
            }
            $custom_types = get_option(WPCF_OPTION_NAME_CUSTOM_TYPES, array());
            $custom_type = strval($_GET['wpcf-post-type']);
            /**
             * Delete relation between custom posts types
             *
             * Filter allow to delete all custom fields used to make
             * a relation between posts.
             *
             * @since 1.6.4
             *
             * @param bool   $delete True or false flag to delete relationships.
             * @param string $var Currently deleted custom post type.
             */
            if (apply_filters('wpcf_delete_relation_meta', false, $custom_type)) {
                global $wpdb;
                $wpdb->delete($wpdb->postmeta, array('meta_key' => sprintf('_wpcf_belongs_%s_id', $custom_type)), array('%s'));
            }
            unset($custom_types[$custom_type]);
            /**
             * remove post relation
             */
            foreach (array_keys($custom_types) as $post_type) {
                if (array_key_exists('post_relationship', $custom_types[$post_type])) {
                    /**
                     * remove "has" relation
                     */
                    if (array_key_exists('has', $custom_types[$post_type]['post_relationship']) && array_key_exists($custom_type, $custom_types[$post_type]['post_relationship']['has'])) {
                        unset($custom_types[$post_type]['post_relationship']['has'][$custom_type]);
                        $custom_types[$post_type][TOOLSET_EDIT_LAST] = time();
                    }
                    /**
                     * remove "belongs" relation
                     */
                    if (array_key_exists('belongs', $custom_types[$post_type]['post_relationship']) && array_key_exists($custom_type, $custom_types[$post_type]['post_relationship']['belongs'])) {
                        unset($custom_types[$post_type]['post_relationship']['belongs'][$custom_type]);
                        $custom_types[$post_type][TOOLSET_EDIT_LAST] = time();
                    }
                }
            }
            update_option(WPCF_OPTION_NAME_CUSTOM_TYPES, $custom_types);
            wpcf_admin_deactivate_content('post_type', $custom_type);
            echo json_encode(array('output' => '', 'execute' => 'location.reload();'));
            break;
        case 'duplicate_post_type':
            if (!isset($_GET['wpcf-post-type'])) {
                die;
            }
            $custom_types = get_option(WPCF_OPTION_NAME_CUSTOM_TYPES, array());
            $custom_type = esc_html(strval($_GET['wpcf-post-type']));
            if (isset($custom_types[$custom_type])) {
                $i = 0;
                $key = false;
                do {
                    $key = sprintf($custom_type . '-%d', ++$i);
                } while (isset($custom_types[$key]));
                if ($key) {
                    /**
                     * duplicate custom post type
                     */
                    $custom_types[$key] = $custom_types[$custom_type];
                    /**
                     * update some options
                     */
                    $custom_types[$key]['labels']['name'] .= sprintf(' (%d)', $i);
                    $custom_types[$key]['labels']['singular_name'] .= sprintf(' (%d)', $i);
                    $custom_types[$key]['slug'] = $key;
                    $custom_types[$key]['__types_id'] = $key;
                    /**
                     * update custom post types
                     */
                    update_option(WPCF_OPTION_NAME_CUSTOM_TYPES, $custom_types);
                    /**
                     * update custom taxonomies too
                     */
                    $custom_taxonomies = get_option(WPCF_OPTION_NAME_CUSTOM_TAXONOMIES, array());
                    foreach ($custom_taxonomies as $taxonomy_key => $taxonomy_data) {
                        if (isset($taxonomy_data['supports']) && isset($taxonomy_data['supports'][$custom_type])) {
                            $custom_taxonomies[$taxonomy_key]['supports'][$key] = 1;
                        }
                    }
                    update_option(WPCF_OPTION_NAME_CUSTOM_TAXONOMIES, $custom_taxonomies);
                    echo json_encode(array('execute' => 'location.reload();'));
                }
            } else {
                echo json_encode(array('output' => __('Error occured', 'wpcf')));
            }
            break;
        case 'taxonomy_duplicate':
            if (!isset($_GET['wpcf-tax'])) {
                die;
            }
            $custom_taxonomy = esc_html(strval($_GET['wpcf-tax']));
            require_once WPCF_INC_ABSPATH . '/custom-taxonomies.php';
            $custom_taxonomies = get_option(WPCF_OPTION_NAME_CUSTOM_TAXONOMIES, array());
            if (isset($custom_taxonomies[$custom_taxonomy])) {
                $i = 0;
                $key = false;
                do {
                    $key = sprintf($custom_taxonomy . '-%d', ++$i);
                } while (isset($custom_taxonomies[$key]));
                if ($key) {
                    /**
                     * duplicate custom taxonomies
                     */
                    $custom_taxonomies[$key] = $custom_taxonomies[$custom_taxonomy];
                    /**
                     * update some options
                     */
                    $custom_taxonomies[$key]['labels']['name'] .= sprintf(' (%d)', $i);
                    $custom_taxonomies[$key]['labels']['singular_name'] .= sprintf(' (%d)', $i);
                    $custom_taxonomies[$key]['slug'] = $key;
                    $custom_taxonomies[$key]['id'] = $key;
                    $custom_taxonomies[$key]['__types_id'] = $key;
                    /**
                     * update custom taxonomies
                     */
                    update_option(WPCF_OPTION_NAME_CUSTOM_TAXONOMIES, $custom_taxonomies);
                    /**
                     * update post types
                     */
                    if (isset($custom_taxonomies[$key]['supports']) && is_array($custom_taxonomies[$key]['supports']) && !empty($custom_taxonomies[$key]['supports'])) {
                        $custom_types = get_option(WPCF_OPTION_NAME_CUSTOM_TYPES, array());
                        foreach (array_keys($custom_taxonomies[$key]['supports']) as $custom_type) {
                            /**
                             * avoid to create fake CPT from old data
                             */
                            if (!isset($custom_types[$custom_type])) {
                                continue;
                            }
                            if (!isset($custom_types[$custom_type]['taxonomies'])) {
                                $custom_types[$custom_type]['taxonomies'] = array();
                            }
                            $custom_types[$custom_type]['taxonomies'][$key] = 1;
                        }
                        /**
                         * update custom post types
                         */
                        update_option(WPCF_OPTION_NAME_CUSTOM_TYPES, $custom_types);
                    }
                    echo json_encode(array('execute' => 'location.reload();'));
                }
            } else {
                echo json_encode(array('output' => __('Error occured', 'wpcf')));
            }
            break;
        case 'deactivate_taxonomy':
            if (!isset($_GET['wpcf-tax'])) {
                die;
            }
            require_once WPCF_INC_ABSPATH . '/custom-taxonomies.php';
            $custom_taxonomies = get_option(WPCF_OPTION_NAME_CUSTOM_TAXONOMIES, array());
            if (isset($custom_taxonomies[$_GET['wpcf-tax']])) {
                $custom_taxonomies[$_GET['wpcf-tax']]['disabled'] = 1;
                $custom_taxonomies[$_GET['wpcf-tax']][TOOLSET_EDIT_LAST] = time();
                update_option(WPCF_OPTION_NAME_CUSTOM_TAXONOMIES, $custom_taxonomies);
                echo json_encode(array('output' => __('Taxonomy deactivated', 'wpcf'), 'execute' => 'location.reload();'));
            } else {
                echo json_encode(array('output' => __('Error occured', 'wpcf')));
            }
            break;
        case 'activate_taxonomy':
            if (!isset($_GET['wpcf-tax'])) {
                die;
            }
            require_once WPCF_INC_ABSPATH . '/custom-taxonomies.php';
            $custom_taxonomies = get_option(WPCF_OPTION_NAME_CUSTOM_TAXONOMIES, array());
            if (isset($custom_taxonomies[$_GET['wpcf-tax']])) {
                $custom_taxonomies[$_GET['wpcf-tax']]['disabled'] = 0;
                $custom_taxonomies[$_GET['wpcf-tax']][TOOLSET_EDIT_LAST] = time();
                update_option(WPCF_OPTION_NAME_CUSTOM_TAXONOMIES, $custom_taxonomies);
                echo json_encode(array('output' => __('Taxonomy activated', 'wpcf'), 'execute' => 'location.reload();'));
            } else {
                echo json_encode(array('output' => __('Error occured', 'wpcf')));
            }
            break;
        case 'delete_taxonomy':
            if (!isset($_GET['wpcf-tax'])) {
                die;
            }
            $custom_taxonomies = get_option(WPCF_OPTION_NAME_CUSTOM_TAXONOMIES, array());
            $custom_taxonomy = strval($_GET['wpcf-tax']);
            unset($custom_taxonomies[$custom_taxonomy]);
            update_option(WPCF_OPTION_NAME_CUSTOM_TAXONOMIES, $custom_taxonomies);
            wpcf_admin_deactivate_content('taxonomy', $custom_taxonomy);
            echo json_encode(array('output' => '', 'execute' => 'location.reload();'));
            break;
        case 'add_radio_option':
            require_once WPCF_INC_ABSPATH . '/fields/radio.php';
            $element = wpcf_fields_radio_get_option(urldecode($_GET['parent_name']));
            $id = array_shift($element);
            $element_txt = wpcf_fields_radio_get_option_alt_text($id, urldecode($_GET['parent_name']));
            echo json_encode(array('output' => wpcf_form_simple($element), 'execute' => 'jQuery("#wpcf-form-groups-radio-ajax-response-' . urldecode($_GET['wpcf_ajax_update_add']) . '").append(\'' . trim(str_replace("\r\n", '', wpcf_form_simple($element_txt))) . '\');', 'wpcf_nonce_ajax_callback' => wp_create_nonce('execute')));
            break;
        case 'add_select_option':
            require_once WPCF_INC_ABSPATH . '/fields/select.php';
            $element = wpcf_fields_select_get_option(urldecode($_GET['parent_name']));
            echo json_encode(array('output' => wpcf_form_simple($element)));
            break;
        case 'add_checkboxes_option':
            require_once WPCF_INC_ABSPATH . '/fields/checkboxes.php';
            $element = wpcf_fields_checkboxes_get_option(urldecode($_GET['parent_name']));
            $id = array_shift($element);
            $element_txt = wpcf_fields_checkboxes_get_option_alt_text($id, urldecode($_GET['parent_name']));
            echo json_encode(array('output' => wpcf_form_simple($element), 'wpcf_nonce_ajax_callback' => wp_create_nonce('execute')));
            break;
        case 'group_form_collapsed':
            require_once WPCF_INC_ABSPATH . '/fields-form.php';
            $group_id = sanitize_text_field($_GET['group_id']);
            $action = sanitize_text_field($_GET['toggle']);
            $fieldset = sanitize_text_field($_GET['id']);
            wpcf_admin_fields_form_save_open_fieldset($action, $fieldset, $group_id);
            break;
        case 'form_fieldset_toggle':
            $action = sanitize_text_field($_GET['toggle']);
            $fieldset = sanitize_text_field($_GET['id']);
            wpcf_admin_form_fieldset_save_toggle($action, $fieldset);
            break;
        case 'group_update_post_types':
            require_once WPCF_INC_ABSPATH . '/fields.php';
            // @todo Sanitize this $post_types
            $post_types = empty($_GET['wpcf']['group']['supports']) ? array() : $_GET['wpcf']['group']['supports'];
            if (!empty($_GET['group_id'])) {
                wpcf_admin_fields_save_group_post_types(sanitize_text_field($_GET['group_id']), $post_types);
                $output = array();
                foreach ($post_types as $post_type) {
                    $post_type = get_post_type_object($post_type);
                    if (!empty($post_type->label)) {
                        $output[] = $post_type->label;
                    }
                }
                if (empty($post_types)) {
                    $output[] = __('No post types associated', 'wpcf');
                }
                $output = implode(', ', $output);
            } else {
                $output = __('No post types associated', 'wpcf');
            }
            echo json_encode(array('output' => $output));
            break;
        case 'group_update_taxonomies':
            require_once WPCF_INC_ABSPATH . '/fields.php';
            $taxonomies_post = empty($_GET['wpcf']['group']['taxonomies']) ? array() : $_GET['wpcf']['group']['taxonomies'];
            $terms = array();
            foreach ($taxonomies_post as $taxonomy) {
                foreach ($taxonomy as $tax => $term) {
                    $terms[] = $term;
                }
            }
            if (!empty($_GET['group_id'])) {
                wpcf_admin_fields_save_group_terms(sanitize_text_field($_GET['group_id']), $terms);
                $output = array();
                foreach ($taxonomies_post as $taxonomy => $terms) {
                    $taxonomy = get_taxonomy($taxonomy);
                    if (!empty($taxonomy)) {
                        $title = $taxonomy->label . ': ';
                        foreach ($terms as $term_id) {
                            $term = get_term($term_id, $taxonomy->name);
                            $output[] = $title . $term->name;
                            $title = '';
                        }
                    }
                }
                if (empty($output)) {
                    $output[] = __('No taxonomies associated', 'wpcf');
                }
                $output = implode(', ', $output);
            } else {
                $output = __('No taxonomies associated', 'wpcf');
            }
            echo json_encode(array('output' => $output));
            break;
        case 'custom_fields_control_bulk':
            require_once WPCF_INC_ABSPATH . '/fields.php';
            require_once WPCF_EMBEDDED_INC_ABSPATH . '/fields.php';
            require_once WPCF_INC_ABSPATH . '/fields-control.php';
            wpcf_admin_custom_fields_control_bulk_ajax();
            break;
        case 'fields_delete':
        case 'delete_field':
            require_once WPCF_INC_ABSPATH . '/fields.php';
            if (isset($_GET['field_id'])) {
                wpcf_admin_fields_delete_field(sanitize_text_field($_GET['field_id']));
            }
            if (isset($_GET['field'])) {
                wpcf_admin_fields_delete_field(sanitize_text_field($_GET['field']));
            }
            echo json_encode(array('output' => ''));
            break;
        case 'remove_from_history':
            require_once WPCF_INC_ABSPATH . '/fields.php';
            $fields = wpcf_admin_fields_get_fields();
            if (isset($_GET['field_id']) && isset($fields[$_GET['field_id']])) {
                $fields[$_GET['field_id']]['data']['removed_from_history'] = 1;
                wpcf_admin_fields_save_fields($fields, true);
            }
            echo json_encode(array('output' => ''));
            break;
        case 'add_condition':
            require_once WPCF_INC_ABSPATH . '/fields.php';
            require_once WPCF_ABSPATH . '/includes/conditional-display.php';
            if (!empty($_GET['field']) || !empty($_GET['group'])) {
                $data = array();
                if (isset($_GET['group'])) {
                    $output = wpcf_form_simple(wpcf_cd_admin_form_single_filter(array(), array(), null, true));
                    echo json_encode(array('output' => $output));
                } else {
                    $data['id'] = str_replace('_conditional_display', '', sanitize_text_field($_GET['field']));
                    $output = wpcf_form_simple(wpcf_cd_admin_form_single_filter($data, array(), null, false));
                    if (!empty($data['id'])) {
                        echo json_encode(array('output' => $output));
                    } else {
                        echo json_encode(array('output' => __('Error occured', 'wpcf')));
                    }
                }
            } else {
                echo json_encode(array('output' => __('Error occured', 'wpcf')));
            }
            break;
        case 'pt_edit_fields':
            if (!empty($_GET['parent']) && !empty($_GET['child'])) {
                require_once WPCF_INC_ABSPATH . '/fields.php';
                require_once WPCF_INC_ABSPATH . '/post-relationship.php';
                wpcf_pr_admin_edit_fields(sanitize_text_field($_GET['parent']), sanitize_text_field($_GET['child']));
            }
            break;
        case 'toggle':
            $option = get_option('wpcf_toggle', array());
            $hidden = isset($_GET['hidden']) ? (bool) $_GET['hidden'] : 1;
            $_GET['div'] = strval($_GET['div']);
            if (!$hidden) {
                unset($option[$_GET['div']]);
            } else {
                $option[$_GET['div']] = 1;
            }
            update_option('wpcf_toggle', $option);
            break;
        case 'cb_save_empty_migrate':
            $output = sprintf('<span style="color:red;">%s</div>', __('Migration process is not yet finished - please save group first, then change settings of this field.', 'wpcf'));
            if (isset($_GET['field']) && isset($_GET['subaction'])) {
                require_once WPCF_INC_ABSPATH . '/fields.php';
                $option = $_GET['meta_type'] == 'usermeta' ? 'wpcf-usermeta' : 'wpcf-fields';
                $meta_type = sanitize_text_field($_GET['meta_type']);
                $field = wpcf_admin_fields_get_field(sanitize_text_field($_GET['field']), false, false, false, $option);
                $_txt_updates = $meta_type == 'usermeta' ? __('%d users require update', 'wpcf') : __('%d posts require update', 'wpcf');
                $_txt_no_updates = $meta_type == 'usermeta' ? __('No users require update', 'wpcf') : __('No posts require update', 'wpcf');
                $_txt_updated = $meta_type == 'usermeta' ? __('Users updated', 'wpcf') : __('Posts updated', 'wpcf');
                if (!empty($field)) {
                    if ($_GET['subaction'] == 'save_check' || $_GET['subaction'] == 'do_not_save_check') {
                        if ($field['type'] == 'checkbox') {
                            $posts = wpcf_admin_fields_checkbox_migrate_empty_check($field, $_GET['subaction']);
                        } else {
                            if ($field['type'] == 'checkboxes') {
                                $posts = wpcf_admin_fields_checkboxes_migrate_empty_check($field, $_GET['subaction']);
                            }
                        }
                        if (!empty($posts)) {
                            $output = '<div class="message updated"><p>' . sprintf($_txt_updates, count($posts)) . '&nbsp;' . '<a href="javascript:void(0);" class="button-primary" onclick="' . 'wpcfCbSaveEmptyMigrate(jQuery(this).parent().parent().parent(), \'' . sanitize_text_field($_GET['field']) . '\', ' . count($posts) . ', \'' . wp_create_nonce('cb_save_empty_migrate') . '\', \'';
                            $output .= $_GET['subaction'] == 'save_check' ? 'save' : 'do_not_save';
                            $output .= '\', \'' . $meta_type . '\');' . '">' . __('Update') . '</a>' . '</p></div>';
                        } else {
                            $output = '<div class="message updated"><p><em>' . $_txt_no_updates . '</em></p></div>';
                        }
                    } else {
                        if ($_GET['subaction'] == 'save' || $_GET['subaction'] == 'do_not_save') {
                            if ($field['type'] == 'checkbox') {
                                $posts = wpcf_admin_fields_checkbox_migrate_empty($field, $_GET['subaction']);
                            } else {
                                if ($field['type'] == 'checkboxes') {
                                    $posts = wpcf_admin_fields_checkboxes_migrate_empty($field, $_GET['subaction']);
                                }
                            }
                            if (isset($posts['offset'])) {
                                if (!isset($_GET['total'])) {
                                    $output = '<span style="color:red;">' . __('Error occured', 'wpcf') . '</div>';
                                } else {
                                    $output = '<script type="text/javascript">wpcfCbMigrateStep(' . intval($_GET['total']) . ',' . $posts['offset'] . ',' . '\'' . sanitize_text_field($_GET['field']) . '\',' . '\'' . wp_create_nonce('cb_save_empty_migrate') . '\', \'' . $meta_type . '\');</script>' . number_format($posts['offset']) . '/' . number_format(intval($_GET['total'])) . '<div class="wpcf-ajax-loading-small"></div>';
                                }
                            } else {
                                $output = '<div class="message updated"><p>' . $_txt_updated . '</p></div>';
                            }
                        }
                    }
                }
            }
            echo json_encode(array('output' => $output));
            break;
        default:
            break;
    }
    die;
}
Esempio n. 22
0
/**
 * Custom Conditinal Statement hook returns timestamp if array.
 * 
 * NOTE that $null is already filtered to use $_POST values
 * at priority 10.
 * 
 * @param type $null
 * @param type $object_id
 * @param type $meta_key
 * @param type $single
 * @return mixed timestamp or $null
 */
function wpcf_fields_date_custom_conditional_statement_filter($null, $object_id, $meta_key, $single)
{
    $post = get_post($object_id);
    if (!empty($post->ID)) {
        $field = wpcf_admin_fields_get_field($single);
        $field->set($post, $meta_key);
        if (isset($field->cf['type']) && $field->cf['type'] == 'date') {
            $res = wpcf_fields_date_value_get_filter($null, $field, 'timestamp', 'skip_hour_and_minute');
            if (is_int($res)) {
                return $res;
            }
        }
    }
    return $null;
}
/**
 * Passes $_POST values for AJAX call.
 *
 * @todo still used by group.
 *
 * @param type $null
 * @param type $object_id
 * @param type $meta_key
 * @param type $single
 * @return type
 */
function wpcf_cd_meta_ajax_validation_filter($null, $object_id, $meta_key, $single)
{
    $meta_key = str_replace('wpcf-', '', $meta_key);
    $field = wpcf_admin_fields_get_field($meta_key);
    $value = !empty($field) && isset($_POST['wpcf'][$meta_key]) ? $_POST['wpcf'][$meta_key] : '';
    /**
     * be sure do not return string if array is expected!
     */
    if (!$single && !is_array($value)) {
        return array($value);
    }
    return $value;
}
/**
 * 
 * Views-Shortcode: wpv-control
 *
 * Description: Add filters for View
 *
 * Parameters:
 * type: type of retrieved field layout (radio, checkbox, select, textfield, checkboxes, datepicker)
 * url_param: the URL parameter passed as an argument
 * values: Optional. a list of supplied values
 * display_values: Optional. A list of values to display for the corresponding values
 * auto_fill: Optional. When set to a "field-slug" the control will be populated with custom field values from the database.
 * auto_fill_default: Optional. Used to set the default, unselected, value of the control. eg Ignore or Don't care
 * auto_fill_sort: Optional. 'asc', 'desc', 'ascnum', 'descnum', 'none'. Defaults to ascending.
 * field: Optional. a Types field to retrieve values from
 * title: Optional. Use for the checkbox title
 * taxonomy: Optional. Use when a taxonomy control should be displayed.
 * default_label: Optional. Use when a taxonomy control should be displayed using select input type.
 * date_format: Optional. Used for a datepicker control
 *
 * Example usage:
 *
 * Link:
 * More details about this shortcode here: <a href="http://wp-types.com/documentation/wpv-control-fields-in-front-end-filters/" title="wpv-control – Displaying fields in front-end filters">http://wp-types.com/documentation/wpv-control-fields-in-front-end-filters/</a>
 *
 * Note:
 *
 */
function wpv_shortcode_wpv_control($atts)
{
    if (!isset($atts['url_param'])) {
        return __('The url_param is missing from the wpv-control shortcode argument.', 'wpv-views');
    }
    if ((!isset($atts['type']) || $atts == '') && !isset($atts['field'])) {
        return __('The "type" or "field" needs to be set in the wpv-control shortcode argument.', 'wpv-views');
    }
    extract(shortcode_atts(array('type' => '', 'values' => array(), 'display_values' => array(), 'field' => '', 'url_param' => '', 'title' => '', 'taxonomy' => '', 'default_label' => '', 'auto_fill' => '', 'auto_fill_default' => '', 'auto_fill_sort' => '', 'date_format' => ''), $atts));
    if ($taxonomy != '') {
        // pass the new shortcode attribute $default_label
        return _wpv_render_taxonomy_control($taxonomy, $type, $url_param, $default_label);
    }
    if ($auto_fill != '') {
        // See if we should handle types checkboxes
        $types_checkboxes_field = false;
        if (_wpv_is_field_of_type($auto_fill, 'checkboxes')) {
            if (!function_exists('wpcf_admin_fields_get_fields')) {
                if (defined('WPCF_EMBEDDED_ABSPATH')) {
                    include WPCF_EMBEDDED_ABSPATH . '/includes/fields.php';
                }
            }
            if (function_exists('wpcf_admin_fields_get_fields')) {
                $fields = wpcf_admin_fields_get_fields();
                $field_name = substr($auto_fill, 5);
                if (isset($fields[$field_name])) {
                    $types_checkboxes_field = true;
                    $db_values = array();
                    $options = $fields[$field_name]['data']['options'];
                    foreach ($options as $option) {
                        $db_values[] = $option['title'];
                    }
                    switch (strtolower($auto_fill_sort)) {
                        case 'desc':
                            sort($db_values);
                            $db_values = array_reverse($db_values);
                            break;
                        case 'descnum':
                            sort($db_values, SORT_NUMERIC);
                            $db_values = array_reverse($db_values);
                            break;
                        case 'none':
                            break;
                        case 'ascnum':
                            sort($db_values, SORT_NUMERIC);
                            break;
                        default:
                            sort($db_values);
                            break;
                    }
                }
            }
        }
        if (!$types_checkboxes_field) {
            if (!function_exists('wpcf_admin_fields_get_fields')) {
                if (defined('WPCF_EMBEDDED_ABSPATH')) {
                    include WPCF_EMBEDDED_ABSPATH . '/includes/fields.php';
                }
            }
            if (function_exists('wpcf_admin_fields_get_fields')) {
                $fields = wpcf_admin_fields_get_fields();
            }
            $field_name = substr($auto_fill, 5);
            if (isset($fields) && isset($fields[$field_name]) && isset($fields[$field_name]['data']['options'])) {
                $display_text = array();
                $options = $fields[$field_name]['data']['options'];
                if (isset($options['default'])) {
                    unset($options['default']);
                }
                // remove the default option from the array
                if (isset($fields[$field_name]['data']['display'])) {
                    $display_option = $fields[$field_name]['data']['display'];
                }
                foreach ($options as $option) {
                    if (isset($option['value'])) {
                        $db_values[] = $option['value'];
                    }
                    if (isset($display_option) && 'value' == $display_option && isset($option['display_value'])) {
                        $display_text[$option['value']] = $option['display_value'];
                        // fill an array with the actual display values
                    } else {
                        $display_text[$option['value']] = $option['title'];
                    }
                }
            } else {
                global $wpdb;
                switch (strtolower($auto_fill_sort)) {
                    case 'desc':
                        $db_values = $wpdb->get_col("SELECT DISTINCT meta_value FROM {$wpdb->postmeta} WHERE meta_key = '{$auto_fill}' ORDER BY meta_value DESC");
                        break;
                    case 'descnum':
                        $db_values = $wpdb->get_col("SELECT DISTINCT meta_value FROM {$wpdb->postmeta} WHERE meta_key = '{$auto_fill}' ORDER BY meta_value + 0 DESC");
                        break;
                    case 'none':
                        $db_values = $wpdb->get_col("SELECT DISTINCT meta_value FROM {$wpdb->postmeta} WHERE meta_key = '{$auto_fill}'");
                        break;
                    case 'ascnum':
                        $db_values = $wpdb->get_col("SELECT DISTINCT meta_value FROM {$wpdb->postmeta} WHERE meta_key = '{$auto_fill}' ORDER BY meta_value + 0 ASC");
                        break;
                    default:
                        $db_values = $wpdb->get_col("SELECT DISTINCT meta_value FROM {$wpdb->postmeta} WHERE meta_key = '{$auto_fill}' ORDER BY meta_value ASC");
                        break;
                }
            }
        }
        if ($auto_fill_default != '') {
            $values = '';
            $display_values = $auto_fill_default;
            $first = false;
        } else {
            $values = '';
            $display_values = '';
            $first = true;
        }
        foreach ($db_values as $value) {
            if ($value) {
                if (!$first) {
                    $values .= ',';
                    $display_values .= ',';
                }
                $values .= $value;
                if (isset($display_text[$value])) {
                    $display_values .= $display_text[$value];
                } else {
                    $display_values .= $value;
                }
                $first = false;
            }
        }
    }
    $out = '';
    // Use when values attributes are defined (predefined values to list)
    if (!empty($values)) {
        $values_arr = explode(',', $values);
        if (!empty($display_values)) {
            $display_values = explode(',', $display_values);
        }
        $options = array();
        if (!in_array($type, array('radio', 'radios', 'select', 'checkboxes'))) {
            $type = 'select';
        }
        if ($type == 'radio') {
            $type = 'radios';
        }
        switch ($type) {
            case 'checkboxes':
                $defaults = array();
                $original_get = null;
                if (isset($auto_fill_default)) {
                    // check if the defaul value already exists and set the appropriate arrays and values
                    $num_auto_fill_default_display = array_count_values($display_values);
                    if (isset($num_auto_fill_default_display[$auto_fill_default]) && $num_auto_fill_default_display[$auto_fill_default] > 1 || in_array($auto_fill_default, $values_arr)) {
                        // if the default value is an existing display value or stored value
                        $values_arr_def = array_shift($values_arr);
                        $display_values_def = array_shift($display_values);
                    }
                    $defaults = explode(',', $auto_fill_default);
                    $defaults = array_map('trim', $defaults);
                }
                if (isset($_GET[$url_param])) {
                    $original_get = $_GET[$url_param];
                    $defaults = $_GET[$url_param];
                    if (is_string($defaults)) {
                        $defaults = explode(',', $defaults);
                    }
                    unset($_GET[$url_param]);
                }
                for ($i = 0; $i < count($values_arr); $i++) {
                    $value = $values_arr[$i];
                    $value = trim($value);
                    // Check for a display value.
                    if (isset($display_values[$i])) {
                        $display_value = $display_values[$i];
                    } else {
                        $display_value = $value;
                    }
                    $options[$value]['#name'] = $url_param . '[]';
                    $options[$value]['#title'] = $display_value;
                    $options[$value]['#value'] = $value;
                    $options[$value]['#default_value'] = in_array($value, $defaults) || in_array($options[$value]['#title'], $defaults);
                    // set default using option titles too
                    //                    $options[$value]['#inline'] = true;
                    //                    $options[$value]['#after'] = '&nbsp;&nbsp;';
                }
                $element = wpv_form_control(array('field' => array('#type' => $type, '#id' => 'wpv_control_' . $type . '_' . $url_param, '#name' => $url_param . '[]', '#attributes' => array('style' => ''), '#inline' => true, '#options' => $options)));
                if ($original_get) {
                    $_GET[$url_param] = $original_get;
                }
                break;
            default:
                for ($i = 0; $i < count($values_arr); $i++) {
                    $value = $values_arr[$i];
                    $value = trim($value);
                    // Check for a display value.
                    if (isset($display_values[$i])) {
                        $display_value = $display_values[$i];
                    } else {
                        $display_value = $value;
                    }
                    $options[$display_value] = $value;
                }
                if (count($values_arr) != count($options)) {
                    // if the $values_arr has one more item than $options, there is a repeating value reset on creation: the existing default
                    $default_value = reset($options);
                } else {
                    // so the default value in this case is the first element in $values_arr
                    $default_value = $values_arr[0];
                }
                if (isset($_GET[$url_param]) && in_array($_GET[$url_param], $options)) {
                    $default_value = $_GET[$url_param];
                }
                $element = wpv_form_control(array('field' => array('#type' => $type, '#id' => 'wpv_control_' . $type . '_' . $url_param, '#name' => $url_param, '#attributes' => array('style' => ''), '#inline' => true, '#options' => $options, '#default_value' => $default_value)));
                break;
        }
        return $element;
    } else {
        if (!empty($field)) {
            // check if Types is active
            if (!function_exists('wpcf_admin_fields_get_field')) {
                if (defined('WPCF_EMBEDDED_ABSPATH')) {
                    include WPCF_EMBEDDED_ABSPATH . '/includes/fields.php';
                } else {
                    return __('Types plugin is required.', 'wpv-views');
                }
            }
            if (!function_exists('wpv_form_control')) {
                include '../common/functions.php';
            }
            // get field options
            $field_options = wpcf_admin_fields_get_field($field);
            if (empty($field_options)) {
                return __('Empty field values or incorrect field defined. ', 'wpv-views');
            }
            $field_options['name'] = wpcf_translate('field ' . $field_options['id'] . ' name', $field_options['name']);
            // get the type of custom field (radio, checkbox, other)
            $field_type = $field_options['type'];
            // override with type
            if (!empty($type)) {
                $field_type = $type;
            }
            if (!in_array($field_type, array('radio', 'checkbox', 'checkboxes', 'select', 'textfield', 'date', 'datepicker'))) {
                $field_type = 'textfield';
            }
            // Radio field
            if ($field_type == 'radio') {
                $field_radio_options = $field_options['data']['options'];
                $options = array();
                foreach ($field_radio_options as $key => $opts) {
                    if (is_array($opts)) {
                        if (isset($field_options['data']['display']) && 'value' == $field_options['data']['display'] && isset($opts['display_value'])) {
                            $options[$opts['display_value']] = $opts['value'];
                            // if we have an actual display value and is set to be used, use it
                        } else {
                            $options[$opts['title']] = $opts['value'];
                            // else, use the field value title
                        }
                    }
                }
                // get the form content
                $element = wpv_form_control(array('field' => array('#type' => 'radios', '#id' => 'wpv_control_radio_' . $field, '#name' => $url_param, '#attributes' => array('style' => ''), '#inline' => true, '#options' => $options, '#default_value' => isset($_GET[$url_param]) ? $_GET[$url_param] : null)));
                return $element;
            } else {
                if ($field_type == 'checkbox') {
                    if (isset($atts['title'])) {
                        $checkbox_name = $title;
                    } else {
                        $checkbox_name = $field_options['name'];
                    }
                    $element = wpv_form_control(array('field' => array('#type' => 'checkbox', '#id' => 'wpv_control_checkbox_' . $field, '#name' => $url_param, '#attributes' => array('style' => ''), '#inline' => true, '#title' => $checkbox_name, '#value' => $field_options['data']['set_value'], '#default_value' => 0)));
                    return $element;
                } else {
                    if ($field_type == 'checkboxes') {
                        $defaults = array();
                        $original_get = null;
                        if (isset($_GET[$url_param])) {
                            $original_get = $_GET[$url_param];
                            $defaults = $_GET[$url_param];
                            if (is_string($defaults)) {
                                $defaults = explode(',', $defaults);
                            }
                            unset($_GET[$url_param]);
                        }
                        foreach ($field_options['data']['options'] as $value) {
                            $value = trim($value['title']);
                            $display_value = $value;
                            $options[$value]['#name'] = $url_param . '[]';
                            $options[$value]['#title'] = $display_value;
                            $options[$value]['#value'] = $value;
                            $options[$value]['#default_value'] = in_array($value, $defaults);
                            //                $options[$value]['#inline'] = true;
                            //                $options[$value]['#after'] = '&nbsp;&nbsp;';
                        }
                        $element = wpv_form_control(array('field' => array('#type' => 'checkboxes', '#id' => 'wpv_control_checkbox_' . $field, '#name' => $url_param . '[]', '#attributes' => array('style' => ''), '#inline' => true, '#options' => $options)));
                        if ($original_get) {
                            $_GET[$url_param] = $original_get;
                        }
                        return $element;
                    } else {
                        if ($field_type == 'select') {
                            $field_select_options = $field_options['data']['options'];
                            $options = array();
                            foreach ($field_select_options as $key => $opts) {
                                if (is_array($opts)) {
                                    $options[$opts['title']] = $opts['value'];
                                }
                            }
                            $default_value = false;
                            if (isset($_GET[$url_param]) && in_array($_GET[$url_param], $options)) {
                                $default_value = $_GET[$url_param];
                            }
                            $element = wpv_form_control(array('field' => array('#type' => 'select', '#id' => 'wpv_control_select_' . $url_param, '#name' => $url_param, '#attributes' => array('style' => ''), '#inline' => true, '#options' => $options, '#default_value' => $default_value)));
                            return $element;
                        } else {
                            if ($field_type == 'textfield') {
                                $default_value = '';
                                if (isset($_GET[$url_param])) {
                                    $default_value = esc_attr($_GET[$url_param]);
                                }
                                $element = wpv_form_control(array('field' => array('#type' => 'textfield', '#id' => 'wpv_control_textfield_' . $url_param, '#name' => $url_param, '#attributes' => array('style' => ''), '#inline' => true, '#value' => $default_value)));
                                return $element;
                            } else {
                                if ($field_type == 'date' || $field_type == 'datepicker') {
                                    $out = wpv_render_datepicker($url_param, $date_format);
                                    return $out;
                                }
                            }
                        }
                    }
                }
            }
            return '';
        } else {
            // type parameter without values
            $default_value = '';
            if (isset($_GET[$url_param])) {
                $default_value = $_GET[$url_param];
            }
            switch ($type) {
                case 'checkbox':
                    $element = array('field' => array('#type' => $type, '#id' => 'wpv_control_' . $type . '_' . $url_param, '#name' => $url_param, '#attributes' => array('style' => ''), '#inline' => true, '#value' => $default_value));
                    $element['field']['#title'] = $title;
                    $element = wpv_form_control($element);
                    break;
                case 'datepicker':
                    $element = wpv_render_datepicker($url_param, $date_format);
                    break;
                default:
                    $element = array('field' => array('#type' => $type, '#id' => 'wpv_control_' . $type . '_' . $url_param, '#name' => $url_param, '#attributes' => array('style' => ''), '#inline' => true, '#value' => $default_value));
                    $element = wpv_form_control($element);
                    break;
            }
            return $element;
        }
    }
}
Esempio n. 25
0
/**
 * Gets all fields that belong to specific group.
 * 
 * @global type $wpdb
 * @param type $group_id
 * @param type $key
 * @param type $only_active
 * @return type 
 */
function wpcf_admin_fields_get_fields_by_group($group_id, $key = 'slug', $only_active = false, $disabled_by_type = false, $strictly_active = false)
{
    static $cache = array();
    $cache_key = md5($group_id . $key . $only_active . $disabled_by_type . $strictly_active);
    if (isset($cache[$cache_key])) {
        return $cache[$cache_key];
    }
    $group_fields = get_post_meta($group_id, '_wp_types_group_fields', true);
    if (empty($group_fields)) {
        return array();
    }
    $group_fields = explode(',', trim($group_fields, ','));
    $fields = wpcf_admin_fields_get_fields($only_active, $disabled_by_type, $strictly_active);
    $results = array();
    foreach ($group_fields as $field_id) {
        if (!isset($fields[$field_id])) {
            continue;
        }
        $field = wpcf_admin_fields_get_field($field_id);
        if (!empty($field)) {
            $results[$field_id] = $field;
        }
    }
    $cache[$cache_key] = $results;
    return $results;
}
Esempio n. 26
0
/**
 * Editor callback form submit.
 */
function wpcf_fields_file_editor_submit()
{
    $add = '';
    if (!empty($_POST['link'])) {
        $add .= ' link="true"';
        if (!empty($_POST['title'])) {
            $add .= ' title="' . strval($_POST['title']) . '"';
        }
    }
    if (!empty($_POST['class'])) {
        $add .= ' class="' . $_POST['class'] . '"';
    }
    if (!empty($_POST['style'])) {
        $add .= ' style="' . $_POST['style'] . '"';
    }
    $field = wpcf_admin_fields_get_field($_GET['field_id']);
    if (!empty($field)) {
        $shortcode = wpcf_fields_get_shortcode($field, $add);
        wpcf_admin_fields_save_field_last_settings($_GET['field_id'], $_POST);
        echo editor_admin_popup_insert_shortcode_js($shortcode);
        die;
    }
}
Esempio n. 27
0
/**
 * All AJAX calls go here.
 *
 * @todo auth
 */
function wpcf_ajax_embedded()
{
    if (isset($_REQUEST['_typesnonce'])) {
        if (!wp_verify_nonce($_REQUEST['_typesnonce'], '_typesnonce')) {
            die('Verification failed (1)');
        }
    } else {
        if (!isset($_REQUEST['_wpnonce']) || !wp_verify_nonce($_REQUEST['_wpnonce'], $_REQUEST['wpcf_action'])) {
            die('Verification failed (2)');
        }
    }
    global $wpcf;
    switch ($_REQUEST['wpcf_action']) {
        case 'insert_skype_button':
            if (!current_user_can('edit_posts')) {
                die('Authentication failed');
            }
            require_once WPCF_EMBEDDED_INC_ABSPATH . '/fields/skype.php';
            wpcf_fields_skype_meta_box_ajax();
            break;
        case 'editor_callback':
            if (!current_user_can('edit_posts')) {
                die('Authentication failed');
            }
            // Determine Field type and context
            $views_meta = false;
            $field_id = sanitize_text_field($_GET['field_id']);
            // todo this could be written in like four lines
            if (isset($_GET['field_type']) && $_GET['field_type'] == 'usermeta') {
                // Group filter
                wp_enqueue_script('suggest');
                $field = types_get_field($field_id, 'usermeta');
                $meta_type = 'usermeta';
            } elseif (isset($_GET['field_type']) && $_GET['field_type'] == 'views-usermeta') {
                $field = types_get_field($field_id, 'usermeta');
                $meta_type = 'usermeta';
                $views_meta = true;
            } elseif (isset($_GET['field_type']) && $_GET['field_type'] == 'termmeta') {
                // Group filter
                wp_enqueue_script('suggest');
                $field = types_get_field($field_id, 'termmeta');
                $meta_type = 'termmeta';
            } elseif (isset($_GET['field_type']) && $_GET['field_type'] == 'views-termmeta') {
                $field = types_get_field($field_id, 'termmeta');
                $meta_type = 'termmeta';
                $views_meta = true;
            } else {
                $field = types_get_field($field_id);
                $meta_type = 'postmeta';
            }
            $parent_post_id = isset($_GET['post_id']) ? intval($_GET['post_id']) : null;
            $shortcode = isset($_GET['shortcode']) ? urldecode($_GET['shortcode']) : null;
            $callback = isset($_GET['callback']) ? sanitize_text_field($_GET['callback']) : false;
            if (!empty($field)) {
                // Editor
                WPCF_Loader::loadClass('editor');
                $editor = new WPCF_Editor();
                $editor->frame($field, $meta_type, $parent_post_id, $shortcode, $callback, $views_meta);
            }
            break;
        case 'dismiss_message':
            if (!is_user_logged_in()) {
                die('Authentication failed');
            }
            if (isset($_GET['id'])) {
                $messages = get_option('wpcf_dismissed_messages', array());
                $messages[] = sanitize_text_field($_GET['id']);
                update_option('wpcf_dismissed_messages', $messages);
            }
            break;
        case 'pr_add_child_post':
            global $current_user;
            $output = '<tr>' . __('Passed wrong parameters', 'wpcf') . '</tr>';
            $id = 0;
            $target_post_type = isset($_GET['post_type_child']) ? sanitize_text_field($_GET['post_type_child']) : '';
            $has_permissions = current_user_can('publish_posts');
            $has_permissions = apply_filters('toolset_access_api_get_post_type_permissions', $has_permissions, $target_post_type, 'publish');
            if (!$has_permissions) {
                $output = '<tr><td>' . __('You do not have rights to create new items', 'wpcf') . '</td></tr>';
            } else {
                if (isset($_GET['post_id']) && isset($_GET['post_type_child']) && isset($_GET['post_type_parent'])) {
                    $relationships = get_option('wpcf_post_relationship', array());
                    $parent_post_id = intval($_GET['post_id']);
                    $parent_post = get_post($parent_post_id);
                    if (!empty($parent_post->ID)) {
                        $post_type = sanitize_text_field($_GET['post_type_child']);
                        $parent_post_type = sanitize_text_field($_GET['post_type_parent']);
                        // @todo isset & error handling
                        $data = $relationships[$parent_post_type][$post_type];
                        /*
                         * Since Types 1.1.5
                         * 
                         * We save new post
                         * CHECKPOINT
                         */
                        $id = $wpcf->relationship->add_new_child($parent_post->ID, $post_type);
                        if (is_wp_error($id)) {
                            $output = '<tr>' . $id->get_error_message() . '</tr>';
                        } else {
                            /*
                             * Here we set Relationship
                             * CHECKPOINT
                             */
                            $parent = get_post($parent_post_id);
                            $child = get_post($id);
                            if (!empty($parent->ID) && !empty($child->ID)) {
                                // Set post
                                $wpcf->post = $child;
                                // Set relationship :)
                                $wpcf->relationship->_set($parent, $child, $data);
                                // Render new row
                                $output = $wpcf->relationship->child_row($parent_post->ID, $id, $data);
                            } else {
                                $output = '<tr>' . __('Error creating post relationship', 'wpcf') . '</tr>';
                            }
                        }
                    } else {
                        $output = '<tr>' . __('Error getting parent post', 'wpcf') . '</tr>';
                    }
                }
            }
            if (!defined('WPTOOLSET_FORMS_VERSION')) {
                echo json_encode(array('output' => $output . wpcf_form_render_js_validation('#post', false), 'child_id' => $id));
            } else {
                echo json_encode(array('output' => $output, 'conditionals' => array('#post' => wptoolset_form_get_conditional_data('post')), 'child_id' => $id));
            }
            break;
        case 'pr_save_all':
            ob_start();
            // Try to catch any errors
            $output = '';
            if (current_user_can('edit_posts') && isset($_POST['post_id'])) {
                $parent_id = intval($_POST['post_id']);
                $post_type = sanitize_text_field($_POST['post_type']);
                if (isset($_POST['wpcf_post_relationship'][$parent_id])) {
                    $children = wpcf_sanitize_post_realtionship_input((array) $_POST['wpcf_post_relationship'][$parent_id]);
                    $wpcf->relationship->save_children($parent_id, $children);
                    $output = $wpcf->relationship->child_meta_form($parent_id, strval($post_type));
                }
            }
            if (!defined('WPTOOLSET_FORMS_VERSION')) {
                // TODO Move to conditional
                $output .= '<script type="text/javascript">wpcfConditionalInit();</script>';
            }
            wpcf_show_admin_messages('echo');
            $errors = ob_get_clean();
            if (!defined('WPTOOLSET_FORMS_VERSION')) {
                echo json_encode(array('output' => $output, 'errors' => $errors));
            } else {
                echo json_encode(array('output' => $output, 'conditionals' => array('#post' => wptoolset_form_get_conditional_data('post')), 'errors' => $errors));
            }
            break;
        case 'pr_save_child_post':
            ob_start();
            // Try to catch any errors
            $output = '';
            if (current_user_can('edit_posts') && isset($_GET['post_id']) && isset($_GET['parent_id']) && isset($_GET['post_type_parent']) && isset($_GET['post_type_child']) && isset($_POST['wpcf_post_relationship'])) {
                $parent_id = intval($_GET['parent_id']);
                $child_id = intval($_GET['post_id']);
                $parent_post_type = sanitize_text_field($_GET['post_type_parent']);
                $child_post_type = sanitize_text_field($_GET['post_type_child']);
                if (isset($_POST['wpcf_post_relationship'][$parent_id][$child_id])) {
                    $fields = wpcf_sanitize_post_relationship_input_fields((array) $_POST['wpcf_post_relationship'][$parent_id][$child_id]);
                    $wpcf->relationship->save_child($parent_id, $child_id, $fields);
                    $output = $wpcf->relationship->child_row($parent_id, $child_id, $wpcf->relationship->settings($parent_post_type, $child_post_type));
                    if (!defined('WPTOOLSET_FORMS_VERSION')) {
                        // TODO Move to conditional
                        $output .= '<script type="text/javascript">wpcfConditionalInit(\'#types-child-row-' . $child_id . '\');</script>';
                    }
                }
            }
            wpcf_show_admin_messages('echo');
            $errors = ob_get_clean();
            if (!defined('WPTOOLSET_FORMS_VERSION')) {
                echo json_encode(array('output' => $output, 'errors' => $errors));
            } else {
                echo json_encode(array('output' => $output, 'errors' => $errors, 'conditionals' => array('#post' => wptoolset_form_get_conditional_data('post'))));
            }
            break;
        case 'pr_delete_child_post':
            require_once WPCF_EMBEDDED_ABSPATH . '/includes/post-relationship.php';
            $output = 'Passed wrong parameters';
            if (current_user_can('edit_posts') && isset($_GET['post_id'])) {
                $output = wpcf_pr_admin_delete_child_item(intval($_GET['post_id']));
            }
            echo json_encode(array('output' => $output));
            break;
        case 'pr_pagination':
            require_once WPCF_EMBEDDED_INC_ABSPATH . '/fields.php';
            require_once WPCF_EMBEDDED_INC_ABSPATH . '/fields-post.php';
            require_once WPCF_EMBEDDED_ABSPATH . '/includes/post-relationship.php';
            $output = 'Passed wrong parameters';
            if (current_user_can('edit_posts') && isset($_GET['post_id']) && isset($_GET['post_type'])) {
                global $wpcf;
                $parent = get_post(intval($_GET['post_id']));
                $child_post_type = sanitize_text_field($_GET['post_type']);
                if (!empty($parent->ID)) {
                    // Set post in loop
                    $wpcf->post = $parent;
                    // Save items_per_page
                    $wpcf->relationship->save_items_per_page($parent->post_type, $child_post_type, intval($_GET[$wpcf->relationship->items_per_page_option_name]));
                    $output = $wpcf->relationship->child_meta_form($parent->ID, $child_post_type);
                }
            }
            if (!defined('WPTOOLSET_FORMS_VERSION')) {
                echo json_encode(array('output' => $output));
            } else {
                echo json_encode(array('output' => $output, 'conditionals' => array('#post' => wptoolset_form_get_conditional_data('post'))));
            }
            break;
        case 'pr_sort':
            $output = 'Passed wrong parameters';
            if (current_user_can('edit_posts') && isset($_GET['field']) && isset($_GET['sort']) && isset($_GET['post_id']) && isset($_GET['post_type'])) {
                $output = $wpcf->relationship->child_meta_form(intval($_GET['post_id']), sanitize_text_field($_GET['post_type']));
            }
            if (!defined('WPTOOLSET_FORMS_VERSION')) {
                echo json_encode(array('output' => $output));
            } else {
                echo json_encode(array('output' => $output, 'conditionals' => array('#post' => wptoolset_form_get_conditional_data('post'))));
            }
            break;
            // Not used anywhere
            /*case 'pr_sort_parent':
              $output = 'Passed wrong parameters';
              if ( isset( $_GET['field'] ) && isset( $_GET['sort'] ) && isset( $_GET['post_id'] ) && isset( $_GET['post_type'] ) ) {
                  $output = $wpcf->relationship->child_meta_form(
                          intval( $_GET['post_id'] ), strval( $_GET['post_type'] )
                  );
              }
              if ( !defined( 'WPTOOLSET_FORMS_VERSION' ) ) {
                  echo json_encode( array(
                      'output' => $output,
                  ) );
              } else {
                  echo json_encode( array(
                      'output' => $output,
                      'conditionals' => array('#post' => wptoolset_form_get_conditional_data( 'post' )),
                  ) );
              }
              break;*/
            /* Usermeta */
        // Not used anywhere
        /*case 'pr_sort_parent':
          $output = 'Passed wrong parameters';
          if ( isset( $_GET['field'] ) && isset( $_GET['sort'] ) && isset( $_GET['post_id'] ) && isset( $_GET['post_type'] ) ) {
              $output = $wpcf->relationship->child_meta_form(
                      intval( $_GET['post_id'] ), strval( $_GET['post_type'] )
              );
          }
          if ( !defined( 'WPTOOLSET_FORMS_VERSION' ) ) {
              echo json_encode( array(
                  'output' => $output,
              ) );
          } else {
              echo json_encode( array(
                  'output' => $output,
                  'conditionals' => array('#post' => wptoolset_form_get_conditional_data( 'post' )),
              ) );
          }
          break;*/
        /* Usermeta */
        case 'um_repetitive_add':
            if (isset($_GET['user_id'])) {
                $user_id = (int) $_GET['user_id'];
            } else {
                $user_id = wpcf_usermeta_get_user();
            }
            if (isset($_GET['field_id']) && current_user_can('edit_user', $user_id)) {
                require_once WPCF_EMBEDDED_INC_ABSPATH . '/fields.php';
                require_once WPCF_EMBEDDED_INC_ABSPATH . '/fields-post.php';
                require_once WPCF_EMBEDDED_INC_ABSPATH . '/usermeta-post.php';
                $field = wpcf_admin_fields_get_field(sanitize_text_field($_GET['field_id']), false, false, false, 'wpcf-usermeta');
                global $wpcf;
                $wpcf->usermeta_repeater->set($user_id, $field);
                /*
                 * 
                 * Force empty values!
                 */
                $wpcf->usermeta_repeater->cf['value'] = null;
                $wpcf->usermeta_repeater->meta = null;
                $form = $wpcf->usermeta_repeater->get_field_form(null, true);
                echo json_encode(array('output' => wpcf_form_simple($form) . wpcf_form_render_js_validation('#your-profile', false)));
            } else {
                echo json_encode(array('output' => 'params missing'));
            }
            break;
        case 'um_repetitive_delete':
            if (isset($_POST['user_id']) && isset($_POST['field_id']) && current_user_can('edit_user', intval($_POST['user_id']))) {
                require_once WPCF_EMBEDDED_INC_ABSPATH . '/fields.php';
                $user_id = intval($_POST['user_id']);
                $field = wpcf_admin_fields_get_field(sanitize_text_field($_POST['field_id']), false, false, false, 'wpcf-usermeta');
                $meta_id = intval($_POST['meta_id']);
                if (!empty($field) && !empty($user_id) && !empty($meta_id)) {
                    /*
                     * 
                     * 
                     * Changed.
                     * Since Types 1.2
                     */
                    global $wpcf;
                    $wpcf->usermeta_repeater->set($user_id, $field);
                    $wpcf->usermeta_repeater->delete($meta_id);
                    echo json_encode(array('output' => 'deleted'));
                } else {
                    echo json_encode(array('output' => 'field or post not found'));
                }
            } else {
                echo json_encode(array('output' => 'params missing'));
            }
            break;
            /* End Usermeta */
        /* End Usermeta */
        case 'repetitive_add':
            if (current_user_can('edit_posts') && isset($_GET['field_id'])) {
                require_once WPCF_EMBEDDED_INC_ABSPATH . '/fields.php';
                require_once WPCF_EMBEDDED_INC_ABSPATH . '/fields-post.php';
                $field = wpcf_admin_fields_get_field(sanitize_text_field($_GET['field_id']));
                $parent_post_id = intval($_GET['post_id']);
                /*
                 * When post is new - post_id is 0
                 * We can safely set post_id to 1 cause
                 * values compared are filtered anyway.
                 */
                if ($parent_post_id == 0) {
                    $parent_post_id = 1;
                }
                $parent_post = get_post($parent_post_id);
                global $wpcf;
                $wpcf->repeater->set($parent_post, $field);
                /*
                 * 
                 * Force empty values!
                 */
                $wpcf->repeater->cf['value'] = null;
                $wpcf->repeater->meta = null;
                $form = $wpcf->repeater->get_field_form(null, true);
                echo json_encode(array('output' => wpcf_form_simple($form) . wpcf_form_render_js_validation('#post', false)));
            } else {
                echo json_encode(array('output' => 'params missing'));
            }
            break;
        case 'repetitive_delete':
            if (current_user_can('edit_posts') && isset($_POST['post_id']) && isset($_POST['field_id'])) {
                require_once WPCF_EMBEDDED_INC_ABSPATH . '/fields.php';
                $post_id = intval($_POST['post_id']);
                $parent_post = get_post($post_id);
                $field = wpcf_admin_fields_get_field(sanitize_text_field($_POST['field_id']));
                $meta_id = intval($_POST['meta_id']);
                if (!empty($field) && !empty($parent_post->ID) && !empty($meta_id)) {
                    /*
                     * 
                     * 
                     * Changed.
                     * Since Types 1.2
                     */
                    global $wpcf;
                    $wpcf->repeater->set($parent_post, $field);
                    $wpcf->repeater->delete($meta_id);
                    echo json_encode(array('output' => 'deleted'));
                } else {
                    echo json_encode(array('output' => 'field or post not found'));
                }
            } else {
                echo json_encode(array('output' => 'params missing'));
            }
            break;
        case 'wpcf_entry_search':
            if (current_user_can('edit_posts') && isset($_REQUEST['post_type'])) {
                $posts_per_page = apply_filters('wpcf_pr_belongs_post_numberposts', 10);
                $args = array('posts_per_page' => apply_filters('wpcf_pr_belongs_post_posts_per_page', $posts_per_page), 'post_status' => apply_filters('wpcf_pr_belongs_post_status', array('publish', 'private')), 'post_type' => sanitize_text_field($_REQUEST['post_type']), 'suppress_filters' => 1);
                if (isset($_REQUEST['s'])) {
                    $args['s'] = $_REQUEST['s'];
                }
                if (isset($_REQUEST['page']) && preg_match('/^\\d+$/', $_REQUEST['page'])) {
                    $args['paged'] = intval($_REQUEST['page']);
                }
                $the_query = new WP_Query($args);
                $posts = array('items' => array(), 'total_count' => $the_query->found_posts, 'incomplete_results' => $the_query->found_posts > $posts_per_page, 'posts_per_page' => $posts_per_page);
                if ($the_query->have_posts()) {
                    while ($the_query->have_posts()) {
                        $the_query->the_post();
                        $post_title = get_the_title();
                        if (empty($post_title)) {
                            $post_title = sprintf(__('[empty title] ID: %d', 'wpcf'), get_the_ID());
                        }
                        $posts['items'][] = array('ID' => get_the_ID(), 'post_title' => $post_title);
                    }
                }
                /* Restore original Post Data */
                wp_reset_postdata();
                echo json_encode($posts);
            } else {
                echo json_encode(array('output' => 'params missing'));
            }
            break;
        case 'wpcf_entry_entry':
            if (current_user_can('edit_posts') && isset($_REQUEST['p'])) {
                $wpcf_post = get_post((int) $_REQUEST['p'], ARRAY_A);
                if (isset($wpcf_post['ID'])) {
                    $post_title = $wpcf_post['post_title'];
                    if (empty($post_title)) {
                        $post_title = sprintf(__('[empty title] ID: %d', 'wpcf'), $wpcf_post['ID']);
                    }
                    echo json_encode(array('ID' => $wpcf_post['ID'], 'post_title' => $wpcf_post['post_title']));
                } else {
                    echo json_encode(array('output' => 'params missing'));
                }
            } else {
                echo json_encode(array('output' => 'params missing'));
            }
            break;
        default:
            break;
    }
    if (function_exists('wpcf_ajax')) {
        wpcf_ajax();
    }
    die;
}
Esempio n. 28
0
/**
 * Returns 'skypename' if available.
 *
 * @global type $wpcf
 * @param type $null
 * @param type $object_id
 * @param type $meta_key
 * @param type $single
 * @return type
 */
function wpcf_fields_skype_conditional_filter_post_meta($null, $object_id, $meta_key, $single)
{
    global $wpcf;
    $field = wpcf_admin_fields_get_field($wpcf->field->__get_slug_no_prefix($meta_key));
    if (!empty($field) && $field['type'] == 'skype') {
        $_meta = maybe_unserialize(wpcf_get_post_meta($object_id, $meta_key, $single));
        if (is_array($_meta)) {
            $null = isset($_meta['skypename']) ? $_meta['skypename'] : '';
        }
        /**
         * be sure do not return string if array is expected!
         */
        if (!$single && !is_array($null)) {
            return array($null);
        }
    }
    return $null;
}
Esempio n. 29
0
 /**
  *
  * @global object $wpdb
  *
  */
 function prepare_items()
 {
     global $wpdb;
     $wpcf_per_page = 15;
     // Get ours and enabled
     $cf_types = wpcf_admin_fields_get_fields(true, true);
     $__groups = wpcf_admin_fields_get_groups();
     foreach ($__groups as $__group_id => $__group) {
         $__groups[$__group_id]['fields'] = wpcf_admin_fields_get_fields_by_group($__group['id'], 'slug', false, true, false);
     }
     foreach ($cf_types as $cf_id => $cf) {
         foreach ($__groups as $__group) {
             if (isset($__group['fields'][$cf_id])) {
                 $cf_types[$cf_id]['groups'][$__group['id']] = $__group['name'];
             }
         }
         $cf_types[$cf_id]['groups_txt'] = empty($cf_types[$cf_id]['groups']) ? __('None', 'wpcf') : implode(', ', $cf_types[$cf_id]['groups']);
     }
     // Get others (cache this result?)
     $cf_other = $wpdb->get_results("\r\n\t\tSELECT meta_id, meta_key\r\n\t\tFROM {$wpdb->postmeta}\r\n\t\tGROUP BY meta_key\r\n\t\tHAVING meta_key NOT LIKE '\\_%'\r\n\t\tORDER BY meta_key");
     // Clean from ours
     foreach ($cf_other as $type_id => $type_data) {
         if (strpos($type_data->meta_key, WPCF_META_PREFIX) !== false) {
             $field_temp = wpcf_admin_fields_get_field(str_replace(WPCF_META_PREFIX, '', $type_data->meta_key));
             if (!empty($field_temp)) {
                 if (!empty($field_temp['data']['disabled'])) {
                     $cf_types[$field_temp['id']] = array('id' => $field_temp['id'], 'slug' => $type_data->meta_key, 'name' => $type_data->meta_key, 'type' => 0, 'groups_txt' => __('None', 'wpcf'));
                 } else {
                     unset($cf_other[$type_id]);
                 }
             } else {
                 if (wpcf_types_cf_under_control('check_exists', $type_data->meta_key)) {
                     unset($cf_other[$type_id]);
                 } else {
                     $cf_types[$type_data->meta_key] = array('id' => $type_data->meta_key, 'slug' => $type_data->meta_key, 'name' => $type_data->meta_key, 'type' => 0, 'groups_txt' => __('None', 'wpcf'));
                 }
             }
         } else {
             if (wpcf_types_cf_under_control('check_exists', $type_data->meta_key)) {
                 unset($cf_other[$type_id]);
             } else {
                 $cf_types[$type_data->meta_key] = array('id' => $type_data->meta_key, 'slug' => $type_data->meta_key, 'name' => $type_data->meta_key, 'type' => 0, 'groups_txt' => __('None', 'wpcf'));
             }
         }
     }
     // Set some values
     foreach ($cf_types as $cf_id_temp => $cf_temp) {
         if (empty($cf_temp['type']) || !empty($cf_temp['data']['controlled'])) {
             $cf_types[$cf_id_temp]['slug'] = $cf_temp['name'];
         } else {
             $cf_types[$cf_id_temp]['slug'] = wpcf_types_get_meta_prefix($cf_temp) . $cf_temp['slug'];
         }
     }
     // Order
     if (!empty($_REQUEST['orderby'])) {
         $sort_matches = array('c' => 'name', 'g' => 'groups_txt', 't' => 'slug', 'f' => 'type');
         $sorted_keys = array();
         $new_array = array();
         foreach ($cf_types as $cf_id_temp => $cf_temp) {
             if (isset($sort_matches[$_REQUEST['orderby']])) {
                 $sorted_keys[$cf_temp['id']] = strtolower($cf_temp[$sort_matches[$_REQUEST['orderby']]]);
             } else {
                 $sorted_keys[$cf_temp['id']] = strtolower($cf_temp[$sort_matches['c']]);
             }
         }
         asort($sorted_keys, SORT_STRING);
         if ('desc' == $_REQUEST['order']) {
             $sorted_keys = array_reverse($sorted_keys, true);
         }
         foreach ($sorted_keys as $cf_id_temp => $groups_txt) {
             $new_array[$cf_id_temp] = $cf_types[$cf_id_temp];
         }
         $cf_types = $new_array;
     }
     // Search
     if (!empty($_REQUEST['s'])) {
         $search_results = array();
         foreach ($cf_types as $search_id => $search_field) {
             if (strpos(strval($search_field['name']), strval(trim(stripslashes($_REQUEST['s'])))) !== false) {
                 $search_results[$search_id] = $cf_types[$search_id];
             }
         }
         $cf_types = $search_results;
     }
     if (empty($_GET['display_all'])) {
         $total_items = count($cf_types);
         if ($total_items < $wpcf_per_page) {
             $wpcf_per_page = $total_items;
         }
         if ($this->get_pagenum() == 1) {
             $offset = 0;
         } else {
             $offset = ($this->get_pagenum() - 1) * $wpcf_per_page;
         }
         // Display required number of entries on page
         $this->items = array_slice($cf_types, $offset, $wpcf_per_page);
         $this->set_pagination_args(array('total_items' => $total_items, 'per_page' => $wpcf_per_page));
     } else {
         $this->items = $cf_types;
     }
     $this->_column_headers = array($this->get_columns(), array(), $this->get_sortable_columns());
 }
Esempio n. 30
0
/**
 * 
 * Views-Shortcode: wpv-control
 *
 * Description: Add filters for View
 *
 * Parameters:
 * type: Type of retrieved field layout 'radio', 'checkbox', 'select', 'multi-select', 'textfield', 'checkboxes', 'datepicker'
 * url_param: The URL parameter passed as an argument
 * values: Optional, a list of supplied values
 * display_values: Optional, a list of values to display for the corresponding values
 * auto_fill: Optional, when set to a "field-slug" the control will be populated with custom field values from the database.
 * auto_fill_default: Optional, use to set the default, unselected, value of the control. eg Ignore or Don't care
 * auto_fill_sort: Optional. 'asc', 'desc', 'ascnum', 'descnum', 'none'. Defaults to ascending.
 * field: Optional, a custom field to retrieve values from
 * title: Optional, use for the checkbox title
 * taxonomy: Optional, use when a taxonomy control should be displayed.
 * taxonomy_orderby. Optional. 'name', 'id', 'count', 'slug', 'term_group', 'none'. Defaults to 'name'
 * taxonomy_order: Optional 'ASC', 'DESC'. Defaults to ascending.
 * default_label: Optional, use when a taxonomy control should be displayed using select input type.
 * date_format: Optional, use for a datepicker control
 *
 * Example usage:
 *
 * Link:
 * More details about this shortcode here: <a href="http://wp-types.com/documentation/wpv-control-fields-in-front-end-filters/?utm_source=viewsplugin&utm_campaign=views&utm_medium=filter-help-link&utm_term=http://wp-types.com/documentation/wpv-control-fields-in-front-end-filters/" title="wpv-control – Displaying fields in front-end filters">http://wp-types.com/documentation/wpv-control-fields-in-front-end-filters/</a>
 *
 * Note:
 *
 */
function wpv_shortcode_wpv_control($atts) {
	
	// First control checks
	if ( !isset( $atts['url_param'] ) ) {
		return __('The url_param is missing from the wpv-control shortcode argument.', 'wpv-views');
	}
	if ( ( !isset( $atts['type'] ) || $atts == '' ) && !isset( $atts['field'] ) ) {
		return __('The "type" or "field" needs to be set in the wpv-control shortcode argument.', 'wpv-views');
	}
	
	//Start the shortcode management
	global $WP_Views, $no_parameter_found;
	$aux_array = $WP_Views->view_used_ids;
	$view_name = get_post_field( 'post_name', end( $aux_array ) );
	
	extract(
		shortcode_atts(array(
				'type' => '', // select, multi-select, checbox, checkboxes, radio/radios, date/datepicker, textfield
				'values' => array(), // (optional) comma-separated list of user-provided values
                'display_values' => array(), // (optional) comma-separated list of user-provided display values
				'field' => '', // name of the custom field
				'url_param' => '', // URL parameter to be used
                'title' => '', // title to be used on a checkbox field type
                'taxonomy' => '', // name of the taxonomy for taxonomies filter controls
                'taxonomy_orderby' => 'name', // order of the terms for taxonomies filter controls
                'taxonomy_order' => 'ASC', // orderby of the terms for taxonomies filter controls
                'format' => false, // format of the display value, use %%NAME%% or %%COUNT%% as placeholders
                'default_label' => '', // default label for taxonomies filter controls when using select input type
                'hide_empty' => 'false', // option to hide empty terms for taxonomies filter controls
                'auto_fill' => '', // options to auto fill values for custom fields filter controls - provide the field name
                'auto_fill_default' => '', // default value when using auto_fill for custom fields filter controls
                'auto_fill_sort' => '', // order when using auto_fill for custom fields filter controls
                'date_format' => '', // date format for date controls
				'default_date' => '',  // default date for date controls
				'force_zero' => 'false',
                'style' => '', // inline styles for input
                'class' => '', // input classes
                'label_style' => '', // inline styles for input label
                'label_class' => '' // classes for input label
			), $atts)
	);
	
    $style = esc_attr( $style );
    $class = esc_attr( $class );
    $label_style = esc_attr( $label_style );
    $label_class = esc_attr( $label_class );  
    
	// First, parametric search control for taxonomy
	if ( $taxonomy != '' ) {
		// Translate the default label if any
		if ( !empty( $default_label ) ) {
			$default_label = wpv_translate( $url_param . '_default_label', $default_label, false, 'View ' . $view_name );
			$atts['default_label'] = $default_label;
		}
		// Render the taxonomy control
		return wpv_render_taxonomy_control( $atts );
    }
	
	// Before doing anything else, rule out textfields
	if ( $type == 'textfield' ) {
		// Textfield field
		$default_value = '';
		if ( isset( $_GET[ $url_param ] ) ) {
			$default_value = stripslashes( urldecode( sanitize_text_field( $_GET[ $url_param ] ) ) );
		}
		
		// Render the form content
		$element = wpv_form_control( array(
				'field' => array(
						'#type' => 'textfield',
						'#id' => 'wpv_control_textfield_' . $url_param,
						'#name' => $url_param,
						'#attributes' => array( 'style' => $style, 'class' => 'js-wpv-filter-trigger-delayed ' . $class  ),
						'#inline' => true,
						'#value' => $default_value ) ) );
		return $element;
	}
    
	// Check if the View has dependency enabled
    $view_settings = $WP_Views->get_view_settings();
	$dependant = false;
	$counters = ( $format && strpos( $format, '%%COUNT%%' ) !== false ) ? true : false;
	$empty_action = array();
	if ( isset( $view_settings['dps'] )
		&& is_array( $view_settings['dps'] )
		&& isset( $view_settings['dps']['enable_dependency'] )
		&& $view_settings['dps']['enable_dependency'] == 'enable' )
	{
		$dependant = true;
		$force_disable_dependant = $WP_Views->get_force_disable_dependant_parametric_search();
		if ( $force_disable_dependant ) {
			$dependant = false;
		}
	}
	
	// Some basic values
	if ( empty( $field ) ) {
		if ( empty( $auto_fill ) ) {
			// In this case, the shortcode is not about a custom field filter but a generic one without taxonomy, field or auto_fill attributes
			// It can be used to generate custom form inputs, given that the user provides values (and maybe display_values)
			// So we need to disable dependency
			$dependant = false;
			$counters = false;
		} else {
			$field_real_name = _wpv_get_field_real_slug( $auto_fill );
		}
	} else {
		$field_real_name = _wpv_get_field_real_slug( $field );
	}
	
	$display_values_trans = false; // flag to whether the display_values need to be translated
	$out = '';
	
	// If dependency is ON, build the basic data and cache
	if ( $dependant || $counters ) {
		$empty_default = 'hide';
		$empty_alt = 'disable';
		$empty_options = array( 'select', 'radios', 'checkboxes' ); // multi-select is a special case because of dashes and underscores
		foreach ( $empty_options as $empty_opt ) {
			if ( isset( $view_settings['dps'][ 'empty_' . $empty_opt ] )
				&& $view_settings['dps'][ 'empty_' . $empty_opt ] == $empty_alt )
			{
				$empty_action[ $empty_opt ] = $empty_alt;
			} else {
				$empty_action[ $empty_opt ] = $empty_default;
			}
		}
		if ( isset( $view_settings['dps']['empty_multi_select'] )
			&& $view_settings['dps']['empty_multi_select'] == $empty_alt )
		{
			$empty_action['multi-select'] = $empty_alt;
		} else {
			$empty_action['multi-select'] = $empty_default;
		}
		$wpv_data_cache = array();
		$original_value = $view_settings[ 'custom-field-' . $field_real_name . '_value' ];
		$processed_value = wpv_apply_user_functions( $original_value );
		$compare_function = $view_settings[ 'custom-field-' . $field_real_name . '_compare' ];
		$current_value_key = false;
		// @todo check IN, NOT IN and != compare functions
		$comparator = 'equal';
		$filter_full_list = false;
		if ( $compare_function == 'BETWEEN' ) {
			$original_value_array = array_map( 'trim', explode( ',', $original_value ) );
			$processed_value_array = array_map( 'trim', explode( ',', $processed_value ) );
			$current_value_key = array_search( 'URL_PARAM(' . $url_param . ')', $original_value_array );
			if ( $current_value_key !== false ) {
				$processed_value = isset( $processed_value_array[ $current_value_key ] ) ? $processed_value_array[ $current_value_key ] : $no_parameter_found;
				if ( $current_value_key < 1 ) {
					$comparator = 'lower-equal-than';
				} else if ( $current_value_key > 0 ) {
					$comparator = 'greater-equal-than';
				}
			}
		} else if ( $compare_function == '>' ) {
			$comparator = 'lower-than';
		} else if ( $compare_function == '>=' ) {
			$comparator = 'lower-equal-than';
		} else if ( $compare_function == '<' ) {
			$comparator = 'greater-than';
		} else if ( $compare_function == '<=' ) {
			$comparator = 'greater-equal-than';
		}
		// Construct $wpv_data_cache['post_meta']
		if ( $processed_value == $no_parameter_found ) {
			global $wp_object_cache;
			$wpv_data_cache = isset( $wp_object_cache->cache ) ? $wp_object_cache->cache : array();
			$aux_query_count = null;
		} else {
			// When there is a selected value, create a pseudo-cache based on all the other filters
			// Note that checkboxes filters can generate nested meta_query entries
			$query = wpv_get_dependant_view_query_args();
			$aux_cache_query = null;
			$filter_full_list = true;
			if ( isset( $query['meta_query'] ) && is_array( $query['meta_query'] ) ) {
				foreach ( $query['meta_query'] as $qt_index => $qt_val ) {
					if ( is_array( $qt_val ) ) {
						foreach ( $qt_val as $qt_val_key => $qt_val_val ) {
							if ( 
								$qt_val_key == 'key' 
								&& $qt_val_val == $field_real_name
							) {
								if ( $compare_function == 'BETWEEN' ) {
									if ( 
										$qt_val['compare'] == 'BETWEEN' 
										&& $current_value_key !== false 
									) {
										$qt_val['value'] = isset( $qt_val['value'] ) ? $qt_val['value'] : '';
										$passed_values = is_array( $qt_val['value'] ) ? $qt_val['value'] : array_map( 'trim', explode( ',', $qt_val['value'] ) );
										if ( $current_value_key < 1 && isset( $passed_values[1] ) ) {
											$query['meta_query'][ $qt_index ]['compare'] = '<=';
											$query['meta_query'][ $qt_index ]['value']= $passed_values[1];
										} else if ( $current_value_key > 0 && isset( $passed_values[0] ) ) {
											$query['meta_query'][ $qt_index ]['compare'] = '>=';
											$query['meta_query'][ $qt_index ]['value']= $passed_values[0];
										}
									} else {
										unset( $query['meta_query'][ $qt_index ] );
									}
									// if $compare_function is BETWEEN and we have a meta_query not using BETWEEN, we have a partial query here, so keep it
								} else {
									unset( $query['meta_query'][$qt_index] );
								}
							} else if ( 
								is_array( $qt_val_val ) 
								&& isset( $qt_val_val['key'] ) 
								&& $qt_val_val['key'] == $field_real_name
							) {
								if ( $compare_function == 'BETWEEN' ) {
									if ( 
										$qt_val_val['compare'] == 'BETWEEN' 
										&& $current_value_key !== false 
									) {
										$qt_val_val['value'] = isset( $qt_val_val['value'] ) ? $qt_val_val['value'] : '';
										$passed_values = is_array( $qt_val_val['value'] ) ? $qt_val_val['value'] : array_map( 'trim', explode( ',', $qt_val_val['value'] ) );
										if ( $current_value_key < 1 && isset( $passed_values[1] ) ) {
											$query['meta_query'][ $qt_index ][ $qt_val_key ]['compare'] = '<=';
											$query['meta_query'][ $qt_index ][ $qt_val_key ]['value']= $passed_values[1];
										} else if ( $current_value_key > 0 && isset( $passed_values[0] ) ) {
											$query['meta_query'][ $qt_index ][ $qt_val_key ]['compare'] = '>=';
											$query['meta_query'][ $qt_index ][ $qt_val_key ]['value']= $passed_values[0];
										}
									} else {
										unset( $query['meta_query'][ $qt_index ][ $qt_val_key ] );
									}
									// if $compare_function is BETWEEN and we have a meta_query not using BETWEEN, we have a partial query here, so keep it
								} else {
									unset( $query['meta_query'][$qt_index][ $qt_val_key ] );
								}
							}
						}
					}
				}
			}
			$aux_cache_query = new WP_Query($query);
			if ( is_array( $aux_cache_query->posts ) && !empty( $aux_cache_query->posts ) ) {
				$aux_query_count = count( $aux_cache_query->posts );
				$f_fields = array( $field_real_name );
				$wpv_data_cache = wpv_custom_cache_metadata( $aux_cache_query->posts, array( 'cf' => $f_fields ) );
			}
		}
		if ( !isset( $wpv_data_cache['post_meta'] ) ) {
			$wpv_data_cache['post_meta'] = array();
		}
		
		// OK, for checkboxes custom fields the stored value is NOT the one we use for filtering
		// So instead of filtering $wpv_data_cache['post_meta'] we will loop it to see if the $field_real_name key exists
		// AND check the serialized value to see if it contains the given real value (warning, not the label!)
		// AND break as soon as true because we need no counters
		// Expensive, but not sure if more than wp_list_filter though
	}
	
	// Management of multiselect
	$multi = '';
	if ( $type == 'multi-select') {
		$type = 'select';
		$multi = 'multiple';
	}
	
	//  $filter_check_type = _wpv_is_field_of_type( $auto_fill, 'checkboxes' ) ? 'checkboxes' : 'other';
	$filter_check_type = wpv_types_get_field_type( $field );
	
	if ( $auto_fill != '' ) {
		/**
		* If using auto_fill, populate the values and display_values arrays
		*/
        
        /**
        * First we are going to populate those variables
        */
        $fields = array(); // this will hold the Types fields from the Options
        $db_values = array(); // this will hold the field values from Types options or from the database
        $display_text = array(); // this will hold the field values pretty display text, if it is a Types field with options
        $auto_fill_default_trans = false; // flag to whether the auto_fill_default has translated, based on whether it is one of the existing values
        
        if ( !function_exists( 'wpcf_admin_fields_get_fields' ) ) {
			if( defined( 'WPCF_EMBEDDED_ABSPATH' ) ) {
				include WPCF_EMBEDDED_ABSPATH . '/includes/fields.php';
			}
		}
		if ( function_exists( 'wpcf_admin_fields_get_fields' ) ) {
			$fields = wpcf_admin_fields_get_fields();
		}
		// $field_name = substr($auto_fill, 5); // TODO DONE check this for fields created outside of Types and brought under Types control
		if ( strpos( $auto_fill, 'wpcf-' ) === 0 ) {
			$field_name = substr( $auto_fill, 5 );
        } else {
			$field_name = $auto_fill;
        }

        // If it is a Types field with options
        if ( isset( $fields[ $field_name ] ) && isset( $fields[ $field_name ]['data']['options'] ) ) { 
			// If it is a checkboxes Types field
			if ( _wpv_is_field_of_type( $auto_fill, 'checkboxes' ) ) { 
				$options = $fields[ $field_name ]['data']['options'];
				foreach( $options as $field_key => $option ) {
					// Fill the db_values and display_text (translated if needed) arrays
					$db_values[] = $option['title'];
					$display_text[ $option['title'] ] = wpv_translate( 'field '. $fields[ $field_name ]['id'] .' option '. $field_key .' title', $option['title'], false, 'plugin Types' );
				}
			} else {
				// If it is a Types field different from checkboxes but with options
				$options = $fields[ $field_name ]['data']['options'];
				if ( isset( $options['default'] ) ) {
					// remove the default option from the array
					unset( $options['default'] );
				}
				if ( isset( $fields[ $field_name ]['data']['display'] ) ) {
					$display_option =  $fields[ $field_name ]['data']['display'];
				}
				foreach ( $options as $field_key => $option ) {
					if ( isset( $option['value'] ) ) {
						$db_values[] = $option['value'];
					}
					if ( isset( $display_option )
						&& 'value' == $display_option
						&& isset( $option['display_value'] ) )
					{
						$display_text[ $option['value'] ] = wpv_translate( 'field '. $fields[ $field_name ]['id'] .' option '. $field_key .' title', $option['display_value'], false, 'plugin Types' );
					} else {
						$display_text[ $option['value'] ] = wpv_translate( 'field '. $fields[ $field_name ]['id'] .' option '. $field_key .' title', $option['title'], false, 'plugin Types' );
					}
					if ( $auto_fill_default != '' ) {
						// translate the auto_fill_default option if needed, just when it's one of the existing options
						$auto_fill_default = str_replace( '\,', ',', $auto_fill_default );
						if ( $auto_fill_default == $option['title'] ) {
							$auto_fill_default = wpv_translate( 'field '. $fields[ $field_name ]['id'] .' option '. $field_key .' title', $option['title'], false, 'plugin Types' );
							// set this flat to true: we already have translated auto_fill_default
							$auto_fill_default_trans = true; 
						}
						$auto_fill_default = str_replace( ',', '\,', $auto_fill_default );
					}
				}
			}

			// Now sort the values based on auto_fill_sort
			switch ( strtolower( $auto_fill_sort ) ) {
				case 'desc':
					sort( $db_values );
					$db_values = array_reverse( $db_values );
					break;
				case 'descnum':
					sort( $db_values, SORT_NUMERIC );
					$db_values = array_reverse( $db_values );
					break;
				case 'none':
					break;
				case 'ascnum':
					sort( $db_values, SORT_NUMERIC );
					break;
				default:
					sort( $db_values );
					break;
			}
			
        } else {
			// If it is not a Types field OR is a Types field without options

			global $wpdb;
			$values_to_prepare = array();
			$values_to_prepare[] = $auto_fill;
			$wpdb_where = '';
			if ( isset( $view_settings['post_type'] )
				&& is_array( $view_settings['post_type'] )
				&& ! empty( $view_settings['post_type'] )
				&& ! in_array( 'any', $view_settings['post_type'] ) 
			) {
				$post_type_count = count( $view_settings['post_type'] );
				$post_type_placeholders = array_fill( 0, $post_type_count, '%s' );
				$wpdb_where .= " AND p.post_type IN (" . implode( ",", $post_type_placeholders ) . ") ";
				foreach ( $view_settings['post_type'] as $pt ) {
					$values_to_prepare[] = $pt;
				}
			}
			if ( 
				isset( $view_settings['post_status'] ) 
				&& is_array( $view_settings['post_status'] ) 
				&& ! empty( $view_settings['post_status'] )
			) {
				if ( ! in_array( 'any', $view_settings['post_status'] ) ) {
					$post_status_count = count( $view_settings['post_status'] );
					$post_status_placeholders = array_fill( 0, $post_status_count, '%s' );
					$wpdb_where .= " AND p.post_status IN (" . implode( ",", $post_status_placeholders ) . ") ";
					foreach ( $view_settings['post_status'] as $ps ) {
						$values_to_prepare[] = $ps;
					}
				}
			} else {
				$status = array( 'publish' );
				if ( current_user_can( 'read_private_posts' ) ) {
					$status[] = 'private';
				}
				$wpdb_where .= " AND p.post_status IN ( '" . implode( "','", $status ) . "' ) ";
			}
			$wpdb_orderby = '';
			switch ( strtolower( $auto_fill_sort ) ) {
				case 'desc':
					$wpdb_orderby = "ORDER BY pm.meta_value DESC";
					break;
				case 'descnum':
					$wpdb_orderby = "ORDER BY pm.meta_value + 0 DESC";
					break;
				case 'ascnum':
					$wpdb_orderby = "ORDER BY pm.meta_value + 0 ASC";
					break;
				default:
					$wpdb_orderby = "ORDER BY pm.meta_value ASC";
					break;
			}
			$db_values = $wpdb->get_col( 
				$wpdb->prepare(
					"SELECT DISTINCT pm.meta_value FROM {$wpdb->postmeta} pm LEFT JOIN {$wpdb->posts} p ON p.ID = pm.post_id 
					WHERE pm.meta_key = %s AND pm.meta_value IS NOT NULL AND pm.meta_value != '' 
					{$wpdb_where} 
					{$wpdb_orderby}",
					$values_to_prepare 
				) 
			);
        }
        
        /**
        * Now we are going to fill the $values and $display_values comma-separated strings based on $db_values and, in case, $display_text
        * NOTE if $auto_fill_default_trans is FALSE then the auto_fill_default is NOT one of the existing option titles so we will translate it
        */
        if ( $auto_fill_default != '' ) {
			// If auto_fill_default is not empty, adjust and translate when needed
			if ( !$auto_fill_default_trans ) {
				// translate the auto_fill_default option when it's not one of the existing options
				$auto_fill_default = str_replace( '\,', ',', $auto_fill_default );
				$auto_fill_default = wpv_translate( $url_param . '_auto_fill_default', stripslashes( $auto_fill_default ), false, 'View ' . $view_name );
				$auto_fill_default = str_replace( ',', '\,', $auto_fill_default );
			}
            $values = '';
            $display_values = str_replace( '\,', '%comma%', $auto_fill_default );
            // flag to whether there is an auto_fill_default value that we ad at the beginning of the $display_value string
            $first = false; 
        } else {
            $values = '';
            $display_values = '';
            $first = true;
        }
        foreach( $db_values as $value ) {
            if ( $value !== false ) {
                if ( !$first ) {
                    $values .= ',';
                    $display_values .= ',';
                }
                // HACK to handle commas in values
                $values .= str_replace( ',', '%comma%', $value ); 
                if ( isset( $display_text[$value] ) ) {
					// HACK to handle commas in display_values
					$display_values .= str_replace( ',', '%comma%', $display_text[ $value ] ); 
				} else {
					// HACK to handle commas in display_values
					$display_values .= str_replace( ',', '%comma%', $value ); 
				}
                $first = false;
            }
        }
    // If not using auto_fill, check if there are manually added display_values
    } else if ( !empty( $display_values ) ) { 
		// mark that the display_values need to be translated
		$display_values_trans = true; 
    }
    
	/*
	* Now we have a comma-separated list of $values and $display_values, hopefully ;-D
	* In fact, we count with a $values comma-separated list
	* We will fill the $values_arr array and transform $display_values into an array
	*/
	
	if( !empty( $values ) ) {
		// When values attributes are manually defined, the inner commas are formatted as \, and we need to apply the same HACK as for the automatically set values
		$values_fix = str_replace( '\,', '%comma%', $values );
		// Now, get the $values_arr array of values
		$values_arr = explode( ',', $values_fix );
		// And undo the comma HACK
		$values_arr = str_replace( '%comma%', ',', $values_arr );
        if ( !empty( $display_values ) ) {
			// If there are display_values,again sync the comma HACK
			$display_values = str_replace( '\,', '%comma%', $display_values );
			// Get an array of $display_values
			$display_values = explode( ',', $display_values );
			// And undo the comma HACK
			$display_values = str_replace( '%comma%', ',', $display_values );
			if ( $display_values_trans ) {
				// If we need to translate the $display_values
				$translated_values = array();
				foreach ( $display_values as $index => $valuetrans ) {
					$translated_values[ $index ] = wpv_translate( $url_param . '_display_values_' . ( $index + 1 ), stripslashes( $valuetrans ), false, 'View ' . $view_name );
				}
				$display_values = $translated_values;
			}
        }

		// Parse date expressions in values.
		$values_count = count( $values_arr );
		for( $i = 0; $i < $values_count; ++$i ) {
			$values_arr[ $i ] = wpv_filter_parse_date( $values_arr[ $i ] );
		}
        
		/**
		* Now that we have the $values_arr and $display_values we focus on the kind of output
		* Based on $type we will popuate an $options variable and use the wpv_form_control() function
		*/
		
        if( !in_array( $type, array( 'radio', 'radios', 'select', 'checkboxes' ) ) ) {
            // For wpv-control shortcodes using auto_fill or values/display_values we only allow those kind of types
            $type = 'select';
        }
        if ( $type == 'radio' ) {
            // In fact, radios == radio
            $type = 'radios';
        }
        $options = array();
		// Now, depending on $type
        switch ( $type ) {
        
            case 'checkboxes':
                // If we need to render CHECKBOXES
                $defaults = array();
                $original_get = null;
                if ( isset( $auto_fill_default ) ) {
					// First, check if the defaul value already exists and set the appropriate arrays and values
					$num_auto_fill_default_display = array_count_values( $display_values );
					$auto_fill_default_trans = str_replace( '\,', ',', $auto_fill_default );
					if (
							// if the auto_fill_default is one of the display_values
							( isset( $num_auto_fill_default_display[ $auto_fill_default_trans ] )
							&& $num_auto_fill_default_display[ $auto_fill_default_trans ] > 1 )  
						||
							// OR if the auto_fill_default is one of the values
							in_array( $auto_fill_default_trans, $values_arr ) ) 
					{ 
						// Take out the first element of the $values_arr and the $display_values, which holds and empty string and the auto_fill_default value
						$values_arr_def = array_shift( $values_arr );
						$display_values_def = array_shift( $display_values );
					}
					// Then, set the preliminary $defaults value based on auto_fill_default
					$defaults = str_replace( '\,', '%comma%', $auto_fill_default );
					$defaults = explode( ',', $defaults );
					$defaults = str_replace( '%comma%', ',', $defaults );
					$defaults = array_map( 'trim', $defaults );
                }
                if ( isset( $_GET[ $url_param ] ) ) {
                    // Override $defaults if a set of values is coming from the URL parameter
                    $original_get = $_GET[ $url_param ];
                    $defaults = $_GET[ $url_param ];
                    if ( is_string( $defaults ) ) {
						$defaults = explode( ',',$defaults );
					}
                    unset( $_GET[ $url_param ] );
                }
                $count_values_array = count( $values_arr );
                for( $i = 0; $i < $count_values_array; $i++ ) {
                    // Loop through the $values_arr
                    $value = $values_arr[ $i ];
                    $value = trim( $value );
                    // Check for a display value
                    if ( isset( $display_values[ $i ] ) ) {
                        $display_value = $display_values[ $i ];
                    } else {
                        $display_value = $value;
                    }
                    // Compose the $options for this value
                    $options[ $value ]['#name'] = $url_param . '[]';
                    $options[ $value ]['#title'] = $display_value;
                    $options[ $value ]['#value'] = $value;
                    // set default using option titles too
                    $options[ $value ]['#default_value'] = in_array( $value, $defaults ) || in_array( $options[ $value ]['#title'], $defaults); 
                    $options[ $value ]['#attributes']['class'] = 'js-wpv-filter-trigger ' . $class;
                    $options[ $value ]['#attributes']['style'] = $style;
                    $options[ $value ]['#labelclass'] = $label_class;
                    $options[ $value ]['#labelstyle'] = $label_style;
                    // Dependant stuff
                    if ( $dependant || $counters ) {
						if ( $format ) {
							$display_value_formatted_name = str_replace( '%%NAME%%', $options[ $value ]['#title'], $format );
							$options[ $value ]['#title'] = $display_value_formatted_name;
						}
						$meta_criteria_to_filter = array( $field_real_name => array( $value ) );
						$this_query = $WP_Views->get_query();
						if ( empty( $value ) && !is_numeric( $value ) && is_object( $this_query ) ) {
							if ( isset( $aux_query_count ) ) {
								$this_checker = $aux_query_count;
							} else {
								$this_checker = $this_query->found_posts;
							}
						} else {
							$data = array();
							$data['list'] = $wpv_data_cache['post_meta'];
							$data['args'] = $meta_criteria_to_filter;
							$data['kind'] = $filter_check_type;
							$data['comparator'] = $comparator;
							if ( $counters ) {
								$data['count_matches'] = true;
							}
							$data['filter_full_list'] = $filter_full_list;
							$this_checker = wpv_list_filter_checker( $data );
						}
						if ( $counters ) {
							$display_value_formatted_name = str_replace( '%%COUNT%%', $this_checker, $options[ $value ]['#title'] );
							$options[ $value ]['#title'] = $display_value_formatted_name;                            
						}
						if ( !$this_checker && ( !empty( $value ) || is_numeric( $value ) ) && !$options[ $value ]['#default_value'] && $dependant ) {
							$options[ $value ]['#attributes']['#disabled'] = 'true';
							$options[ $value ]['#labelclass'] .= ' wpv-parametric-disabled ';
							if ( isset( $empty_action['checkboxes'] ) && $empty_action['checkboxes'] == 'hide' ) {
								unset( $options[ $value ] );
							}
						}
					}
//                    $options[$value]['#inline'] = true;
//                    $options[$value]['#after'] = '&nbsp;&nbsp;';
                }
                // Render the form control element
               	$element = wpv_form_control( array(
						'field' => array(
				                '#type' => $type,
				                '#id' => 'wpv_control_' . $type . '_' . $url_param,
				                '#name' => $url_param . '[]',
				                '#attributes' => array( 'style' => '' ),
				                '#inline' => true,
				                '#options' => $options,
								'#before' => '<div class="wpcf-checkboxes-grou">', //we need to wrap them for js purposes
								'#after' => '</div>' ) ) );
                
                if ( $original_get ) {
                    $_GET[ $url_param ] = $original_get;
                }
                break;
                
            default:
                // If we need to check any other field with values and a type that is not checkboxes (radios or select)
                $options_array = array();

                // This one will hold options in a display_vaue => value format so we can use it to compose the default_value later
                $options = array(); 

                $count_values_array = count( $values_arr );
                for( $i = 0; $i < $count_values_array; $i++ ) {
                    // Loop through the $values_arr
                    $value = $values_arr[ $i ];
                    $value = trim( $value );
                    // Check for a display value
                    if ( isset( $display_values[ $i ] ) ) {
                        $display_value = $display_values[ $i ];
                    } else {
                        $display_value = $value;
                    }
                    // Compose the $options for this value
                    $options[ $display_value ] = $value;
                    $options_array[ $display_value ] = array(
							'#title' => $display_value,
							'#value' => $value,
							'#inline' => true,
							'#after' => '<br />' );
                    $options_array[ $display_value ]['#attributes']['class'] = 'js-wpv-filter-trigger';
                    
                    if ( $type == 'radios' ) {
                        $options_array[ $display_value ]['#attributes']['class'] .= ' ' . $class;
                        $options_array[ $display_value ]['#attributes']['style'] = $style;
                        $options_array[ $display_value ]['#labelclass'] = $label_class;
                        $options_array[ $display_value ]['#labelstyle'] = $label_style;
                    }
                    // Dependant stuff
					if ( $dependant || $counters ) {
						if ( $format ) {
							$display_value_formatted_name = str_replace( '%%NAME%%', $options_array[ $display_value ]['#title'], $format );
							$options_array[ $display_value ]['#title'] = $display_value_formatted_name;
						}
						$this_query = $WP_Views->get_query();
						if ( empty( $value ) && !is_numeric( $value ) && is_object( $this_query ) ) {
							if ( isset( $aux_query_count ) ) {
								$this_checker = $aux_query_count;
							} else {
								$this_checker = $this_query->found_posts;
							}
						} else {
							$meta_criteria_to_filter = array( $field_real_name => array( $value ) );
							$data = array();
							$data['list'] = $wpv_data_cache['post_meta'];
							$data['args'] = $meta_criteria_to_filter;
							$data['kind'] = $filter_check_type;
							$data['comparator'] = $comparator;
							if ( $counters ) {
								$data['count_matches'] = true;
							}
							$data['filter_full_list'] = $filter_full_list;
							$this_checker = wpv_list_filter_checker( $data );
						}
						if ( $counters ) {
							$display_value_formatted_counter = str_replace( '%%COUNT%%', $this_checker, $options_array[ $display_value ]['#title'] );
							$options_array[ $display_value ]['#title'] = $display_value_formatted_counter;
						}
						
						if ( !$this_checker && ( !empty( $value ) || is_numeric( $value ) ) && $dependant ) {
							// TODO DONE need to merge this with the default_value below, to avoid hiddin or disabling selected items
							$options_array[ $display_value ]['#disable'] = 'true';
							$options_array[ $display_value ]['#labelclass'] = 'wpv-parametric-disabled';
							if ( $type == 'select' && $multi == 'multiple' ) {
								if ( isset( $empty_action['multi-select'] ) && $empty_action['multi-select'] == 'hide' ) {
									unset( $options_array[ $display_value ] );
								}
							} else if ( isset( $empty_action[ $type ] ) && $empty_action[ $type ] == 'hide' ) {
								unset( $options_array[ $display_value ] );
							}
						}
					}
                }
                
                if ( count( $values_arr ) != count( $options ) ) {
					// if the $values_arr has one more item than $options, there is a repeating value: the default one added to the beginning
					$default_value = reset( $options );
				} else {
					if ( 
						$type == 'radios' 
						|| $multi == 'multiple'
					) {
						$default_value = '';
					} else {
						// so the default value in this case is the first element in $values_arr
						$default_value = isset( $values_arr[0] ) ? $values_arr[0] : '';
					}
				}
				if ( $type == 'radios' ) {
					if ( isset( $_GET[ $url_param ] ) && in_array( $_GET[ $url_param ], $options ) ) {
						$default_value = $_GET[ $url_param ];
					}
					$name_aux = $url_param;
				} else {
					// Basically, if $type == 'select'
					if ( isset( $_GET[ $url_param ] ) ) {
						if ( is_array( $_GET[ $url_param ] ) ) {
							if ( count( array_intersect($_GET[ $url_param ], $options) ) > 0 ) {
								$default_value = $_GET[ $url_param ];
							}
						} else {
							if ( in_array( $_GET[ $url_param ], $options ) ) {
								$default_value = $_GET[ $url_param ];
							}
						}
					}
					$name_aux = $url_param . '[]';
				}

				// Now we need to recreate the $options_array element if it is a default one and is disabled or removed
				if ( is_array( $default_value ) ) {
					foreach ( $default_value as $dv ) {
						$aux_display_values = array_keys( $options, $dv, true );
						foreach ( $aux_display_values as $aux_dv ) {
							// TODO where is $aux_dv defined??
							if ( isset( $options_array[ $aux_dv ] ) ) {
								if ( isset( $options_array[ $aux_dv ]['#disable'] ) ) {
									unset( $options_array[ $aux_dv ]['#disable'] );
								}
								$options_array[ $aux_dv ]['#labelclass'] = '';
							} else {
								$options_array[ $aux_dv ] = array(
										'#title' => $aux_dv,
										'#value' => $dv,
										'#inline' => true,
										'#after' => '<br />' );
								$options_array[ $aux_dv ]['#attributes']['class'] = 'js-wpv-filter-trigger ';
							}
						}
					}
				} else {
					$aux_display_values = array_keys( $options, $default_value, true );
					foreach ( $aux_display_values as $aux_dv ) {
						if ( isset( $options_array[ $aux_dv ] ) ) {
							if ( isset( $options_array[$aux_dv]['#disable'] ) ) {
								unset( $options_array[$aux_dv]['#disable'] );
							}
							$options_array[ $aux_dv ]['#labelclass'] = '';
						} else {
							$options_array[ $aux_dv ] = array(
									'#title' => $aux_dv,
									'#value' => $default_value,
									'#inline' => true,
									'#after' => '<br />' );
							$options_array[ $aux_dv ]['#attributes']['class'] = 'js-wpv-filter-trigger';
						}
					}
				}
				
				$element = wpv_form_control( array(
						'field' => array(
								'#type' => $type,
								'#id' => 'wpv_control_' . $type . '_' . $url_param,
								'#name' => $name_aux,
								'#attributes' => array('style' => $style, 'class' => 'js-wpv-filter-trigger' . $class ),
								'#inline' => true,
								'#options' => $options_array, // NOTE this was originally $options but as it's not an array I can not set a "disabled" option
								'#default_value' => $default_value,
								'#multiple' => $multi // NOTE I'd say that radios do not need multiple but it should do no harm
								) )	);
				break;
        }
		return $element;
		
	} else if ( !empty( $field ) ) {
		/**
		* When field attribute is defined but we do not have auto_fill nor manually entered values
		* In this case, we display the control input based on $type or the field type itself if needed (mainly for Types auto style, but we can expect other combinations)
		*/

		// Check if Types is active because we are using wpcf_admin_fields_get_field()
		if ( !function_exists( 'wpcf_admin_fields_get_field' ) ) {
			if ( defined( 'WPCF_EMBEDDED_ABSPATH' ) ) {
				include WPCF_EMBEDDED_ABSPATH . '/includes/fields.php';
			} else {
				return __( 'Types plugin is required.', 'wpv-views' );
			}
		}
		if ( !function_exists( 'wpv_form_control' ) ) {
			include '../common/functions.php';
		}
		//This is important cause wpcf_admin_fields_get_field works with id: $field - 'wpcf-' and search with 'wpcf-'.$field
		/*if( strpos($field, 'wpcf-') !== false ) {
			$tmp = explode('wpcf-', $field);
			$field = $tmp[1];
		}*/
		// Get field options and translate name if needed
		$field_options = wpcf_admin_fields_get_field( $field );
		if ( empty( $field_options ) ) {
			return __( 'Empty field values or incorrect field defined. ', 'wpv-views' );
		}
        $field_options['name'] = wpv_translate( 'field ' . $field_options['id'] . ' name', $field_options['name'], false, 'plugin Types' );
		// Get field type, override if $type exists and default it to textfield if needed
		$field_type = $field_options['type'];
		if ( !empty( $type ) ) {
			// Watch out: this is where we can override the field type itself
			$field_type = $type;
		}
        if ( !in_array( $field_type, array( 'radio', 'checkbox', 'checkboxes', 'select', 'textfield', 'date', 'datepicker' ) ) ) {
            $field_type = 'textfield';
        }
		// Display time!!
		if ( $field_type == 'radio' ) {
			// Radio field
			$field_radio_options = isset( $field_options['data']['options'] ) ? $field_options['data']['options'] : array();
			$options = array();
			foreach ( $field_radio_options as $key => $opts ) {
				if ( is_array( $opts ) ) {
					
					if ( isset( $field_options['data']['display'] )
						&& 'value' == $field_options['data']['display']
						&& isset( $opts['display_value'] ) )
					{
						// if we have an actual display value and is set to be used, use it
						$display_value = $opts['display_value'];
						$value = $opts['value'];
					} else {
						// else, use the field value title and watch out because checkboxes fields need their titles as values
						$display_value = wpv_translate( 'field '. $field_options['id'] .' option '. $key .' title', $opts['title'], false, 'plugin Types' );
						if ( _wpv_is_field_of_type( 'wpcf-' . $field, 'checkboxes' ) ) {
							$value = $opts['title'];
						} else {
							$value = $opts['value'];
						}
					}
					$options[ $display_value ] = array(
						'#title' => $display_value,
						'#value' => $value,
						'#inline' => true,
						'#after' => '<br />'
                    );
                    $options[ $display_value ]['#attributes']['class'] = 'js-wpv-filter-trigger ' . $class;
                    $options[ $display_value ]['#attributes']['style'] = $style;
					// Dependant stuff
					if ( $dependant || $counters ) {
						if ( $format ) {
							$display_value_formatted_name = str_replace( '%%NAME%%', $options[ $display_value ]['#title'], $format );
							$options[ $display_value ]['#title'] = $display_value_formatted_name;
						}
						$this_query = $WP_Views->get_query();
						if ( empty( $value ) && !is_numeric( $value ) && is_object( $this_query ) ) {
							if ( isset( $aux_query_count ) ) {
								$this_checker = $aux_query_count;
							} else {
								$this_checker = $this_query->found_posts;
							}
						} else {
							$meta_criteria_to_filter = array( $field_real_name => array( $value ) );
							$data = array();
							$data['list'] = $wpv_data_cache['post_meta'];
							$data['args'] = $meta_criteria_to_filter;
							$data['kind'] = $filter_check_type;
							$data['comparator'] = $comparator;
							if ( $counters ) {
								$data['count_matches'] = true;
							}
							$data['filter_full_list'] = $filter_full_list;
							$this_checker = wpv_list_filter_checker( $data );
						}
						if ( $counters ) {
							$display_value_formatted_counter = str_replace( '%%COUNT%%', $this_checker, $options[ $display_value ]['#title'] );
							$options[ $display_value ]['#title'] = $display_value_formatted_counter;
						}
						if ( !$this_checker
							&& ( !empty( $value ) || is_numeric( $value ) )
							&& ( !isset( $_GET[$url_param] ) || $_GET[$url_param] !== $value )
							&& $dependant )
						{
							$options[ $display_value ]['#disable'] = 'true';
							$options[ $display_value ]['#labelclass'] = 'wpv-parametric-disabled';
							if ( isset( $empty_action['radios'] ) && $empty_action['radios'] == 'hide' ) {
								unset( $options[ $display_value ] );
							}
						}
					}
				}
			}
			// Render the form content
			$element = wpv_form_control( array(
					'field' => array(
							'#type' => 'radios',
							'#id' => 'wpv_control_radio_' . $field,
							'#name' => $url_param,
							'#attributes' => array( 'style' => $style, 'class' => $class ),
							'#inline' => true,
							'#options' => $options,
							'#default_value' => isset( $_GET[ $url_param ] ) ? $_GET[ $url_param ] : '' ) ) );
							
            return $element;
		} else if ( $field_type == 'checkbox' ) {
            // Checkbox field
            // Populate the $checkbox_name with the wpv-control title attribute OR the field name itself
            if ( isset( $atts['title'] ) ) {
                $checkbox_name =  wpv_translate( $url_param . '_title', $title, false, 'View ' . $view_name );
            } else {
				// NOTE mmmmmm we seem to have translated this $field_options['name'] right above...
                $checkbox_name = wpv_translate( 'field ' . $field_options['name'] . ' name', $field_options['name'], false, 'plugin Types' );
            }
            
            $value = $field_options['data']['set_value'];
            $coming_value = '';
			if ( isset( $_GET[ $url_param ] ) && !empty( $_GET[ $url_param ] ) ) {
				$value = esc_attr( $_GET[ $url_param ] );
				$coming_value = esc_attr( $_GET[ $url_param ] );
			} else if ( isset( $_GET[ $url_param ] ) && is_numeric( $_GET[ $url_param ] ) ) {
				// this only happens when the value to store when checked is actually zero - nonsense
				$value = 0;
				$coming_value = 0;
			} else if ( empty( $_GET[ $url_param ] ) ) {
				unset( $_GET[ $url_param ] );
			}
			$attributes = array( 'style' => '', 'class' => 'js-wpv-filter-trigger' );
            $labelclass = '';
            $show_checkbox = true;
            // Dependant stuff
			if ( $dependant || $counters ) {
				if ( $format ) {
					$display_value_formatted_name = str_replace( '%%NAME%%', $checkbox_name, $format );
					$checkbox_name = $display_value_formatted_name;
				}
				$meta_criteria_to_filter = array( $field_real_name => array( $value ) );
				$data = array();
				$data['list'] = $wpv_data_cache['post_meta'];
				$data['args'] = $meta_criteria_to_filter;
				$data['kind'] = $filter_check_type;
				$data['comparator'] = $comparator;
				if ( $counters ) {
					$data['count_matches'] = true;
				}
				$data['filter_full_list'] = $filter_full_list;
				$this_checker = wpv_list_filter_checker( $data );
				if ( $counters ) {
					$display_value_formatted_count = str_replace( '%%COUNT%%', $this_checker, $checkbox_name );
					$checkbox_name = $display_value_formatted_count;
				}
				if ( !$this_checker && empty( $coming_value ) && $dependant ) {
					$attributes['#disabled'] = 'true';
					$labelclass = 'wpv-parametric-disabled';
					if ( isset( $empty_action['checkboxes'] ) && $empty_action['checkboxes'] == 'hide' ) {
						$show_checkbox = false;
					}
				}
			}
            if ( $show_checkbox ) {
				// Render the form content
                $attributes['class'] .= ' ' . $class;
                $attributes['style'] = $style;
                
				$element = wpv_form_control( array(
						'field' => array(
								'#type' => 'checkbox',
								'#id' => 'wpv_control_checkbox_' . $field,
								'#name' => $url_param,
								'#attributes' => $attributes,
								'#inline' => true,
								'#title' => $checkbox_name,
								'#labelclass' => $labelclass . ' ' . $label_class,
                                '#labelstyle' => $label_style,
								'#value' => $field_options['data']['set_value'],
								'#default_value' => 0 ) ) );
				if ( isset( $field_options['data']['save_empty'] ) && $field_options['data']['save_empty'] == 'yes' && $force_zero == 'true' ) {
					$attributes['class'] = '';
					$attributes['checked'] = 'checked';
					$element .= wpv_form_control( array(
							'field' => array(
									'#type' => 'hidden',
									'#id' => 'wpv_control_checkbox_' . $field . '_fakezero',
									'#name' => $url_param . '_fakezero',
									'#attributes' => $attributes,
									'#inline' => true,
									'#value' => 'yes',
									'#default_value' => 0 ) ) );
				}
			} else {
				$element = '';
			}
            return $element;
            
		} else if ( $field_type == 'checkboxes' ) {

            // Checkboxes field
            $defaults = array();
            $original_get = null;
            if ( isset( $_GET[ $url_param ] ) ) {
                $original_get = $_GET[ $url_param ];
                $defaults = $_GET[ $url_param ];
                if ( is_string( $defaults ) ) {
					$defaults = explode( ',',$defaults );
				}
                unset( $_GET[ $url_param ] );
            }
            $field_checkboxes_options = isset( $field_options['data']['options'] ) ? $field_options['data']['options'] : array();
            if ( isset( $field_checkboxes_options['default'] ) ) {
				// Remove the default option from the array because it breaks the loop below
				unset( $field_checkboxes_options['default'] );
			}
            foreach( $field_checkboxes_options as $key => $value ) {
                $display_value = wpv_translate( 'field '. $field_options['id'] .' option '. $key .' title', trim( $value['title'] ), false, 'plugin Types' );
                if ( _wpv_is_field_of_type( 'wpcf-' . $field, 'checkboxes' ) ) {
					$value = trim( $value['title'] );
				} else {
					$value = trim( $value['value'] );
                }
                
                $options[ $value ]['#name'] = $url_param . '[]';
                $options[ $value ]['#title'] = $display_value;
                $options[ $value ]['#value'] = $value;
                $options[ $value ]['#default_value'] = in_array( $value, $defaults );
                //$options[$value]['#inline'] = true;
                //$options[$value]['#after'] = '&nbsp;&nbsp;';
                $options[ $value ]['#attributes']['class'] = 'js-wpv-filter-trigger ' . $class;
                $options[ $value ]['#attributes']['style'] = $style;
                $options[ $value ]['#labelclass'] = $label_class;
                $options[ $value ]['#labelstyle'] = $label_style;
                // Dependant stuff
				if ( $dependant || $counters ) {
					if ( $format ) {
						$display_value_formatted_name = str_replace( '%%NAME%%', $options[ $value ]['#title'], $format );
						$options[ $value ]['#title'] = $display_value_formatted_name;
					}
					$meta_criteria_to_filter = array( $field_real_name => array( $value ) ); // TODO DONE IMPORTANT check what is coming here as value, maybe $opts['title'] sometimes
					$this_query = $WP_Views->get_query();
					if ( empty( $value ) && !is_numeric( $value ) && is_object( $this_query ) ) {
						if ( isset( $aux_query_count ) ) {
							$this_checker = $aux_query_count;
						} else {
							$this_checker = $this_query->found_posts;
						}
					} else {
						$data = array();
						$data['list'] = $wpv_data_cache['post_meta'];
						$data['args'] = $meta_criteria_to_filter;
						$data['kind'] = $filter_check_type;
						$data['comparator'] = $comparator;
						if ( $counters ) {
							$data['count_matches'] = true;
						}
						$data['filter_full_list'] = $filter_full_list;
						$this_checker = wpv_list_filter_checker( $data );
					}
					if ( $counters ) {
						$display_value_formatted = str_replace( '%%COUNT%%', $this_checker, $options[ $value ]['#title'] );
						$options[ $value ]['#title'] = $display_value_formatted;
					}
					if ( !$this_checker && ( !empty( $value ) || is_numeric( $value ) ) && !$options[ $value ]['#default_value'] && $dependant ) {
						$options[ $value ]['#attributes']['#disabled'] = 'true';
						$options[ $value ]['#labelclass'] .= ' wpv-parametric-disabled';
						if ( isset( $empty_action['checkboxes'] ) && $empty_action['checkboxes'] == 'hide' ) {
							unset( $options[ $value ] );
						}
					}
				}
            }
            // Render the form content
            $element = wpv_form_control( array(
					'field' => array(
                            '#type' => 'checkboxes',
                            '#id' => 'wpv_control_checkbox_' . $field,
                            '#name' => $url_param . '[]',
                            '#attributes' => array( 'style' => '' ),
                            '#inline' => true,
                            '#options' => $options ) ) );
            if ( $original_get ) {
                $_GET[ $url_param ] = $original_get;
            }
            return $element;
		} else if ( $field_type == 'select' ) {
			// Select field
			$field_select_options = isset( $field_options['data']['options'] ) ? $field_options['data']['options'] : array();;
			$options = array();
			$opt_aux = array();
			foreach ( $field_select_options as $key => $opts ) {
				if ( is_array( $opts ) ) {
					
					$display_value = wpv_translate( 'field '. $field_options['id'] .' option '. $key .' title', $opts['title'], false, 'plugin Types' );
					if ( _wpv_is_field_of_type( 'wpcf-' . $field, 'checkboxes' ) ) {
						$value = $opts['title'];
					} else {
						$value = $opts['value'];
					}
					
					$options[ $display_value ] = array(
						'#title' => $display_value,
						'#value' => $value,
						'#inline' => true,
						'#after' => '<br />'
                    );
                    $opt_aux[ $display_value ] = $value;
					$options[ $display_value ]['#attributes']['class'] = 'js-wpv-filter-trigger';
					// Dependant stuff
					if ( $dependant || $counters ) {
						if ( $format ) {
							$display_value_formatted_name = str_replace( '%%NAME%%', $options[ $display_value ]['#title'], $format );
							$options[ $display_value ]['#title'] = $display_value_formatted_name;
						}
						$this_query = $WP_Views->get_query();
						if ( empty( $value ) && !is_numeric( $value ) && is_object( $this_query ) ) {
							if ( isset( $aux_query_count ) ) {
								$this_checker = $aux_query_count;
							} else {
								$this_checker = $this_query->found_posts;
							}
						} else {
							$meta_criteria_to_filter = array( $field_real_name => array( $value ) );
							$data = array();
							$data['list'] = $wpv_data_cache['post_meta'];
							$data['args'] = $meta_criteria_to_filter;
							$data['kind'] = $filter_check_type;
							$data['comparator'] = $comparator;
							if ( $counters ) {
								$data['count_matches'] = true;
							}
							$data['filter_full_list'] = $filter_full_list;
							$this_checker = wpv_list_filter_checker( $data );
						}
						if ( $counters ) {
							$display_value_formatted_counter = str_replace( '%%COUNT%%', $this_checker, $options[ $display_value ]['#title'] );
							$options[ $display_value ]['#title'] = $display_value_formatted_counter;
						}
						if ( !$this_checker && ( !empty( $value ) || is_numeric( $value ) ) && $dependant ) {
							// TODO DONE we need to adjust this with the $default_value below
							$options[ $display_value ]['#disable'] = 'true';
							$options[ $display_value ]['#labelclass'] = 'wpv-parametric-disabled';
							if ( $multi == 'multiple' ) {
								if ( isset( $empty_action['multi-select'] ) && $empty_action['multi-select'] == 'hide' ) {
									unset( $options[ $display_value ] );
								}
							} else if ( isset( $empty_action['select'] ) && $empty_action['select'] == 'hide' ) {
								unset( $options[ $display_value ] );
							}
						}
					}
				}
			}
			$default_value = false;
			if ( isset( $_GET[ $url_param ] ) ) {
				if ( is_array( $_GET[ $url_param ] ) ) {
					if ( count( array_intersect($_GET[ $url_param ], $opt_aux) ) > 0 ) {
						$default_value = $_GET[ $url_param ];
					}
				} else {
					if ( in_array( $_GET[ $url_param ], $opt_aux ) ) {
						$default_value = $_GET[ $url_param ];
					}
				}
			}
			
			// Now we need to recreate the $options element if it is a default one and is disabled or removed
			if ( $default_value !== false && is_array( $default_value ) ) {
				foreach ( $default_value as $dv ) {
					$aux_display_values = array_keys( $opt_aux, $dv, true );
					foreach ( $aux_display_values as $aux_dv ) {
						if ( isset( $options[ $aux_dv ] ) ) {
							if ( isset( $options[ $aux_dv ]['#disable'] ) ) {
								unset( $options[ $aux_dv ]['#disable'] );
							}
							$options[ $aux_dv ]['#labelclass'] = '';
						} else {
							$options[ $aux_dv ] = array(
								'#title' => $aux_dv,
								'#value' => $dv,
								'#inline' => true,
								'#after' => '<br />'
							);
							$options[ $aux_dv ]['#attributes']['class'] = 'js-wpv-filter-trigger';
						}
					}
				}
			} else if ( $default_value !== false ) {
				$aux_display_values = array_keys( $opt_aux, $default_value, true );
				foreach ( $aux_display_values as $aux_dv ) {
					if ( isset( $options[ $aux_dv ] ) ) {
						if ( isset( $options[ $aux_dv ]['#disable'] ) ) {
							unset( $options[ $aux_dv ]['#disable'] );
						}
						$options[ $aux_dv ]['#labelclass'] = '';
					} else {
						$options[ $aux_dv ] = array(
							'#title' => $aux_dv,
							'#value' => $default_value,
							'#inline' => true,
							'#after' => '<br />'
						);
						$options[ $aux_dv ]['#attributes']['class'] = 'js-wpv-filter-trigger';
					}
				}
			}
			
			
			// Render the form content
			$element = wpv_form_control( array(
					'field' => array(
	                        '#type' => 'select',
	                        '#id' => 'wpv_control_select_' . $url_param,
	                        '#name' => $url_param . '[]',
	                        '#attributes' => array( 'style' => $style, 'class' => $class ),
	                        '#inline' => true,
							'#options' => $options,
							'#default_value' => $default_value,
							'#multiple' => $multi ) ) );
	        return $element;
	        
		} else if ( $field_type == 'textfield' ) {
			// Textfield field
			$default_value = '';
			if ( isset( $_GET[ $url_param ] ) ) {
				$default_value = stripslashes( urldecode( sanitize_text_field( $_GET[ $url_param ] ) ) );
			}
			
			// Render the form content
			$element = wpv_form_control( array(
					'field' => array(
	                        '#type' => 'textfield',
	                        '#id' => 'wpv_control_textfield_' . $url_param,
	                        '#name' => $url_param,
	                        '#attributes' => array( 'style' => $style, 'class' => 'js-wpv-filter-trigger-delayed ' . $class  ),
	                        '#inline' => true,
							'#value' => $default_value ) ) );
	        return $element;
	        
		} else if ( $field_type == 'date' || $field_type == 'datepicker' ) {
			// Date or datepicker field
			$out = wpv_render_datepicker( $url_param, $date_format, $default_date );
            return $out;
        }
        // In case we have a field attribute but it does not match any vaid type, return nothing
		return '';
		
	} else {
        // When there is a type attribute without field or auto_fill or values attributes it's likely for a checkbox or a datepicker
        // But I'm not sure what is this used for, because it really does not filter by any field
        $default_value = '';
        if ( isset( $_GET[ $url_param ] ) ) {
            $default_value = $_GET[ $url_param ];
        }
        switch ( $type ) {
            case 'checkbox':
                // In this case, there is no way to implement dependant parametric search, because we have no field to check against
                $element = array(
						'field' => array(
                                '#type' => $type,
                                '#id' => 'wpv_control_' . $type . '_' . $url_param,
                                '#name' => $url_param,
                                '#attributes' => array( 'style' => $style, 'class' => 'js-wpv-filter-trigger ' . $class ),
                                '#inline' => true,
                                '#value' => $default_value ) );
                $element['field']['#title'] = wpv_translate( $url_param . '_title', $title, false, 'View ' . $view_name );
                $element = wpv_form_control( $element );
                break;
            case 'datepicker':
                $element = wpv_render_datepicker( $url_param, $date_format, $default_date );
                break;
            default:
                $element = array(
						'field' => array(
                                '#type' => $type,
                                '#id' => 'wpv_control_' . $type . '_' . $url_param,
                                '#name' => $url_param,
                                '#attributes' => array( 'style' => $style, 'class' => $class ),
                                '#inline' => true,
                                '#value' => $default_value ) );
                $element = wpv_form_control( $element );
                break;
        }
        return $element;
    }
}