function cat_rows( $parent = 0, $level = 0, $categories = 0 ) {
	if ( !$categories ) {
		$args = array('hide_empty' => 0);
		if ( !empty($_GET['s']) )
			$args['search'] = $_GET['s'];
		$categories = get_categories( $args );
	}

	$children = _get_term_hierarchy('category');

	if ( $categories ) {
		ob_start();
		foreach ( $categories as $category ) {
			if ( $category->parent == $parent) {
				echo "\t" . _cat_row( $category, $level );
				if ( isset($children[$category->term_id]) )
					cat_rows( $category->term_id, $level +1, $categories );
			}
		}
		$output = ob_get_contents();
		ob_end_clean();

		$output = apply_filters('cat_rows', $output);

		echo $output;
	} else {
		return false;
	}
}
/**
 * {@internal Missing Short Description}}
 *
 * @since unknown
 *
 * @param unknown_type $categories
 * @param unknown_type $count
 * @param unknown_type $parent
 * @param unknown_type $level
 * @param unknown_type $page
 * @param unknown_type $per_page
 * @return unknown
 */
function _cat_rows( $categories, &$count, $parent = 0, $level = 0, $page = 1, $per_page = 20 ) {
	if ( empty($categories) ) {
		$args = array('hide_empty' => 0);
		if ( !empty($_GET['s']) )
			$args['search'] = $_GET['s'];
		$categories = get_categories( $args );
	}

	if ( !$categories )
		return false;

	$children = _get_term_hierarchy('category');

	$start = ($page - 1) * $per_page;
	$end = $start + $per_page;
	$i = -1;
	ob_start();
	foreach ( $categories as $category ) {
		if ( $count >= $end )
			break;

		$i++;

		if ( $category->parent != $parent )
			continue;

		// If the page starts in a subtree, print the parents.
		if ( $count == $start && $category->parent > 0 ) {
			$my_parents = array();
			while ( $my_parent) {
				$my_parent = get_category($my_parent);
				$my_parents[] = $my_parent;
				if ( !$my_parent->parent )
					break;
				$my_parent = $my_parent->parent;
			}
			$num_parents = count($my_parents);
			while( $my_parent = array_pop($my_parents) ) {
				echo "\t" . _cat_row( $my_parent, $level - $num_parents );
				$num_parents--;
			}
		}

		if ( $count >= $start )
			echo "\t" . _cat_row( $category, $level );

		unset($categories[$i]); // Prune the working set
		$count++;

		if ( isset($children[$category->term_id]) )
			_cat_rows( $categories, $count, $category->term_id, $level + 1, $page, $per_page );

	}

	$output = ob_get_contents();
	ob_end_clean();

	echo $output;
}
function vp_flush_regenerable_options()
{
    wp_cache_flush();
    $taxonomies = get_taxonomies();
    foreach ($taxonomies as $taxonomy) {
        delete_option("{$taxonomy}_children");
        // Regenerate {$taxonomy}_children
        _get_term_hierarchy($taxonomy);
    }
}
 /**
  * Performs post-import cleanup of files and the cache
  */
 function import_end()
 {
     wp_import_cleanup($this->id);
     wp_cache_flush();
     foreach (get_taxonomies() as $tax) {
         delete_option("{$tax}_children");
         _get_term_hierarchy($tax);
     }
     wp_defer_term_counting(false);
     wp_defer_comment_counting(false);
     do_action('import_end');
 }
 public function import_end()
 {
     wp_cache_flush();
     foreach (get_taxonomies() as $tax) {
         delete_option("{$tax}_children");
         _get_term_hierarchy($tax);
     }
     wp_defer_term_counting(false);
     wp_defer_comment_counting(false);
     echo '<p>' . __('All done.', 'wordpress-importer') . ' <a href="' . admin_url() . '">' . __('Have fun!', 'wordpress-importer') . '</a>' . '</p>';
     echo '<p>' . __('Remember to update the passwords and roles of imported users.', 'wordpress-importer') . '</p>';
     do_action('import_end');
 }
Exemplo n.º 6
0
 /**
  * @ticket 30335
  */
 public function test_should_rebuild_split_term_taxonomy_hierarchy()
 {
     global $wpdb;
     register_taxonomy('wptests_tax_3', 'post');
     register_taxonomy('wptests_tax_4', 'post', array('hierarchical' => true));
     $t1 = wp_insert_term('Foo1', 'wptests_tax_3');
     $t2 = wp_insert_term('Foo1 Parent', 'wptests_tax_4');
     $t3 = wp_insert_term('Foo1', 'wptests_tax_4', array('parent' => $t2['term_id']));
     // Manually modify because shared terms shouldn't naturally occur.
     $wpdb->update($wpdb->term_taxonomy, array('term_id' => $t1['term_id']), array('term_taxonomy_id' => $t3['term_taxonomy_id']), array('%d'), array('%d'));
     $th = _get_term_hierarchy('wptests_tax_4');
     $new_term_id = _split_shared_term($t1['term_id'], $t3['term_taxonomy_id']);
     $t2_children = get_term_children($t2['term_id'], 'wptests_tax_4');
     $this->assertEquals(array($new_term_id), $t2_children);
 }
Exemplo n.º 7
0
/**
 * {@internal Missing Short Description}}
 *
 * @since unknown
 *
 * @param unknown_type $parent
 * @param unknown_type $level
 * @param unknown_type $categories
 * @param unknown_type $page
 * @param unknown_type $per_page
 */
function cat_rows($parent = 0, $level = 0, $categories = 0, $page = 1, $per_page = 20)
{
    $count = 0;
    if (empty($categories)) {
        $args = array('hide_empty' => 0);
        if (!empty($_GET['s'])) {
            $args['search'] = $_GET['s'];
        }
        $categories = get_categories($args);
        if (empty($categories)) {
            return false;
        }
    }
    $children = _get_term_hierarchy('category');
    _cat_rows($parent, $level, $categories, $children, $page, $per_page, $count);
}
Exemplo n.º 8
0
/**
 * Add new variation set via AJAX.
 *
 * If the variation set name is the same as an existing variation set,
 * the children variant terms will be added inside that existing set.
 * @since 3.8.8
 */
function wpsc_add_variation_set()
{
    $new_variation_set = $_POST['variation_set'];
    $variants = preg_split('/\\s*,\\s*/', $_POST['variants']);
    $parent_term_exists = term_exists($new_variation_set, 'wpsc-variation');
    // only use an existing parent ID if the term is not a child term
    if ($parent_term_exists) {
        $parent_term = get_term($parent_term_exists['term_id'], 'wpsc-variation');
        if ($parent_term->parent == '0') {
            $variation_set_id = $parent_term_exists['term_id'];
        }
    }
    if (empty($variation_set_id)) {
        $results = wp_insert_term($new_variation_set, 'wpsc-variation');
        if (is_wp_error($results)) {
            die('-1');
        }
        $variation_set_id = $results['term_id'];
    }
    $inserted_variants = array();
    if (!empty($variation_set_id)) {
        foreach ($variants as $variant) {
            $results = wp_insert_term($variant, 'wpsc-variation', array('parent' => $variation_set_id));
            if (is_wp_error($results)) {
                die('-1');
            }
            $inserted_variants[] = $results['term_id'];
        }
        require_once 'includes/walker-variation-checklist.php';
        /* --- DIRTY HACK START --- */
        /*
        There's a bug with term cache in WordPress core. See http://core.trac.wordpress.org/ticket/14485.
        The next 3 lines will delete children term cache for wpsc-variation.
        Without this hack, the new child variations won't be displayed on "Variations" page and
        also won't be displayed in wp_terms_checklist() call below.
        */
        clean_term_cache($variation_set_id, 'wpsc-variation');
        delete_option('wpsc-variation_children');
        wp_cache_set('last_changed', 1, 'terms');
        _get_term_hierarchy('wpsc-variation');
        /* --- DIRTY HACK END --- */
        wp_terms_checklist((int) $_POST['post_id'], array('taxonomy' => 'wpsc-variation', 'descendants_and_self' => $variation_set_id, 'walker' => new WPSC_Walker_Variation_Checklist($inserted_variants), 'checked_ontop' => false));
    }
    exit;
}
Exemplo n.º 9
0
 /**
  * @ticket 14485
  */
 function test_hierachy_invalidation()
 {
     $tax = 'burrito';
     register_taxonomy($tax, 'post', array('hierarchical' => true));
     $this->assertTrue(get_taxonomy($tax)->hierarchical);
     $step = 1;
     $parent_id = 0;
     $children = 0;
     foreach (range(1, 9) as $i) {
         switch ($step) {
             case 1:
                 $parent = wp_insert_term('Parent' . $i, $tax);
                 $parent_id = $parent['term_id'];
                 break;
             case 2:
                 $parent = wp_insert_term('Child' . $i, $tax, array('parent' => $parent_id));
                 $parent_id = $parent['term_id'];
                 $children++;
                 break;
             case 3:
                 wp_insert_term('Grandchild' . $i, $tax, array('parent' => $parent_id));
                 $parent_id = 0;
                 $children++;
                 break;
         }
         $terms = get_terms($tax, array('hide_empty' => false));
         $this->assertEquals($i, count($terms));
         if ($i > 1) {
             $hierarchy = _get_term_hierarchy($tax);
             $this->assertNotEmpty($hierarchy);
             $this->assertEquals($children, count($hierarchy, COUNT_RECURSIVE) - count($hierarchy));
         }
         if ($i % 3 === 0) {
             $step = 1;
         } else {
             $step++;
         }
     }
     _unregister_taxonomy($tax);
 }
 /**
  * Extended get_terms public static function support
  * - Limit category
  * - Limit days
  * - Selection restrict
  * - Min usage
  *
  * @param string|array $taxonomies
  * @param string $args
  * @return array
  */
 public static function getTerms($taxonomies, $args = '')
 {
     global $wpdb;
     $empty_array = array();
     $join_relation = false;
     $single_taxonomy = false;
     if (!is_array($taxonomies)) {
         $single_taxonomy = true;
         $taxonomies = array($taxonomies);
     }
     foreach ((array) $taxonomies as $taxonomy) {
         if (!taxonomy_exists($taxonomy)) {
             $error = new WP_Error('invalid_taxonomy', __('Invalid Taxonomy'));
             return $error;
         }
     }
     $in_taxonomies = "'" . implode("', '", $taxonomies) . "'";
     $defaults = array('orderby' => 'name', 'order' => 'ASC', 'hide_empty' => true, 'exclude' => array(), 'exclude_tree' => array(), 'include' => array(), 'number' => '', 'fields' => 'all', 'slug' => '', 'parent' => '', 'hierarchical' => true, 'child_of' => 0, 'get' => '', 'name__like' => '', 'pad_counts' => false, 'offset' => '', 'search' => '', 'limit_days' => 0, 'category' => 0, 'min_usage' => 0, 'st_name__like' => '');
     $args = wp_parse_args($args, $defaults);
     // Translate selection order
     $args['orderby'] = self::compatOldOrder($args['selectionby'], 'orderby');
     $args['order'] = self::compatOldOrder($args['selection'], 'order');
     $args['number'] = absint($args['number']);
     $args['offset'] = absint($args['offset']);
     $args['limit_days'] = absint($args['limit_days']);
     $args['min_usage'] = absint($args['min_usage']);
     if (!$single_taxonomy || !is_taxonomy_hierarchical($taxonomies[0]) || '' !== $args['parent']) {
         $args['child_of'] = 0;
         $args['hierarchical'] = false;
         $args['pad_counts'] = false;
     }
     if ('all' == $args['get']) {
         $args['child_of'] = 0;
         $args['hide_empty'] = 0;
         $args['hierarchical'] = false;
         $args['pad_counts'] = false;
     }
     extract($args, EXTR_SKIP);
     if ($child_of) {
         $hierarchy = _get_term_hierarchy($taxonomies[0]);
         if (!isset($hierarchy[$child_of])) {
             return $empty_array;
         }
     }
     if ($parent) {
         $hierarchy = _get_term_hierarchy($taxonomies[0]);
         if (!isset($hierarchy[$parent])) {
             return $empty_array;
         }
     }
     // $args can be whatever, only use the args defined in defaults to compute the key
     $filter_key = has_filter('list_terms_exclusions') ? serialize($GLOBALS['wp_filter']['list_terms_exclusions']) : '';
     $key = md5(serialize(compact(array_keys($defaults))) . serialize($taxonomies) . $filter_key);
     $last_changed = wp_cache_get('last_changed', 's-terms');
     if (!$last_changed) {
         $last_changed = time();
         wp_cache_set('last_changed', $last_changed, 's-terms');
     }
     $cache_key = "get_terms:{$key}:{$last_changed}";
     $cache = wp_cache_get($cache_key, 's-terms');
     if (false !== $cache) {
         $cache = apply_filters('get_terms', $cache, $taxonomies, $args);
         return $cache;
     }
     $_orderby = strtolower($orderby);
     if ('count' == $_orderby) {
         $orderby = 'tt.count';
     }
     if ('random' == $_orderby) {
         $orderby = 'RAND()';
     } else {
         if ('name' == $_orderby) {
             $orderby = 't.name';
         } else {
             if ('slug' == $_orderby) {
                 $orderby = 't.slug';
             } else {
                 if ('term_group' == $_orderby) {
                     $orderby = 't.term_group';
                 } elseif (empty($_orderby) || 'id' == $_orderby) {
                     $orderby = 't.term_id';
                 }
             }
         }
     }
     $orderby = apply_filters('get_terms_orderby', $orderby, $args);
     if (!empty($orderby)) {
         $orderby = "ORDER BY {$orderby}";
     } else {
         $order = '';
     }
     $where = '';
     $inclusions = '';
     if (!empty($include)) {
         $exclude = '';
         $exclude_tree = '';
         $interms = wp_parse_id_list($include);
         foreach ($interms as $interm) {
             if (empty($inclusions)) {
                 $inclusions = ' AND ( t.term_id = ' . intval($interm) . ' ';
             } else {
                 $inclusions .= ' OR t.term_id = ' . intval($interm) . ' ';
             }
         }
     }
     if (!empty($inclusions)) {
         $inclusions .= ')';
     }
     $where .= $inclusions;
     $exclusions = '';
     if (!empty($exclude_tree)) {
         $excluded_trunks = wp_parse_id_list($exclude_tree);
         foreach ($excluded_trunks as $extrunk) {
             $excluded_children = (array) get_terms($taxonomies[0], array('child_of' => intval($extrunk), 'fields' => 'ids'));
             $excluded_children[] = $extrunk;
             foreach ($excluded_children as $exterm) {
                 if (empty($exclusions)) {
                     $exclusions = ' AND ( t.term_id <> ' . intval($exterm) . ' ';
                 } else {
                     $exclusions .= ' AND t.term_id <> ' . intval($exterm) . ' ';
                 }
             }
         }
     }
     if (!empty($exclude)) {
         $exterms = wp_parse_id_list($exclude);
         foreach ($exterms as $exterm) {
             if (empty($exclusions)) {
                 $exclusions = ' AND ( t.term_id <> ' . intval($exterm) . ' ';
             } else {
                 $exclusions .= ' AND t.term_id <> ' . intval($exterm) . ' ';
             }
         }
     }
     if (!empty($exclusions)) {
         $exclusions .= ')';
     }
     $exclusions = apply_filters('list_terms_exclusions', $exclusions, $args);
     $where .= $exclusions;
     // ST Features : Restrict category
     if ($category != 0) {
         if (!is_array($taxonomies)) {
             $taxonomies = array($taxonomies);
         }
         $incategories = wp_parse_id_list($category);
         $taxonomies = "'" . implode("', '", $taxonomies) . "'";
         $incategories = "'" . implode("', '", $incategories) . "'";
         $where .= " AND tr.object_id IN ( ";
         $where .= "SELECT tr.object_id FROM {$wpdb->term_relationships} AS tr INNER JOIN {$wpdb->term_taxonomy} AS tt ON tr.term_taxonomy_id = tt.term_taxonomy_id INNER JOIN {$wpdb->posts} as p ON tr.object_id=p.ID WHERE tt.term_id IN ({$incategories}) AND p.post_status='publish'";
         $where .= " ) ";
         $join_relation = true;
         unset($incategories, $category);
     }
     // ST Features : Limit posts date
     if ($limit_days != 0) {
         $where .= " AND tr.object_id IN ( ";
         $where .= "SELECT DISTINCT ID FROM {$wpdb->posts} AS p WHERE p.post_status='publish' AND " . (is_page_have_tags() ? "p.post_type IN('page', 'post')" : "post_type = 'post'") . " AND p.post_date_gmt > '" . date('Y-m-d H:i:s', time() - $limit_days * 86400) . "'";
         $where .= " ) ";
         $join_relation = true;
         unset($limit_days);
     }
     if (!empty($slug)) {
         $slug = sanitize_title($slug);
         $where .= " AND t.slug = '{$slug}'";
     }
     if (!empty($name__like)) {
         $where .= " AND t.name LIKE '{$name__like}%'";
     }
     if ('' !== $parent) {
         $parent = (int) $parent;
         $where .= " AND tt.parent = '{$parent}'";
     }
     // ST Features : Another way to search
     if (strpos($st_name__like, ' ') !== false) {
         $st_terms_formatted = array();
         $st_terms = preg_split('/[\\s,]+/', $st_name_like);
         foreach ((array) $st_terms as $st_term) {
             if (empty($st_term)) {
                 continue;
             }
             $st_terms_formatted[] = "t.name LIKE '%" . like_escape($st_term) . "%'";
         }
         $where .= " AND ( " . explode(' OR ', $st_terms_formatted) . " ) ";
         unset($st_term, $st_terms_formatted, $st_terms);
     } elseif (!empty($st_name__like)) {
         $where .= " AND t.name LIKE '%{$st_name__like}%'";
     }
     // ST Features : Add min usage
     if ($hide_empty && !$hierarchical) {
         if ($min_usage == 0) {
             $where .= ' AND tt.count > 0';
         } else {
             $where .= $wpdb->prepare(' AND tt.count >= %d', $min_usage);
         }
     }
     // don't limit the query results when we have to descend the family tree
     if (!empty($number) && !$hierarchical && empty($child_of) && '' === $parent) {
         if ($offset) {
             $limit = 'LIMIT ' . $offset . ',' . $number;
         } else {
             $limit = 'LIMIT ' . $number;
         }
     } else {
         $limit = '';
     }
     if (!empty($search)) {
         $search = like_escape($search);
         $where .= " AND (t.name LIKE '%{$search}%')";
     }
     $selects = array();
     switch ($fields) {
         case 'all':
             $selects = array('t.*', 'tt.*');
             break;
         case 'ids':
         case 'id=>parent':
             $selects = array('t.term_id', 'tt.parent', 'tt.count');
             break;
         case 'names':
             $selects = array('t.term_id', 'tt.parent', 'tt.count', 't.name');
             break;
         case 'count':
             $orderby = '';
             $order = '';
             $selects = array('COUNT(*)');
     }
     $select_this = implode(', ', apply_filters('get_terms_fields', $selects, $args));
     // Add inner to relation table ?
     $join_relation = $join_relation == false ? '' : "INNER JOIN {$wpdb->term_relationships} AS tr ON tt.term_taxonomy_id = tr.term_taxonomy_id";
     $query = "SELECT {$select_this}\r\n\t\t\tFROM {$wpdb->terms} AS t\r\n\t\t\tINNER JOIN {$wpdb->term_taxonomy} AS tt ON t.term_id = tt.term_id\r\n\t\t\t{$join_relation}\r\n\t\t\tWHERE tt.taxonomy IN ({$in_taxonomies})\r\n\t\t\t{$where}\r\n\t\t\t{$orderby} {$order}\r\n\t\t\t{$limit}";
     // GROUP BY t.term_id
     if ('count' == $fields) {
         $term_count = $wpdb->get_var($query);
         return $term_count;
     }
     $terms = $wpdb->get_results($query);
     if ('all' == $fields) {
         update_term_cache($terms);
     }
     if (empty($terms)) {
         wp_cache_add($cache_key, array(), 's-terms');
         $terms = apply_filters('get_terms', array(), $taxonomies, $args);
         return $terms;
     }
     if ($child_of) {
         $children = _get_term_hierarchy($taxonomies[0]);
         if (!empty($children)) {
             $terms =& _get_term_children($child_of, $terms, $taxonomies[0]);
         }
     }
     // Update term counts to include children.
     if ($pad_counts && 'all' == $fields) {
         _pad_term_counts($terms, $taxonomies[0]);
     }
     // Make sure we show empty categories that have children.
     if ($hierarchical && $hide_empty && is_array($terms)) {
         foreach ($terms as $k => $term) {
             if (!$term->count) {
                 $children = _get_term_children($term->term_id, $terms, $taxonomies[0]);
                 if (is_array($children)) {
                     foreach ($children as $child) {
                         if ($child->count) {
                             continue 2;
                         }
                     }
                 }
                 // It really is empty
                 unset($terms[$k]);
             }
         }
     }
     reset($terms);
     $_terms = array();
     if ('id=>parent' == $fields) {
         while ($term = array_shift($terms)) {
             $_terms[$term->term_id] = $term->parent;
         }
         $terms = $_terms;
     } elseif ('ids' == $fields) {
         while ($term = array_shift($terms)) {
             $_terms[] = $term->term_id;
         }
         $terms = $_terms;
     } elseif ('names' == $fields) {
         while ($term = array_shift($terms)) {
             $_terms[] = $term->name;
         }
         $terms = $_terms;
     }
     if (0 < $number && intval(@count($terms)) > $number) {
         $terms = array_slice($terms, $offset, $number);
     }
     wp_cache_add($cache_key, $terms, 's-terms');
     $terms = apply_filters('get_terms', $terms, $taxonomies, $args);
     return $terms;
 }
