Commit inicial - WordPress Análisis de Precios Unitarios

- WordPress core y plugins
- Tema Twenty Twenty-Four configurado
- Plugin allow-unfiltered-html.php simplificado
- .gitignore configurado para excluir wp-config.php y uploads

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
root
2025-11-03 21:04:30 -06:00
commit a22573bf0b
24068 changed files with 4993111 additions and 0 deletions

View File

@@ -0,0 +1,102 @@
<?php
/**
* Importers Base.
*
* @package AdvancedAds
* @author Advanced Ads <info@wpadvancedads.com>
* @since 1.50.0
*/
namespace AdvancedAds\Importers;
use AdvancedAds\Constants;
defined( 'ABSPATH' ) || exit;
/**
* Importers Base.
*/
abstract class Importer {
/**
* Is importer detected.
*
* @var bool
*/
private $is_detected = null;
/**
* Show import button or not.
*
* @return bool
*/
public function show_button(): bool {
return true;
}
/**
* Is importer detected
*
* @return bool
*/
public function is_detected(): bool {
if ( null === $this->is_detected ) {
$this->is_detected = $this->detect();
}
return $this->is_detected;
}
/**
* Add session key.
*
* @param Ad $ad Ad instance.
* @param Placement $placement Placement instance.
* @param string $key Session unique key.
*
* @return void
*/
protected function add_session_key( $ad, $placement, $key ): void {
update_post_meta( $ad->get_id(), '_importer_session_key', $key );
update_post_meta( $placement->get_id(), '_importer_session_key', $key );
}
/**
* Rollback import
*
* @param string $key Session key.
*
* @return void
*/
public function rollback( $key ): void {
global $wpdb;
$wpdb->query(
$wpdb->prepare(
"DELETE p, pm
FROM {$wpdb->posts} p
INNER JOIN {$wpdb->postmeta} pm
ON pm.post_id = p.ID
WHERE pm.meta_key = '_importer_session_key'
AND pm.meta_value = %s
AND p.post_type in ( %s, %s )",
$key,
Constants::POST_TYPE_AD,
Constants::POST_TYPE_PLACEMENT
)
);
$wpdb->query(
"DELETE pm FROM {$wpdb->postmeta} pm LEFT JOIN {$wpdb->posts} wp ON wp.ID = pm.post_id WHERE wp.ID IS NULL"
);
}
/**
* Get the unique identifier (ID) of the importer.
*
* @return string The unique ID of the importer.
*/
protected function generate_history_key(): string {
return 'advads_' . wp_rand() . '_' . $this->get_id();
}
}

View File

@@ -0,0 +1,359 @@
<?php // phpcs:ignoreFile
/**
* Ad Inserter.
*
* @package AdvancedAds
* @author Advanced Ads <info@wpadvancedads.com>
* @since 1.50.0
*/
namespace AdvancedAds\Importers;
use AdvancedAds\Framework\Utilities\Params;
use AdvancedAds\Interfaces\Importer as Interface_Importer;
defined( 'ABSPATH' ) || exit;
/**
* Ad Inserter.
*/
class Ad_Inserter extends Importer implements Interface_Importer {
/**
* Hold AI options
*
* @var array
*/
private $ai_options = null;
/**
* Get the unique identifier (ID) of the importer.
*
* @return string The unique ID of the importer.
*/
public function get_id(): string {
return 'ad_inserter';
}
/**
* Get the title or name of the importer.
*
* @return string The title of the importer.
*/
public function get_title(): string {
return __( 'Ad Inserter', 'advanced-ads' );
}
/**
* Get a description of the importer.
*
* @return string The description of the importer.
*/
public function get_description(): string {
return '';
}
/**
* Get the icon to this importer.
*
* @return string The icon for the importer.
*/
public function get_icon(): string {
return '<span class="dashicons dashicons-insert"></span>';
}
/**
* Detect the importer in database.
*
* @return bool True if detected; otherwise, false.
*/
public function detect(): bool {
$options = $this->get_ai_options();
return ! empty( $options );
}
/**
* Render form.
*
* @return void
*/
public function render_form(): void {
$blocks = $this->get_ai_options();
unset( $blocks['global'], $blocks['extract'] );
?>
<p class="text-base m-0">
<?php
/* translators: %d: number of ad blocks */
printf( __( 'We found Ad Inserter configuration with <strong>%d ad blocks</strong>.', 'advanced-ads' ), count( $blocks ) ); // phpcs:ignore
?>
</p>
<p><label><input type="checkbox" name="ai_import[blocks]" checked="checked" /> <?php esc_html_e( 'Import Ad Blocks', 'advanced-ads' ); ?></label></p>
<p><label><input type="checkbox" name="ai_import[options]" checked="checked" /> <?php esc_html_e( 'Import Settings', 'advanced-ads' ); ?></label></p>
<?php
}
/**
* Import data.
*
* @return WP_Error|string
*/
public function import() {
$what = Params::post( 'ai_import', [], FILTER_DEFAULT, FILTER_REQUIRE_ARRAY );
$history_key = $this->generate_history_key();
$count = 0;
if ( isset( $what['blocks'] ) ) {
$count = $this->import_ads( $history_key );
}
if ( isset( $what['options'] ) ) {
$this->import_options( $history_key );
}
wp_advads()->importers->add_session_history( $this->get_id(), $history_key, $count );
/* translators: 1: counts 2: Importer title */
return sprintf( esc_html__( '%1$d ads migrated from %2$s', 'advanced-ads' ), $count, $this->get_title() );
}
/**
* Return Ad Inserter block and option array
*
* @return array|bool
*/
private function get_ai_options() {
if ( null !== $this->ai_options ) {
return $this->ai_options;
}
$this->ai_options = get_option( 'ad_inserter' );
if ( false === $this->ai_options ) {
return $this->ai_options;
}
if ( is_string( $this->ai_options ) && substr( $this->ai_options, 0, 4 ) === ':AI:' ) {
$this->ai_options = unserialize( base64_decode( substr( $this->ai_options, 4 ), true ) ); // phpcs:ignore
$this->ai_options = array_filter( $this->ai_options );
}
return $this->ai_options;
}
/**
* Import ads
*
* @param string $history_key Session key for rollback.
*
* @return int
*/
private function import_ads( $history_key ): int {
$count = 0;
$blocks = $this->get_ai_options();
unset( $blocks['global'], $blocks['extract'] );
foreach ( $blocks as $index => $block ) {
$ad = wp_advads_create_new_ad( 'plain' );
$ad->set_title( '[Migrated from Ad Inserter] Ad # ' . $index );
$ad->set_content( $block['code'] );
if ( isset( $block['block_width'] ) ) {
$ad->set_width( absint( $block['block_width'] ) );
}
if ( isset( $block['block_height'] ) ) {
$ad->set_height( absint( $block['block_height'] ) );
}
$visitor_conditions = $this->parse_visitor_conditions_ad( $block );
if ( ! empty( $visitor_conditions ) ) {
$ad->set_visitor_conditions( $visitor_conditions );
}
$ad_id = $ad->save();
if ( $ad_id > 0 ) {
++$count;
$placement = wp_advads_create_new_placement( 'post_content' );
$placement->set_title( '[Migrated from Ad Inserter] Placement # ' . $index );
$placement->set_item( 'ad_' . $ad_id );
$placement->set_prop( 'position', 'after' );
$placement->set_prop( 'index', 3 );
$placement->set_prop( 'tag', 'p' );
$display_conditions = $this->parse_display_conditions_placements( $block );
if ( ! empty( $display_conditions ) ) {
$placement->set_display_conditions( $display_conditions );
}
$placement->save();
$this->add_session_key( $ad, $placement, $history_key );
}
}
return $count;
}
/**
* Parse visitor conditions for ad.
*
* @param array $block Block array.
*
* @return array
*/
private function parse_visitor_conditions_ad( $block ) {
$devices = [];
$conditions = [];
if ( isset( $block['detect_viewport_1'] ) ) {
$devices[] = 'desktop';
}
if ( isset( $block['detect_viewport_2'] ) ) {
$devices[] = 'tablet';
}
if ( isset( $block['detect_viewport_3'] ) ) {
$devices[] = 'mobile';
}
if ( ! empty( $devices ) ) {
$conditions[] = [
'type' => 'mobile',
'value' => $devices,
];
}
return $conditions;
}
/**
* Parse display conditions for placement
*
* @param array $block Block array.
*
* @return array|null
*/
private function parse_display_conditions_placements( $block ) {
$conditions = [];
if ( isset( $block['display_on_homepage'] ) ) {
$conditions[] = [
'type' => 'general',
'value' => [ 'is_front_page' ],
];
}
return $conditions;
}
/**
* Import options
*
* @return void
*/
private function import_options(): void {}
/**
* Imports all Ad Inserter ads.
*
* This method is responsible for importing all Ad Inserter ads.
* It is part of the Ad Inserter importer class.
*
* @return void
*/
public function adsforwp_import_all_ad_inserter_ads() {
global $block_object, $wpdb;
if ( ! current_user_can( 'manage_options' ) ) {
return;
}
$wpdb->query( 'START TRANSACTION' );
$result = [];
$user_id = get_current_user_id();
if ( is_array( $block_object ) ) {
$i = 0;
foreach ( $block_object as $object ) {
$wp_options = $object->wp_options;
$ad_code = $wp_options['code'];
if ( '' !== $ad_code ) {
$ads_post = [
'post_author' => $user_id,
'post_title' => 'Custom Ad '.$i.' (Migrated from Ad Inserter)',
'post_status' => 'publish',
'post_name' => 'Custom Ad '.$i.' (Migrated from Ad Inserter)',
'post_type' => 'adsforwp',
];
$post_id = wp_insert_post( $ads_post );
$wheretodisplay = '';
$ad_align = '';
$pragraph_no = '';
$adposition = '';
if ( $wp_options['display_type'] == 3 || $wp_options['display_type'] == 1) {
$wheretodisplay = 'before_the_content';
}elseif ( $wp_options['display_type'] == 4 || $wp_options['display_type'] == 2) {
$wheretodisplay = 'after_the_content';
}elseif ( $wp_options['display_type'] == 5) {
$wheretodisplay = 'between_the_content';
$pragraph_no = $wp_options['paragraph_number'];
$adposition = 'number_of_paragraph';
}
if ( 1 == $wp_options['alignment_type'] ) {
$ad_align = 'left';
}elseif ( 2 == $wp_options['alignment_type'] ) {
$ad_align = 'right';
}elseif ( 3 == $wp_options['alignment_type'] ) {
$ad_align = 'center';
}
$data_group_array['group-0'] = array(
'data_array' => array(
array(
'key_1' => 'show_globally',
'key_2' => 'equal',
'key_3' => 'post',
)
)
);
$adforwp_meta_key = array(
'select_adtype' => 'custom',
'custom_code' => $ad_code,
'adposition' => $adposition,
'paragraph_number' => $pragraph_no,
'adsforwp_ad_align' => $ad_align,
'imported_from' => 'ad_inserter',
'wheretodisplay' => $wheretodisplay,
'data_group_array' => $data_group_array
);
foreach ($adforwp_meta_key as $key => $val) {
$result[] = update_post_meta($post_id, $key, $val);
}
}
$i++;
}
}
if (is_wp_error($result) ) {
echo $result->get_error_message();
$wpdb->query('ROLLBACK');
} else {
$wpdb->query('COMMIT');
return $result;
}
}
}

View File

