Ejemplo n.º 1
0
    def pluck(self, field, index_key=None):
        ''' Plucks a certain field out of each object in the list.
    This has the same functionality and prototype of
    array_column() (PHP 5.5) but also supports objects.
    @param int|str field     Field from the object to place instead of the
                             entire object
    @param int|str index_key Optional. Field from the object to use as keys
                             for the new array. Default None.
    @return array Array of found values. If `index_key` is set, an array of
                  found values with keys corresponding to `index_key`. If
                  `index_key` is None, array keys from the original
                  `list` will be preserved in the results.
    '''
        if not index_key:
            # This is simple. Could at some point wrap array_column()
            # if we knew we had an array of arrays.
            for key, value in self.output.items():
                print('pluck', field, key, value)
                if Php.is_object(value):
                    #self.output[ $key ] = $value->$field
                    #Php returns None if no attr found, rather than raise error
                    self.output[key] = getattr(value, field, None)
                else:
                    try:
                        self.output[key] = value[field]
                    except:
                        self.output[key] = None  # Php> false[1]  #Out=> NULL
            return self.output

        # When index_key is not set for a particular item, push the value
        # to the end of the stack. This is how array_column() behaves.
        newlist = array()
        for value in self.output:
            if Php.is_object(value):
                #if isset( $value->$index_key ):
                if Php.isset(value, index_key):
                    #$newlist[ $value->$index_key ] = $value->$field
                    newlist[getattr(value, index_key)] = getattr(value, field)
                else:
                    #$newlist[] = $value->$field
                    newlist[None] = getattr(value, field)
            else:
                if Php.isset(value, index_key):
                    newlist[value[index_key]] = value[field]
                else:
                    newlist[None] = value[field]

        self.output = newlist

        return self.output
Ejemplo n.º 2
0
def map_deep(value, callback):
    ''' Maps a function to all non-iterable elements of an array or an object.
  This is similar to `array_walk_recursive()` but acts upon objects too.
  @param mixed    value    The array, object, or scalar.
  @param callable callback The function to map onto value.
  @return mixed   The value with the callback applied to all non-arrays and
                  non-objects inside it.
  refer to Php.serialize FlattenObj()
  '''
    #from copy import deepcopy
    #val = deepcopy(value)

    if value is None:
        return None
    #from datetime import datetime
    #if isinstance(value, Php.SeqSetTypes): #= (list,tuple,range,set,frozenset,)
    #  value = [ map_deep( item, callback) for item in value ]
    #isinstance( value, Php.MappingTypes): #= (dict, ODict, array)
    if Php.is_array(value):
        for index, item in value.items():
            value[index] = map_deep(item, callback)
    elif Php.is_object(value):
        #if inspect.isclass(value):  # class, not instance of a class
        #  element = Func(value, Func)
        #else:                       # by now, must be instance of class
        object_vars = Php.get_object_vars(value)
        for property_name, property_value in object_vars.items():
            setattr(value, property_name, map_deep(property_value, callback))
    else:  #elif isinstance( value, Php.ScalarTypes +(datetime,) ):
        # Php.ScalarTypes = (bool, str, bytes, int, float, complex,)
        value = callback(value)
    #else:
    #  raise TypeError("map_deep value={} has wrong type!".format(value))

    return value
Ejemplo n.º 3
0
def get_tag_link( tag ):
  ''' Retrieve the link to the tag.
  @see get_term_link()
  @param int|object tag Tag ID or object.
  @return string Link on success, empty string if tag does not exist.
  '''
  if not Php.is_object( tag ):
    tag = int( tag )

  tag = get_term_link( tag, 'post_tag' )

  if WpC.WB.Wj.is_wp_error( tag ):
    return ''

  return tag
Ejemplo n.º 4
0
def get_category_link( category ):
  ''' Retrieve category link URL.
  @see get_term_link()
  @param int|object category Category ID or object.
  @return string Link on success, empty string if category does not exist.
  '''
  if not Php.is_object( category ):
    category = int( category )

  category = get_term_link( category, 'category' )

  if WpC.WB.Wj.is_wp_error( category ):
    return ''

  return category
