Exemplo n.º 1
0
def metadata_exists(meta_type, object_id, meta_key):
    ''' Determine if a meta key is set for a given object
  @param string meta_type Type of object metadata is for (e.g., comment, post, or user)
  @param int    object_id ID of the object metadata is for
  @param string meta_key  Metadata key.
  @return bool True of the key is set, False if not.
  '''
    if not meta_type or not Php.is_numeric(object_id):
        return False

    object_id = xFn.AbsInt(object_id)
    if not object_id:
        return False

    # This filter is documented in wp-includes/meta.php */
    check = WiPg.apply_filters("get_{}_metadata".format(meta_type), None,
                               object_id, meta_key, True)
    if None is not check:
        return bool(check)

    meta_cache = WiCa.wp_cache_get(object_id, meta_type + '_meta')

    if not meta_cache:
        meta_cache = update_meta_cache(meta_type, array(object_id))
        meta_cache = meta_cache[object_id]

    if Php.isset(meta_cache, meta_key):
        return True
    return False
Exemplo n.º 2
0
def wp_load_alloptions():
    ''' Loads and caches all autoloaded options, if available or all options.
  @global wpdb wpdb WordPress database abstraction object.
  @return array List of all options.
  '''
    wpdb = WpC.WB.Wj.wpdb  # global wpdb

    if not wp_installing() or not WpC.WB.Wj.is_multisite():
        alloptions = WiCa.wp_cache_get('alloptions', 'options')
    else:
        alloptions = False

    if not alloptions:
        suppress = wpdb.suppress_errors()
        alloptions_db = wpdb.get_results(
            "SELECT option_name, option_value FROM "
            "{} WHERE autoload = 'yes'".format(wpdb.options))
        if not alloptions_db:
            alloptions_db = wpdb.get_results(
                "SELECT option_name, option_value FROM " + wpdb.options)
        wpdb.suppress_errors(suppress)
        alloptions = array()
        for o in Php.Array(alloptions_db):
            alloptions[o.option_name] = o.option_value
        if not wp_installing() or not WpC.WB.Wj.is_multisite():
            WiCa.wp_cache_add('alloptions', alloptions, 'options')

    return alloptions
Exemplo n.º 3
0
    def get_instance(post_id):
        ''' Retrieve WP_Post instance.
    @static
    @access public
    @global wpdb wpdb WordPress database abstraction object.
    @param int post_id Post ID.
    @return WP_Post|False Post object, False otherwise.
    '''
        wpdb = WpC.WB.Wj.wpdb  # global wpdb
        import wp.i.post as WpP

        if (not Php.is_numeric(post_id) or post_id != Php.floor(post_id)
                or not post_id):
            return False
        post_id = int(post_id)

        _post = WiCc.wp_cache_get(post_id, 'posts')
        #print('WP_Post.get_instance 1 _post=', _post)

        if not _post:
            _post = wpdb.get_row(
                wpdb.prepare(
                    "SELECT * FROM {} WHERE ID = %s LIMIT 1".format(
                        wpdb.posts), post_id))  # PyMySQL %d->%s
            if not _post:
                return False

            _post = WpP.sanitize_post(_post, 'raw')
            #print("WP_Post.get_instance _post.ID={} _post = {}"
            #      .format(_post.ID, _post))
            WiCc.wp_cache_add(_post.ID, _post, 'posts')
        elif Php.empty(_post, 'filter'):
            _post = WpP.sanitize_post(_post, 'raw')

        return WP_Post(_post)
Exemplo n.º 4
0
def wp_cache_get_last_changed(group):
    ''' Get last changed date for the specified cache group.
  @param group Where the cache contents are grouped.
  @return string last_changed UNIX timestamp with microseconds representing when the group was last changed.
  '''
    import wp.i.cache as WiCa
    last_changed = WiCa.wp_cache_get('last_changed', group)
    if not last_changed:
        last_changed = Php.microtime()
        WiCa.wp_cache_set('last_changed', last_changed, group)