@@ -0,0 +1,645 @@
<?php // phpcs:ignoreFile
/**
* Ads for WP Ads.
*
* @package AdvancedAds
* @author Advanced Ads <info@wpadvancedads.com>
* @since 1.50.0
*/
namespace AdvancedAds\Importers;
use AdvancedAds\Interfaces\Importer as Interface_Importer;
defined( 'ABSPATH' ) || exit;
/**
* Ads for WP Ads.
*/
class Ads_WP_Ads extends Importer implements Interface_Importer {
/**
* Get the unique identifier (ID) of the importer.
*
* @return string The unique ID of the importer.
*/
public function get_id(): string {
return 'ads_wp_ads';
}
/**
* Get the title or name of the importer.
*
* @return string The title of the importer.
*/
public function get_title(): string {
return __( 'Ads for WP Ads', 'advanced-ads' );
}
/**
* Get a description of the importer.
*
* @return string The description of the importer.
*/
public function get_description(): string {
return '';
}
/**
* Get the icon to this importer.
*
* @return string The icon for the importer.
*/
public function get_icon(): string {
return '<span class="dashicons dashicons-insert"></span>';
}
/**
* Detect the importer in database.
*
* @return bool True if detected; otherwise, false.
*/
public function detect(): bool {
return false;
}
/**
* Render form.
*
* @return void
*/
public function render_form(): void {
?>
<fieldset>
<p><label><input type="radio" name="import_type" checked="checked" /> <?php esc_html_e( 'Import Ads', 'advanced-ads' ); ?></label></p>
<p><label><input type="radio" name="import_type" /> <?php esc_html_e( 'Import Groups', 'advanced-ads' ); ?></label></p>
<p><label><input type="radio" name="import_type" /> <?php esc_html_e( 'Import Placements', 'advanced-ads' ); ?></label></p>
<p><label><input type="radio" name="import_type" /> <?php esc_html_e( 'Import Settings', 'advanced-ads' ); ?></label></p>
</fieldset>
<?php
}
/**
* Import data.
*
* @return WP_Error|string
*/
public function import() {
return '';
}
public function importampforwp_ads(){
global $redux_builder_amp;
$args = array(
'post_type' => 'quads-ads'
);
$the_query = new WP_Query( $args );
$ad_count = $the_query->found_posts;
$post_status = 'publish';
$amp_options = get_option('redux_builder_amp');
$user_id = get_current_user_id();
$after_the_percentage_value = '';
for($i=1; $i<=6; $i++){
if($amp_options['enable-amp-ads-'.$i] != 1){
continue;
}
$ad_type = $amp_options['enable-amp-ads-type-'.$i];
if(($ad_type== 'adsense' && (empty($amp_options['enable-amp-ads-text-feild-client-'.$i]) || empty($amp_options['enable-amp-ads-text-feild-slot-'.$i]))) || ($ad_type== 'mgid' && (empty($amp_options['enable-amp-ads-mgid-field-data-pub-'.$i]) || empty($amp_options['enable-amp-ads-mgid-field-data-widget-'.$i])))){
continue;
}
$ad_count++;
switch ($i) {
case 1:
$position = 'amp_below_the_header';
break;
case 2:
$position = 'amp_below_the_footer';
break;
case 3:
$position = 'amp_above_the_post_content';
break;
case 4:
$position = 'amp_below_the_post_content';
break;
case 5:
$position = 'amp_below_the_title';
break;
case 6:
$position = 'amp_above_related_post';
break;
}
switch ($amp_options['enable-amp-ads-select-'.$i]) {
case '1':
$g_data_ad_width = '300';
$g_data_ad_height = '250';
break;
case '2':
$g_data_ad_width = '336';
$g_data_ad_height = '280';
break;
case '3':
$g_data_ad_width = '728';
$g_data_ad_height = '90';
break;
case '4':
$g_data_ad_width = '300';
$g_data_ad_height = '600';
break;
case '5':
$g_data_ad_width = '320';
$g_data_ad_height = '100';
break;
case '6':
$g_data_ad_width = '200';
$g_data_ad_height = '50';
break;
case '7':
$g_data_ad_width = '320';
$g_data_ad_height = '50';
break;
default:
$g_data_ad_width = '300';
$g_data_ad_height= '250';
break;
}
if($ad_type== 'mgid'){
if($i == 2){
$position = 'ad_shortcode';
}
$post_title ='MGID Ad '.$i.' (Migrated from AMP)';
$g_data_ad_width = $amp_options['enable-amp-ads-mgid-width-'.$i];
$g_data_ad_height= $amp_options['enable-amp-ads-mgid-height-'.$i];
}else{
$post_title ='Adsense Ad '.$i.' (Migrated from AMP)';
}
$ads_post = array(
'post_author' => $user_id,
'post_title' => $post_title,
'post_status' => $post_status,
'post_name' => $post_title,
'post_type' => 'quads-ads',
);
if($amp_options['enable-amp-ads-resp-'.$i]){
$adsense_type = 'responsive';
}else{
$adsense_type = 'normal';
}
$post_id = wp_insert_post($ads_post);
$visibility_include =array();
if($i == 3){
$display_on = $amp_options['made-amp-ad-3-global'];
$j =0;
foreach ($display_on as $display_on_data) {
switch ($display_on_data) {
case '1':
$visibility_include[$j]['type']['label'] = 'Post Type';
$visibility_include[$j]['type']['value'] = 'post_type';
$visibility_include[$j]['value']['label'] = "post";
$visibility_include[$j]['value']['value'] = "post";
$j++;
break;
case '2':
$visibility_include[$j]['type']['label'] = 'Post Type';
$visibility_include[$j]['type']['value'] = 'post_type';
$visibility_include[$j]['value']['label'] = "page";
$visibility_include[$j]['value']['value'] = "page";
$j++;
break;
case '4':
$visibility_include[$j]['type']['label'] = 'General';
$visibility_include[$j]['type']['value'] = 'general';
$visibility_include[$j]['value']['label'] = "Show Globally";
$visibility_include[$j]['value']['value'] = "show_globally";
$j++;
break;
}
}
}else{
$visibility_include[0]['type']['label'] = 'General';
$visibility_include[0]['type']['value'] = 'general';
$visibility_include[0]['value']['label'] = "Show Globally";
$visibility_include[0]['value']['value'] = "show_globally";
}
$adforwp_meta_key = array(
'ad_type' => $ad_type ,
'g_data_ad_client' => $amp_options['enable-amp-ads-text-feild-client-'.$i],
'g_data_ad_slot' => $amp_options['enable-amp-ads-text-feild-slot-'.$i],
'data_publisher' => $amp_options['enable-amp-ads-mgid-field-data-pub-'.$i],
'data_widget' => $amp_options['enable-amp-ads-mgid-field-data-widget-'.$i],
'data_container' => $amp_options['enable-amp-ads-mgid-field-data-con-'.$i],
'g_data_ad_width' => $g_data_ad_width,
'g_data_ad_height' => $g_data_ad_height,
'adsense_type' => $adsense_type,
'enabled_on_amp' => 1,
'visibility_include' => $visibility_include,
'position' => $position,
'imported_from' => 'ampforwp_ads',
'label' => $post_title,
'ad_id' => $post_id,
'code' => '',
'enable_one_end_of_post' =>'',
'quads_ad_old_id' => 'ad'.$ad_count,
'ad_label_check' => $amp_options['ampforwp-ads-sponsorship'],
'ad_label_text' => $amp_options['ampforwp-ads-sponsorship-label'],
);
foreach ($adforwp_meta_key as $key => $val){
update_post_meta($post_id, $key, $val);
}
}
if ( defined( 'ADVANCED_AMP_ADS_VERSION' ) ) {
// Incontent Ads
for($i=1; $i<=6; $i++){
if($redux_builder_amp['ampforwp-incontent-ad-'.$i] != 1){
continue;
}
$ad_type = $redux_builder_amp['ampforwp-advertisement-type-incontent-ad-'.$i];
$ad_type_label = '';
if($ad_type== '4'){
continue;
}
if(($ad_type== '1' && (empty($redux_builder_amp['ampforwp-adsense-ad-data-ad-client-incontent-ad-'.$i]) || empty($redux_builder_amp['ampforwp-adsense-ad-data-ad-slot-incontent-ad-'.$i]))) || ($ad_type== '5' && (empty($redux_builder_amp['ampforwp-mgid-ad-Data-Publisher-incontent-ad-'.$i]) || empty($redux_builder_amp['ampforwp-mgid-ad-Data-Widget-incontent-ad-'.$i])))){
continue;
}
$ad_count++;
$g_data_ad_width = '';
$g_data_ad_height= '';
if($ad_type == '1'){
$ad_type_label = 'adsense';
$post_title = 'Adsense Ad '.$i.' Incontent Ad (Migrated from AMP)';
$g_data_ad_width = $redux_builder_amp['ampforwp-adsense-ad-width-incontent-ad-'.$i];
$g_data_ad_height = $redux_builder_amp['ampforwp-adsense-ad-height-incontent-ad-'.$i];
$position = $redux_builder_amp['ampforwp-adsense-ad-position-incontent-ad-'.$i];
}else if($ad_type == '2'){
$ad_type_label = 'double_click';
$post_title = 'DoubleClick Ad '.$i.' Incontent Ad (Migrated from AMP)';
$g_data_ad_width = $redux_builder_amp['ampforwp-doubleclick-ad-width-incontent-ad-'.$i];
$g_data_ad_height = $redux_builder_amp['ampforwp-doubleclick-ad-height-incontent-ad-'.$i];
$position = $redux_builder_amp['ampforwp-doubleclick-ad-position-incontent-ad-'.$i];
}else if($ad_type == '3'){
$ad_type_label = 'plain_text';
$post_title = 'Plain Text Ad '.$i.' Incontent Ad (Migrated from AMP)';
$position = $redux_builder_amp['ampforwp-custom-ads-ad-position-incontent-ad-'.$i];
}else if($ad_type == '5'){
$ad_type_label = 'mgid';
$post_title ='MGID Ad '.$i.' Incontent Ad (Migrated from AMP)';
$g_data_ad_width = $redux_builder_amp['ampforwp-mgid-ad-width-incontent-ad-'.$i];
$g_data_ad_height = $redux_builder_amp['ampforwp-mgid-ad-height-incontent-ad-'.$i];
$position = $redux_builder_amp['ampforwp-mgid-ad-position-incontent-ad-'.$i];
}
if($redux_builder_amp['adsense-rspv-ad-incontent-'.$i]){
$adsense_type = 'responsive';
}else{
$adsense_type = 'normal';
}
$ads_post = array(
'post_author' => $user_id,
'post_title' => $post_title,
'post_status' => $post_status,
'post_name' => $post_title,
'post_type' => 'quads-ads',
);
$post_id = wp_insert_post($ads_post);
$visibility_include =array();
$visibility_include[0]['type']['label'] = 'Post Type';
$visibility_include[0]['type']['value'] = 'post_type';
$visibility_include[0]['value']['label'] = "post";
$visibility_include[0]['value']['value'] = "post";
$doubleclick_ad_data_slot = explode('/', $redux_builder_amp['ampforwp-doubleclick-ad-data-slot-incontent-ad-'.$i]);
$adlabel = 'above';
if($redux_builder_amp['ampforwp-ad-sponsorship-location'] == '2'){
$adlabel = 'below';
}
$paragraph_number = '1';
switch ($position) {
case '20-percent':
$position = 'after_the_percentage';
$after_the_percentage_value = '20';
break;
case '40-percent':
$position = 'after_the_percentage';
$after_the_percentage_value = '40';
break;
case '50-percent':
$position = 'after_the_percentage';
$after_the_percentage_value = '50';
break;
case '60-percent':
$position = 'after_the_percentage';
$after_the_percentage_value = '60';
break;
case '80-percent':
$position = 'after_the_percentage';
$after_the_percentage_value = '80';
break;
case 'custom':
$position = 'code';
break;
default:
if(is_numeric($position)){
$paragraph_number = $position;
$position = 'after_paragraph';
}
break;
}
$network_code = '';
$doubleclick_flag = 2;
if(isset($doubleclick_ad_data_slot[0]) && !empty($doubleclick_ad_data_slot[0])){
$doubleclick_flag = 3;
$network_code = $doubleclick_ad_data_slot[0];
}
if(isset($doubleclick_ad_data_slot[1]) && !empty($doubleclick_ad_data_slot[1])){
if($doubleclick_flag == 3){
$ad_unit_name = $doubleclick_ad_data_slot[1];
}else{
$network_code = $doubleclick_ad_data_slot[1];
if(isset($doubleclick_ad_data_slot[2]) && !empty($doubleclick_ad_data_slot[2])){
$ad_unit_name = $doubleclick_ad_data_slot[2];
}
}
}
$adforwp_meta_key = array(
'ad_type' => $ad_type_label ,
'g_data_ad_client' => $redux_builder_amp['ampforwp-adsense-ad-data-ad-client-incontent-ad-'.$i],
'g_data_ad_slot' => $redux_builder_amp['ampforwp-adsense-ad-data-ad-slot-incontent-ad-'.$i],
'data_publisher' => $redux_builder_amp['ampforwp-mgid-ad-Data-Publisher-incontent-ad-'.$i],
'data_widget' => $redux_builder_amp['ampforwp-mgid-ad-Data-Widget-incontent-ad-'.$i],
'data_container' => $redux_builder_amp['ampforwp-mgid-ad-Data-Container-incontent-ad-'.$i],
'network_code' => $network_code,
'ad_unit_name' => $ad_unit_name,
'code' => $redux_builder_amp['ampforwp-custom-advertisement-incontent-ad-'.$i],
'g_data_ad_width' => $g_data_ad_width,
'g_data_ad_height' => $g_data_ad_height,
'adsense_type' => $adsense_type,
'enabled_on_amp' => 1,
'visibility_include' => $visibility_include,
'position' => $position,
'after_the_percentage_value' => $after_the_percentage_value,
'paragraph_number' => $paragraph_number,
'imported_from' => 'ampforwp_ads',
'label' => $post_title,
'ad_id' => $post_id,
'enable_one_end_of_post' =>'',
'quads_ad_old_id' => 'ad'.$ad_count,
'ad_label_check' => $redux_builder_amp['ampforwp-ad-sponsorship'],
'adlabel' => $adlabel,
'ad_label_text' => $redux_builder_amp['ampforwp-ad-sponsorship-label'],
);
foreach ($adforwp_meta_key as $key => $val){
update_post_meta($post_id, $key, $val);
}
require_once QUADS_PLUGIN_DIR . '/admin/includes/migration-service.php';
$this->migration_service = new QUADS_Ad_Migration();
$this->migration_service->quadsUpdateOldAd('ad'.$ad_count, $adforwp_meta_key);
}
// General Ads
for($i=1; $i<=10; $i++){
if($amp_options['ampforwp-standard-ads-'.$i] != 1){
continue;
}
$ad_type = $amp_options['ampforwp-advertisement-type-standard-'.$i];
if(($ad_type== '1' && (empty($redux_builder_amp['ampforwp-adsense-ad-data-ad-client-standard-'.$i]) || empty($redux_builder_amp['ampforwp-adsense-ad-data-ad-slot-standard-'.$i])))|| ($ad_type== '2' && empty($redux_builder_amp['ampforwp-doubleclick-ad-data-slot-standard-'.$i])) || ($ad_type== '5' && (empty($redux_builder_amp['ampforwp-mgid-data-ad-data-publisher-standard-'.$i]) || empty($redux_builder_amp['ampforwp-mgid-data-ad-data-widget-standard-'.$i])))){
continue;
}
$ad_count++;
switch ($i) {
case 1:
$position = 'amp_below_the_header';
break;
case 2:
$position = 'amp_below_the_footer';
break;
case 3:
$position = 'amp_above_the_footer';
break;
case 4:
$position = 'amp_above_the_post_content';
break;
case 5:
$position = 'amp_below_the_post_content';
break;
case 6:
$position = 'amp_below_the_title';
break;
case 7:
$position = 'amp_above_related_post';
break;
case 8:
$position = 'amp_below_author_box';
break;
case 9:
$position = 'amp_ads_in_loops';
break;
case 10:
$position = 'amp_doubleclick_sticky_ad';
break;
}
$g_data_ad_width = '';
$g_data_ad_height= '';
$adsense_type = 'normal';
if($ad_type == '1'){
$ad_type_label = 'adsense';
$post_title = 'Adsense Ad '.$i.' General Options (Migrated from AMP)';
$g_data_ad_width = $redux_builder_amp['ampforwp-adsense-ad-width-standard-'.$i];
$g_data_ad_height = $redux_builder_amp['ampforwp-adsense-ad-height-standard-'.$i];
if($amp_options['adsense-rspv-ad-type-standard-'.$i]){
$adsense_type = 'responsive';
}else{
$adsense_type = 'normal';
}
}else if($ad_type == '2'){
$ad_type_label = 'double_click';
$post_title = 'DoubleClick Ad '.$i.' General Options (Migrated from AMP)';
$g_data_ad_width = $redux_builder_amp['ampforwp-doubleclick-ad-width-standard-'.$i];
$g_data_ad_height = $redux_builder_amp['ampforwp-doubleclick-ad-height-standard-'.$i];
$adsense_type = 'normal';
}else if($ad_type == '3'){
$ad_type_label = 'plain_text';
$post_title = 'Ad '.$i.' General Options (Migrated from AMP)';
}else if($ad_type == '5'){
$ad_type_label = 'mgid';
$post_title ='MGID Ad '.$i.' General Options (Migrated from AMP)';
$g_data_ad_width = $redux_builder_amp['ampforwp-mgid-ad-width-standard-'.$i];
$g_data_ad_height = $redux_builder_amp['ampforwp-mgid-ad-height-standard-'.$i];
$adsense_type = 'normal';
}
$ads_post = array(
'post_author' => $user_id,
'post_title' => $post_title,
'post_status' => $post_status,
'post_name' => $post_title,
'post_type' => 'quads-ads',
);
$post_id = wp_insert_post($ads_post);
$visibility_include =array();
$visibility_include[0]['type']['label'] = 'Post Type';
$visibility_include[0]['type']['value'] = 'post_type';
$visibility_include[0]['value']['label'] = "post";
$visibility_include[0]['value']['value'] = "post";
$network_code = '';
$ad_unit_name = '';
$doubleclick_flag = 2;
$doubleclick_ad_data_slot = explode('/', $redux_builder_amp['ampforwp-doubleclick-ad-data-slot-standard-'.$i]);
if(isset($doubleclick_ad_data_slot[0]) && !empty($doubleclick_ad_data_slot[0])){
$doubleclick_flag = 3;
$network_code = $doubleclick_ad_data_slot[0];
}
if(isset($doubleclick_ad_data_slot[1]) && !empty($doubleclick_ad_data_slot[1])){
if($doubleclick_flag == 3){
$ad_unit_name = $doubleclick_ad_data_slot[1];
}else{
$network_code = $doubleclick_ad_data_slot[1];
if(isset($doubleclick_ad_data_slot[2]) && !empty($doubleclick_ad_data_slot[2])){
$ad_unit_name = $doubleclick_ad_data_slot[2];
}
}
}
$adforwp_meta_key = array(
'ad_type' => $ad_type_label ,
'g_data_ad_client' => $redux_builder_amp['ampforwp-adsense-ad-data-ad-client-standard-'.$i],
'g_data_ad_slot' => $redux_builder_amp['ampforwp-adsense-ad-data-ad-slot-standard-'.$i],
'data_publisher' => $redux_builder_amp['ampforwp-mgid-ad-Data-Publisher-standard-'.$i],
'data_widget' => $redux_builder_amp['ampforwp-mgid-ad-Data-Widget-standard-'.$i],
'data_container' => $redux_builder_amp['ampforwp-mgid-ad-Data-Container-standard-'.$i],
'network_code' => $network_code,
'ad_unit_name' => $ad_unit_name,
'code' => $redux_builder_amp['ampforwp-custom-advertisement-standard-'.$i],
'g_data_ad_width' => $g_data_ad_width,
'g_data_ad_height' => $g_data_ad_height,
'adsense_type' => $adsense_type,
'enabled_on_amp' => 1,
'visibility_include' => $visibility_include,
'position' => $position,
'imported_from' => 'ampforwp_ads',
'label' => $post_title,
'ad_id' => $post_id,
'enable_one_end_of_post' => '',
'quads_ad_old_id' => 'ad'.$ad_count,
'ad_label_check' => $redux_builder_amp['ampforwp-ad-sponsorship'],
'adlabel' => $adlabel,
'ad_label_text' => $redux_builder_amp['ampforwp-ad-sponsorship-label'],
);
foreach ($adforwp_meta_key as $key => $val){
update_post_meta($post_id, $key, $val);
}
require_once QUADS_PLUGIN_DIR . '/admin/includes/migration-service.php';
$this->migration_service = new QUADS_Ad_Migration();
$this->migration_service->quadsUpdateOldAd('ad'.$ad_count, $adforwp_meta_key);
}
if($amp_options['ampforwp-after-featured-image-ad']){
$ad_count++;
$ad_type = $amp_options['ampforwp-after-featured-image-ad-type'];
$g_data_ad_width = '';
$g_data_ad_height = '';
$adsense_type = 'normal';
if($ad_type == '1'){
$ad_type_label = 'adsense';
$post_title = 'Adsense Ad '.$ad_count.' (Migrated from AMP)';
$g_data_ad_width = $redux_builder_amp['ampforwp-after-featured-image-ad-type-1-width'];
$g_data_ad_height = $redux_builder_amp['ampforwp-after-featured-image-ad-type-1-height'];
if($redux_builder_amp['adsense-rspv-ad-after-featured-img']){
$adsense_type = 'responsive';
}else{
$adsense_type = 'normal';
}
}else if($ad_type == '2'){
$ad_type_label = 'double_click';
$post_title = 'DoubleClick Ad '.$ad_count.' (Migrated from AMP)';
$g_data_ad_width = $redux_builder_amp['ampforwp-after-featured-image-ad-type-2-width'];
$g_data_ad_height = $redux_builder_amp['ampforwp-after-featured-image-ad-type-2-height'];
}else if($ad_type == '3'){
$ad_type_label = 'plain_text';
$post_title = 'Adsense Ad '.$ad_count.' (Migrated from AMP)';
}else if($ad_type == '5'){
$ad_type_label = 'mgid';
$post_title = 'MGID Ad '.$ad_count.' (Migrated from AMP)';
$g_data_ad_width = $redux_builder_amp['ampforwp-after-featured-image-ad-type-5-width'];
$g_data_ad_height = $redux_builder_amp['ampforwp-after-featured-image-ad-type-5-height'];
}
$network_code = '';
$ad_unit_name = '';
$doubleclick_flag = 2;
$doubleclick_ad_data_slot = explode('/', $redux_builder_amp['ampforwp-after-featured-image-ad-type-2-ad-data-slot']);
if(isset($doubleclick_ad_data_slot[0]) && !empty($doubleclick_ad_data_slot[0])){
$doubleclick_flag = 3;
$network_code = $doubleclick_ad_data_slot[0];
}
if(isset($doubleclick_ad_data_slot[1]) && !empty($doubleclick_ad_data_slot[1])){
if($doubleclick_flag == 3){
$ad_unit_name = $doubleclick_ad_data_slot[1];
}else{
$network_code = $doubleclick_ad_data_slot[1];
if(isset($doubleclick_ad_data_slot[2]) && !empty($doubleclick_ad_data_slot[2])){
$ad_unit_name = $doubleclick_ad_data_slot[2];
}
}
}
$visibility_include =array();
$visibility_include[0]['type']['label'] = 'Post Type';
$visibility_include[0]['type']['value'] = 'post_type';
$visibility_include[0]['value']['label'] = "post";
$visibility_include[0]['value']['value'] = "post";
$ads_post = array(
'post_author' => $user_id,
'post_title' => $post_title,
'post_status' => $post_status,
'post_name' => $post_title,
'post_type' => 'quads-ads',
);
$post_id = wp_insert_post($ads_post);
$adforwp_meta_key = array(
'ad_type' => $ad_type_label ,
'g_data_ad_client' => $redux_builder_amp['ampforwp-after-featured-image-ad-type-1-data-ad-client'],
'g_data_ad_slot' => $redux_builder_amp['ampforwp-after-featured-image-ad-type-1-data-ad-slot'],
'data_publisher' => $redux_builder_amp['ampforwp-after-featured-image-ad-type-5-Data-publisher'],
'data_widget' => $redux_builder_amp['ampforwp-after-featured-image-ad-type-5-Data-widget'],
'data_container' => $redux_builder_amp['ampforwp-after-featured-image-ad-type-5-Data-Container'],
'network_code' => $network_code,
'ad_unit_name' => $ad_unit_name,
'code' => $redux_builder_amp['ampforwp-after-featured-image-ad-custom-advertisement'],
'g_data_ad_width' => $g_data_ad_width,
'g_data_ad_height' => $g_data_ad_height,
'adsense_type' => $adsense_type,
'enabled_on_amp' => 1,
'visibility_include' => $visibility_include,
'position' => 'amp_after_featured_image',
'imported_from' => 'ampforwp_ads',
'label' => $post_title,
'ad_id' => $post_id,
'enable_one_end_of_post' => '',
'quads_ad_old_id' => 'ad'.$ad_count,
'ad_label_check' => $redux_builder_amp['ampforwp-ad-sponsorship'],
'adlabel' => $adlabel,
'ad_label_text' => $redux_builder_amp['ampforwp-ad-sponsorship-label'],
);
foreach ($adforwp_meta_key as $key => $val){
update_post_meta($post_id, $key, $val);
}
require_once QUADS_PLUGIN_DIR . '/admin/includes/migration-service.php';
$this->migration_service = new QUADS_Ad_Migration();
$this->migration_service->quadsUpdateOldAd('ad'.$ad_count, $adforwp_meta_key);
}
}
return array('status' => 't', 'data' => 'Ads have been successfully imported');
}
}

View File