Ejemplo n.º 5
0
def wp_parse_args(args, defaults=''):
    '''/fs/web/wp/wp-includes/functions.php
  Merge user defined arguments into defaults array.
  This function is used throughout WordPress to allow for both string or array
  to be merged into another array.
  @param string|array|object args     Value to merge with defaults.
  @param array               defaults Optional. Array that serves as the
                             defaults. Default empty.
  @return array Merged user defined values with defaults.
  '''
    if Php.is_object(args):
        r = Php.get_object_vars(args)  #same as:
        #r = array( (attr, getattr(args, attr, None)) for attr in dir(args)
        #             if not attr.startswith(('_',)) )
    elif Php.is_array(args):
        r = args  # no need for & args since array is mutable
    else:  #elif isinstance(args, str):
        #Php# WiF.wp_parse_str( args, r )
        r = WiF.wp_parse_str(args)

    if Php.is_array(defaults):
        return Php.array_merge(defaults, r)
    return r
Ejemplo n.º 6
0
def register_uninstall_hook(File, callback):
    ''' Set the uninstallation hook for a plugin.
  Registers the uninstall hook that will be called when the user clicks on the
  uninstall link that calls for the plugin to uninstall itself. The link won't
  be active unless the plugin hooks into the action.
  The plugin should not run arbitrary code outside of functions, when
  registering the uninstall hook. In order to run using the hook, the plugin
  will have to be included, which means that any code laying outside of a
  function will be run during the uninstall process. The plugin should not
  hinder the uninstall process.
  If the plugin can not be written without running code within the plugin, then
  the plugin should create a file named 'uninstall.php' in the base plugin
  folder. This file will be called, if it exists, during the uninstall process
  bypassing the uninstall hook. The plugin, when using the 'uninstall.php'
  should always check for the 'WP_UNINSTALL_PLUGIN' constant, before
  executing.
  @param string   File     Plugin file.
  @param callable callback The callback to run when the hook is called. Must be
                            a static method or function.
  '''
    import wp.i.option as WiO
    if Php.is_array(callback) and Php.is_object(callback[0]):
        _doing_it_wrong(
            register_uninstall_hook.__name__,  # __FUNCTION__,
            __('Only a static class method or function can be used in an uninstall hook.'
               ),
            '3.1.0')
        return

    # The option should not be autoloaded, because it is not needed in most
    # cases. Emphasis should be put on using the 'uninstall.php' way of
    # uninstalling the plugin.
    uninstallable_plugins = Php.Array(WiO.get_option('uninstall_plugins'))
    uninstallable_plugins[plugin_basename(File)] = callback

    WiO.update_option('uninstall_plugins', uninstallable_plugins)
