/classes/WpMatomo/Annotations.php

https://github.com/matomo-org/wp-matomo · PHP · 88 lines · 49 code · 15 blank · 24 comment · 6 complexity · 375eb93ddcdfd51ea90bf6b3b854618b MD5 · raw file

  1. <?php
  2. /**
  3. * Matomo - free/libre analytics platform
  4. *
  5. * @link https://matomo.org
  6. * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
  7. * @package matomo
  8. */
  9. namespace WpMatomo;
  10. use Exception;
  11. if ( ! defined( 'ABSPATH' ) ) {
  12. exit; // if accessed directly
  13. }
  14. class Annotations {
  15. /**
  16. * @var Settings
  17. */
  18. private $settings;
  19. /**
  20. * @var Logger
  21. */
  22. private $logger;
  23. /**
  24. * @param Settings $settings
  25. */
  26. public function __construct( $settings ) {
  27. $this->settings = $settings;
  28. $this->logger = new Logger();
  29. }
  30. public function register_hooks() {
  31. add_action( 'transition_post_status', [ $this, 'add_annotation' ], 10, 3 );
  32. }
  33. /**
  34. * Identify new posts if an annotation is required
  35. * and create Piwik annotation
  36. *
  37. * @param string $new_status new post status
  38. * @param string $old_status old post status
  39. * @param object $post current post object
  40. */
  41. public function add_annotation( $new_status, $old_status, $post ) {
  42. if ( ! $this->settings->is_tracking_enabled() ) {
  43. return;
  44. }
  45. $enabled_post_types = $this->settings->get_global_option( 'add_post_annotations' );
  46. if ( empty( $enabled_post_types[ $post->post_type ] ) ) {
  47. return;
  48. }
  49. if ( 'publish' === $new_status
  50. && 'publish' !== $old_status ) {
  51. $site = new Site();
  52. $idsite = $site->get_current_matomo_site_id();
  53. if ( ! $idsite ) {
  54. return; // no site we can add it to
  55. }
  56. try {
  57. Bootstrap::do_bootstrap();
  58. $logger = $this->logger;
  59. \Piwik\Access::doAsSuperUser(
  60. function () use ( $post, $logger, $idsite ) {
  61. $note = esc_html__( 'Published:', 'matomo' ) . ' ' . $post->post_title . ' - URL: ' . get_permalink( $post->ID );
  62. \Piwik\Plugins\Annotations\API::unsetInstance();// make sure latest instance will be loaded with all up to date dependencies... mainly needed for tests
  63. $id = \Piwik\Plugins\Annotations\API::getInstance()->add( $idsite, gmdate( 'Y-m-d' ), $note );
  64. $logger->log( 'Add post annotation. ' . $note . ' - ' . wp_json_encode( $id ) );
  65. }
  66. );
  67. } catch ( Exception $e ) {
  68. $this->logger->log( 'Add post annotation failed: ' . $e->getMessage() );
  69. return;
  70. }
  71. }
  72. }
  73. }