@@ -0,0 +1,824 @@
<?php // phpcs:ignoreFile
/**
* Amp for WP Ads.
*
* @package AdvancedAds
* @author Advanced Ads <info@wpadvancedads.com>
* @since 1.50.0
*/
namespace AdvancedAds\Importers;
use AdvancedAds\Framework\Utilities\Params;
use AdvancedAds\Interfaces\Importer as Interface_Importer;
defined( 'ABSPATH' ) || exit;
/**
* Amp for WP Ads.
*/
class Amp_WP_Ads extends Importer implements Interface_Importer {
/**
* Get the unique identifier (ID) of the importer.
*
* @return string The unique ID of the importer.
*/
public function get_id(): string {
return 'amp_wp_ads';
}
/**
* Get the title or name of the importer.
*
* @return string The title of the importer.
*/
public function get_title(): string {
return __( 'AMP for WP Ads', 'advanced-ads' );
}
/**
* Get a description of the importer.
*
* @return string The description of the importer.
*/
public function get_description(): string {
return '';
}
/**
* Get the icon to this importer.
*
* @return string The icon for the importer.
*/
public function get_icon(): string {
return '<span class="dashicons dashicons-insert"></span>';
}
/**
* Detect the importer in database.
*
* @return bool True if detected; otherwise, false.
*/
public function detect(): bool {
return false;
}
/**
* Render form.
*
* @return void
*/
public function render_form(): void {
?>
<fieldset>
<p><label><input type="radio" name="import_type" checked="checked" /> <?php esc_html_e( 'Import Ads', 'advanced-ads' ); ?></label></p>
<p><label><input type="radio" name="import_type" /> <?php esc_html_e( 'Import Groups', 'advanced-ads' ); ?></label></p>
<p><label><input type="radio" name="import_type" /> <?php esc_html_e( 'Import Placements', 'advanced-ads' ); ?></label></p>
<p><label><input type="radio" name="import_type" /> <?php esc_html_e( 'Import Settings', 'advanced-ads' ); ?></label></p>
</fieldset>
<?php
}
/**
* Import data.
*
* @return WP_Error|string
*/
public function import() {
return '';
}
public function adsforwp_migrate_ampforwp_ads(){
if ( ! current_user_can( 'manage_options' ) ) {
return;
}
$nonce = Params::get( 'adsforwp_security_nonce', '' );
if ( ! $nonce || ! wp_verify_nonce( $nonce, 'adsforwp_ajax_check_nonce' ) ){
return;
}
$result = array();
$adforwp_meta_key = array();
$amp_options = get_option('redux_builder_amp');
$user_id = get_current_user_id();
$ad_size = array('1'=> '300x250','2'=> '336x280','3'=> '728x90','4'=> '300x600', '5'=> '320x100', '6'=> '200x50', '7'=> '320x50');
$wheretodisplayamp = array(
'1' => 'adsforwp_below_the_header',
'2' => 'adsforwp_below_the_footer',
'3' => 'adsforwp_above_the_post_content',
'4' => 'adsforwp_below_the_post_content',
'5' => 'adsforwp_below_the_title',
'6' => 'adsforwp_above_related_post',
);
if($amp_options){
for($i=1; $i<=6; $i++){
$amp_options['enable-amp-ads-select-'.$i];
$amp_options['enable-amp-ads-text-feild-client-'.$i];
$amp_options['enable-amp-ads-text-feild-slot-'.$i];
$ads_post = array(
'post_author' => $user_id,
'post_title' => 'Adsense Ad '.$i.' (Migrated from AMP)',
'post_status' => 'publish',
'post_name' => 'Adsense Ad '.$i.' (Migrated from AMP)',
'post_type' => 'adsforwp',
);
if($amp_options['enable-amp-ads-'.$i] == 1){
$post_id = wp_insert_post($ads_post);
$data_group_array = array();
$conditions = array();
if($i==3){
if(isset($amp_options['made-amp-ad-3-global'])){
$conditions = $amp_options['made-amp-ad-3-global'];
if(!empty($conditions)){
for($k = 0; $k <count($conditions); $k++){
$displayon = '';
$key_type = '';
if($conditions[$k] == 1){ //Single
$displayon = 'post';
$key_type = 'post_type';
}else if($conditions[$k] == 2){ //pages
$displayon = 'page';
$key_type = 'post_type';
}else if($conditions[$k] == 3){ //custom post type
$displayon = 'post';
$key_type = 'post_type';
}else if ($conditions[$k] == 4){ //global
unset($data_group_array);
$displayon = 'post';
$key_type = 'show_globally';
}
$data_group_array['group-'.$k] = array(
'data_array' => array(
array(
'key_1' => $key_type,
'key_2' => 'equal',
'key_3' => $displayon,
)
)
);
}
}else{
$data_group_array['group-0'] = array(
'data_array' => array(
array(
'key_1' => 'show_globally',
'key_2' => 'equal',
'key_3' => 'post',
)
)
);
}
}
}else{
if($i == 4 || $i == 5 || $i == 6){
$con_key = 'post_type';
}else{
$con_key = 'show_globally';
}
$data_group_array['group-0'] =array(
'data_array' => array(
array(
'key_1' => $con_key,
'key_2' => 'equal',
'key_3' => 'post',
)
)
);
}
$adforwp_meta_key = array(
'select_adtype' => 'adsense',
'adsense_type' => 'normal',
'data_client_id' => $amp_options['enable-amp-ads-text-feild-client-'.$i],
'data_ad_slot' => $amp_options['enable-amp-ads-text-feild-slot-'.$i],
'banner_size' => $ad_size[$amp_options['enable-amp-ads-select-'.$i]],
'adsforwp_ad_responsive' => $amp_options['enable-amp-ads-resp-'.$i],
'wheretodisplay' => $wheretodisplayamp[$i],
'adsforwp_ad_align' => 'center',
'ads_for_wp_non_amp_visibility' => 'hide',
'imported_from' => 'ampforwp_ads',
'data_group_array' => $data_group_array
);
foreach ($adforwp_meta_key as $key => $val){
$result[] = update_post_meta($post_id, $key, $val);
}
}
}
$options = array();
$settings = get_option( 'adsforwp_settings');
$options['ad_sponsorship_label'] = $amp_options['ampforwp-ads-sponsorship'];
$options['ad_sponsorship_label_text'] = $amp_options['ampforwp-ads-sponsorship-label'];
$options = array_merge($settings,$options);
update_option('adsforwp_settings', $options); // Security: Permission and nonce verified
}
return $result;
}
public function importampforwp_ads(){
global $redux_builder_amp;
$args = array(
'post_type' => 'quads-ads'
);
$the_query = new WP_Query( $args );
$ad_count = $the_query->found_posts;
$post_status = 'publish';
$amp_options = get_option('redux_builder_amp');
$user_id = get_current_user_id();
$after_the_percentage_value = '';
for($i=1; $i<=6; $i++){
if($amp_options['enable-amp-ads-'.$i] != 1){
continue;
}
$ad_type = $amp_options['enable-amp-ads-type-'.$i];
if(($ad_type== 'adsense' && (empty($amp_options['enable-amp-ads-text-feild-client-'.$i]) || empty($amp_options['enable-amp-ads-text-feild-slot-'.$i]))) || ($ad_type== 'mgid' && (empty($amp_options['enable-amp-ads-mgid-field-data-pub-'.$i]) || empty($amp_options['enable-amp-ads-mgid-field-data-widget-'.$i])))){
continue;
}
$ad_count++;
switch ($i) {
case 1:
$position = 'amp_below_the_header';
break;
case 2:
$position = 'amp_below_the_footer';
break;
case 3:
$position = 'amp_above_the_post_content';
break;
case 4:
$position = 'amp_below_the_post_content';
break;
case 5:
$position = 'amp_below_the_title';
break;
case 6:
$position = 'amp_above_related_post';
break;
}
switch ($amp_options['enable-amp-ads-select-'.$i]) {
case '1':
$g_data_ad_width = '300';
$g_data_ad_height = '250';
break;
case '2':
$g_data_ad_width = '336';
$g_data_ad_height = '280';
break;
case '3':
$g_data_ad_width = '728';
$g_data_ad_height = '90';
break;
case '4':
$g_data_ad_width = '300';
$g_data_ad_height = '600';
break;
case '5':
$g_data_ad_width = '320';
$g_data_ad_height = '100';
break;
case '6':
$g_data_ad_width = '200';
$g_data_ad_height = '50';
break;
case '7':
$g_data_ad_width = '320';
$g_data_ad_height = '50';
break;
default:
$g_data_ad_width = '300';
$g_data_ad_height= '250';
break;
}
if($ad_type== 'mgid'){
if($i == 2){
$position = 'ad_shortcode';
}
$post_title ='MGID Ad '.$i.' (Migrated from AMP)';
$g_data_ad_width = $amp_options['enable-amp-ads-mgid-width-'.$i];
$g_data_ad_height= $amp_options['enable-amp-ads-mgid-height-'.$i];
}else{
$post_title ='Adsense Ad '.$i.' (Migrated from AMP)';
}
$ads_post = array(
'post_author' => $user_id,
'post_title' => $post_title,
'post_status' => $post_status,
'post_name' => $post_title,
'post_type' => 'quads-ads',
);
if($amp_options['enable-amp-ads-resp-'.$i]){
$adsense_type = 'responsive';
}else{
$adsense_type = 'normal';
}
$post_id = wp_insert_post($ads_post);
$visibility_include =array();
if($i == 3){
$display_on = $amp_options['made-amp-ad-3-global'];
$j =0;
foreach ($display_on as $display_on_data) {
switch ($display_on_data) {
case '1':
$visibility_include[$j]['type']['label'] = 'Post Type';
$visibility_include[$j]['type']['value'] = 'post_type';
$visibility_include[$j]['value']['label'] = "post";
$visibility_include[$j]['value']['value'] = "post";
$j++;
break;
case '2':
$visibility_include[$j]['type']['label'] = 'Post Type';
$visibility_include[$j]['type']['value'] = 'post_type';
$visibility_include[$j]['value']['label'] = "page";
$visibility_include[$j]['value']['value'] = "page";
$j++;
break;
case '4':
$visibility_include[$j]['type']['label'] = 'General';
$visibility_include[$j]['type']['value'] = 'general';
$visibility_include[$j]['value']['label'] = "Show Globally";
$visibility_include[$j]['value']['value'] = "show_globally";
$j++;
break;
}
}
}else{
$visibility_include[0]['type']['label'] = 'General';
$visibility_include[0]['type']['value'] = 'general';
$visibility_include[0]['value']['label'] = "Show Globally";
$visibility_include[0]['value']['value'] = "show_globally";
}
$adforwp_meta_key = array(
'ad_type' => $ad_type ,
'g_data_ad_client' => $amp_options['enable-amp-ads-text-feild-client-'.$i],
'g_data_ad_slot' => $amp_options['enable-amp-ads-text-feild-slot-'.$i],
'data_publisher' => $amp_options['enable-amp-ads-mgid-field-data-pub-'.$i],
'data_widget' => $amp_options['enable-amp-ads-mgid-field-data-widget-'.$i],
'data_container' => $amp_options['enable-amp-ads-mgid-field-data-con-'.$i],
'g_data_ad_width' => $g_data_ad_width,
'g_data_ad_height' => $g_data_ad_height,
'adsense_type' => $adsense_type,
'enabled_on_amp' => 1,
'visibility_include' => $visibility_include,
'position' => $position,
'imported_from' => 'ampforwp_ads',
'label' => $post_title,
'ad_id' => $post_id,
'code' => '',
'enable_one_end_of_post' =>'',
'quads_ad_old_id' => 'ad'.$ad_count,
'ad_label_check' => $amp_options['ampforwp-ads-sponsorship'],
'ad_label_text' => $amp_options['ampforwp-ads-sponsorship-label'],
);
foreach ($adforwp_meta_key as $key => $val){
update_post_meta($post_id, $key, $val);
}
}
if ( defined( 'ADVANCED_AMP_ADS_VERSION' ) ) {
// Incontent Ads
for($i=1; $i<=6; $i++){
if($redux_builder_amp['ampforwp-incontent-ad-'.$i] != 1){
continue;
}
$ad_type = $redux_builder_amp['ampforwp-advertisement-type-incontent-ad-'.$i];
$ad_type_label = '';
if($ad_type== '4'){
continue;
}
if(($ad_type== '1' && (empty($redux_builder_amp['ampforwp-adsense-ad-data-ad-client-incontent-ad-'.$i]) || empty($redux_builder_amp['ampforwp-adsense-ad-data-ad-slot-incontent-ad-'.$i]))) || ($ad_type== '5' && (empty($redux_builder_amp['ampforwp-mgid-ad-Data-Publisher-incontent-ad-'.$i]) || empty($redux_builder_amp['ampforwp-mgid-ad-Data-Widget-incontent-ad-'.$i])))){
continue;
}
$ad_count++;
$g_data_ad_width = '';
$g_data_ad_height= '';
if($ad_type == '1'){
$ad_type_label = 'adsense';
$post_title = 'Adsense Ad '.$i.' Incontent Ad (Migrated from AMP)';
$g_data_ad_width = $redux_builder_amp['ampforwp-adsense-ad-width-incontent-ad-'.$i];
$g_data_ad_height = $redux_builder_amp['ampforwp-adsense-ad-height-incontent-ad-'.$i];
$position = $redux_builder_amp['ampforwp-adsense-ad-position-incontent-ad-'.$i];
}else if($ad_type == '2'){
$ad_type_label = 'double_click';
$post_title = 'DoubleClick Ad '.$i.' Incontent Ad (Migrated from AMP)';
$g_data_ad_width = $redux_builder_amp['ampforwp-doubleclick-ad-width-incontent-ad-'.$i];
$g_data_ad_height = $redux_builder_amp['ampforwp-doubleclick-ad-height-incontent-ad-'.$i];
$position = $redux_builder_amp['ampforwp-doubleclick-ad-position-incontent-ad-'.$i];
}else if($ad_type == '3'){
$ad_type_label = 'plain_text';
$post_title = 'Plain Text Ad '.$i.' Incontent Ad (Migrated from AMP)';
$position = $redux_builder_amp['ampforwp-custom-ads-ad-position-incontent-ad-'.$i];
}else if($ad_type == '5'){
$ad_type_label = 'mgid';
$post_title ='MGID Ad '.$i.' Incontent Ad (Migrated from AMP)';
$g_data_ad_width = $redux_builder_amp['ampforwp-mgid-ad-width-incontent-ad-'.$i];
$g_data_ad_height = $redux_builder_amp['ampforwp-mgid-ad-height-incontent-ad-'.$i];
$position = $redux_builder_amp['ampforwp-mgid-ad-position-incontent-ad-'.$i];
}
if($redux_builder_amp['adsense-rspv-ad-incontent-'.$i]){
$adsense_type = 'responsive';
}else{
$adsense_type = 'normal';
}
$ads_post = array(
'post_author' => $user_id,
'post_title' => $post_title,
'post_status' => $post_status,
'post_name' => $post_title,
'post_type' => 'quads-ads',
);
$post_id = wp_insert_post($ads_post);
$visibility_include =array();
$visibility_include[0]['type']['label'] = 'Post Type';
$visibility_include[0]['type']['value'] = 'post_type';
$visibility_include[0]['value']['label'] = "post";
$visibility_include[0]['value']['value'] = "post";
$doubleclick_ad_data_slot = explode('/', $redux_builder_amp['ampforwp-doubleclick-ad-data-slot-incontent-ad-'.$i]);
$adlabel = 'above';
if($redux_builder_amp['ampforwp-ad-sponsorship-location'] == '2'){
$adlabel = 'below';
}
$paragraph_number = '1';
switch ($position) {
case '20-percent':
$position = 'after_the_percentage';
$after_the_percentage_value = '20';
break;
case '40-percent':
$position = 'after_the_percentage';
$after_the_percentage_value = '40';
break;
case '50-percent':
$position = 'after_the_percentage';
$after_the_percentage_value = '50';
break;
case '60-percent':
$position = 'after_the_percentage';
$after_the_percentage_value = '60';
break;
case '80-percent':
$position = 'after_the_percentage';
$after_the_percentage_value = '80';
break;
case 'custom':
$position = 'code';
break;
default:
if(is_numeric($position)){
$paragraph_number = $position;
$position = 'after_paragraph';
}
break;
}
$network_code = '';
$doubleclick_flag = 2;
if(isset($doubleclick_ad_data_slot[0]) && !empty($doubleclick_ad_data_slot[0])){
$doubleclick_flag = 3;
$network_code = $doubleclick_ad_data_slot[0];
}
if(isset($doubleclick_ad_data_slot[1]) && !empty($doubleclick_ad_data_slot[1])){
if($doubleclick_flag == 3){
$ad_unit_name = $doubleclick_ad_data_slot[1];
}else{
$network_code = $doubleclick_ad_data_slot[1];
if(isset($doubleclick_ad_data_slot[2]) && !empty($doubleclick_ad_data_slot[2])){
$ad_unit_name = $doubleclick_ad_data_slot[2];
}
}
}
$adforwp_meta_key = array(
'ad_type' => $ad_type_label ,
'g_data_ad_client' => $redux_builder_amp['ampforwp-adsense-ad-data-ad-client-incontent-ad-'.$i],
'g_data_ad_slot' => $redux_builder_amp['ampforwp-adsense-ad-data-ad-slot-incontent-ad-'.$i],
'data_publisher' => $redux_builder_amp['ampforwp-mgid-ad-Data-Publisher-incontent-ad-'.$i],
'data_widget' => $redux_builder_amp['ampforwp-mgid-ad-Data-Widget-incontent-ad-'.$i],
'data_container' => $redux_builder_amp['ampforwp-mgid-ad-Data-Container-incontent-ad-'.$i],
'network_code' => $network_code,
'ad_unit_name' => $ad_unit_name,
'code' => $redux_builder_amp['ampforwp-custom-advertisement-incontent-ad-'.$i],
'g_data_ad_width' => $g_data_ad_width,
'g_data_ad_height' => $g_data_ad_height,
'adsense_type' => $adsense_type,
'enabled_on_amp' => 1,
'visibility_include' => $visibility_include,
'position' => $position,
'after_the_percentage_value' => $after_the_percentage_value,
'paragraph_number' => $paragraph_number,
'imported_from' => 'ampforwp_ads',
'label' => $post_title,
'ad_id' => $post_id,
'enable_one_end_of_post' =>'',
'quads_ad_old_id' => 'ad'.$ad_count,
'ad_label_check' => $redux_builder_amp['ampforwp-ad-sponsorship'],
'adlabel' => $adlabel,
'ad_label_text' => $redux_builder_amp['ampforwp-ad-sponsorship-label'],
);
foreach ($adforwp_meta_key as $key => $val){
update_post_meta($post_id, $key, $val);
}
require_once QUADS_PLUGIN_DIR . '/admin/includes/migration-service.php';
$this->migration_service = new QUADS_Ad_Migration();
$this->migration_service->quadsUpdateOldAd('ad'.$ad_count, $adforwp_meta_key);
}
// General Ads
for($i=1; $i<=10; $i++){
if($amp_options['ampforwp-standard-ads-'.$i] != 1){
continue;
}
$ad_type = $amp_options['ampforwp-advertisement-type-standard-'.$i];
if(($ad_type== '1' && (empty($redux_builder_amp['ampforwp-adsense-ad-data-ad-client-standard-'.$i]) || empty($redux_builder_amp['ampforwp-adsense-ad-data-ad-slot-standard-'.$i])))|| ($ad_type== '2' && empty($redux_builder_amp['ampforwp-doubleclick-ad-data-slot-standard-'.$i])) || ($ad_type== '5' && (empty($redux_builder_amp['ampforwp-mgid-data-ad-data-publisher-standard-'.$i]) || empty($redux_builder_amp['ampforwp-mgid-data-ad-data-widget-standard-'.$i])))){
continue;
}
$ad_count++;
switch ($i) {
case 1:
$position = 'amp_below_the_header';
break;
case 2:
$position = 'amp_below_the_footer';
break;
case 3:
$position = 'amp_above_the_footer';
break;
case 4:
$position = 'amp_above_the_post_content';
break;
case 5:
$position = 'amp_below_the_post_content';
break;
case 6:
$position = 'amp_below_the_title';
break;
case 7:
$position = 'amp_above_related_post';
break;
case 8:
$position = 'amp_below_author_box';
break;
case 9:
$position = 'amp_ads_in_loops';
break;
case 10:
$position = 'amp_doubleclick_sticky_ad';
break;
}
$g_data_ad_width = '';
$g_data_ad_height= '';
$adsense_type = 'normal';
if($ad_type == '1'){
$ad_type_label = 'adsense';
$post_title = 'Adsense Ad '.$i.' General Options (Migrated from AMP)';
$g_data_ad_width = $redux_builder_amp['ampforwp-adsense-ad-width-standard-'.$i];
$g_data_ad_height = $redux_builder_amp['ampforwp-adsense-ad-height-standard-'.$i];
if($amp_options['adsense-rspv-ad-type-standard-'.$i]){
$adsense_type = 'responsive';
}else{
$adsense_type = 'normal';
}
}else if($ad_type == '2'){
$ad_type_label = 'double_click';
$post_title = 'DoubleClick Ad '.$i.' General Options (Migrated from AMP)';
$g_data_ad_width = $redux_builder_amp['ampforwp-doubleclick-ad-width-standard-'.$i];
$g_data_ad_height = $redux_builder_amp['ampforwp-doubleclick-ad-height-standard-'.$i];
$adsense_type = 'normal';
}else if($ad_type == '3'){
$ad_type_label = 'plain_text';
$post_title = 'Ad '.$i.' General Options (Migrated from AMP)';
}else if($ad_type == '5'){
$ad_type_label = 'mgid';
$post_title ='MGID Ad '.$i.' General Options (Migrated from AMP)';
$g_data_ad_width = $redux_builder_amp['ampforwp-mgid-ad-width-standard-'.$i];
$g_data_ad_height = $redux_builder_amp['ampforwp-mgid-ad-height-standard-'.$i];
$adsense_type = 'normal';
}
$ads_post = array(
'post_author' => $user_id,
'post_title' => $post_title,
'post_status' => $post_status,
'post_name' => $post_title,
'post_type' => 'quads-ads',
);
$post_id = wp_insert_post($ads_post);
$visibility_include =array();
$visibility_include[0]['type']['label'] = 'Post Type';
$visibility_include[0]['type']['value'] = 'post_type';
$visibility_include[0]['value']['label'] = "post";
$visibility_include[0]['value']['value'] = "post";
$network_code = '';
$ad_unit_name = '';
$doubleclick_flag = 2;
$doubleclick_ad_data_slot = explode('/', $redux_builder_amp['ampforwp-doubleclick-ad-data-slot-standard-'.$i]);
if(isset($doubleclick_ad_data_slot[0]) && !empty($doubleclick_ad_data_slot[0])){
$doubleclick_flag = 3;
$network_code = $doubleclick_ad_data_slot[0];
}
if(isset($doubleclick_ad_data_slot[1]) && !empty($doubleclick_ad_data_slot[1])){
if($doubleclick_flag == 3){
$ad_unit_name = $doubleclick_ad_data_slot[1];
}else{
$network_code = $doubleclick_ad_data_slot[1];
if(isset($doubleclick_ad_data_slot[2]) && !empty($doubleclick_ad_data_slot[2])){
$ad_unit_name = $doubleclick_ad_data_slot[2];
}
}
}
$adforwp_meta_key = array(
'ad_type' => $ad_type_label ,
'g_data_ad_client' => $redux_builder_amp['ampforwp-adsense-ad-data-ad-client-standard-'.$i],
'g_data_ad_slot' => $redux_builder_amp['ampforwp-adsense-ad-data-ad-slot-standard-'.$i],
'data_publisher' => $redux_builder_amp['ampforwp-mgid-ad-Data-Publisher-standard-'.$i],
'data_widget' => $redux_builder_amp['ampforwp-mgid-ad-Data-Widget-standard-'.$i],
'data_container' => $redux_builder_amp['ampforwp-mgid-ad-Data-Container-standard-'.$i],
'network_code' => $network_code,
'ad_unit_name' => $ad_unit_name,
'code' => $redux_builder_amp['ampforwp-custom-advertisement-standard-'.$i],
'g_data_ad_width' => $g_data_ad_width,
'g_data_ad_height' => $g_data_ad_height,
'adsense_type' => $adsense_type,
'enabled_on_amp' => 1,
'visibility_include' => $visibility_include,
'position' => $position,
'imported_from' => 'ampforwp_ads',
'label' => $post_title,
'ad_id' => $post_id,
'enable_one_end_of_post' => '',
'quads_ad_old_id' => 'ad'.$ad_count,
'ad_label_check' => $redux_builder_amp['ampforwp-ad-sponsorship'],
'adlabel' => $adlabel,
'ad_label_text' => $redux_builder_amp['ampforwp-ad-sponsorship-label'],
);
foreach ($adforwp_meta_key as $key => $val){
update_post_meta($post_id, $key, $val);
}
require_once QUADS_PLUGIN_DIR . '/admin/includes/migration-service.php';
$this->migration_service = new QUADS_Ad_Migration();
$this->migration_service->quadsUpdateOldAd('ad'.$ad_count, $adforwp_meta_key);
}
if($amp_options['ampforwp-after-featured-image-ad']){
$ad_count++;
$ad_type = $amp_options['ampforwp-after-featured-image-ad-type'];
$g_data_ad_width = '';
$g_data_ad_height = '';
$adsense_type = 'normal';
if($ad_type == '1'){
$ad_type_label = 'adsense';
$post_title = 'Adsense Ad '.$ad_count.' (Migrated from AMP)';
$g_data_ad_width = $redux_builder_amp['ampforwp-after-featured-image-ad-type-1-width'];
$g_data_ad_height = $redux_builder_amp['ampforwp-after-featured-image-ad-type-1-height'];
if($redux_builder_amp['adsense-rspv-ad-after-featured-img']){
$adsense_type = 'responsive';
}else{
$adsense_type = 'normal';
}
}else if($ad_type == '2'){
$ad_type_label = 'double_click';
$post_title = 'DoubleClick Ad '.$ad_count.' (Migrated from AMP)';
$g_data_ad_width = $redux_builder_amp['ampforwp-after-featured-image-ad-type-2-width'];
$g_data_ad_height = $redux_builder_amp['ampforwp-after-featured-image-ad-type-2-height'];
}else if($ad_type == '3'){
$ad_type_label = 'plain_text';
$post_title = 'Adsense Ad '.$ad_count.' (Migrated from AMP)';
}else if($ad_type == '5'){
$ad_type_label = 'mgid';
$post_title = 'MGID Ad '.$ad_count.' (Migrated from AMP)';
$g_data_ad_width = $redux_builder_amp['ampforwp-after-featured-image-ad-type-5-width'];
$g_data_ad_height = $redux_builder_amp['ampforwp-after-featured-image-ad-type-5-height'];
}
$network_code = '';
$ad_unit_name = '';
$doubleclick_flag = 2;
$doubleclick_ad_data_slot = explode('/', $redux_builder_amp['ampforwp-after-featured-image-ad-type-2-ad-data-slot']);
if(isset($doubleclick_ad_data_slot[0]) && !empty($doubleclick_ad_data_slot[0])){
$doubleclick_flag = 3;
$network_code = $doubleclick_ad_data_slot[0];
}
if(isset($doubleclick_ad_data_slot[1]) && !empty($doubleclick_ad_data_slot[1])){
if($doubleclick_flag == 3){
$ad_unit_name = $doubleclick_ad_data_slot[1];
}else{
$network_code = $doubleclick_ad_data_slot[1];
if(isset($doubleclick_ad_data_slot[2]) && !empty($doubleclick_ad_data_slot[2])){
$ad_unit_name = $doubleclick_ad_data_slot[2];
}
}
}
$visibility_include =array();
$visibility_include[0]['type']['label'] = 'Post Type';
$visibility_include[0]['type']['value'] = 'post_type';
$visibility_include[0]['value']['label'] = "post";
$visibility_include[0]['value']['value'] = "post";
$ads_post = array(
'post_author' => $user_id,
'post_title' => $post_title,
'post_status' => $post_status,
'post_name' => $post_title,
'post_type' => 'quads-ads',
);
$post_id = wp_insert_post($ads_post);
$adforwp_meta_key = array(
'ad_type' => $ad_type_label ,
'g_data_ad_client' => $redux_builder_amp['ampforwp-after-featured-image-ad-type-1-data-ad-client'],
'g_data_ad_slot' => $redux_builder_amp['ampforwp-after-featured-image-ad-type-1-data-ad-slot'],
'data_publisher' => $redux_builder_amp['ampforwp-after-featured-image-ad-type-5-Data-publisher'],
'data_widget' => $redux_builder_amp['ampforwp-after-featured-image-ad-type-5-Data-widget'],
'data_container' => $redux_builder_amp['ampforwp-after-featured-image-ad-type-5-Data-Container'],
'network_code' => $network_code,
'ad_unit_name' => $ad_unit_name,
'code' => $redux_builder_amp['ampforwp-after-featured-image-ad-custom-advertisement'],
'g_data_ad_width' => $g_data_ad_width,
'g_data_ad_height' => $g_data_ad_height,
'adsense_type' => $adsense_type,
'enabled_on_amp' => 1,
'visibility_include' => $visibility_include,
'position' => 'amp_after_featured_image',
'imported_from' => 'ampforwp_ads',
'label' => $post_title,
'ad_id' => $post_id,
'enable_one_end_of_post' => '',
'quads_ad_old_id' => 'ad'.$ad_count,
'ad_label_check' => $redux_builder_amp['ampforwp-ad-sponsorship'],
'adlabel' => $adlabel,
'ad_label_text' => $redux_builder_amp['ampforwp-ad-sponsorship-label'],
);
foreach ($adforwp_meta_key as $key => $val){
update_post_meta($post_id, $key, $val);
}
require_once QUADS_PLUGIN_DIR . '/admin/includes/migration-service.php';
$this->migration_service = new QUADS_Ad_Migration();
$this->migration_service->quadsUpdateOldAd('ad'.$ad_count, $adforwp_meta_key);
}
}
return array('status' => 't', 'data' => 'Ads have been successfully imported');
}
}

