Completed
Branch FET/11183/improvements-to-pue-... (dfe6b8)
by
unknown
75:16 queued 60:57
created

Stats::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 10
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 8
nc 1
nop 3
dl 0
loc 10
rs 9.4285
c 0
b 0
f 0
1
<?php
2
namespace EventEspresso\core\domain\services\pue;
3
4
use Closure;
5
use EE_Admin_Page;
6
use EE_Error;
7
use EE_Maintenance_Mode;
8
use EEH_Template;
9
use EEM_Payment_Method;
10
use Exception;
11
use const WEEK_IN_SECONDS;
12
13
/**
14
 * Stats
15
 * This service exposes various stat collection logic retrieval and storage. Used for prepping the stats package sent
16
 * through PUE as a part of the UXIP stats collection.
17
 *
18
 * @package EventEspresso\core\domain\services\pue
19
 * @author  Darren Ethier
20
 * @since   $VID:$
21
 */
22
class Stats
23
{
24
25
    const OPTIONS_KEY_EXPIRY_TIMESTAMP_FOR_SENDING_STATS = 'ee_uxip_stats_expiry';
26
27
    /**
28
     * @var Config
29
     */
30
    private $config;
31
32
33
    /**
34
     * @var StatsGatherer
35
     */
36
    private $stats_gatherer;
37
38
39
    /**
40
     * @var EE_Maintenance_Mode
41
     */
42
    private $maintenance_mode;
43
44
    public function __construct(
45
        Config $config,
46
        EE_Maintenance_Mode $maintenance_mode,
47
        StatsGatherer $stats_gatherer
48
    ) {
49
        $this->config = $config;
50
        $this->maintenance_mode = $maintenance_mode;
51
        $this->stats_gatherer = $stats_gatherer;
52
        $this->setUxipNotices();
53
    }
54
55
56
    /**
57
     * Displays uxip opt-in notice if necessary.
58
     */
59
    private function setUxipNotices()
60
    {
61
        if ($this->canDisplayNotices()) {
62
            add_action('admin_notices', array($this, 'optinNotice'));
63
            add_action('admin_enqueue_scripts', array($this, 'enqueueScripts'));
64
            add_action('wp_ajax_espresso_data_optin', array($this, 'ajaxHandler'));
65
            //makes sure optin defaults to yes even if its currently empty.
66
            $this->config->setHasOptedInForUxip();
67
        }
68
    }
69
70
71
    /**
72
     * This returns the callback that PluginUpdateEngineChecker will use for getting any extra stats to send.
73
     * @return Closure
74
     */
75
    public function statsCallback()
76
    {
77
        //returns a callback that can is used to retrieve the stats to send along to the pue server.
78
        return function () {
79
            //we only send stats one a week, so let's see if our stat timestamp has expired.
80
            if (! $this->sendStats()) {
81
                return array();
82
            }
83
            return $this->stats_gatherer->stats();
84
        };
85
    }
86
87
88
    /**
89
     * Return whether notices can be displayed or not
90
     * @return bool
91
     */
92
    private function canDisplayNotices()
93
    {
94
        return ! $this->config->hasNotifiedForUxip()
95
               && $this->maintenance_mode->level() !== EE_Maintenance_Mode::level_2_complete_maintenance;
96
    }
97
98
99
    /**
100
     * Callback for the admin_notices hook that outputs the UXIP optin-in notice.
101
     */
102
    public function optinNotice()
103
    {
104
        ?>
105
        <div class="updated data-collect-optin" id="espresso-data-collect-optin-container">
106
            <div id="data-collect-optin-options-container">
107
                <span class="dashicons dashicons-admin-site"></span>
108
                <span class="data-optin-text"><?php echo self::optinText(); ?></span>
109
                <span style="display: none" id="data-optin-nonce"><?php echo wp_create_nonce('ee-data-optin'); ?></span>
110
                <button class="button-secondary data-optin-button" value="no">
111
                    <?php _e('Dismiss', 'event_espresso'); ?>
112
                </button>
113
                <div style="clear:both"></div>
114
            </div>
115
        </div>
116
        <?php
117
    }
118
119
120
    /**
121
     * Retrieves the optin text (static so it can be used in multiple places as necessary).
122
     * @param bool $extra
123
     */
124
    public static function optinText($extra = true)
125
    {
126
        if (! $extra) {
127
            echo '<h2 class="ee-admin-settings-hdr" '
128
                 . (! $extra ? 'id="UXIP_settings"' : '')
129
                 . '>'
130
                 . esc_html__('User eXperience Improvement Program (UXIP)', 'event_espresso')
131
                 . EEH_Template::get_help_tab_link('organization_logo_info')
132
                 . '</h2>';
133
            printf(
134
                esc_html__(
135
                    '%sPlease help us make Event Espresso better and vote for your favorite features.%s The %sUser eXperience Improvement Program (UXIP)%s, has been created so when you use Event Espresso you are voting for the features and settings that are important to you. The UXIP helps us understand how you use our products and services, track problems and in what context. If you opt-out of the UXIP you essentially elect for us to disregard how you use Event Espresso as we build new features and make changes. Participation in the program is completely voluntary but it is enabled by default. The end results of the UXIP are software improvements to better meet your needs. The data we collect will never be sold, traded, or misused in any way. %sPlease see our %sPrivacy Policy%s for more information.',
136
                    'event_espresso'
137
                ),
138
                '<p><em>',
139
                '</em></p>',
140
                '<a href="https://eventespresso.com/about/user-experience-improvement-program-uxip/" target="_blank">',
141
                '</a>',
142
                '<br><br>',
143
                '<a href="https://eventespresso.com/about/privacy-policy/" target="_blank">',
144
                '</a>'
145
            );
146
        } else {
147
            $settings_url = EE_Admin_Page::add_query_args_and_nonce(
148
                array('action' => 'default'),
149
                admin_url('admin.php?page=espresso_general_settings')
150
            );
151
            $settings_url .= '#UXIP_settings';
152
            printf(
153
                esc_html__(
154
                    'The Event Espresso UXIP feature is active on your site. For %smore info%s and to opt-out %sclick here%s.',
155
                    'event_espresso'
156
                ),
157
                '<a href="https://eventespresso.com/about/user-experience-improvement-program-uxip/" target="_blank">',
158
                '</a>',
159
                '<a href="' . $settings_url . '" target="_blank">',
160
                '</a>'
161
            );
162
        }
163
    }
164
165
166
    /**
167
     * Callback for admin_enqueue_scripts that sets up the scripts and styles for the uxip notice
168
     */
169 View Code Duplication
    public function enqueueScripts()
170
    {
171
        wp_register_script(
172
            'ee-data-optin-js',
173
            EE_GLOBAL_ASSETS_URL . 'scripts/ee-data-optin.js',
174
            array('jquery'),
175
            EVENT_ESPRESSO_VERSION,
176
            true
177
        );
178
        wp_register_style(
179
            'ee-data-optin-css',
180
            EE_GLOBAL_ASSETS_URL . 'css/ee-data-optin.css',
181
            array(),
182
            EVENT_ESPRESSO_VERSION
183
        );
184
185
        wp_enqueue_script('ee-data-optin-js');
186
        wp_enqueue_style('ee-data-optin-css');
187
    }
188
189
190
    /**
191
     * Callback for wp_ajax_espresso_data_optin that handles the ajax request
192
     */
193
    public function ajaxHandler()
194
    {
195
        //verify nonce
196
        if (isset($_POST['nonce']) && ! wp_verify_nonce($_POST['nonce'], 'ee-data-optin')) {
197
            exit();
198
        }
199
200
        //update has notified option
201
        $this->config->setHasNotifiedAboutUxip();
202
        exit();
203
    }
204
205
206
    /**
207
     * Used to determine whether additional stats are sent.
208
     */
209
    private function sendStats()
210
    {
211
        return $this->config->isOptedInForUxip()
212
            && $this->maintenance_mode->level() !== EE_Maintenance_Mode::level_2_complete_maintenance
213
            && $this->statSendTimestampExpired();
214
    }
215
216
217
    /**
218
     * Returns true when the timestamp used to track whether stats get sent (currently a weekly interval) is expired.
219
     * Returns false otherwise.
220
     * @return bool
221
     */
222
    private function statSendTimestampExpired()
223
    {
224
        $current_expiry = get_option(self::OPTIONS_KEY_EXPIRY_TIMESTAMP_FOR_SENDING_STATS, null);
225
        if ($current_expiry === null) {
226
            add_option(self::OPTIONS_KEY_EXPIRY_TIMESTAMP_FOR_SENDING_STATS, time() + WEEK_IN_SECONDS, '', 'no');
227
            return true;
228
        }
229
230
        if (time() > (int) $current_expiry) {
231
            update_option(self::OPTIONS_KEY_EXPIRY_TIMESTAMP_FOR_SENDING_STATS, time() + WEEK_IN_SECONDS);
232
            return true;
233
        }
234
        return false;
235
    }
236
}