/**
  * Constructor - set the MLA Terms.
  *
  * @param string Taxonomy name/slug.
  */
 function __construct($taxonomy)
 {
     $attr = array('taxonomy' => $taxonomy, 'pad_counts' => 'true');
     $terms = MLAShortcodes::mla_get_terms($attr);
     unset($terms['found_rows']);
     foreach ($terms as $term) {
         $this->mla_terms[$term->term_taxonomy_id] = $term->count;
     }
 }
 /**
  * Builds the $mla_galleries or $galleries array
  *
  * @since 0.70
  *
  * @param	string name of the gallery's cache/option variable
  * @param	array by reference to the private static galleries array variable
  * @param	string the shortcode to be searched for and processed
  * @param	boolean true to exclude revisions from the search
  *
  * @return	boolean true if the galleries array is not empty
  */
 private static function _build_mla_galleries($option_name, &$galleries_array, $shortcode, $exclude_revisions)
 {
     global $wpdb, $post;
     if (is_array($galleries_array)) {
         if (!empty($galleries_array)) {
             return true;
         } else {
             return false;
         }
     }
     $option_value = MLAOptions::mla_get_option($option_name);
     if ('disabled' == $option_value) {
         return false;
     } elseif ('cached' == $option_value) {
         $galleries_array = get_transient(MLA_OPTION_PREFIX . 't_' . $option_name);
         if (is_array($galleries_array)) {
             if (!empty($galleries_array)) {
                 return true;
             } else {
                 return false;
             }
         } else {
             $galleries_array = NULL;
         }
     }
     // cached
     /*
      * $galleries_array is null, so build the array
      */
     $galleries_array = array();
     if ($exclude_revisions) {
         $exclude_revisions = "(post_type <> 'revision') AND ";
     } else {
         $exclude_revisions = '';
     }
     $like = like_escape($shortcode);
     $results = $wpdb->get_results($wpdb->prepare("\r\n\t\t\t\tSELECT ID, post_type, post_title, post_content\r\n\t\t\t\tFROM {$wpdb->posts}\r\n\t\t\t\tWHERE {$exclude_revisions}(\r\n\t\t\t\t\tCONVERT(`post_content` USING utf8 )\r\n\t\t\t\t\tLIKE %s)\r\n\t\t\t\t", "%{$like}%"));
     if (empty($results)) {
         return false;
     }
     foreach ($results as $result) {
         $count = preg_match_all("/\\{$shortcode}([^\\]]*)\\]/", $result->post_content, $matches, PREG_PATTERN_ORDER);
         if ($count) {
             $result_id = $result->ID;
             $galleries_array[$result_id]['parent_title'] = $result->post_title;
             $galleries_array[$result_id]['parent_type'] = $result->post_type;
             $galleries_array[$result_id]['results'] = array();
             $galleries_array[$result_id]['galleries'] = array();
             $instance = 0;
             foreach ($matches[1] as $index => $match) {
                 /*
                  * Filter out shortcodes that are not an exact match
                  */
                 if (empty($match) || ' ' == substr($match, 0, 1)) {
                     $instance++;
                     $galleries_array[$result_id]['galleries'][$instance]['query'] = trim($matches[1][$index]);
                     $galleries_array[$result_id]['galleries'][$instance]['results'] = array();
                     $post = $result;
                     // set global variable for mla_gallery_shortcode
                     $attachments = MLAShortcodes::mla_get_shortcode_attachments($result_id, $galleries_array[$result_id]['galleries'][$instance]['query']);
                     if (is_string($attachments)) {
                         trigger_error(htmlentities(sprintf('(%1$s) %2$s (ID %3$d) query "%4$s" failed, returning "%5$s"', $result->post_type, $result->post_title, $result->ID, $galleries_array[$result_id]['galleries'][$instance]['query'], $attachments)), E_USER_WARNING);
                     } elseif (!empty($attachments)) {
                         foreach ($attachments as $attachment) {
                             $galleries_array[$result_id]['results'][$attachment->ID] = $attachment->ID;
                             $galleries_array[$result_id]['galleries'][$instance]['results'][] = $attachment->ID;
                         }
                     }
                     // foreach $attachment
                 }
                 // exact match
             }
             // foreach $match
         }
         // if $count
     }
     // foreach $result
     /*
      * Maybe cache the results
      */
     if ('cached' == $option_value) {
         set_transient(MLA_OPTION_PREFIX . 't_' . $option_name, $galleries_array, 900);
         // fifteen minutes
     }
     return true;
 }
 /**
  * WordPress Filter for edit taxonomy "Attachments" column,
  * which returns a count of the attachments assigned a given term
  *
  * @since 0.30
  *
  * @param	string	current column value; always ''
  * @param	array	name of the column
  * @param	array	ID of the term for which the count is desired
  *
  * @return	array	HTML markup for the column content; number of attachments in the category
  *					and alink to retrieve a list of them
  */
 public static function mla_taxonomy_column_filter($place_holder, $column_name, $term_id)
 {
     static $taxonomy = NULL, $tax_object = NULL, $count_terms = false, $terms = array();
     /*
      * Do these setup tasks once per page load
      */
     if (NULL == $taxonomy) {
         /*
          * Adding or inline-editing a tag is done with AJAX, and there's no current screen object
          */
         if (defined('DOING_AJAX') && DOING_AJAX) {
             $taxonomy = !empty($_POST['taxonomy']) ? $_POST['taxonomy'] : 'post_tag';
         } else {
             $screen = get_current_screen();
             $taxonomy = !empty($screen->taxonomy) ? $screen->taxonomy : 'post_tag';
         }
         $tax_object = get_taxonomy($taxonomy);
         $count_terms = 'checked' == MLAOptions::mla_get_option(MLAOptions::MLA_COUNT_TERM_ATTACHMENTS);
         if ($count_terms) {
             $terms = get_transient(MLA_OPTION_PREFIX . 't_term_counts_' . $taxonomy);
             if (!is_array($terms)) {
                 $cloud = MLAShortcodes::mla_get_terms(array('taxonomy' => $taxonomy, 'fields' => 't.term_id, t.name, t.slug, COUNT(p.ID) AS `count`', 'number' => 0, 'no_orderby' => true));
                 unset($cloud['found_rows']);
                 foreach ($cloud as $term) {
                     $terms[$term->term_id] = $term;
                 }
                 set_transient(MLA_OPTION_PREFIX . 't_term_counts_' . $taxonomy, $terms, 300);
                 // five minutes
             }
             // build the array
         }
         // set $terms
     }
     // setup tasks
     if (isset($terms[$term_id])) {
         $term = $terms[$term_id];
         $column_text = number_format_i18n($term->count);
     } else {
         $term = get_term($term_id, $taxonomy);
         if (is_wp_error($term)) {
             /* translators: 1: ERROR tag 2: taxonomy 3: error message */
             error_log(sprintf(_x('%1$s: mla_taxonomy_column_filter( "%2$s" ) - get_term failed: "%3$s"', 'error_log', 'media-library-assistant'), __('ERROR', 'media-library-assistant'), $taxonomy, $term->get_error_message()), 0);
             return 0;
         } elseif ($count_terms) {
             $column_text = number_format_i18n(0);
         } else {
             $column_text = __('click to search', 'media-library-assistant');
         }
     }
     return sprintf('<a href="%1$s">%2$s</a>', esc_url(add_query_arg(array('page' => MLA::ADMIN_PAGE_SLUG, 'mla-tax' => $taxonomy, 'mla-term' => $term->slug, 'heading_suffix' => urlencode($tax_object->label . ':' . $term->name)), 'upload.php')), $column_text);
 }
 /**
  * Parses shortcode parameters and returns the gallery objects
  *
  * @since .50
  *
  * @param int Post ID of the parent
  * @param array Attributes of the shortcode
  * @param boolean true to calculate and return ['found_posts'] as an array element
  *
  * @return array List of attachments returned from WP_Query
  */
 public static function mla_get_shortcode_attachments($post_parent, $attr, $return_found_rows = NULL)
 {
     global $wp_query;
     /*
      * Parameters passed to the where and orderby filter functions
      */
     self::$query_parameters = array();
     /*
      * Parameters passed to the posts_search filter function in MLAData
      */
     MLAData::$search_parameters = array('debug' => 'none');
     /*
      * Make sure $attr is an array, even if it's empty
      */
     if (empty($attr)) {
         $attr = array();
     } elseif (is_string($attr)) {
         $attr = shortcode_parse_atts($attr);
     }
     /*
      * The "where used" queries have no $_REQUEST context available to them,
      * so tax_, date_ and meta_query evaluation will fail if they contain "{+request:"
      * parameters. Ignore these errors.
      */
     if (isset($attr['where_used_query']) && 'this-is-a-where-used-query' == $attr['where_used_query']) {
         $where_used_query = true;
         unset($attr['where_used_query']);
     } else {
         $where_used_query = false;
     }
     /*
      * Merge input arguments with defaults, then extract the query arguments.
      *
      * $return_found_rows is used to indicate that the call comes from gallery_shortcode(),
      * which is the only call that supplies it.
      */
     if (!is_null($return_found_rows)) {
         $attr = apply_filters('mla_gallery_query_attributes', $attr);
     }
     $arguments = shortcode_atts(self::$mla_get_shortcode_attachments_parameters, $attr);
     $mla_page_parameter = $arguments['mla_page_parameter'];
     unset($arguments['mla_page_parameter']);
     /*
      * $mla_page_parameter, if set, doesn't make it through the shortcode_atts filter,
      * so we handle it separately
      */
     if (!isset($arguments[$mla_page_parameter])) {
         if (isset($attr[$mla_page_parameter])) {
             $arguments[$mla_page_parameter] = $attr[$mla_page_parameter];
         } else {
             $arguments[$mla_page_parameter] = NULL;
         }
     }
     /*
     		 * 'RAND' is not documented in the codex, but is present in the code.
     		 * CODE REMOVED in WordPress 4.1
     		 * /
     		if ( 'RAND' == strtoupper( $arguments['order'] ) ) {
     			$arguments['orderby'] = 'none';
     			unset( $arguments['order'] );
     		} // */
     if (!empty($arguments['ids'])) {
         // 'ids' is explicitly ordered, unless you specify otherwise.
         if (empty($attr['orderby'])) {
             $arguments['orderby'] = 'post__in';
         }
         $arguments['include'] = $arguments['ids'];
     }
     unset($arguments['ids']);
     if (!is_null($return_found_rows)) {
         $arguments = apply_filters('mla_gallery_query_arguments', $arguments);
     }
     /*
      * Extract taxonomy arguments
      */
     $query_arguments = array();
     if (!empty($attr)) {
         $all_taxonomies = get_taxonomies(array('show_ui' => true), 'names');
         $simple_tax_queries = array();
         foreach ($attr as $key => $value) {
             if ('tax_query' == $key) {
                 if (is_array($value)) {
                     $query_arguments[$key] = $value;
                 } else {
                     $tax_query = NULL;
                     $value = self::_sanitize_query_specification($value);
                     /*
                      * Replace invalid queries from "where-used" callers with a harmless equivalent
                      */
                     if ($where_used_query && false !== strpos($value, '{+')) {
                         $value = "array( array( 'taxonomy' => 'none', 'field' => 'slug', 'terms' => 'none' ) )";
                     }
                     $function = @create_function('', 'return ' . $value . ';');
                     if (is_callable($function)) {
                         $tax_query = $function();
                     }
                     if (is_array($tax_query)) {
                         $query_arguments[$key] = $tax_query;
                         break;
                         // Done - the tax_query overrides all other taxonomy parameters
                     } else {
                         return '<p>' . __('ERROR', 'media-library-assistant') . ': ' . __('Invalid mla_gallery', 'media-library-assistant') . ' tax_query = ' . var_export($value, true) . '</p>';
                     }
                 }
                 // not array
             } elseif (array_key_exists($key, $all_taxonomies)) {
                 $simple_tax_queries[$key] = implode(',', array_filter(array_map('trim', explode(',', $value))));
             }
             // array_key_exists
         }
         //foreach $attr
         /*
          * One of five outcomes:
          * 1) An explicit tax_query was found; use it and ignore all other taxonomy parameters
          * 2) No tax query is present; no further processing required
          * 3) Two or more simple tax queries are present; compose a tax_query
          * 4) One simple tax query and (tax_operator or tax_include_children) are present; compose a tax_query
          * 5) One simple tax query is present; use it as-is or convert 'category' to 'category_name'
          */
         if (isset($query_arguments['tax_query']) || empty($simple_tax_queries)) {
             // No further action required
         } elseif (1 < count($simple_tax_queries) || isset($attr['tax_operator']) || isset($attr['tax_include_children'])) {
             // Build a tax_query
             if (1 < count($simple_tax_queries)) {
                 $tax_relation = 'AND';
                 if (isset($attr['tax_relation'])) {
                     if ('OR' == strtoupper($attr['tax_relation'])) {
                         $tax_relation = 'OR';
                     }
                 }
                 $tax_query = array('relation' => $tax_relation);
             } else {
                 $tax_query = array();
             }
             // Validate other tax_query parameters or set defaults
             $tax_operator = 'IN';
             if (isset($attr['tax_operator'])) {
                 $attr_value = strtoupper($attr['tax_operator']);
                 if (in_array($attr_value, array('IN', 'NOT IN', 'AND'))) {
                     $tax_operator = $attr_value;
                 }
             }
             $tax_include_children = true;
             if (isset($attr['tax_include_children'])) {
                 if ('FALSE' == strtoupper($attr['tax_include_children'])) {
                     $tax_include_children = false;
                 }
             }
             foreach ($simple_tax_queries as $key => $value) {
                 $tax_query[] = array('taxonomy' => $key, 'field' => 'slug', 'terms' => explode(',', $value), 'operator' => $tax_operator, 'include_children' => $tax_include_children);
             }
             $query_arguments['tax_query'] = $tax_query;
         } else {
             // exactly one simple query is present
             if (isset($simple_tax_queries['category'])) {
                 $arguments['category_name'] = $simple_tax_queries['category'];
             } else {
                 $query_arguments = $simple_tax_queries;
             }
         }
     }
     // ! empty
     /*
      * $query_arguments has been initialized in the taxonomy code above.
      */
     $is_tax_query = !($use_children = empty($query_arguments));
     foreach ($arguments as $key => $value) {
         /*
          * There are several "fallthru" cases in this switch statement that decide 
          * whether or not to limit the query to children of a specific post.
          */
         $children_ok = true;
         switch ($key) {
             case 'post_parent':
                 switch (strtolower($value)) {
                     case 'all':
                         $value = NULL;
                         $use_children = false;
                         break;
                     case 'any':
                         self::$query_parameters['post_parent'] = 'any';
                         $value = NULL;
                         $use_children = false;
                         break;
                     case 'current':
                         $value = $post_parent;
                         $use_children = true;
                         break;
                     case 'none':
                         self::$query_parameters['post_parent'] = 'none';
                         $value = NULL;
                         $use_children = false;
                         break;
                 }
                 // fallthru
             // fallthru
             case 'id':
                 if (is_numeric($value)) {
                     $query_arguments[$key] = intval($value);
                     if (!$children_ok) {
                         $use_children = false;
                     }
                 }
                 unset($arguments[$key]);
                 break;
             case 'numberposts':
             case 'posts_per_page':
             case 'posts_per_archive_page':
                 if (is_numeric($value)) {
                     $value = intval($value);
                     if (!empty($value)) {
                         $query_arguments[$key] = $value;
                     }
                 }
                 unset($arguments[$key]);
                 break;
             case 'meta_value_num':
                 $children_ok = false;
                 // fallthru
             // fallthru
             case 'offset':
                 if (is_numeric($value)) {
                     $query_arguments[$key] = intval($value);
                     if (!$children_ok) {
                         $use_children = false;
                     }
                 }
                 unset($arguments[$key]);
                 break;
             case 'paged':
                 if ('current' == strtolower($value)) {
                     /*
                      * Note: The query variable 'page' holds the pagenumber for a single paginated
                      * Post or Page that includes the <!--nextpage--> Quicktag in the post content. 
                      */
                     if (get_query_var('page')) {
                         $query_arguments[$key] = get_query_var('page');
                     } else {
                         $query_arguments[$key] = get_query_var('paged') ? get_query_var('paged') : 1;
                     }
                 } elseif (is_numeric($value)) {
                     $query_arguments[$key] = intval($value);
                 } elseif ('' === $value) {
                     $query_arguments[$key] = 1;
                 }
                 unset($arguments[$key]);
                 break;
             case $mla_page_parameter:
             case 'mla_paginate_total':
                 if (is_numeric($value)) {
                     $query_arguments[$key] = intval($value);
                 } elseif ('' === $value) {
                     $query_arguments[$key] = 1;
                 }
                 unset($arguments[$key]);
                 break;
             case 'author':
             case 'cat':
             case 'tag_id':
                 if (!empty($value)) {
                     if (is_array($value)) {
                         $query_arguments[$key] = array_filter($value);
                     } else {
                         $query_arguments[$key] = array_filter(array_map('intval', explode(",", $value)));
                     }
                     if (1 == count($query_arguments[$key])) {
                         $query_arguments[$key] = $query_arguments[$key][0];
                     } else {
                         $query_arguments[$key] = implode(',', $query_arguments[$key]);
                     }
                     $use_children = false;
                 }
                 unset($arguments[$key]);
                 break;
             case 'category__and':
             case 'category__in':
             case 'category__not_in':
             case 'tag__and':
             case 'tag__in':
             case 'tag__not_in':
             case 'include':
                 $children_ok = false;
                 // fallthru
             // fallthru
             case 'exclude':
                 if (!empty($value)) {
                     if (is_array($value)) {
                         $value = array_filter($value);
                     } else {
                         $value = array_filter(array_map('intval', explode(",", $value)));
                     }
                     if (!empty($value)) {
                         $query_arguments[$key] = $value;
                         if (!$children_ok) {
                             $use_children = false;
                         }
                     }
                 }
                 unset($arguments[$key]);
                 break;
             case 'tag_slug__and':
             case 'tag_slug__in':
                 if (!empty($value)) {
                     if (is_array($value)) {
                         $query_arguments[$key] = $value;
                     } else {
                         $query_arguments[$key] = array_filter(array_map('trim', explode(",", $value)));
                     }
                     $use_children = false;
                 }
                 unset($arguments[$key]);
                 break;
             case 'nopaging':
                 // boolean value, default false
                 if (!empty($value) && 'false' != strtolower($value)) {
                     $query_arguments[$key] = true;
                 }
                 unset($arguments[$key]);
                 break;
                 // boolean values, default true
             // boolean values, default true
             case 'cache_results':
             case 'update_post_meta_cache':
             case 'update_post_term_cache':
                 if (!empty($value) && 'true' != strtolower($value)) {
                     $query_arguments[$key] = false;
                 }
                 unset($arguments[$key]);
                 break;
             case 'sentence':
             case 'exact':
                 if (!empty($value) && 'true' == strtolower($value)) {
                     MLAData::$search_parameters[$key] = true;
                 } else {
                     MLAData::$search_parameters[$key] = false;
                 }
                 unset($arguments[$key]);
                 break;
             case 'mla_search_connector':
             case 'mla_phrase_connector':
             case 'mla_term_connector':
                 if (!empty($value) && 'OR' == strtoupper($value)) {
                     MLAData::$search_parameters[$key] = 'OR';
                 } else {
                     MLAData::$search_parameters[$key] = 'AND';
                 }
                 unset($arguments[$key]);
                 break;
             case 'mla_terms_phrases':
                 $children_ok = false;
                 // fallthru
             // fallthru
             case 'mla_terms_taxonomies':
             case 'mla_search_fields':
                 if (!empty($value)) {
                     MLAData::$search_parameters[$key] = $value;
                     if (!$children_ok) {
                         $use_children = false;
                     }
                 }
                 unset($arguments[$key]);
                 break;
             case 's':
                 MLAData::$search_parameters['s'] = $value;
                 // fallthru
             // fallthru
             case 'author_name':
             case 'category_name':
             case 'tag':
             case 'meta_key':
             case 'meta_value':
             case 'meta_compare':
                 $children_ok = false;
                 // fallthru
             // fallthru
             case 'post_type':
             case 'post_status':
             case 'post_mime_type':
             case 'orderby':
                 if (!empty($value)) {
                     $query_arguments[$key] = $value;
                     if (!$children_ok) {
                         $use_children = false;
                     }
                 }
                 unset($arguments[$key]);
                 break;
             case 'order':
                 if (!empty($value)) {
                     $value = strtoupper($value);
                     if (in_array($value, array('ASC', 'DESC'))) {
                         $query_arguments[$key] = $value;
                     }
                 }
                 unset($arguments[$key]);
                 break;
             case 'date_query':
                 if (!empty($value)) {
                     if (is_array($value)) {
                         $query_arguments[$key] = $value;
                     } else {
                         $date_query = NULL;
                         $value = self::_sanitize_query_specification($value);
                         /*
                          * Replace invalid queries from "where-used" callers with a harmless equivalent
                          */
                         if ($where_used_query && false !== strpos($value, '{+')) {
                             $value = "array( array( 'key' => 'unlikely', 'value' => 'none or otherwise unlikely' ) )";
                         }
                         $function = @create_function('', 'return ' . $value . ';');
                         if (is_callable($function)) {
                             $date_query = $function();
                         }
                         if (is_array($date_query)) {
                             $query_arguments[$key] = $date_query;
                         } else {
                             return '<p>' . __('ERROR', 'media-library-assistant') . ': ' . __('Invalid mla_gallery', 'media-library-assistant') . ' date_query = ' . var_export($value, true) . '</p>';
                         }
                     }
                     // not array
                     $use_children = false;
                 }
                 unset($arguments[$key]);
                 break;
             case 'meta_query':
                 if (!empty($value)) {
                     if (is_array($value)) {
                         $query_arguments[$key] = $value;
                     } else {
                         $meta_query = NULL;
                         $value = self::_sanitize_query_specification($value);
                         /*
                          * Replace invalid queries from "where-used" callers with a harmless equivalent
                          */
                         if ($where_used_query && false !== strpos($value, '{+')) {
                             $value = "array( array( 'key' => 'unlikely', 'value' => 'none or otherwise unlikely' ) )";
                         }
                         $function = @create_function('', 'return ' . $value . ';');
                         if (is_callable($function)) {
                             $meta_query = $function();
                         }
                         if (is_array($meta_query)) {
                             $query_arguments[$key] = $meta_query;
                         } else {
                             return '<p>' . __('ERROR', 'media-library-assistant') . ': ' . __('Invalid mla_gallery', 'media-library-assistant') . ' meta_query = ' . var_export($value, true) . '</p>';
                         }
                     }
                     // not array
                     $use_children = false;
                 }
                 unset($arguments[$key]);
                 break;
             case 'fields':
                 if (!empty($value)) {
                     $value = strtolower($value);
                     if (in_array($value, array('ids', 'id=>parent'))) {
                         $query_arguments[$key] = $value;
                     }
                 }
                 unset($arguments[$key]);
                 break;
             default:
                 // ignore anything else
         }
         // switch $key
     }
     // foreach $arguments
     /*
      * Decide whether to use a "get_children" style query
      */
     self::$query_parameters['disable_tax_join'] = $is_tax_query && !$use_children;
     if ($use_children && !isset($query_arguments['post_parent'])) {
         if (!isset($query_arguments['id'])) {
             $query_arguments['post_parent'] = $post_parent;
         } else {
             $query_arguments['post_parent'] = $query_arguments['id'];
         }
         unset($query_arguments['id']);
     }
     if (isset($query_arguments['numberposts']) && !isset($query_arguments['posts_per_page'])) {
         $query_arguments['posts_per_page'] = $query_arguments['numberposts'];
     }
     unset($query_arguments['numberposts']);
     /*
      * MLA pagination will override WordPress pagination
      */
     if (isset($query_arguments[$mla_page_parameter])) {
         unset($query_arguments['nopaging']);
         unset($query_arguments['offset']);
         unset($query_arguments['paged']);
         if (isset($query_arguments['mla_paginate_total']) && $query_arguments[$mla_page_parameter] > $query_arguments['mla_paginate_total']) {
             $query_arguments['offset'] = 0x7fffffff;
             // suppress further output
         } else {
             $query_arguments['paged'] = $query_arguments[$mla_page_parameter];
         }
     } else {
         if (isset($query_arguments['posts_per_page']) || isset($query_arguments['posts_per_archive_page']) || isset($query_arguments['paged']) || isset($query_arguments['offset'])) {
             unset($query_arguments['nopaging']);
         }
     }
     unset($query_arguments[$mla_page_parameter]);
     unset($query_arguments['mla_paginate_total']);
     if (isset($query_arguments['post_mime_type']) && 'all' == strtolower($query_arguments['post_mime_type'])) {
         unset($query_arguments['post_mime_type']);
     }
     if (!empty($query_arguments['include'])) {
         $incposts = wp_parse_id_list($query_arguments['include']);
         $query_arguments['posts_per_page'] = count($incposts);
         // only the number of posts included
         $query_arguments['post__in'] = $incposts;
         unset($query_arguments['include']);
     } elseif (!empty($query_arguments['exclude'])) {
         $query_arguments['post__not_in'] = wp_parse_id_list($query_arguments['exclude']);
         unset($query_arguments['exclude']);
     }
     $query_arguments['ignore_sticky_posts'] = true;
     $query_arguments['no_found_rows'] = is_null($return_found_rows) ? true : !$return_found_rows;
     /*
      * We will always handle "orderby" in our filter
      */
     self::$query_parameters['orderby'] = self::_validate_sql_orderby($query_arguments);
     if (false === self::$query_parameters['orderby']) {
         unset(self::$query_parameters['orderby']);
     }
     unset($query_arguments['orderby']);
     unset($query_arguments['order']);
     if (self::$mla_debug) {
         add_filter('posts_clauses', 'MLAShortcodes::mla_shortcode_query_posts_clauses_filter', 0x7fffffff, 1);
         add_filter('posts_clauses_request', 'MLAShortcodes::mla_shortcode_query_posts_clauses_request_filter', 0x7fffffff, 1);
     }
     add_filter('posts_join', 'MLAShortcodes::mla_shortcode_query_posts_join_filter', 0x7fffffff, 1);
     add_filter('posts_where', 'MLAShortcodes::mla_shortcode_query_posts_where_filter', 0x7fffffff, 1);
     add_filter('posts_orderby', 'MLAShortcodes::mla_shortcode_query_posts_orderby_filter', 0x7fffffff, 1);
     /*
      * Handle the keyword and terms search in the posts_search filter.
      * One or both of 'mla_terms_phrases' and 's' must be present to
      * trigger the search.
      */
     if (empty(MLAData::$search_parameters['mla_terms_phrases']) && empty(MLAData::$search_parameters['s'])) {
         MLAData::$search_parameters = array('debug' => 'none');
     } else {
         /*
          * Convert Terms Search parameters to the filter's requirements.
          * mla_terms_taxonomies is shared with keyword search.
          */
         if (empty(MLAData::$search_parameters['mla_terms_taxonomies'])) {
             MLAData::$search_parameters['mla_terms_search']['taxonomies'] = MLAOptions::mla_supported_taxonomies('term-search');
         } else {
             MLAData::$search_parameters['mla_terms_search']['taxonomies'] = array_filter(array_map('trim', explode(',', MLAData::$search_parameters['mla_terms_taxonomies'])));
         }
         if (!empty(MLAData::$search_parameters['mla_terms_phrases'])) {
             MLAData::$search_parameters['mla_terms_search']['phrases'] = MLAData::$search_parameters['mla_terms_phrases'];
             if (empty(MLAData::$search_parameters['mla_phrase_connector'])) {
                 MLAData::$search_parameters['mla_terms_search']['radio_phrases'] = 'AND';
             } else {
                 MLAData::$search_parameters['mla_terms_search']['radio_phrases'] = MLAData::$search_parameters['mla_phrase_connector'];
             }
             if (empty(MLAData::$search_parameters['mla_term_connector'])) {
                 MLAData::$search_parameters['mla_terms_search']['radio_terms'] = 'OR';
             } else {
                 MLAData::$search_parameters['mla_terms_search']['radio_terms'] = MLAData::$search_parameters['mla_phrase_connector'];
             }
         }
         unset(MLAData::$search_parameters['mla_terms_phrases']);
         unset(MLAData::$search_parameters['mla_terms_taxonomies']);
         unset(MLAData::$search_parameters['mla_phrase_connector']);
         unset(MLAData::$search_parameters['mla_term_connector']);
         if (empty(MLAData::$search_parameters['mla_search_fields'])) {
             MLAData::$search_parameters['mla_search_fields'] = array('title', 'content');
         } else {
             MLAData::$search_parameters['mla_search_fields'] = array_filter(array_map('trim', explode(',', MLAData::$search_parameters['mla_search_fields'])));
             MLAData::$search_parameters['mla_search_fields'] = array_intersect(array('title', 'content', 'excerpt', 'name', 'terms'), MLAData::$search_parameters['mla_search_fields']);
             /*
              * Look for keyword search including 'terms' 
              */
             foreach (MLAData::$search_parameters['mla_search_fields'] as $index => $field) {
                 if ('terms' == $field) {
                     if (isset(MLAData::$search_parameters['mla_terms_search']['phrases'])) {
                         /*
                          * The Terms Search overrides any terms-based keyword search for now; too complicated.
                          */
                         unset(MLAData::$search_parameters['mla_search_fields'][$index]);
                     } else {
                         MLAData::$search_parameters['mla_search_taxonomies'] = MLAData::$search_parameters['mla_terms_search']['taxonomies'];
                         unset(MLAData::$search_parameters['mla_terms_search']['taxonomies']);
                     }
                 }
                 // terms in search fields
             }
         }
         // mla_search_fields present
         if (empty(MLAData::$search_parameters['mla_search_connector'])) {
             MLAData::$search_parameters['mla_search_connector'] = 'AND';
         }
         if (empty(MLAData::$search_parameters['sentence'])) {
             MLAData::$search_parameters['sentence'] = false;
         }
         if (empty(MLAData::$search_parameters['exact'])) {
             MLAData::$search_parameters['exact'] = false;
         }
         MLAData::$search_parameters['debug'] = self::$mla_debug ? 'shortcode' : 'none';
         add_filter('posts_search', 'MLAData::mla_query_posts_search_filter', 10, 2);
         add_filter('posts_groupby', 'MLAData::mla_query_posts_groupby_filter');
     }
     if (self::$mla_debug) {
         global $wp_filter;
         foreach ($wp_filter['posts_where'] as $priority => $filters) {
             $debug_message = '<strong>mla_debug $wp_filter[posts_where]</strong> priority = ' . var_export($priority, true) . '<br />';
             foreach ($filters as $name => $descriptor) {
                 $debug_message .= 'filter name = ' . var_export($name, true) . '<br />';
             }
             MLA::mla_debug_add($debug_message);
         }
         foreach ($wp_filter['posts_orderby'] as $priority => $filters) {
             $debug_message = '<strong>mla_debug $wp_filter[posts_orderby]</strong> priority = ' . var_export($priority, true) . '<br />';
             foreach ($filters as $name => $descriptor) {
                 $debug_message .= 'filter name = ' . var_export($name, true) . '<br />';
             }
             MLA::mla_debug_add($debug_message);
         }
     }
     /*
      * Disable Relevanssi - A Better Search, v3.2 by Mikko Saari 
      * relevanssi_prevent_default_request( $request, $query )
      * apply_filters('relevanssi_admin_search_ok', $admin_search_ok, $query );
      */
     if (function_exists('relevanssi_prevent_default_request')) {
         add_filter('relevanssi_admin_search_ok', 'MLAData::mla_query_relevanssi_admin_search_ok_filter');
     }
     self::$mla_gallery_wp_query_object = new WP_Query();
     $attachments = self::$mla_gallery_wp_query_object->query($query_arguments);
     /*
      * $return_found_rows is used to indicate that the call comes from gallery_shortcode(),
      * which is the only call that supplies it.
      */
     if (is_null($return_found_rows)) {
         $return_found_rows = false;
     } else {
         do_action('mla_gallery_wp_query_object', $query_arguments);
     }
     if ($return_found_rows) {
         $attachments['found_rows'] = self::$mla_gallery_wp_query_object->found_posts;
     }
     if (!empty(MLAData::$search_parameters)) {
         remove_filter('posts_search', 'MLAData::mla_query_posts_search_filter');
     }
     if (function_exists('relevanssi_prevent_default_request')) {
         remove_filter('relevanssi_admin_search_ok', 'MLAData::mla_query_relevanssi_admin_search_ok_filter');
     }
     remove_filter('posts_join', 'MLAShortcodes::mla_shortcode_query_posts_join_filter', 0x7fffffff);
     remove_filter('posts_where', 'MLAShortcodes::mla_shortcode_query_posts_where_filter', 0x7fffffff);
     remove_filter('posts_orderby', 'MLAShortcodes::mla_shortcode_query_posts_orderby_filter', 0x7fffffff);
     if (self::$mla_debug) {
         remove_filter('posts_clauses', 'MLAShortcodes::mla_shortcode_query_posts_clauses_filter', 0x7fffffff);
         remove_filter('posts_clauses_request', 'MLAShortcodes::mla_shortcode_query_posts_clauses_request_filter', 0x7fffffff);
         MLA::mla_debug_add('<strong>' . __('mla_debug query', 'media-library-assistant') . '</strong> = ' . var_export($query_arguments, true));
         MLA::mla_debug_add('<strong>' . __('mla_debug request', 'media-library-assistant') . '</strong> = ' . var_export(self::$mla_gallery_wp_query_object->request, true));
         MLA::mla_debug_add('<strong>' . __('mla_debug query_vars', 'media-library-assistant') . '</strong> = ' . var_export(self::$mla_gallery_wp_query_object->query_vars, true));
         MLA::mla_debug_add('<strong>' . __('mla_debug post_count', 'media-library-assistant') . '</strong> = ' . var_export(self::$mla_gallery_wp_query_object->post_count, true));
     }
     self::$mla_gallery_wp_query_object = NULL;
     return $attachments;
 }
 /**
  * Builds the $mla_galleries or $galleries array
  *
  * @since 0.70
  *
  * @param	string name of the gallery's cache/option variable
  * @param	array by reference to the private static galleries array variable
  * @param	string the shortcode to be searched for and processed
  * @param	boolean true to exclude revisions from the search
  *
  * @return	boolean true if the galleries array is not empty
  */
 private static function _build_mla_galleries($option_name, &$galleries_array, $shortcode, $exclude_revisions)
 {
     global $wpdb, $post;
     if (is_array($galleries_array)) {
         if (!empty($galleries_array)) {
             return true;
         } else {
             return false;
         }
     }
     $option_value = MLACore::mla_get_option($option_name);
     if ('disabled' == $option_value) {
         return false;
     } elseif ('cached' == $option_value) {
         $galleries_array = get_transient(MLA_OPTION_PREFIX . 't_' . $option_name);
         if (is_array($galleries_array)) {
             if (!empty($galleries_array)) {
                 return true;
             } else {
                 return false;
             }
         } else {
             $galleries_array = NULL;
         }
     }
     // cached
     /* 
      * The MLAShortcodes class is only loaded when needed.
      */
     if (!class_exists('MLAShortcodes')) {
         require_once MLA_PLUGIN_PATH . 'includes/class-mla-shortcodes.php';
     }
     /*
      * $galleries_array is null, so build the array
      */
     $galleries_array = array();
     if ($exclude_revisions) {
         $exclude_revisions = "(post_type <> 'revision') AND ";
     } else {
         $exclude_revisions = '';
     }
     if (MLAQuery::$wp_4dot0_plus) {
         $like = $wpdb->esc_like($shortcode);
     } else {
         $like = like_escape($shortcode);
     }
     $results = $wpdb->get_results($wpdb->prepare("\r\n\t\t\t\tSELECT ID, post_type, post_status, post_title, post_content\r\n\t\t\t\tFROM {$wpdb->posts}\r\n\t\t\t\tWHERE {$exclude_revisions}(\r\n\t\t\t\t\tCONVERT(`post_content` USING utf8 )\r\n\t\t\t\t\tLIKE %s)\r\n\t\t\t\t", "%{$like}%"));
     if (empty($results)) {
         return false;
     }
     foreach ($results as $result) {
         $count = preg_match_all("/\\{$shortcode}([^\\]]*)\\]/", $result->post_content, $matches, PREG_PATTERN_ORDER);
         if ($count) {
             $result_id = $result->ID;
             $galleries_array[$result_id]['parent_title'] = $result->post_title;
             $galleries_array[$result_id]['parent_type'] = $result->post_type;
             $galleries_array[$result_id]['parent_status'] = $result->post_status;
             $galleries_array[$result_id]['results'] = array();
             $galleries_array[$result_id]['galleries'] = array();
             $instance = 0;
             foreach ($matches[1] as $index => $match) {
                 /*
                  * Filter out shortcodes that are not an exact match
                  */
                 if (empty($match) || ' ' == substr($match, 0, 1)) {
                     $instance++;
                     /*
                      * Remove trailing "/" from XHTML-style self-closing shortcodes
                      */
                     $galleries_array[$result_id]['galleries'][$instance]['query'] = trim(rtrim($matches[1][$index], '/'));
                     $galleries_array[$result_id]['galleries'][$instance]['results'] = array();
                     $post = $result;
                     // set global variable for mla_gallery_shortcode
                     $attachments = MLAShortcodes::mla_get_shortcode_attachments($result_id, $galleries_array[$result_id]['galleries'][$instance]['query'] . ' cache_results=false update_post_meta_cache=false update_post_term_cache=false where_used_query=this-is-a-where-used-query');
                     if (is_string($attachments)) {
                         /* translators: 1: post_type, 2: post_title, 3: post ID, 4: query string, 5: error message */
                         trigger_error(htmlentities(sprintf(__('(%1$s) %2$s (ID %3$d) query "%4$s" failed, returning "%5$s"', 'media-library-assistant'), $result->post_type, $result->post_title, $result->ID, $galleries_array[$result_id]['galleries'][$instance]['query'], $attachments)), E_USER_WARNING);
                     } elseif (!empty($attachments)) {
                         foreach ($attachments as $attachment) {
                             $galleries_array[$result_id]['results'][$attachment->ID] = $attachment->ID;
                             $galleries_array[$result_id]['galleries'][$instance]['results'][] = $attachment->ID;
                         }
                     }
                 }
                 // exact match
             }
             // foreach $match
         }
         // if $count
     }
     // foreach $result
     /*
      * Maybe cache the results
      */
     if ('cached' == $option_value) {
         set_transient(MLA_OPTION_PREFIX . 't_' . $option_name, $galleries_array, 900);
         // fifteen minutes
     }
     return true;
 }
 /**
  * Parses shortcode parameters and returns the gallery objects
  *
  * @since .50
  *
  * @param int Post ID of the parent
  * @param array Attributes of the shortcode
  * @param boolean true to calculate and return ['found_posts'] as an array element
  *
  * @return array List of attachments returned from WP_Query
  */
 public static function mla_get_shortcode_attachments($post_parent, $attr, $return_found_rows = NULL)
 {
     global $wp_query;
     /*
      * Parameters passed to the where and orderby filter functions
      */
     self::$query_parameters = array();
     /*
      * Make sure $attr is an array, even if it's empty
      */
     if (empty($attr)) {
         $attr = array();
     } elseif (is_string($attr)) {
         $attr = shortcode_parse_atts($attr);
     }
     /*
      * Merge input arguments with defaults, then extract the query arguments.
      *
      * $return_found_rows is used to indicate that the call comes from gallery_shortcode(),
      * which is the only call that supplies it.
      */
     if (!is_null($return_found_rows)) {
         $attr = apply_filters('mla_gallery_query_attributes', $attr);
     }
     $arguments = shortcode_atts(self::$data_selection_parameters, $attr);
     $mla_page_parameter = $arguments['mla_page_parameter'];
     unset($arguments['mla_page_parameter']);
     /*
      * $mla_page_parameter, if set, doesn't make it through the shortcode_atts filter,
      * so we handle it separately
      */
     if (!isset($arguments[$mla_page_parameter])) {
         if (isset($attr[$mla_page_parameter])) {
             $arguments[$mla_page_parameter] = $attr[$mla_page_parameter];
         } else {
             $arguments[$mla_page_parameter] = NULL;
         }
     }
     /*
      * 'RAND' is not documented in the codex, but is present in the code.
      */
     if ('RAND' == strtoupper($arguments['order'])) {
         $arguments['orderby'] = 'none';
         unset($arguments['order']);
     }
     if (!empty($arguments['ids'])) {
         // 'ids' is explicitly ordered, unless you specify otherwise.
         if (empty($attr['orderby'])) {
             $arguments['orderby'] = 'post__in';
         }
         $arguments['include'] = $arguments['ids'];
     }
     unset($arguments['ids']);
     if (!is_null($return_found_rows)) {
         $arguments = apply_filters('mla_gallery_query_arguments', $arguments);
     }
     /*
      * Extract taxonomy arguments
      */
     $taxonomies = get_taxonomies(array('show_ui' => true), 'names');
     // 'objects'
     $query_arguments = array();
     if (!empty($attr)) {
         foreach ($attr as $key => $value) {
             if ('tax_query' == $key) {
                 if (is_array($value)) {
                     $query_arguments[$key] = $value;
                 } else {
                     $tax_query = NULL;
                     $value = self::_sanitize_query_specification($value);
                     $function = @create_function('', 'return ' . $value . ';');
                     if (is_callable($function)) {
                         $tax_query = $function();
                     }
                     if (is_array($tax_query)) {
                         $query_arguments[$key] = $tax_query;
                     } else {
                         return '<p>ERROR: invalid mla_gallery tax_query = ' . var_export($value, true) . '</p>';
                     }
                 }
                 // not array
             } elseif (array_key_exists($key, $taxonomies)) {
                 $query_arguments[$key] = implode(',', array_filter(array_map('trim', explode(',', $value))));
                 if ('false' == strtolower(trim($arguments['tax_include_children']))) {
                     $arguments['tax_include_children'] = false;
                     if ('' == $arguments['tax_operator']) {
                         $arguments['tax_operator'] = 'OR';
                     }
                 } else {
                     $arguments['tax_include_children'] = true;
                 }
                 if (in_array(strtoupper($arguments['tax_operator']), array('OR', 'IN', 'NOT IN', 'AND'))) {
                     $query_arguments['tax_query'] = array(array('taxonomy' => $key, 'field' => 'slug', 'terms' => explode(',', $query_arguments[$key]), 'operator' => strtoupper($arguments['tax_operator']), 'include_children' => $arguments['tax_include_children']));
                     unset($query_arguments[$key]);
                 }
             }
             // array_key_exists
         }
         //foreach $attr
     }
     // ! empty
     unset($arguments['tax_operator']);
     unset($arguments['tax_include_children']);
     /*
      * $query_arguments has been initialized in the taxonomy code above.
      */
     $use_children = empty($query_arguments);
     foreach ($arguments as $key => $value) {
         /*
          * There are several "fallthru" cases in this switch statement that decide 
          * whether or not to limit the query to children of a specific post.
          */
         $children_ok = true;
         switch ($key) {
             case 'post_parent':
                 switch (strtolower($value)) {
                     case 'all':
                         $value = NULL;
                         $use_children = false;
                         break;
                     case 'any':
                         self::$query_parameters['post_parent'] = 'any';
                         $value = NULL;
                         $use_children = false;
                         break;
                     case 'current':
                         $value = $post_parent;
                         break;
                     case 'none':
                         self::$query_parameters['post_parent'] = 'none';
                         $value = NULL;
                         $use_children = false;
                         break;
                 }
                 // fallthru
             // fallthru
             case 'id':
                 if (is_numeric($value)) {
                     $query_arguments[$key] = intval($value);
                     if (!$children_ok) {
                         $use_children = false;
                     }
                 }
                 unset($arguments[$key]);
                 break;
             case 'numberposts':
             case 'posts_per_page':
             case 'posts_per_archive_page':
                 if (is_numeric($value)) {
                     $value = intval($value);
                     if (!empty($value)) {
                         $query_arguments[$key] = $value;
                     }
                 }
                 unset($arguments[$key]);
                 break;
             case 'meta_value_num':
                 $children_ok = false;
                 // fallthru
             // fallthru
             case 'offset':
                 if (is_numeric($value)) {
                     $query_arguments[$key] = intval($value);
                     if (!$children_ok) {
                         $use_children = false;
                     }
                 }
                 unset($arguments[$key]);
                 break;
             case 'paged':
                 if ('current' == strtolower($value)) {
                     /*
                      * Note: The query variable 'page' holds the pagenumber for a single paginated
                      * Post or Page that includes the <!--nextpage--> Quicktag in the post content. 
                      */
                     if (get_query_var('page')) {
                         $query_arguments[$key] = get_query_var('page');
                     } else {
                         $query_arguments[$key] = get_query_var('paged') ? get_query_var('paged') : 1;
                     }
                 } elseif (is_numeric($value)) {
                     $query_arguments[$key] = intval($value);
                 } elseif ('' === $value) {
                     $query_arguments[$key] = 1;
                 }
                 unset($arguments[$key]);
                 break;
             case $mla_page_parameter:
             case 'mla_paginate_total':
                 if (is_numeric($value)) {
                     $query_arguments[$key] = intval($value);
                 } elseif ('' === $value) {
                     $query_arguments[$key] = 1;
                 }
                 unset($arguments[$key]);
                 break;
             case 'author':
             case 'cat':
             case 'tag_id':
                 if (!empty($value)) {
                     if (is_array($value)) {
                         $query_arguments[$key] = array_filter($value);
                     } else {
                         $query_arguments[$key] = array_filter(array_map('intval', explode(",", $value)));
                     }
                     if (1 == count($query_arguments[$key])) {
                         $query_arguments[$key] = $query_arguments[$key][0];
                     } else {
                         $query_arguments[$key] = implode(',', $query_arguments[$key]);
                     }
                     $use_children = false;
                 }
                 unset($arguments[$key]);
                 break;
             case 'category__and':
             case 'category__in':
             case 'category__not_in':
             case 'tag__and':
             case 'tag__in':
             case 'tag__not_in':
             case 'include':
                 $children_ok = false;
                 // fallthru
             // fallthru
             case 'exclude':
                 if (!empty($value)) {
                     if (is_array($value)) {
                         $query_arguments[$key] = array_filter($value);
                     } else {
                         $query_arguments[$key] = array_filter(array_map('intval', explode(",", $value)));
                     }
                     if (!$children_ok) {
                         $use_children = false;
                     }
                 }
                 unset($arguments[$key]);
                 break;
             case 'tag_slug__and':
             case 'tag_slug__in':
                 if (!empty($value)) {
                     if (is_array($value)) {
                         $query_arguments[$key] = $value;
                     } else {
                         $query_arguments[$key] = array_filter(array_map('trim', explode(",", $value)));
                     }
                     $use_children = false;
                 }
                 unset($arguments[$key]);
                 break;
             case 'nopaging':
                 // boolean
                 if (!empty($value) && 'false' != strtolower($value)) {
                     $query_arguments[$key] = true;
                 }
                 unset($arguments[$key]);
                 break;
             case 'author_name':
             case 'category_name':
             case 'tag':
             case 'meta_key':
             case 'meta_value':
             case 'meta_compare':
             case 's':
                 $children_ok = false;
                 // fallthru
             // fallthru
             case 'post_type':
             case 'post_status':
             case 'post_mime_type':
             case 'orderby':
                 if (!empty($value)) {
                     $query_arguments[$key] = $value;
                     if (!$children_ok) {
                         $use_children = false;
                     }
                 }
                 unset($arguments[$key]);
                 break;
             case 'order':
                 if (!empty($value)) {
                     $value = strtoupper($value);
                     if (in_array($value, array('ASC', 'DESC'))) {
                         $query_arguments[$key] = $value;
                     }
                 }
                 unset($arguments[$key]);
                 break;
             case 'meta_query':
                 if (!empty($value)) {
                     if (is_array($value)) {
                         $query_arguments[$key] = $value;
                     } else {
                         $meta_query = NULL;
                         $value = self::_sanitize_query_specification($value);
                         $function = @create_function('', 'return ' . $value . ';');
                         if (is_callable($function)) {
                             $meta_query = $function();
                         }
                         if (is_array($meta_query)) {
                             $query_arguments[$key] = $meta_query;
                         } else {
                             return '<p>ERROR: invalid mla_gallery meta_query = ' . var_export($value, true) . '</p>';
                         }
                     }
                     // not array
                     $use_children = false;
                 }
                 unset($arguments[$key]);
                 break;
             default:
                 // ignore anything else
         }
         // switch $key
     }
     // foreach $arguments
     /*
      * Decide whether to use a "get_children" style query
      */
     if ($use_children && !isset($query_arguments['post_parent'])) {
         if (!isset($query_arguments['id'])) {
             $query_arguments['post_parent'] = $post_parent;
         } else {
             $query_arguments['post_parent'] = $query_arguments['id'];
         }
         unset($query_arguments['id']);
     }
     if (isset($query_arguments['numberposts']) && !isset($query_arguments['posts_per_page'])) {
         $query_arguments['posts_per_page'] = $query_arguments['numberposts'];
     }
     unset($query_arguments['numberposts']);
     /*
      * MLA pagination will override WordPress pagination
      */
     if (isset($query_arguments[$mla_page_parameter])) {
         unset($query_arguments['nopaging']);
         unset($query_arguments['offset']);
         unset($query_arguments['paged']);
         if (isset($query_arguments['mla_paginate_total']) && $query_arguments[$mla_page_parameter] > $query_arguments['mla_paginate_total']) {
             $query_arguments['offset'] = 0x7fffffff;
         } else {
             $query_arguments['paged'] = $query_arguments[$mla_page_parameter];
         }
     } else {
         if (isset($query_arguments['posts_per_page']) || isset($query_arguments['posts_per_archive_page']) || isset($query_arguments['paged']) || isset($query_arguments['offset'])) {
             unset($query_arguments['nopaging']);
         }
     }
     unset($query_arguments[$mla_page_parameter]);
     unset($query_arguments['mla_paginate_total']);
     if (isset($query_arguments['post_mime_type']) && 'all' == strtolower($query_arguments['post_mime_type'])) {
         unset($query_arguments['post_mime_type']);
     }
     if (!empty($query_arguments['include'])) {
         $incposts = wp_parse_id_list($query_arguments['include']);
         $query_arguments['posts_per_page'] = count($incposts);
         // only the number of posts included
         $query_arguments['post__in'] = $incposts;
     } elseif (!empty($query_arguments['exclude'])) {
         $query_arguments['post__not_in'] = wp_parse_id_list($query_arguments['exclude']);
     }
     $query_arguments['ignore_sticky_posts'] = true;
     $query_arguments['no_found_rows'] = is_null($return_found_rows) ? true : !$return_found_rows;
     /*
      * We will always handle "orderby" in our filter
      */
     self::$query_parameters['orderby'] = self::_validate_sql_orderby($query_arguments);
     if (false === self::$query_parameters['orderby']) {
         unset(self::$query_parameters['orderby']);
     }
     unset($query_arguments['orderby']);
     unset($query_arguments['order']);
     if (self::$mla_debug) {
         add_filter('posts_clauses', 'MLAShortcodes::mla_shortcode_query_posts_clauses_filter', 0x7fffffff, 1);
         add_filter('posts_clauses_request', 'MLAShortcodes::mla_shortcode_query_posts_clauses_request_filter', 0x7fffffff, 1);
     }
     add_filter('posts_orderby', 'MLAShortcodes::mla_shortcode_query_posts_orderby_filter', 0x7fffffff, 1);
     add_filter('posts_where', 'MLAShortcodes::mla_shortcode_query_posts_where_filter', 0x7fffffff, 1);
     if (self::$mla_debug) {
         global $wp_filter;
         self::$mla_debug_messages .= '<p><strong>mla_debug $wp_filter[posts_where]</strong> = ' . var_export($wp_filter['posts_where'], true) . '</p>';
         self::$mla_debug_messages .= '<p><strong>mla_debug $wp_filter[posts_orderby]</strong> = ' . var_export($wp_filter['posts_orderby'], true) . '</p>';
     }
     self::$mla_gallery_wp_query_object = new WP_Query();
     $attachments = self::$mla_gallery_wp_query_object->query($query_arguments);
     /*
      * $return_found_rows is used to indicate that the call comes from gallery_shortcode(),
      * which is the only call that supplies it.
      */
     if (is_null($return_found_rows)) {
         $return_found_rows = false;
     } else {
         do_action('mla_gallery_wp_query_object', $query_arguments);
     }
     if ($return_found_rows) {
         $attachments['found_rows'] = self::$mla_gallery_wp_query_object->found_posts;
     }
     remove_filter('posts_where', 'MLAShortcodes::mla_shortcode_query_posts_where_filter', 0x7fffffff, 1);
     remove_filter('posts_orderby', 'MLAShortcodes::mla_shortcode_query_posts_orderby_filter', 0x7fffffff, 1);
     if (self::$mla_debug) {
         remove_filter('posts_clauses', 'MLAShortcodes::mla_shortcode_query_posts_clauses_filter', 0x7fffffff, 1);
         remove_filter('posts_clauses_request', 'MLAShortcodes::mla_shortcode_query_posts_clauses_request_filter', 0x7fffffff, 1);
         self::$mla_debug_messages .= '<p><strong>mla_debug query</strong> = ' . var_export($query_arguments, true) . '</p>';
         self::$mla_debug_messages .= '<p><strong>mla_debug request</strong> = ' . var_export(self::$mla_gallery_wp_query_object->request, true) . '</p>';
         self::$mla_debug_messages .= '<p><strong>mla_debug query_vars</strong> = ' . var_export(self::$mla_gallery_wp_query_object->query_vars, true) . '</p>';
         self::$mla_debug_messages .= '<p><strong>mla_debug post_count</strong> = ' . var_export(self::$mla_gallery_wp_query_object->post_count, true) . '</p>';
     }
     self::$mla_gallery_wp_query_object = NULL;
     return $attachments;
 }
 /**
  * Process IPTC/EXIF custom field settings against all image attachments
  * without saving the settings to the mla_option
  *
  * @since 1.00
  *
  * @uses $_REQUEST if passed a NULL parameter
  *
  * @param	array | NULL	specific iptc_exif_custom_mapping values 
  * @param	integer			offset for chunk mapping 
  * @param	integer			length for chunk mapping
  *
  * @return	array	Message(s) reflecting the results of the operation
  */
 private static function _process_iptc_exif_custom($settings = NULL, $offset = 0, $length = 0)
 {
     if (NULL == $settings) {
         $source = 'iptc_exif_custom';
         $settings = isset($_REQUEST['iptc_exif_mapping']) ? stripslashes_deep($_REQUEST['iptc_exif_mapping']) : array();
         if (isset($settings['custom'][MLAOptions::MLA_NEW_CUSTOM_FIELD])) {
             unset($settings['custom'][MLAOptions::MLA_NEW_CUSTOM_FIELD]);
         }
         if (isset($settings['custom'][MLAOptions::MLA_NEW_CUSTOM_RULE])) {
             unset($settings['custom'][MLAOptions::MLA_NEW_CUSTOM_RULE]);
         }
     } else {
         $source = 'iptc_exif_custom_rule';
         $settings = stripslashes_deep($settings);
     }
     if (empty($settings['custom'])) {
         return array('message' => sprintf(__('%1$s: No %2$s settings to process.', 'media-library-assistant'), __('ERROR', 'media-library-assistant'), __('Custom field', 'media-library-assistant')), 'body' => '');
     }
     $examine_count = 0;
     $update_count = 0;
     $query = array('orderby' => 'none', 'post_parent' => 'all', 'post_mime_type' => 'image,application/*pdf*');
     if ($length > 0) {
         $query['numberposts'] = $length;
         $query['offset'] = $offset;
     }
     $posts = MLAShortcodes::mla_get_shortcode_attachments(0, $query);
     if (is_string($posts)) {
         return array('message' => $posts, 'body' => '');
     }
     do_action('mla_begin_mapping', $source, NULL);
     foreach ($posts as $key => $post) {
         $updates = MLAOptions::mla_evaluate_iptc_exif_mapping($post, 'iptc_exif_custom_mapping', $settings);
         $examine_count += 1;
         if (!empty($updates)) {
             $results = MLAData::mla_update_single_item($post->ID, $updates);
             if (stripos($results['message'], __('updated.', 'media-library-assistant'))) {
                 $update_count += 1;
             }
         }
     }
     // foreach post
     do_action('mla_end_mapping');
     if ($update_count) {
         /* translators: 1: field type 2: examined count 3: updated count */
         $message = sprintf(__('%1$s mapping completed; %2$d attachment(s) examined, %3$d updated.'), 'IPTC/EXIF ' . __('Custom field', 'media-library-assistant'), $examine_count, $update_count) . "\r\n";
     } else {
         /* translators: 1: field type 2: examined count */
         $message = sprintf(__('%1$s mapping completed; %2$d attachment(s) examined, no changes detected.'), 'IPTC/EXIF ' . __('Custom field', 'media-library-assistant'), $examine_count) . "\r\n";
     }
     return array('message' => $message, 'body' => '', 'processed' => $examine_count, 'unchanged' => $examine_count - $update_count, 'success' => $update_count);
 }
 /**
  * Process IPTC/EXIF custom field settings against all image attachments
  * without saving the settings to the mla_option
  *
  * @since 1.00
  *
  * @uses $_REQUEST if passed a NULL parameter
  *
  * @param	array | NULL	specific iptc_exif_custom_mapping values 
  *
  * @return	array	Message(s) reflecting the results of the operation
  */
 private static function _process_iptc_exif_custom($settings = NULL)
 {
     if (NULL == $settings) {
         $settings = isset($_REQUEST['iptc_exif_mapping']) ? $_REQUEST['iptc_exif_mapping'] : array();
         if (isset($settings['custom'][MLAOptions::MLA_NEW_CUSTOM_FIELD])) {
             unset($settings['custom'][MLAOptions::MLA_NEW_CUSTOM_FIELD]);
         }
         if (isset($settings['custom'][MLAOptions::MLA_NEW_CUSTOM_RULE])) {
             unset($settings['custom'][MLAOptions::MLA_NEW_CUSTOM_RULE]);
         }
     }
     if (empty($settings['custom'])) {
         return array('message' => 'ERROR: No custom field settings to process.', 'body' => '');
     }
     $examine_count = 0;
     $update_count = 0;
     //		$query = array( 'orderby' => 'none', 'post_parent' => 'all' ); // , 'post_mime_type' => 'image' );
     //		$query = array( 'orderby' => 'none', 'post_parent' => 'all', 'post_mime_type' => 'application/*pdf*' );
     $query = array('orderby' => 'none', 'post_parent' => 'all', 'post_mime_type' => 'image,application/*pdf*');
     $posts = MLAShortcodes::mla_get_shortcode_attachments(0, $query);
     if (is_string($posts)) {
         return array('message' => $posts, 'body' => '');
     }
     foreach ($posts as $key => $post) {
         $updates = MLAOptions::mla_evaluate_iptc_exif_mapping($post, 'iptc_exif_custom_mapping', $settings);
         $examine_count += 1;
         if (!empty($updates)) {
             $results = MLAData::mla_update_single_item($post->ID, $updates);
             if (stripos($results['message'], 'updated.')) {
                 $update_count += 1;
             }
         }
     }
     // foreach post
     if ($update_count) {
         $message = "IPTC/EXIF custom field mapping completed; {$examine_count} attachment(s) examined, {$update_count} updated.\r\n";
     } else {
         $message = "IPTC/EXIF custom field mapping completed; {$examine_count} attachment(s) examined, no changes detected.\r\n";
     }
     return array('message' => $message, 'body' => '');
 }