Ejemplo n.º 7
0
def get_the_category_list( separator = '', parents='', post_id = False ):
  ''' Retrieve category list in either HTML list or custom format.
  @global WP_Rewrite wp_rewrite
  @param string separator Optional, default is empty string. Separator for between the categories.
  @param string parents Optional. How to display the parents.
  @param int post_id Optional. Post ID to retrieve categories.
  @return string
  '''
  wp_rewrite = WpC.WB.Wj.wp_rewrite  # global wp_rewrite
  if not is_object_in_taxonomy( get_post_type( post_id ), 'category' ):
    # This filter is documented in wp-includes/category-template.php
    return WiPg.apply_filters( 'the_category', '', separator, parents )

  # Filters the categories before building the category list.
  # @param array    categories An array of the post's categories.
  # @param int|bool post_id    ID of the post we're retrieving categories for. When `False`, we assume the
  #                             current post in the loop.
  categories = WiPg.apply_filters( 'the_category_list', get_the_category( post_id ), post_id )

  if Php.empty( categories ):
    # This filter is documented in wp-includes/category-template.php
    return WiPg.apply_filters( 'the_category', __( 'Uncategorized' ), separator, parents )

  rel = 'rel="category tag"' if ( Php.is_object( wp_rewrite ) and wp_rewrite.using_permalinks() ) else 'rel="category"'

  thelist = ''
  if '' == separator:
    thelist += '<ul class="post-categories">'
    for category in categories:
      thelist += "\n\t<li>"
      #switch ( strtolower( parents ) ) {
      ParentsLower = Php.strtolower( parents )
      if   ParentsLower == 'multiple':
        if category.parent:
          thelist += get_category_parents( category.parent, True, separator )
        thelist += '<a href="' + esc_url( get_category_link( category.term_id ) ) + '" ' + rel + '>' + category.name +'</a></li>'
      elif ParentsLower == 'single':
        thelist += '<a href="' + esc_url( get_category_link( category.term_id ) ) + '"  ' + rel + '>'
        if category.parent:
          thelist += get_category_parents( category.parent, False, separator )
        thelist += category.name +'</a></li>'
      #if  ParentsLower == '':
      else:
        thelist += '<a href="' + esc_url( get_category_link( category.term_id ) ) + '" ' + rel + '>' + category.name +'</a></li>'

    thelist += '</ul>'
  else:
    i = 0
    for category in categories:
      if 0 < i:
        thelist += separator
      #switch ( strtolower( parents ) ) {
      ParentsLower = Php.strtolower( parents )
      if   ParentsLower == 'multiple':
        if category.parent:
          thelist += get_category_parents( category.parent, True, separator )
        thelist += '<a href="' + esc_url( get_category_link( category.term_id ) ) + '" ' + rel + '>' + category.name +'</a>'
      elif ParentsLower == 'single':
        thelist += '<a href="' + esc_url( get_category_link( category.term_id ) ) + '" ' + rel  +'>'
        if category.parent:
          thelist += get_category_parents( category.parent, False, separator )
        thelist += category.name +"</a>"
      #if  ParentsLower == '':
      else:
        thelist += '<a href="' + esc_url( get_category_link( category.term_id ) ) + '" ' + rel + '>' + category.name +'</a>'
      i += 1

  # Filters the category or list of categories.
  # @param array  thelist   List of categories for the current post.
  # @param string separator Separator used between the categories.
  # @param string parents   How to display the category parents. Accepts 'multiple',
  #                          'single', or empty.
  return WiPg.apply_filters( 'the_category', thelist, separator, parents )
Ejemplo n.º 8
0
def _wp_filter_build_unique_id(tag, function, priority, Wj=None):
    ''' Build Unique ID for storage and retrieval.
  The old way to serialize the callback caused issues and this function is the
  solution. It works by checking for objects and creating a new property in
  the class to keep track of the object and new objects of the same class that
  need to be added.
  It also allows for the removal of actions and filters for objects after they
  change class properties. It is possible to include the property wp_filter_id
  in your class and set it to "None" or a number to bypass the workaround.
  However this will prevent you from adding new classes and any new classes
  will overwrite the previous hook by the same class.
  Functions and static method callbacks are just returned as strings and
  shouldn't have any speed penalty.
  @link https://core.trac.wordpress.org/ticket/3875
  @global array wp_filter Storage for all of the filters and actions.
  @staticvar int filter_id_count
  @param string   tag      Used in counting how many hooks were applied
  @param callable function Used for creating unique id
  @param int|bool priority Used in counting how many hooks were applied. If === False
                            and function is an object reference, we return the unique
                            id only if it already has one, False otherwise.
  @return string|False Unique ID for usage as array key or False if priority === False
                       and function is an object reference, and it does not already have
                       a unique id.
  '''
    #global var==>WpC.WB.Wj.var, except: var=WpC.WB.Wj.var=same Obj,mutable array
    if Wj is None:
        Wj = WpC.WB.Wj
    wp_filter = Wj.wp_filter  # global wp_filter
    #static filter_id_count = 0

    if Php.is_string(function):
        return function

    if Php.is_object(function):
        # Closures are currently implemented as objects
        function = array(function, '')
    else:
        function = Php.Array(function)

    if Php.is_object(function[0]):
        # Object Class Calling
        if Php.function_exists('spl_object_hash'):
            return spl_object_hash(function[0]) + function[1]
        else:
            obj_idx = get_class(function[0]).function[1]
            if not Php.isset(function[0], 'wp_filter_id'):
                if priority is False:
                    return False
                obj_idx += (len(Php.Array(wp_filter[tag][priority]))
                            if Php.isset(wp_filter[tag], priority) else
                            _wp_filter_build_unique_id.filter_id_count)
                function[
                    0].wp_filter_id = _wp_filter_build_unique_id.filter_id_count
                _wp_filter_build_unique_id.filter_id_count += 1
            else:
                obj_idx += function[0].wp_filter_id

            return obj_idx

    elif Php.is_string(function[0]):
        # Static Calling
        return function[0] + '::' + function[1]