View File

@@ -0,0 +1,531 @@
<?php
/**
* Auto Ads Creation from api.
*
* @package AdvancedAds
* @author Advanced Ads <info@wpadvancedads.com>
* @since 1.50.0
*/
namespace AdvancedAds\Importers;
use WP_Error;
use AdvancedAds\Constants;
use AdvancedAds\Framework\Utilities\Str;
use AdvancedAds\Modules\OneClick\Helpers;
use AdvancedAds\Interfaces\Importer as Interface_Importer;
use AdvancedAds\Modules\OneClick\Options;
defined( 'ABSPATH' ) || exit;
/**
* Auto Ads Creation.
*/
class Api_Ads extends Importer implements Interface_Importer {
/**
* Author id
*
* @var int
*/
private $author_id = null;
/**
* Hold slot ids from database.
*
* @var array
*/
private $slots = [];
/**
* Get the unique identifier (ID) of the importer.
*
* @return string The unique ID of the importer.
*/
public function get_id(): string {
return 'api_ads';
}
/**
* Get the title or name of the importer.
*
* @return string The title of the importer.
*/
public function get_title(): string {
return __( 'Ads from API', 'advanced-ads' );
}
/**
* Get a description of the importer.
*
* @return string The description of the importer.
*/
public function get_description(): string {
return __( 'For MonetizeMore clients using PubGuru, you will be able to create all of your new ads from api.', 'advanced-ads' );
}
/**
* Get the icon to this importer.
*
* @return string The icon for the importer.
*/
public function get_icon(): string {
return '<span class="dashicons dashicons-media-spreadsheet"></span>';
}
/**
* Detect the importer in database.
*
* @return bool True if detected; otherwise, false.
*/
public function detect(): bool {
return false;
}
/**
* Render form.
*
* @return void
*/
public function render_form(): void {}
/**
* Import data.
*
* @return WP_Error|string
*/
public function import() {
kses_remove_filters();
$this->fetch_created_slots();
// Final import create ads.
$ads = Helpers::get_ads_from_config();
$ads = $this->normalize_ads( $ads );
if ( $ads ) {
$this->rollback_preview();
return $this->create_ads( $ads );
}
}
/**
* Rollback import
*
* @param string $key Session key.
*
* @return void
*/
public function rollback( $key ): void {
parent::rollback( $key );
$this->migrate_old_entities( $key, 'publish' );
$config = Options::pubguru_config();
unset( $config['page'], $config['method'], $config['history_key'] );
Options::pubguru_config( $config );
}
/**
* Rollback Preview mode
*
* @return void
*/
private function rollback_preview(): void {
$config = Options::pubguru_config();
if ( ! $config || ! isset( $config['history_key'] ) ) {
return;
}
parent::rollback( $config['history_key'] );
// Remove keys.
$importers = wp_advads()->importers ?? new Manager();
$importers->delete_session_history( $config['history_key'] );
unset( $config['history_key'] );
Options::pubguru_config( $config );
}
/**
* Get ads from sheet by device
*
* @param array $ads Ads selected by user.
*
* @return string
*/
private function create_ads( $ads ): string {
$count = 0;
$history_key = $this->get_id() . '_' . wp_rand() . '_' . count( $ads );
$this->migrate_old_entities( $history_key, 'draft' );
$this->save_history_key( $history_key );
foreach ( $ads as $data ) {
$ad = wp_advads_create_new_ad( 'plain' );
$ad->set_title( '[PubGuru] Ad # ' . $data['ad_unit'] );
$ad->set_status( 'publish' );
$ad->set_content( sprintf( '<pubguru data-pg-ad="%s"></pubguru>', $data['ad_unit'] ) );
$ad->set_author_id( $this->get_author_id() );
$ad->set_prop( 'pghb_slot_id', $data['ad_unit'] );
if ( 'all' !== $data['device'] ) {
$ad->set_visitor_conditions(
[
[
'type' => 'mobile',
'value' => [ $data['device'] ],
],
]
);
}
$ad_id = $ad->save();
if ( $ad_id > 0 ) {
++$count;
if ( ! wp_advads_has_placement_type( $data['placement'] ) ) {
wp_advads_create_placement_type( $data['placement'] );
}
$placement = wp_advads_create_new_placement( $data['placement'] );
$placement->set_title( '[PubGuru] Placement # ' . $data['ad_unit'] );
$placement->set_item( 'ad_' . $ad_id );
$placement->set_status( 'publish' );
if ( ! empty( $data['placement_conditions'] ) ) {
$placement->set_display_conditions( $data['placement_conditions'] );
}
if ( $placement->is_type( 'post_content' ) ) {
$placement->set_prop( 'position', $data['in_content_position'] );
$placement->set_prop( 'index', $data['in_content_count'] );
$placement->set_prop( 'tag', $data['in_content_element'] );
$placement->set_prop( 'repeat', boolval( $data['in_content_repeat'] ) );
}
$placement->save();
$this->add_session_key( $ad, $placement, $history_key );
}
}
$importers = wp_advads()->importers ?? new Manager();
$importers->add_session_history( $this->get_id(), $history_key, $count );
/* translators: 1: counts 2: Importer title */
return sprintf( __( '%1$d ads migrated from %2$s', 'advanced-ads' ), $count, $this->get_title() );
}
/**
* Get author id
*
* @return int
*/
private function get_author_id(): int {
if ( null !== $this->author_id ) {
return $this->author_id;
}
$users = get_users(
[
'role' => 'Administrator',
'number' => 1,
]
);
$this->author_id = isset( $users[0] ) ? $users[0]->ID : 0;
return $this->author_id;
}
/**
* Fetch created slots from database.
*
* @return void
*/
private function fetch_created_slots(): void {
global $wpdb;
$this->slots = $wpdb->get_col( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.DirectDatabaseQuery.DirectQuery
$wpdb->prepare(
"SELECT meta_value FROM {$wpdb->postmeta} WHERE meta_key = %s",
'pghb_slot_id'
)
);
}
/**
* Migrate old entities
*
* @param string $key Session key.
* @param string $status Status of ads.
*
* @return void
*/
private function migrate_old_entities( $key, $status ): void {
// Early bail!!
if ( $this->is_preview_mode() ) {
return;
}
$args = [
'post_type' => [ Constants::POST_TYPE_AD, Constants::POST_TYPE_PLACEMENT ],
'posts_per_page' => -1,
'post_status' => 'publish',
];
if ( 'publish' === $status ) {
$args['post_status'] = 'draft';
$args['meta_query'] = [ // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_query
[
'key' => '_importer_session_key',
'value' => $key . '_draft',
],
];
}
$entities = get_posts( $args );
foreach ( $entities as $entity ) {
if ( 'draft' === $status ) {
$entity->meta_input = [
'_importer_session_key' => $key . '_draft',
'_importer_old_status' => $entity->post_status,
];
$entity->post_status = 'draft';
} elseif ( 'publish' === $status ) {
$entity->post_status = $entity->_importer_old_status;
}
wp_update_post( $entity );
}
}
/**
* Normalize ads
*
* @param array $ads Ads from api.
*
* @return array
*/
public function normalize_ads( $ads ): array {
$normalized = [];
foreach ( $ads as $ad ) {
if ( empty( $ad['slot'] ) ) {
$ad['slot'] = explode( '/', $ad['id'] );
$ad['slot'] = array_pop( $ad['slot'] );
}
// already created.
if ( in_array( $ad['slot'], $this->slots, true ) ) {
continue;
}
$advanced_placement = $ad['advanced_placement'] ?? [];
$placement_type = $this->map_placement_type( $advanced_placement['placement'] ?? $ad['slot'] );
$in_content_rules = $advanced_placement['inContentRule'] ?? [];
if ( isset( $advanced_placement['pageType'] ) && ! empty( $advanced_placement['pageType'] ) ) {
$advanced_placement['pageType'] = array_filter( $advanced_placement['pageType'] );
$advanced_placement['pageType'] = array_keys( $advanced_placement['pageType'] );
}
$normalized_ad = [
'ad_unit' => $ad['slot'],
'device' => $ad['device'],
'placement' => $placement_type,
'placement_conditions' => $this->parse_display_conditions( $advanced_placement['pageType'] ?? 'all' ),
];
if ( 'post_content' === $placement_type ) {
$normalized_ad['in_content_position'] = $in_content_rules['position'] ?? 'before';
$normalized_ad['in_content_count'] = $in_content_rules['positionCount'] ?? 1;
$normalized_ad['in_content_repeat'] = $in_content_rules['positionRepeat'] ?? false;
$normalized_ad['in_content_element'] = $this->map_element( $in_content_rules['positionElement'] ?? 'p' );
}
$normalized[] = $normalized_ad;
}
return $normalized;
}
/**
* Maps the placement type to a corresponding value.
*
* This function takes a placement type as input and returns the corresponding value based on a predefined mapping.
*
* @param string $type The placement type to be mapped.
*
* @return string The mapped placement type value.
*/
private function map_placement_type( $type ): string {
$type = strtolower( str_replace( ' ', '_', $type ) );
$hash = [
'leaderboard' => 'post_top',
'beforecontent' => 'post_top',
'in_content_1' => 'post_content',
'in_content_2' => 'post_content',
'incontent' => 'post_content',
'sidebar' => 'sidebar_widget',
'header' => 'header',
'footer' => 'footer',
'aboveheadline' => 'post_above_headline',
];
foreach ( $hash as $key => $value ) {
if ( Str::contains( $type, $key ) ) {
return $value;
}
}
return 'post_content';
}
/**
* Parse display conditions
*
* @param array|string $terms Dictionary term.
*
* @return array|null
*/
private function parse_display_conditions( $terms ) {
// Return for debugging.
if ( $this->is_preview_mode() ) {
$config = Options::pubguru_config();
return [
[
'type' => 'postids',
'operator' => 'is',
'value' => [ absint( $config['page'] ) ],
],
];
}
$conditions = [];
$terms = array_filter( (array) $terms );
if ( count( $terms ) === 5 ) {
$terms = [ 'all' ];
}
$hash = [
'all' => null,
'homepage' => [
[
'type' => 'general',
'value' => [ 'is_front_page' ],
],
],
'post_pages' => [
[
'type' => 'general',
'value' => [ 'is_singular' ],
],
],
'pages' => [
[
'type' => 'general',
'value' => [ 'is_singular' ],
],
],
'posts' => [
[
'type' => 'general',
'value' => [ 'is_singular' ],
],
[
'type' => 'posttypes',
'operator' => 'is',
'value' => [ 'post' ],
],
],
'category_pages' => [
[
'type' => 'general',
'value' => [ 'is_archive' ],
],
],
'categoryPages' => [
[
'type' => 'general',
'value' => [ 'is_archive' ],
],
],
'secondaryQueries' => [
[
'type' => 'general',
'value' => [ 'is_main_query' ],
],
],
];
foreach ( $terms as $term ) {
if ( 'all' === $term ) {
$conditions = [];
break;
}
if ( $hash[ $term ] ) {
$conditions = array_merge( $conditions, $hash[ $term ] );
}
}
return $conditions;
}
/**
* Maps the element to a corresponding value.
*
* @param string $element The element to be mapped.
*
* @return string The mapped element value.
*/
private function map_element( $element ): string {
$element = strtolower( $element );
$hash = [
'paragraph' => 'p',
'paragraphWithoutImage' => 'pwithoutimg',
'headline2' => 'h2',
'headline3' => 'h3',
'headline4' => 'h4',
'headlineAny' => 'headlines',
'image' => 'img',
'table' => 'table',
'listItem' => 'li',
'blockquote' => 'blockquote',
'iframe' => 'iframe',
'div' => 'div',
];
return $hash[ $element ] ?? 'p';
}
/**
* Checks if the current mode is preview mode.
*
* @return bool True if the current mode is preview mode, false otherwise.
*/
private function is_preview_mode(): bool {
$config = Options::pubguru_config();
if ( $config && 'page' === $config['method'] && absint( $config['page'] ) > 0 ) {
return true;
}
return false;
}
/**
* Save history key
*
* @param string $key Session key.
*
* @return void
*/
private function save_history_key( $key ): void {
if ( ! $this->is_preview_mode() ) {
return;
}
$config = Options::pubguru_config();
$config['history_key'] = $key;
Options::pubguru_config( $config );
}
}

