function adrotate_inject_posts($post_content)
{
    global $wpdb, $post, $adrotate_debug;
    $group_array = array();
    if (is_page()) {
        // Inject ads into page
        $ids = $wpdb->get_results("SELECT `id`, `page`, `page_loc`, `page_par` FROM `{$wpdb->prefix}adrotate_groups` WHERE `page_loc` > 0 AND  `page_loc` < 5;");
        foreach ($ids as $id) {
            $pages = explode(",", $id->page);
            if (!is_array($pages)) {
                $pages = array();
            }
            if (in_array($post->ID, $pages)) {
                $group_array[$id->id] = array('location' => $id->page_loc, 'paragraph' => $id->page_par, 'ids' => $pages);
            }
        }
        unset($ids, $pages);
    }
    if (is_single()) {
        // Inject ads into posts in specified category
        $ids = $wpdb->get_results("SELECT `id`, `cat`, `cat_loc`, `cat_par` FROM `{$wpdb->prefix}adrotate_groups` WHERE `cat_loc` > 0 AND `cat_loc` < 5;");
        $wp_categories = get_terms('category', array('fields' => 'ids'));
        foreach ($ids as $id) {
            $categories = explode(",", $id->cat);
            if (!is_array($categories)) {
                $categories = array();
            }
            foreach ($wp_categories as &$value) {
                if (in_array($value, $categories)) {
                    $group_array[$id->id] = array('location' => $id->cat_loc, 'paragraph' => $id->cat_par, 'ids' => $categories);
                }
            }
        }
        unset($ids, $wp_categories, $categories);
    }
    $group_array = adrotate_shuffle($group_array);
    $group_count = count($group_array);
    if ($adrotate_debug['general'] == true) {
        echo "<p><strong>[DEBUG][adrotate_inject_posts()] group_array</strong><pre>";
        echo "Group count: " . $group_count . "</br>";
        print_r($group_array);
        echo "</pre></p>";
    }
    if ($group_count > 0) {
        $before = $after = $inside = 0;
        foreach ($group_array as $group_id => $group) {
            if (is_page($group['ids']) or is_category($group['ids']) or in_category($group['ids'])) {
                // Advert in front of content
                if (($group['location'] == 1 or $group['location'] == 3) and $before == 0) {
                    $post_content = adrotate_group($group_id) . $post_content;
                    unset($group_array[$group_id]);
                    $before = 1;
                }
                // Advert behind the content
                if (($group['location'] == 2 or $group['location'] == 3) and $after == 0) {
                    $post_content = $post_content . adrotate_group($group_id);
                    unset($group_array[$group_id]);
                    $after = 1;
                }
                // Adverts inside the content
                if ($group['location'] == 4) {
                    $paragraphs = explode('</p>', $post_content);
                    $paragraph_count = count($paragraphs);
                    $count_p = $group['paragraph'] == 99 ? ceil($paragraph_count / 2) : $group['paragraph'];
                    foreach ($paragraphs as $index => $paragraph) {
                        if (trim($paragraph)) {
                            $paragraphs[$index] .= '</p>';
                        }
                        if ($count_p == $index + 1 and $inside == 0) {
                            $paragraphs[$index] .= adrotate_group($group_id);
                            unset($group_array[$group_id]);
                            $inside = 1;
                        }
                    }
                    $inside = 0;
                    // Reset for the next paragraph
                    $post_content = implode('', $paragraphs);
                    unset($paragraphs, $paragraph_count);
                }
            }
        }
        unset($group_array, $before, $after, $inside);
    }
    return $post_content;
}
function adrotate_group($group_ids, $fallback = 0, $weight = 0, $site = 0)
{
    global $wpdb, $adrotate_config, $adrotate_debug;
    $output = $group_select = '';
    if ($group_ids) {
        $now = adrotate_now();
        $group_array = !is_array($group_ids) ? explode(",", $group_ids) : $group_ids;
        foreach ($group_array as $key => $value) {
            $group_select .= " `{$wpdb->prefix}adrotate_linkmeta`.`group` = {$value} OR";
        }
        $group_select = rtrim($group_select, " OR");
        $group = $wpdb->get_row($wpdb->prepare("SELECT * FROM `{$wpdb->prefix}adrotate_groups` WHERE `name` != '' AND `id` = %d;", $group_array[0]));
        if ($adrotate_debug['general'] == true) {
            echo "<p><strong>[DEBUG][adrotate_group] Selected group</strong><pre>";
            print_r($group);
            echo "</pre></p>";
        }
        if ($group) {
            // Get all ads in all selected groups
            $ads = $wpdb->get_results("SELECT \n\t\t\t\t\t`{$wpdb->prefix}adrotate`.`id`, \n\t\t\t\t\t`{$wpdb->prefix}adrotate`.`title`, \n\t\t\t\t\t`{$wpdb->prefix}adrotate`.`bannercode`, \n\t\t\t\t\t`{$wpdb->prefix}adrotate`.`link`, \n\t\t\t\t\t`{$wpdb->prefix}adrotate`.`image`, \n\t\t\t\t\t`{$wpdb->prefix}adrotate`.`responsive`, \n\t\t\t\t\t`{$wpdb->prefix}adrotate`.`tracker`, \n\t\t\t\t\t`{$wpdb->prefix}adrotate_linkmeta`.`group`\n\t\t\t\tFROM \n\t\t\t\t\t`{$wpdb->prefix}adrotate`, \n\t\t\t\t\t`{$wpdb->prefix}adrotate_linkmeta` \n\t\t\t\tWHERE \n\t\t\t\t\t({$group_select}) \n\t\t\t\t\tAND `{$wpdb->prefix}adrotate_linkmeta`.`user` = 0 \n\t\t\t\t\tAND `{$wpdb->prefix}adrotate`.`id` = `{$wpdb->prefix}adrotate_linkmeta`.`ad` \n\t\t\t\t\tAND (`{$wpdb->prefix}adrotate`.`type` = 'active' \n\t\t\t\t\t\tOR `{$wpdb->prefix}adrotate`.`type` = '2days'\n\t\t\t\t\t\tOR `{$wpdb->prefix}adrotate`.`type` = '7days')\n\t\t\t\tGROUP BY `{$wpdb->prefix}adrotate`.`id`\n\t\t\t\tORDER BY `{$wpdb->prefix}adrotate`.`id`;");
            if ($ads) {
                if ($adrotate_debug['general'] == true) {
                    echo "<p><strong>[DEBUG][adrotate_group()] All ads in group</strong><pre>";
                    print_r($ads);
                    echo "</pre></p>";
                }
                foreach ($ads as $ad) {
                    $selected[$ad->id] = $ad;
                    $selected = adrotate_filter_schedule($selected, $ad);
                }
                unset($ads);
                if ($adrotate_debug['general'] == true) {
                    echo "<p><strong>[DEBUG][adrotate_group] Reduced array based on schedule restrictions</strong><pre>";
                    print_r($selected);
                    echo "</pre></p>";
                }
                $array_count = count($selected);
                if ($array_count > 0) {
                    $before = $after = '';
                    $before = str_replace('%id%', $group_array[0], stripslashes(html_entity_decode($group->wrapper_before, ENT_QUOTES)));
                    $after = str_replace('%id%', $group_array[0], stripslashes(html_entity_decode($group->wrapper_after, ENT_QUOTES)));
                    $output .= '<div class="g g-' . $group->id . '">';
                    if ($group->modus == 1) {
                        // Dynamic ads
                        $i = 1;
                        // Limit group to save resources
                        $amount = $group->adspeed >= 10000 ? 10 : 20;
                        // Randomize and trim output
                        $selected = adrotate_shuffle($selected);
                        foreach ($selected as $key => $banner) {
                            if ($i <= $amount) {
                                $image = str_replace('%folder%', $adrotate_config['banner_folder'], $banner->image);
                                $output .= '<div class="g-dyn a-' . $banner->id . ' c-' . $i . '">';
                                $output .= $before . adrotate_ad_output($banner->id, $group->id, $banner->title, $banner->bannercode, $banner->tracker, $banner->link, $image, $banner->responsive) . $after;
                                $output .= '</div>';
                                $i++;
                            }
                        }
                    } else {
                        if ($group->modus == 2) {
                            // Block of ads
                            $block_count = $group->gridcolumns * $group->gridrows;
                            if ($array_count < $block_count) {
                                $block_count = $array_count;
                            }
                            $columns = 1;
                            for ($i = 1; $i <= $block_count; $i++) {
                                $banner_id = array_rand($selected, 1);
                                $image = str_replace('%folder%', $adrotate_config['banner_folder'], $selected[$banner_id]->image);
                                $output .= '<div class="g-col b-' . $group->id . ' a-' . $selected[$banner_id]->id . '">';
                                $output .= $before . adrotate_ad_output($selected[$banner_id]->id, $group->id, $selected[$banner_id]->title, $selected[$banner_id]->bannercode, $selected[$banner_id]->tracker, $selected[$banner_id]->link, $image, $selected[$banner_id]->responsive) . $after;
                                $output .= '</div>';
                                if ($columns == $group->gridcolumns and $i != $block_count) {
                                    $output .= '</div><div class="g g-' . $group->id . '">';
                                    $columns = 1;
                                } else {
                                    $columns++;
                                }
                                if ($adrotate_config['stats'] == 1) {
                                    adrotate_count_impression($selected[$banner_id]->id, $group->id, 0, $adrotate_config['impression_timer']);
                                }
                                unset($selected[$banner_id]);
                            }
                        } else {
                            // Default (single ad)
                            $banner_id = array_rand($selected, 1);
                            $image = str_replace('%folder%', $adrotate_config['banner_folder'], $selected[$banner_id]->image);
                            $output .= '<div class="g-single a-' . $selected[$banner_id]->id . '">';
                            $output .= $before . adrotate_ad_output($selected[$banner_id]->id, $group->id, $selected[$banner_id]->title, $selected[$banner_id]->bannercode, $selected[$banner_id]->tracker, $selected[$banner_id]->link, $image, $selected[$banner_id]->responsive) . $after;
                            $output .= '</div>';
                            if ($adrotate_config['stats'] == 1) {
                                adrotate_count_impression($selected[$banner_id]->id, $group->id, 0, $adrotate_config['impression_timer']);
                            }
                        }
                    }
                    $output .= '</div>';
                    unset($selected);
                } else {
                    $output .= adrotate_error('ad_expired');
                }
            } else {
                $output .= adrotate_error('ad_unqualified');
            }
        } else {
            $output .= adrotate_error('group_not_found', array($group_array[0]));
        }
    } else {
        $output .= adrotate_error('group_no_id');
    }
    return $output;
}