Exemplo n.º 5
0
    def get_terms(self):
        ''' Get terms, based on query_vars.
    @global wpdb wpdb WordPress database abstraction object.
    @return array
    '''
        import wp.i.taxonomy as WiTx
        wpdb = WpC.WB.Wj.wpdb  # global wpdb

        self.parse_query(self.query_vars)
        args = self.query_vars
        #pprint(self.query_vars)  # TypeError: unhashable type: 'instancemethod'
        # userdata is array, inspect.ismethod(A.__repr__) is True
        print('WP_Term_Query.get_terms: self.query_vars=', self.query_vars)

        # Set up meta_query so it's available to 'pre_get_terms'.
        self.meta_query = WcMQ.WP_Meta_Query()
        self.meta_query.parse_query_vars(args)

        # Fires before terms are retrieved.
        # @param WP_Term_Query self Current instance of WP_Term_Query.
        WiPg.do_action('pre_get_terms', self)

        taxonomies = args['taxonomy']
        print("WcTQ.get_terms: taxonomies=", taxonomies)

        # Save queries by not crawling the tree in the case of multiple taxes or a flat tax.
        has_hierarchical_tax = False
        if taxonomies:
            for _tax in taxonomies:
                if WiTx.is_taxonomy_hierarchical(_tax):
                    has_hierarchical_tax = True

        if not has_hierarchical_tax:
            args['hierarchical'] = False
            args['pad_counts'] = False

        # 'parent' overrides 'child_of'.
        if 0 < Php.intval(args['parent']):
            args['child_of'] = False

        if 'all' == args['get']:
            args['childless'] = False
            args['child_of'] = 0
            args['hide_empty'] = 0
            args['hierarchical'] = False
            args['pad_counts'] = False

        # Filters the terms query arguments.
        # @param array args       An array of get_terms() arguments.
        # @param array taxonomies An array of taxonomies.
        args = WiPg.apply_filters('get_terms_args', args, taxonomies)
        #pprint(args)  # TypeError: unhashable type: 'instancemethod'
        # userdata is array, inspect.ismethod(A.__repr__) is True
        print('WP_Term_Query.get_terms: args=', args)

        # Avoid the query if the queried parent/child_of term has no descendants.
        child_of = args['child_of']
        parent = args['parent']

        if child_of:
            _parent = child_of
        elif parent:
            _parent = parent
        else:
            _parent = False

        if _parent:
            in_hierarchy = False
            for _tax in taxonomies:
                hierarchy = WiTx._get_term_hierarchy(_tax)

                if Php.isset(hierarchy, _parent):
                    in_hierarchy = True

            if not in_hierarchy:
                return array()

        # 'term_order' is a legal sort order only when joining the relationship
        #    table.
        _orderby = self.query_vars['orderby']
        if 'term_order' == _orderby and Php.empty(self.query_vars,
                                                  'object_ids'):
            _orderby = 'term_id'
        orderby = self.parse_orderby(_orderby)

        if orderby:
            orderby = "ORDER BY " + orderby

        order = self.parse_order(self.query_vars['order'])

        if taxonomies:
            self.sql_clauses['where']['taxonomy'] = (
                "tt.taxonomy IN ('" +
                Php.implode("', '", Php.array_map(WiF.esc_sql, taxonomies)) +
                "')")

        exclude = args['exclude']
        exclude_tree = args['exclude_tree']
        include = args['include']

        inclusions = ''
        if include:  # if not Php.empty(locals(), 'include'):
            exclude = ''
            exclude_tree = ''
            inclusions = Php.implode(',', WiFc.wp_parse_id_list(include))

        if inclusions:  # if not Php.empty(locals(), 'inclusions'):
            self.sql_clauses['where']['inclusions'] = ('t.term_id IN ( ' +
                                                       inclusions + ' )')

        exclusions = array()  # Php.array_map( int, exclusions=List)
        if exclude_tree:  # if not Php.empty(locals(), 'exclude_tree'):
            exclude_tree = WiFc.wp_parse_id_list(exclude_tree)
            excluded_children = exclude_tree
            for extrunk in exclude_tree:
                excluded_children = Php.array_merge(
                    excluded_children,
                    Php.Array(
                        get_terms(
                            taxonomies[0],
                            array(
                                ('child_of', Php.intval(extrunk)),
                                ('fields', 'ids'),
                                ('hide_empty', 0),
                            ))))
            exclusions = Php.array_merge(excluded_children, exclusions)

        if exclude:  # if not Php.empty(locals(), 'exclude'):
            exclusions = Php.array_merge(WiFc.wp_parse_id_list(exclude),
                                         exclusions)

        # 'childless' terms are those without an entry in the flattened term hierarchy.
        childless = bool(args['childless'])
        if childless:
            for _tax in taxonomies:
                term_hierarchy = WiTx._get_term_hierarchy(_tax)
                exclusions = Php.array_merge(Php.array_keys(term_hierarchy),
                                             exclusions)

        if exclusions:  # if not Php.empty(locals(), 'exclusions'):
            exclusions = 't.term_id NOT IN (' + Php.implode(
                ',', Php.array_map(Php.intval, exclusions)) + ')'
        else:
            exclusions = ''

        # Filters the terms to exclude from the terms query.
        # @param string exclusions `NOT IN` clause of the terms query.
        # @param array  args       An array of terms query arguments.
        # @param array  taxonomies An array of taxonomies.
        exclusions = WiPg.apply_filters('list_terms_exclusions', exclusions,
                                        args, taxonomies)

        if exclusions:  # if not Php.empty(locals(), 'exclusions'):
            # Must do string manipulation here for backward compatibility with filter.
            self.sql_clauses['where']['exclusions'] = preg_replace(
                '/^\s*AND\s*/', '', exclusions)

        print("\n WcTQ.get_terms: args['name'] =", args['name'])

        print("WcTQ.get_terms: taxonomies=", taxonomies)
        if not Php.empty(args, 'name'):
            names = Php.Array(args['name'])
            print("WcTQ.get_terms: names=", names, taxonomies)
            #foreach ( names as &_name ) {
            #modify list entries during for loop stackoverflow.com/questions/4081217
            for k, _name in names.items(
            ):  #use enumerate(names) if type(names)=list
                # `sanitize_term_field()` returns slashed data.
                #_name = Php.stripslashes( WiTx.sanitize_term_field(
                #                      'name', _name, 0, Php.reset(taxonomies), 'db'))
                names[k] = Php.stripslashes(
                    WiTx.sanitize_term_field('name', _name, 0,
                                             Php.reset(taxonomies), 'db'))

            print("WcTQ.get_terms: names=", names, taxonomies)
            self.sql_clauses['where']['name'] = "t.name IN ('" + Php.implode(
                "', '", Php.array_map(WiF.esc_sql, names)) + "')"

        if not Php.empty(args, 'slug'):
            if Php.is_array(args['slug']):
                slug = Php.array_map(WiF.sanitize_title, args['slug'])
                self.sql_clauses['where'][
                    'slug'] = "t.slug IN ('" + Php.implode("', '", slug) + "')"
            else:
                slug = WiF.sanitize_title(args['slug'])
                self.sql_clauses['where']['slug'] = "t.slug = 'slug'"

        if not Php.empty(args, 'term_taxonomy_id'):
            if Php.is_array(args['term_taxonomy_id']):
                tt_ids = Php.implode(
                    ',', Php.array_map(Php.intval, args['term_taxonomy_id']))
                self.sql_clauses['where']['term_taxonomy_id'] = \
                                            "tt.term_taxonomy_id IN ({})".format(tt_ids)
            else:
                self.sql_clauses['where']['term_taxonomy_id'] = wpdb.prepare(
                    "tt.term_taxonomy_id = %s",
                    args['term_taxonomy_id'])  # PyMySQL %d->%s

        if not Php.empty(args, 'name__like'):
            self.sql_clauses['where']['name__like'] = wpdb.prepare(
                "t.name LIKE %s",
                '%' + wpdb.esc_like(args['name__like']) + '%')

        if not Php.empty(args, 'description__like'):
            self.sql_clauses['where']['description__like'] = wpdb.prepare(
                "tt.description LIKE %s",
                '%' + wpdb.esc_like(args['description__like']) + '%')

        if not Php.empty(args, 'object_ids'):
            object_ids = args['object_ids']
            if not Php.is_array(object_ids):
                object_ids = array(object_ids)

            object_ids = Php.implode(', ',
                                     Php.array_map(Php.intval, object_ids))
            self.sql_clauses['where'][
                'object_ids'] = "tr.object_id IN ({})".format(object_ids)

        # When querying for object relationships, the 'count > 0' check
        # added by 'hide_empty' is superfluous.
        if not Php.empty(args['object_ids']):
            args['hide_empty'] = False

        if '' != parent:
            parent = Php.intval(parent)
            self.sql_clauses['where']['parent'] = "tt.parent = 'parent'"

        hierarchical = args['hierarchical']
        if 'count' == args['fields']:
            hierarchical = False
        if args['hide_empty'] and not hierarchical:
            self.sql_clauses['where']['count'] = 'tt.count > 0'

        number = args['number']
        offset = args['offset']

        # Don't limit the query results when we have to descend the family tree.
        if number and not hierarchical and not child_of and '' == parent:
            if offset:
                limits = 'LIMIT ' + offset + ',' + number
            else:
                limits = 'LIMIT ' + number
        else:
            limits = ''

        if not Php.empty(args, 'search'):
            self.sql_clauses['where']['search'] = self.get_search_sql(
                args['search'])

        # Meta query support.
        join = ''
        distinct = ''

        # Reparse meta_query query_vars, in case they were modified in a 'pre_get_terms' callback.
        self.meta_query.parse_query_vars(self.query_vars)
        mq_sql = self.meta_query.get_sql('term', 't', 'term_id')
        meta_clauses = self.meta_query.get_clauses()

        if not Php.empty(args, 'meta_clauses'):
            join += mq_sql['join']
            self.sql_clauses['where']['meta_query'] = preg_replace(
                '/^\s*AND\s*/', '', mq_sql['where'])
            distinct += "DISTINCT"

        selects = array()
        #switch ( args['fields'] ) {
        #  case 'all':
        AF = args['fields']
        if AF in ('all', 'all_with_object_id', 'tt_ids', 'slugs'):
            selects = array('t.*', 'tt.*')
            if ('all_with_object_id' == args['fields']
                    and not Php.empty(args, 'object_ids')):
                selects[None] = 'tr.object_id'

        #elif AF in ('ids', 'id=>parent'):
        elif AF in ('ids', 'id=>parent', 'id.parent'):
            selects = array('t.term_id', 'tt.parent', 'tt.count',
                            'tt.taxonomy')
        elif AF == 'names':
            selects = array('t.term_id', 'tt.parent', 'tt.count', 't.name',
                            'tt.taxonomy')
        elif AF == 'count':
            orderby = ''
            order = ''
            selects = array('COUNT(*)', )
        #elif AF == 'id=>name':
        elif AF in ('id=>name', 'id.name'):
            selects = array('t.term_id', 't.name', 'tt.count', 'tt.taxonomy')
        #elif AF == 'id=>slug':
        elif AF in ('id=>slug', 'id.slug'):
            selects = array('t.term_id', 't.slug', 'tt.count', 'tt.taxonomy')

        _fields = args['fields']

        # Filters the fields to select in the terms query.
        # Field lists modified using this filter will only modify the term fields returned
        # by the function when the `fields` parameter set to 'count' or 'all'. In all other
        # cases, the term fields in the results array will be determined by the `fields`
        # parameter alone.
        # Use of this filter can result in unpredictable behavior, and is not recommended.
        # @param array selects    An array of fields to select for the terms query.
        # @param array args       An array of term query arguments.
        # @param array taxonomies An array of taxonomies.
        fields = Php.implode(
            ', ',
            WiPg.apply_filters('get_terms_fields', selects, args, taxonomies))
        join += (" INNER JOIN " + wpdb.term_taxonomy +
                 " AS tt ON t.term_id = tt.term_id")

        if not Php.empty(self.query_vars, 'object_ids'):
            join += (" INNER JOIN {} AS tr ON tr.term_taxonomy_id = "
                     "tt.term_taxonomy_id".format(wpdb.term_relationships))
        where = Php.implode(' AND ', self.sql_clauses['where'])

        # Filters the terms query SQL clauses.
        # @param array pieces     Terms query SQL clauses.
        # @param array taxonomies An array of taxonomies.
        # @param array args       An array of terms query arguments.
        pieces = ('fields', 'join', 'where', 'distinct', 'orderby', 'order',
                  'limits')
        clauses = WiPg.apply_filters('terms_clauses',
                                     Php.compact(locals(), pieces), taxonomies,
                                     args)

        #fields = isset( clauses[ 'fields' ] ) ? clauses[ 'fields' ] : ''
        fields = clauses.get('fields', '')
        join = clauses.get('join', '')
        where = clauses.get('where', '')
        distinct = clauses.get('distinct', '')
        orderby = clauses.get('orderby', '')
        order = clauses.get('order', '')
        limits = clauses.get('limits', '')

        if where:
            where = "WHERE " + where

        self.sql_clauses['select'] = "SELECT {} {}".format(distinct, fields)
        self.sql_clauses['from'] = "FROM {} AS t {}".format(wpdb.terms, join)
        self.sql_clauses['orderby'] = orderby + " " + order if orderby else ''
        self.sql_clauses['limits'] = limits

        #self.request = "{self.sql_clauses['select']} {self.sql_clauses['from']} {where} {self.sql_clauses['orderby']} {self.sql_clauses['limits']}"
        self.request = "{} {} {} {} {}".format(self.sql_clauses['select'],
                                               self.sql_clauses['from'], where,
                                               self.sql_clauses['orderby'],
                                               self.sql_clauses['limits'])

        # args can be anything. Only use the args defined in defaults to compute the key.
        key = Php.md5(
            Php.serialize(
                WiFc.wp_array_slice_assoc(
                    args, Php.array_keys(self.query_var_defaults))) +
            Php.serialize(taxonomies) + self.request)
        last_changed = WiFc.wp_cache_get_last_changed('terms')
        cache_key = "get_terms:{}:{}".format(key, last_changed)
        cache = WiCa.wp_cache_get(cache_key, 'terms')
        if False != cache:
            if 'all' == _fields:
                cache = Php.array_map(WiTx.get_term, cache)

            self.terms = cache
            print("WcTQ get_terms 1 self.terms=", self.terms)
            return self.terms

        if 'count' == _fields:
            count = wpdb.get_var(self.request)
            WiCa.wp_cache_set(cache_key, count, 'terms')
            return count

        terms = wpdb.get_results(self.request)
        print("WcTQ get_terms 2 terms=", terms)
        if 'all' == _fields or 'all_with_object_id' == _fields:
            WiTx.update_term_cache(terms)
        print("WcTQ get_terms 3 terms=", terms)

        # Prime termmeta cache.
        if args['update_term_meta_cache']:
            term_ids = WiFc.wp_list_pluck(terms, 'term_id')
            WiTx.update_termmeta_cache(term_ids)

        print("WcTQ get_terms 4 terms=", terms)
        if not terms:  # if Php.empty(locals(), 'terms'):
            WiCa.wp_cache_add(cache_key, array(), 'terms',
                              WpC.WB.Wj.DAY_IN_SECONDS)
            return array()

        print("WcTQ get_terms 5 terms=", terms)
        if child_of:
            for _tax in taxonomies:
                children = WiTx._get_term_hierarchy(_tax)
                if children:  # if not Php.empty(locals(), 'children'):
                    terms = _get_term_children(child_of, terms, _tax)
                    print("WcTQ get_terms 6 terms=", terms)

        # Update term counts to include children.
        if args['pad_counts'] and 'all' == _fields:
            for _tax in taxonomies:
                _pad_term_counts(terms, _tax)

        # Make sure we show empty categories that have children.
        if hierarchical and args['hide_empty'] and Php.is_array(terms):
            for k, term in terms.items():
                Continue2 = False  #VT added to translate php: continue 2
                if not term.count:
                    children = get_term_children(term.term_id, term.taxonomy)
                    if Php.is_array(children):
                        for child_id in children:
                            child = WiTx.get_term(child_id, term.taxonomy)
                            if child.count:
                                #continue 2
                                Continue2 = True  #VT added to translate php: continue 2
                                continue  #VT added to translate php: continue 2
                    # It really is empty.
                    del terms[k]
                if Continue2:  #VT added to translate php: continue 2
                    continue  #VT added to translate php: continue 2

        print("WcTQ get_terms 7 terms=", terms)

        # When querying for terms connected to objects, we may get
        # duplicate results. The duplicates should be preserved if
        # `fields` is 'all_with_object_id', but should otherwise be
        # removed.
        if not Php.empty(args,
                         'object_ids') and 'all_with_object_id' != _fields:
            _tt_ids = array()  # need to be sperate mutable obj
            _terms = array()  # need to be sperate mutable obj
            for term in terms:
                if Php.isset(_tt_ids, getattr(term, 'term_id', None)):
                    continue
                _tt_ids[term.term_id] = 1
                _terms[None] = term

            terms = _terms

        _terms = array()  # array()
        #if 'id=>parent' == _fields:
        if _fields in ('id=>parent', 'id.parent'):
            for term in terms:
                _terms[term.term_id] = term.parent
        elif 'ids' == _fields:
            #for i,term in enumerate(terms):
            #  _terms[i] = int(term.term_id)
            for term in terms:
                _terms[None] = int(term.term_id)
        elif 'tt_ids' == _fields:
            for term in terms:
                _terms[None] = int(term.term_taxonomy_id)
        elif 'names' == _fields:
            #for i,term in enumerate(terms):
            #  _terms[i] = term.name
            for term in terms:
                _terms[None] = term.name
        elif 'slug' == _fields:
            for term in terms:
                _terms[None] = term.slug
        #elif 'id=>name' == _fields:
        elif _fields in ('id=>name', 'id.name'):
            for term in terms:
                _terms[term.term_id] = term.name
        #elif 'id=>slug' == _fields:
        elif _fields in ('id=>slug', 'id.slug'):
            for term in terms:
                _terms[term.term_id] = term.slug

        if _terms:  # if not Php.empty(locals(), '_terms'):
            terms = _terms

        # Hierarchical queries are not limited, so 'offset' and 'number' must be handled now.
        if hierarchical and number and Php.is_array(terms):
            if offset >= len(terms):
                terms = array()  # array()
            else:
                terms = Php.array_slice(terms, offset, number, True)

        WiCa.wp_cache_add(cache_key, terms, 'terms', WpC.WB.Wj.DAY_IN_SECONDS)

        if 'all' == _fields or 'all_with_object_id' == _fields:
            terms = Php.array_map(WiTx.get_term, terms)

        self.terms = terms
        return self.terms