View File

@@ -0,0 +1,366 @@
<?php
/**
* Google Sheet.
*
* @package AdvancedAds
* @author Advanced Ads <info@wpadvancedads.com>
* @since 1.50.0
*/
namespace AdvancedAds\Importers;
use WP_Error;
use AdvancedAds\Framework\Utilities\Params;
use AdvancedAds\Interfaces\Importer as Interface_Importer;
defined( 'ABSPATH' ) || exit;
/**
* Google Sheet.
*/
class Google_Sheet extends Importer implements Interface_Importer {
/**
* Ads from sheets
*
* @var array
*/
private $sheet_ads = null;
/**
* Get the unique identifier (ID) of the importer.
*
* @return string The unique ID of the importer.
*/
public function get_id(): string {
return 'google_sheet';
}
/**
* Get the title or name of the importer.
*
* @return string The title of the importer.
*/
public function get_title(): string {
return __( 'PubGuru Importer', 'advanced-ads' );
}
/**
* Get a description of the importer.
*
* @return string The description of the importer.
*/
public function get_description(): string {
return __( 'For MonetizeMore clients using PubGuru, you will be able to upload all of your new ads from your Google sheet. Please make sure that you support rep has confirmed that you are ready to do so. Below you will a “rollback changes” option, in case of any error. As a warning, these ad placements will over take your current ad setup.', 'advanced-ads' );
}
/**
* Get the icon to this importer.
*
* @return string The icon for the importer.
*/
public function get_icon(): string {
return '<span class="dashicons dashicons-media-spreadsheet"></span>';
}
/**
* Detect the importer in database.
*
* @return bool True if detected; otherwise, false.
*/
public function detect(): bool {
return false;
}
/**
* Render form.
*
* @return void
*/
public function render_form(): void {
// phpcs:disable WordPress.Security.EscapeOutput.OutputNotEscaped
if ( null === $this->sheet_ads ) :
?>
<input type="url" name="sheet_url" id="google-sheet-url" class="w-full" required value="" />
<?php else : ?>
<table class="widefat striped">
<thead>
<tr>
<td></td>
<td>Ad Unit</td>
<td>Device</td>
<td>Display Condition</td>
<td>Page Type</td>
</tr>
</thead>
<tbody>
<?php foreach ( $this->sheet_ads as $index => $ad ) : ?>
<tr>
<td>
<input type="checkbox" name="google_ads[<?php echo $index; ?>][enabled]" value="1"<?php checked( true, $ad['is_active'] ); ?>>
<input type="hidden" name="google_ads[<?php echo $index; ?>][ad_unit]" value="<?php echo $ad['ad_unit']; ?>">
<input type="hidden" name="google_ads[<?php echo $index; ?>][placement]" value="<?php echo $ad['placement']; ?>">
<input type="hidden" name="google_ads[<?php echo $index; ?>][placement_conditions]" value="<?php echo $ad['placement_conditions']; ?>">
<input type="hidden" name="google_ads[<?php echo $index; ?>][in_content_position]" value="<?php echo $ad['in_content_position']; ?>">
<input type="hidden" name="google_ads[<?php echo $index; ?>][in_content_element]" value="<?php echo $ad['in_content_element']; ?>">
<input type="hidden" name="google_ads[<?php echo $index; ?>][in_content_count]" value="<?php echo $ad['in_content_count']; ?>">
<input type="hidden" name="google_ads[<?php echo $index; ?>][in_content_repeat]" value="<?php echo $ad['in_content_repeat']; ?>">
</td>
<td><?php echo $ad['ad_unit']; ?></td>
<td>
<select name="google_ads[<?php echo $index; ?>][device]">
<option value="all"<?php selected( $ad['device'], 'all' ); ?>><?php esc_html_e( 'All', 'advanced-ads' ); ?></option>
<option value="desktop"<?php selected( $ad['device'], 'desktop' ); ?>><?php esc_html_e( 'Desktop', 'advanced-ads' ); ?></option>
<option value="mobile"<?php selected( $ad['device'], 'mobile' ); ?>><?php esc_html_e( 'Mobile', 'advanced-ads' ); ?></option>
</select>
</td>
<td><?php echo $ad['placement']; ?></td>
<td><?php echo $ad['placement_conditions']; ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<?php
endif;
// phpcs:enable WordPress.Security.EscapeOutput.OutputNotEscaped
}
/**
* Import data.
*
* @return WP_Error|string
*/
public function import() {
// Final import create ads.
$google_ads = Params::post( 'google_ads', [], FILTER_DEFAULT, FILTER_REQUIRE_ARRAY );
if ( $google_ads ) {
return $this->create_ads( $google_ads );
}
// Parse ads from google sheet using URL.
$sheet_url = Params::post( 'sheet_url' );
if ( empty( $sheet_url ) ) {
return new WP_Error( 'not_sheet_url_found', __( 'No google sheet url found.', 'advanced-ads' ) );
}
$sheet_id = $this->get_sheet_id( $sheet_url );
$sheet_ads = $this->get_ads( $sheet_id, 'AdvAdsMap' );
if ( is_wp_error( $sheet_ads ) ) {
return $sheet_ads;
}
if ( empty( $sheet_ads ) ) {
return new WP_Error( 'not_ads_found', __( 'No ads found in google sheet.', 'advanced-ads' ) );
}
$this->sheet_ads = $sheet_ads;
}
/**
* Parse sheet id from url
*
* @param string $url Sheet url.
*
* @return string
*/
private function get_sheet_id( $url ): string {
$url = str_replace( 'https://docs.google.com/spreadsheets/d/', '', $url );
$url = explode( '/', $url );
return current( $url );
}
/**
* Retrieves ads from a Google Sheet.
*
* @param string $sheet_id The ID of the Google Sheet.
* @param string $sheet_name The name of the sheet within the Google Sheet.
*
* @return array|WP_Error An array of ads retrieved from the Google Sheet or error if any
*/
private function get_ads( $sheet_id, $sheet_name ) {
$ads = [];
$sheet_api_url = 'https://sheets.googleapis.com/v4/spreadsheets/' . $sheet_id . '/values/' . $sheet_name . '?alt=json&key=AIzaSyBky3Y-0NwlCBSHFYquhN15Y-5QovYXSdM';
$response = wp_remote_get( $sheet_api_url );
if ( is_wp_error( $response ) || 200 !== wp_remote_retrieve_response_code( $response ) ) {
$error = json_decode( wp_remote_retrieve_body( $response ), true );
return new WP_Error( $error['error']['status'], $error['error']['message'] );
}
$body = json_decode( wp_remote_retrieve_body( $response ), true );
if ( is_array( $body ) ) {
$rows = $body['values'];
array_shift( $rows );
foreach ( $rows as $row ) {
if ( ! empty( $row[0] ) && ! empty( $row[1] ) ) {
$ad = [
'ad_unit' => $row[0],
'device' => strtolower( $row[1] ),
'placement' => $row[2],
'placement_conditions' => $row[3],
'is_active' => 'FALSE' === $row[4] ? false : true,
'in_content_position' => $row[5],
'in_content_element' => $row[6],
'in_content_count' => $row[7],
'in_content_repeat' => 'FALSE' === $row[8] ? false : true,
];
$ads[] = $ad;
}
}
}
return $ads;
}
/**
* Get ads from sheet by device
*
* @param array $ads Ads selected by user.
*
* @return string
*/
private function create_ads( $ads ): string {
$count = 0;
$history_key = $this->get_id() . '_' . wp_rand() . '_' . count( $ads );
foreach ( $ads as $data ) {
if ( ! isset( $data['enabled'] ) ) {
continue;
}
$ad = wp_advads_create_new_ad( 'plain' );
$ad->set_title( '[Migrated from Googlesheet] Ad # ' . $data['ad_unit'] );
$ad->set_content( sprintf( '<pubguru data-pg-ad="%s"></pubguru>', $data['ad_unit'] ) );
if ( 'all' !== $data['device'] ) {
$ad->set_visitor_conditions(
[
[
'type' => 'mobile',
'value' => [ $data['device'] ],
],
]
);
}
$ad_id = $ad->save();
if ( $ad_id > 0 ) {
++$count;
$placement = wp_advads_create_new_placement( $this->map_placement_type( $data['placement'] ) );
$placement->set_title( '[Migrated from Googlesheet] Placement # ' . $ad_id );
$placement->set_item( 'ad_' . $ad_id );
$display_conditions = $this->parse_display_conditions( $data['placement_conditions'] );
if ( ! empty( $display_conditions ) ) {
$placement->set_display_conditions( [ $display_conditions ] );
}
if ( $placement->is_type( 'post_content' ) ) {
$placement->set_prop( 'position', $data['in_content_position'] );
$placement->set_prop( 'index', $data['in_content_count'] );
$placement->set_prop( 'tag', $this->map_position_tag( $data['in_content_element'] ) );
$placement->set_prop( 'repeat', boolval( $data['in_content_repeat'] ) );
}
$placement->save();
$this->add_session_key( $ad, $placement, $history_key );
}
}
wp_advads()->importers->add_session_history( $this->get_id(), $history_key, $count );
/* translators: 1: counts 2: Importer title */
return sprintf( __( '%1$d ads migrated from %2$s', 'advanced-ads' ), $count, $this->get_title() );
}
/**
* Maps the placement type to a corresponding value.
*
* This function takes a placement type as input and returns the corresponding value based on a predefined mapping.
*
* @param string $type The placement type to be mapped.
*
* @return string The mapped placement type value.
*/
private function map_placement_type( $type ): string {
$type = strtolower( str_replace( ' ', '_', $type ) );
$hash = [
'after_content' => 'post_bottom',
'before_content' => 'post_top',
'in_content' => 'post_content',
'sidebar' => 'sidebar_widget',
];
return $hash[ $type ] ?? $type;
}
/**
* Maps the position tag to its corresponding value.
*
* @param string $tag The position tag to be mapped.
*
* @return string The mapped position tag value.
*/
private function map_position_tag( $tag ): string {
$hash = [
'paragraph (<p>)' => 'p',
'paragraph without image (<p>)' => 'pwithoutimg',
'headline 2 (<h2>)' => 'h2',
'headline 3 (<h3>)' => 'h3',
'headline 4 (<h4>)' => 'h4',
'any headline (<h2>, <h3>, <h4>)' => 'headlines',
'image (<img>)' => 'img',
'table (<table>)' => 'table',
'list item (<li>)' => 'li',
'quote (<blockquote>)' => 'blockquote',
'iframe (<iframe>)' => 'iframe',
'container (<div>)' => 'div',
];
$tag = strtolower( $tag );
return $hash[ $tag ] ?? 'anyelement';
}
/**
* Parse display conditions
*
* @param string $term Dictionary term.
*
* @return array|null
*/
private function parse_display_conditions( $term ) {
$term = str_replace( ' ', '_', strtolower( $term ) );
if ( 'all' === $term ) {
return null;
}
if ( 'homepage' === $term ) {
return [
'type' => 'general',
'value' => [ 'is_front_page' ],
];
}
if ( 'post_pages' === $term ) {
return [
'type' => 'general',
'value' => [ 'is_singular' ],
];
}
if ( 'category_pages' === $term ) {
return [
'type' => 'general',
'value' => [ 'is_archive' ],
];
}
}
}

View File

@@ -0,0 +1,234 @@
<?php
/**
* Importers Manager.
*
* @package AdvancedAds
* @author Advanced Ads <info@wpadvancedads.com>
* @since 1.50.0
*/
namespace AdvancedAds\Importers;
use WP_Error;
use AdvancedAds\Utilities\WordPress;
use AdvancedAds\Utilities\Conditional;
use AdvancedAds\Framework\Utilities\Params;
use AdvancedAds\Framework\Interfaces\Integration_Interface;
defined( 'ABSPATH' ) || exit;
/**
* Importers Manager.
*/
class Manager implements Integration_Interface {
/**
* Importer history option key.
*
* @var string
*/
const HISTORY_OPTION_KEY = '_advads_importer_history';
/**
* Hold all registered importers
*
* @var array
*/
private $importers = [];
/**
* Hold message to display on page
*
* @var string|WP_Error
*/
private $message = false;
/**
* Hook into WordPress.
*
* @return void
*/
public function hooks(): void {
$this->register_importers();
add_action( 'admin_init', [ $this, 'handle_action' ] );
}
/**
* Get importers
*
* @return array
*/
public function get_importers(): array {
return $this->importers;
}
/**
* Handle importing
*
* @return void
*/
public function handle_action(): void {
// Early bail!!
if ( ! Conditional::user_cap( 'advanced_ads_edit_ads' ) ) {
return;
}
$action = WordPress::current_action();
if ( 'advads_import' === $action && check_admin_referer( 'advads_import' ) ) {
$importer = Params::post( 'importer' );
$importer = $this->importers[ $importer ];
$this->message = $importer->import();
}
if ( 'advads_export' === $action && check_admin_referer( 'advads_export' ) ) {
$exporter = new Plugin_Exporter();
$this->message = $exporter->download_file();
}
if ( 'advads_import_delete' === $action && check_admin_referer( 'advads_import_delete' ) ) {
$this->rollback_import();
}
}
/**
* Rollback import
*
* @return void
*/
private function rollback_import(): void {
$session_key = Params::get( 'session_key' );
$session_data = $this->delete_session_history( $session_key );
if ( ! $session_data ) {
return;
}
$importer = $this->get_importer( $session_data['importer_id'] );
$importer->rollback( $session_key );
$this->message = __( 'History deleted successfully.', 'advanced-ads' );
}
/**
* Register importers
*
* @return void
*/
private function register_importers(): void {
$this->register_importer( Tutorials::class );
$this->register_importer( Google_Sheet::class );
$this->register_importer( Ad_Inserter::class );
$this->register_importer( Ads_WP_Ads::class );
$this->register_importer( Amp_WP_Ads::class );
$this->register_importer( Quick_Adsense::class );
$this->register_importer( WP_Quads::class );
$this->register_importer( XML_Importer::class );
$this->register_importer( Api_Ads::class );
}
/**
* Register custom type.
*
* @param string $classname Type class name.
*
* @return void
*/
public function register_importer( $classname ): void {
$importer = new $classname();
$this->importers[ $importer->get_id() ] = $importer;
}
/**
* Get the registered importer
*
* @param string $id Importer to get.
*
* @return mixed|bool
*/
public function get_importer( $id ) {
return $this->importers[ $id ] ?? false;
}
/**
* Display any message
*
* @return void
*/
public function display_message(): void {
// Early bail!!
if ( empty( $this->message ) ) {
return;
}
if ( is_array( $this->message ) ) {
foreach ( $this->message as $message ) {
$type = $message[0] ?? 'success';
$message = $message[1] ?? '';
?>
<div class="notice notice-<?php echo esc_attr( $type ); ?>">
<p><?php echo $message; // phpcs:ignore ?></p>
</div>
<?php
}
return;
}
$type = 'success';
$message = $this->message;
if ( is_wp_error( $this->message ) ) {
$type = 'error';
$message = $this->message->get_error_message();
}
?>
<div class="notice notice-<?php echo $type; // phpcs:ignore ?>">
<p><?php echo $message; // phpcs:ignore ?></p>
</div>
<?php
}
/**
* Add row to session history
*
* @param string $importer_id Importer id.
* @param string $key Session key.
* @param int $count Ad and Placement created.
*
* @return void
*/
public function add_session_history( $importer_id, $key, $count ): void {
$history = get_option( self::HISTORY_OPTION_KEY, [] );
$history[ $key ] = [
'importer_id' => $importer_id,
'session_key' => $key,
'count' => $count,
'created_at' => wp_date( 'U' ),
];
update_option( self::HISTORY_OPTION_KEY, $history );
}
/**
* Delete row from session history
*
* @param string $key Session key.
*
* @return array|bool
*/
public function delete_session_history( $key ) {
$return = false;
$history = get_option( self::HISTORY_OPTION_KEY, [] );
if ( isset( $history[ $key ] ) ) {
$return = $history[ $key ];
unset( $history[ $key ] );
update_option( self::HISTORY_OPTION_KEY, $history );
}
return $return;
}
}

View File

