PageRenderTime 33ms CodeModel.GetById 11ms app.highlight 17ms RepoModel.GetById 1ms app.codeStats 0ms

/wp-content/plugins/google-analytics-for-wordpress/includes/admin/reports/abstract-report.php

https://bitbucket.org/carloskikea/helpet
PHP | 375 lines | 287 code | 51 blank | 37 comment | 78 complexity | d4412a2d76602d56e3dafc762a676057 MD5 | raw file
  1<?php
  2/**
  3 * Report Abstract
  4 *
  5 * Ensures all of the reports have a uniform class with helper functions.
  6 *
  7 * @since 6.0.0
  8 *
  9 * @package MonsterInsights
 10 * @subpackage Reports
 11 * @author  Chris Christoff
 12 */
 13
 14// Exit if accessed directly
 15if ( ! defined( 'ABSPATH' ) ) {
 16	exit;
 17}
 18
 19class MonsterInsights_Report {
 20
 21	public $title;
 22	public $class;
 23	public $name;
 24	public $version = '1.0.0';
 25
 26	/**
 27	 * Primary class constructor.
 28	 *
 29	 * @access public
 30	 * @since 6.0.0
 31	 */
 32	public function __construct() {
 33		add_filter( 'monsterinsights_reports_abstract_get_data_pre_cache', array( $this, 'requirements' ), 10 , 3 );
 34	}
 35
 36	// Let's get the HTML to output for a particular report. This is not the AJAX endpoint. Args can hold things (generally start/end date range)
 37	protected function get_report_html( $args = array() ) { 
 38		/* Defined in the report class */ 
 39		// For ajax, args start, end, and data will be set with the data to use. Else call $this->get_data( array( 'default' => true ) )
 40		return ''; 
 41	}
 42
 43	public function additional_data(){
 44		return array();
 45	}
 46
 47	public function requirements( $error = false, $args = array(), $name = '' ) {
 48		return $error;
 49	}
 50
 51	public function show_report( $args = array() ) {
 52
 53		if ( ! current_user_can( 'monsterinsights_view_dashboard' ) ) {
 54			return monsterinsights_get_message( 'error', esc_html__( 'Access denied' , 'google-analytics-for-wordpress' ) );
 55		}
 56
 57		if ( monsterinsights_get_option( 'dashboard_disabled', false ) ) { 
 58			if ( current_user_can( 'monsterinsights_save_settings' ) ) {
 59				$url = is_network_admin() ? network_admin_url( 'admin.php?page=monsterinsights_settings' ) : admin_url( 'admin.php?page=monsterinsights_settings' );
 60				return monsterinsights_get_message( 'error',
 61					sprintf(
 62						 esc_html__( 'Please %1$senable the dashboard%2$s to see report data.', 'google-analytics-for-wordpress' ),
 63							'<a href="' . $url . '">',
 64							'</a>'
 65						)
 66				);
 67			} else {
 68				return monsterinsights_get_message( 'error', esc_html__( 'The dashboard is disabled.', 'google-analytics-for-wordpress' ) );
 69			}
 70		}
 71
 72		if ( monsterinsights_is_pro_version() ){
 73			if ( ! MonsterInsights()->license->has_license() ) {
 74				$url = is_network_admin() ? network_admin_url( 'admin.php?page=monsterinsights_settings' ) : admin_url( 'admin.php?page=monsterinsights_settings' );
 75				return monsterinsights_get_message( 'error', esc_html__( 'You do not have an active license. Please %1$scheck your license configuration.%2$s', 'google-analytics-for-wordpress' ),'<a href="' . $url . '">','</a>' );
 76			} else if ( MonsterInsights()->license->license_has_error() ) {
 77				return monsterinsights_get_message( 'error', $this->get_license_error() );
 78			}
 79		}
 80
 81		if ( ! ( MonsterInsights()->auth->is_authed() || MonsterInsights()->auth->is_network_authed() ) ) {
 82			if ( current_user_can( 'monsterinsights_save_settings' ) ) {
 83				$url = is_network_admin() ? network_admin_url( 'admin.php?page=monsterinsights_settings' ) : admin_url( 'admin.php?page=monsterinsights_settings' );
 84				return monsterinsights_get_message( 'error',
 85					sprintf(
 86						esc_html__( 'Please %1$sauthenticate %2$swith Google Analytics to allow the plugin to fetch data.', 'google-analytics-for-wordpress' ),
 87							'<a href="' . $url . '">',
 88							'</a>'
 89					)
 90				);
 91			} else {
 92				return monsterinsights_get_message( 'error', esc_html__( 'The Google oAuth authentication needs to be re-authenticated to view data.', 'google-analytics-for-wordpress' ) );
 93			}
 94		}
 95
 96		if ( ! MonsterInsights()->license->license_can( $this->level ) ) {
 97			return $this->get_upsell_notice();
 98		}
 99
100		$error = $this->requirements( false, array(), $this->name );
101
102		if ( ! empty( $error ) ) {
103			return monsterinsights_get_message( 'error', $error );
104		}
105
106		if ( ! empty( $args['error'] ) ) {
107			return monsterinsights_get_message( 'error', $args['error'] );
108		}
109
110		if ( empty( $args['data' ] ) || ! is_array( $args['data' ] ) ) {
111			if ( monsterinsights_is_pro_version() ) {
112				return '';
113			} else {
114				// Try to get default data.
115				$args = $this->get_data( array( 'default' => true ) );
116				if ( empty( $args['data'] ) || is_array( $args['data' ] ) ) {
117					return monsterinsights_get_message( 'error', __( 'No data found', 'google-analytics-for-wordpress' ) );
118				}
119
120				if ( ! empty( $args['error'] ) ) {
121					return monsterinsights_get_message( 'error', $data['error'] );
122				}
123			}
124		}
125
126		return $this->get_report_html( $args['data'] );
127	}
128
129	// Deletes the report data from the cache
130	public function delete_cache( $where = 'site' ) {
131
132		if ( $where === 'site' || $where === 'both' ) {
133			delete_option( 'monsterinsights_report_data_' . $this->name );
134		}
135	
136		if ( $where === 'network' || $where === 'both' ) {
137			delete_option( 'monsterinsights_network_report_data_' . $this->name );
138		}
139	}
140
141	// Get report data
142	public function get_data( $args = array() ) {
143
144		if ( ! empty( $args['default'] ) ) {
145			$args['start']   = $this->default_start_date();
146			$args['end']     = $this->default_end_date();
147		}
148		
149		$start = ! empty( $args['start'] ) && $this->is_valid_date( $args['start'] ) ? $args['start'] : '';
150		$end   = ! empty( $args['end'] )   && $this->is_valid_date( $args['end'] )   ? $args['end']   : '';
151
152		if ( ! MonsterInsights()->license->license_can( $this->level ) ) {
153			return array(
154				'success' => true,
155				'upgrade' => true,
156				'data'    => array(),
157			);
158		}
159
160		if ( ! $this->is_valid_date_range( $start, $end ) ) {
161			return array(
162				'success' => false,
163				'error'   => __( 'Invalid date range.', 'google-analytics-for-wordpress' ),
164				'data'    => array(),
165			);
166		}
167
168		if ( ( $start !== $this->default_start_date() || $end !== $this->default_end_date() ) && ! monsterinsights_is_pro_version() ) {
169			return array(
170				'success' => false,
171				'error'   => __( 'Please upgrade to MonsterInsights Pro to use custom date ranges.', 'google-analytics-for-wordpress' ),
172				'data'    => array(),
173			);
174		}
175
176		$error = apply_filters( 'monsterinsights_reports_abstract_get_data_pre_cache', false, $args, $this->name );
177		if ( $error ) {
178			return array(
179				'success' => false,
180				'error'   => $error,
181				'data'    => array(),
182			);
183		}
184
185		$check_cache = ( $start === $this->default_start_date() && $end === $this->default_end_date() );
186		$site_auth   = MonsterInsights()->auth->get_viewname();
187		$ms_auth     = is_multisite() && MonsterInsights()->auth->get_network_viewname();
188		$transient   = 'monsterinsights_report_' . $this->name . '_' . $start . '_' . $end;
189		// Set to same time as MI cache. MI caches same day to 15 and others to 1 day, so there's no point pinging MI before then.
190		$expiration  = $end === date( 'Y-m-d' ) ? 15 * MINUTE_IN_SECONDS : DAY_IN_SECONDS;
191
192		// Default date range, check
193		if ( $site_auth || $ms_auth ) {
194			// Single site or MS with auth at subsite
195			$option_name  = $site_auth ? 'monsterinsights_report_data_' . $this->name : 'monsterinsights_network_report_data_' . $this->name;
196			$p            = $site_auth ? MonsterInsights()->auth->get_viewid() : MonsterInsights()->auth->get_network_viewid();
197
198			$data = array();
199			if ( $check_cache ) {
200				$data = ! $site_auth && $ms_auth ? get_site_option( $option_name, array() ) : get_option( $option_name, array() );
201			} else {
202				$data = ! $site_auth && $ms_auth ? get_site_transient( $transient ) : get_transient( $transient );
203			}
204
205			if ( ! empty( $data )             &&
206				 ! empty( $data['expires'] )  &&
207				   $data['expires'] >= time() &&
208				 ! empty( $data['data'] )     && 
209				 ! empty( $data['p'] )        && 
210				   $data['p'] === $p
211			) {
212				return array(
213					'success' => true,
214					'data'    => $data['data'],
215				);
216			}
217
218			// Nothing in cache, either not saved before, expired or mismatch. Let's grab from API
219			$api_options = array( 'start' => $start, 'end' => $end);
220			if ( ! $site_auth && $ms_auth ) {
221				$api_options['network'] = true;
222			}
223			
224			$api   = new MonsterInsights_API_Request( 'analytics/reports/' . $this->name . '/', $api_options, 'GET' );
225
226			$additional_data = $this->additional_data();
227			
228			if ( ! empty( $additional_data ) ) {
229				$api->set_additional_data( $additional_data );
230			}
231			
232			$ret   = $api->request();
233			//echo print_r( $ret['data']);wp_die();
234			
235			if ( is_wp_error( $ret ) ) {
236				return array(
237					'success' => false,
238					'error'   => $ret->get_error_message(),
239					'data'    => array(),
240				);
241			} else {
242				// Success
243				$data = array( 
244					'expires' => $expiration,
245					'p'       => $p,
246					'data'    => $ret['data'],
247				);
248				if ( $check_cache ) {
249					! $site_auth && $ms_auth ? update_site_option( $option_name, $data ) : update_option( $option_name, $data );
250				} else {
251					! $site_auth && $ms_auth ? set_site_transient( $option_name, $data, $expiration ) : set_transient( $option_name, $data, $expiration );
252				}
253				
254				return array(
255					'success' => true,
256					'data'    => $ret['data'],
257				);
258			}
259
260		} else {
261			return array(
262				'success' => false,
263				'error'   => __( 'You must authenticate with MonsterInsights to use reports.', 'google-analytics-for-wordpress' ),
264				'data'    => array(),
265			);
266		}
267	}
268
269	public function default_start_date() {
270		return date( 'Y-m-d', strtotime( '-30 days' ) );
271	}
272
273	public function default_end_date() {
274		return date( 'Y-m-d', strtotime( '-1 day' ) );
275	}
276
277	// Checks to see if date range is valid. Should be 30-yesterday always for lite & any valid date range to today for Pro.
278	public function is_valid_date_range( $start, $end ) {
279		$start = strtotime( $start );
280		$end   = strtotime( $end );
281
282		if ( $start > strtotime( 'now' ) || $end > strtotime( 'now' ) || $start < strtotime( '01 January 2005' ) || $end < strtotime( '01 January 2005' ) ) {
283			return false;
284		}
285
286		// return false if the start date is after the end date
287		return ( $start > $end ) ? false : true;
288	}
289
290	// Is a valid date value
291	public function is_valid_date( $date = '' ) {
292		$d = MonsterInsightsDateTime::createFromFormat( 'Y-m-d', $date );
293		return $d && $d->format('Y-m-d') === $date;
294	}
295
296	/**
297	 * Do not use the functions below this. They are unused and are just here so people
298	 * with out of date MonsterInsights addons won't get fatal errors.
299	 */
300	protected function get_api_max_limit() {return 300;}
301	protected function get_date_range() {return array();}
302
303	public function get_upsell_notice() {
304		$has_level = MonsterInsights()->license->get_license_type();
305		$has_level = $has_level ? $has_level : 'lite';
306		$message = sprintf( __( 'You currently have a %s level license, but this report requires at least a %s level license to view the %s. Please upgrade to view this report.', 'google-analytics-for-wordpress' ), $has_level, $this->level, $this->title );
307		ob_start();?>
308		<div class="monsterinsights-upsell-report-container monsterinsights-upsell-report-<?php echo $this->name;?>-bg">
309			<div class="monsterinsights-upsell-container">
310		  		<div class="row justify-content-center">
311					<div class="col-lg-10 col-lg-offset-1 align-self-center">
312						<div class="monsterinsights-upsell-card">
313							  <img class="monsterinsights-upgrade-mascot" src="<?php echo trailingslashit( MONSTERINSIGHTS_PLUGIN_URL );?>assets/css/images/mascot.png" srcset="<?php echo trailingslashit( MONSTERINSIGHTS_PLUGIN_URL );?>assets/css/images/mascot@2x.png 2x" alt="">
314								<div class="monsterinsights-upsell-card-card-content">
315								  <span class="monsterinsights-upsell-card-title"><?php esc_html_e( 'Ready to Get Analytics Super-Powers?', 'google-analytics-for-wordpress' );?></span>
316								  <p class="monsterinsights-upsell-card-subtitle"><strong><?php esc_html_e( '(And Crush Your Competition?)', 'google-analytics-for-wordpress' );?></strong></p> &nbsp;
317								  <?php if ( monsterinsights_is_pro_version() ) { ?>
318									  <p ><?php echo sprintf( esc_html__( "Hey there! It looks like you've got the %s license installed on your site.
319									  That's awesome! %s",'google-analytics-for-wordpress'), $has_level, '<span class="dashicons dashicons-smiley"></span>' ); ?></p>
320									   &nbsp;
321									  <p><?php echo sprintf( esc_html__( "Do you you want to access to %s reporting right now%s in your WordPress Dashboard? That comes with %s level%s of our paid packages. You'll need to upgrade your license to get instant access.",'google-analytics-for-wordpress'), '<strong>' . $this->title, '</strong>','<a href="https://monsterinsights.com/my-account/">' . $this->level,'</a>' ); ?></p>
322									   &nbsp;<p><?php echo sprintf( esc_html__( "It's easy! To upgrade, navigate to %sMy Account%s on MonsterInsights.com, go to the licenses tab, and click upgrade. We also have a %sstep by step guide%s with pictures of this process.",'google-analytics-for-wordpress'), '<a href="https://monsterinsights.com/my-account/?utm_source=wpdashboard&utm_campaign=reportupsellpro"><strong>','</strong></a>', '<a href="https://www.monsterinsights.com/docs/upgrade-monsterinsights-license/" style="text-decoration:underline !important">', '</a>' ); ?></p>
323									   &nbsp;<p><?php esc_html_e( "If you have any questions, don't hesitate to reach out. We're here to help.", 'google-analytics-for-wordpress');?></p>
324									<?php } else { ?>
325									   <p><?php echo sprintf( esc_html__( "Hey there! %s It looks like you've got the free version of MonsterInsights installed on your site.
326									  That's awesome!",'google-analytics-for-wordpress'), '<span class="dashicons dashicons-smiley"></span>' ); ?></p>
327									   &nbsp;
328									  <p><?php echo sprintf( esc_html__( "Do you you want to access to %s reporting right now%s in your WordPress Dashboard? That comes with %s level%s of our paid packages. To get instant access, you'll want to buy a MonsterInsights license, which also gives you access to powerful addons, expanded reporting (including the ability to use custom date ranges), comprehensive tracking features (like UserID tracking) and access to our world-class support team.",'google-analytics-for-wordpress'), '<strong>' . $this->title, '</strong>','<a href="https://monsterinsights.com/lite/">' . $this->level,'</a>' ); ?></p>
329									   &nbsp;<p><?php echo sprintf( esc_html__( "Upgrading is easy! To upgrade, navigate to %sour pricing page%s, purchase the required license, and then follow the %sinstructions in the email receipt%s to upgrade. It only takes a few minutes to unlock the most powerful, yet easy to use analytics tracking system for WordPress.",'google-analytics-for-wordpress'), '<a href="https://monsterinsights.com/lite/?utm_source=wpdashboard&utm_campaign=reportupselllite"><strong>', '</strong></a>','<a style="text-decoration:underline !important" href="https://www.monsterinsights.com/docs/go-lite-pro/">', '</a>' ); ?></p>
330									   &nbsp;<p><?php esc_html_e( "If you have any questions, don't hesitate to reach out. We're here to help.", 'google-analytics-for-wordpress');?></p>
331									<?php } ?>
332								</div>
333								<div class="monsterinsights-upsell-card-action">
334									 <?php if ( monsterinsights_is_pro_version() ) { ?>
335								  	<a href="https://monsterinsights.com/my-account/?utm_source=wpdashboard&utm_campaign=reportupsellpro" class="monsterinsights-upsell-card-button"><?php esc_html_e( 'Upgrade Now', 'google-analytics-for-wordpress' ); ?></a>
336								  	<?php } else { ?>
337								  	<a href="https://monsterinsights.com/lite/?utm_source=wpdashboard&utm_campaign=reportupselllite" class="monsterinsights-upsell-card-button"><?php esc_html_e( 'Get MonsterInsights Pro', 'google-analytics-for-wordpress' ); ?></a>
338								  	<?php } ?>
339									</div>
340								  </div>
341		                         </div>
342		                   </div>
343		               </div>
344		           </div>
345		 </div>
346		<?php
347		return ob_get_clean();
348	}
349
350    function get_ga_report_range( $data = array() ) {
351    	if ( empty( $data['reportcurrentrange'] ) || empty( $data['reportcurrentrange']['startDate'] ) || empty( $data['reportcurrentrange']['endDate'] ) ) {
352    		return '';
353    	} else {
354    		if ( ! empty( $data['reportprevrange'] ) && ! empty( $data['reportprevrange']['startDate'] ) && ! empty( $data['reportprevrange']['endDate'] ) ) {
355    			return '%3F_u.date00%3D' . str_replace( '-', '', $data['reportcurrentrange']['startDate'] ) .'%26_u.date01%3D' . str_replace( '-', '', $data['reportcurrentrange']['endDate'] ) . '%26_u.date10%3D' . str_replace( '-', '', $data['reportprevrange']['startDate'] ) .'%26_u.date11%3D' . str_replace( '-', '', $data['reportprevrange']['endDate'] ) . '/';
356    		} else {
357    			return '%3F_u.date00%3D' . str_replace( '-', '', $data['reportcurrentrange']['startDate'] ) .'%26_u.date01%3D' . str_replace( '-', '', $data['reportcurrentrange']['endDate'] ) . '/';
358    		}
359    	}
360    }
361}
362
363if ( ! class_exists( 'MonsterInsightsDateTime' ) ) {
364	class MonsterInsightsDateTime extends DateTime {
365		public static function createFromFormat( $format, $time, $timezone = null ) {
366			if ( ! $timezone ) { 
367				$timezone = new DateTimeZone( date_default_timezone_get() );
368			}
369			if ( version_compare( PHP_VERSION, '5.3', '>=' ) ) {
370				return parent::createFromFormat( $format, $time, $timezone );
371			}
372			return new DateTime( date( $format, strtotime( $time ) ), $timezone );
373		}
374	}
375}