Exemplo n.º 6
0
def update_meta_cache(meta_type, object_ids):
    '''Update the metadata cache for the specified objects.
  @param string    meta_type  Type of object metadata is for
                              (e.g., comment, post, or user)
  @param int|array object_ids Array or comma delimited list of object IDs
                              to update cache for
  @return array|False         Metadata cache for the specified objects,
                              or False on failure.
  '''
    #global var==>WpC.WB.Wj.var, except: var=WpC.WB.Wj.var=same Obj,mutable array
    wpdb = WpC.WB.Wj.wpdb  # global wpdb

    print('update_meta_cache meta_type={}, object_ids={}'.format(
        meta_type, object_ids))

    if not meta_type or not object_ids:
        print('update_meta_cache not meta_type or not object_ids:')
        return False
    table = _get_meta_table(meta_type)
    if not table:
        print('update_meta_cache not table:')
        return False

    column = WiF.sanitize_key(meta_type + '_id')

    #if not isinstance(object_ids, (list,tuple,)):
    if not Php.is_array(object_ids):
        #import re
        #Re = re.compile('[^0-9,]')
        #object_ids = Re.sub('', object_ids)
        object_ids = Php.preg_replace('|[^0-9,]|', '', object_ids)
        #object_ids= object_ids.split(',')
        object_ids = Php.explode(',', object_ids)
        # object_ids = [ val for val in object_ids.values() ]

    #object_ids = [int(val) for val in object_ids]   #same as:
    object_ids = Php.array_map(Php.intval, object_ids)
    print('update_meta_cache object_ids=', object_ids)

    cache_key = meta_type + '_meta'
    ids = array()
    cache = array()
    for Id in object_ids:
        cached_object = WiCa.wp_cache_get(Id, cache_key)
        if False is cached_object:
            ids[None] = Id
        else:
            cache[Id] = cached_object

    if not ids:  # if Php.empty(locals(), 'ids'):
        return cache

    # Get meta info
    #id_list = ','.join(str(ids))  #BAD!!#= [,2,6,8,3,4,]
    id_list = ','.join([str(Id) for Id in ids])
    id_column = 'umeta_id' if 'user' == meta_type else 'meta_id'
    #meta_list = wpdb->get_results( "SELECT $column, meta_key, meta_value FROM $table WHERE $column IN ($id_list) ORDER BY $id_column ASC", ARRAY_A )
    # in wp-db.php get_results( , ARRAY_A) = column name-keyed row arrays
    Sql = ("SELECT {}, meta_key, meta_value FROM {} WHERE {} IN ({}) ORDER BY "
           "{} ASC".format(column, table, column, id_list, id_column))
    #meta_list = wDB.GetDB(MetaC, table).Exec(Sql)
    meta_list = wpdb.get_results(Sql, 'ARRAY_A')
    # in wp-db.php get_results( , ARRAY_A) = column name-keyed row arrays
    print('\n update_meta_cache meta_list =', meta_list)

    if meta_list:  # if not Php.empty(locals(), 'meta_list'):
        for metarow in meta_list:
            mpid = int(metarow[column])
            mkey = metarow['meta_key']
            mval = metarow['meta_value']

            # Force subkeys to be arry type:
            if not Php.isset(cache, mpid) or not Php.is_array(cache[mpid]):
                cache[mpid] = array()
            if (not Php.isset(cache[mpid], mkey)
                    or not Php.is_array(cache[mpid][mkey])):
                cache[mpid][mkey] = array()

            # Add a value to the current pid/key:
            cache[mpid][mkey][None] = mval

    for Id in ids:
        if not Php.isset(cache, Id):
            cache[Id] = array()
        WiCa.wp_cache_add(Id, cache[Id], cache_key)

    print('\n update_meta_cache return cache =', cache)
    return cache