@@ -0,0 +1,359 @@
<?php
/**
* Plugin exporter.
*
* @package AdvancedAds
* @author Advanced Ads <info@wpadvancedads.com>
* @since 1.50.0
*/
namespace AdvancedAds\Importers;
use WP_Error;
use Exception;
use XML_Encoder;
use AdvancedAds\Options;
use Advanced_Ads_Privacy;
use AdvancedAds\Constants;
use Advanced_Ads_Ads_Txt_Strategy;
use AdvancedAds\Ads\Ad_Repository;
use AdvancedAds\Utilities\Conditional;
use AdvancedAds\Framework\Utilities\Params;
defined( 'ABSPATH' ) || exit;
/**
* Plugin exporter.
*
* phpcs:disable WordPress.PHP.NoSilencedErrors.Discouraged
* phpcs:disable WordPress.PHP.DevelopmentFunctions.error_log_error_log
* phpcs:disable WordPress.PHP.DevelopmentFunctions.error_log_print_r
* phpcs:disable WordPress.PHP.DevelopmentFunctions.error_log_var_export
*/
class Plugin_Exporter {
/**
* Hold data to make export file
*
* @var array
*/
public $data = [];
/**
* Types of content to be exported.
*
* @var array
*/
public $options = false;
/**
* Download export file
*
* @return array|string|WP_Error
*/
public function download_file() {
if ( ! Conditional::user_can( 'advanced_ads_manage_options' ) ) {
return new WP_Error( 'no_permission', __( 'User dont have premission to export.', 'advanced-ads' ) );
}
$this->options = Params::post( 'content', false, FILTER_DEFAULT, FILTER_REQUIRE_ARRAY );
if ( empty( $this->options ) ) {
return new WP_Error( 'no_option_selected', __( 'No content option selected to export.', 'advanced-ads' ) );
}
$this->process();
if ( ! empty( $this->data ) ) {
if ( defined( 'IMPORT_DEBUG' ) && IMPORT_DEBUG ) {
error_log( print_r( 'Array to decode', true ) );
error_log( print_r( $this->data, true ) );
}
$filename = $this->get_filename();
try {
$encoded = XML_Encoder::get_instance()->encode(
$this->data,
[ 'encoding' => get_option( 'blog_charset' ) ]
);
header( 'Content-Description: File Transfer' );
header( 'Content-Disposition: attachment; filename=' . $filename );
header( 'Content-Type: text/xml; charset=' . get_option( 'blog_charset' ), true );
echo $encoded; // phpcs:ignore
if ( defined( 'IMPORT_DEBUG' ) && IMPORT_DEBUG ) {
error_log( print_r( $encoded, true ) );
$decoded = XML_Encoder::get_instance()->decode( $encoded );
error_log( 'result ' . var_export( $this->data === $decoded, true ) );
}
exit();
} catch ( Exception $e ) {
return new WP_Error( 'error', $e->getMessage() );
}
}
return false;
}
/**
* Generate XML file
*
* @return void
*/
private function process(): void {
@set_time_limit( 0 );
@ini_set( 'memory_limit', apply_filters( 'admin_memory_limit', WP_MAX_MEMORY_LIMIT ) ); // phpcs:ignore WordPress.PHP.IniSet.memory_limit_Disallowed
foreach ( $this->options as $option ) {
$method = "process_{$option}";
if ( method_exists( $this, $method ) ) {
$this->$method();
}
}
do_action_ref_array( 'advanced-ads-export', [ $this->options, &$this->data ] );
}
/**
* Process ads
*
* @return void
*/
private function process_ads(): void {
$ads = [];
$mime_types = $this->get_mime_types();
$search = '/' . preg_quote( home_url(), '/' ) . '(\S+?)\.(' . implode( '|', array_keys( $mime_types ) ) . ')/i';
$posts = $this->get_posts( Constants::POST_TYPE_AD );
foreach ( $posts as $index => $post ) {
if ( ! empty( $post['post_content'] ) ) {
// Wrap images in <advads_import_img></advads_import_img> tags.
$post['post_content'] = preg_replace( $search, '<advads_import_img>\\0</advads_import_img>', $post['post_content'] );
}
if ( in_array( 'groups', $this->options, true ) ) {
$terms = wp_get_object_terms( $post['ID'], Constants::TAXONOMY_GROUP );
if ( ! empty( $terms ) && ! is_wp_error( $terms ) ) {
$post['groups'] = [];
foreach ( $terms as $term ) {
$post['groups'][] = $this->get_group( $term->term_id );
}
}
}
$this->get_post_meta( $post );
$ads[] = $post;
}
if ( $ads ) {
$this->data['ads'] = $ads;
}
}
/**
* Process placements
*
* @return void
*/
private function process_placements(): void {
$placements = [];
$posts = $this->get_posts( Constants::POST_TYPE_PLACEMENT );
foreach ( $posts as $index => $post ) {
$this->get_post_meta( $post );
$placements[] = $post;
}
if ( $placements ) {
$this->data['placements'] = $placements;
}
}
/**
* Process groups
*
* @return void
*/
private function process_groups(): void {
$this->data['groups'] = [];
foreach ( wp_advads_get_groups_dropdown() as $term_id => $name ) {
$this->data['groups'][] = $this->get_group( $term_id );
}
}
/**
* Process options
*
* @return void
*/
private function process_options(): void {
/**
* Filters the list of options to be exported.
*
* @param $options An array of options
*/
$this->data['options'] = array_filter(
apply_filters(
'advanced-ads-export-options',
[
ADVADS_SLUG => get_option( ADVADS_SLUG ),
GADSENSE_OPT_NAME => get_option( GADSENSE_OPT_NAME ),
Advanced_Ads_Privacy::OPTION_KEY => get_option( Advanced_Ads_Privacy::OPTION_KEY ),
Advanced_Ads_Ads_Txt_Strategy::OPTION => get_option( Advanced_Ads_Ads_Txt_Strategy::OPTION ),
Constants::OPTION_ADBLOCKER_SETTINGS => Options::instance()->get( 'adblocker', [] ),
]
)
);
}
/**
* Get the filename
*
* @return string
*/
private function get_filename(): string {
return sprintf(
'%s-advanced-ads-export-%s.xml',
sanitize_title(
preg_replace(
'#^(?:[^:]+:)?//(?:www\.)?([^/]+)#',
'$1',
get_bloginfo( 'url' )
)
),
gmdate( 'Y-m-d' )
);
}
/**
* Get group info
*
* @param int $group_id Group id.
*
* @return array
*/
private function get_group( $group_id ): array {
static $advads_groups;
if ( null === $advads_groups ) {
$advads_groups = [];
}
if ( ! isset( $advads_groups[ $group_id ] ) ) {
$group = wp_advads_get_group( $group_id );
$advads_groups[ $group_id ] = [
'term_id' => $group->get_id(),
'slug' => $group->get_slug(),
'name' => $group->get_name(),
'type' => $group->get_type(),
'ad_count' => $group->get_ad_count(),
'options' => $group->get_options(),
'weight' => $group->get_ad_weights(),
];
}
return $advads_groups[ $group_id ];
}
/**
* Get posts for export
*
* @param string $post_type Post type to fetch.
*
* @return array
*/
private function get_posts( $post_type ): array {
global $wpdb;
$export_fields = implode(
', ',
[
'ID',
'post_date',
'post_date_gmt',
'post_content',
'post_title',
'post_password',
'post_name',
'post_status',
'post_modified',
'post_modified_gmt',
'guid',
]
);
// phpcs:disable
return $wpdb->get_results(
$wpdb->prepare(
"SELECT $export_fields FROM {$wpdb->posts} where post_type = '%s' and post_status not in ('trash', 'auto-draft')",
$post_type
),
ARRAY_A
);
// phpcs:enable
}
/**
* Get mime types
*
* @return array
*/
private function get_mime_types(): array {
static $mime_types;
if ( null === $mime_types ) {
$mime_types = array_filter(
get_allowed_mime_types(),
function ( $mime_type ) {
return preg_match( '/image\//', $mime_type );
}
);
}
return $mime_types;
}
/**
* Get ads meta
*
* @param array $post Post object array.
*
* @return void
*/
private function get_post_meta( &$post ) {
global $wpdb;
$postmeta = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM {$wpdb->postmeta} WHERE post_id = %d", absint( $post['ID'] ) ) ); // phpcs:ignore
foreach ( $postmeta as $meta ) {
if ( '_edit_lock' === $meta->meta_key ) {
continue;
}
if ( Ad_Repository::OPTION_METAKEY === $meta->meta_key ) {
$image_id = false;
$ad_options = maybe_unserialize( $meta->meta_value );
if ( isset( $ad_options['output']['image_id'] ) ) {
$image_id = absint( $ad_options['output']['image_id'] );
}
if ( isset( $ad_options['image_id'] ) ) {
$image_id = absint( $ad_options['image_id'] );
}
if ( $image_id ) {
$atached_img = wp_get_attachment_url( $image_id );
if ( $atached_img ) {
$post['attached_img_url'] = $atached_img;
}
}
$post['meta_input'][ $meta->meta_key ] = maybe_unserialize( $ad_options );
} else {
$post['meta_input'][ $meta->meta_key ] = maybe_unserialize( $meta->meta_value );
}
}
}
}

View File

@@ -0,0 +1,318 @@
<?php // phpcs:ignoreFile
/**
* Quick Adsense.
*
* @package AdvancedAds
* @author Advanced Ads <info@wpadvancedads.com>
* @since 1.50.0
*/
namespace AdvancedAds\Importers;
use AdvancedAds\Framework\Utilities\Params;
use AdvancedAds\Interfaces\Importer as Interface_Importer;
defined( 'ABSPATH' ) || exit;
/**
* Quick Adsense.
*/
class Quick_Adsense extends Importer implements Interface_Importer {
/**
* Get the unique identifier (ID) of the importer.
*
* @return string The unique ID of the importer.
*/
public function get_id(): string {
return 'quick_adsense';
}
/**
* Get the title or name of the importer.
*
* @return string The title of the importer.
*/
public function get_title(): string {
return __( 'Quick Adsense', 'advanced-ads' );
}
/**
* Get a description of the importer.
*
* @return string The description of the importer.
*/
public function get_description(): string {
return '';
}
/**
* Get the icon to this importer.
*
* @return string The icon for the importer.
*/
public function get_icon(): string {
return '<span class="dashicons dashicons-insert"></span>';
}
/**
* Detect the importer in database.
*
* @return bool True if detected; otherwise, false.
*/
public function detect(): bool {
return false;
}
/**
* Render form.
*
* @return void
*/
public function render_form(): void {
?>
<fieldset>
<p><label><input type="radio" name="import_type" checked="checked" /> <?php esc_html_e( 'Import Ads', 'advanced-ads' ); ?></label></p>
<p><label><input type="radio" name="import_type" /> <?php esc_html_e( 'Import Groups', 'advanced-ads' ); ?></label></p>
<p><label><input type="radio" name="import_type" /> <?php esc_html_e( 'Import Placements', 'advanced-ads' ); ?></label></p>
<p><label><input type="radio" name="import_type" /> <?php esc_html_e( 'Import Settings', 'advanced-ads' ); ?></label></p>
</fieldset>
<?php
}
/**
* Import data.
*
* @return WP_Error|string
*/
public function import() {
return '';
}
public function adsforwp_import_all_quick_adsense_ads(){
global $wpdb;
if ( ! current_user_can( 'manage_options' ) ) {
return;
}
$nonce = Params::get( 'adsforwp_security_nonce', '' );
if ( ! $nonce || ! wp_verify_nonce( $nonce, 'adsforwp_ajax_check_nonce' ) ){
return;
}
$wpdb->query('START TRANSACTION');
$result = array();
$user_id = get_current_user_id();
global $quickAdsenseAdsDisplayed;
global $ampfowpAdsenseAdsId;
global $quickAdsenseBeginEnd;
$ampfowpAdsenseAdsId = array();
$settings = get_option('quick_adsense_settings');
for($i = 1; $i <= 10; $i++) {
if(isset($settings['onpost_ad_'.$i.'_content']) && !empty($settings['onpost_ad_'.$i.'_content'])) {
$ads_post = array(
'post_author' => $user_id,
'post_title' => 'Custom Ad '.$i.' (Migrated from Quick Adsense)',
'post_status' => 'publish',
'post_name' => 'Custom Ad '.$i.' (Migrated from Quick Adsense)',
'post_type' => 'adsforwp',
);
$post_id = wp_insert_post($ads_post);
$ads_content = $settings['onpost_ad_'.$i.'_content'];
$ads_alignment = $settings['onpost_ad_'.$i.'_alignment'];
$ads_margin = $settings['onpost_ad_'.$i.'_margin'];
$wheretodisplay = '';
$ad_align = '';
$pragraph_no = '';
$adposition = '';
if($ads_alignment == 1){
$ad_align ='left';
if(!empty($ads_margin)){
$ads_align_margin = array('ad_margin_top' => $ads_margin,'ad_margin_bottom' => $ads_margin,'ad_margin_left' => 0,'ad_margin_right' => $ads_margin);
}
}elseif($ads_alignment == 2){
$ad_align ='center';
if(!empty($ads_margin)){
$ads_align_margin = array('ad_margin_top' => $ads_margin,'ad_margin_bottom' => $ads_margin,'ad_margin_left' => 0,'ad_margin_right' => 0);
}
}elseif($ads_alignment == 3){
$ad_align ='right';
if(!empty($ads_margin)){
$ads_align_margin = array('ad_margin_top' => $ads_margin,'ad_margin_bottom' => $ads_margin,'ad_margin_left' => $ads_margin,'ad_margin_right' => 0);
}
}elseif($ads_alignment == 4){
$ad_align = 'none';
if(!empty($ads_margin)){
$ads_align_margin = array('ad_margin_top' => 0,'ad_margin_bottom' => 0,'ad_margin_left' => 0,'ad_margin_right' => 0);
}
}
if( isset($settings['enable_on_posts']) && $settings['enable_on_posts'] == 1){
$data_group_array['group-0'] = array(
'data_array' => array(
array(
'key_1' => 'post_type',
'key_2' => 'equal',
'key_3' => 'post',
)
)
);
}
if( isset($settings['enable_on_pages']) && $settings['enable_on_pages'] == 1){
$data_group_array['group-1'] = array(
'data_array' => array(
array(
'key_1' => 'post_type',
'key_2' => 'equal',
'key_3' => 'page',
)
)
);
}
//enable_position_before_last_para, ad_before_last_para
if($settings['ad_beginning_of_post'] == $i){
if($settings['enable_position_beginning_of_post'] == 1){
$wheretodisplay = 'before_the_content';
}
}elseif($settings['ad_end_of_post'] == $i){
if( $settings['enable_position_end_of_post'] == 1){
$wheretodisplay = 'after_the_content';
}
}elseif($settings['ad_middle_of_post'] == $i){
if($settings['enable_position_middle_of_post'] == 1 ){
$wheretodisplay = 'between_the_content';
}
}
for($j = 1; $j <= 3; $j++) {
if($settings['ad_after_para_option_'.$j] == $i){
if($settings['enable_position_after_para_option_'.$j] == 1){
$wheretodisplay = 'between_the_content';
$numberofparas = 'number_of_paragraph';
$display_tag_name = 'p_tag';
$paragraph_number = $settings['position_after_para_option_'.$j];
if($settings['enable_jump_position_after_para_option_'.$j] == 1){
$ads_on_every_paras = 1;
}
}elseif($settings['enable_position_after_image_option_'.$j] == 1){
$wheretodisplay = 'between_the_content';
$numberofparas = 'number_of_paragraph';
$display_tag_name = 'img_tag';
$paragraph_number = $settings['position_after_para_option_'.$j];
if($settings['enable_jump_position_after_para_option_'.$j] == 1){
$ads_on_every_paras = 1;
}
}
}
}
//enable_on_posts
//enable_on_pages
//enable_on_homepage
$adforwp_meta_key = array(
'select_adtype' => 'custom',
'custom_code' => $ads_content,
'adposition' => $adposition,
'paragraph_number' => $pragraph_no,
'adsforwp_ad_align' => $ad_align,
'adsforwp_ad_margin'=> $ads_align_margin,
'imported_from' => 'quick_adsense',
'wheretodisplay' => $wheretodisplay,
'display_tag_name' => $display_tag_name,
'adposition' => $numberofparas,
'paragraph_number' => $paragraph_number,
'ads_on_every_paragraphs_number' => $ads_on_every_paras,
'data_group_array' => $data_group_array
);
foreach ($adforwp_meta_key as $key => $val){
$result[] = update_post_meta($post_id, $key, $val);
}
}
}
for($i = 1; $i <= 10; $i++) {
if(isset($settings['widget_ad_'.$i.'_content']) && !empty($settings['widget_ad_'.$i.'_content'])) {
$ads_post = array(
'post_author' => $user_id,
'post_title' => 'Custom widget Ad '.$i.' (Migrated from Quick Adsense)',
'post_status' => 'publish',
'post_name' => 'Custom widget Ad '.$i.' (Migrated from Quick Adsense)',
'post_type' => 'adsforwp',
);
$post_id = wp_insert_post($ads_post);
$ads_content = $settings['widget_ad_'.$i.'_content'];
$ads_alignment = $settings['onpost_ad_'.$i.'_alignment'];
$ads_margin = $settings['onpost_ad_'.$i.'_margin'];
$wheretodisplay = '';
$ad_align = '';
$pragraph_no = '';
$adposition = '';
if($ads_alignment == 1){
$ad_align ='left';
if(!empty($ads_margin)){
$ads_align_margin = array('ad_margin_top' => $ads_margin,'ad_margin_bottom' => $ads_margin,'ad_margin_left' => 0,'ad_margin_right' => $ads_margin);
}
}elseif($ads_alignment == 2){
$ad_align ='center';
if(!empty($ads_margin)){
$ads_align_margin = array('ad_margin_top' => $ads_margin,'ad_margin_bottom' => $ads_margin,'ad_margin_left' => 0,'ad_margin_right' => 0);
}
}elseif($ads_alignment == 3){
$ad_align ='right';
if(!empty($ads_margin)){
$ads_align_margin = array('ad_margin_top' => $ads_margin,'ad_margin_bottom' => $ads_margin,'ad_margin_left' => $ads_margin,'ad_margin_right' => 0);
}
}elseif($ads_alignment == 4){
$ad_align = 'none';
if(!empty($ads_margin)){
$ads_align_margin = array('ad_margin_top' => 0,'ad_margin_bottom' => 0,'ad_margin_left' => 0,'ad_margin_right' => 0);
}
}
$data_group_array['group-0'] = array(
'data_array' => array(
array(
'key_1' => 'show_globally',
'key_2' => 'equal',
'key_3' => 'post',
)
)
);
$adforwp_meta_key = array(
'select_adtype' => 'custom',
'custom_code' => $ad_code,
'adposition' => $adposition,
'paragraph_number' => $pragraph_no,
'adsforwp_ad_align' => $ad_align,
'imported_from' => 'quick_adsense',
'wheretodisplay' => $wheretodisplay,
'data_group_array' => $data_group_array
);
foreach ($adforwp_meta_key as $key => $val){
$result[] = update_post_meta($post_id, $key, $val);
}
}
}
//die;
if (is_wp_error($result) ){
echo $result->get_error_message();
$wpdb->query('ROLLBACK');
}else{
$wpdb->query('COMMIT');
return $result;
}
}
}

View File