Exemplo n.º 11
0
 private static function Categories_box(&$data, $parent = 0, $level = 0, $categories = 0)
 {
     if (!$categories) {
         $categories = get_categories(array('hide_empty' => 0));
     }
     if (function_exists('_get_category_hierarchy')) {
         $children = _get_category_hierarchy();
     } elseif (function_exists('_get_term_hierarchy')) {
         $children = _get_term_hierarchy('category');
     } else {
         $children = array();
     }
     if ($categories) {
         ob_start();
         foreach ($categories as $category) {
             if ($category->parent == $parent) {
                 echo "\t" . self::_wpe_edit_cat_row($category, $level, $data);
                 if (isset($children[$category->term_id])) {
                     self::Categories_box($data, $category->term_id, $level + 1, $categories);
                 }
             }
         }
         $output = ob_get_contents();
         ob_end_clean();
         echo $output;
     } else {
         return false;
     }
 }
Exemplo n.º 12
0
function cherry_plugin_import_end()
{
    wp_cache_flush();
    foreach (get_taxonomies() as $tax) {
        delete_option("{$tax}_children");
        _get_term_hierarchy($tax);
    }
    wp_defer_term_counting(false);
    wp_defer_comment_counting(false);
    update_option('cherry_sample_data', 1);
    cherry_plugin_set_to_draft('hello-world');
    cherry_plugin_set_to_draft('sample-page');
    settings();
    do_action('cherry_plugin_import_end');
    session_name("import_xml");
    session_destroy();
    exit('import_json');
}
 function display_rows_or_placeholder()
 {
     global $taxonomy;
     $args = wp_parse_args($this->callback_args, array('page' => 1, 'number' => 20, 'search' => '', 'hide_empty' => 0));
     extract($args, EXTR_SKIP);
     $args['offset'] = $offset = ($page - 1) * $number;
     // convert it to table rows
     $out = '';
     $count = 0;
     $terms = array();
     if (is_taxonomy_hierarchical($taxonomy) && !isset($orderby)) {
         // We'll need the full set of terms then.
         $args['number'] = $args['offset'] = 0;
         $terms = get_terms($taxonomy, $args);
         if (!empty($search)) {
             // Ignore children on searches.
             $children = array();
         } else {
             $children = _get_term_hierarchy($taxonomy);
         }
         // Some funky recursion to get the job done( Paging & parents mainly ) is contained within, Skip it for non-hierarchical taxonomies for performance sake
         $out .= $this->_rows($taxonomy, $terms, $children, $offset, $number, $count);
     } else {
         $terms = get_terms($taxonomy, $args);
         foreach ($terms as $term) {
             $out .= $this->single_row($term, 0, $taxonomy);
         }
         $count = $number;
         // Only displaying a single page.
     }
     if (empty($terms)) {
         list($columns, $hidden) = $this->get_column_info();
         echo '<tr class="no-items"><td class="colspanchange" colspan="' . $this->get_column_count() . '">';
         $this->no_items();
         echo '</td></tr>';
     } else {
         echo $out;
     }
 }
Exemplo n.º 14
0
/**
 * Add count of children to parent count.
 *
 * Recalculates term counts by including items from child terms. Assumes all
 * relevant children are already in the $terms argument.
 *
 * @access private
 * @since 2.3.0
 *
 * @global wpdb $wpdb WordPress database abstraction object.
 *
 * @param array  $terms    List of term IDs, passed by reference.
 * @param string $taxonomy Term context.
 */
