: str_replace(): Passing null to parameter #2 ($replace) of type array|string is deprecated in
use AdvancedAds\Entities;
use AdvancedAds\Utilities\WordPress;
* @package Advanced_Ads_Group
* @author Thomas Maier <support@wpadvancedads.com>
* @link https://wpadvancedads.com
* @copyright 2014 Thomas Maier, Advanced Ads GmbH
class Advanced_Ads_Group {
* Default ad group weight
* previously called MAX_AD_GROUP_WEIGHT
const MAX_AD_GROUP_DEFAULT_WEIGHT = 10;
* Term id of this ad group
public $type = 'default';
protected $post_type = '';
protected $current_ad = '';
* The description of the term
public $description = '';
* Number of ads to display in the group block
* Optional arguments passed to ads.
* Array with post type objects (ads)
* Multidimensional array contains information about the wrapper
* each possible html attribute is an array with possible multiple elements.
* Displayed above the ad.
* Whether this group is in a head placement.
private $is_head_placement;
* True, if this is an Advanced Ads Ad Group
public $is_group = false;
* The decorated WP_Term object.
* @param int|WP_Term $group Either id of the ad group or term object.
* @param iterable $ad_args Optional arguments passed to ads.
public function __construct( $group, iterable $ad_args = [] ) {
$this->taxonomy = Entities::TAXONOMY_AD_GROUP;
$this->group = get_term( $group, $this->taxonomy );
if ( $this->group === null || is_wp_error( $this->group ) ) {
$this->id = $this->group->term_id;
$this->name = $this->group->name;
$this->slug = $this->group->slug;
$this->description = $this->group->description;
$this->post_type = Entities::POST_TYPE_AD;
$this->ad_args = $ad_args;
$this->is_head_placement = isset( $this->ad_args['placement_type'] ) && $this->ad_args['placement_type'] === 'header';
$this->ad_args['is_top_level'] = ! isset( $this->ad_args['is_top_level'] );
$this->load_additional_attributes();
if ( ! $this->is_head_placement ) {
* If a property on the original WP_Term is requested, return it, otherwise null.
* @param string $name The requested property name.
* @noinspection MagicMethodsValidityInspection -- We don't want to allow setting of properties.
public function __get( string $name ) {
return $this->group->$name ?? null;
* Whether a property is set.
* @param string $name The requested property name.
* @noinspection MagicMethodsValidityInspection -- We don't want to allow setting of properties.
public function __isset( string $name ): bool {
return isset( $this->group->$name );
* Load additional attributes for groups that are not part of the WP terms
protected function load_additional_attributes() {
// -TODO should abstract (i.e. only call once per request)
$all_groups = get_option( 'advads-ad-groups', [] );
if ( ! isset( $all_groups[ $this->id ] ) || ! is_array( $all_groups[ $this->id ] ) ) { return; }
if ( isset( $this->ad_args['change-group'] ) ) {
// some options was provided by the user
$group_data = Advanced_Ads_Utils::merge_deep_array( [ $all_groups[ $this->id ], $this->ad_args['change-group'] ] ) ;
$group_data = $all_groups[ $this->id ];
if ( isset( $group_data['type'] ) ) {
$this->type = $group_data['type'];
// get ad count; default is 1
if ( isset( $group_data['ad_count'] ) ) {
$this->ad_count = $group_data['ad_count'] === 'all' ? 'all' : (int) $group_data['ad_count'];
if ( isset( $group_data['options'] ) ) {
$this->options = isset( $group_data['options'] ) ? $group_data['options'] : [];
* Control the output of the group by type and amount of ads
* @param array $ordered_ad_ids Ordered ids of the ads that belong to the group.
* @return string $output output of ad(s) by ad
public function output( $ordered_ad_ids ) {
if ( empty( $ordered_ad_ids ) ) {
$ad_count = apply_filters( 'advanced-ads-group-ad-count', $this->ad_count, $this );
$ad_select = Advanced_Ads_Select::get_instance();
// the Advanced_Ads_Ad obj can access this info
$this->ad_args['group_info'] = [
'refresh_enabled' => ! empty( $this->options['refresh']['enabled'] ),
$this->ad_args['ad_label'] = 'disabled';
if( is_array( $ordered_ad_ids ) ){
foreach ( $ordered_ad_ids as $_ad_id ) {
$this->ad_args['group_info']['ads_displayed'] = $ads_displayed;
$ad = $ad_select->get_ad_by_method( $_ad_id, Advanced_Ads_Select::AD, $this->ad_args );
// break the loop when maximum ads are reached
if( $ads_displayed === $ad_count ) {
$global_output = ! isset( $this->ad_args['global_output'] ) || $this->ad_args['global_output'];
// add the group to the global output array
$advads = Advanced_Ads::get_instance();
$advads->current_ads[] = ['type' => 'group', 'id' => $this->id, 'title' => $this->name];
if ( $output === [] || ! is_array( $output ) ) {
// filter grouped ads output
$output_array = apply_filters( 'advanced-ads-group-output-array', $output, $this );
// make sure the right format comes through the filter
if ( $output_array === [] || ! is_array( $output_array ) ) {
$output_string = implode( '', $output_array );
// Adds inline css to the wrapper.
if ( ! empty( $this->ad_args['inline-css'] ) && $this->ad_args['is_top_level'] ) {
$inline_css = new Advanced_Ads_Inline_Css();
$this->wrapper = $inline_css->add_css( $this->wrapper, $this->ad_args['inline-css'], $global_output );
if ( ! $this->is_head_placement && $this->wrapper !== [] ) {
$output_string = '<div' . Advanced_Ads_Utils::build_html_attributes( $this->wrapper ) . '>'
. apply_filters( 'advanced-ads-output-wrapper-before-content-group', '', $this )
. apply_filters( 'advanced-ads-output-wrapper-after-content-group', '', $this )
if ( ! empty( $this->ad_args['is_top_level'] ) && ! empty( $this->ad_args['placement_clearfix'] ) ) {
$output_string .= '<br style="clear: both; display: block; float: none;"/>';
// filter final group output
return apply_filters( 'advanced-ads-group-output', $output_string, $this );
* Get ordered ids of the ads that belong to the group
public function get_ordered_ad_ids() {
$ads = $this->load_all_ads();
if ( ! is_array( $ads ) ) {
// get ad weights serving as an order here
$weights = $this->get_ad_weights( array_keys( $ads ) );
$ad_ids = wp_list_pluck( $ads, 'ID' );
// remove ads with 0 ad weight and unavailable ads (e.g. drafts).
foreach ( $weights as $ad_id => $ad_weight ) {
if ( $ad_weight === 0 || ! in_array( $ad_id, $ad_ids, true ) ) {
unset( $weights[ $ad_id ] );
// order ads based on group type
if ( $this->type === 'ordered' ) {
$ordered_ad_ids = $this->shuffle_ordered_ads( $weights );
$ordered_ad_ids = $this->shuffle_ads( $ads, $weights );
return apply_filters( 'advanced-ads-group-output-ad-ids', $ordered_ad_ids, $this->type, $ads, $weights, $this );
* Return all ads from this group
public function get_all_ads() {
return $this->load_all_ads();
* Load all public ads for this group
* @update 1.1.0 load only public ads
* @update allow to cache groups for few minutes
* @return bool|WP_Post[] $ads array with ad (post) objects
private function load_all_ads() {
if ( false !== $this->ads ) {
// Much more complex than needed: one of the three queries is not needed and the last query gets slow quiet fast.
'post_type' => $this->post_type,
'post_status' => 'publish',
'taxonomy' => $this->taxonomy,
'orderby' => 'id', // Might want to avoid sorting as not needed for most calls and fast in PHP; slight I/O blocking concern.
$ads = new WP_Query( $args );
if ( $ads->have_posts() ) {
$this->ads = $this->add_post_ids( $ads->posts );
* Use post ids as keys for ad array
* @param array $ads array with post objects.
* @return array $ads array with post objects with post id as their key.
private function add_post_ids( array $ads ) {
* Shuffle ads based on ad weight.
* @param array $ads ad objects.
* @param array $weights ad weights, indexed by ad id.
public function shuffle_ads( $ads, $weights ) {
// get a random ad for every ad there is
// while non-zero weights are set select random next
// phpcs:ignore WordPress.CodeAnalysis.AssignmentInCondition.FoundInWhileCondition -- prevents code duplication.
while ( null !== ( $random_ad_id = $this->get_random_ad_by_weight( $weights ) ) ) {
// remove chosen ad from weights array
unset( $weights[ $random_ad_id ] );
// put random ad into shuffled array
if ( ! empty( $ads[ $random_ad_id ] ) ) {
$shuffled_ads[] = $random_ad_id;
* Shuffle ads that have the same width.
* @param array $weights Array of $ad_id => weight pairs.
* @return array $ordered_ad_ids Ordered ad ids.
public function shuffle_ordered_ads( array $weights ) {
// order to highest weight first
$ordered_ad_ids = array_keys( $weights );
$weights = array_values( $weights );
$count = count( $weights );
for ( $i = 1; $i <= $count; $i++ ) {
if ( $i == $count || $weights[ $i ] !== $weights[ $i - 1] ) {
if ( $slice_len !== 1 ) {
$shuffled = array_slice( $ordered_ad_ids, $pos, $slice_len );
// Replace the unshuffled chunk with the shuffled one.
array_splice( $ordered_ad_ids, $pos, $slice_len, $shuffled );
* Get random ad by ad weight.
* @param array $ad_weights Indexed by ad_id [int $ad_id => int $weight].
* @source applied with fix for order http://stackoverflow.com/a/11872928/904614
private function get_random_ad_by_weight(array $ad_weights) {
// use maximum ad weight for ads without this
// ads might have a weight of zero (0); to avoid mt_rand fail assume that at least 1 is set.
$max = array_sum( $ad_weights );
$rand = mt_rand( 1, $max );
foreach ( $ad_weights as $ad_id => $weight ) {
* Get weights of ads in this group
* @param array $ad_ids Ids of ads assigned to this group.