Exemplo n.º 7
0
def get_metadata(meta_type, object_id, meta_key='', single=False):
    '''
   Retrieve metadata for the specified object.
   @param string meta_type Type of object metadata is for
                           (e.g., comment, post, or user)
   @param int    object_id ID of the object metadata is for
   @param string meta_key  Optional. Metadata key. If not specified,
                           retrieve all metadata for the specified object.
   @param bool   single    Optional, default is False.
                           If True, return only the first value of the
                           specified meta_key. This parameter has no effect
                           if meta_key is not specified.
   @return mixed Single metadata value, or array of values = list = [] !!!
  '''
    if not meta_type or not isinstance(object_id, int):
        return False
    object_id = abs(object_id)
    if not object_id:
        return False
    print('get_metadata meta_type={}, object_id ={}, meta_key={}'.format(
        meta_type, object_id, meta_key))

    # Filter whether to retrieve metadata of a specific type.
    # The dynamic portion of the hook, `meta_type`, refers to the meta
    # object type (comment, post, or user). Returning a non-None value
    # will effectively short-circuit the function.
    # @param None|array|string value  The value get_metadata() should return -
    #                           a single metadata value, or an array of values.
    # @param int     object_id Object ID.
    # @param string  meta_key  Meta key.
    # @param bool    single    Whether to return only the first value of the
    #                          specified meta_key.
    check = WiPg.apply_filters("get_{}_metadata".format(meta_type), None,
                               object_id, meta_key, single)
    if check is not None:
        if single and Php.is_array(check):
            return check[0]
        else:
            return check
    meta_cache = WiCa.wp_cache_get(object_id, meta_type + '_meta')

    if not meta_cache:
        meta_cache = update_meta_cache(meta_type, array(object_id))
        # wp> $m = false; wp> $m[1] => NULL
        meta_cache = meta_cache[object_id]
        # The folllowing is BAD! since meta_cache = array( (object_id, array))
        #   so object_id in meta_cache is always False!
        #meta_cache  = meta_cache[object_id] if object_id in meta_cache else None
        # Can use array_key_exists or object_id in meta_cache.keys()

    if not meta_key:
        print('\n get_metadata not meta_key, return meta_cache =', meta_cache)
        return meta_cache

    #if meta_cache.get(meta_key, None) is not None:
    if Php.isset(meta_cache, meta_key):
        mkey = meta_cache[meta_key]
        print('get_metadata:', meta_type, object_id, meta_key, single, mkey)
        if single:
            return WiFc.maybe_unserialize(mkey[0])
        else:
            #print('get_metadata return:', Php.array_map(WiFc.maybe_unserialize, mkey))
            #return [ WiFc.maybe_unserialize(v) for v in mkey ]
            return Php.array_map(WiFc.maybe_unserialize, mkey)  #same as:

    #print('\n get_metadata not isset(meta_cache, meta_key)', meta_cache, meta_key)
    if single:
        return ''
    else:
        return array()