function _pad_term_counts(&$terms, $taxonomy)
{
    global $wpdb;
    // This function only works for hierarchical taxonomies like post categories.
    if (!is_taxonomy_hierarchical($taxonomy)) {
        return;
    }
    $term_hier = _get_term_hierarchy($taxonomy);
    if (empty($term_hier)) {
        return;
    }
    $term_items = array();
    $terms_by_id = array();
    $term_ids = array();
    foreach ((array) $terms as $key => $term) {
        $terms_by_id[$term->term_id] =& $terms[$key];
        $term_ids[$term->term_taxonomy_id] = $term->term_id;
    }
    // Get the object and term ids and stick them in a lookup table.
    $tax_obj = get_taxonomy($taxonomy);
    $object_types = esc_sql($tax_obj->object_type);
    $results = $wpdb->get_results("SELECT object_id, term_taxonomy_id FROM {$wpdb->term_relationships} INNER JOIN {$wpdb->posts} ON object_id = ID WHERE term_taxonomy_id IN (" . implode(',', array_keys($term_ids)) . ") AND post_type IN ('" . implode("', '", $object_types) . "') AND post_status = 'publish'");
    foreach ($results as $row) {
        $id = $term_ids[$row->term_taxonomy_id];
        $term_items[$id][$row->object_id] = isset($term_items[$id][$row->object_id]) ? ++$term_items[$id][$row->object_id] : 1;
    }
    // Touch every ancestor's lookup row for each post in each term.
    foreach ($term_ids as $term_id) {
        $child = $term_id;
        $ancestors = array();
        while (!empty($terms_by_id[$child]) && ($parent = $terms_by_id[$child]->parent)) {
            $ancestors[] = $child;
            if (!empty($term_items[$term_id])) {
                foreach ($term_items[$term_id] as $item_id => $touches) {
                    $term_items[$parent][$item_id] = isset($term_items[$parent][$item_id]) ? ++$term_items[$parent][$item_id] : 1;
                }
            }
            $child = $parent;
            if (in_array($parent, $ancestors)) {
                break;
            }
        }
    }
    // Transfer the touched cells.
    foreach ((array) $term_items as $id => $items) {
        if (isset($terms_by_id[$id])) {
            $terms_by_id[$id]->count = count($items);
        }
    }
}
Exemplo n.º 15
0
	/**
	 * Extended get_terms function support
	 * - Limit category
	 * - Limit days
	 * - Selection restrict
	 * - Min usage
	 *
	 * @param string|array $taxonomies
	 * @param string $args
	 * @return array
	 */
	function getTerms( $taxonomies, $args = '', $skip_cache = false, $internal_st = false ) {
		global $wpdb;
		$empty_array = array();

		$single_taxonomy = false;
		if ( !is_array($taxonomies) ) {
			$single_taxonomy = true;
			$taxonomies = array($taxonomies);
		}

		foreach ( $taxonomies as $taxonomy ) {
			if ( ! is_taxonomy($taxonomy) ) {
				return new WP_Error('invalid_taxonomy', __('Invalid Taxonomy'));
			}
		}

		$in_taxonomies = "'" . implode("', '", $taxonomies) . "'";

		$defaults = array(
			'orderby' => 'name',
			'order' => 'ASC',
			'cloud_selection' => 'count-desc',
			'hide_empty' => true,
			'exclude' => '',
			'include' => '',
			'number' => '',
			'fields' => 'all',
			'slug' => '',
			'parent' => '',
			'hierarchical' => true,
			'child_of' => 0,
			'get' => '',
			'name__like' => '',
			'st_name_like' => '',
			'pad_counts' => false,
			'offset' => '',
			'search' => '',
			'limit_days' => 0,
			'category' => 0,
			'min_usage' => 0
		);

		$args = wp_parse_args( $args, $defaults );
		if ( $internal_st != true ) { // Allow limit :)
			$args['number'] = absint( $args['number'] );
		}
		$args['offset'] = absint( $args['offset'] );
		if ( !$single_taxonomy || !is_taxonomy_hierarchical($taxonomies[0]) || '' != $args['parent'] ) {
			$args['child_of'] = 0;
			$args['hierarchical'] = false;
			$args['pad_counts'] = false;
		}

		if ( 'all' == $args['get'] ) {
			$args['child_of'] = 0;
			$args['hide_empty'] = 0;
			$args['hierarchical'] = false;
			$args['pad_counts'] = false;
		}
		extract($args, EXTR_SKIP);

		if ( $child_of ) {
			$hierarchy = _get_term_hierarchy($taxonomies[0]);
			if ( !isset($hierarchy[$child_of]) )
				return $empty_array;
		}

		if ( $parent ) {
			$hierarchy = _get_term_hierarchy($taxonomies[0]);
			if ( !isset($hierarchy[$parent]) )
				return $empty_array;
		}
		
		if ( $skip_cache != true ) {
			// $args can be whatever, only use the args defined in defaults to compute the key
			$filter_key = ( has_filter('list_terms_exclusions') ) ? serialize($GLOBALS['wp_filter']['list_terms_exclusions']) : '';
			$key = md5( serialize( compact(array_keys($defaults)) ) . serialize( $taxonomies ) . $filter_key );
			$last_changed = wp_cache_get('last_changed', 'terms');
			if ( !$last_changed ) {
			    $last_changed = time();
			    wp_cache_set('last_changed', $last_changed, 'terms');
			}
			$cache_key = "get_terms:$key:$last_changed";
			
			if ( $cache = wp_cache_get( $cache_key, 'terms' ) ) {
			    $terms = apply_filters('get_terms', $cache, $taxonomies, $args);
			    return $terms;
			}
		}

		// Restrict category
		$category_sql = '';
		if ( !empty($category) && $category != '0' ) {
			$incategories = preg_split('/[\s,]+/', $category);

			$objects_id = get_objects_in_term( $incategories, 'category' );
			$objects_id = array_unique ($objects_id); // to be sure haven't duplicates

			if ( empty($objects_id) ) { // No posts for this category = no tags for this category
				return array();
			}

			foreach ( (array) $objects_id as $object_id ) {
				$category_sql .= "'". $object_id . "', ";
			}

			$category_sql = substr($category_sql, 0, strlen($category_sql) - 2); // Remove latest ", "
			$category_sql = 'AND p.ID IN ('.$category_sql.')';
		}

		// count-asc/count-desc/name-asc/name-desc/random
		$cloud_selection = strtolower($cloud_selection);
		switch ( $cloud_selection ) {
			case 'count-asc':
				$order_by = 'tt.count ASC';
				break;
			case 'random':
				$order_by = 'RAND()';
				break;
			case 'name-asc':
				$order_by = 't.name ASC';
				break;
			case 'name-desc':
				$order_by = 't.name DESC';
				break;
			default: // count-desc
			$order_by = 'tt.count DESC';
			break;
		}

		// Min usage
		$restict_usage = '';
		$min_usage = (int) $min_usage;
		if ( $min_usage != 0 ) {
			$restict_usage = ' AND tt.count >= '. $min_usage;
		}

		$where = '';
		$inclusions = '';
		if ( !empty($include) ) {
			$exclude = '';
			$interms = preg_split('/[\s,]+/',$include);
			foreach ( (array) $interms as $interm ) {
				if (empty($inclusions)) {
					$inclusions = ' AND ( t.term_id = ' . intval($interm) . ' ';
				} else {
					$inclusions .= ' OR t.term_id = ' . intval($interm) . ' ';
				}
			}
		}

		if ( !empty($inclusions) ) {
			$inclusions .= ')';
		}
		$where .= $inclusions;

		$exclusions = '';
		if ( !empty($exclude) ) {
			$exterms = preg_split('/[\s,]+/',$exclude);
			foreach ( (array) $exterms as $exterm ) {
				if (empty($exclusions)) {
					$exclusions = ' AND ( t.term_id <> ' . intval($exterm) . ' ';
				} else {
					$exclusions .= ' AND t.term_id <> ' . intval($exterm) . ' ';
				}
			}
		}

		if ( !empty($exclusions) ) {
			$exclusions .= ')';
		}
		$exclusions = apply_filters('list_terms_exclusions', $exclusions, $args );
		$where .= $exclusions;

		if ( !empty($slug) ) {
			$slug = sanitize_title($slug);
			$where .= " AND t.slug = '$slug'";
		}

		if ( !empty($name__like) ) {
			$where .= " AND t.name LIKE '{$name__like}%'";
		}

		if ( strpos($st_name_like, ' ') != false || strpos($st_name_like, ' ') != null ) {
			$tmp = '';
			$sts = explode(' ', $st_name_like);
			foreach ( (array) $sts as $st ) {
				if ( empty($st) )
				continue;

				$st = addslashes_gpc($st);
				$tmp .= " t.name LIKE '%{$st}%' OR ";
			}
			// Remove latest OR
			$tmp = substr( $tmp, 0, strlen($tmp) - 4);

			$where .= " AND ( $tmp ) ";
			unset($tmp)	;
		} elseif ( !empty($st_name_like) ) {
			$where .= " AND t.name LIKE '%{$st_name_like}%'";
		}

		if ( '' != $parent ) {
			$parent = (int) $parent;
			$where .= " AND tt.parent = '$parent'";
		}

		if ( $hide_empty && !$hierarchical ) {
			$where .= ' AND tt.count > 0';
		}

		$number_sql = '';
		if ( strpos($number, ',') != false || strpos($number, ',') != null ) {
			$number_sql = $number;
		} else {
			$number = (int) $number;
			if ( $number != 0 ) {
				$number_sql = 'LIMIT ' . $number;
			}
		}

		if ( !empty($search) ) {
			$search = like_escape($search);
			$where .= " AND (t.name LIKE '%$search%')";
		}

		$select_this = '';

		if ( 'all' == $fields ) {
			$select_this = 't.*, tt.*';
		} else if ( 'ids' == $fields ) {
 	        $select_this = 't.term_id, tt.parent, tt.count';
		} else if ( 'names' == $fields ) {
			$select_this = 't.term_id, tt.parent, tt.count, t.name';
		}

		// Limit posts date
		$limitdays_sql = '';
		$limit_days = (int) $limit_days;
		if ( $limit_days != 0 ) {
			$limitdays_sql = 'AND p.post_date_gmt > "' .date( 'Y-m-d H:i:s', time() - $limit_days * 86400 ). '"';
		}

		$query = "SELECT {$select_this}
			FROM {$wpdb->terms} AS t
			INNER JOIN {$wpdb->term_taxonomy} AS tt ON t.term_id = tt.term_id
			INNER JOIN {$wpdb->term_relationships} AS tr ON tt.term_taxonomy_id = tr.term_taxonomy_id
			INNER JOIN {$wpdb->posts} AS p ON tr.object_id = p.ID
			WHERE tt.taxonomy IN ( {$in_taxonomies} )
			AND p.post_date_gmt < '".current_time('mysql')."'
			{$limitdays_sql}
			{$category_sql}
			{$where}
			{$restict_usage}
			GROUP BY t.term_id
			ORDER BY {$order_by}
			{$number_sql}";
		
		if ( 'all' == $fields ) {
			$terms = $wpdb->get_results($query);
			if ( $skip_cache != true ) {
				update_term_cache($terms);
			}
		} else if ( ('ids' == $fields) || ('names' == $fields) ) {
			$terms = $wpdb->get_results($query);
		}

		if ( empty($terms) ) {
			$cache[ $key ] = array();
			wp_cache_set( 'get_terms', $cache, 'terms' );
			$terms = apply_filters('get_terms', array(), $taxonomies, $args);
			return $terms;
		}

		if ( $child_of ) {
		    $children = _get_term_hierarchy($taxonomies[0]);
		    if ( ! empty($children) )
		        $terms = & _get_term_children($child_of, $terms, $taxonomies[0]);
		}

		// Update term counts to include children.
 	    if ( $pad_counts && 'all' == $fields )
	        _pad_term_counts($terms, $taxonomies[0]);

		// Make sure we show empty categories that have children.
		if ( $hierarchical && $hide_empty && is_array($terms) ) {
		    foreach ( $terms as $k => $term ) {
		        if ( ! $term->count ) {
		            $children = _get_term_children($term->term_id, $terms, $taxonomies[0]);
		            if( is_array($children) )
		                foreach ( $children as $child )
		                    if ( $child->count )
		                        continue 2;
		
		            // It really is empty
		            unset($terms[$k]);
		        }
		    }
		}
		reset ( $terms );
		
		$_terms = array();
		if ( 'ids' == $fields ) {
		    while ( $term = array_shift($terms) )
		        $_terms[] = $term->term_id;
		    $terms = $_terms;
		} elseif ( 'names' == $fields ) {
		    while ( $term = array_shift($terms) )
		        $_terms[] = $term->name;
		    $terms = $_terms;
		}
		
		if ( $skip_cache != true ) {
			wp_cache_add( $cache_key, $terms, 'terms' );
		}

		$terms = apply_filters('get_terms', $terms, $taxonomies, $args);
		return $terms;
	}
 * These are the main WPSC Admin functions
 *
 * @package wp-e-commerce
 * @since 3.8
 */
