class-tracking.php 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. <?php
  2. /**
  3. * WPSEO plugin file.
  4. *
  5. * @package WPSEO\Admin\Tracking
  6. */
  7. /**
  8. * This class handles the tracking routine.
  9. */
  10. class WPSEO_Tracking {
  11. /** @var string */
  12. protected $option_name = 'wpseo_tracking_last_request';
  13. /** @var int */
  14. protected $threshold = 0;
  15. /** @var string */
  16. protected $endpoint = '';
  17. /**
  18. * Constructor setting the treshhold..
  19. *
  20. * @param string $endpoint The endpoint to send the data to.
  21. * @param int $threshold The limit for the option.
  22. */
  23. public function __construct( $endpoint, $threshold ) {
  24. $this->endpoint = $endpoint;
  25. $this->threshold = $threshold;
  26. }
  27. /**
  28. * Registers all hooks to WordPress
  29. */
  30. public function send() {
  31. $current_time = time();
  32. if ( ! $this->should_send_tracking( $current_time ) ) {
  33. return;
  34. }
  35. $collector = $this->get_collector();
  36. $request = new WPSEO_Remote_Request( $this->endpoint );
  37. $request->set_body( $collector->get_as_json() );
  38. $request->send();
  39. update_option( $this->option_name, $current_time, 'yes' );
  40. }
  41. /**
  42. * Returns true when last tracking data was send more than two weeks ago.
  43. *
  44. * @param int $current_time The current timestamp.
  45. *
  46. * @return bool True when tracking data should be send.
  47. */
  48. protected function should_send_tracking( $current_time ) {
  49. $last_time = get_option( $this->option_name );
  50. // When there is no data being set.
  51. if ( ! $last_time ) {
  52. return true;
  53. }
  54. return $this->exceeds_treshhold( $current_time - $last_time );
  55. }
  56. /**
  57. * Checks if the given amount of seconds exceeds the set threshold.
  58. *
  59. * @param int $seconds The amount of seconds to check.
  60. *
  61. * @return bool True when seconds is bigger than threshold.
  62. */
  63. protected function exceeds_treshhold( $seconds ) {
  64. return ( $seconds > $this->threshold );
  65. }
  66. /**
  67. * Returns the collector for collecting the data.
  68. *
  69. * @return WPSEO_Collector The instance of the collector.
  70. */
  71. protected function get_collector() {
  72. $collector = new WPSEO_Collector();
  73. $collector->add_collection( new WPSEO_Tracking_Default_Data() );
  74. $collector->add_collection( new WPSEO_Tracking_Server_Data() );
  75. $collector->add_collection( new WPSEO_Tracking_Theme_Data() );
  76. $collector->add_collection( new WPSEO_Tracking_Plugin_Data() );
  77. return $collector;
  78. }
  79. }