Exemplo n.º 8
0
    def get_instance(term_id, taxonomy=None):
        ''' Retrieve WP_Term instance.
    @access public  @static
    @global wpdb wpdb WordPress database abstraction object.
    @param int    term_id  Term ID.
    @param string taxonomy Optional. Limit matched terms to those matching `taxonomy`. Only used for
                            disambiguating potentially shared terms.
    @return WP_Term|WP_Error|False Term object, if found. WP_Error if `term_id` is shared between taxonomies and
                                   there's insufficient data to distinguish which term is intended.
                                   False for other failures.
    '''
        wpdb = WpC.WB.Wj.wpdb  # global wpdb
        import wp.i.taxonomy as WpTx

        if (not Php.is_numeric(term_id) or term_id != Php.floor(term_id)
                or not term_id):
            return False

        term_id = int(term_id)

        _term = WiCa.wp_cache_get(term_id, 'terms')

        # If there isn't a cached version, hit the database.
        if not _term or (taxonomy and taxonomy != _term.taxonomy):
            # Grab all matching terms, in case any are shared between taxonomies.
            terms = wpdb.get_results(
                wpdb.prepare(
                    "SELECT t.*, tt.* FROM {} AS t INNER JOIN {} AS tt ON t.term_id = tt.term_id WHERE t.term_id = %d"
                    .format(wpdb.terms, wpdb.term_taxonomy), term_id))
            if not terms:
                return False

            # If a taxonomy was specified, find a match.
            if taxonomy:
                for match in terms:
                    if taxonomy == match.taxonomy:
                        _term = match
                        break

            # If only one match was found, it's the one we want.
            elif 1 == len(terms):
                _term = reset(terms)

            # Otherwise, the term must be shared between taxonomies.
            else:
                # If the term is shared only with invalid taxonomies, return the one valid term.
                for t in terms:
                    if not WpTx.taxonomy_exists(t.taxonomy):
                        continue

                    # Only hit if we've already identified a term in a valid taxonomy.
                    if _term:
                        return WcE.WP_Error(
                            'ambiguous_term_id',
                            __('Term ID is shared between multiple taxonomies'
                               ), term_id)

                    _term = t

            if not _term:
                return False

            # Don't return terms from invalid taxonomies.
            if not WpTx.taxonomy_exists(_term.taxonomy):
                return WcE.WP_Error('invalid_taxonomy',
                                    __('Invalid taxonomy.'))

            _term = WpTx.sanitize_term(_term, _term.taxonomy, 'raw')

            # Don't cache terms that are shared between taxonomies.
            if 1 == len(terms):
                WiCa.wp_cache_add(term_id, _term, 'terms')

        term_obj = WP_Term(_term)
        term_obj.filter(term_obj.filter)

        return term_obj