global $wpdb, $wp_version;
$show_update_page = 1;
// if there's nothing in the children variation cache, refresh it, just to make sure.
if (0 == count(get_option('wpsc-variation_children'))) {
    delete_option('wpsc-variation_children');
    _get_term_hierarchy('wpsc-variation');
}
// if there's nothing in the children variation cache, refresh it, just to make sure.
if (0 == count(get_option('wpsc_product_category_children'))) {
    delete_option('wpsc_product_category_children');
    _get_term_hierarchy('wpsc_product_category_children');
}
$wpsc_version = get_option('wpsc_version', '0');
// If database is already updated, then no need to update
if (!get_option('wpsc_needs_update', false)) {
    $show_update_page = 0;
} else {
    $table_exists = $wpdb->get_var("SHOW TABLES LIKE '" . WPSC_TABLE_PRODUCT_LIST . "'");
    $product_count = empty($table_exists) ? 0 : $wpdb->get_var("SELECT COUNT(*) FROM " . WPSC_TABLE_PRODUCT_LIST);
    if ($product_count > 0) {
        function wpsc_display_update_notice()
        {
            echo "<div id='wpsc-warning' class='error fade'><p><strong>" . __('WP eCommerce is almost ready.', 'wpsc') . "</strong> " . sprintf(__('You must <a href="%1$s">update your database</a> to import all of your products.', 'wpsc'), "admin.php?page=wpsc-update") . "</p></div>";
        }
        if (!isset($_GET['page']) || $_GET['page'] != 'wpsc-update') {
            add_action('admin_notices', 'wpsc_display_update_notice');
Exemplo n.º 17
0
function force_flush_term_cache($taxonomy = 'category')
{
    if (!taxonomy_exists($taxonomy)) {
        return FALSE;
    }
    wp_cache_set('last_changed', time() - 1800, 'terms');
    wp_cache_delete('all_ids', $taxonomy);
    wp_cache_delete('get', $taxonomy);
    delete_option("{$taxonomy}_children");
    _get_term_hierarchy($taxonomy);
    return TRUE;
}
Exemplo n.º 18
0
    function convert_categories()
    {
        global $wpdb;
        if ((!isset($_POST['cats_to_convert']) || !is_array($_POST['cats_to_convert'])) && empty($this->categories_to_convert)) {
            ?>
			<div class="narrow">
			<p><?php 
            printf(__('Uh, oh. Something didn&#8217;t work. Please <a href="%s">try again</a>.'), 'admin.php?import=wp-cat2tag');
            ?>
</p>
			</div>
<?php 
            return;
        }
        if (empty($this->categories_to_convert)) {
            $this->categories_to_convert = $_POST['cats_to_convert'];
        }
        $hier = _get_term_hierarchy('category');
        $hybrid_cats = $clear_parents = $parents = false;
        $clean_term_cache = $clean_cat_cache = array();
        $default_cat = get_option('default_category');
        echo '<ul>';
        foreach ((array) $this->categories_to_convert as $cat_id) {
            $cat_id = (int) $cat_id;
            if (!$this->_category_exists($cat_id)) {
                echo '<li>' . sprintf(__('Category %s doesn\'t exist!'), $cat_id) . "</li>\n";
            } else {
                $category =& get_category($cat_id);
                echo '<li>' . sprintf(__('Converting category <strong>%s</strong> ... '), $category->name);
                // If the category is the default, leave category in place and create tag.
                if ($default_cat == $category->term_id) {
                    if (!($id = is_term($category->slug, 'post_tag'))) {
                        $id = wp_insert_term($category->name, 'post_tag', array('slug' => $category->slug));
                    }
                    $id = $id['term_taxonomy_id'];
                    $posts = get_objects_in_term($category->term_id, 'category');
                    $term_order = 0;
                    foreach ($posts as $post) {
                        $values[] = $wpdb->prepare("(%d, %d, %d)", $post, $id, $term_order);
                        clean_post_cache($post);
                    }
                    if ($values) {
                        $wpdb->query("INSERT INTO {$wpdb->term_relationships} (object_id, term_taxonomy_id, term_order) VALUES " . join(',', $values) . " ON DUPLICATE KEY UPDATE term_order = VALUES(term_order)");
                        $wpdb->query($wpdb->prepare("UPDATE {$wpdb->term_taxonomy} SET count = %d WHERE term_id = %d AND taxonomy = 'post_tag'", $category->count, $category->term_id));
                    }
                    echo __('Converted successfully.') . "</li>\n";
                    continue;
                }
                // if tag already exists, add it to all posts in the category
                if ($tag_ttid = $wpdb->get_var($wpdb->prepare("SELECT term_taxonomy_id FROM {$wpdb->term_taxonomy} WHERE term_id = %d AND taxonomy = 'post_tag'", $category->term_id))) {
                    $objects_ids = get_objects_in_term($category->term_id, 'category');
                    $tag_ttid = (int) $tag_ttid;
                    $term_order = 0;
                    foreach ($objects_ids as $object_id) {
                        $values[] = $wpdb->prepare("(%d, %d, %d)", $object_id, $tag_ttid, $term_order);
                    }
                    if ($values) {
                        $wpdb->query("INSERT INTO {$wpdb->term_relationships} (object_id, term_taxonomy_id, term_order) VALUES " . join(',', $values) . " ON DUPLICATE KEY UPDATE term_order = VALUES(term_order)");
                        $count = $wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM {$wpdb->term_relationships} WHERE term_taxonomy_id = %d", $tag_ttid));
                        $wpdb->query($wpdb->prepare("UPDATE {$wpdb->term_taxonomy} SET count = %d WHERE term_id = %d AND taxonomy = 'post_tag'", $count, $category->term_id));
                    }
                    echo __('Tag added to all posts in this category.') . " *</li>\n";
                    $hybrid_cats = true;
                    $clean_term_cache[] = $category->term_id;
                    $clean_cat_cache[] = $category->term_id;
                    continue;
                }
                $tt_ids = $wpdb->get_col($wpdb->prepare("SELECT term_taxonomy_id FROM {$wpdb->term_taxonomy} WHERE term_id = %d AND taxonomy = 'category'", $category->term_id));
                if ($tt_ids) {
                    $posts = $wpdb->get_col("SELECT object_id FROM {$wpdb->term_relationships} WHERE term_taxonomy_id IN (" . join(',', $tt_ids) . ") GROUP BY object_id");
                    foreach ((array) $posts as $post) {
                        clean_post_cache($post);
                    }
                }
                // Change the category to a tag.
                $wpdb->query($wpdb->prepare("UPDATE {$wpdb->term_taxonomy} SET taxonomy = 'post_tag' WHERE term_id = %d AND taxonomy = 'category'", $category->term_id));
                // Set all parents to 0 (root-level) if their parent was the converted tag
                $parents = $wpdb->query($wpdb->prepare("UPDATE {$wpdb->term_taxonomy} SET parent = 0 WHERE parent = %d AND taxonomy = 'category'", $category->term_id));
                if ($parents) {
                    $clear_parents = true;
                }
                $clean_cat_cache[] = $category->term_id;
                echo __('Converted successfully.') . "</li>\n";
            }
        }
        echo '</ul>';
        if (!empty($clean_term_cache)) {
            $clean_term_cache = array_unique(array_values($clean_term_cache));
            foreach ($clean_term_cache as $id) {
                wp_cache_delete($id, 'post_tag');
            }
        }
        if (!empty($clean_cat_cache)) {
            $clean_cat_cache = array_unique(array_values($clean_cat_cache));
            foreach ($clean_cat_cache as $id) {
                wp_cache_delete($id, 'category');
            }
        }
        if ($clear_parents) {
            delete_option('category_children');
        }
        if ($hybrid_cats) {
            echo '<p>' . sprintf(__('* This category is also a tag. The converter has added that tag to all posts currently in the category. If you want to remove it, please confirm that all tags were added successfully, then delete it from the <a href="%s">Manage Categories</a> page.'), 'categories.php') . '</p>';
        }
        echo '<p>' . sprintf(__('We&#8217;re all done here, but you can always <a href="%s">convert more</a>.'), 'admin.php?import=wp-cat2tag') . '</p>';
    }
 /**
  * Performs post-import cleanup of files and the cache
  */
 protected function import_end()
 {
     // Re-enable stuff in core
     wp_suspend_cache_invalidation(false);
     wp_cache_flush();
     foreach (get_taxonomies() as $tax) {
         delete_option("{$tax}_children");
         _get_term_hierarchy($tax);
     }
     wp_defer_term_counting(false);
     wp_defer_comment_counting(false);
     /**
      * Complete the import.
      *
      * Fires after the import process has finished. If you need to update
      * your cache or re-enable processing, do so here.
      */
     do_action('import_end');
 }
Exemplo n.º 20
0
/**
 * _pad_term_counts() - Add count of children to parent count
 *
 * Recalculates term counts by including items from child terms.
 * Assumes all relevant children are already in the $terms argument
 *
 * @package WordPress
 * @subpackage Taxonomy
 * @access private
 * @since 2.3
 * @uses $wpdb
 *
 * @param array $terms List of Term IDs
 * @param string $taxonomy Term Context
 * @return null Will break from function if conditions are not met.
 */
function _pad_term_counts(&$terms, $taxonomy) {
	global $wpdb;

	// This function only works for post categories.
	if ( 'category' != $taxonomy )
		return;

	$term_hier = _get_term_hierarchy($taxonomy);

	if ( empty($term_hier) )
		return;

	$term_items = array();

	foreach ( $terms as $key => $term ) {
		$terms_by_id[$term->term_id] = & $terms[$key];
		$term_ids[$term->term_taxonomy_id] = $term->term_id;
	}

	// Get the object and term ids and stick them in a lookup table
	$results = $wpdb->get_results("SELECT object_id, term_taxonomy_id FROM $wpdb->term_relationships INNER JOIN $wpdb->posts ON object_id = ID WHERE term_taxonomy_id IN (".join(',', array_keys($term_ids)).") AND post_type = 'post' AND post_status = 'publish'");
	foreach ( $results as $row ) {
		$id = $term_ids[$row->term_taxonomy_id];
		++$term_items[$id][$row->object_id];
	}

	// Touch every ancestor's lookup row for each post in each term
	foreach ( $term_ids as $term_id ) {
		$child = $term_id;
		while ( $parent = $terms_by_id[$child]->parent ) {
			if ( !empty($term_items[$term_id]) )
				foreach ( $term_items[$term_id] as $item_id => $touches )
					++$term_items[$parent][$item_id];
			$child = $parent;
		}
	}

	// Transfer the touched cells
	foreach ( (array) $term_items as $id => $items )
		if ( isset($terms_by_id[$id]) )
			$terms_by_id[$id]->count = count($items);
}
Exemplo n.º 21
0
 /**
  * Get terms, based on query_vars.
  *
  * @param 4.6.0
  * @access public
  *
  * @global wpdb $wpdb WordPress database abstraction object.
  *
  * @return array
  */
 public function get_terms()
 {
     global $wpdb;
     $this->parse_query($this->query_vars);
     $args = $this->query_vars;
     // Set up meta_query so it's available to 'pre_get_terms'.
     $this->meta_query = new WP_Meta_Query();
     $this->meta_query->parse_query_vars($args);
     /**
      * Fires before terms are retrieved.
      *
      * @since 4.6.0
      *
      * @param WP_Term_Query $this Current instance of WP_Term_Query.
      */
     do_action('pre_get_terms', $this);
     $taxonomies = $args['taxonomy'];
     // Save queries by not crawling the tree in the case of multiple taxes or a flat tax.
     $has_hierarchical_tax = false;
     if ($taxonomies) {
         foreach ($taxonomies as $_tax) {
             if (is_taxonomy_hierarchical($_tax)) {
                 $has_hierarchical_tax = true;
             }
         }
     }
     if (!$has_hierarchical_tax) {
         $args['hierarchical'] = false;
         $args['pad_counts'] = false;
     }
     // 'parent' overrides 'child_of'.
     if (0 < 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.
      *
      * @since 3.1.0
      *
      * @param array $args       An array of get_terms() arguments.
      * @param array $taxonomies An array of taxonomies.
      */
     $args = apply_filters('get_terms_args', $args, $taxonomies);
     // 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;
     } elseif ($parent) {
         $_parent = $parent;
     } else {
         $_parent = false;
     }
     if ($_parent) {
         $in_hierarchy = false;
         foreach ($taxonomies as $_tax) {
             $hierarchy = _get_term_hierarchy($_tax);
             if (isset($hierarchy[$_parent])) {
                 $in_hierarchy = true;
             }
         }
         if (!$in_hierarchy) {
             return array();
         }
     }
     $orderby = $this->parse_orderby($this->query_vars['orderby']);
     $order = $this->parse_order($this->query_vars['order']);
     if ($taxonomies) {
         $this->sql_clauses['where']['taxonomy'] = "tt.taxonomy IN ('" . implode("', '", array_map('esc_sql', $taxonomies)) . "')";
     }
     $exclude = $args['exclude'];
     $exclude_tree = $args['exclude_tree'];
     $include = $args['include'];
     $inclusions = '';
     if (!empty($include)) {
         $exclude = '';
         $exclude_tree = '';
         $inclusions = implode(',', wp_parse_id_list($include));
     }
     if (!empty($inclusions)) {
         $this->sql_clauses['where']['inclusions'] = 't.term_id IN ( ' . $inclusions . ' )';
     }
     $exclusions = array();
     if (!empty($exclude_tree)) {
         $exclude_tree = wp_parse_id_list($exclude_tree);
         $excluded_children = $exclude_tree;
         foreach ($exclude_tree as $extrunk) {
             $excluded_children = array_merge($excluded_children, (array) get_terms($taxonomies[0], array('child_of' => intval($extrunk), 'fields' => 'ids', 'hide_empty' => 0)));
         }
         $exclusions = array_merge($excluded_children, $exclusions);
     }
     if (!empty($exclude)) {
         $exclusions = array_merge(wp_parse_id_list($exclude), $exclusions);
     }
     // 'childless' terms are those without an entry in the flattened term hierarchy.
     $childless = (bool) $args['childless'];
     if ($childless) {
         foreach ($taxonomies as $_tax) {
             $term_hierarchy = _get_term_hierarchy($_tax);
             $exclusions = array_merge(array_keys($term_hierarchy), $exclusions);
         }
     }
     if (!empty($exclusions)) {
         $exclusions = 't.term_id NOT IN (' . implode(',', array_map('intval', $exclusions)) . ')';
     } else {
         $exclusions = '';
     }
     /**
      * Filters the terms to exclude from the terms query.
      *
      * @since 2.3.0
      *
      * @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 = apply_filters('list_terms_exclusions', $exclusions, $args, $taxonomies);
     if (!empty($exclusions)) {
         // Must do string manipulation here for backward compatibility with filter.
         $this->sql_clauses['where']['exclusions'] = preg_replace('/^\\s*AND\\s*/', '', $exclusions);
     }
     if (!empty($args['name'])) {
         $names = (array) $args['name'];
         foreach ($names as &$_name) {
             // `sanitize_term_field()` returns slashed data.
             $_name = stripslashes(sanitize_term_field('name', $_name, 0, reset($taxonomies), 'db'));
         }
         $this->sql_clauses['where']['name'] = "t.name IN ('" . implode("', '", array_map('esc_sql', $names)) . "')";
     }
     if (!empty($args['slug'])) {
         if (is_array($args['slug'])) {
             $slug = array_map('sanitize_title', $args['slug']);
             $this->sql_clauses['where']['slug'] = "t.slug IN ('" . implode("', '", $slug) . "')";
         } else {
             $slug = sanitize_title($args['slug']);
             $this->sql_clauses['where']['slug'] = "t.slug = '{$slug}'";
         }
     }
     if (!empty($args['term_taxonomy_id'])) {
         if (is_array($args['term_taxonomy_id'])) {
             $tt_ids = implode(',', array_map('intval', $args['term_taxonomy_id']));
             $this->sql_clauses['where']['term_taxonomy_id'] = "tt.term_taxonomy_id IN ({$tt_ids})";
         } else {
             $this->sql_clauses['where']['term_taxonomy_id'] = $wpdb->prepare("tt.term_taxonomy_id = %d", $args['term_taxonomy_id']);
         }
     }
     if (!empty($args['name__like'])) {
         $this->sql_clauses['where']['name__like'] = $wpdb->prepare("t.name LIKE %s", '%' . $wpdb->esc_like($args['name__like']) . '%');
     }
     if (!empty($args['description__like'])) {
         $this->sql_clauses['where']['description__like'] = $wpdb->prepare("tt.description LIKE %s", '%' . $wpdb->esc_like($args['description__like']) . '%');
     }
     if ('' !== $parent) {
         $parent = (int) $parent;
         $this->sql_clauses['where']['parent'] = "tt.parent = '{$parent}'";
     }
     $hierarchical = $args['hierarchical'];
     if ('count' == $args['fields']) {
         $hierarchical = false;
     }
     if ($args['hide_empty'] && !$hierarchical) {
         $this->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 && !$hierarchical && !$child_of && '' === $parent) {
         if ($offset) {
             $limits = 'LIMIT ' . $offset . ',' . $number;
         } else {
             $limits = 'LIMIT ' . $number;
         }
     } else {
         $limits = '';
     }
     if (!empty($args['search'])) {
         $this->sql_clauses['where']['search'] = $this->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.
     $this->meta_query->parse_query_vars($this->query_vars);
     $mq_sql = $this->meta_query->get_sql('term', 't', 'term_id');
     $meta_clauses = $this->meta_query->get_clauses();
     if (!empty($meta_clauses)) {
         $join .= $mq_sql['join'];
         $this->sql_clauses['where']['meta_query'] = preg_replace('/^\\s*AND\\s*/', '', $mq_sql['where']);
         $distinct .= "DISTINCT";
     }
     $selects = array();
     switch ($args['fields']) {
         case 'all':
             $selects = array('t.*', 'tt.*');
             break;
         case 'ids':
         case 'id=>parent':
             $selects = array('t.term_id', 'tt.parent', 'tt.count', 'tt.taxonomy');
             break;
         case 'names':
             $selects = array('t.term_id', 'tt.parent', 'tt.count', 't.name', 'tt.taxonomy');
             break;
         case 'count':
             $orderby = '';
             $order = '';
             $selects = array('COUNT(*)');
             break;
         case 'id=>name':
             $selects = array('t.term_id', 't.name', 'tt.count', 'tt.taxonomy');
             break;
         case 'id=>slug':
             $selects = array('t.term_id', 't.slug', 'tt.count', 'tt.taxonomy');
             break;
     }
     $_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.
      *
      * @since 2.8.0
      *
      * @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 = implode(', ', apply_filters('get_terms_fields', $selects, $args, $taxonomies));
     $join .= " INNER JOIN {$wpdb->term_taxonomy} AS tt ON t.term_id = tt.term_id";
     $where = implode(' AND ', $this->sql_clauses['where']);
     $pieces = array('fields', 'join', 'where', 'distinct', 'orderby', 'order', 'limits');
     /**
      * Filters the terms query SQL clauses.
      *
      * @since 3.1.0
      *
      * @param array $pieces     Terms query SQL clauses.
      * @param array $taxonomies An array of taxonomies.
      * @param array $args       An array of terms query arguments.
      */
     $clauses = apply_filters('terms_clauses', compact($pieces), $taxonomies, $args);
     $fields = isset($clauses['fields']) ? $clauses['fields'] : '';
     $join = isset($clauses['join']) ? $clauses['join'] : '';
     $where = isset($clauses['where']) ? $clauses['where'] : '';
     $distinct = isset($clauses['distinct']) ? $clauses['distinct'] : '';
     $orderby = isset($clauses['orderby']) ? $clauses['orderby'] : '';
     $order = isset($clauses['order']) ? $clauses['order'] : '';
     $limits = isset($clauses['limits']) ? $clauses['limits'] : '';
     if ($where) {
         $where = "WHERE {$where}";
     }
     $this->sql_clauses['select'] = "SELECT {$distinct} {$fields}";
     $this->sql_clauses['from'] = "FROM {$wpdb->terms} AS t {$join}";
     $this->sql_clauses['orderby'] = $orderby ? "ORDER BY {$orderby} {$order}" : '';
     $this->sql_clauses['limits'] = $limits;
     $this->request = "{$this->sql_clauses['select']} {$this->sql_clauses['from']} {$where} {$this->sql_clauses['orderby']} {$this->sql_clauses['limits']}";
     // $args can be anything. Only use the args defined in defaults to compute the key.
     $key = md5(serialize(wp_array_slice_assoc($args, array_keys($this->query_var_defaults))) . serialize($taxonomies) . $this->request);
     $last_changed = wp_cache_get('last_changed', 'terms');
     if (!$last_changed) {
         $last_changed = microtime();
         wp_cache_set('last_changed', $last_changed, 'terms');
     }
     $cache_key = "get_terms:{$key}:{$last_changed}";
     $cache = wp_cache_get($cache_key, 'terms');
     if (false !== $cache) {
         if ('all' === $_fields) {
             $cache = array_map('get_term', $cache);
         }
         return $cache;
     }
     if ('count' == $_fields) {
         return $wpdb->get_var($this->request);
     }
     $terms = $wpdb->get_results($this->request);
     if ('all' == $_fields) {
         update_term_cache($terms);
     }
     // Prime termmeta cache.
     if ($args['update_term_meta_cache']) {
         $term_ids = wp_list_pluck($terms, 'term_id');
         update_termmeta_cache($term_ids);
     }
     if (empty($terms)) {
         wp_cache_add($cache_key, array(), 'terms', DAY_IN_SECONDS);
         return array();
     }
     if ($child_of) {
         foreach ($taxonomies as $_tax) {
             $children = _get_term_hierarchy($_tax);
             if (!empty($children)) {
                 $terms = _get_term_children($child_of, $terms, $_tax);
             }
         }
     }
     // Update term counts to include children.
     if ($args['pad_counts'] && 'all' == $_fields) {
         foreach ($taxonomies as $_tax) {
             _pad_term_counts($terms, $_tax);
         }
     }
     // Make sure we show empty categories that have children.
     if ($hierarchical && $args['hide_empty'] && is_array($terms)) {
         foreach ($terms as $k => $term) {
             if (!$term->count) {
                 $children = get_term_children($term->term_id, $term->taxonomy);
                 if (is_array($children)) {
                     foreach ($children as $child_id) {
                         $child = get_term($child_id, $term->taxonomy);
                         if ($child->count) {
                             continue 2;
                         }
                     }
                 }
                 // It really is empty.
                 unset($terms[$k]);
             }
         }
     }
     $_terms = array();
     if ('id=>parent' == $_fields) {
         foreach ($terms as $term) {
             $_terms[$term->term_id] = $term->parent;
         }
     } elseif ('ids' == $_fields) {
         foreach ($terms as $term) {
             $_terms[] = $term->term_id;
         }
     } elseif ('names' == $_fields) {
         foreach ($terms as $term) {
             $_terms[] = $term->name;
         }
     } elseif ('id=>name' == $_fields) {
         foreach ($terms as $term) {
             $_terms[$term->term_id] = $term->name;
         }
     } elseif ('id=>slug' == $_fields) {
         foreach ($terms as $term) {
             $_terms[$term->term_id] = $term->slug;
         }
     }
     if (!empty($_terms)) {
         $terms = $_terms;
     }
     // Hierarchical queries are not limited, so 'offset' and 'number' must be handled now.
     if ($hierarchical && $number && is_array($terms)) {
         if ($offset >= count($terms)) {
             $terms = array();
         } else {
             $terms = array_slice($terms, $offset, $number, true);
         }
     }
     wp_cache_add($cache_key, $terms, 'terms', DAY_IN_SECONDS);
     if ('all' === $_fields) {
         $terms = array_map('get_term', $terms);
     }
     $this->terms = $terms;
     return $this->terms;
 }
Exemplo n.º 22
0
/**
 * Split all shared taxonomy terms.
 *
 * @since 4.3.0
 */
function split_all_shared_terms()
{
    global $wpdb;
    // Get a list of shared terms (those with more than one associated row in term_taxonomy).
    $shared_terms = $wpdb->get_results("SELECT tt.term_id, t.*, count(*) as term_tt_count FROM {$wpdb->term_taxonomy} tt\n\t\t LEFT JOIN {$wpdb->terms} t ON t.term_id = tt.term_id\n\t\t GROUP BY t.term_id\n\t\t HAVING term_tt_count > 1");
    if (empty($shared_terms)) {
        return;
    }
    // Rekey shared term array for faster lookups.
    $_shared_terms = array();
    foreach ($shared_terms as $shared_term) {
        $term_id = intval($shared_term->term_id);
        $_shared_terms[$term_id] = $shared_term;
    }
    $shared_terms = $_shared_terms;
    // Get term taxonomy data for all shared terms.
    $shared_term_ids = implode(',', array_keys($shared_terms));
    $shared_tts = $wpdb->get_results("SELECT * FROM {$wpdb->term_taxonomy} WHERE `term_id` IN ({$shared_term_ids})");
    // Split term data recording is slow, so we do it just once, outside the loop.
    $suspend = wp_suspend_cache_invalidation(true);
    $split_term_data = get_option('_split_terms', array());
    $skipped_first_term = $taxonomies = array();
    foreach ($shared_tts as $shared_tt) {
        $term_id = intval($shared_tt->term_id);
        // Don't split the first tt belonging to a given term_id.
        if (!isset($skipped_first_term[$term_id])) {
            $skipped_first_term[$term_id] = 1;
            continue;
        }
        if (!isset($split_term_data[$term_id])) {
            $split_term_data[$term_id] = array();
        }
        // Keep track of taxonomies whose hierarchies need flushing.
        if (!isset($taxonomies[$shared_tt->taxonomy])) {
            $taxonomies[$shared_tt->taxonomy] = 1;
        }
        // Split the term.
        $split_term_data[$term_id][$shared_tt->taxonomy] = _split_shared_term($shared_terms[$term_id], $shared_tt, false);
    }
    // Rebuild the cached hierarchy for each affected taxonomy.
    foreach (array_keys($taxonomies) as $tax) {
        delete_option("{$tax}_children");
        _get_term_hierarchy($tax);
    }
    wp_suspend_cache_invalidation($suspend);
    update_option('_split_terms', $split_term_data);
}
Exemplo n.º 23
0
function wpsc_convert_variation_combinations()
{
    global $wpdb, $user_ID, $current_version_number;
    $wpsc_update = WPSC_Update::get_instance();
    remove_filter('get_terms', 'wpsc_get_terms_category_sort_filter');
    if (!($offset = get_transient('wpsc_update_variation_comb_offset'))) {
        $offset = 0;
    }
    $limit = 150;
    wp_defer_term_counting(true);
    $sql = "SELECT * FROM {$wpdb->posts} WHERE post_type = 'wpsc-product' AND post_parent = 0 LIMIT %d, %d";
    $total = $wpdb->get_var("SELECT COUNT(*) FROM {$wpdb->posts} WHERE post_type = 'wpsc-product' AND post_parent = 0");
    $progress = new WPSC_Update_Progress($total);
    while (true) {
        // get the posts
        // I use a direct SQL query here because the get_posts function sometimes does not function for a reason that is not clear.
        $posts = $wpdb->get_results($wpdb->prepare($sql, $offset, $limit));
        $i = $offset;
        if (empty($posts)) {
            break;
        }
        foreach ((array) $posts as $post) {
            if (!($child_products = get_transient('wpsc_update_current_child_products'))) {
                $child_products = array();
            }
            $wpsc_update->check_timeout();
            $base_product_terms = array();
            //create a post template
            $child_product_template = array('post_author' => $user_ID, 'post_content' => $post->post_content, 'post_excerpt' => $post->post_excerpt, 'post_title' => $post->post_title, 'post_status' => 'inherit', 'post_type' => "wpsc-product", 'post_name' => $post->post_title, 'post_parent' => $post->ID);
            // select the original product ID
            $original_id = get_post_meta($post->ID, '_wpsc_original_id', true);
            $parent_stock = get_post_meta($post->ID, '_wpsc_stock', true);
            // select the variation set associations
            $variation_set_associations = $wpdb->get_col("SELECT `variation_id` FROM " . WPSC_TABLE_VARIATION_ASSOC . " WHERE `associated_id` = '{$original_id}'");
            // select the variation associations if the count of variation sets is greater than zero
            if ($original_id > 0 && count($variation_set_associations) > 0) {
                $variation_associations = $wpdb->get_col("SELECT `value_id` FROM " . WPSC_TABLE_VARIATION_VALUES_ASSOC . " WHERE `product_id` = '{$original_id}' AND `variation_id` IN(" . implode(", ", $variation_set_associations) . ") AND `visible` IN ('1')");
            } else {
                // otherwise, we have no active variations, skip to the next product
                $i++;
                $progress->update($i);
                set_transient('wpsc_update_variation_comb_offset', $i, 604800);
                continue;
            }
            $variation_set_id_sql = "SELECT meta_value FROM " . WPSC_TABLE_META . " WHERE object_type='wpsc_variation_set' AND object_id IN (" . implode(',', $variation_set_associations) . ") AND meta_key = 'variation_set_id'";
            $variation_set_terms = $wpdb->get_col($variation_set_id_sql);
            $variation_associations_sql = "SELECT meta_value FROM " . WPSC_TABLE_META . " WHERE object_type='wpsc_variation' AND object_id IN (" . implode(',', $variation_associations) . ") AND meta_key = 'variation_id'";
            $variation_associations_terms = $wpdb->get_col($variation_associations_sql);
            $base_product_terms = array_merge($base_product_terms, $variation_set_terms, $variation_associations_terms);
            // Now that we have the term IDs, we need to retrieve the slugs, as wp_set_object_terms will not use IDs in the way we want
            // If we pass IDs into wp_set_object_terms, it creates terms using the ID as the name.
            $parent_product_terms = get_terms('wpsc-variation', array('hide_empty' => 0, 'include' => implode(",", $base_product_terms), 'orderby' => 'parent'));
            $base_product_term_slugs = array();
            foreach ($parent_product_terms as $parent_product_term) {
                $base_product_term_slugs[] = $parent_product_term->slug;
            }
            wp_set_object_terms($post->ID, $base_product_term_slugs, 'wpsc-variation');
            // select all variation "products"
            $variation_items = $wpdb->get_results("SELECT * FROM " . WPSC_TABLE_VARIATION_PROPERTIES . " WHERE `product_id` = '{$original_id}'");
            foreach ((array) $variation_items as $variation_item) {
                $wpsc_update->check_timeout();
                // initialize the requisite arrays to empty
                $variation_ids = array();
                $term_data = array('ids' => array(), 'slugs' => array(), 'names' => array());
                // make a temporary copy of the product teplate
                $product_values = $child_product_template;
                // select all values this "product" is associated with, then loop through them, getting the term id of the variation using the value ID
                $variation_associations_combinations = $wpdb->get_results("SELECT * FROM " . WPSC_TABLE_VARIATION_COMBINATIONS . " WHERE `priceandstock_id` = '{$variation_item->id}'");
                foreach ((array) $variation_associations_combinations as $association) {
                    $variation_id = (int) wpsc_get_meta($association->value_id, 'variation_id', 'wpsc_variation');
                    // discard any values that are null, as they break the selecting of the terms
                    if ($variation_id > 0 && in_array($association->value_id, $variation_associations)) {
                        $variation_ids[] = $variation_id;
                    }
                }
                // if we have more than zero remaining terms, get the term data, then loop through it to convert it to a more useful set of arrays.
                if (count($variation_ids) > 0 && count($variation_set_associations) == count($variation_ids)) {
                    $combination_terms = get_terms('wpsc-variation', array('hide_empty' => 0, 'include' => implode(",", $variation_ids)));
                    foreach ($combination_terms as $term) {
                        $term_data['ids'][] = $term->term_id;
                        $term_data['slugs'][] = $term->slug;
                        $term_data['names'][] = $term->name;
                    }
                    $product_values['post_title'] .= " (" . implode(", ", $term_data['names']) . ")";
                    $product_values['post_name'] = sanitize_title($product_values['post_title']);
                    $selected_post = get_posts(array('name' => $product_values['post_name'], 'post_parent' => $post->ID, 'post_type' => "wpsc-product", 'post_status' => 'all', 'suppress_filters' => true));
                    $selected_post = array_shift($selected_post);
                    $key = md5($post->ID . ':' . count($term_data['ids']) . ':' . implode(',', $term_data['ids']));
                    $child_product_id = false;
                    if (!empty($child_products[$key])) {
                        $child_product_id = $child_products[$key];
                    }
                    $post_data = array();
                    $post_data['_wpsc_price'] = (double) $variation_item->price;
                    $post_data['_wpsc_stock'] = (double) $variation_item->stock;
                    if (!is_numeric($parent_stock)) {
                        $post_data['_wpsc_stock'] = false;
                    }
                    $post_data['_wpsc_original_variation_id'] = (double) $variation_item->id;
                    // Product Weight
                    $post_data['_wpsc_product_metadata']['weight'] = wpsc_convert_weight($variation_item->weight, $variation_item->weight_unit, "pound", true);
                    $post_data['_wpsc_product_metadata']['display_weight_as'] = $variation_item->weight_unit;
                    $post_data['_wpsc_product_metadata']['weight_unit'] = $variation_item->weight_unit;
                    // Parts of the code (eg wpsc_product_variation_price_from() make the assumption that these meta keys exist
                    $post_data['_wpsc_special_price'] = 0;
                    $post_data['_wpsc_sku'] = '';
                    $already_exists = true;
                    if (!empty($selected_post) && $selected_post->ID != $child_product_id) {
                        $child_product_id = $selected_post->ID;
                    } elseif (empty($child_product_id)) {
                        $child_product_id = wp_insert_post($product_values);
                        $already_exists = false;
                    }
                    if ($child_product_id > 0) {
                        foreach ($post_data as $meta_key => $meta_value) {
                            // prefix all meta keys with _wpsc_
                            update_post_meta($child_product_id, $meta_key, $meta_value);
                        }
                        wp_set_object_terms($child_product_id, $term_data['slugs'], 'wpsc-variation');
                        if (!$already_exists) {
                            $child_products[$key] = $child_product_id;
                            set_transient('wpsc_update_current_child_products', $child_products, 604800);
                        }
                    }
                    unset($term_data);
                }
            }
            $i++;
            $progress->update($i);
            set_transient('wpsc_update_variation_comb_offset', $i, 604800);
            delete_transient('wpsc_update_current_child_products');
        }
        $offset += $limit;
    }
    delete_option("wpsc-variation_children");
    _get_term_hierarchy('wpsc-variation');
    delete_option("wpsc_product_category_children");
    _get_term_hierarchy('wpsc_product_category');
}
Exemplo n.º 24
0
    /**
     * Import processing step (status console)
     */
    public function process($save_history = true)
    {
        $wp_uploads = wp_upload_dir();
        $import = $this->data['update_previous'];
        $history_log = new PMXI_History_Record();
        $input = new PMXI_Input();
        if (!empty(PMXI_Plugin::$session->history_id)) {
            $history_log->getById(PMXI_Plugin::$session->history_id);
        }
        $log_storage = (int) PMXI_Plugin::getInstance()->getOption('log_storage');
        if (!PMXI_Plugin::is_ajax()) {
            $import->set((empty(PMXI_Plugin::$session->source) ? array() : PMXI_Plugin::$session->source) + array('xpath' => PMXI_Plugin::$session->xpath, 'options' => PMXI_Plugin::$session->options, 'count' => PMXI_Plugin::$session->count, 'friendly_name' => PMXI_Plugin::$session->options['friendly_name'], 'feed_type' => PMXI_Plugin::$session->feed_type, 'parent_import_id' => $this->data['update_previous']->isEmpty() ? PMXI_Plugin::$session->parent_import_id : $this->data['update_previous']->parent_import_id, 'queue_chunk_number' => 0, 'triggered' => 0, 'processing' => 0, 'executing' => 1, 'iteration' => !empty($import->iteration) ? $import->iteration : 0))->save();
            if (PMXI_Plugin::$session->action != 'continue') {
                // store import info in database
                $import->set(array('imported' => 0, 'created' => 0, 'updated' => 0, 'skipped' => 0, 'deleted' => 0))->update();
            }
            // add history log
            $custom_type = get_post_type_object($import->options['custom_type']);
            // unlink previous logs
            $by = array();
            $by[] = array(array('import_id' => $import->id, 'type NOT LIKE' => 'trigger'), 'AND');
            $historyLogs = new PMXI_History_List();
            $historyLogs->setColumns('id', 'import_id', 'type', 'date')->getBy($by, 'id ASC');
            if ($historyLogs->count() and $historyLogs->count() >= $log_storage) {
                $logsToRemove = $historyLogs->count() - $log_storage;
                foreach ($historyLogs as $i => $file) {
                    $historyRecord = new PMXI_History_Record();
                    $historyRecord->getBy('id', $file['id']);
                    if (!$historyRecord->isEmpty()) {
                        $historyRecord->delete();
                    }
                    // unlink history file only
                    if ($i == $logsToRemove) {
                        break;
                    }
                }
            }
            $history_log->set(array('import_id' => $import->id, 'date' => date('Y-m-d H:i:s'), 'type' => PMXI_Plugin::$session->action != 'continue' ? 'manual' : 'continue', 'summary' => sprintf(__("%d %ss created %d updated %d deleted %d skipped", "pmxi_plugin"), $import->created, $custom_type->labels->singular_name, $import->updated, $import->deleted, $import->skipped)))->save();
            PMXI_Plugin::$session->set('history_id', $history_log->id);
            foreach (get_taxonomies() as $tax) {
                delete_transient("pmxi_{$tax}_terms");
            }
            do_action('pmxi_before_xml_import', $import->id);
            PMXI_Plugin::$session->set('update_previous', $import->id);
            if (empty($import->options['encoding'])) {
                $currentOptions = $import->options;
                $currentOptions['encoding'] = 'UTF-8';
                $import->set(array('options' => $currentOptions))->update();
            }
            // unlink previous files
            $history = new PMXI_File_List();
            $history->setColumns('id', 'name', 'registered_on', 'path')->getBy(array('import_id' => $import->id), 'id DESC');
            if ($history->count()) {
                foreach ($history as $file) {
                    $history_file_path = wp_all_import_get_absolute_path($file['path']);
                    if (@file_exists($history_file_path) and $history_file_path != PMXI_Plugin::$session->filePath) {
                        if (in_array($import->type, array('upload'))) {
                            wp_all_import_remove_source($history_file_path, false);
                        } else {
                            wp_all_import_remove_source($history_file_path);
                        }
                    }
                    $history_file = new PMXI_File_Record();
                    $history_file->getBy('id', $file['id']);
                    if (!$history_file->isEmpty()) {
                        $history_file->delete();
                    }
                }
            }
            if ($save_history) {
                $history_file = new PMXI_File_Record();
                $history_file->set(array('name' => $import->name, 'import_id' => $import->id, 'path' => wp_all_import_get_relative_path(PMXI_Plugin::$session->filePath), 'registered_on' => date('Y-m-d H:i:s')))->save();
            }
            /*
            	Split file up into 1000 record chunks.			
            	This option will decrease the amount of slowdown experienced at the end of large imports. 
            	The slowdown is partially caused by the need for WP All Import to read deeper and deeper into the file on each successive iteration. 
            	Splitting the file into pieces means that, for example, instead of having to read 19000 records into a 20000 record file when importing the last 1000 records, 
            	WP All Import will just split it into 20 chunks, and then read the last chunk from the beginning.
            */
            if ("ajax" == $import->options['import_processing'] and $import->count > PMXI_Plugin::getInstance()->getOption('large_feed_limit') and $import->options['chuncking']) {
                $chunk_files = array();
                if (!empty(PMXI_Plugin::$session->local_paths)) {
                    $records_count = 0;
                    $chunk_records_count = 0;
                    $feed = "<?xml version=\"1.0\" encoding=\"" . $import->options['encoding'] . "\"?>" . "\n" . "<pmxi_records>";
                    foreach (PMXI_Plugin::$session->local_paths as $key => $path) {
                        $file = new PMXI_Chunk($path, array('element' => $import->root_element, 'encoding' => $import->options['encoding']));
                        // loop through the file until all lines are read
                        while ($xml = $file->read()) {
                            if (!empty($xml)) {
                                PMXI_Import_Record::preprocessXml($xml);
                                $chunk = "<?xml version=\"1.0\" encoding=\"" . $import->options['encoding'] . "\"?>" . "\n" . $xml;
                                $dom = new DOMDocument('1.0', $import->options['encoding']);
                                $old = libxml_use_internal_errors(true);
                                $dom->loadXML($chunk);
                                // FIX: libxml xpath doesn't handle default namespace properly, so remove it upon XML load
                                libxml_use_internal_errors($old);
                                $xpath = new DOMXPath($dom);
                                if ($elements = @$xpath->query($import->xpath) and $elements->length) {
                                    $records_count += $elements->length;
                                    $chunk_records_count += $elements->length;
                                    $feed .= $xml;
                                }
                            }
                            if ($chunk_records_count == PMXI_Plugin::getInstance()->getOption('large_feed_limit') or $records_count == $import->count) {
                                $feed .= "</pmxi_records>";
                                $chunk_file_path = wp_all_import_secure_file($wp_uploads['basedir'] . DIRECTORY_SEPARATOR . PMXI_Plugin::TEMP_DIRECTORY) . DIRECTORY_SEPARATOR . "pmxi_chunk_" . count($chunk_files) . "_" . basename($path);
                                file_put_contents($chunk_file_path, $feed);
                                $chunk_files[] = $chunk_file_path;
                                $chunk_records_count = 0;
                                $feed = "<?xml version=\"1.0\" encoding=\"" . $import->options['encoding'] . "\"?>" . "\n" . "<pmxi_records>";
                            }
                        }
                    }
                    PMXI_Plugin::$session->set('local_paths', $chunk_files);
                }
            }
            PMXI_Plugin::$session->save_data();
            if ($log_storage) {
                $log_file = wp_all_import_secure_file($wp_uploads['basedir'] . DIRECTORY_SEPARATOR . PMXI_Plugin::LOGS_DIRECTORY, $history_log->id) . DIRECTORY_SEPARATOR . $history_log->id . '.html';
                if (PMXI_Plugin::$session->action != 'continue') {
                    if (file_exists($log_file)) {
                        wp_all_import_remove_source($log_file, false);
                    }
                    //@file_put_contents($log_file, sprintf(__('<p>Source path `%s`</p>', 'wp_all_import_plugin'), $import->path));
                }
            }
            $this->data['ajax_processing'] = "ajax" == $import->options['import_processing'] ? true : false;
            $this->render();
            wp_ob_end_flush_all();
            flush();
            @set_time_limit(0);
            $import_id = $input->get('id', 0);
            if ("ajax" == $import->options['import_processing'] and !$import_id) {
                PMXI_Plugin::$session->convertData($import->id);
                //die();
            }
        } elseif (empty($import->id)) {
            $import = new PMXI_Import_Record();
            $import_id = $input->get('id', PMXI_Plugin::$session->update_previous);
            $import->getById($import_id);
        }
        $ajax_processing = "ajax" == $import->options['import_processing'] ? true : false;
        if (PMXI_Plugin::is_ajax() and $ajax_processing and !check_ajax_referer('wp_all_import_secure', 'security', false)) {
            exit(__('Security check', 'wp_all_import_plugin'));
        }
        if ($ajax_processing) {
            $logger = create_function('$m', 'echo "<div class=\\"progress-msg\\">$m</div>\\n"; flush();');
        } else {
            $logger = create_function('$m', 'echo "<div class=\\"progress-msg\\">$m</div>\\n"; if ( "" != strip_tags(wp_all_import_strip_tags_content($m))) { PMXI_Plugin::$session->log .= "<p>".strip_tags(wp_all_import_strip_tags_content($m))."</p>"; flush(); }');
        }
        PMXI_Plugin::$session->set('start_time', empty(PMXI_Plugin::$session->start_time) ? time() : PMXI_Plugin::$session->start_time);
        wp_cache_flush();
        if (PMXI_Plugin::is_ajax() or !$ajax_processing) {
            $iteration_start_time = time();
            if ($log_storage) {
                $log_file = wp_all_import_secure_file($wp_uploads['basedir'] . DIRECTORY_SEPARATOR . PMXI_Plugin::LOGS_DIRECTORY, $history_log->id) . DIRECTORY_SEPARATOR . $history_log->id . '.html';
            }
            if ($ajax_processing) {
                // HTTP headers for no cache etc
                header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
                header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
                header("Cache-Control: no-store, no-cache, must-revalidate");
                header("Cache-Control: post-check=0, pre-check=0", false);
                header("Pragma: no-cache");
            }
            $loop = 0;
            $pointer = 0;
            $records = array();
            if ($import->options['is_import_specified']) {
                foreach (preg_split('% *, *%', $import->options['import_specified'], -1, PREG_SPLIT_NO_EMPTY) as $chank) {
                    if (preg_match('%^(\\d+)-(\\d+)$%', $chank, $mtch)) {
                        $records = array_merge($records, range(intval($mtch[1]), intval($mtch[2])));
                    } else {
                        $records = array_merge($records, array(intval($chank)));
                    }
                }
            }
            $records_to_import = empty($records) ? $import->count : $records[count($records) - 1];
            $failures = $input->get('failures', 0);
            // auto decrease records per iteration option
            if ($failures) {
                $options = $import->options;
                $options['records_per_request'] = ceil($options['records_per_request'] / 2) ? ceil($options['records_per_request'] / 2) : 1;
                $import->set(array('options' => $options))->update();
            }
            $records_per_request = (!$ajax_processing and $import->options['records_per_request'] < 50) ? 50 : $import->options['records_per_request'];
            if (!empty(PMXI_Plugin::$session->local_paths)) {
                $feed = "<?xml version=\"1.0\" encoding=\"" . $import->options['encoding'] . "\"?>" . "\n" . "<pmxi_records>";
                foreach (PMXI_Plugin::$session->local_paths as $key => $path) {
                    $import_done = $import->imported + $import->skipped == $records_to_import ? true : false;
                    if ($import_done) {
                        if (strpos($path, "pmxi_chunk_") !== false and @file_exists($path)) {
                            wp_all_import_remove_source($path, false);
                        }
                        PMXI_Plugin::$session->set('local_paths', array());
                        PMXI_Plugin::$session->save_data();
                        break;
                    }
                    $file = new PMXI_Chunk($path, array('element' => $import->root_element, 'encoding' => $import->options['encoding'], 'pointer' => PMXI_Plugin::$session->pointer, 'filter' => true));
                    // loop through the file until all lines are read
                    while ($xml = $file->read() and empty($import->canceled)) {
                        if (!empty($xml)) {
                            if (!$import->options['chuncking']) {
                                PMXI_Import_Record::preprocessXml($xml);
                            }
                            $chunk = "<?xml version=\"1.0\" encoding=\"" . $import->options['encoding'] . "\"?>" . "\n" . $xml;
                            $dom = new DOMDocument('1.0', $import->options['encoding']);
                            $old = libxml_use_internal_errors(true);
                            $dom->loadXML($chunk);
                            // FIX: libxml xpath doesn't handle default namespace properly, so remove it upon XML load
                            libxml_use_internal_errors($old);
                            $xpath = new DOMXPath($dom);
                            $pointer++;
                            if ($this->data['elements'] = $elements = @$xpath->query($import->xpath) and $elements->length) {
                                /* Merge nested XML/CSV files */
                                /*$nested_files = json_decode($import->options['nested_files'], true);
                                		if ( ! empty($nested_files) and is_array($nested_files)){										
                                			$merger = new PMXI_Nested($dom, $nested_files, $xml, $import->xpath, $elements);
                                			$merger->merge();
                                			$xml = $merger->get_xml();
                                			unset($merger);
                                		}	*/
                                // continue action
                                if ($import->imported + $import->skipped >= PMXI_Plugin::$session->chunk_number + $elements->length - 1) {
                                    PMXI_Plugin::$session->set('chunk_number', PMXI_Plugin::$session->chunk_number + $elements->length);
                                    PMXI_Plugin::$session->save_data();
                                    continue;
                                }
                                if (!$loop and $ajax_processing) {
                                    ob_start();
                                }
                                $feed .= $xml;
                                $loop += $elements->length;
                                $processed_records = $import->imported + $import->skipped;
                                if ($loop == $records_per_request or $processed_records + $loop == $records_to_import or $processed_records == $records_to_import) {
                                    $feed .= "</pmxi_records>";
                                    $import->process($feed, $logger, PMXI_Plugin::$session->chunk_number, false, '/pmxi_records', $loop);
                                    unset($dom, $xpath);
                                    if (!$ajax_processing) {
                                        $feed = "<?xml version=\"1.0\" encoding=\"" . $import->options['encoding'] . "\"?>" . "\n" . "<pmxi_records>";
                                        $loop = 0;
                                    } else {
                                        if (!$history_log->isEmpty()) {
                                            $custom_type = get_post_type_object($import->options['custom_type']);
                                            $history_log->set(array('time_run' => time() - strtotime($history_log->date), 'summary' => sprintf(__("%d %ss created %d updated %d deleted %d skipped", "pmxi_plugin"), $import->created, $custom_type->labels->singular_name, $import->updated, $import->deleted, $import->skipped)))->update();
                                        }
                                        unset($file);
                                        PMXI_Plugin::$session->set('pointer', PMXI_Plugin::$session->pointer + $pointer);
                                        PMXI_Plugin::$session->save_data();
                                        $log_data = ob_get_clean();
                                        if ($log_storage) {
                                            $log = @fopen($log_file, 'a+');
                                            @fwrite($log, $log_data);
                                            @fclose($log);
                                        }
                                        $iteration_execution_time = time() - $iteration_start_time;
                                        wp_send_json(array('imported' => $import->imported, 'created' => $import->created, 'updated' => $import->updated, 'percentage' => ceil($processed_records / $import->count * 100), 'warnings' => PMXI_Plugin::$session->warnings, 'errors' => PMXI_Plugin::$session->errors, 'log' => $log_data, 'done' => false, 'records_per_request' => $import->options['records_per_request']));
                                    }
                                }
                            }
                        }
                    }
                    // Move to the next file, set pointer to first element
                    if ($ajax_processing) {
                        if (strpos($path, "pmxi_chunk_") !== false and @file_exists($path)) {
                            @unlink($path);
                        }
                        PMXI_Plugin::$session->set('pointer', 1);
                        $pointer = 0;
                        $lp = PMXI_Plugin::$session->local_paths;
                        array_shift($lp);
                        PMXI_Plugin::$session->set('local_paths', $lp);
                        PMXI_Plugin::$session->save_data();
                    } else {
                        break;
                    }
                }
            }
        }
        if (PMXI_Plugin::is_ajax() and empty(PMXI_Plugin::$session->local_paths) or !$ajax_processing or !empty($import->canceled)) {
            if ("ajax" != $import->options['import_processing'] and $log_storage) {
                $log_file = wp_all_import_secure_file($wp_uploads['basedir'] . DIRECTORY_SEPARATOR . PMXI_Plugin::LOGS_DIRECTORY, $history_log->id) . DIRECTORY_SEPARATOR . $history_log->id . '.html';
                if (PMXI_Plugin::$session->action != 'continue') {
                    @file_put_contents($log_file, PMXI_Plugin::$session->log);
                } else {
                    $log = @fopen($log_file, 'a+');
                    @fwrite($log, PMXI_Plugin::$session->log);
                    @fclose($log);
                }
            }
            wp_cache_flush();
            foreach (get_taxonomies() as $tax) {
                delete_option("{$tax}_children");
                _get_term_hierarchy($tax);
            }
            $import->set(array('registered_on' => date('Y-m-d H:i:s'), 'executing' => 0))->update();
            // add history log
            $custom_type = get_post_type_object($import->options['custom_type']);
            $history_log->set(array('time_run' => time() - strtotime($history_log->date), 'summary' => sprintf(__("%d %ss created %d updated %d deleted %d skipped", "pmxi_plugin"), $import->created, $custom_type->labels->singular_name, $import->updated, $import->deleted, $import->skipped)))->update();
            // clear import session
            PMXI_Plugin::$session->clean_session($import->id);
            // clear session data (prevent from reimporting the same data on page refresh)
            // [indicate in header process is complete]
            $msg = !empty($import->canceled) ? addcslashes(__('Canceled', 'wp_all_import_plugin'), "\n\r") : addcslashes(__('Complete', 'wp_all_import_plugin'), "\n\r");
            if ($ajax_processing) {
                ob_start();
            }
            do_action('pmxi_after_xml_import', $import->id);
            $import->options['is_import_specified'] and $logger and call_user_func($logger, 'Done');
            echo <<<COMPLETE
<script type="text/javascript">
//<![CDATA[
(function(\$){\t
\t\$('#status').html('{$msg}');\t
\twindow.onbeforeunload = false;
})(jQuery);
//]]>
</script>
COMPLETE;
            // [/indicate in header process is complete]
            if ($ajax_processing) {
                wp_send_json(array('imported' => $import->imported, 'created' => $import->created, 'updated' => $import->updated, 'percentage' => 100, 'warnings' => PMXI_Plugin::$session->warnings, 'errors' => PMXI_Plugin::$session->errors, 'log' => ob_get_clean(), 'done' => true, 'records_per_request' => $import->options['records_per_request']));
            }
        }
    }
Exemplo n.º 25
0
/**
 * Add the class property classes for the current context, if applicable.
 *
 * @access private
 * @since 3.0
 *
 * @param array $menu_items The current menu item objects to which to add the class property information.
 */
function _wp_menu_item_classes_by_context(&$menu_items)
{
    global $wp_query;
    $queried_object = $wp_query->get_queried_object();
    $queried_object_id = (int) $wp_query->queried_object_id;
    $active_object = '';
    $active_ancestor_item_ids = array();
    $active_parent_item_ids = array();
    $active_parent_object_ids = array();
    $possible_taxonomy_ancestors = array();
    $possible_object_parents = array();
    $home_page_id = (int) get_option('page_for_posts');
    if ($wp_query->is_singular && !empty($queried_object->post_type) && !is_post_type_hierarchical($queried_object->post_type)) {
        foreach ((array) get_object_taxonomies($queried_object->post_type) as $taxonomy) {
            if (is_taxonomy_hierarchical($taxonomy)) {
                $term_hierarchy = _get_term_hierarchy($taxonomy);
                $terms = wp_get_object_terms($queried_object_id, $taxonomy, array('fields' => 'ids'));
                if (is_array($terms)) {
                    $possible_object_parents = array_merge($possible_object_parents, $terms);
                    $term_to_ancestor = array();
                    foreach ((array) $term_hierarchy as $anc => $descs) {
                        foreach ((array) $descs as $desc) {
                            $term_to_ancestor[$desc] = $anc;
                        }
                    }
                    foreach ($terms as $desc) {
                        do {
                            $possible_taxonomy_ancestors[$taxonomy][] = $desc;
                            if (isset($term_to_ancestor[$desc])) {
                                $_desc = $term_to_ancestor[$desc];
                                unset($term_to_ancestor[$desc]);
                                $desc = $_desc;
                            } else {
                                $desc = 0;
                            }
                        } while (!empty($desc));
                    }
                }
            }
        }
    } elseif (!empty($queried_object->post_type) && is_post_type_hierarchical($queried_object->post_type)) {
        _get_post_ancestors($queried_object);
    } elseif (!empty($queried_object->taxonomy) && is_taxonomy_hierarchical($queried_object->taxonomy)) {
        $term_hierarchy = _get_term_hierarchy($queried_object->taxonomy);
        $term_to_ancestor = array();
        foreach ((array) $term_hierarchy as $anc => $descs) {
            foreach ((array) $descs as $desc) {
                $term_to_ancestor[$desc] = $anc;
            }
        }
        $desc = $queried_object->term_id;
        do {
            $possible_taxonomy_ancestors[$queried_object->taxonomy][] = $desc;
            if (isset($term_to_ancestor[$desc])) {
                $_desc = $term_to_ancestor[$desc];
                unset($term_to_ancestor[$desc]);
                $desc = $_desc;
            } else {
                $desc = 0;
            }
        } while (!empty($desc));
    }
    $possible_object_parents = array_filter($possible_object_parents);
    $front_page_url = home_url();
    foreach ((array) $menu_items as $key => $menu_item) {
        $menu_items[$key]->current = false;
        $classes = (array) $menu_item->classes;
        $classes[] = 'menu-item';
        $classes[] = 'menu-item-type-' . $menu_item->type;
        $classes[] = 'menu-item-object-' . $menu_item->object;
        // if the menu item corresponds to a taxonomy term for the currently-queried non-hierarchical post object
        if ($wp_query->is_singular && 'taxonomy' == $menu_item->type && in_array($menu_item->object_id, $possible_object_parents)) {
            $active_parent_object_ids[] = (int) $menu_item->object_id;
            $active_parent_item_ids[] = (int) $menu_item->db_id;
            $active_object = $queried_object->post_type;
            // if the menu item corresponds to the currently-queried post or taxonomy object
        } elseif ($menu_item->object_id == $queried_object_id && (!empty($home_page_id) && 'post_type' == $menu_item->type && $wp_query->is_home && $home_page_id == $menu_item->object_id || 'post_type' == $menu_item->type && $wp_query->is_singular || 'taxonomy' == $menu_item->type && ($wp_query->is_category || $wp_query->is_tag || $wp_query->is_tax))) {
            $classes[] = 'current-menu-item';
            $menu_items[$key]->current = true;
            $_anc_id = (int) $menu_item->db_id;
            while (($_anc_id = get_post_meta($_anc_id, '_menu_item_menu_item_parent', true)) && !in_array($_anc_id, $active_ancestor_item_ids)) {
                $active_ancestor_item_ids[] = $_anc_id;
            }
            if ('post_type' == $menu_item->type && 'page' == $menu_item->object) {
                // Back compat classes for pages to match wp_page_menu()
                $classes[] = 'page_item';
                $classes[] = 'page-item-' . $menu_item->object_id;
                $classes[] = 'current_page_item';
            }
            $active_parent_item_ids[] = (int) $menu_item->menu_item_parent;
            $active_parent_object_ids[] = (int) $menu_item->post_parent;
            $active_object = $menu_item->object;
            // if the menu item corresponds to the currently-requested URL
        } elseif ('custom' == $menu_item->object) {
            $current_url = untrailingslashit((is_ssl() ? 'https://' : 'http://') . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']);
            $item_url = untrailingslashit(strpos($menu_item->url, '#') ? substr($menu_item->url, 0, strpos($menu_item->url, '#')) : $menu_item->url);
            $_indexless_current = untrailingslashit(preg_replace('/index.php$/', '', $current_url));
            if (in_array($item_url, array($current_url, $_indexless_current))) {
                $classes[] = 'current-menu-item';
                $menu_items[$key]->current = true;
                $_anc_id = (int) $menu_item->db_id;
                while (($_anc_id = get_post_meta($_anc_id, '_menu_item_menu_item_parent', true)) && !in_array($_anc_id, $active_ancestor_item_ids)) {
                    $active_ancestor_item_ids[] = $_anc_id;
                }
                if (in_array(home_url(), array(untrailingslashit($current_url), untrailingslashit($_indexless_current)))) {
                    // Back compat for home link to match wp_page_menu()
                    $classes[] = 'current_page_item';
                }
                $active_parent_item_ids[] = (int) $menu_item->menu_item_parent;
                $active_parent_object_ids[] = (int) $menu_item->post_parent;
                $active_object = $menu_item->object;
                // give front page item current-menu-item class when extra query arguments involved
            } elseif ($item_url == $front_page_url && is_front_page()) {
                $classes[] = 'current-menu-item';
            }
            if (untrailingslashit($item_url) == home_url()) {
                $classes[] = 'menu-item-home';
            }
        }
        // back-compat with wp_page_menu: add "current_page_parent" to static home page link for any non-page query
        if (!empty($home_page_id) && 'post_type' == $menu_item->type && empty($wp_query->is_page) && $home_page_id == $menu_item->object_id) {
            $classes[] = 'current_page_parent';
        }
        $menu_items[$key]->classes = array_unique($classes);
    }
    $active_ancestor_item_ids = array_filter(array_unique($active_ancestor_item_ids));
    $active_parent_item_ids = array_filter(array_unique($active_parent_item_ids));
    $active_parent_object_ids = array_filter(array_unique($active_parent_object_ids));
    // set parent's class
    foreach ((array) $menu_items as $key => $parent_item) {
        $classes = (array) $parent_item->classes;
        $menu_items[$key]->current_item_ancestor = false;
        $menu_items[$key]->current_item_parent = false;
        if (isset($parent_item->type) && ('post_type' == $parent_item->type && !empty($queried_object->post_type) && is_post_type_hierarchical($queried_object->post_type) && in_array($parent_item->object_id, $queried_object->ancestors) && $parent_item->object != $queried_object->ID || 'taxonomy' == $parent_item->type && isset($possible_taxonomy_ancestors[$parent_item->object]) && in_array($parent_item->object_id, $possible_taxonomy_ancestors[$parent_item->object]) && (!isset($queried_object->term_id) || $parent_item->object_id != $queried_object->term_id))) {
            $classes[] = empty($queried_object->taxonomy) ? 'current-' . $queried_object->post_type . '-ancestor' : 'current-' . $queried_object->taxonomy . '-ancestor';
        }
        if (in_array(intval($parent_item->db_id), $active_ancestor_item_ids)) {
            $classes[] = 'current-menu-ancestor';
            $menu_items[$key]->current_item_ancestor = true;
        }
        if (in_array($parent_item->db_id, $active_parent_item_ids)) {
            $classes[] = 'current-menu-parent';
            $menu_items[$key]->current_item_parent = true;
        }
        if (in_array($parent_item->object_id, $active_parent_object_ids)) {
            $classes[] = 'current-' . $active_object . '-parent';
        }
        if ('post_type' == $parent_item->type && 'page' == $parent_item->object) {
            // Back compat classes for pages to match wp_page_menu()
            if (in_array('current-menu-parent', $classes)) {
                $classes[] = 'current_page_parent';
            }
            if (in_array('current-menu-ancestor', $classes)) {
                $classes[] = 'current_page_ancestor';
            }
        }
        $menu_items[$key]->classes = array_unique($classes);
    }
}
Exemplo n.º 26
0
/**
 * Add new variation set via AJAX.
 *
 * If the variation set name is the same as an existing variation set,
 * the children variant terms will be added inside that existing set.
 *
 * @since 3.8.8
 * @access private
 *
 * @uses term_exists()                      Returns true if term exists
 * @uses get_term()                         Gets all term data by term_id
 * @uses wp_insert_term()                   Inserts a term to the WordPress database
 * @uses is_wp_error()                      Checks whether variable is a WordPress error
 * @uses WP_Error                           WordPress Error class
 * @uses clean_term_cache()                 Will remove all of the term ids from the cache.
 * @uses delete_option()                    Deletes option from the database
 * @uses wp_cache_set()                     Saves the data to the cache.
 * @uses _get_term_hierarchy()              Retrieves children of taxonomy as Term IDs.
 * @uses wp_terms_checklist()               Output an unordered list of checkbox <input> elements labelled
 * @uses WPSC_Walker_Variation_Checklist    Walker variation checklist
 *
 * @return array Response args
 */
function _wpsc_ajax_add_variation_set()
{
    $new_variation_set = $_POST['variation_set'];
    $variants = preg_split('/\\s*,\\s*/', $_POST['variants']);
    $return = array();
    $parent_term_exists = term_exists($new_variation_set, 'wpsc-variation');
    // only use an existing parent ID if the term is not a child term
    if ($parent_term_exists) {
        $parent_term = get_term($parent_term_exists['term_id'], 'wpsc-variation');
        if ($parent_term->parent == '0') {
            $variation_set_id = $parent_term_exists['term_id'];
        }
    }
    if (empty($variation_set_id)) {
        $results = wp_insert_term(apply_filters('wpsc_new_variation_set', $new_variation_set), 'wpsc-variation');
        if (is_wp_error($results)) {
            return $results;
        }
        $variation_set_id = $results['term_id'];
    }
    if (empty($variation_set_id)) {
        return new WP_Error('wpsc_invalid_variation_id', __('Cannot retrieve the variation set in order to proceed.', 'wpsc'));
    }
    foreach ($variants as $variant) {
        $results = wp_insert_term(apply_filters('wpsc_new_variant', $variant, $variation_set_id), 'wpsc-variation', array('parent' => $variation_set_id));
        if (is_wp_error($results)) {
            return $results;
        }
        $inserted_variants[] = $results['term_id'];
    }
    require_once 'includes/walker-variation-checklist.php';
    if (!version_compare($GLOBALS['wp_version'], '3.8.3', '>')) {
        /* --- DIRTY HACK START --- */
        /*
        There's a bug with term cache in WordPress core. See http://core.trac.wordpress.org/ticket/14485. Fixed in 3.9.
        The next 3 lines will delete children term cache for wpsc-variation.
        Without this hack, the new child variations won't be displayed on "Variations" page and
        also won't be displayed in wp_terms_checklist() call below.
        */
        clean_term_cache($variation_set_id, 'wpsc-variation');
        delete_option('wpsc-variation_children');
        wp_cache_set('last_changed', 1, 'terms');
        _get_term_hierarchy('wpsc-variation');
        /* --- DIRTY HACK END --- */
    }
    ob_start();
    wp_terms_checklist((int) $_POST['post_id'], array('taxonomy' => 'wpsc-variation', 'descendants_and_self' => $variation_set_id, 'walker' => new WPSC_Walker_Variation_Checklist($inserted_variants), 'checked_ontop' => false));
    $content = ob_get_clean();
    $return = array('variation_set_id' => $variation_set_id, 'inserted_variants' => $inserted_variants, 'content' => $content);
    return $return;
}
Exemplo n.º 27
0
 /**
  * @access public
  */
 public function display_rows_or_placeholder()
 {
     $taxonomy = $this->screen->taxonomy;
     $args = wp_parse_args($this->callback_args, array('page' => 1, 'number' => 20, 'search' => '', 'hide_empty' => 0));
     $page = $args['page'];
     // Set variable because $args['number'] can be subsequently overridden.
     $number = $args['number'];
     $args['offset'] = $offset = ($page - 1) * $number;
     // Convert it to table rows.
     $count = 0;
     if (is_taxonomy_hierarchical($taxonomy) && !isset($args['orderby'])) {
         // We'll need the full set of terms then.
         $args['number'] = $args['offset'] = 0;
     }
     $terms = get_terms($taxonomy, $args);
     if (empty($terms) || !is_array($terms)) {
         echo '<tr class="no-items"><td class="colspanchange" colspan="' . $this->get_column_count() . '">';
         $this->no_items();
         echo '</td></tr>';
         return;
     }
     if (is_taxonomy_hierarchical($taxonomy) && !isset($args['orderby'])) {
         if (!empty($args['search'])) {
             // Ignore children on searches.
             $children = array();
         } else {
             $children = _get_term_hierarchy($taxonomy);
         }
         // Some funky recursion to get the job done( Paging & parents mainly ) is contained within, Skip it for non-hierarchical taxonomies for performance sake
         $this->_rows($taxonomy, $terms, $children, $offset, $number, $count);
     } else {
         foreach ($terms as $term) {
             $this->single_row($term);
         }
     }
 }
 function convert_them()
 {
     global $wpdb;
     if ((!isset($_POST['cats_to_convert']) || !is_array($_POST['cats_to_convert'])) && empty($this->categories_to_convert)) {
         echo '<div class="narrow">';
         echo '<p>' . sprintf(__('Uh, oh. Something didn&#8217;t work. Please <a href="%s">try again</a>.'), 'admin.php?import=wp-cat2tag') . '</p>';
         echo '</div>';
         return;
     }
     if (empty($this->categories_to_convert)) {
         $this->categories_to_convert = $_POST['cats_to_convert'];
     }
     $hier = _get_term_hierarchy('category');
     echo '<ul>';
     foreach ((array) $this->categories_to_convert as $cat_id) {
         $cat_id = (int) $cat_id;
         echo '<li>' . sprintf(__('Converting category #%s ... '), $cat_id);
         if (!$this->_category_exists($cat_id)) {
             _e('Category doesn\'t exist!');
         } else {
             $category =& get_category($cat_id);
             if (tag_exists($wpdb->escape($category->name))) {
                 _e('Category is already a tag.');
                 echo '</li>';
                 continue;
             }
             // If the category is the default, leave category in place and create tag.
             if (get_option('default_category') == $category->term_id) {
                 $id = wp_insert_term($category->name, 'post_tag', array('slug' => $category->slug));
                 $id = $id['term_taxonomy_id'];
                 $posts = get_objects_in_term($category->term_id, 'category');
                 foreach ($posts as $post) {
                     if (!$wpdb->get_var("SELECT object_id FROM {$wpdb->term_relationships} WHERE object_id = '{$post}' AND term_taxonomy_id = '{$id}'")) {
                         $wpdb->query("INSERT INTO {$wpdb->term_relationships} (object_id, term_taxonomy_id) VALUES ('{$post}', '{$id}')");
                     }
                     clean_post_cache($post);
                 }
             } else {
                 $tt_ids = $wpdb->get_col("SELECT term_taxonomy_id FROM {$wpdb->term_taxonomy} WHERE term_id = '{$category->term_id}' AND taxonomy = 'category'");
                 if ($tt_ids) {
                     $posts = $wpdb->get_col("SELECT object_id FROM {$wpdb->term_relationships} WHERE term_taxonomy_id IN (" . join(',', $tt_ids) . ") GROUP BY object_id");
                     foreach ((array) $posts as $post) {
                         clean_post_cache($post);
                     }
                 }
                 // Change the category to a tag.
                 $wpdb->query("UPDATE {$wpdb->term_taxonomy} SET taxonomy = 'post_tag' WHERE term_id = '{$category->term_id}' AND taxonomy = 'category'");
                 $terms = $wpdb->get_col("SELECT term_id FROM {$wpdb->term_taxonomy} WHERE parent = '{$category->term_id}' AND taxonomy = 'category'");
                 foreach ((array) $terms as $term) {
                     clean_category_cache($term);
                 }
                 // Set all parents to 0 (root-level) if their parent was the converted tag
                 $wpdb->query("UPDATE {$wpdb->term_taxonomy} SET parent = 0 WHERE parent = '{$category->term_id}' AND taxonomy = 'category'");
             }
             // Clean the cache
             clean_category_cache($category->term_id);
             _e('Converted successfully.');
         }
         echo '</li>';
     }
     echo '</ul>';
     echo '<p>' . sprintf(__('We&#8217;re all done here, but you can always <a href="%s">convert more</a>.'), 'admin.php?import=wp-cat2tag') . '</p>';
 }
Exemplo n.º 29
0
/**
 * Splits a batch of shared taxonomy terms.
 *
 * @since 4.3.0
 *
 * @global wpdb $wpdb WordPress database abstraction object.
 */
function _wp_batch_split_terms()
{
    global $wpdb;
    $lock_name = 'term_split.lock';
    // Try to lock.
    $lock_result = $wpdb->query($wpdb->prepare("INSERT IGNORE INTO `{$wpdb->options}` ( `option_name`, `option_value`, `autoload` ) VALUES (%s, %s, 'no') /* LOCK */", $lock_name, time()));
    if (!$lock_result) {
        $lock_result = get_option($lock_name);
        // Bail if we were unable to create a lock, or if the existing lock is still valid.
        if (!$lock_result || $lock_result > time() - HOUR_IN_SECONDS) {
            wp_schedule_single_event(time() + 5 * MINUTE_IN_SECONDS, 'wp_split_shared_term_batch');
            return;
        }
    }
    // Update the lock, as by this point we've definitely got a lock, just need to fire the actions.
    update_option($lock_name, time());
    // Get a list of shared terms (those with more than one associated row in term_taxonomy).
    $shared_terms = $wpdb->get_results("SELECT tt.term_id, t.*, count(*) as term_tt_count FROM {$wpdb->term_taxonomy} tt\n\t\t LEFT JOIN {$wpdb->terms} t ON t.term_id = tt.term_id\n\t\t GROUP BY t.term_id\n\t\t HAVING term_tt_count > 1\n\t\t LIMIT 10");
    // No more terms, we're done here.
    if (!$shared_terms) {
        update_option('finished_splitting_shared_terms', true);
        delete_option($lock_name);
        return;
    }
    // Shared terms found? We'll need to run this script again.
    wp_schedule_single_event(time() + 2 * MINUTE_IN_SECONDS, 'wp_split_shared_term_batch');
    // Rekey shared term array for faster lookups.
    $_shared_terms = array();
    foreach ($shared_terms as $shared_term) {
        $term_id = intval($shared_term->term_id);
        $_shared_terms[$term_id] = $shared_term;
    }
    $shared_terms = $_shared_terms;
    // Get term taxonomy data for all shared terms.
    $shared_term_ids = implode(',', array_keys($shared_terms));
    $shared_tts = $wpdb->get_results("SELECT * FROM {$wpdb->term_taxonomy} WHERE `term_id` IN ({$shared_term_ids})");
    // Split term data recording is slow, so we do it just once, outside the loop.
    $split_term_data = get_option('_split_terms', array());
    $skipped_first_term = $taxonomies = array();
    foreach ($shared_tts as $shared_tt) {
        $term_id = intval($shared_tt->term_id);
        // Don't split the first tt belonging to a given term_id.
        if (!isset($skipped_first_term[$term_id])) {
            $skipped_first_term[$term_id] = 1;
            continue;
        }
        if (!isset($split_term_data[$term_id])) {
            $split_term_data[$term_id] = array();
        }
        // Keep track of taxonomies whose hierarchies need flushing.
        if (!isset($taxonomies[$shared_tt->taxonomy])) {
            $taxonomies[$shared_tt->taxonomy] = 1;
        }
        // Split the term.
        $split_term_data[$term_id][$shared_tt->taxonomy] = _split_shared_term($shared_terms[$term_id], $shared_tt, false);
    }
    // Rebuild the cached hierarchy for each affected taxonomy.
    foreach (array_keys($taxonomies) as $tax) {
        delete_option("{$tax}_children");
        _get_term_hierarchy($tax);
    }
    update_option('_split_terms', $split_term_data);
    delete_option($lock_name);
}
 /**
  * Performs post-import cleanup of files and the cache
  */
 function import_end()
 {
     wp_import_cleanup($this->id);
     wp_cache_flush();
     foreach (get_taxonomies() as $tax) {
         delete_option("{$tax}_children");
         _get_term_hierarchy($tax);
     }
     wp_defer_term_counting(false);
     wp_defer_comment_counting(false);
     echo '<p>' . __('All done.', 'wordpress-importer') . '</p>';
     do_action('import_end');
 }