@@ -0,0 +1,115 @@
<?php
/**
* Import Tutorials.
*
* @package AdvancedAds
* @author Advanced Ads <info@wpadvancedads.com>
* @since 1.50.0
*/
namespace AdvancedAds\Importers;
use AdvancedAds\Interfaces\Importer as Interface_Importer;
defined( 'ABSPATH' ) || exit;
/**
* Tutorials.
*/
class Tutorials extends Importer implements Interface_Importer {
/**
* Get the unique identifier (ID) of the importer.
*
* @return string The unique ID of the importer.
*/
public function get_id(): string {
return 'import-tutorials';
}
/**
* Get the title or name of the importer.
*
* @return string The title of the importer.
*/
public function get_title(): string {
return __( 'Tutorials', 'advanced-ads' );
}
/**
* Get a description of the importer.
*
* @return string The description of the importer.
*/
public function get_description(): string {
return '';
}
/**
* Get the icon to this importer.
*
* @return string The icon for the importer.
*/
public function get_icon(): string {
return '<span class="dashicons dashicons-book"></span>';
}
/**
* Detect the importer in database.
*
* @return bool True if detected; otherwise, false.
*/
public function detect(): bool {
return true;
}
/**
* Show import button or not.
*
* @return bool
*/
public function show_button(): bool {
return false;
}
/**
* Render form.
*
* @return void
*/
public function render_form(): void {
?>
<p class="text-base m-0">
<?php
echo wp_kses_post(
__( 'While these other import options are still in beta, we do have resources on how to make setting up your first ad easier than ever. If you have any specific feature requests please make sure to contact us or <a href="https://wpadvancedads.com/support/missing-feature/">request a feature</a>.', 'advanced-ads' )
);
?>
</p>
<h3 class="mt-8"><?php esc_html_e( 'Quick Links', 'advanced-ads' ); ?></h3>
<ul class="text-primary space-y-4">
<li>
<a href="https://wpadvancedads.com/manual/import-export/?utm_source=advanced-ads&utm_medium=link&utm_campaign=tools-quicklinks" target="_blank">
<span><?php esc_html_e( 'Import and Export', 'advanced-ads' ); ?></span>
</a>
</li>
<li>
<a href="https://wpadvancedads.com/manual/ad-templates/?utm_source=advanced-ads&utm_medium=link&utm_campaign=tools-quicklinks" target="_blank">
<span><?php esc_html_e( 'Ad Templates', 'advanced-ads' ); ?></span>
</a>
</li>
</ul>
<?php
}
/**
* Import data.
*
* @return WP_Error|string
*/
public function import() {
return '';
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,347 @@
<?php // phpcs:ignoreFile
/**
* Encodes XML data.
*
* Based on code from the Symfony package
*
* Copyright (c) 2004-2016 Fabien Potencier <fabien@symfony.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is furnished
* to do so, subject to the following conditions:
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* @author Jordi Boggiano <j.boggiano@seld.be>
* @author John Wards <jwards@whiteoctober.co.uk>
* @author Fabian Vogler <fabian@equivalence.ch>
* @author Kévin Dunglas <dunglas@gmail.com>
*/
class XML_Encoder
{
/**
* @var DOMDocument
*/
private $dom;
/**
* @var XML_Encoder
*/
private static $instance;
private function __construct() {}
/**
* @return XML_Encoder
*/
public static function get_instance()
{
if ( ! isset(self::$instance) ) {
self::$instance = new self;
}
return self::$instance;
}
public function encode( $data, $options = []) {
if ( ! extension_loaded( 'simplexml' ) ) {
throw new Exception( sprintf( __( 'The %s extension(s) is not loaded', 'advanced-ads' ), 'simplexml' ) );
}
if ( ! extension_loaded( 'dom' ) ) {
throw new Exception( sprintf( __( 'The %s extension(s) is not loaded', 'advanced-ads' ), 'dom' ) );
}
$this->dom = new DOMDocument();
$this->dom->preserveWhiteSpace = false;
$this->dom->formatOutput = true;
if (isset($options['encoding'])) {
$this->dom->encoding = $options['encoding'];
}
if ( ! is_array($data) ) {
throw new UnexpectedValueException( _x( 'The data must be an array', 'import_export', 'advanced-ads' ) );
}
if (isset($options['skip_root'])) {
$this->buildXml($this->dom, $data );
} else {
// create root <advads-export> tag
$root = $this->dom->createElement('advads-export');
$this->dom->appendChild($root);
$this->buildXml($root, $data );
}
return $this->dom->saveXML();
}
/**
* Parse the data and convert it to DOMElements.
*/
private function buildXml(DOMNode $parentNode, $data ) {
$append = true;
foreach ($data as $key => $data) {
if (is_numeric($key) ) {
$append = $this->appendNode($parentNode, $data, 'item', $key);
} elseif ( $this->isElementNameValid($key) ) {
$append = $this->appendNode($parentNode, $data, $key);
}
}
return $append;
}
/**
* Selects the type of node to create and appends it to the parent.
*
* @param DOMNode $parentNode
* @param array|object $data
* @param string $nodeName
* @param string $key
*
* @return bool
*/
private function appendNode(DOMNode $parentNode, $data, $nodeName, $key = null) {
$node = $this->dom->createElement($nodeName);
if (null !== $key) {
$node->setAttribute('key', $key);
}
$appendNode = false;
if (is_array($data)) {
$node->setAttribute('type', 'array' );
$appendNode = $this->buildXml($node, $data);
} elseif (is_numeric($data)) {
$node->setAttribute('type', is_string( $data) ? 'string' : 'numeric' );
$appendNode = $this->appendText($node, (string) $data);
} elseif (is_string($data)) {
$node->setAttribute('type', 'string');
$appendNode = $this->needsCdataWrapping($data) ? $this->appendCData($node, $data) : $this->appendText($node, $data);
} elseif (is_bool($data)) {
$node->setAttribute('type', 'boolean');
$appendNode = $this->appendText($node, (int) $data);
} elseif (is_null($data)) {
$node->setAttribute('type', 'null');
$appendNode = $this->appendText($node, '');
}
if ($appendNode) {
$parentNode->appendChild($node);
} else {
/* translators: %s node data */
throw new UnexpectedValueException( sprintf( _x( 'An unexpected value could not be serialized: %s', 'import_export', 'advanced-ads' ), var_export($data, true) ) );
}
return $appendNode;
}
final protected function appendText(DOMNode $node, $val) {
$nodeText = $this->dom->createTextNode($val);
$node->appendChild($nodeText);
return true;
}
final protected function appendCData(DOMNode $node, $val) {
$nodeText = $this->dom->createCDATASection($val);
$node->appendChild($nodeText);
return true;
}
/**
* Checks if a value contains any characters which would require CDATA wrapping.
*
* @param string $val
*
* @return bool
*/
private function needsCdataWrapping($val) {
return preg_match('/[<>&]/', $val);
}
/**
* Checks the name is a valid xml element name.
*
* @param string $name
*
* @return bool
*/
final protected function isElementNameValid($name) {
return $name && false === strpos($name, ' ') && preg_match('#^[\pL_][\pL0-9._:-]*$#ui', $name);
}
/**
* Decode XML data.
*
* @throws Exception If an extension is lt loaded.
* @throws UnexpectedValueException If XML data is invalid.
*
* @param string $data XML data.
* @return array Decoded XML data.
*/
public function decode( $data ) {
if ( ! extension_loaded( 'simplexml' ) ) {
/* translators: %s: A name of not loaded extension. */
throw new Exception( sprintf( __( 'The %s extension(s) is not loaded', 'advanced-ads' ), 'simplexml' ) );
}
if ( ! extension_loaded( 'dom' ) ) {
/* translators: %s: A name of not loaded extension. */
throw new Exception( sprintf( __( 'The %s extension(s) is not loaded', 'advanced-ads' ), 'dom' ) );
}
if ('' === trim($data)) {
throw new UnexpectedValueException( _x( 'Invalid XML data, it can not be empty', 'import_export', 'advanced-ads' ) );
}
$internal_errors = libxml_use_internal_errors( true );
if ( LIBXML_VERSION < 20900 ) {
// The `libxml_disable_entity_loading` function has been deprecated in PHP 8.0 because in
// libxml >= 2.9.0 (that is required by PHP 8), external entity loading is disabled by default,
// so this function is no longer needed to protect against XXE attacks.
// phpcs:ignore PHPCompatibility.FunctionUse.RemovedFunctions.libxml_disable_entity_loaderDeprecated
$disable_entities = libxml_disable_entity_loader( true );
}
libxml_clear_errors();
$dom = new DOMDocument();
if ( strpos( $data, '<advads-export>' ) === false ) {
$data = preg_replace('/^<\?xml.*?\?>/', '', $data );
$data = '<advads-export>' . $data . '</advads-export>';
}
$dom->loadXML($data, LIBXML_NONET | LIBXML_NOBLANKS);
libxml_use_internal_errors( $internal_errors );
if ( LIBXML_VERSION < 20900 ) {
// phpcs:ignore PHPCompatibility.FunctionUse.RemovedFunctions.libxml_disable_entity_loaderDeprecated -- see L215ff. for an explanation
libxml_disable_entity_loader( $disable_entities );
}
if ($error = libxml_get_last_error()) {
libxml_clear_errors();
/* translators: %s error messages while trying to decode xml file */
throw new UnexpectedValueException( sprintf( _x( 'XML error: %s', 'import_export', 'advanced-ads' ), $error->message ) );
}
// <advads-export>
$rootNode = $dom->firstChild;
if ($rootNode->hasChildNodes()) {
return $this->parseXml($rootNode);
}
}
/**
* Parse the input DOMNode into an array or a string.
*
* @param DOMNode $node xml to parse
*
* @return array|string
*/
private function parseXml(DOMNode $node) {
// Parse the input DOMNode value (content and children) into an array or a string
$data = [];
if ( $node->hasAttributes() ) {
foreach ($node->attributes as $attr) {
if (ctype_digit($attr->nodeValue)) {
$data['@'.$attr->nodeName] = (int) $attr->nodeValue;
} else {
$data['@'.$attr->nodeName] = $attr->nodeValue;
}
}
}
$text_type = isset($data['@type']) ? $data['@type'] : null;
unset( $data['@type'] );
// Parse the input DOMNode value (content and children) into an array or a string.
if (!$node->hasChildNodes()) {
$value = $node->nodeValue;
} elseif (1 === $node->childNodes->length && in_array($node->firstChild->nodeType, [XML_TEXT_NODE, XML_CDATA_SECTION_NODE])) {
$value = $node->firstChild->nodeValue;
} else {
$value = [];
foreach ($node->childNodes as $subnode) {
$val = $this->parseXml($subnode);
if ('item' === $subnode->nodeName && is_array($val) && isset($val['@key'])) {
$a = $val['@key'];
if (isset($val['#'])) {
$value[$a] = $val['#'] !== 'null' ? $val['#'] : null;
} else {
$value[$a] = $val !== 'null' ? $val : null;
}
} else {
$value[$subnode->nodeName][] = $val === 'null' ? null : $val;
}
}
foreach ($value as $key => $val) {
if (is_array($val) && 1 === count($val)) {
$value[$key] = current($val);
} else if ( is_array( $value[$key] ) && isset( $value[$key]['@key'] ) ) {
unset( $value[$key]['@key'] );
}
}
}
if (!count($data)) {
$value = $this->changeType( $value, $text_type );
return $value;
}
if (!is_array($value)) {
$value = $this->changeType( $value, $text_type );
$data['#'] = $value;
return $data;
}
if (1 === count($value) && key($value)) {
$data[key($value)] = current($value);
return $data;
}
foreach ($value as $key => $val) {
$data[$key] = $val;
}
return $data;
}
private function changeType( $text, $type ) {
if ( $type === 'string' ) return (string) $text;
if ( $type === 'numeric' ) return 0 + $text;
if ( $type === 'boolean' ) return (boolean) $text;
if ( $type === 'array' && $text=== '' ) return [];
if ( $type === 'null' ) return 'null';
return $text;
}
}

View File

@@ -0,0 +1,865 @@
<?php // phpcs:ignoreFile
/**
* XML Importer.
*
* @package AdvancedAds
* @author Advanced Ads <info@wpadvancedads.com>
* @since 1.50.0
*/
namespace AdvancedAds\Importers;
use AdvancedAds\Abstracts\Ad;
use AdvancedAds\Ads\Ad_Repository;
use AdvancedAds\Constants;
use AdvancedAds\Framework\Utilities\Arr;
use AdvancedAds\Framework\Utilities\Params;
use AdvancedAds\Interfaces\Importer as Interface_Importer;
use AdvancedAds\Utilities\WordPress;
use Exception;
use XML_Encoder;
defined( 'ABSPATH' ) || exit;
/**
* XML Importer.
* TODO: Refactor logic.
*/
class XML_Importer extends Importer implements Interface_Importer {
/**
* Uploaded XML file path
*
* @var string
*/
private $import_id;
/**
* Status messages
*
* @var array
*/
private $messages = [];
/**
* Imported data mapped with previous data, e.g. ['ads'][ new_ad_id => old_ad_id (or null if does not exist) ]
*
* @var array
*/
public $imported_data = [
'ads' => [],
'groups' => [],
'placements' => [],
];
/**
* Attachments, created for Image Ads and images in ad content
*
* @var array
*/
private $created_attachments = [];
/**
* Post data indexs to set before inserting into the database
*
* @var array
*/
private $post_data_index = [];
/**
* Constructor.
*/
public function __construct() {
add_action( 'advanced-ads-cleanup-import-file', [ $this, 'delete_old_import_file' ] );
add_filter( 'advanced-ads-new-ad-data', [ $this, 'ad_before_inserting' ], 10, 2 );
remove_action( 'advanced-ads-ad-pre-save', [ \Advanced_Ads_AdSense_Admin::get_instance(), 'save_ad_options' ] );
}
/**
* Get the unique identifier (ID) of the importer.
*
* @return string The unique ID of the importer.
*/
public function get_id(): string {
return 'xml';
}
/**
* Get the title or name of the importer.
*
* @return string The title of the importer.
*/
public function get_title(): string {
return __( 'XML', 'advanced-ads' );
}
/**
* Get a description of the importer.
*
* @return string The description of the importer.
*/
public function get_description(): string {
return '';
}
/**
* Get the icon to this importer.
*
* @return string The icon for the importer.
*/
public function get_icon(): string {
return '<span class="dashicons dashicons-insert"></span>';
}
/**
* Detect the importer in database.
*
* @return bool True if detected; otherwise, false.
*/
public function detect(): bool {
return false;
}
/**
* Render form.
*
* @return void
*/
public function render_form(): void {
}
/**
* Import data.
*
* @return array|string
*/
public function import() {
switch ( Params::post( 'import_type' ) ) {
case 'xml_content':
if ( '' === Params::post( 'xml_textarea', '' ) ) {
$this->messages[] = [ 'error', __( 'Please enter XML content', 'advanced-ads' ) ];
break;
}
$content = stripslashes( Params::post( 'xml_textarea' ) );
$this->import_content( $content );
break;
case 'xml_file':
if ( $this->handle_upload() ) {
$content = file_get_contents( $this->import_id );
$this->import_content( $content );
@unlink( $this->import_id );
}
break;
default:
return [ 'error', __( 'Please select import type', 'advanced-ads' ) ];
}
if ( $this->created_attachments ) {
/* translators: %s number of attachments */
$this->messages[] = [ 'success', sprintf( _n( '%s attachment uploaded', '%s attachments uploaded', count( $this->created_attachments ), 'advanced-ads' ), count( $this->created_attachments) ) ];
}
return $this->messages;
}
/**
* The main controller for the actual import stage
*
* @param string $xml_content XML content to import.
*/
public function import_content( &$xml_content ) {
@set_time_limit( 0 );
@ini_set( 'memory_limit', apply_filters( 'admin_memory_limit', WP_MAX_MEMORY_LIMIT ) );
$xml_content = trim( $xml_content );
if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
error_log( 'source XML:' );
error_log( $xml_content );
}
try {
$decoded = XML_Encoder::get_instance()->decode( $xml_content );
} catch ( Exception $e ) {
error_log( $e->getMessage() );
$this->messages[] = [ 'error', $e->getMessage() ];
return;
}
if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
error_log( 'decoded XML:' );
error_log( print_r( $decoded, true ) );
}
$this->import_ads( $decoded['ads'] ?? [] );
$this->import_groups( $decoded['groups'] ?? [], $decoded['ads'] ?? [] );
$this->import_placements( $decoded['placements'] ?? [] );
$this->import_options( $decoded );
do_action_ref_array( 'advanced-ads-import', [ &$decoded, &$this->imported_data, &$this->messages ] );
wp_cache_flush();
}
/**
* Set the ad data before inserting into the database
*
* @param array $post_data Default post data.
* @param Ad $ad Ad object.
*
* @return array
*/
public function ad_before_inserting( $post_data, $ad ) {
foreach ( $this->post_data_index as $index ) {
if ( ! empty( $ad->get_prop( $index ) ) ) {
$post_data[ $index ] = $ad->get_prop( $index );
}
}
return $post_data;
}
/**
* Delete old import file via cron
*
* @param string $path Path to the file.
*
* @return void
*/
public function delete_old_import_file( $path ) {
if ( file_exists( $path ) ) {
@unlink( $path );
}
}
/**
* Handles the XML upload
*
* @return bool false if error, true otherwise
*/
private function handle_upload() {
$uploads_dir = wp_upload_dir();
if ( ! empty( $uploads_dir['error'] ) ) {
$this->messages[] = [ 'error', $uploads_dir['error'] ];
return false;
}
$import_dir = $uploads_dir['basedir'] . '/advads-import';
$this->import_id = $import_dir . '/' . md5( time() . NONCE_SALT );
if ( ! is_dir( $import_dir ) && ! wp_mkdir_p( $import_dir ) ) {
/* translators: %s import directory */
$this->messages[] = [ 'error', sprintf( __( 'Failed to create import directory <em>%s</em>', 'advanced-ads' ), $import_dir ) ];
return false;
}
if ( ! is_writable( $import_dir ) ) {
/* translators: %s import directory */
$this->messages[] = [ 'error', sprintf( __( 'Import directory is not writable: <em>%s</em>', 'advanced-ads' ), $import_dir ) ];
return false;
}
if ( ! @file_exists( $import_dir . '/index.php' ) ) {
@touch( $import_dir . '/index.php' );
}
if ( ! isset( $_FILES['import'] ) ) {
$this->messages[] = [ 'error', __( 'File is empty, uploads are disabled or post_max_size is smaller than upload_max_filesize in php.ini', 'advanced-ads' ) ];
return false;
}
$file = $_FILES['import'];
// determine if uploaded file exceeds space quota.
$file = apply_filters( 'wp_handle_upload_prefilter', $file );
if ( ! empty( $file['error'] ) ) {
/* translators: %s error in file */
$this->messages[] = [ 'error', sprintf( __( 'Failed to upload file, error: <em>%s</em>', 'advanced-ads' ), $file['error'] ) ];
return false;
}
if ( ! ( $file['size'] > 0 ) ) {
$this->messages[] = [ 'error', __( 'File is empty.', 'advanced-ads' ), $file['error'] ];
return false;
}
if ( ! is_uploaded_file( $file['tmp_name'] ) || ! @ move_uploaded_file( $file['tmp_name'], $this->import_id ) || ! is_readable( $this->import_id ) ) {
/* translators: %s import id */
$this->messages[] = [ 'error', sprintf( __( 'The file could not be created: <em>%s</em>. This is probably a permissions problem', 'advanced-ads' ), $this->import_id ) ];
return false;
}
// Set correct file permissions.
$stat = stat( dirname( $import_dir ) );
$perms = $stat['mode'] & 0000666;
@ chmod( $this->import_id, $perms );
// cleanup in case of failed import.
wp_schedule_single_event( time() + 10 * MINUTE_IN_SECONDS, 'advanced-ads-cleanup-import-file', [ $this->import_id ] );
return true;
}
/**
* Create new ads and groups based on import information
*
* @param array $decoded decoded XML.
*/
private function import_ads( $decoded ) {
// Early bail!!
if ( empty( $decoded ) ) {
return;
}
$count_attachment = 0;
$count_ads = 0;
foreach ( $decoded as $ad ) {
if ( isset( $ad['meta_input'] ) && is_array( $ad['meta_input'] ) ) {
foreach ( $ad['meta_input'] as $meta_k => &$meta_v ) {
if ( Ad_Repository::OPTION_METAKEY !== $meta_k ) {
$meta_v = WordPress::maybe_unserialize( $meta_v );
}
}
}
// upload images for Image ad type.
if (
isset( $ad['attached_img_url'] )
&& (
isset( $ad['meta_input']['advanced_ads_ad_options']['output']['image_id'] )
|| isset( $ad['meta_input']['advanced_ads_ad_options']['image_id'] )
)
) {
$attached_img_url = $this->replace_placeholders( $ad['attached_img_url'] );
$attachment_id = null;
if ( isset( $this->created_attachments[ $attached_img_url ] ) ) {
$attachment_id = $this->created_attachments[ $attached_img_url ]['post_id'];
} else if ( $attachment = $this->upload_image_from_url( $attached_img_url ) ) {
$link = ( $link = get_attachment_link( $attachment['post_id'] ) ) ? sprintf( '<a href="%s">%s</a>', esc_url( $link ), __( 'Edit', 'advanced-ads' ) ) : '';
$attachment_id = $attachment['post_id'];
++$count_attachment;
$this->created_attachments[ $attached_img_url ] = $attachment;
}
if ( $attachment_id ) {
$ad['meta_input']['advanced_ads_ad_options']['output']['image_id'] = $attachment_id;
}
}
$ad_obj = wp_advads_create_new_ad( $ad['meta_input']['advanced_ads_ad_options']['type'] );
if ( ! $ad_obj ) {
/* translators: %s Ad title */
$this->messages[] = [ 'error', sprintf( __( 'Failed to import <em>%s</em>', 'advanced-ads' ), esc_html( Arr::get( $ad, 'post_title' ) ) ) ];
continue;
}
$ad_obj->set_title( Arr::get( $ad, 'post_title' ) );
$ad_obj->set_content( $this->process_ad_content( Arr::get( $ad, 'post_content', '' ) ) );
$ad_obj->set_status( Arr::get( $ad, 'post_status', 'publish' ) );
$ad_obj->set_author_id( get_current_user_id() );
// set on filter 'advanced-ads-new-ad-data'.
$ad_obj->set_prop_temp( 'post_date', Arr::get( $ad, 'post_date' ) );
$ad_obj->set_prop_temp( 'post_date_gmt', Arr::get( $ad, 'post_date_gmt' ) );
$ad_obj->set_prop_temp( 'post_password', Arr::get( $ad, 'post_password', '' ) );
$ad_obj->set_prop_temp( 'post_name', Arr::get( $ad, 'post_name', '' ) );
$ad_obj->set_prop_temp( 'post_modified', Arr::get( $ad, 'post_modified', 0 ) );
$ad_obj->set_prop_temp( 'post_modified_gmt', Arr::get( $ad, 'post_modified_gmt', 0 ) );
$ad_obj->set_prop_temp( 'guid', Arr::get( $ad, 'guid', '' ) );
$this->post_data_index = [
'post_date',
'post_date_gmt',
'post_password',
'post_name',
'post_modified',
'post_modified_gmt',
'guid',
];
foreach ( Arr::get( $ad, 'meta_input.advanced_ads_ad_options', [] ) as $key => $value ) {
if ( 'output' === $key ) {
foreach ( $value as $prop => $inner_value ) {
$ad_obj->set_prop( $prop, $inner_value );
}
} elseif ( 'tracking' === $key ) {
foreach ( Arr::get( $ad, 'meta_input.advanced_ads_ad_options.tracking' ) as $inner_key => $inner_value ) {
$ad_obj->set_prop( "tracking.{$inner_key}", $inner_value );
}
} else {
$ad_obj->set_prop_temp( $key, $value );
}
}
if ( $ad_obj->is_type( 'adsense' ) ) {
$content = json_decode( str_replace( [ "\n", "\r", ' ' ], '', wp_unslash( $ad['post_content'] ) ), true );
if ( in_array( $content['unitType'] ?? 'none', [
'responsive',
'link',
'link-responsive',
'matched-content',
'in-article',
'in-feed',
], true )
) {
$ad_obj->set_width( 0 );
$ad_obj->set_height( 0 );
}
}
$ad_obj->save();
if ( Arr::get( $ad, 'meta_input.advanced_ads_selling_order' ) ) {
update_post_meta( $ad_obj->get_id(), 'advanced_ads_selling_order', absint( $ad['meta_input']['advanced_ads_selling_order'] ) );
}
if ( Arr::get( $ad, 'meta_input.advanced_ads_selling_order_item' ) ) {
update_post_meta( $ad_obj->get_id(), 'advanced_ads_selling_order_item', absint( $ad['meta_input']['advanced_ads_selling_order_item'] ) );
}
++$count_ads;
// new ad id => old ad id, if exists.
$this->imported_data['ads'][ $ad_obj->get_id() ] = isset( $ad['ID'] ) ? absint( $ad['ID'] ) : null;
}
if ( $count_ads ) {
/* translators: %s number of ads */
$this->messages[] = [ 'success', sprintf( _n( '%s ad imported', '%s ads imported', $count_ads, 'advanced-ads' ), $count_ads ) ];
}
}
/**
* Create new empty groups based on import information
*
* @param array $decoded group related info.
* @param array $ads ads related info.
*
* @return void
*/
private function import_groups( $decoded, $ads ) {
// Early bail!!
if ( empty( $decoded ) ) {
return;
}
foreach ( $decoded as $_group ) {
$group = wp_advads_create_new_group( $_group['type'] ?? 'default' );
$group->set_name( $_group['name'] ?? '' );
$group->set_ad_count( $_group['ad_count'] ?? 1 );
$group->set_options( $_group['options'] ?? [] );
$ad_weights = [];
if ( isset( $_group['weight'] ) ) {
foreach ( $_group['weight'] ?? [] as $old_ad_id => $weight ) {
$ad_id = array_search( $old_ad_id, $this->imported_data['ads'] );
if ( $ad_id ) {
$ad_weights[ $ad_id ] = $weight ?? Constants::GROUP_AD_DEFAULT_WEIGHT;
}
}
} else {
foreach ( $ads as $ad ) {
if ( ! isset( $ad['groups'] ) ) {
continue;
}
foreach ( $ad['groups'] as $group_of_current_ad ) {
if ( $group_of_current_ad['term_id'] !== $_group['term_id'] ) {
continue;
}
$ad_id = $this->search_item( $ad['ID'], 'ad' );
if ( $ad_id ) {
$ad_weights[ $ad_id ] = $group_of_current_ad['weight'] ?? Constants::GROUP_AD_DEFAULT_WEIGHT;
}
}
}
}
$group->set_ad_weights( $ad_weights );
$group->save();
$this->imported_data['groups'][ $group->get_id() ] = $_group['term_id'] ?? null;
}
if ( count( $this->imported_data['groups'] ) ) {
/* translators: %s number of groups */
$this->messages[] = [ 'success', sprintf( _n( '%s group imported', '%s groups imported', count( $this->imported_data['groups'] ), 'advanced-ads' ), count( $this->imported_data['groups'] ) ) ];
}
}
/**
* Create new placements based on import information
*
* @param array $decoded decoded XML.
*/
private function import_placements( $decoded ) {
// Early bail!!
if ( empty( $decoded ) ) {
return;
}
$existing_placements = wp_advads_get_placements();
$updated_placements = $existing_placements;
foreach ( $decoded as &$placement ) {
$use_existing = ! empty( $placement['use_existing'] );
if ( $use_existing ) {
if ( empty( $placement['key'] ) ) {
continue;
}
$placement_key_uniq = sanitize_title( $placement['key'] );
if ( ! isset( $existing_placements[ $placement_key_uniq ] ) ) {
continue;
}
$existing_placement = $existing_placements[ $placement_key_uniq ];
$existing_placement['key'] = $placement_key_uniq;
} else {
$placement_key_uniq = $placement['ID'] ?? $placement['key'];
$placement_type = Arr::get( $placement, 'meta_input.type', $placement['type'] ?? '' );
$placement['type'] = wp_advads_has_placement_type( $placement_type ) ? $placement_type : 'default';
$placement['name'] = $placement['post_title'] ?? $placement['name'];
$placement['item'] = Arr::get( $placement, 'meta_input.item', $placement['item'] ?? null ) ?? '';
// make sure the key in placement array is unique.
if ( isset( $existing_placements[ $placement_key_uniq ] ) ) {
$count = 1;
while ( isset( $existing_placements[ $placement_key_uniq . '_' . $count ] ) ) {
++$count;
}
$placement_key_uniq .= '_' . $count;
}
// new placement key => old placement key.
$this->imported_data['placements'][ $placement_key_uniq ] = $placement['ID'] ?? null;
}
// try to set "Item" (ad or group).
if ( ! empty( $placement['item'] ) ) {
$_item = explode( '_', $placement['item'] );
if ( ! empty( $_item[1] ) ) {
switch ( $_item[0] ) {
case 'ad':
case Constants::ENTITY_AD:
$found = $this->search_item( $_item[1], Constants::ENTITY_AD );
if ( false === $found ) {
break;
}
if ( $use_existing ) {
// assign new ad to an existing placement
// - if the placement has no or a single ad assigned, it will be swapped against the new one
// - if a group is assigned to the placement, the new ad will be added to this group with a weight of 1.
$placement = $existing_placement;
if ( ! empty( $placement['item'] ) ) {
// get the item from the existing placement.
$_item_existing = explode( '_', $placement['item'] );
if ( ! empty( $_item_existing[1] ) && Constants::ENTITY_GROUP === $_item_existing[0] ) {
$advads_ad_weights = get_option( 'advads-ad-weights', [] );
if ( term_exists( absint( $_item_existing[1] ), Constants::TAXONOMY_GROUP ) ) {
wp_set_post_terms( $found, $_item_existing[1], Constants::TAXONOMY_GROUP, true );
/**
* By default, a new add added to a group receives the weight of 5
* so that users could set the weight of existing ads either higher or lower
* depending on whether they want to show the new ad with a higher weight or not.
* This is especially useful with Selling Ads to replace an existing ad in a group
* with a newly sold one
*
* Advanced users could use the `advanced-ads-import-default-group-weight` filter
* to manipulate the value
*/
$advads_ad_weights[ $_item_existing[1] ][ $found ] = apply_filters( 'advanced-ads-import-default-group-weight', 5 );
update_option( 'advads-ad-weights', $advads_ad_weights );
// new placement key => old placement key.
$this->imported_data['placements'][ $placement_key_uniq ] = $placement_key_uniq;
break;
}
}
}
}
$placement['item'] = 'ad_' . $found;
// new placement key => old placement key.
$this->imported_data['placements'][ $placement_key_uniq ] = $placement_key_uniq;
break;
case Constants::ENTITY_GROUP:
$found = $this->search_item( $_item[1], Constants::ENTITY_GROUP );
if ( false === $found ) {
break;
}
$placement['item'] = 'group_' . $found;
// new placement key => old placement key.
$this->imported_data['placements'][ $placement_key_uniq ] = $placement_key_uniq;
break;
}
}
}
if ( ! isset( $placement['options'] ) ) {
$placement['options'] = $placement['meta_input']['options'] ?? [];
}
$updated_placements[ $placement_key_uniq ] = apply_filters( 'advanced-ads-import-placement', $placement, $this );
}
if ( $existing_placements !== $updated_placements ) {
$count_placements = 0;
foreach ( $updated_placements as $placement_key => $placement_data ) {
if ( isset( $existing_placements[ $placement_key ] ) ) {
continue;
}
$new_placement = wp_advads_create_new_placement( $placement_data['type'] );
$new_placement->set_title( $placement_data['name'] );
$new_placement->set_item( $placement_data['item'] ?? '' );
foreach ( $placement_data['options'] as $key => $option ) {
if ( 'placement_conditions' === $key ) {
foreach ( $placement_data['options']['placement_conditions'] as $prop => $value ) {
$new_placement->set_prop( $prop, $value );
}
} else {
$new_placement->set_prop( $key, $option );
}
}
$new_placement->save();
++$count_placements;
$this->imported_data['placements'][ $placement_key ] = $new_placement->get_id();
}
if ( $count_placements ) {
/* translators: %s number of placements */
$this->messages[] = [ 'success', sprintf( _n( '%s placement imported', '%s placements imported', $count_placements, 'advanced-ads' ), $count_placements ) ];
}
}
}
/**
* Search for ad/group id
*
* @param string $id ad/group Group id.
* @param string $type Group type.
* @return int|bool
* - int id of the imported ad/group if exists
* - or int id of the existing ad/group if exists
* - or bool false
*/
public function search_item( $id, $type ) {
$found = false;
switch ( $type ) {
case 'ad':
case Constants::ENTITY_AD:
// if the ad was imported.
$found = array_search( $id, $this->imported_data['ads'] );
if ( ! $found ) {
// if the ad already exists.
if ( get_post_type( $id ) === Constants::POST_TYPE_AD ) {
$found = $id;
}
}
break;
case Constants::ENTITY_GROUP:
$found = array_search( $id, $this->imported_data['groups'] );
if ( ! $found ) {
if ( term_exists( absint( $id ), Constants::TAXONOMY_GROUP ) ) {
$found = $id;
}
}
break;
}
return (int) $found;
}
/**
* Create new options based on import information.
*
* @param array $decoded decoded XML.
*/
private function import_options( $decoded ) {
if ( isset( $decoded['options'] ) && is_array( $decoded['options'] ) ) {
$count_options = 0;
foreach ( $decoded['options'] as $option_name => $imported_option ) {
// Ignore options not belonging to advanced ads.
if (
0 !== strpos( $option_name, 'advads-' )
&& 0 !== strpos( $option_name, 'advads_' )
&& 0 !== strpos( $option_name, 'advanced-ads' )
&& 0 !== strpos( $option_name, 'advanced_ads' )
) {
continue;
}
$existing_option = get_option( $option_name, [] );
if ( ! is_array( $imported_option ) ) {
$imported_option = [];
}
if ( ! is_array( $existing_option ) ) {
$existing_option = [];
}
$option_to_import = array_merge( $existing_option, $imported_option );
$count_options++;
update_option( $option_name, WordPress::maybe_unserialize( $option_to_import ) );
}
if ( $count_options ) {
/* translators: %s number of options */
$this->messages[] = [ 'success', sprintf( _n( '%s option imported', '%s options imported', $count_options, 'advanced-ads' ), $count_options ) ];
}
}
}
/**
* Replace placeholders
*
* @param string $content The content.
*
* @return string with replaced placeholders
*/
private function replace_placeholders( $content ) {
$content = str_replace( '{ADVADS_BASE_URL}', ADVADS_BASE_URL, $content );
return $content;
}
/**
* Upload image from URL and create attachment
*
* @param string $image_url Image url.
* @return array with indices: post_id, attachment_url, false on failure
*/
private function upload_image_from_url( $image_url ) {
$file_name = basename( current( explode( '?', $image_url ) ) );
$wp_filetype = wp_check_filetype( $file_name, null );
$parsed_url = @parse_url( $image_url );
$image_url = str_replace( ' ', '%20', $image_url );
if ( ! $wp_filetype['type'] ) {
/* translators: %s image url */
$this->messages[] = [ 'error', sprintf( __( 'Invalid filetype <em>%s</em>', 'advanced-ads' ), $image_url ) ];
return false;
}
if ( ! $parsed_url || ! is_array( $parsed_url ) ) {
/* translators: %s image url */
$this->messages[] = [ 'error', sprintf( __( 'Error getting remote image <em>%s</em>', 'advanced-ads' ), $image_url ) ];
return false;
}
$response = wp_safe_remote_get( $image_url, [ 'timeout' => 20 ] );
if ( is_wp_error( $response ) || 200 !== wp_remote_retrieve_response_code( $response ) ) {
/* translators: %s image url */
$this->messages[] = [ 'error', sprintf( __( 'Error getting remote image <em>%s</em>', 'advanced-ads' ), $image_url ) ];
return false;
}
// Upload the file.
$upload = wp_upload_bits( $file_name, '', wp_remote_retrieve_body( $response ) );
if ( $upload['error'] ) {
/* translators: %s image url */
$this->messages[] = [ 'error', sprintf( __( 'Error getting remote image <em>%s</em>', 'advanced-ads' ), $image_url ) ];
return false;
}
// Get filesize.
$filesize = filesize( $upload['file'] );
if ( 0 == $filesize ) {
@unlink( $upload['file'] );
/* translators: %s image url */
$this->messages[] = [ 'error', sprintf( __( 'Zero size file downloaded <em>%s</em>', 'advanced-ads' ), $image_url ) ];
return false;
}
/**
* Get allowed image mime types.
*
* @var string Single mime type.
*/
$allowed_mime_types = get_allowed_mime_types() ?? [];
$mime_types = array_filter( get_allowed_mime_types(), function( $mime_type ) {
return preg_match( '/image\//', $mime_type );
} );
$fileinfo = @getimagesize( $upload['file'] );
if ( ! $fileinfo || ! in_array( $fileinfo['mime'], $mime_types, true ) ) {
@unlink( $upload['file'] );
/* translators: %s image url */
$this->messages[] = [ 'error', sprintf( __( 'Error getting remote image <em>%s</em>', 'advanced-ads' ), $image_url ) ];
return false;
}
// create new post.
$new_post = [
'post_title' => $file_name,
'post_mime_type' => $wp_filetype['type'],
'guid' => $upload['url'],
];
if ( ! function_exists( 'wp_generate_attachment_metadata' ) ) {
require_once ABSPATH . 'wp-admin/includes/image.php';
}
$post_id = wp_insert_attachment( $new_post, $upload['file'] );
wp_update_attachment_metadata( $post_id, wp_generate_attachment_metadata( $post_id, $upload['file'] ) );
return [
'post_id' => $post_id,
'attachment_url' => wp_get_attachment_url( $post_id ),
];
}
/**
* Ad content manipulations
*
* @param string $content Content.
*
* @return string $content
*/
private function process_ad_content( $content ) {
$replacement_map = [];
if ( preg_match_all( '/\<advads_import_img\>(\S+?)\<\/advads_import_img\>/i', $content, $matches ) ) {
foreach ( $matches[1] as $k => $url ) {
if ( isset( $this->created_attachments[ $url ] ) ) {
$replacement_map[ $url ] = $this->created_attachments[ $url ]['attachment_url'];
} else if ( $attachment = $this->upload_image_from_url( $url ) ) {
$link = ( $link = get_attachment_link( $attachment['post_id'] ) ) ? sprintf( '<a href="%s">%s</a>', esc_url( $link ), __( 'Edit', 'advanced-ads' ) ) : '';
/* translators: 1: Attachment ID 2: Attachment link */
$this->messages[] = [ 'success', sprintf( __( 'New attachment created <em>%1$s</em> %2$s', 'advanced-ads' ), $attachment['post_id'], $link ) ];
$this->created_attachments[ $url ] = $attachment;
$replacement_map[ $url ] = $attachment['attachment_url'];
}
}
}
$content = str_replace( [ '<advads_import_img>', '</advads_import_img>' ], '', $content );
if ( count( $replacement_map ) ) {
$content = str_replace( array_keys( $replacement_map ), array_values( $replacement_map ), $content );
}
return $this->replace_placeholders( $content );
}
}