Example #9
0
 /**
  * Analyze a template, expanding Field-level Markup Substitution Parameters
  *
  * Field-level parameters must have one of the following prefix values:
  * template, request, query, custom, terms, meta, iptc, exif, xmp, pdf.
  * All but request and query require an attachment ID.
  *
  * @since 1.50
  *
  * @param	string	A formatting string containing [+placeholders+]
  * @param	array	Optional: an array of values from the query, if any, e.g. shortcode parameters
  * @param	array	Optional: an array of values to add to the returned array
  * @param	integer	Optional: attachment ID for attachment-specific placeholders
  * @param	boolean	Optional: for option 'multi', retain existing values
  * @param	string	Optional: default option value
  *
  * @return	array	( parameter => value ) for all field-level parameters and anything in $markup_values
  */
 public static function mla_expand_field_level_parameters($tpl, $query = NULL, $markup_values = array(), $post_id = 0, $keep_existing = false, $default_option = 'text')
 {
     static $cached_post_id = 0, $item_metadata = NULL, $attachment_metadata = NULL, $id3_metadata = NULL;
     if ($cached_post_id != $post_id) {
         $item_metadata = NULL;
         $attachment_metadata = NULL;
         $id3_metadata = NULL;
         $cached_post_id = $post_id;
     }
     $placeholders = self::mla_get_template_placeholders($tpl, $default_option);
     $template_count = 0;
     foreach ($placeholders as $key => $value) {
         if (isset($markup_values[$key])) {
             continue;
         }
         switch ($value['prefix']) {
             case 'template':
                 $markup_values = self::mla_expand_field_level_parameters($value['value'], $query, $markup_values, $post_id, $keep_existing, $default_option);
                 $template_count++;
                 break;
             case 'meta':
                 if (is_null($item_metadata)) {
                     if (0 < $post_id) {
                         $item_metadata = get_metadata('post', $post_id, '_wp_attachment_metadata', true);
                     } else {
                         break;
                     }
                 }
                 $markup_values[$key] = self::mla_find_array_element($value['value'], $item_metadata, $value['option']);
                 break;
             case 'query':
                 if (isset($query) && isset($query[$value['value']])) {
                     $markup_values[$key] = $query[$value['value']];
                 } else {
                     $markup_values[$key] = '';
                 }
                 break;
             case 'request':
                 if (isset($_REQUEST[$value['value']])) {
                     $record = $_REQUEST[$value['value']];
                 } else {
                     $record = '';
                 }
                 if (is_scalar($record)) {
                     $text = sanitize_text_field((string) $record);
                 } elseif (is_array($record)) {
                     if ('export' == $value['option']) {
                         $text = sanitize_text_field(var_export($record, true));
                     } else {
                         $text = '';
                         foreach ($record as $term) {
                             $term_name = sanitize_text_field($term);
                             $text .= strlen($text) ? ',' . $term_name : $term_name;
                         }
                     }
                 }
                 // is_array
                 $markup_values[$key] = $text;
                 break;
             case 'terms':
                 if (0 < $post_id) {
                     $terms = get_object_term_cache($post_id, $value['value']);
                     if (false === $terms) {
                         $terms = wp_get_object_terms($post_id, $value['value']);
                         wp_cache_add($post_id, $terms, $value['value'] . '_relationships');
                     }
                 } else {
                     break;
                 }
                 $text = '';
                 if (is_wp_error($terms)) {
                     $text = implode(',', $terms->get_error_messages());
                 } elseif (!empty($terms)) {
                     if ('single' == $value['option'] || 1 == count($terms)) {
                         reset($terms);
                         $term = current($terms);
                         $text = sanitize_term_field('name', $term->name, $term->term_id, $value['value'], 'display');
                     } elseif ('export' == $value['option']) {
                         $text = sanitize_text_field(var_export($terms, true));
                     } else {
                         foreach ($terms as $term) {
                             $term_name = sanitize_term_field('name', $term->name, $term->term_id, $value['value'], 'display');
                             $text .= strlen($text) ? ', ' . $term_name : $term_name;
                         }
                     }
                 }
                 $markup_values[$key] = $text;
                 break;
             case 'custom':
                 if (0 < $post_id) {
                     $record = get_metadata('post', $post_id, $value['value'], 'single' == $value['option']);
                     if (empty($record) && 'ALL_CUSTOM' == $value['value']) {
                         $meta_values = MLAQuery::mla_fetch_attachment_metadata($post_id);
                         $clean_data = array();
                         foreach ($meta_values as $meta_key => $meta_value) {
                             if (0 !== strpos($meta_key, 'mla_item_')) {
                                 continue;
                             }
                             $meta_key = substr($meta_key, 9);
                             if (is_array($meta_value)) {
                                 $clean_data[$meta_key] = '(ARRAY)';
                             } elseif (is_string($meta_value)) {
                                 $clean_data[$meta_key] = self::_bin_to_utf8(substr($meta_value, 0, 256));
                             } else {
                                 $clean_data[$meta_key] = $meta_value;
                             }
                         }
                         // foreach value
                         /*
                          * Convert the array to text, strip the outer "array( ... ,)" literal,
                          * the interior linefeed/space/space separators and backslashes.
                          */
                         $record = var_export($clean_data, true);
                         $record = substr($record, 7, strlen($record) - 10);
                         $record = str_replace(chr(0xa) . '  ', ' ', $record);
                         $record = str_replace('\\', '', $record);
                     }
                     // ALL_CUSTOM
                 } else {
                     break;
                 }
                 $text = '';
                 if (is_wp_error($record)) {
                     $text = implode(',', $record->get_error_messages());
                 } elseif (!empty($record)) {
                     if (is_scalar($record)) {
                         $text = 'raw' == $value['format'] ? (string) $record : sanitize_text_field((string) $record);
                     } elseif (is_array($record)) {
                         if ('export' == $value['option']) {
                             $text = 'raw' == $value['format'] ? var_export($record, true) : sanitize_text_field(var_export($record, true));
                         } else {
                             $text = '';
                             foreach ($record as $term) {
                                 $term_name = 'raw' == $value['format'] ? $term : sanitize_text_field($term);
                                 $text .= strlen($text) ? ', ' . $term_name : $term_name;
                             }
                         }
                     }
                     // is_array
                 }
                 // ! empty
                 $markup_values[$key] = $text;
                 break;
             case 'iptc':
                 if (is_null($attachment_metadata)) {
                     if (0 < $post_id) {
                         $attachment_metadata = self::mla_fetch_attachment_image_metadata($post_id);
                     } else {
                         break;
                     }
                 }
                 $markup_values[$key] = self::mla_iptc_metadata_value($value['value'], $attachment_metadata, $value['option'], $keep_existing);
                 break;
             case 'exif':
                 if (is_null($attachment_metadata)) {
                     if (0 < $post_id) {
                         $attachment_metadata = self::mla_fetch_attachment_image_metadata($post_id);
                     } else {
                         break;
                     }
                 }
                 $record = self::mla_exif_metadata_value($value['value'], $attachment_metadata, $value['option'], $keep_existing);
                 if (is_array($record)) {
                     $markup_values[$key] = self::_process_field_level_array($record, $value['option'], $keep_existing);
                 } else {
                     $markup_values[$key] = $record;
                 }
                 break;
             case 'xmp':
                 if (is_null($attachment_metadata)) {
                     if (0 < $post_id) {
                         $attachment_metadata = self::mla_fetch_attachment_image_metadata($post_id);
                     } else {
                         break;
                     }
                 }
                 $markup_values[$key] = self::mla_xmp_metadata_value($value['value'], $attachment_metadata['mla_xmp_metadata'], $value['option'], $keep_existing);
                 break;
             case 'id3':
                 if (is_null($id3_metadata)) {
                     if (0 < $post_id) {
                         $id3_metadata = self::mla_fetch_attachment_id3_metadata($post_id);
                     } else {
                         break;
                     }
                 }
                 $markup_values[$key] = self::mla_id3_metadata_value($value['value'], $id3_metadata, $value['option'], $keep_existing);
                 break;
             case 'pdf':
                 if (is_null($attachment_metadata)) {
                     if (0 < $post_id) {
                         $attachment_metadata = self::mla_fetch_attachment_image_metadata($post_id);
                     } else {
                         break;
                     }
                 }
                 $record = self::mla_pdf_metadata_value($value['value'], $attachment_metadata);
                 if (is_array($record)) {
                     $markup_values[$key] = self::_process_field_level_array($record, $value['option'], $keep_existing);
                 } else {
                     $markup_values[$key] = $record;
                 }
                 break;
             case '':
                 $candidate = str_replace('{', '[', str_replace('}', ']', $value['value']));
                 $key = str_replace('{', '[', str_replace('}', ']', $key));
                 if (MLAShortcodes::mla_is_data_source($candidate)) {
                     $data_value = array('data_source' => $candidate, 'keep_existing' => false, 'format' => 'raw', 'option' => $value['option']);
                     // single, export, text for array values, e.g., alt_text
                     $markup_values[$key] = MLAShortcodes::mla_get_data_source($post_id, 'single_attachment_mapping', $data_value);
                 } elseif (isset($markup_values[$value['value']])) {
                     /*
                      * A standard element can have a format modifier, e.g., commas, attr
                      */
                     $markup_values[$key] = $markup_values[$value['value']];
                 }
                 break;
             default:
                 // ignore anything else
         }
         // switch
         if (isset($markup_values[$key])) {
             $markup_values[$key] = self::mla_apply_field_level_format($markup_values[$key], $value);
         }
         // isset( $markup_values[ $key ] )
     }
     // foreach placeholder
     if ($template_count) {
         $markup_values['[+template_count+]'] = $template_count;
     }
     return $markup_values;
 }