Ejemplo n.º 9
0
def do_action(tag, arg='', *OtherArgs, Wj=None):
    ''' Execute functions hooked on a specific action hook.
  This function invokes all functions attached to action hook `tag`. It is
  possible to create new action hooks by simply calling this function,
  specifying the name of the new hook using the `tag` parameter.
  You can pass extra arguments to the hooks, much like you can with apply_filters().
  @global array wp_filter         Stores all of the filters
  @global array wp_actions        Increments the amount of times action was triggered.
  @global array merged_filters    Merges the filter hooks using this function.
  @global array wp_current_filter Stores the list of current filters with the current one last
  @param string tag     The name of the action to be executed.
  @param mixed  arg,... Optional. Additional arguments which are passed on to the
                         functions hooked to the action. Default empty.
  '''
    #global var==>WpC.WB.Wj.var, except: var=WpC.WB.Wj.var=same Obj,mutable array
    if Wj is None:
        Wj = WpC.WB.Wj
    wp_filter = Wj.wp_filter  # global wp_filter
    wp_actions = Wj.wp_actions  # global wp_actions
    merged_filters = Wj.merged_filters  # global merged_filters
    wp_current_filter = Wj.wp_current_filter  # global wp_current_filter

    AllArgs = tag, arg, *OtherArgs

    if not Php.isset(wp_actions, tag):
        wp_actions[tag] = 1
    else:
        wp_actions[tag] += 1

    # Do 'all' actions first
    if Php.isset(wp_filter, 'all'):
        wp_current_filter.append(tag)
        # php2python.com/wiki/function.func-get-args/
        all_args = Php.func_get_args(AllArgs)
        _wp_call_all_hook(all_args)

    if not Php.isset(wp_filter, tag):
        if Php.isset(wp_filter, 'all'):
            wp_current_filter.popitem()
        return

    if not Php.isset(wp_filter, 'all'):
        wp_current_filter.append(tag)

    args = array()
    # 1 == len(arg) #implies: isset(arg[0])
    if Php.is_array(arg) and 1 == len(arg) and Php.is_object(
            arg[0]):  # array(&this)
        #args.append(& arg[0])    # & <<== Check!!  # & not needed for object?
        args.append(arg[0])
    else:
        args.append(arg)
    #for ( a = 2, num = func_num_args(); a < num; a++ )
    for a in range(2, Php.func_num_args(AllArgs)):
        args[None] = Php.func_get_arg(AllArgs, a)  # differ from func_get_args

    # Sort
    if not Php.isset(merged_filters, tag):
        wp_filter[tag] = Php.ksort(wp_filter[tag])
        merged_filters[tag] = True

    # No need to reset in py since for loop alawys starts at elem#1 in list
    #reset( wp_filter[ tag ] )

    #do {
    #Php: the first iteration of a do-while loop is guaranteed to run
    #    (the truth expression is only checked at the end of the iteration)
    for Tag in [True, *wp_filter[tag]]:
        if Tag is False:
            break
        for the_ in Php.Array(Php.current(wp_filter[tag])):
            if not Php.is_null(the_['function']):
                Php.call_user_func_array(
                    the_['function'],
                    Php.array_slice(args, 0, int(the_['accepted_args'])))

    #} while ( next(wp_filter[tag]) is not False )

    wp_current_filter.popitem()