function filterable_gallery_output($atts)
{
    // fail silently if somehow MLA isn't working.
    if (!shortcode_exists('mla_gallery')) {
        return;
    }
    $filtration_arguments = array('default_album' => '', 'menu_order' => '');
    $filterable_gallery_atts = shortcode_atts($filtration_arguments, $atts);
    // open the divs for the gallery and menu
    $return_value = '<div class="filtration-gallery" id="filtration-gallery">';
    $return_value .= '<div class="album-selector" id="album-selector">';
    $return_value .= '<div class="album-button" id="album-button"> Select an Album </div>';
    // create the menu
    if (strtolower($filterable_gallery_atts["menu_order"]) == "desc") {
        $filterable_gallery_atts["menu_order"] = "DESC";
    } else {
        $filterable_gallery_atts["menu_order"] = "ASC";
    }
    $args = array('order' => $filterable_gallery_atts["menu_order"], 'parent' => '0');
    $terms = get_terms('attachment_category', $args);
    $first_term_slug = $terms[0]->slug;
    $first_term_name = $terms[0]->name;
    $linkstart = '<li><a href="' . esc_url(get_page_link() . '/?album=');
    $linkslug = '" data-slug="';
    $linkend = ' <span class="album-arrows">&rang;&rang;</span></a></li>';
    $return_value .= '<ul class="mla-parent-categories" id="mla-parent-categories">';
    foreach ($terms as $value) {
        $slug = $value->slug;
        $return_value .= $linkstart . $slug . $linkslug . $slug . '" class="parent-link">' . $value->name . '</a>';
        $return_value .= '<ul class="mla-sub-categories">';
        $return_value .= $linkstart . $slug . $linkslug . $slug . '">All' . $linkend;
        $newargs = array('parent' => $value->term_id);
        $subterms = get_terms('attachment_category', $newargs);
        foreach ($subterms as $subvalue) {
            $s_slug = $subvalue->slug;
            $return_value .= $linkstart . $s_slug . $linkslug . $s_slug . '">' . $subvalue->name . $linkend;
        }
        $return_value .= '</ul> <!-- .mla-sub-categories -->';
        $return_value .= '</li>';
    }
    $return_value .= '</ul> <!-- .mla-parent-category -->';
    $return_value .= '</div> <!-- .album-selector -->';
    // menu area closed out, open up actual gallery area
    // extra wrapper for ajax purposes
    $return_value .= '<div id="current-album-wrapper">';
    $return_value .= '<div class="current-album" id="current-album">';
    // add the appropriate attachment category attribute to what was in the
    // shortcode already and then execute the MLA function
    if (isset($_GET["album"]) && term_exists($_GET["album"], 'attachment_category')) {
        $slugarray = array('slug' => $_GET["album"]);
        $albumarray = get_terms('attachment_category', $slugarray);
        $atts['attachment_category'] = $_GET["album"];
        $return_value .= '<h2>' . $albumarray[0]->name . '</h2>';
        $return_value .= MLAShortcodes::mla_gallery_shortcode($atts);
    } else {
        $default_gallery_name = $first_term_name;
        $atts['attachment_category'] = $first_term_slug;
        if ($filterable_gallery_atts["default_album"] != $first_term_slug) {
            if (term_exists($filterable_gallery_atts["default_album"])) {
                $default_term = get_term_by('name', $filterable_gallery_atts["default_album"], 'attachment_category');
                $default_gallery_name = $default_term->name;
                $atts['attachment_category'] = $default_term->slug;
            }
        }
        $return_value .= '<h2>' . $default_gallery_name . '</h2>';
        $return_value .= MLAShortcodes::mla_gallery_shortcode($atts);
    }
    // close up shop!
    $return_value .= '</div> <!-- .current-album -->';
    $return_value .= '</div> <!-- #current-album-wrapper -->';
    $return_value .= '</div> <!-- .filtration-gallery -->';
    return $return_value;
}