PluginProbe
BlockSpare – Gutenberg Blocks for News, Magazine, Blog & Business Websites / 2.6.1
BlockSpare – Gutenberg Blocks for News, Magazine, Blog & Business Websites v2.6.1
4.1.0 trunk 1.0.0 1.0.1 1.0.2 1.0.3 1.0.4 1.0.5 1.1.0 1.1.1 1.1.2 1.2.0 1.2.1 1.2.2 1.2.3 1.3.0 1.3.1 1.3.2 1.3.3 1.3.4 1.3.5 2.1.2 2.5.0 2.5.3 2.6.1 All 38 releases
blockspare / freemius / includes / class-freemius.php

class-freemius.php in BlockSpare – Gutenberg Blocks for News, Magazine, Blog & Business Websites 2.6.1, at freemius/includes/class-freemius.php

26,392 lines 964.5 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2 /**
3 * @package Freemius
4 * @copyright Copyright (c) 2015, Freemius, Inc.
5 * @license https://www.gnu.org/licenses/gpl-3.0.html GNU General Public License Version 3
6 * @since 1.0.3
7 */
8 if ( ! defined( 'ABSPATH' ) ) {
9 exit;
10 }
11
12 // "final class"
13 class Freemius extends Freemius_Abstract {
14 /**
15 * SDK Version
16 *
17 * @var string
18 */
19 public $version = WP_FS__SDK_VERSION;
20
21 #region Plugin Info
22
23 /**
24 * @since 1.0.1
25 *
26 * @var string
27 */
28 private $_slug;
29
30 /**
31 * @since 1.0.0
32 *
33 * @var string
34 */
35 private $_plugin_basename;
36 /**
37 * @since 2.2.1
38 *
39 * @var string
40 */
41 private $_premium_plugin_basename;
42 /**
43 * @since 1.0.0
44 *
45 * @var string
46 */
47 private $_free_plugin_basename;
48 /**
49 * @since 1.0.0
50 *
51 * @var string
52 */
53 private $_plugin_dir_path;
54 /**
55 * @since 1.0.0
56 *
57 * @var string
58 */
59 private $_plugin_dir_name;
60 /**
61 * @since 1.0.0
62 *
63 * @var string
64 */
65 private $_plugin_main_file_path;
66 /**
67 * @var string[]
68 */
69 private $_plugin_data;
70 /**
71 * @since 1.0.9
72 *
73 * @var string
74 */
75 private $_plugin_name;
76 /**
77 * @since 1.2.2
78 *
79 * @var string
80 */
81 private $_module_type;
82
83 #endregion Plugin Info
84
85 /**
86 * @since 1.0.9
87 *
88 * @var bool If false, don't turn Freemius on.
89 */
90 private $_is_on;
91
92 /**
93 * @since 1.1.3
94 *
95 * @var bool If false, don't turn Freemius on.
96 */
97 private $_is_anonymous;
98
99 /**
100 * @since 1.0.9
101 * @var bool If false, issues with connectivity to Freemius API.
102 */
103 private $_has_api_connection;
104
105 /**
106 * @since 1.0.9
107 * @since 2.0.0 Default to true since we need the property during the instance construction, prior to the dynamic_init() execution.
108 * @var bool Hints the SDK if plugin can support anonymous mode (if skip connect is visible).
109 */
110 private $_enable_anonymous = true;
111
112 /**
113 * @since 1.1.7.5
114 * @var bool Hints the SDK if plugin should run in anonymous mode (only adds feedback form).
115 */
116 private $_anonymous_mode;
117
118 /**
119 * @since 1.1.9
120 * @var bool Hints the SDK if plugin have any free plans.
121 */
122 private $_is_premium_only;
123
124 /**
125 * @since 1.2.1.6
126 * @var bool Hints the SDK if plugin have premium code version at all.
127 */
128 private $_has_premium_version;
129
130 /**
131 * @since 1.2.1.6
132 * @var bool Hints the SDK if plugin should ignore pending mode by simulating a skip.
133 */
134 private $_ignore_pending_mode;
135
136 /**
137 * @since 1.0.8
138 * @var bool Hints the SDK if the plugin has any paid plans.
139 */
140 private $_has_paid_plans;
141
142 /**
143 * @since 1.2.1.5
144 * @var int Hints the SDK if the plugin offers a trial period. If negative, no trial, if zero - has a trial but
145 * without a specified period, if positive - the number of trial days.
146 */
147 private $_trial_days = - 1;
148
149 /**
150 * @since 1.2.1.5
151 * @var bool Hints the SDK if the trial requires a payment method or not.
152 */
153 private $_is_trial_require_payment = false;
154
155 /**
156 * @since 1.0.7
157 * @var bool Hints the SDK if the plugin is WordPress.org compliant.
158 */
159 private $_is_org_compliant;
160
161 /**
162 * @since 1.0.7
163 * @var bool Hints the SDK if the plugin is has add-ons.
164 */
165 private $_has_addons;
166
167 /**
168 * @since 2.4.5
169 * @var string Navigation type: 'menu' or 'tabs'.
170 */
171 private $_navigation;
172
173 const NAVIGATION_MENU = 'menu';
174 const NAVIGATION_TABS = 'tabs';
175
176 /**
177 * @since 1.1.6
178 * @var string[]bool.
179 */
180 private $_permissions;
181
182 /**
183 * @var FS_Storage
184 */
185 private $_storage;
186
187 /**
188 * @since 1.2.2.7
189 * @var FS_Cache_Manager
190 */
191 private $_cache;
192
193 /**
194 * @since 1.0.0
195 *
196 * @var FS_Logger
197 */
198 private $_logger;
199 /**
200 * @since 1.0.4
201 *
202 * @var FS_Plugin
203 */
204 private $_plugin = false;
205 /**
206 * @since 1.0.4
207 *
208 * @var FS_Plugin|false
209 */
210 private $_parent_plugin = false;
211 /**
212 * @since 1.1.1
213 *
214 * @var Freemius
215 */
216 private $_parent = false;
217 /**
218 * @since 1.0.1
219 *
220 * @var FS_User
221 */
222 private $_user = false;
223 /**
224 * @since 1.0.1
225 *
226 * @var FS_Site
227 */
228 private $_site = false;
229 /**
230 * @since 1.0.1
231 *
232 * @var FS_Plugin_License
233 */
234 private $_license;
235 /**
236 * @since 1.0.2
237 *
238 * @var FS_Plugin_Plan[]
239 */
240 private $_plans = false;
241 /**
242 * @var FS_Plugin_License[]
243 * @since 1.0.5
244 */
245 private $_licenses = false;
246
247 /**
248 * @since 1.0.1
249 *
250 * @var FS_Admin_Menu_Manager
251 */
252 private $_menu;
253
254 /**
255 * @var FS_Admin_Notices
256 */
257 private $_admin_notices;
258
259 /**
260 * @since 1.1.6
261 *
262 * @var FS_Admin_Notices
263 */
264 private static $_global_admin_notices;
265
266 /**
267 * @var FS_Logger
268 * @since 1.0.0
269 */
270 private static $_static_logger;
271
272 /**
273 * @var FS_Options
274 * @since 1.0.2
275 */
276 private static $_accounts;
277
278 /**
279 * @since 1.2.2
280 *
281 * @var number
282 */
283 private $_module_id;
284
285 /**
286 * @var Freemius[]
287 */
288 private static $_instances = array();
289
290 /**
291 * @since 1.2.3
292 *
293 * @var FS_Affiliate
294 */
295 private $affiliate = null;
296
297 /**
298 * @since 1.2.3
299 *
300 * @var FS_AffiliateTerms
301 */
302 private $plugin_affiliate_terms = null;
303
304 /**
305 * @since 1.2.3
306 *
307 * @var FS_AffiliateTerms
308 */
309 private $custom_affiliate_terms = null;
310
311 /**
312 * @since 2.0.0
313 *
314 * @var bool
315 */
316 private $_is_multisite_integrated;
317
318 /**
319 * @since 2.0.0
320 *
321 * @var bool True if the current request is for a network admin screen and the plugin is network active.
322 */
323 private $_is_network_active;
324
325 /**
326 * @since 2.0.0
327 *
328 * @var int|null The original blog ID the plugin was loaded with.
329 */
330 private $_blog_id = null;
331
332 /**
333 * @since 2.0.0
334 *
335 * @var int|null The current execution context. When true, run on network context. When int, run on the specified blog context.
336 */
337 private $_context_is_network_or_blog_id = null;
338
339 /**
340 * @since 2.0.0
341 *
342 * @var string
343 */
344 private $_dynamically_added_top_level_page_hook_name = '';
345
346 /**
347 * @author Leo Fajardo (@leorw)
348 * @since 2.3.1
349 *
350 * @var bool
351 */
352 private $is_whitelabeled;
353
354 /**
355 * @author Leo Fajardo (@leorw)
356 * @since 2.4.0
357 *
358 * @var bool
359 */
360 private $_is_bundle_license_auto_activation_enabled = false;
361
362 #region Uninstall Reasons IDs
363
364 const REASON_NO_LONGER_NEEDED = 1;
365 const REASON_FOUND_A_BETTER_PLUGIN = 2;
366 const REASON_NEEDED_FOR_A_SHORT_PERIOD = 3;
367 const REASON_BROKE_MY_SITE = 4;
368 const REASON_SUDDENLY_STOPPED_WORKING = 5;
369 const REASON_CANT_PAY_ANYMORE = 6;
370 const REASON_OTHER = 7;
371 const REASON_DIDNT_WORK = 8;
372 const REASON_DONT_LIKE_TO_SHARE_MY_INFORMATION = 9;
373 const REASON_COULDNT_MAKE_IT_WORK = 10;
374 const REASON_GREAT_BUT_NEED_SPECIFIC_FEATURE = 11;
375 const REASON_NOT_WORKING = 12;
376 const REASON_NOT_WHAT_I_WAS_LOOKING_FOR = 13;
377 const REASON_DIDNT_WORK_AS_EXPECTED = 14;
378 const REASON_TEMPORARY_DEACTIVATION = 15;
379
380 #endregion
381
382 /**
383 * @author Leo Fajardo (@leorw)
384 * @since 2.3.1
385 *
386 * @var boolean|null
387 */
388 private $_use_external_pricing = null;
389 /**
390 * @author Leo Fajardo (@leorw)
391 * @since 2.4.2
392 *
393 * @var string|null
394 */
395 private $_pricing_js_path = null;
396
397 const VERSION_MAX_CHARS = 16;
398 const LANGUAGE_MAX_CHARS = 8;
399
400 /* Ctor
401 ------------------------------------------------------------------------------------------------------------------*/
402
403 /**
404 * Main singleton instance.
405 *
406 * @author Vova Feldman (@svovaf)
407 * @since 1.0.0
408 *
409 * @param number $module_id
410 * @param string|bool $slug
411 * @param bool $is_init Since 1.2.1 Is initiation sequence.
412 */
413 private function __construct( $module_id, $slug = false, $is_init = false ) {
414 $main_file = false;
415
416 if ( $is_init && is_numeric( $module_id ) && is_string( $slug ) ) {
417 $main_file = $this->store_id_slug_type_path_map( $module_id, $slug );
418 }
419
420 $this->_module_id = $module_id;
421 $this->_slug = $this->get_slug();
422 $this->_module_type = $this->get_module_type();
423
424 $this->_blog_id = is_multisite() ? get_current_blog_id() : null;
425
426 $this->_storage = FS_Storage::instance( $this->_module_type, $this->_slug );
427
428 $this->_cache = FS_Cache_Manager::get_manager( WP_FS___OPTION_PREFIX . "cache_{$module_id}" );
429
430 $this->_logger = FS_Logger::get_logger( WP_FS__SLUG . '_' . $this->get_unique_affix(), WP_FS__DEBUG_SDK, WP_FS__ECHO_DEBUG_SDK );
431
432 $this->_plugin_main_file_path = $this->_find_caller_plugin_file( $is_init, $main_file );
433 $this->_plugin_dir_path = plugin_dir_path( $this->_plugin_main_file_path );
434 $this->_plugin_basename = $this->get_plugin_basename();
435 $this->_free_plugin_basename = str_replace( '-premium/', '/', $this->_plugin_basename );
436
437 $this->_is_multisite_integrated = (
438 defined( "WP_FS__PRODUCT_{$module_id}_MULTISITE" ) &&
439 ( true === constant( "WP_FS__PRODUCT_{$module_id}_MULTISITE" ) )
440 );
441
442 $this->_is_network_active = (
443 is_multisite() &&
444 $this->_is_multisite_integrated &&
445 // Themes are always network activated, but the ACTUAL activation is per site.
446 $this->is_plugin() &&
447 (
448 is_plugin_active_for_network( $this->_plugin_basename ) ||
449 // Plugin network level activation or uninstall.
450 ( fs_is_network_admin() && is_plugin_inactive( $this->_plugin_basename ) )
451 )
452 );
453
454 $this->_storage->set_network_active(
455 $this->_is_network_active,
456 $this->is_delegated_connection()
457 );
458
459 if ( ! isset( $this->_storage->is_network_activated ) ) {
460 $this->_storage->is_network_activated = $this->_is_network_active;
461 }
462
463 if ( $this->_storage->is_network_activated != $this->_is_network_active ) {
464 // Update last activation level.
465 $this->_storage->is_network_activated = $this->_is_network_active;
466
467 $this->maybe_adjust_storage();
468 }
469
470 #region Migration
471
472 if ( is_multisite() ) {
473 /**
474 * If the install_timestamp exists on the site level but doesn't exist on the
475 * network level storage, it means that we need to process the storage with migration.
476 *
477 * The code in this `if` scope will only be executed once and only for the first site that will execute it because once we migrate the storage data, install_timestamp will be already set in the network level storage.
478 *
479 * @author Vova Feldman (@svovaf)
480 * @since 2.0.0
481 */
482 if ( false === $this->_storage->get( 'install_timestamp', false, true ) &&
483 false !== $this->_storage->get( 'install_timestamp', false, false )
484 ) {
485 // Initiate storage migration.
486 $this->_storage->migrate_to_network();
487
488 // Migrate module cache to network level storage.
489 $this->_cache->migrate_to_network();
490 }
491 }
492
493 #endregion
494
495 $base_name_split = explode( '/', $this->_plugin_basename );
496 $this->_plugin_dir_name = $base_name_split[0];
497
498 if ( $this->_logger->is_on() ) {
499 $this->_logger->info( 'plugin_main_file_path = ' . $this->_plugin_main_file_path );
500 $this->_logger->info( 'plugin_dir_path = ' . $this->_plugin_dir_path );
501 $this->_logger->info( 'plugin_basename = ' . $this->_plugin_basename );
502 $this->_logger->info( 'free_plugin_basename = ' . $this->_free_plugin_basename );
503 $this->_logger->info( 'plugin_dir_name = ' . $this->_plugin_dir_name );
504 }
505
506 // Remember link between file to slug.
507 $this->store_file_slug_map();
508
509 // Store plugin's initial install timestamp.
510 if ( ! isset( $this->_storage->install_timestamp ) ) {
511 $this->_storage->install_timestamp = WP_FS__SCRIPT_START_TIME;
512 }
513
514 if ( ! is_object( $this->_plugin ) ) {
515 $this->_plugin = FS_Plugin_Manager::instance( $this->_module_id )->get();
516 }
517
518 $this->_admin_notices = FS_Admin_Notices::instance(
519 $this->_slug . ( $this->is_theme() ? ':theme' : '' ),
520 /**
521 * Ensure that the admin notice will always have a title by using the stored plugin title if available and
522 * retrieving the title via the "get_plugin_name" method if there is no stored plugin title available.
523 *
524 * @author Leo Fajardo (@leorw)
525 * @since 1.2.2
526 */
527 ( is_object( $this->_plugin ) && isset( $this->_plugin->title ) ?
528 $this->_plugin->title :
529 $this->get_plugin_name()
530 ),
531 $this->get_unique_affix()
532 );
533
534 if ( 'true' === fs_request_get( 'fs_clear_api_cache' ) ||
535 fs_request_is_action( 'restart_freemius' )
536 ) {
537 FS_Api::clear_cache();
538 $this->_cache->clear();
539 }
540
541 $this->register_constructor_hooks();
542
543 /**
544 * Starting from version 2.0.0, `FS_Site` entities no longer have the `plan` property and have `plan_id`
545 * instead. This should be called before calling `_load_account()`, otherwise, `$this->_site` will not be
546 * loaded in `_load_account` for versions of SDK starting from 2.0.0.
547 *
548 * @author Leo Fajardo (@leorw)
549 */
550 self::migrate_install_plan_to_plan_id( $this->_storage );
551
552 $this->_load_account();
553
554 $this->_version_updates_handler();
555 }
556
557 /**
558 * @author Leo Fajardo (@leorw)
559 * @since 2.3.0
560 */
561 private function maybe_adjust_storage() {
562 $install_timestamp = null;
563 $prev_is_premium = null;
564
565 $options_to_update = array();
566
567 $is_network_admin = fs_is_network_admin();
568
569 $network_install_timestamp = $this->_storage->get( 'install_timestamp', null, true );
570
571 if ( ! $is_network_admin ) {
572 if ( is_null( $network_install_timestamp ) ) {
573 // Plugin was not network-activated before.
574 return;
575 }
576
577 if ( is_null( $this->_storage->get( 'install_timestamp', null, false ) ) ) {
578 // Set the `install_timestamp` only if it's not yet set.
579 $install_timestamp = $network_install_timestamp;
580 }
581
582 $prev_is_premium = $this->_storage->get( 'prev_is_premium', null, true );
583 } else {
584 $current_wp_user = self::_get_current_wp_user();
585 $current_fs_user = self::_get_user_by_email( $current_wp_user->user_email );
586 $network_user_info = array();
587
588 $skips_count = 0;
589
590 $sites = self::get_sites();
591 $sites_count = count( $sites );
592
593 $blog_id_2_install_map = array();
594
595 $is_first_non_ignored_blog = true;
596
597 foreach ( $sites as $site ) {
598 $blog_id = self::get_site_blog_id( $site );
599
600 $blog_install_timestamp = $this->_storage->get( 'install_timestamp', null, $blog_id );
601
602 if ( is_null( $blog_install_timestamp ) ) {
603 // Plugin has not been installed on this blog.
604 continue;
605 }
606
607 $is_earlier_install = (
608 ! is_null( $install_timestamp ) &&
609 $blog_install_timestamp < $install_timestamp
610 );
611
612 $install = $this->get_install_by_blog_id( $blog_id );
613
614 $update_network_user_info = false;
615
616 if ( ! is_object( $install ) ) {
617 if ( ! $this->_storage->get( 'is_anonymous', false, $blog_id ) ) {
618 // The opt-in decision (whether to skip or opt in) is yet to be made.
619 continue;
620 }
621
622 $skips_count ++;
623 } else {
624 $blog_id_2_install_map[ $blog_id ] = $install;
625
626 if ( empty( $network_user_info ) ) {
627 // Set the network user info for the 1st time. Choose any user information whether or not it is for the current WP user.
628 $update_network_user_info = true;
629 }
630
631 if ( ! $update_network_user_info &&
632 is_object( $current_fs_user ) &&
633 $network_user_info['user_id'] != $current_fs_user->id &&
634 $install->user_id == $current_fs_user->id
635 ) {
636 // If an install that is owned by the current WP user is found, use its user information instead.
637 $update_network_user_info = true;
638 }
639
640 if ( ! $update_network_user_info &&
641 $is_earlier_install &&
642 ( ! is_object( $current_fs_user ) || $current_fs_user->id == $install->user_id )
643 ) {
644 // Update to the earliest install info if there's no install found so far that is owned by the current WP user; OR only if the found install is owned by the current WP user.
645 $update_network_user_info = true;
646 }
647 }
648
649 if ( $update_network_user_info ) {
650 $network_user_info = array(
651 'user_id' => $install->user_id,
652 'blog_id' => $blog_id
653 );
654 }
655
656 $site_prev_is_premium = $this->_storage->get( 'prev_is_premium', null, $blog_id );
657
658 if ( $is_first_non_ignored_blog ) {
659 $prev_is_premium = $site_prev_is_premium;
660
661 if ( is_null( $network_install_timestamp ) ) {
662 $install_timestamp = $blog_install_timestamp;
663 }
664
665 $is_first_non_ignored_blog = false;
666
667 continue;
668 }
669
670 if ( ! is_null( $prev_is_premium ) && $prev_is_premium !== $site_prev_is_premium ) {
671 // If a different `$site_prev_is_premium` value is found, do not include the option in the collection of options to update.
672 $prev_is_premium = null;
673 }
674
675 if ( $is_earlier_install ) {
676 // If an earlier install timestamp is found.
677 $install_timestamp = $blog_install_timestamp;
678 }
679 }
680
681 $installs_count = count( $blog_id_2_install_map );
682
683 if ( $sites_count === ( $installs_count + $skips_count ) ) {
684 if ( ! empty( $network_user_info ) ) {
685 $options_to_update['network_user_id'] = $network_user_info['user_id'];
686 $options_to_update['network_install_blog_id'] = $network_user_info['blog_id'];
687
688 foreach ( $blog_id_2_install_map as $blog_id => $install ) {
689 if ( $install->user_id == $network_user_info['user_id'] ) {
690 continue;
691 }
692
693 $this->_storage->store( 'is_delegated_connection', true, $blog_id );
694 }
695 }
696
697 if ( $sites_count === $skips_count ) {
698 /**
699 * Assume network-level skipping as the intended action if all actions identified were only
700 * skipping of the connection (i.e., no opt-ins and delegated connections so far).
701 */
702 $options_to_update['is_anonymous_ms'] = true;
703 } else if ( $sites_count === $installs_count ) {
704 /**
705 * Assume network-level opt-in as the intended action if all actions identified were only opt-ins
706 * (i.e., no delegation and skipping of the connections so far).
707 */
708 $options_to_update['is_network_connected'] = true;
709 }
710 }
711 }
712
713 if ( ! is_null( $install_timestamp ) ) {
714 $options_to_update['install_timestamp'] = $install_timestamp;
715 }
716
717 if ( ! is_null( $prev_is_premium ) ) {
718 $options_to_update['prev_is_premium'] = $prev_is_premium;
719 }
720
721 if ( ! empty( $options_to_update ) ) {
722 $this->adjust_storage( $options_to_update, $is_network_admin );
723 }
724 }
725
726 /**
727 * @author Leo Fajardo (@leorw)
728 * @since 2.3.0
729 *
730 * @param array $options
731 * @param bool $is_network_admin
732 */
733 private function adjust_storage( $options, $is_network_admin ) {
734 foreach ( $options as $name => $value ) {
735 $this->_storage->store( $name, $value, $is_network_admin ? true : null );
736 }
737 }
738
739 /**
740 * Checks whether this module has a settings menu.
741 *
742 * @author Leo Fajardo (@leorw)
743 * @since 1.2.2
744 *
745 * @return bool
746 */
747 function has_settings_menu() {
748 return ( $this->_is_network_active && fs_is_network_admin() ) ?
749 $this->_menu->has_network_menu() :
750 $this->_menu->has_menu();
751 }
752
753 /**
754 * If `true` the opt-in should be shown as a modal dialog box on the themes.php page. WordPress.org themes guidelines prohibit from redirecting the user from the themes.php page after activating a theme.
755 *
756 * @author Vova Feldman (@svovaf)
757 * @since 2.4.5
758 *
759 * @return bool
760 */
761 function show_opt_in_on_themes_page() {
762 if ( ! $this->is_free_wp_org_theme() ) {
763 return false;
764 }
765
766 if ( ! $this->has_settings_menu() ) {
767 return true;
768 }
769
770 return $this->show_settings_with_tabs();
771 }
772
773 /**
774 * If `true` the opt-in should be shown on the product's main setting page.
775 *
776 * @author Vova Feldman (@svovaf)
777 * @since 2.4.5
778 *
779 * @return bool
780 *
781 * @uses show_opt_in_on_themes_page();
782 */
783 function show_opt_in_on_setting_page() {
784 return ! $this->show_opt_in_on_themes_page();
785 }
786
787 /**
788 * If `true` the settings should be shown using tabs.
789 *
790 * @author Vova Feldman (@svovaf)
791 * @since 2.4.5
792 *
793 * @return bool
794 */
795 function show_settings_with_tabs() {
796 return ( self::NAVIGATION_TABS === $this->_navigation );
797 }
798
799 /**
800 * Check if the context module is free wp.org theme.
801 *
802 * This method is helpful because:
803 * 1. wp.org themes are limited to a single submenu item,
804 * and sub-submenu items are most likely not allowed (never verified).
805 * 2. wp.org themes are not allowed to redirect the user
806 * after the theme activation, therefore, the agreed UX
807 * is showing the opt-in as a modal dialog box after
808 * activation (approved by @otto42, @emiluzelac, @greenshady, @grapplerulrich).
809 *
810 * @author Vova Feldman (@svovaf)
811 * @since 1.2.2.7
812 *
813 * @return bool
814 */
815 function is_free_wp_org_theme() {
816 return (
817 $this->is_theme() &&
818 $this->is_org_repo_compliant() &&
819 ! $this->is_premium()
820 );
821 }
822
823 /**
824 * Checks whether this a submenu item is visible.
825 *
826 * @author Vova Feldman (@svovaf)
827 * @since 1.2.2.6
828 * @since 1.2.2.7 Even if the menu item was specified to be hidden, when it is the context page, then show the submenu item so the user will have the right context page.
829 *
830 * @param string $slug
831 * @param bool $is_tabs_visibility_check This is used to decide if the associated tab should be shown or hidden.
832 *
833 * @return bool
834 */
835 function is_submenu_item_visible( $slug, $is_tabs_visibility_check = false ) {
836 if ( $this->is_admin_page( $slug ) ) {
837 /**
838 * It is the current context page, so show the submenu item
839 * so the user will have the right context page, even if it
840 * was set to hidden.
841 */
842 return true;
843 }
844
845 if ( ! $this->has_settings_menu() ) {
846 // No menu settings at all.
847 return false;
848 }
849
850 if (
851 ! $is_tabs_visibility_check &&
852 $this->is_org_repo_compliant() &&
853 $this->show_settings_with_tabs()
854 ) {
855 /**
856 * wp.org themes are limited to a single submenu item, and
857 * sub-submenu items are most likely not allowed (never verified).
858 */
859 return false;
860 }
861
862 return $this->_menu->is_submenu_item_visible( $slug );
863 }
864
865 /**
866 * Check if a Freemius page should be accessible via the UI.
867 *
868 * @author Vova Feldman (@svovaf)
869 * @since 1.2.2.7
870 *
871 * @param string $slug
872 *
873 * @return bool
874 */
875 function is_page_visible( $slug ) {
876 if ( $this->is_admin_page( $slug ) ) {
877 return true;
878 }
879
880 return $this->_menu->is_submenu_item_visible( $slug, true, true );
881 }
882
883 /**
884 * @author Vova Feldman (@svovaf)
885 * @since 1.0.9
886 */
887 private function _version_updates_handler() {
888 if ( ! isset( $this->_storage->sdk_version ) || $this->_storage->sdk_version != $this->version ) {
889 // Freemius version upgrade mode.
890 $this->_storage->sdk_last_version = $this->_storage->sdk_version;
891 $this->_storage->sdk_version = $this->version;
892
893 if ( empty( $this->_storage->sdk_last_version ) ||
894 version_compare( $this->_storage->sdk_last_version, $this->version, '<' )
895 ) {
896 $this->_storage->sdk_upgrade_mode = true;
897 $this->_storage->sdk_downgrade_mode = false;
898 } else {
899 $this->_storage->sdk_downgrade_mode = true;
900 $this->_storage->sdk_upgrade_mode = false;
901
902 }
903
904 $this->do_action( 'sdk_version_update', $this->_storage->sdk_last_version, $this->version );
905 }
906
907 $plugin_version = $this->get_plugin_version();
908 if ( ! isset( $this->_storage->plugin_version ) || $this->_storage->plugin_version != $plugin_version ) {
909 // Plugin version upgrade mode.
910 $this->_storage->plugin_last_version = $this->_storage->plugin_version;
911 $this->_storage->plugin_version = $plugin_version;
912
913 if ( empty( $this->_storage->plugin_last_version ) ||
914 version_compare( $this->_storage->plugin_last_version, $plugin_version, '<' )
915 ) {
916 $this->_storage->plugin_upgrade_mode = true;
917 $this->_storage->plugin_downgrade_mode = false;
918 } else {
919 $this->_storage->plugin_downgrade_mode = true;
920 $this->_storage->plugin_upgrade_mode = false;
921 }
922
923 if ( ! empty( $this->_storage->plugin_last_version ) ) {
924 // Different version of the plugin was installed before, therefore it's an update.
925 $this->_storage->is_plugin_new_install = false;
926 }
927
928 $this->do_action( 'plugin_version_update', $this->_storage->plugin_last_version, $plugin_version );
929 }
930 }
931
932 #--------------------------------------------------------------------------------
933 #region Data Migration on SDK Update
934 #--------------------------------------------------------------------------------
935
936 /**
937 * @author Vova Feldman (@svovaf)
938 * @since 1.1.5
939 *
940 * @param string $sdk_prev_version
941 * @param string $sdk_version
942 */
943 function _sdk_version_update( $sdk_prev_version, $sdk_version ) {
944 if ( empty( $sdk_prev_version ) ) {
945 return;
946 }
947
948 if (
949 version_compare( $sdk_prev_version, '2.5.1', '<' ) &&
950 version_compare( $sdk_version, '2.5.1', '>=' )
951 ) {
952 if ( $this->is_registered( true ) ) {
953 /**
954 * Migrate to new permissions layer.
955 */
956 require_once WP_FS__DIR_INCLUDES . '/supplements/fs-migration-2.5.1.php';
957
958 $install_by_blog_id = is_multisite() ?
959 $this->get_blog_install_map() :
960 array( 0 => $this->_site );
961
962 fs_migrate_251( $this, $install_by_blog_id );
963 }
964 }
965 }
966
967 /**
968 * @author Leo Fajardo (@leorw)
969 * @since 2.0.0
970 *
971 * @param \FS_Storage $storage
972 * @param bool|int|null $blog_id
973 */
974 private static function migrate_install_plan_to_plan_id( FS_Storage $storage, $blog_id = null ) {
975 if ( empty( $storage->sdk_version ) ) {
976 // New installation of the plugin, no need to upgrade.
977 return;
978 }
979
980 if ( ! version_compare( $storage->sdk_version, '2.0.0', '<' ) ) {
981 // Previous version is >= 2.0.0, so no need to migrate.
982 return;
983 }
984
985 // Alias.
986 $module_type = $storage->get_module_type();
987 $module_slug = $storage->get_module_slug();
988
989 $installs = self::get_all_sites( $module_type, $blog_id );
990 $install = isset( $installs[ $module_slug ] ) ? $installs[ $module_slug ] : null;
991
992 if ( ! is_object( $install ) ) {
993 return;
994 }
995
996 if ( isset( $install->plan ) && is_object( $install->plan ) ) {
997 if ( isset( $install->plan->id ) && ! empty( $install->plan->id ) ) {
998 $install->plan_id = self::_decrypt( $install->plan->id );
999 }
1000
1001 unset( $install->plan );
1002
1003 $installs[ $module_slug ] = clone $install;
1004
1005 self::set_account_option_by_module(
1006 $module_type,
1007 'sites',
1008 $installs,
1009 true,
1010 $blog_id
1011 );
1012 }
1013 }
1014
1015 /**
1016 * @author Vova Feldman (@svovaf)
1017 * @since 1.2.2.7
1018 *
1019 * @param string $plugin_prev_version
1020 * @param string $plugin_version
1021 */
1022 function _after_version_update( $plugin_prev_version, $plugin_version ) {
1023 if ( $this->is_theme() ) {
1024 // Expire the cache of the previous tabs since the theme may
1025 // have setting updates.
1026 $this->_cache->expire( 'tabs' );
1027 $this->_cache->expire( 'tabs_stylesheets' );
1028 }
1029 }
1030
1031 /**
1032 * A special migration logic for the $_accounts, executed for all the plugins in the system:
1033 * - Moves some data to the network level storage.
1034 * - If the plugin's connection was skipped for all sites, set the plugin as if it was network skipped.
1035 * - If the plugin's connection was ignored for all sites, don't do anything in terms of the network connection.
1036 * - If the plugin was connected to all sites by the same super-admin, set the plugin as if was network opted-in for all sites.
1037 * - If there's at least one site that was connected by a super-admin, find the "main super-admin" (the one that installed the majority of the plugin installs) and set the plugin as if was network activated with the main super-admin, set all the sites that were skipped or opted-in with a different user to delegated mode. Then, prompt the currently logged super-admin to choose what to do with the ignored sites.
1038 * - If there are any sites in the network which the connection decision was not yet taken for, set this plugin into network activation mode so a super-admin can choose what to do with the rest of the sites.
1039 *
1040 * @author Vova Feldman (@svovaf)
1041 * @since 2.0.0
1042 */
1043 private static function migrate_accounts_to_network() {
1044 $sites = self::get_sites();
1045 $sites_count = count( $sites );
1046 $connection_status = array();
1047 $plugin_slugs = array();
1048 foreach ( $sites as $site ) {
1049 $blog_id = self::get_site_blog_id( $site );
1050
1051 self::$_accounts->migrate_to_network( $blog_id );
1052
1053 /**
1054 * Build a list of all Freemius powered plugins slugs.
1055 */
1056 $id_slug_type_path_map = self::$_accounts->get_option( 'id_slug_type_path_map', array(), $blog_id );
1057 foreach ( $id_slug_type_path_map as $module_id => $data ) {
1058 if ( WP_FS__MODULE_TYPE_PLUGIN === $data['type'] ) {
1059 $plugin_slugs[ $data['slug'] ] = true;
1060 }
1061 }
1062
1063 $installs = self::get_account_option( 'sites', WP_FS__MODULE_TYPE_PLUGIN, $blog_id );
1064
1065 if ( is_array( $installs ) ) {
1066 foreach ( $installs as $slug => $install ) {
1067 if ( ! isset( $connection_status[ $slug ] ) ) {
1068 $connection_status[ $slug ] = array();
1069 }
1070
1071 if ( is_object( $install ) &&
1072 FS_Site::is_valid_id( $install->id ) &&
1073 FS_User::is_valid_id( $install->user_id )
1074 ) {
1075 $connection_status[ $slug ][ $blog_id ] = $install->user_id;
1076 }
1077 }
1078 }
1079 }
1080
1081 foreach ( $plugin_slugs as $slug => $true ) {
1082 if ( ! isset( $connection_status[ $slug ] ) ) {
1083 $connection_status[ $slug ] = array();
1084 }
1085
1086 foreach ( $sites as $site ) {
1087 $blog_id = self::get_site_blog_id( $site );
1088
1089 if ( isset( $connection_status[ $slug ][ $blog_id ] ) ) {
1090 continue;
1091 }
1092
1093 $storage = FS_Storage::instance( WP_FS__MODULE_TYPE_PLUGIN, $slug );
1094
1095 $is_anonymous = $storage->get( 'is_anonymous', null, $blog_id );
1096
1097 if ( ! is_null( $is_anonymous ) ) {
1098 // Since 1.1.3 is_anonymous is an array.
1099 if ( is_array( $is_anonymous ) && isset( $is_anonymous['is'] ) ) {
1100 $is_anonymous = $is_anonymous['is'];
1101 }
1102
1103 if ( is_bool( $is_anonymous ) && true === $is_anonymous ) {
1104 $connection_status[ $slug ][ $blog_id ] = 'skipped';
1105 }
1106 }
1107
1108 if ( ! isset( $connection_status[ $slug ][ $blog_id ] ) ) {
1109 $connection_status[ $slug ][ $blog_id ] = 'ignored';
1110 }
1111 }
1112 }
1113
1114 $super_admins = array();
1115
1116 foreach ( $connection_status as $slug => $blogs_status ) {
1117 $skips = 0;
1118 $ignores = 0;
1119 $connections = 0;
1120 $opted_in_users = array();
1121 $opted_in_super_admins = array();
1122
1123 $storage = FS_Storage::instance( WP_FS__MODULE_TYPE_PLUGIN, $slug );
1124
1125 foreach ( $blogs_status as $blog_id => $status_or_user_id ) {
1126 if ( 'skipped' === $status_or_user_id ) {
1127 $skips ++;
1128 } else if ( 'ignored' === $status_or_user_id ) {
1129 $ignores ++;
1130 } else if ( FS_User::is_valid_id( $status_or_user_id ) ) {
1131 $connections ++;
1132
1133 if ( ! isset( $opted_in_users[ $status_or_user_id ] ) ) {
1134 $opted_in_users[ $status_or_user_id ] = array();
1135 }
1136
1137 $opted_in_users[ $status_or_user_id ][] = $blog_id;
1138
1139 if ( isset( $super_admins[ $status_or_user_id ] ) ||
1140 self::is_super_admin( $status_or_user_id )
1141 ) {
1142 // Cache super-admin data.
1143 $super_admins[ $status_or_user_id ] = true;
1144
1145 // Remember opted-in super-admins for the plugin.
1146 $opted_in_super_admins[ $status_or_user_id ] = true;
1147 }
1148 }
1149 }
1150
1151 $main_super_admin_user_id = null;
1152 $all_migrated = false;
1153 if ( $sites_count == $skips ) {
1154 // All sites were skipped -> network skip by copying the anonymous mode from any of the sites.
1155 $storage->is_anonymous_ms = $storage->is_anonymous;
1156
1157 $all_migrated = true;
1158 } else if ( $sites_count == $ignores ) {
1159 // Don't do anything, still in activation mode.
1160
1161 $all_migrated = true;
1162 } else if ( 0 < count( $opted_in_super_admins ) ) {
1163 // Find the super-admin with the majority of installs.
1164 $max_installs_by_super_admin = 0;
1165 foreach ( $opted_in_super_admins as $user_id => $true ) {
1166 $installs_count = count( $opted_in_users[ $user_id ] );
1167
1168 if ( $installs_count > $max_installs_by_super_admin ) {
1169 $max_installs_by_super_admin = $installs_count;
1170 $main_super_admin_user_id = $user_id;
1171 }
1172 }
1173
1174 if ( $sites_count == $connections && 1 == count( $opted_in_super_admins ) ) {
1175 // Super-admin opted-in for all sites in the network.
1176 $storage->is_network_connected = true;
1177
1178 $all_migrated = true;
1179 }
1180
1181 // Store network user.
1182 $storage->network_user_id = $main_super_admin_user_id;
1183
1184 $storage->network_install_blog_id = ( $sites_count == $connections ) ?
1185 // Since all sites are opted-in, associating with the main site.
1186 get_current_blog_id() :
1187 // Associating with the 1st found opted-in site.
1188 $opted_in_users[ $main_super_admin_user_id ][0];
1189
1190 /**
1191 * Make sure we migrate the plan ID of the network install, otherwise, if after the migration
1192 * the 1st page that will be loaded is the network level WP Admin and $storage->network_install_blog_id
1193 * is different than the main site of the network, the $this->_site will not be set since the plan_id
1194 * will be empty.
1195 */
1196 $storage->migrate_to_network();
1197 self::migrate_install_plan_to_plan_id( $storage, $storage->network_install_blog_id );
1198 } else {
1199 // At least one opt-in. All the opt-in were created by a non-super-admin.
1200 if ( 0 == $ignores ) {
1201 // All sites were opted-in or skipped, all by non-super-admin. So delegate all.
1202 $storage->store( 'is_delegated_connection', true, true );
1203
1204 $all_migrated = true;
1205 }
1206 }
1207
1208 if ( ! $all_migrated ) {
1209 /**
1210 * Delegate all sites that were:
1211 * 1) Opted-in by a user that is NOT the main-super-admin.
1212 * 2) Skipped and non of the sites was opted-in by a super-admin. If any site was opted-in by a super-admin, there will be a main-super-admin, and we consider the skip as if it was done by that user.
1213 */
1214 foreach ( $blogs_status as $blog_id => $status_or_user_id ) {
1215 if ( $status_or_user_id == $main_super_admin_user_id ) {
1216 continue;
1217 }
1218
1219 if ( FS_User::is_valid_id( $status_or_user_id ) ||
1220 ( 'skipped' === $status_or_user_id && is_null( $main_super_admin_user_id ) )
1221 ) {
1222 $storage->store( 'is_delegated_connection', true, $blog_id );
1223 }
1224 }
1225 }
1226
1227
1228 if ( ( $connections + $skips > 0 ) ) {
1229 if ( $ignores > 0 ) {
1230 /**
1231 * If admin already opted-in or skipped in any of the network sites, and also
1232 * have sites which the connection decision was not yet taken, set this plugin
1233 * into network activation mode so the super-admin can choose what to do with
1234 * the rest of the sites.
1235 */
1236 self::set_network_upgrade_mode( $storage );
1237 }
1238 }
1239 }
1240 }
1241
1242 /**
1243 * Set a module into network upgrade mode.
1244 *
1245 * @author Vova Feldman (@svovaf)
1246 * @since 2.0.0
1247 *
1248 * @param \FS_Storage $storage
1249 *
1250 * @return bool
1251 */
1252 private static function set_network_upgrade_mode( FS_Storage $storage ) {
1253 return $storage->is_network_activation = true;
1254 }
1255
1256 /**
1257 * Will return true after upgrading to the SDK with the network level integration,
1258 * when the super-admin involvement is required regarding the rest of the sites.
1259 *
1260 * @author Vova Feldman (@svovaf)
1261 * @since 2.0.0
1262 *
1263 * @return bool
1264 */
1265 function is_network_upgrade_mode() {
1266 return $this->_storage->get( 'is_network_activation' );
1267 }
1268
1269 /**
1270 * Clear flag after the upgrade mode completion.
1271 *
1272 * @author Vova Feldman (@svovaf)
1273 * @since 2.0.0
1274 *
1275 * @return bool True if network activation was on and now completed.
1276 */
1277 private function network_upgrade_mode_completed() {
1278 if ( fs_is_network_admin() && $this->is_network_upgrade_mode() ) {
1279 $this->_storage->remove( 'is_network_activation' );
1280
1281 return true;
1282 }
1283
1284 return false;
1285 }
1286
1287 #endregion
1288
1289 /**
1290 * This action is connected to the 'plugins_loaded' hook and helps to determine
1291 * if this is a new plugin installation or a plugin update.
1292 *
1293 * There are 3 different use-cases:
1294 * 1) New plugin installation right with Freemius:
1295 * 1.1 _activate_plugin_event_hook() will be executed first
1296 * 1.2 Since $this->_storage->is_plugin_new_install is not set,
1297 * and $this->_storage->plugin_last_version is not set,
1298 * $this->_storage->is_plugin_new_install will be set to TRUE.
1299 * 1.3 When _plugins_loaded() will be executed, $this->_storage->is_plugin_new_install will
1300 * be already set to TRUE.
1301 *
1302 * 2) Plugin update, didn't have Freemius before, and now have the SDK:
1303 * 2.1 _activate_plugin_event_hook() will not be executed, because
1304 * the activation hook do NOT fires on updates since WP 3.1.
1305 * 2.2 When _plugins_loaded() will be executed, $this->_storage->is_plugin_new_install will
1306 * be empty, therefore, it will be set to FALSE.
1307 *
1308 * 3) Plugin update, had Freemius in prev version as well:
1309 * 3.1 _version_updates_handler() will be executed 1st, since FS was installed
1310 * before, $this->_storage->plugin_last_version will NOT be empty,
1311 * therefore, $this->_storage->is_plugin_new_install will be set to FALSE.
1312 * 3.2 When _plugins_loaded() will be executed, $this->_storage->is_plugin_new_install is
1313 * already set, therefore, it will not be modified.
1314 *
1315 * Use-case #3 is backward compatible, #3.1 will be executed since 1.0.9.
1316 *
1317 * NOTE:
1318 * The only fallback of this mechanism is if an admin updates a plugin based on use-case #2,
1319 * and then, the next immediate PageView is the plugin's main settings page, it will not
1320 * show the opt-in right away. The reason it will happen is because Freemius execution
1321 * will be turned off till the plugin is fully loaded at least once
1322 * (till $this->_storage->was_plugin_loaded is TRUE).
1323 *
1324 * @author Vova Feldman (@svovaf)
1325 * @since 1.1.9
1326 *
1327 */
1328 function _plugins_loaded() {
1329 // Update flag that plugin was loaded with Freemius at least once.
1330 $this->_storage->was_plugin_loaded = true;
1331
1332 /**
1333 * Bug fix - only set to false when it's a plugin, due to the
1334 * execution sequence of the theme hooks and our methods, if
1335 * this will be set for themes, Freemius will always assume
1336 * it's a theme update.
1337 *
1338 * @author Vova Feldman (@svovaf)
1339 * @since 1.2.2.2
1340 */
1341 if ( $this->is_plugin() &&
1342 ! isset( $this->_storage->is_plugin_new_install )
1343 ) {
1344 $this->_storage->is_plugin_new_install = (
1345 ! is_plugin_active( $this->_plugin_basename ) &&
1346 empty( $this->_storage->plugin_last_version )
1347 );
1348 }
1349 }
1350
1351 /**
1352 * Opens the support forum subemenu item in a new browser page.
1353 *
1354 * @author Vova Feldman (@svovaf)
1355 * @since 2.1.4
1356 */
1357 static function _open_support_forum_in_new_page() {
1358 ?>
1359 <script type="text/javascript">
1360 (function ($) {
1361 $('.fs-submenu-item.wp-support-forum').parent().attr( { target: '_blank', rel: 'noopener noreferrer' } );
1362 })(jQuery);
1363 </script>
1364 <?php
1365 }
1366
1367 /**
1368 * @author Vova Feldman (@svovaf)
1369 * @since 1.0.9
1370 */
1371 private function register_constructor_hooks() {
1372 $this->_logger->entrance();
1373
1374 if ( is_admin() ) {
1375 add_action( 'admin_init', array( &$this, '_hook_action_links_and_register_account_hooks' ) );
1376
1377 if ( $this->is_plugin() ) {
1378 if ( self::is_plugin_install_page() && true !== fs_request_get_bool( 'fs_allow_updater_and_dialog' ) ) {
1379 /**
1380 * Unless the `fs_allow_updater_and_dialog` URL param exists and its value is `true`, make
1381 * Freemius-related updates unavailable on the "Add Plugins" admin page (/plugin-install.php)
1382 * so that they won't interfere with the .org plugins' functionalities on that page (e.g.
1383 * updating of a .org plugin).
1384 */
1385 add_filter( 'site_transient_update_plugins', array( 'Freemius', '_remove_fs_updates_from_plugin_install_page' ), 10, 2 );
1386 } else if ( self::is_plugins_page() || self::is_updates_page() ) {
1387 /**
1388 * On the "Plugins" and "Updates" admin pages, if there are premium or non–org-compliant plugins, modify their details dialog URLs (add a Freemius-specific param) so that the SDK can determine if the plugin information dialog should show information from Freemius.
1389 *
1390 * @author Leo Fajardo (@leorw)
1391 * @since 2.2.3
1392 */
1393 add_action( 'admin_footer', array( 'Freemius', '_prepend_fs_allow_updater_and_dialog_flag_url_param' ) );
1394 }
1395
1396 $plugin_dir = dirname( $this->_plugin_dir_path ) . '/';
1397
1398 /**
1399 * @since 1.2.2
1400 *
1401 * Hook to both free and premium version activations to support
1402 * auto deactivation on the other version activation.
1403 */
1404 register_activation_hook(
1405 $plugin_dir . $this->_free_plugin_basename,
1406 array( &$this, '_activate_plugin_event_hook' )
1407 );
1408
1409 register_activation_hook(
1410 $plugin_dir . $this->premium_plugin_basename(),
1411 array( &$this, '_activate_plugin_event_hook' )
1412 );
1413 } else {
1414 add_action( 'after_switch_theme', array( &$this, '_activate_theme_event_hook' ), 10, 2 );
1415
1416 add_action( 'admin_footer', array( &$this, '_style_premium_theme' ) );
1417 }
1418
1419 /**
1420 * Part of the mechanism to identify new plugin install vs. plugin update.
1421 *
1422 * @author Vova Feldman (@svovaf)
1423 * @since 1.1.9
1424 */
1425 if ( empty( $this->_storage->was_plugin_loaded ) ) {
1426 /**
1427 * During the plugin activation (not theme), 'plugins_loaded' will be already executed
1428 * when the logic gets here since the activation logic first add the activate plugins,
1429 * then triggers 'plugins_loaded', and only then include the code of the plugin that
1430 * is activated. Which means that _plugins_loaded() will NOT be executed during the
1431 * plugin activation, and that IS intentional.
1432 *
1433 * @author Vova Feldman (@svovaf)
1434 */
1435 if ( $this->is_plugin() &&
1436 $this->is_activation_mode( false ) &&
1437 0 == did_action( 'plugins_loaded' )
1438 ) {
1439 add_action( 'plugins_loaded', array( &$this, '_plugins_loaded' ) );
1440 } else {
1441 // If was activated before, then it was already loaded before.
1442 $this->_plugins_loaded();
1443 }
1444 }
1445
1446 if ( ! self::is_ajax() ) {
1447 if ( ! $this->is_addon() ) {
1448 add_action( 'init', array( &$this, '_add_default_submenu_items' ), WP_FS__LOWEST_PRIORITY );
1449 }
1450 }
1451
1452 if ( $this->_storage->handle_gdpr_admin_notice ) {
1453 add_action( 'init', array( &$this, '_maybe_show_gdpr_admin_notice' ) );
1454 }
1455
1456 add_action( 'init', array( &$this, '_maybe_add_gdpr_optin_ajax_handler') );
1457 add_action( 'init', array( &$this, '_maybe_add_pricing_ajax_handler' ) );
1458 }
1459
1460 if ( $this->is_plugin() ) {
1461 if ( version_compare( $GLOBALS['wp_version'], '5.1', '<' ) ) {
1462 add_action( 'wpmu_new_blog', array( $this, '_after_new_blog_callback' ), 10, 6 );
1463 } else {
1464 add_action( 'wp_initialize_site', array( $this, '_after_wp_initialize_site_callback' ), 11, 2 );
1465 }
1466
1467 register_deactivation_hook( $this->_plugin_main_file_path, array( &$this, '_deactivate_plugin_hook' ) );
1468 }
1469
1470 if ( is_multisite() ) {
1471 add_action( 'deactivate_blog', array( &$this, '_after_site_deactivated_callback' ) );
1472 add_action( 'archive_blog', array( &$this, '_after_site_deactivated_callback' ) );
1473 add_action( 'make_spam_blog', array( &$this, '_after_site_deactivated_callback' ) );
1474
1475 if ( version_compare( $GLOBALS['wp_version'], '5.1', '<' ) ) {
1476 add_action( 'deleted_blog', array( $this, '_after_site_deleted_callback' ), 10, 2 );
1477 } else {
1478 add_action( 'wp_delete_site', array( $this, '_after_wpsite_deleted_callback' ) );
1479 }
1480
1481 add_action( 'activate_blog', array( &$this, '_after_site_reactivated_callback' ) );
1482 add_action( 'unarchive_blog', array( &$this, '_after_site_reactivated_callback' ) );
1483 add_action( 'make_ham_blog', array( &$this, '_after_site_reactivated_callback' ) );
1484 }
1485
1486 if ( $this->is_theme() &&
1487 self::is_customizer() &&
1488 $this->apply_filters( 'show_customizer_upsell', true )
1489 ) {
1490 // Register customizer upsell.
1491 add_action( 'customize_register', array( &$this, '_customizer_register' ) );
1492 }
1493
1494 add_action( 'admin_init', array( &$this, '_redirect_on_clicked_menu_link' ), WP_FS__LOWEST_PRIORITY );
1495
1496 if ( $this->is_theme() && ! $this->is_migration() ) {
1497 add_action( 'admin_init', array( &$this, '_add_tracking_links' ) );
1498 }
1499
1500 add_action( 'admin_init', array( &$this, '_add_license_activation' ) );
1501 add_action( 'admin_init', array( &$this, '_add_premium_version_upgrade_selection' ) );
1502 add_action( 'admin_init', array( &$this, '_add_beta_mode_update_handler' ) );
1503 add_action( 'admin_init', array( &$this, '_add_user_change_option' ) );
1504 add_action( 'admin_init', array( &$this, '_add_email_address_update_option' ) );
1505
1506 $this->add_ajax_action( 'update_billing', array( &$this, '_update_billing_ajax_action' ) );
1507 $this->add_ajax_action( 'start_trial', array( &$this, '_start_trial_ajax_action' ) );
1508 $this->add_ajax_action( 'set_data_debug_mode', array( &$this, '_set_data_debug_mode' ) );
1509 $this->add_ajax_action( 'toggle_whitelabel_mode', array( &$this, '_toggle_whitelabel_mode_ajax_handler' ) );
1510
1511 if ( $this->_is_network_active && fs_is_network_admin() ) {
1512 $this->add_ajax_action( 'network_activate', array( &$this, '_network_activate_ajax_action' ) );
1513 }
1514
1515 $this->add_ajax_action( 'install_premium_version', array(
1516 &$this,
1517 '_install_premium_version_ajax_action'
1518 ) );
1519
1520 $this->add_ajax_action( 'submit_affiliate_application', array( &$this, '_submit_affiliate_application' ) );
1521
1522 $this->add_action( 'after_plans_sync', array( &$this, '_check_for_trial_plans' ) );
1523
1524 $this->add_action( 'sdk_version_update', array( &$this, '_sdk_version_update' ), WP_FS__DEFAULT_PRIORITY, 2 );
1525
1526 $this->add_action(
1527 'plugin_version_update',
1528 array( &$this, '_after_version_update' ),
1529 WP_FS__DEFAULT_PRIORITY,
1530 2
1531 );
1532 $this->add_filter( 'after_code_type_change', array( &$this, '_after_code_type_change' ) );
1533
1534 add_action( 'admin_init', array( &$this, '_add_trial_notice' ) );
1535 add_action( 'admin_init', array( &$this, '_add_affiliate_program_notice' ) );
1536 add_action( 'admin_enqueue_scripts', array( &$this, '_enqueue_common_css' ) );
1537
1538 /**
1539 * Handle request to reset anonymous mode for `get_reconnect_url()` or reset the pending activation mode.
1540 *
1541 * @author Vova Feldman (@svovaf)
1542 * @since 1.2.1.5
1543 */
1544 if (
1545 (
1546 fs_request_is_action( 'reset_anonymous_mode' ) ||
1547 fs_request_is_action( 'reset_pending_activation_mode' )
1548 ) &&
1549 $this->get_unique_affix() === fs_request_get( 'fs_unique_affix' )
1550 ) {
1551 add_action( 'admin_init', array( &$this, 'connect_again' ) );
1552 }
1553 }
1554
1555 /**
1556 * Register the required hooks right after the settings parse is completed.
1557 *
1558 * @author Vova Feldman (@svovaf)
1559 * @since 2.3.1
1560 */
1561 private function register_after_settings_parse_hooks() {
1562 if ( is_admin() &&
1563 $this->is_theme() &&
1564 $this->is_premium() &&
1565 ! $this->has_active_valid_license()
1566 ) {
1567 $this->add_ajax_action(
1568 'delete_theme_update_data',
1569 array( &$this, '_delete_theme_update_data_action' )
1570 );
1571 }
1572
1573 if ( $this->show_settings_with_tabs() ) {
1574 /**
1575 * Include the required hooks to capture the theme settings' page tabs
1576 * and cache them.
1577 *
1578 * @author Vova Feldman (@svovaf)
1579 * @since 1.2.2.7
1580 */
1581 if ( ! $this->_cache->has_valid( 'tabs' ) ) {
1582 add_action( 'admin_footer', array( &$this, '_tabs_capture' ) );
1583 // Add license activation AJAX callback.
1584 $this->add_ajax_action( 'store_tabs', array( &$this, '_store_tabs_ajax_action' ) );
1585
1586 add_action( 'admin_enqueue_scripts', array( &$this, '_store_tabs_styles' ), 9999999 );
1587 }
1588
1589 add_action(
1590 'admin_footer',
1591 array( &$this, '_add_freemius_tabs' ),
1592 /**
1593 * The tabs JS code must be executed after the tabs capture logic (_tabs_capture()).
1594 * That's why the priority is 11 while the tabs capture logic is added
1595 * with priority 10.
1596 *
1597 * @author Vova Feldman (@svovaf)
1598 */
1599 11
1600 );
1601 }
1602
1603 if ( ! self::is_ajax() ) {
1604 if ( ! $this->is_addon() || $this->is_only_premium() ) {
1605 add_action(
1606 ( $this->_is_network_active && fs_is_network_admin() ? 'network_' : '' ) . 'admin_menu',
1607 array( &$this, '_prepare_admin_menu' ),
1608 WP_FS__LOWEST_PRIORITY
1609 );
1610 }
1611 }
1612 }
1613
1614 /**
1615 * Makes Freemius-related updates unavailable on the "Add Plugins" admin page (/plugin-install.php) so that
1616 * they won't interfere with the .org plugins' functionalities on that page (e.g. updating of a .org plugin).
1617 *
1618 * @author Leo Fajardo (@leorw)
1619 * @since 2.2.3
1620 *
1621 * @param object $updates
1622 * @param string|null $transient
1623 *
1624 * @return object
1625 */
1626 static function _remove_fs_updates_from_plugin_install_page( $updates, $transient = null ) {
1627 if ( is_object( $updates ) && isset( $updates->response ) ) {
1628 foreach ( $updates->response as $file => $plugin ) {
1629 if ( isset( $plugin->package ) && false !== strpos( $plugin->package, 'api.freemius' ) ) {
1630 unset( $updates->response[ $file ] );
1631 }
1632 }
1633 }
1634
1635 return $updates;
1636 }
1637
1638 /**
1639 * Prepends the `fs_allow_updater_and_dialog` param to the plugin information URLs to tell the SDK to handle
1640 * the information that is shown on the plugin details dialog that is shown when the relevant link is clicked.
1641 *
1642 * @author Leo Fajardo (@leorw)
1643 * @since 2.2.3
1644 *
1645 * @return string
1646 */
1647 static function _prepend_fs_allow_updater_and_dialog_flag_url_param() {
1648 $slug_basename_map = array();
1649 foreach ( self::$_instances as $instance ) {
1650 if ( ! $instance->is_plugin() ) {
1651 continue;
1652 }
1653
1654 $slug_basename_map[ $instance->get_slug() ] = $instance->premium_plugin_basename();
1655 }
1656 ?>
1657 <script type="text/javascript">
1658 (function( $ ) {
1659 var slugBasenameMap = <?php echo json_encode( $slug_basename_map ) ?>;
1660 for ( var slug in slugBasenameMap ) {
1661 var basename = slugBasenameMap[ slug ];
1662
1663 // Try to get the plugin rows if on the "Plugins" page.
1664 var $pluginRows = $( '.wp-list-table.plugins tr[data-plugin="' + basename + '"]');
1665
1666 if ( 0 === $pluginRows.length ) {
1667 // Try to get the plugin rows if on the "Updates" page.
1668 var $pluginCheckbox = $( '#update-plugins-table input[type="checkbox"][value="' + basename + '"]' );
1669 if ( 0 !== $pluginCheckbox.length ) {
1670 $pluginRows = $pluginCheckbox.parents( 'tr:first' );
1671 }
1672 }
1673
1674 if ( 0 === $pluginRows.length ) {
1675 // No plugin rows found.
1676 continue;
1677 }
1678
1679 // Find the "View details" links and add the `fs_allow_updater_and_dialog` param to the URL.
1680 $pluginRows.find( 'a[href*="plugin-install.php?tab=plugin-information"]' ).each(function() {
1681 var $this = $( this ),
1682 href = $this.attr( 'href' ).replace( '?tab=', '?fs_allow_updater_and_dialog=true&tab=');
1683
1684 $this.attr( 'href', href );
1685 });
1686 }
1687 })( jQuery );
1688 </script>
1689 <?php
1690 }
1691
1692 /**
1693 * @author Leo Fajardo (@leorw)
1694 * @since 2.3.0
1695 */
1696 static function _maybe_add_beta_label_styles() {
1697 $has_any_beta_version = false;
1698
1699 foreach ( self::$_instances as $instance ) {
1700 if ( $instance->is_beta() ) {
1701 $has_any_beta_version = true;
1702 break;
1703 }
1704 }
1705
1706 if ( $has_any_beta_version ) {
1707 fs_enqueue_local_style( 'fs_plugins', '/admin/plugins.css' );
1708 }
1709 }
1710
1711 /**
1712 * @author Leo Fajardo (@leorw)
1713 * @since 2.3.0
1714 */
1715 static function _maybe_add_beta_label_to_plugins_and_handle_confirmation() {
1716 $beta_data = array();
1717
1718 foreach ( self::$_instances as $instance ) {
1719 if ( ! $instance->is_premium() ) {
1720 continue;
1721 }
1722
1723 /**
1724 * If there's an available beta version update, a confirmation message will be shown when the
1725 * "Update now" link on the "Plugins" or "Themes" page is clicked.
1726 */
1727 $has_beta_update = $instance->has_beta_update();
1728
1729 $is_beta = (
1730 // The "Beta" label is added separately for themes.
1731 $instance->is_plugin() &&
1732 $instance->is_beta()
1733 );
1734
1735 if ( ! $is_beta && ! $has_beta_update ) {
1736 continue;
1737 }
1738
1739 $beta_data[ $instance->get_plugin_basename() ] = array( 'is_installed_version_beta' => $is_beta );
1740
1741 if ( ! $has_beta_update ) {
1742 continue;
1743 }
1744
1745 $beta_data[ $instance->get_plugin_basename() ]['beta_version_update_confirmation_message'] = sprintf(
1746 '%s %s',
1747 sprintf(
1748 fs_esc_attr_inline(
1749 'An update to a Beta version will replace your installed version of %s with the latest Beta release - use with caution, and not on production sites. You have been warned.',
1750 'beta-version-update-caution',
1751 $instance->get_slug()
1752 ),
1753 $instance->get_plugin_title()
1754 ),
1755 fs_esc_attr_inline( 'Would you like to proceed with the update?', 'update-confirmation', $instance->get_slug() )
1756 );
1757 }
1758
1759 if ( empty( $beta_data ) ) {
1760 return;
1761 }
1762 ?>
1763 <script type="text/javascript">
1764 ( function( $ ) {
1765 var betaData = <?php echo json_encode( $beta_data ) ?>;
1766
1767 for ( var pluginBasename in betaData ) {
1768 if ( ! betaData.hasOwnProperty( pluginBasename ) ) {
1769 continue;
1770 }
1771
1772 if ( ! betaData[ pluginBasename ].is_installed_version_beta ) {
1773 continue;
1774 }
1775
1776 var $parentContainer = $( '.wp-list-table.plugins tr[data-plugin="' + pluginBasename + '"]' );
1777 if ( 0 === $parentContainer.length ) {
1778 continue;
1779 }
1780
1781 $parentContainer.find( '.plugin-title > strong:first-child').append(
1782 '<span class="fs-tag fs-info"><?php fs_esc_js_echo_inline( 'Beta', 'beta' ) ?></span>'
1783 );
1784 }
1785
1786 setTimeout( function() {
1787 // Wait a little bit before adding the event handler, otherwise, it will be overridden by the core WP logic.
1788 $( '.plugins .update-message .update-link, .themes .theme .update-message' ).on( 'click', function() {
1789 var $parentContainer = $( this ).parents( 'tr:first' );
1790 pluginBasename = ( 0 !== $parentContainer.length ) ?
1791 $parentContainer.data( 'plugin' ) :
1792 $( this ).parents( '.theme:first' ).data( 'slug' );
1793
1794 if (
1795 betaData[ pluginBasename ] &&
1796 betaData[ pluginBasename ].beta_version_update_confirmation_message &&
1797 ! confirm( betaData[ pluginBasename ].beta_version_update_confirmation_message )
1798 ) {
1799 return false;
1800 }
1801 } );
1802 }, 20 );
1803 } )( jQuery );
1804 </script>
1805 <?php
1806 }
1807
1808 /**
1809 * Keeping the uninstall hook registered for free or premium plugin version may result to a fatal error that
1810 * could happen when a user tries to uninstall either version while one of them is still active. Uninstalling a
1811 * plugin will trigger inclusion of the free or premium version and if one of them is active during the
1812 * uninstallation, a fatal error may occur in case the plugin's class or functions are already defined.
1813 *
1814 * @author Leo Fajardo (@leorw)
1815 *
1816 * @since 1.2.0
1817 */
1818 private function unregister_uninstall_hook() {
1819 $uninstallable_plugins = (array) get_option( 'uninstall_plugins' );
1820 unset( $uninstallable_plugins[ $this->_free_plugin_basename ] );
1821 unset( $uninstallable_plugins[ $this->premium_plugin_basename() ] );
1822
1823 update_option( 'uninstall_plugins', $uninstallable_plugins );
1824 }
1825
1826 /**
1827 * @since 1.2.0 Invalidate module's main file cache, otherwise, FS_Plugin_Updater will not fetch updates.
1828 *
1829 * @param bool $store_prev_path
1830 */
1831 private function clear_module_main_file_cache( $store_prev_path = true ) {
1832 if ( ! isset( $this->_storage->plugin_main_file ) ||
1833 empty( $this->_storage->plugin_main_file->path )
1834 ) {
1835 return;
1836 }
1837
1838 if ( ! $store_prev_path ) {
1839 /**
1840 * Storing the previous path is not needed when clearing the cache after an SDK version update since
1841 * the main purpose of the cache clearing in that event is to correct a wrong plugin main file path
1842 * which causes data mix-up between plugins (e.g. titles and versions of an add-on and its parent plugin).
1843 *
1844 * @author Leo Fajardo (@leorw)
1845 * @since 2.2.1
1846 */
1847 unset( $this->_storage->plugin_main_file->path );
1848 } else {
1849 $plugin_main_file = clone $this->_storage->plugin_main_file;
1850
1851 // Store cached path (2nd layer cache).
1852 $plugin_main_file->prev_path = $plugin_main_file->path;
1853
1854 // Clear cached path.
1855 unset( $plugin_main_file->path );
1856
1857 $this->_storage->plugin_main_file = $plugin_main_file;
1858 }
1859
1860 /**
1861 * Clear global cached path.
1862 *
1863 * @author Leo Fajardo (@leorw)
1864 * @since 1.2.2
1865 */
1866 $id_slug_type_path_map = self::$_accounts->get_option( 'id_slug_type_path_map' );
1867 unset( $id_slug_type_path_map[ $this->_module_id ]['path'] );
1868 self::$_accounts->set_option( 'id_slug_type_path_map', $id_slug_type_path_map, true );
1869 }
1870
1871 /**
1872 * @author Leo Fajardo (@leorw)
1873 * @since 2.0.0
1874 */
1875 function _hook_action_links_and_register_account_hooks() {
1876 if ( $this->is_migration() ) {
1877 return;
1878 }
1879
1880 if (
1881 ( self::is_plugins_page() && $this->is_plugin() ) ||
1882 ( self::is_themes_page() && $this->is_theme() ) ||
1883 fs_request_is_action_secure( $this->get_unique_affix() . '_reconnect' )
1884 ) {
1885 $this->_add_tracking_links();
1886 }
1887
1888 if ( self::is_plugins_page() && $this->is_plugin() ) {
1889 $this->hook_plugin_action_links();
1890 }
1891
1892 $this->_register_account_hooks();
1893 }
1894
1895 /**
1896 * @author Vova Feldman (@svovaf)
1897 * @since 1.0.9
1898 */
1899 private function _register_account_hooks() {
1900 if ( ! is_admin() ) {
1901 return;
1902 }
1903
1904 /**
1905 * Always show the deactivation feedback form since we added
1906 * automatic free version deactivation upon premium code activation.
1907 *
1908 * @since 1.2.1.6
1909 */
1910 $this->add_ajax_action(
1911 'submit_uninstall_reason',
1912 array( &$this, '_submit_uninstall_reason_action' )
1913 );
1914
1915 $this->add_ajax_action(
1916 'cancel_subscription_or_trial',
1917 array( &$this, 'cancel_subscription_or_trial_ajax_action' )
1918 );
1919
1920 if ( ! $this->is_addon() || $this->is_parent_plugin_installed() ) {
1921 if ( ( $this->is_plugin() && self::is_plugins_page() ) ||
1922 ( $this->is_theme() && self::is_themes_page() )
1923 ) {
1924 add_action( 'admin_footer', array( &$this, '_add_deactivation_feedback_dialog_box' ) );
1925 }
1926 }
1927 }
1928
1929 /**
1930 * Leverage backtrace to find caller plugin file path.
1931 *
1932 * @param bool $is_init Is initiation sequence.
1933 * @param string $main_file Since 2.5.0 expects the module's main file path to potentially purge the cached path.
1934 *
1935 * @return string
1936 * @since 1.0.6
1937 *
1938 * @author Vova Feldman (@svovaf)
1939 */
1940 private function _find_caller_plugin_file( $is_init = false, $main_file = '' ) {
1941 // Try to load the cached value of the file path.
1942 if ( isset( $this->_storage->plugin_main_file ) ) {
1943 $plugin_main_file = $this->_storage->plugin_main_file;
1944 if ( ! empty( $plugin_main_file->path ) ) {
1945 $absolute_path = $this->get_absolute_path( $plugin_main_file->path );
1946 if ( file_exists( $absolute_path ) ) {
1947 if ( $is_init && $absolute_path !== $this->get_absolute_path( $main_file ) ) {
1948 // Update cached path if not matching the actual path.
1949 $plugin_main_file->path = $main_file;
1950 $this->_storage->plugin_main_file = $plugin_main_file;
1951 }
1952
1953 return $absolute_path;
1954 }
1955 }
1956 }
1957
1958 /**
1959 * @since 1.2.1
1960 *
1961 * `clear_module_main_file_cache()` is clearing the plugin's cached path on
1962 * deactivation. Therefore, if any plugin/theme was initiating `Freemius`
1963 * with that plugin's slug, it was overriding the empty plugin path with a wrong path.
1964 *
1965 * So, we've added a special mechanism with a 2nd layer of cache that uses `prev_path`
1966 * when the class instantiator isn't the module.
1967 */
1968 if ( ! $is_init ) {
1969 // Fetch prev path cache.
1970 if ( isset( $this->_storage->plugin_main_file ) &&
1971 ! empty( $this->_storage->plugin_main_file->prev_path )
1972 ) {
1973 $absolute_path = $this->get_absolute_path( $this->_storage->plugin_main_file->prev_path );
1974 if ( file_exists( $absolute_path ) ) {
1975 return $absolute_path;
1976 }
1977 }
1978
1979 wp_die(
1980 $this->get_text_inline( 'Freemius SDK couldn\'t find the plugin\'s main file. Please contact sdk@freemius.com with the current error.', 'failed-finding-main-path' ) .
1981 " Module: {$this->_slug}; SDK: " . WP_FS__SDK_VERSION . ";",
1982 $this->get_text_inline( 'Error', 'error' ),
1983 array( 'back_link' => true )
1984 );
1985 }
1986
1987 /**
1988 * @since 1.2.1
1989 *
1990 * Only the original instantiator that calls dynamic_init can modify the module's path.
1991 */
1992 // Find caller module.
1993 $this->_storage->plugin_main_file = (object) array(
1994 'path' => $main_file,
1995 );
1996
1997 return $this->get_absolute_path( $main_file );
1998 }
1999
2000 /**
2001 * @author Leo Fajardo (@leorw)
2002 * @since 1.2.3
2003 *
2004 * @param string $path
2005 *
2006 * @return string
2007 */
2008 private function get_relative_path( $path ) {
2009 $module_root_dir = $this->get_module_root_dir_path();
2010 if ( 0 === strpos( $path, $module_root_dir ) ) {
2011 $path = substr( $path, strlen( $module_root_dir ) );
2012 }
2013
2014 return $path;
2015 }
2016
2017 /**
2018 * @author Leo Fajardo (@leorw)
2019 * @since 1.2.3
2020 *
2021 * @param string $path
2022 * @param string|bool $module_type
2023 *
2024 * @return string
2025 */
2026 private function get_absolute_path( $path, $module_type = false ) {
2027 $module_root_dir = $this->get_module_root_dir_path( $module_type );
2028 if ( 0 !== strpos( $path, $module_root_dir ) ) {
2029 $path = fs_normalize_path( $module_root_dir . $path );
2030 }
2031
2032 return $path;
2033 }
2034
2035 /**
2036 * @author Leo Fajardo (@leorw)
2037 * @since 1.2.3
2038 *
2039 * @param string|bool $module_type
2040 *
2041 * @return string
2042 */
2043 private function get_module_root_dir_path( $module_type = false ) {
2044 $is_plugin = empty( $module_type ) ?
2045 $this->is_plugin() :
2046 ( WP_FS__MODULE_TYPE_PLUGIN === $module_type );
2047
2048 return fs_normalize_path( trailingslashit( $is_plugin ?
2049 WP_PLUGIN_DIR :
2050 get_theme_root( get_stylesheet() ) ) );
2051 }
2052
2053 /**
2054 * @author Leo Fajardo (@leorw)
2055 *
2056 * @param number $module_id
2057 * @param string $slug
2058 *
2059 * @return string Since 2.5.0 return the module's main file path.
2060 *
2061 * @since 1.2.2
2062 */
2063 private function store_id_slug_type_path_map( $module_id, $slug ) {
2064 $id_slug_type_path_map = self::$_accounts->get_option( 'id_slug_type_path_map', array() );
2065
2066 $store_option = false;
2067
2068 if ( ! isset( $id_slug_type_path_map[ $module_id ] ) ) {
2069 $id_slug_type_path_map[ $module_id ] = array(
2070 'slug' => $slug
2071 );
2072
2073 $store_option = true;
2074 } else if (
2075 isset( $id_slug_type_path_map[ $module_id ]['slug'] ) &&
2076 $slug !== $id_slug_type_path_map[ $module_id ]['slug']
2077 ) {
2078 $id_slug_type_path_map[ $module_id ]['slug'] = $slug;
2079 $store_option = true;
2080 }
2081
2082 $find_caller = empty( $id_slug_type_path_map[ $module_id ]['path'] );
2083
2084 if ( ! $find_caller ) {
2085 /**
2086 * This verification is for cases when suddenly the same module
2087 * is installed but with a different folder name.
2088 *
2089 * @author Vova Feldman (@svovaf)
2090 * @since 1.2.3
2091 */
2092 $find_caller = ! file_exists( $this->get_absolute_path(
2093 $id_slug_type_path_map[ $module_id ]['path'],
2094 $id_slug_type_path_map[ $module_id ]['type']
2095 ) );
2096 }
2097
2098 foreach ( $id_slug_type_path_map as $id => $data ) {
2099 if ( empty( $id ) ) {
2100 // Remove maps with empty module ID.
2101 unset( $id_slug_type_path_map[ $id ] );
2102 $store_option = true;
2103 continue;
2104 }
2105
2106 /**
2107 * If the module's main file path is identical to the main file path of another module then it means that the cached path of the current module or the other one with the same path is wrong, and therefore, we need to recalculate those paths.
2108 *
2109 * @author Vova Feldman (@svovaf)
2110 * @since 2.5.0
2111 */
2112 if ( ! $find_caller ) {
2113 if ( $id == $module_id ) {
2114 continue;
2115 }
2116
2117 if (
2118 isset( $data['path'] ) &&
2119 $data['path'] === $id_slug_type_path_map[ $module_id ]['path']
2120 ) {
2121 $find_caller = true;
2122 }
2123 }
2124 }
2125
2126 if ( $find_caller ) {
2127 $caller_main_file_and_type = $this->get_caller_main_file_and_type( $module_id );
2128
2129 $id_slug_type_path_map[ $module_id ]['type'] = $caller_main_file_and_type->module_type;
2130 $id_slug_type_path_map[ $module_id ]['path'] = $caller_main_file_and_type->path;
2131
2132 $store_option = true;
2133 }
2134
2135 if ( $store_option ) {
2136 self::$_accounts->set_option( 'id_slug_type_path_map', $id_slug_type_path_map, true );
2137 }
2138
2139 return $id_slug_type_path_map[ $module_id ]['path'];
2140 }
2141
2142 /**
2143 * Identifies the caller type: plugin or theme.
2144 *
2145 * @author Leo Fajardo (@leorw)
2146 * @since 1.2.2
2147 *
2148 * @author Vova Feldman (@svovaf)
2149 * @since 1.2.2.3 Find the earliest module in the call stack that calls to the SDK. This fix is for cases when
2150 * add-ons are relying on loading the SDK from the parent module, and also allows themes including the
2151 * SDK an internal file instead of directly from functions.php.
2152 * @since 1.2.1.7 Knows how to handle cases when an add-on includes the parent module logic.
2153 *
2154 * @param number $module_id @since 2.5.0
2155 */
2156 private function get_caller_main_file_and_type( $module_id ) {
2157 self::require_plugin_essentials();
2158
2159 $all_plugins = fs_get_plugins( true );
2160 $all_plugins_paths = array();
2161
2162 // Get active plugin's main files real full names (might be symlinks).
2163 foreach ( $all_plugins as $relative_path => $data ) {
2164 if ( false === strpos( fs_normalize_path( $relative_path ), '/' ) ) {
2165 /**
2166 * Ignore plugins that don't have a folder (e.g. Hello Dolly) since they
2167 * can't really include the SDK.
2168 *
2169 * @author Vova Feldman
2170 * @since 1.2.1.7
2171 */
2172 continue;
2173 }
2174
2175 $all_plugins_paths[] = fs_normalize_path( realpath( WP_PLUGIN_DIR . '/' . $relative_path ) );
2176 }
2177
2178 $caller_file_candidate = false;
2179 $caller_map = array();
2180 $module_type = WP_FS__MODULE_TYPE_PLUGIN;
2181 $themes_dir = fs_normalize_path( get_theme_root( get_stylesheet() ) );
2182 $plugin_dir_to_skip = false;
2183
2184 for ( $i = 1, $bt = debug_backtrace(), $len = count( $bt ); $i < $len; $i ++ ) {
2185 if ( empty( $bt[ $i ]['file'] ) ) {
2186 continue;
2187 }
2188
2189 if ( $i > 1 && ! empty( $bt[ $i - 1 ]['file'] ) && $bt[ $i ]['file'] === $bt[ $i - 1 ]['file'] ) {
2190 // If file same as the prev file in the stack, skip it.
2191 continue;
2192 }
2193
2194 if ( ! empty( $bt[ $i ]['function'] ) && in_array( $bt[ $i ]['function'], array(
2195 'do_action',
2196 'apply_filter',
2197 // The string split is stupid, but otherwise, theme check
2198 // throws info notices.
2199 'requir' . 'e_once',
2200 'requir' . 'e',
2201 'includ' . 'e_once',
2202 'includ' . 'e',
2203 'install_and_activate_plugin',
2204 'try_activate_plugin',
2205 'activate_plugin'
2206 ) )
2207 ) {
2208 if ( 'activate_plugin' === $bt[ $i ]['function'] ) {
2209 /**
2210 * Store the directory of the activator plugin so that any other file that starts with it
2211 * cannot be mistakenly chosen as a candidate caller file.
2212 *
2213 * @author Leo Fajardo
2214 *
2215 * @since 2.3.0
2216 */
2217 $caller_file_path = fs_normalize_path( $bt[ $i ]['file'] );
2218
2219 foreach ( $all_plugins_paths as $plugin_path ) {
2220 $plugin_dir = fs_normalize_path( dirname( $plugin_path ) . '/' );
2221 if ( false !== strpos( $caller_file_path, $plugin_dir ) ) {
2222 $plugin_dir_to_skip = $plugin_dir;
2223
2224 break;
2225 }
2226 }
2227 }
2228
2229 // Ignore call stack hooks and files inclusion.
2230 continue;
2231 }
2232
2233 $caller_file_path = fs_normalize_path( $bt[ $i ]['file'] );
2234
2235 if ( ! empty( $plugin_dir_to_skip ) ) {
2236 /**
2237 * Skip if it's an activator plugin file to avoid mistakenly choosing it as a candidate caller file.
2238 *
2239 * @author Leo Fajardo
2240 *
2241 * @since 2.3.0
2242 */
2243 if ( 0 === strpos( $caller_file_path, $plugin_dir_to_skip ) ) {
2244 continue;
2245 }
2246 }
2247
2248 if ( 'functions.php' === basename( $caller_file_path ) ) {
2249 /**
2250 * 1. Assumes that theme's starting execution file is functions.php.
2251 * 2. This complex logic fixes symlink issues (e.g. with Vargant).
2252 *
2253 * @author Vova Feldman (@svovaf)
2254 * @since 1.2.2.5
2255 */
2256
2257 if ( $caller_file_path == fs_normalize_path( realpath( trailingslashit( $themes_dir ) . basename( dirname( $caller_file_path ) ) . '/' . basename( $caller_file_path ) ) ) ) {
2258 $module_type = WP_FS__MODULE_TYPE_THEME;
2259
2260 /**
2261 * Relative path of the theme, e.g.:
2262 * `my-theme/functions.php`
2263 *
2264 * @author Leo Fajardo (@leorw)
2265 */
2266 $caller_file_candidate = basename( dirname( $caller_file_path ) ) .
2267 '/' .
2268 basename( $caller_file_path );
2269
2270 continue;
2271 }
2272 }
2273
2274 $caller_file_hash = md5( $caller_file_path );
2275
2276 if ( ! isset( $caller_map[ $caller_file_hash ] ) ) {
2277 foreach ( $all_plugins_paths as $plugin_path ) {
2278 if ( empty( $plugin_path ) ) {
2279 continue;
2280 }
2281
2282 if ( false !== strpos( $caller_file_path, fs_normalize_path( dirname( $plugin_path ) . '/' ) ) ) {
2283 $caller_map[ $caller_file_hash ] = fs_normalize_path( $plugin_path );
2284 break;
2285 }
2286 }
2287 }
2288
2289 if ( isset( $caller_map[ $caller_file_hash ] ) ) {
2290 $module_type = WP_FS__MODULE_TYPE_PLUGIN;
2291 $caller_file_candidate = plugin_basename( $caller_map[ $caller_file_hash ] );
2292 }
2293 }
2294
2295 $caller_main_file_and_type = (object) array(
2296 'module_type' => $module_type,
2297 'path' => $caller_file_candidate
2298 );
2299
2300 return apply_filters( "fs_{$module_id}_caller_main_file_and_type", $caller_main_file_and_type );
2301 }
2302
2303 #----------------------------------------------------------------------------------
2304 #region Deactivation Feedback Form
2305 #----------------------------------------------------------------------------------
2306
2307 /**
2308 * Displays a confirmation and feedback dialog box when the user clicks on the "Deactivate" link on the plugins
2309 * page.
2310 *
2311 * @author Vova Feldman (@svovaf)
2312 * @author Leo Fajardo (@leorw)
2313 *
2314 * @since 1.1.2
2315 */
2316 function _add_deactivation_feedback_dialog_box() {
2317 if (
2318 $this->is_clone() ||
2319 ( is_object( $this->_site ) && ! $this->is_registered() )
2320 ) {
2321 return;
2322 }
2323
2324 $subscription_cancellation_dialog_box_template_params = $this->apply_filters( 'show_deactivation_subscription_cancellation', true ) ?
2325 $this->_get_subscription_cancellation_dialog_box_template_params() :
2326 array();
2327
2328 /**
2329 * @since 2.3.0 Developers can optionally hide the deactivation feedback form using the 'show_deactivation_feedback_form' filter.
2330 */
2331 $show_deactivation_feedback_form = ! self::is_deactivation_snoozed();
2332 if ( $this->has_filter( 'show_deactivation_feedback_form' ) ) {
2333 $show_deactivation_feedback_form = $this->apply_filters( 'show_deactivation_feedback_form', true );
2334 } else if ( $this->is_addon() ) {
2335 /**
2336 * If the add-on's 'show_deactivation_feedback_form' is not set, try to inherit the value from the parent.
2337 */
2338 $show_deactivation_feedback_form = $this->get_parent_instance()->apply_filters( 'show_deactivation_feedback_form', true );
2339 }
2340
2341 $uninstall_confirmation_message = $this->apply_filters( 'uninstall_confirmation_message', '' );
2342
2343 if (
2344 empty( $subscription_cancellation_dialog_box_template_params ) &&
2345 ! $show_deactivation_feedback_form &&
2346 empty( $uninstall_confirmation_message )
2347 ) {
2348 return;
2349 }
2350
2351 $vars = array( 'id' => $this->_module_id );
2352
2353 if ( $show_deactivation_feedback_form ) {
2354 /* Check the type of user:
2355 * 1. Long-term (long-term)
2356 * 2. Non-registered and non-anonymous short-term (non-registered-and-non-anonymous-short-term).
2357 * 3. Short-term (short-term)
2358 */
2359 $is_long_term_user = true;
2360
2361 // Check if the site is at least 2 days old.
2362 $time_installed = $this->_storage->install_timestamp;
2363
2364 // Difference in seconds.
2365 $date_diff = time() - $time_installed;
2366
2367 // Convert seconds to days.
2368 $date_diff_days = floor( $date_diff / ( 60 * 60 * 24 ) );
2369
2370 if ( $date_diff_days < 2 ) {
2371 $is_long_term_user = false;
2372 }
2373
2374 $is_long_term_user = $this->apply_filters( 'is_long_term_user', $is_long_term_user );
2375
2376 if ( $is_long_term_user ) {
2377 $user_type = 'long-term';
2378 } else {
2379 if ( ! $this->is_registered() && ! $this->is_anonymous() ) {
2380 $user_type = 'non-registered-and-non-anonymous-short-term';
2381 } else {
2382 $user_type = 'short-term';
2383 }
2384 }
2385
2386 $uninstall_reasons = $this->_get_uninstall_reasons( $user_type );
2387
2388 $vars['reasons'] = $uninstall_reasons;
2389 }
2390
2391 $vars['subscription_cancellation_dialog_box_template_params'] = &$subscription_cancellation_dialog_box_template_params;
2392 $vars['show_deactivation_feedback_form'] = $show_deactivation_feedback_form;
2393 $vars['uninstall_confirmation_message'] = $uninstall_confirmation_message;
2394
2395 /**
2396 * Load the HTML template for the deactivation feedback dialog box.
2397 *
2398 * @todo Deactivation form core functions should be loaded only once! Otherwise, when there are multiple Freemius powered plugins the same code is loaded multiple times. The only thing that should be loaded differently is the various deactivation reasons object based on the state of the plugin.
2399 */
2400 fs_require_template( 'forms/deactivation/form.php', $vars );
2401 }
2402
2403 /**
2404 * @author Leo Fajardo (@leorw)
2405 * @since 1.1.2
2406 *
2407 * @param string $user_type
2408 *
2409 * @return array The uninstall reasons for the specified user type.
2410 */
2411 function _get_uninstall_reasons( $user_type = 'long-term' ) {
2412 $module_type = $this->_module_type;
2413
2414 $internal_message_template_var = array(
2415 'id' => $this->_module_id
2416 );
2417
2418 $plan = $this->get_plan();
2419
2420 if ( $this->is_registered() && is_object( $plan ) && $plan->has_technical_support() ) {
2421 $contact_support_template = fs_get_template( 'forms/deactivation/contact.php', $internal_message_template_var );
2422 } else {
2423 $contact_support_template = '';
2424 }
2425
2426 $reason_found_better_plugin = array(
2427 'id' => self::REASON_FOUND_A_BETTER_PLUGIN,
2428 'text' => sprintf( $this->get_text_inline( 'I found a better %s', 'reason-found-a-better-plugin' ), $module_type ),
2429 'input_type' => 'textfield',
2430 'input_placeholder' => sprintf( $this->get_text_inline( "What's the %s's name?", 'placeholder-plugin-name' ), $module_type ),
2431 );
2432
2433 $reason_temporary_deactivation = array(
2434 'id' => self::REASON_TEMPORARY_DEACTIVATION,
2435 'text' => sprintf(
2436 $this->get_text_inline( "It's a temporary %s - I'm troubleshooting an issue", 'reason-temporary-x' ),
2437 strtolower( $this->is_plugin() ?
2438 $this->get_text_inline( 'Deactivation', 'deactivation' ) :
2439 $this->get_text_inline( 'Theme Switch', 'theme-switch' )
2440 )
2441 ),
2442 'input_type' => '',
2443 'input_placeholder' => ''
2444 );
2445
2446 $reason_other = array(
2447 'id' => self::REASON_OTHER,
2448 'text' => $this->get_text_inline( 'Other', 'reason-other' ),
2449 'input_type' => 'textfield',
2450 'input_placeholder' => ''
2451 );
2452
2453 $long_term_user_reasons = array(
2454 array(
2455 'id' => self::REASON_NO_LONGER_NEEDED,
2456 'text' => sprintf( $this->get_text_inline( 'I no longer need the %s', 'reason-no-longer-needed' ), $module_type ),
2457 'input_type' => '',
2458 'input_placeholder' => ''
2459 ),
2460 $reason_found_better_plugin,
2461 array(
2462 'id' => self::REASON_NEEDED_FOR_A_SHORT_PERIOD,
2463 'text' => sprintf( $this->get_text_inline( 'I only needed the %s for a short period', 'reason-needed-for-a-short-period' ), $module_type ),
2464 'input_type' => '',
2465 'input_placeholder' => ''
2466 ),
2467 array(
2468 'id' => self::REASON_BROKE_MY_SITE,
2469 'text' => sprintf( $this->get_text_inline( 'The %s broke my site', 'reason-broke-my-site' ), $module_type ),
2470 'input_type' => '',
2471 'input_placeholder' => '',
2472 'internal_message' => $contact_support_template
2473 ),
2474 array(
2475 'id' => self::REASON_SUDDENLY_STOPPED_WORKING,
2476 'text' => sprintf( $this->get_text_inline( 'The %s suddenly stopped working', 'reason-suddenly-stopped-working' ), $module_type ),
2477 'input_type' => '',
2478 'input_placeholder' => '',
2479 'internal_message' => $contact_support_template
2480 )
2481 );
2482
2483 if ( $this->is_paying() ) {
2484 $long_term_user_reasons[] = array(
2485 'id' => self::REASON_CANT_PAY_ANYMORE,
2486 'text' => $this->get_text_inline( "I can't pay for it anymore", 'reason-cant-pay-anymore' ),
2487 'input_type' => 'textfield',
2488 'input_placeholder' => $this->get_text_inline( 'What price would you feel comfortable paying?', 'placeholder-comfortable-price' )
2489 );
2490 }
2491
2492 $reason_dont_share_info = array(
2493 'id' => self::REASON_DONT_LIKE_TO_SHARE_MY_INFORMATION,
2494 'text' => $this->get_text_inline( "I don't like to share my information with you", 'reason-dont-like-to-share-my-information' ),
2495 'input_type' => '',
2496 'input_placeholder' => ''
2497 );
2498
2499 /**
2500 * If the current user has selected the "don't share data" reason in the deactivation feedback modal, inform the
2501 * user by showing additional message that he doesn't have to share data and can just choose to skip the opt-in
2502 * (the Skip button is included in the message to show). This message will only be shown if anonymous mode is
2503 * enabled and the user's account is currently not in pending activation state (similar to the way the Skip
2504 * button in the opt-in form is shown/hidden).
2505 */
2506 if ( $this->is_enable_anonymous() && ! $this->is_pending_activation() ) {
2507 $reason_dont_share_info['internal_message'] = fs_get_template( 'forms/deactivation/retry-skip.php', $internal_message_template_var );
2508 }
2509
2510 $uninstall_reasons = array(
2511 'long-term' => $long_term_user_reasons,
2512 'non-registered-and-non-anonymous-short-term' => array(
2513 array(
2514 'id' => self::REASON_DIDNT_WORK,
2515 'text' => sprintf( $this->get_text_inline( "The %s didn't work", 'reason-didnt-work' ), $module_type ),
2516 'input_type' => '',
2517 'input_placeholder' => ''
2518 ),
2519 $reason_dont_share_info,
2520 $reason_found_better_plugin
2521 ),
2522 'short-term' => array(
2523 array(
2524 'id' => self::REASON_COULDNT_MAKE_IT_WORK,
2525 'text' => $this->get_text_inline( "I couldn't understand how to make it work", 'reason-couldnt-make-it-work' ),
2526 'input_type' => '',
2527 'input_placeholder' => '',
2528 'internal_message' => $contact_support_template
2529 ),
2530 $reason_found_better_plugin,
2531 array(
2532 'id' => self::REASON_GREAT_BUT_NEED_SPECIFIC_FEATURE,
2533 'text' => sprintf( $this->get_text_inline( "The %s is great, but I need specific feature that you don't support", 'reason-great-but-need-specific-feature' ), $module_type ),
2534 'input_type' => 'textarea',
2535 'input_placeholder' => $this->get_text_inline( 'What feature?', 'placeholder-feature' )
2536 ),
2537 array(
2538 'id' => self::REASON_NOT_WORKING,
2539 'text' => sprintf( $this->get_text_inline( 'The %s is not working', 'reason-not-working' ), $module_type ),
2540 'input_type' => 'textarea',
2541 'input_placeholder' => $this->get_text_inline( "Kindly share what didn't work so we can fix it for future users...", 'placeholder-share-what-didnt-work' )
2542 ),
2543 array(
2544 'id' => self::REASON_NOT_WHAT_I_WAS_LOOKING_FOR,
2545 'text' => $this->get_text_inline( "It's not what I was looking for", 'reason-not-what-i-was-looking-for' ),
2546 'input_type' => 'textarea',
2547 'input_placeholder' => $this->get_text_inline( "What you've been looking for?", 'placeholder-what-youve-been-looking-for' )
2548 ),
2549 array(
2550 'id' => self::REASON_DIDNT_WORK_AS_EXPECTED,
2551 'text' => sprintf( $this->get_text_inline( "The %s didn't work as expected", 'reason-didnt-work-as-expected' ), $module_type ),
2552 'input_type' => 'textarea',
2553 'input_placeholder' => $this->get_text_inline( 'What did you expect?', 'placeholder-what-did-you-expect' )
2554 )
2555 )
2556 );
2557
2558 // Randomize the reasons for the current user type.
2559 shuffle( $uninstall_reasons[ $user_type ] );
2560
2561 // Keep the following reasons as the last items in the list.
2562 $uninstall_reasons[ $user_type ][] = $reason_temporary_deactivation;
2563 $uninstall_reasons[ $user_type ][] = $reason_other;
2564
2565 $uninstall_reasons = $this->apply_filters( 'uninstall_reasons', $uninstall_reasons );
2566
2567 return $uninstall_reasons[ $user_type ];
2568 }
2569
2570 /**
2571 * Called after the user has submitted his reason for deactivating the plugin.
2572 *
2573 * @author Leo Fajardo (@leorw)
2574 * @since 1.1.2
2575 */
2576 function _submit_uninstall_reason_action() {
2577 $this->_logger->entrance();
2578
2579 $this->check_ajax_referer( 'submit_uninstall_reason' );
2580
2581 $reason_id = fs_request_get( 'reason_id' );
2582
2583 // Check if the given reason ID is an unsigned integer.
2584 if ( ! ctype_digit( $reason_id ) ) {
2585 exit;
2586 }
2587
2588 $reason_info = trim( fs_request_get( 'reason_info', '' ) );
2589 if ( ! empty( $reason_info ) ) {
2590 $reason_info = substr( $reason_info, 0, 128 );
2591 }
2592
2593 $reason = (object) array(
2594 'id' => $reason_id,
2595 'info' => $reason_info,
2596 'is_anonymous' => fs_request_get_bool( 'is_anonymous' )
2597 );
2598
2599 $this->_storage->store( 'uninstall_reason', $reason );
2600
2601 if ( self::REASON_TEMPORARY_DEACTIVATION == $reason->id ) {
2602 $snooze_period = fs_request_get( 'snooze_period' );
2603
2604 if ( is_numeric( $snooze_period ) && 0 < $snooze_period ) {
2605 self::snooze_deactivation_form( (int) $snooze_period );
2606 }
2607 }
2608
2609 /**
2610 * If the module type is "theme", trigger the uninstall event here (on theme deactivation) since themes do
2611 * not support uninstall hook.
2612 *
2613 * @author Leo Fajardo (@leorw)
2614 * @since 1.2.2
2615 */
2616 if ( $this->is_theme() ) {
2617 if ( $this->is_premium() && ! $this->has_active_valid_license() ) {
2618 FS_Plugin_Updater::instance( $this )->delete_update_data();
2619 }
2620
2621 $this->_uninstall_plugin_event( false );
2622 $this->remove_sdk_reference();
2623 }
2624
2625 // Print '1' for successful operation.
2626 echo 1;
2627 exit;
2628 }
2629
2630 #--------------------------------------------------------------------------------
2631 #region Deactivation Feedback Snoozing
2632 #--------------------------------------------------------------------------------
2633
2634 /**
2635 * @author Vova Feldman (@svovaf)
2636 * @since 2.4.3
2637 *
2638 * @param int $period
2639 *
2640 * @return bool True if the value was set, false otherwise.
2641 */
2642 private static function snooze_deactivation_form( $period ) {
2643 return ( 0 < $period && self::reset_deactivation_snoozing( $period ) );
2644 }
2645
2646 /**
2647 * Check if deactivation feedback form is snoozed.
2648 *
2649 * @author Vova Feldman (@svovaf)
2650 * @since 2.4.3
2651 *
2652 * @return bool
2653 */
2654 static function is_deactivation_snoozed() {
2655 $is_snoozed = ( ! is_multisite() || fs_is_network_admin() ) ?
2656 get_transient( 'fs_snooze_period' ) :
2657 get_site_transient( 'fs_snooze_period' );
2658
2659
2660 return ( 'true' === $is_snoozed );
2661 }
2662
2663 /**
2664 * Reset deactivation snoozing. When `$period` is `0` will stop deactivation snoozing by deleting the transients. Otherwise, will set the transients for the selected period.
2665 *
2666 * @param int $period Period in seconds.
2667 *
2668 * @author Vova Feldman (@svovaf)
2669 * @since 2.4.3
2670 */
2671 private static function reset_deactivation_snoozing( $period = 0 ) {
2672 $value = ( 0 === $period ) ? null : 'true';
2673
2674 if ( ! is_multisite() || fs_is_network_admin() ) {
2675 return set_transient( 'fs_snooze_period', $value, $period );
2676 } else {
2677 return set_site_transient( 'fs_snooze_period', $value, $period );
2678 }
2679 }
2680
2681 /**
2682 * The deactivation snooze expiration UNIX timestamp (in sec).
2683 *
2684 * @author Vova Feldman (@svovaf)
2685 * @since 2.4.3
2686 *
2687 * @return int
2688 */
2689 static function deactivation_snooze_expires_at() {
2690 return ( ! is_multisite() || fs_is_network_admin() ) ?
2691 (int) get_option( '_transient_timeout_fs_snooze_period' ) :
2692 (int) get_site_option( '_site_transient_timeout_fs_snooze_period' );
2693 }
2694
2695 #endregion
2696
2697 /**
2698 * @author Leo Fajardo (@leorw)
2699 * @since 2.1.4
2700 */
2701 function cancel_subscription_or_trial_ajax_action() {
2702 $this->_logger->entrance();
2703
2704 $this->check_ajax_referer( 'cancel_subscription_or_trial' );
2705
2706 $result = $this->cancel_subscription_or_trial( fs_request_get( 'plugin_id', $this->get_id() ), false );
2707
2708 if ( $this->is_api_error( $result ) ) {
2709 $this->shoot_ajax_failure( $result->error->message );
2710 }
2711
2712 $this->shoot_ajax_success();
2713 }
2714
2715 /**
2716 * @author Leo Fajardo (@leorw)
2717 * @since 2.1.4
2718 *
2719 * @param number $plugin_id
2720 *
2721 * @return object
2722 */
2723 private function cancel_subscription_or_trial( $plugin_id ) {
2724 $fs = null;
2725 if ( $plugin_id == $this->get_id() ) {
2726 $fs = $this;
2727 } else if ( $this->is_addon_activated( $plugin_id ) ) {
2728 $fs = self::get_instance_by_id( $plugin_id );
2729 }
2730
2731 $result = null;
2732
2733 if ( ! is_null( $fs ) ) {
2734 $result = $fs->is_paid_trial() ?
2735 $fs->_cancel_trial() :
2736 $fs->_downgrade_site();
2737 }
2738
2739 return $result;
2740 }
2741
2742 /**
2743 * @author Leo Fajardo (@leorw)
2744 * @since 2.0.2
2745 */
2746 function _delete_theme_update_data_action() {
2747 FS_Plugin_Updater::instance( $this )->delete_update_data();
2748 }
2749
2750 #endregion
2751
2752 #----------------------------------------------------------------------------------
2753 #region Instance
2754 #----------------------------------------------------------------------------------
2755
2756 /**
2757 * Main singleton instance.
2758 *
2759 * @author Vova Feldman (@svovaf)
2760 * @since 1.0.0
2761 *
2762 * @param number $module_id
2763 * @param string|bool $slug
2764 * @param bool $is_init Is initiation sequence.
2765 *
2766 * @return Freemius|false
2767 */
2768 static function instance( $module_id, $slug = false, $is_init = false ) {
2769 if ( empty( $module_id ) ) {
2770 return false;
2771 }
2772
2773 /**
2774 * Load the essential static data prior to initiating FS_Plugin_Manager since there's an essential MS network migration logic that needs to be executed prior to the initiation.
2775 */
2776 self::_load_required_static();
2777
2778 if ( ! is_numeric( $module_id ) ) {
2779 if ( ! $is_init && true === $slug ) {
2780 $is_init = true;
2781 }
2782
2783 $slug = $module_id;
2784
2785 $module = FS_Plugin_Manager::instance( $slug )->get();
2786
2787 if ( is_object( $module ) ) {
2788 $module_id = $module->id;
2789 }
2790 }
2791
2792 $key = 'm_' . $module_id;
2793
2794 if ( ! isset( self::$_instances[ $key ] ) ) {
2795 self::$_instances[ $key ] = new Freemius( $module_id, $slug, $is_init );
2796 }
2797
2798 return self::$_instances[ $key ];
2799 }
2800
2801 /**
2802 * @author Vova Feldman (@svovaf)
2803 * @since 1.0.6
2804 *
2805 * @param number $addon_id
2806 *
2807 * @return bool
2808 */
2809 private static function has_instance( $addon_id ) {
2810 return isset( self::$_instances[ 'm_' . $addon_id ] );
2811 }
2812
2813 /**
2814 * @author Leo Fajardo (@leorw)
2815 * @since 1.2.2
2816 *
2817 * @param string|number $id_or_slug
2818 * @param string $module_type
2819 *
2820 * @return number|false
2821 */
2822 private static function get_module_id( $id_or_slug, $module_type = WP_FS__MODULE_TYPE_PLUGIN ) {
2823 if ( is_numeric( $id_or_slug ) ) {
2824 return $id_or_slug;
2825 }
2826
2827 foreach ( self::$_instances as $instance ) {
2828 // Also check the module type since there can be a plugin and a theme with the same slug.
2829 if ( ( $module_type === $instance->get_module_type() ) && ( $id_or_slug === $instance->get_slug() ) ) {
2830 return $instance->get_id();
2831 }
2832 }
2833
2834 return false;
2835 }
2836
2837 /**
2838 * @author Vova Feldman (@svovaf)
2839 * @since 1.0.6
2840 *
2841 * @param number $id
2842 *
2843 * @return false|Freemius
2844 */
2845 static function get_instance_by_id( $id ) {
2846 return isset ( self::$_instances[ 'm_' . $id ] ) ?
2847 self::$_instances[ 'm_' . $id ] :
2848 false;
2849 }
2850
2851 /**
2852 *
2853 * @author Vova Feldman (@svovaf)
2854 * @since 1.0.1
2855 *
2856 * @param string $plugin_file
2857 * @param string $module_type
2858 *
2859 * @return false|Freemius
2860 */
2861 static function get_instance_by_file( $plugin_file, $module_type = WP_FS__MODULE_TYPE_PLUGIN ) {
2862 $slug = self::find_slug_by_basename( $plugin_file );
2863
2864 return ( false !== $slug ) ?
2865 self::instance( self::get_module_id( $slug, $module_type ) ) :
2866 false;
2867 }
2868
2869 /**
2870 * @author Vova Feldman (@svovaf)
2871 * @since 1.0.6
2872 *
2873 * @return false|Freemius
2874 */
2875 function get_parent_instance() {
2876 return self::get_instance_by_id( $this->_plugin->parent_plugin_id );
2877 }
2878
2879 /**
2880 * @author Vova Feldman (@svovaf)
2881 * @since 1.0.6
2882 *
2883 * @param string|number $id_or_slug
2884 *
2885 * @return false|Freemius
2886 */
2887 function get_addon_instance( $id_or_slug ) {
2888 $addon_id = self::get_module_id( $id_or_slug );
2889
2890 return self::instance( $addon_id );
2891 }
2892
2893 /**
2894 * @return Freemius[]
2895 */
2896 static function _get_all_instances() {
2897 return self::$_instances;
2898 }
2899
2900 #endregion ------------------------------------------------------------------
2901
2902 /**
2903 * @author Vova Feldman (@svovaf)
2904 * @since 1.0.6
2905 *
2906 * @return bool
2907 */
2908 function is_parent_plugin_installed() {
2909 $is_active = self::has_instance( $this->_plugin->parent_plugin_id );
2910
2911 if ( $is_active ) {
2912 return true;
2913 }
2914
2915 /**
2916 * Parent module might be a theme. If that's the case, the add-on's FS
2917 * instance will be loaded prior to the theme's FS instance, therefore,
2918 * we need to check if it's active with a "look ahead".
2919 *
2920 * @author Vova Feldman
2921 * @since 1.2.2.3
2922 */
2923 global $fs_active_plugins;
2924 if ( is_object( $fs_active_plugins ) && is_array( $fs_active_plugins->plugins ) ) {
2925 $active_theme = wp_get_theme();
2926
2927 foreach ( $fs_active_plugins->plugins as $sdk => $module ) {
2928 if ( WP_FS__MODULE_TYPE_THEME === $module->type ) {
2929 if ( $module->plugin_path == $active_theme->get_stylesheet() ) {
2930 // Parent module is a theme and it's currently active.
2931 return true;
2932 }
2933 }
2934 }
2935 }
2936
2937 return false;
2938 }
2939
2940 /**
2941 * Check if add-on parent plugin in activation mode.
2942 *
2943 * @author Vova Feldman (@svovaf)
2944 * @since 1.0.7
2945 *
2946 * @return bool
2947 */
2948 function is_parent_in_activation() {
2949 $parent_fs = $this->get_parent_instance();
2950 if ( ! is_object( $parent_fs ) ) {
2951 return false;
2952 }
2953
2954 return ( $parent_fs->is_activation_mode() );
2955 }
2956
2957 /**
2958 * Is plugin in activation mode.
2959 *
2960 * @author Vova Feldman (@svovaf)
2961 * @since 1.0.7
2962 *
2963 * @param bool $and_on
2964 *
2965 * @return bool
2966 */
2967 function is_activation_mode( $and_on = true ) {
2968 return fs_is_network_admin() ?
2969 $this->is_network_activation_mode( $and_on ) :
2970 $this->is_site_activation_mode( $and_on );
2971 }
2972
2973 /**
2974 * Is plugin in activation mode.
2975 *
2976 * @author Vova Feldman (@svovaf)
2977 * @since 1.0.7
2978 *
2979 * @param bool $and_on
2980 *
2981 * @return bool
2982 */
2983 function is_site_activation_mode( $and_on = true ) {
2984 return (
2985 ( $this->is_on() || ! $and_on ) &&
2986 (
2987 ( $this->is_premium() && true === $this->_storage->require_license_activation ) ||
2988 (
2989 ( ! $this->is_registered() ||
2990 ( $this->is_only_premium() && ! $this->has_features_enabled_license() ) ) &&
2991 ( ! $this->is_enable_anonymous() ||
2992 ( ! $this->is_anonymous() && ! $this->is_pending_activation() ) )
2993 )
2994 )
2995 );
2996 }
2997
2998 /**
2999 * Checks if the SDK in network activation mode.
3000 *
3001 * @author Leo Fajardo (@leorw)
3002 * @since 2.0.0
3003 *
3004 * @param bool $and_on
3005 *
3006 * @return bool
3007 */
3008 private function is_network_activation_mode( $and_on = true ) {
3009 if ( ! $this->_is_network_active ) {
3010 // Not network activated.
3011 return false;
3012 }
3013
3014 if ( $this->is_network_upgrade_mode() ) {
3015 // Special flag to enforce network activation mode to decide what to do with the sites that are not yet opted-in nor skipped.
3016 return true;
3017 }
3018
3019 if ( ! $this->is_site_activation_mode( $and_on ) ) {
3020 // Whether the context is single site or the network, if the plugin is no longer in activation mode then it is not in network activation mode as well.
3021 return false;
3022 }
3023
3024 if ( $this->is_network_delegated_connection() ) {
3025 // Super-admin delegated the connection to the site admins -> not activation mode.
3026 return false;
3027 }
3028
3029 if ( $this->is_network_anonymous() && true !== $this->_storage->require_license_activation ) {
3030 // Super-admin skipped the connection network wide -> not activation mode.
3031 return false;
3032 }
3033
3034 if ( $this->is_network_registered() ) {
3035 // Super-admin connected at least one site -> not activation mode.
3036 return false;
3037 }
3038
3039 return true;
3040 }
3041
3042 /**
3043 * Check if current page is the opt-in/pending-activation page.
3044 *
3045 * @author Vova Feldman (@svovaf)
3046 * @since 1.2.1.7
3047 *
3048 * @return bool
3049 */
3050 function is_activation_page() {
3051 if ( $this->_menu->is_activation_page( $this->show_opt_in_on_themes_page() ) ) {
3052 return true;
3053 }
3054
3055 if ( ! $this->is_activation_mode() ) {
3056 return false;
3057 }
3058
3059 // Check if current page is matching the activation page.
3060 return $this->is_matching_url( $this->get_activation_url() );
3061 }
3062
3063 /**
3064 * Check if URL path's are matching and that all querystring
3065 * arguments of the $sub_url exist in the $url with the same values.
3066 *
3067 * WARNING:
3068 * 1. This method doesn't check if the sub/domain are matching.
3069 * 2. Ignore case sensitivity.
3070 *
3071 * @author Vova Feldman (@svovaf)
3072 * @since 1.2.1.7
3073 *
3074 * @param string $sub_url
3075 * @param string $url If argument is not set, check if the sub_url matching the current's page URL.
3076 *
3077 * @return bool
3078 */
3079 private function is_matching_url( $sub_url, $url = '' ) {
3080 if ( empty( $url ) ) {
3081 $url = $_SERVER['REQUEST_URI'];
3082 }
3083
3084 $url = strtolower( $url );
3085 $sub_url = strtolower( $sub_url );
3086
3087 if ( parse_url( $sub_url, PHP_URL_PATH ) !== parse_url( $url, PHP_URL_PATH ) ) {
3088 // Different path - DO NOT OVERRIDE PAGE.
3089 return false;
3090 }
3091
3092 $url_params = array();
3093 parse_str( parse_url( $url, PHP_URL_QUERY ), $url_params );
3094
3095 $sub_url_params = array();
3096 parse_str( parse_url( $sub_url, PHP_URL_QUERY ), $sub_url_params );
3097
3098 foreach ( $sub_url_params as $key => $val ) {
3099 if ( ! isset( $url_params[ $key ] ) || $val != $url_params[ $key ] ) {
3100 // Not matching query string - DO NOT OVERRIDE PAGE.
3101 return false;
3102 }
3103 }
3104
3105 return true;
3106 }
3107
3108 /**
3109 * Get the basenames of all active plugins for specific blog. Including network activated plugins.
3110 *
3111 * @author Vova Feldman (@svovaf)
3112 * @since 2.0.0
3113 *
3114 * @param int $blog_id
3115 *
3116 * @return string[]
3117 */
3118 private static function get_active_plugins_basenames( $blog_id = 0 ) {
3119 if ( is_multisite() && $blog_id > 0 ) {
3120 $active_basenames = get_blog_option( $blog_id, 'active_plugins' );
3121 } else {
3122 $active_basenames = get_option( 'active_plugins' );
3123 }
3124
3125 if ( ! is_array( $active_basenames ) ) {
3126 $active_basenames = array();
3127 }
3128
3129 if ( is_multisite() ) {
3130 $network_active_basenames = get_site_option( 'active_sitewide_plugins' );
3131
3132 if ( is_array( $network_active_basenames ) && ! empty( $network_active_basenames ) ) {
3133 $active_basenames = array_merge( $active_basenames, array_keys( $network_active_basenames ) );
3134 }
3135 }
3136
3137 return $active_basenames;
3138 }
3139
3140 /**
3141 * @author Leo Fajardo (@leorw)
3142 * @since 2.3.0
3143 *
3144 * @param int $blog_id
3145 *
3146 * @return array
3147 */
3148 static function get_active_plugins_directories_map( $blog_id = 0 ) {
3149 $active_basenames = self::get_active_plugins_basenames( $blog_id );
3150
3151 $map = array();
3152
3153 foreach ( $active_basenames as $active_basename ) {
3154 $active_basename = fs_normalize_path( $active_basename );
3155
3156 if ( false === strpos( $active_basename, '/' ) ) {
3157 continue;
3158 }
3159
3160 $map[ dirname( $active_basename ) ] = true;
3161 }
3162
3163 return $map;
3164 }
3165
3166 /**
3167 * Get collection of all active plugins. Including network activated plugins.
3168 *
3169 * @author Vova Feldman (@svovaf)
3170 * @since 1.0.9
3171 *
3172 * @param int $blog_id Since 2.0.0
3173 *
3174 * @return array[string]array
3175 */
3176 private static function get_active_plugins( $blog_id = 0 ) {
3177 self::require_plugin_essentials();
3178
3179 $active_plugin = array();
3180 $all_plugins = fs_get_plugins();
3181 $active_plugins_basenames = self::get_active_plugins_basenames( $blog_id );
3182
3183 foreach ( $active_plugins_basenames as $plugin_basename ) {
3184 $active_plugin[ $plugin_basename ] = $all_plugins[ $plugin_basename ];
3185 }
3186
3187 return $active_plugin;
3188 }
3189
3190 /**
3191 * Get collection of all site active plugins for a specified blog.
3192 *
3193 * @author Vova Feldman (@svovaf)
3194 * @since 2.0.0
3195 *
3196 * @param int $blog_id
3197 *
3198 * @return array[string]array
3199 */
3200 private static function get_site_active_plugins( $blog_id = 0 ) {
3201 $active_basenames = ( is_multisite() && $blog_id > 0 ) ?
3202 get_blog_option( $blog_id, 'active_plugins' ) :
3203 get_option( 'active_plugins' );
3204
3205 $active = array();
3206
3207 if ( ! is_array( $active_basenames ) ) {
3208 return $active;
3209 }
3210
3211 foreach ( $active_basenames as $basename ) {
3212 $active[ $basename ] = array(
3213 'is_active' => true,
3214 'Version' => '1.0', // Dummy version.
3215 'slug' => self::get_plugin_slug( $basename ),
3216 );
3217 }
3218
3219 return $active;
3220 }
3221
3222 /**
3223 * Get collection of all plugins with their activation status for a specified blog.
3224 *
3225 * @author Vova Feldman (@svovaf)
3226 * @since 1.1.8
3227 *
3228 * @param int $blog_id Since 2.0.0
3229 *
3230 * @return array Key is the plugin file path and the value is an array of the plugin data.
3231 */
3232 private static function get_all_plugins( $blog_id = 0 ) {
3233 self::require_plugin_essentials();
3234
3235 $all_plugins = fs_get_plugins();
3236
3237 $active_plugins_basenames = self::get_active_plugins_basenames( $blog_id );
3238
3239 foreach ( $all_plugins as $basename => &$data ) {
3240 // By default set to inactive (next foreach update the active plugins).
3241 $data['is_active'] = false;
3242 // Enrich with plugin slug.
3243 $data['slug'] = self::get_plugin_slug( $basename );
3244 }
3245
3246 // Flag active plugins.
3247 foreach ( $active_plugins_basenames as $basename ) {
3248 if ( isset( $all_plugins[ $basename ] ) ) {
3249 $all_plugins[ $basename ]['is_active'] = true;
3250 }
3251 }
3252
3253 return $all_plugins;
3254 }
3255
3256 /**
3257 * Get collection of all plugins and if they are network level activated.
3258 *
3259 * @author Vova Feldman (@svovaf)
3260 * @since 2.0.0
3261 *
3262 * @return array Key is the plugin basename and the value is an array of the plugin data.
3263 */
3264 private static function get_network_plugins() {
3265 self::require_plugin_essentials();
3266
3267 $all_plugins = fs_get_plugins();
3268
3269 $network_active_basenames = is_multisite() ?
3270 get_site_option( 'active_sitewide_plugins' ) :
3271 array();
3272
3273 foreach ( $all_plugins as $basename => &$data ) {
3274 // By default set to inactive (next foreach update the active plugins).
3275 $data['is_active'] = false;
3276 // Enrich with plugin slug.
3277 $data['slug'] = self::get_plugin_slug( $basename );
3278 }
3279
3280 // Flag active plugins.
3281 foreach ( $network_active_basenames as $basename ) {
3282 if ( isset( $all_plugins[ $basename ] ) ) {
3283 $all_plugins[ $basename ]['is_active'] = true;
3284 }
3285 }
3286
3287 return $all_plugins;
3288 }
3289
3290 /**
3291 * Cached result of get_site_transient( 'update_plugins' )
3292 *
3293 * @author Vova Feldman (@svovaf)
3294 * @since 1.1.8
3295 *
3296 * @var object
3297 */
3298 private static $_plugins_info;
3299
3300 /**
3301 * Helper function to get specified plugin's slug.
3302 *
3303 * @author Vova Feldman (@svovaf)
3304 * @since 1.1.8
3305 *
3306 * @param $basename
3307 *
3308 * @return string
3309 */
3310 private static function get_plugin_slug( $basename ) {
3311 if ( ! isset( self::$_plugins_info ) ) {
3312 self::$_plugins_info = get_site_transient( 'update_plugins' );
3313 }
3314
3315 $slug = '';
3316
3317 if ( is_object( self::$_plugins_info ) ) {
3318 if ( isset( self::$_plugins_info->no_update ) &&
3319 isset( self::$_plugins_info->no_update[ $basename ] ) &&
3320 ! empty( self::$_plugins_info->no_update[ $basename ]->slug )
3321 ) {
3322 $slug = self::$_plugins_info->no_update[ $basename ]->slug;
3323 } else if ( isset( self::$_plugins_info->response ) &&
3324 isset( self::$_plugins_info->response[ $basename ] ) &&
3325 ! empty( self::$_plugins_info->response[ $basename ]->slug )
3326 ) {
3327 $slug = self::$_plugins_info->response[ $basename ]->slug;
3328 }
3329 }
3330
3331 if ( empty( $slug ) ) {
3332 // Try to find slug from FS data.
3333 $slug = self::find_slug_by_basename( $basename );
3334 }
3335
3336 if ( empty( $slug ) ) {
3337 // Fallback to plugin's folder name.
3338 $slug = dirname( $basename );
3339 }
3340
3341 return $slug;
3342 }
3343
3344 private static $_statics_loaded = false;
3345
3346 /**
3347 * Load static resources.
3348 *
3349 * @author Vova Feldman (@svovaf)
3350 * @since 1.0.1
3351 */
3352 private static function _load_required_static() {
3353 if ( self::$_statics_loaded ) {
3354 return;
3355 }
3356
3357 self::$_static_logger = FS_Logger::get_logger( WP_FS__SLUG, WP_FS__DEBUG_SDK, WP_FS__ECHO_DEBUG_SDK );
3358
3359 self::$_static_logger->entrance();
3360
3361 self::$_accounts = FS_Options::instance( WP_FS__ACCOUNTS_OPTION_NAME, true );
3362
3363 if ( is_multisite() ) {
3364 $has_skipped_migration = (
3365 // 'id_slug_type_path_map' - was never stored on older versions, therefore, not exists on the site level.
3366 null === self::$_accounts->get_option( 'id_slug_type_path_map', null, false ) &&
3367 // 'file_slug_map' stored on the site level, so it was running an SDK version before it was integrated with MS-network.
3368 null !== self::$_accounts->get_option( 'file_slug_map', null, false )
3369 );
3370
3371 /**
3372 * If the file_slug_map exists on the site level but doesn't exist on the
3373 * network level storage, it means that we need to process the storage with migration.
3374 *
3375 * The code in this `if` scope will only be executed once and only for the first site that will execute it because once we migrate the storage data, file_slug_map will be already set in the network level storage.
3376 *
3377 * @author Vova Feldman (@svovaf)
3378 * @since 2.0.0
3379 */
3380 if (
3381 ( $has_skipped_migration && true !== self::$_accounts->get_option( 'ms_migration_complete', false, true ) ) ||
3382 ( null === self::$_accounts->get_option( 'file_slug_map', null, true ) &&
3383 null !== self::$_accounts->get_option( 'file_slug_map', null, false ) )
3384 ) {
3385 self::migrate_options_to_network();
3386 }
3387 }
3388
3389 self::$_global_admin_notices = FS_Admin_Notices::instance( 'global' );
3390
3391 if ( ! WP_FS__DEMO_MODE ) {
3392 add_action( ( fs_is_network_admin() ? 'network_' : '' ) . 'admin_menu', array(
3393 'Freemius',
3394 '_add_debug_section'
3395 ) );
3396 }
3397
3398 add_action( "wp_ajax_fs_toggle_debug_mode", array( 'Freemius', '_toggle_debug_mode' ) );
3399
3400 self::add_ajax_action_static( 'get_debug_log', array( 'Freemius', '_get_debug_log' ) );
3401
3402 self::add_ajax_action_static( 'get_db_option', array( 'Freemius', '_get_db_option' ) );
3403
3404 self::add_ajax_action_static( 'set_db_option', array( 'Freemius', '_set_db_option' ) );
3405
3406 if ( 0 == did_action( 'plugins_loaded' ) ) {
3407 add_action( 'plugins_loaded', array( 'Freemius', '_load_textdomain' ), 1 );
3408 }
3409
3410 $clone_manager = FS_Clone_Manager::instance();
3411 add_action( 'init', array( $clone_manager, '_init' ) );
3412
3413 add_action( 'admin_footer', array( 'Freemius', '_open_support_forum_in_new_page' ) );
3414
3415 if ( self::is_plugins_page() || self::is_themes_page() ) {
3416 add_action( 'admin_print_footer_scripts', array( 'Freemius', '_maybe_add_beta_label_styles' ), 9 );
3417
3418 /**
3419 * Specifically use this hook so that the JS event handlers will work properly on the "Themes"
3420 * page.
3421 *
3422 * @author Leo Fajardo (@leorw)
3423 * @since 2.3.0
3424 */
3425 add_action( 'admin_footer-' . self::get_current_page(), array( 'Freemius', '_maybe_add_beta_label_to_plugins_and_handle_confirmation') );
3426 }
3427
3428 self::$_statics_loaded = true;
3429 }
3430
3431 #--------------------------------------------------------------------------------
3432 #region Clone
3433 #--------------------------------------------------------------------------------
3434
3435 /**
3436 * @author Leo Fajardo (@leorw)
3437 * @since 2.5.0
3438 *
3439 * @param bool $only_if_manual_resolution_is_not_hidden
3440 *
3441 * @return bool
3442 */
3443 private function is_unresolved_clone( $only_if_manual_resolution_is_not_hidden = false ) {
3444 if ( ! $this->is_clone( $only_if_manual_resolution_is_not_hidden ) ) {
3445 return false;
3446 }
3447
3448 return FS_Clone_Manager::instance()->has_temporary_duplicate_mode_expired();
3449 }
3450
3451 /**
3452 * @author Leo Fajardo (@leorw)
3453 * @since 2.5.0
3454 *
3455 * @param bool $only_if_manual_resolution_is_not_hidden
3456 */
3457 function is_clone( $only_if_manual_resolution_is_not_hidden = false ) {
3458 if ( ! is_object( $this->_site ) ) {
3459 return false;
3460 }
3461
3462 $blog_id = null;
3463
3464 if (
3465 fs_is_network_admin() &&
3466 FS_Site::is_valid_id( $this->_storage->network_install_blog_id )
3467 ) {
3468 // Ensure that we're comparing the network install's URL with the relevant subsite's URL.
3469 $blog_id = $this->_storage->network_install_blog_id;
3470 }
3471
3472 $site_url = Freemius::get_unfiltered_site_url( $blog_id, true, true );
3473
3474 if ( ! $this->_site->is_clone( $site_url ) ) {
3475 return false;
3476 }
3477
3478 return (
3479 ! $only_if_manual_resolution_is_not_hidden ||
3480 ! FS_Clone_Manager::instance()->should_hide_manual_resolution()
3481 );
3482 }
3483
3484 /**
3485 * @author Leo Fajardo (@leorw)
3486 * @since 2.5.0
3487 *
3488 * @param int|null $blog_id
3489 * @param bool $strip_protocol
3490 * @param bool $add_trailing_slash
3491 *
3492 * @return string
3493 */
3494 static function get_unfiltered_site_url( $blog_id = null, $strip_protocol = false, $add_trailing_slash = false ) {
3495 global $wp_filter;
3496
3497 $site_url_filters = array(
3498 'site_url' => null,
3499 'pre_option_siteurl' => null,
3500 'default_option_siteurl' => null,
3501 'option_siteurl' => null,
3502 );
3503
3504 // Detach all URL-related filters to get the actual site's URL (stripped of potential manipulations by multilingual plugins).
3505 foreach ( $site_url_filters as $hook_name => $site_url_filter ) {
3506 if ( ! empty( $wp_filter[ $hook_name ] ) ) {
3507 $site_url_filters[ $hook_name ] = $wp_filter[ $hook_name ];
3508 unset( $wp_filter[ $hook_name ] );
3509 }
3510 }
3511
3512 $url = get_site_url( $blog_id );
3513
3514 // Re-attach the filters back.
3515 foreach ( $site_url_filters as $hook_name => $site_url_filter ) {
3516 if ( ! empty( $site_url_filter ) ) {
3517 $wp_filter[ $hook_name ] = $site_url_filter;
3518 }
3519 }
3520
3521 if ( $strip_protocol ) {
3522 $url = fs_strip_url_protocol( $url );
3523 }
3524
3525 if ( $add_trailing_slash ) {
3526 $url = trailingslashit( $url );
3527 }
3528
3529 return $url;
3530 }
3531
3532 /**
3533 * @author Leo Fajardo (@leorw)
3534 * @since 2.5.0
3535 *
3536 * @param number $site_id
3537 */
3538 function fetch_install_by_id( $site_id ) {
3539 return $this->get_current_or_network_user_api_scope()->get( "/installs/{$site_id}.json" );
3540 }
3541
3542 /**
3543 * @author Leo Fajardo (@leorw)
3544 * @since 2.5.0
3545 *
3546 * @return string|object|bool
3547 */
3548 function _handle_long_term_duplicate() {
3549 $this->_logger->entrance();
3550
3551 $this->delete_current_install( false );
3552
3553 $license_key = false;
3554
3555 if (
3556 is_object( $this->_license ) &&
3557 ! $this->_license->is_utilized(
3558 ( WP_FS__IS_LOCALHOST_FOR_SERVER || FS_Site::is_localhost_by_address( self::get_unfiltered_site_url() ) )
3559 )
3560 ) {
3561 $license_key = $this->_license->secret_key;
3562 }
3563
3564 return $this->opt_in(
3565 false,
3566 false,
3567 false,
3568 $license_key,
3569 false,
3570 false,
3571 false,
3572 null,
3573 array(),
3574 false
3575 );
3576 }
3577
3578 #endregion
3579
3580 /**
3581 * @author Leo Fajardo (@leorw)
3582 *
3583 * @since 2.1.3
3584 */
3585 private static function migrate_options_to_network() {
3586 self::migrate_accounts_to_network();
3587
3588 // Migrate API options from site level to network level.
3589 $api_network_options = FS_Option_Manager::get_manager( WP_FS__OPTIONS_OPTION_NAME, true, true );
3590 $api_network_options->migrate_to_network();
3591
3592 // Migrate API cache to network level storage.
3593 FS_Cache_Manager::get_manager( WP_FS__API_CACHE_OPTION_NAME )->migrate_to_network();
3594
3595 self::$_accounts->set_option( 'ms_migration_complete', true, true );
3596 }
3597
3598 #----------------------------------------------------------------------------------
3599 #region Localization
3600 #----------------------------------------------------------------------------------
3601
3602 /**
3603 * Load framework's text domain.
3604 *
3605 * @author Vova Feldman (@svovaf)
3606 * @since 1.2.1
3607 */
3608 static function _load_textdomain() {
3609 if ( ! is_admin() ) {
3610 return;
3611 }
3612
3613 global $fs_active_plugins;
3614
3615 // Works both for plugins and themes.
3616 load_plugin_textdomain(
3617 'freemius',
3618 false,
3619 $fs_active_plugins->newest->sdk_path . '/languages/'
3620 );
3621 }
3622
3623 #endregion
3624
3625 #----------------------------------------------------------------------------------
3626 #region Debugging
3627 #----------------------------------------------------------------------------------
3628
3629 /**
3630 * @author Vova Feldman (@svovaf)
3631 * @since 1.0.8
3632 */
3633 static function _add_debug_section() {
3634 if ( ! is_super_admin() ) {
3635 // Add debug page only for super-admins.
3636 return;
3637 }
3638
3639 self::$_static_logger->entrance();
3640
3641 $title = sprintf( '%s [v.%s]', fs_text_inline( 'Freemius Debug' ), WP_FS__SDK_VERSION );
3642
3643 if ( WP_FS__DEV_MODE ) {
3644 // Add top-level debug menu item.
3645 $hook = FS_Admin_Menu_Manager::add_page(
3646 $title,
3647 $title,
3648 'manage_options',
3649 'freemius',
3650 array( 'Freemius', '_debug_page_render' )
3651 );
3652 } else {
3653 // Add hidden debug page.
3654 $hook = FS_Admin_Menu_Manager::add_subpage(
3655 '',
3656 $title,
3657 $title,
3658 'manage_options',
3659 'freemius',
3660 array( 'Freemius', '_debug_page_render' )
3661 );
3662 }
3663
3664 if ( ! empty( $hook ) ) {
3665 add_action( "load-$hook", array( 'Freemius', '_debug_page_actions' ) );
3666 }
3667 }
3668
3669 /**
3670 * @author Vova Feldman (@svovaf)
3671 * @since 1.1.7.3
3672 */
3673 static function _toggle_debug_mode() {
3674 check_admin_referer( 'fs_toggle_debug_mode' );
3675
3676 if ( ! is_super_admin() ) {
3677 return;
3678 }
3679
3680 $is_on = fs_request_get( 'is_on', false, 'post' );
3681
3682 if ( fs_request_is_post() && in_array( $is_on, array( 0, 1 ) ) ) {
3683 update_option( 'fs_debug_mode', $is_on );
3684
3685 // Turn on/off storage logging.
3686 FS_Logger::_set_storage_logging( ( 1 == $is_on ) );
3687 }
3688
3689 exit;
3690 }
3691
3692 /**
3693 * @author Vova Feldman (@svovaf)
3694 * @since 1.2.1.6
3695 */
3696 static function _get_debug_log() {
3697 check_admin_referer( 'fs_get_debug_log' );
3698
3699 if ( ! is_super_admin() ) {
3700 return;
3701 }
3702
3703 $limit = min( ! empty( $_POST['limit'] ) ? absint( $_POST['limit'] ) : 200, 200 );
3704 $offset = min( ! empty( $_POST['offset'] ) ? absint( $_POST['offset'] ) : 200, 200 );
3705
3706 $logs = FS_Logger::load_db_logs(
3707 fs_request_get( 'filters', false, 'post' ),
3708 $limit,
3709 $offset
3710 );
3711
3712 self::shoot_ajax_success( $logs );
3713 }
3714
3715 /**
3716 * @author Vova Feldman (@svovaf)
3717 * @since 1.2.1.7
3718 */
3719 static function _get_db_option() {
3720 check_admin_referer( 'fs_get_db_option' );
3721
3722 $option_name = fs_request_get( 'option_name' );
3723
3724 if ( ! is_super_admin() ||
3725 ! fs_starts_with( $option_name, 'fs_' )
3726 ) {
3727 self::shoot_ajax_failure();
3728 }
3729
3730 $value = get_option( $option_name );
3731
3732 $result = array(
3733 'name' => $option_name,
3734 );
3735
3736 if ( false !== $value ) {
3737 if ( ! is_string( $value ) ) {
3738 $value = json_encode( $value );
3739 }
3740
3741 $result['value'] = $value;
3742 }
3743
3744 self::shoot_ajax_success( $result );
3745 }
3746
3747 /**
3748 * @author Vova Feldman (@svovaf)
3749 * @since 1.2.1.7
3750 */
3751 static function _set_db_option() {
3752 check_admin_referer( 'fs_set_db_option' );
3753
3754 $option_name = fs_request_get( 'option_name' );
3755
3756 if ( ! is_super_admin() ||
3757 ! fs_starts_with( $option_name, 'fs_' )
3758 ) {
3759 self::shoot_ajax_failure();
3760 }
3761
3762 $option_value = fs_request_get( 'option_value' );
3763
3764 if ( ! empty( $option_value ) ) {
3765 update_option( $option_name, $option_value );
3766 }
3767
3768 self::shoot_ajax_success();
3769 }
3770
3771 /**
3772 * @author Vova Feldman (@svovaf)
3773 * @since 1.0.8
3774 */
3775 static function _debug_page_actions() {
3776 self::_clean_admin_content_section();
3777
3778 if ( fs_request_is_action( 'restart_freemius' ) ) {
3779 check_admin_referer( 'restart_freemius' );
3780
3781 if ( ! is_multisite() ) {
3782 // Clear accounts data.
3783 self::$_accounts->clear( null, true );
3784 } else {
3785 $sites = self::get_sites();
3786 foreach ( $sites as $site ) {
3787 $blog_id = self::get_site_blog_id( $site );
3788 self::$_accounts->clear( $blog_id, true );
3789 }
3790
3791 // Clear network level storage.
3792 self::$_accounts->clear( true, true );
3793 }
3794
3795 // Clear SDK reference cache.
3796 delete_option( 'fs_active_plugins' );
3797 } else if ( fs_request_is_action( 'clear_updates_data' ) ) {
3798 check_admin_referer( 'clear_updates_data' );
3799
3800 if ( ! is_multisite() ) {
3801 set_site_transient( 'update_plugins', null );
3802 set_site_transient( 'update_themes', null );
3803 } else {
3804 $current_blog_id = get_current_blog_id();
3805
3806 $sites = self::get_sites();
3807 foreach ( $sites as $site ) {
3808 switch_to_blog( self::get_site_blog_id( $site ) );
3809
3810 set_site_transient( 'update_plugins', null );
3811 set_site_transient( 'update_themes', null );
3812 }
3813
3814 switch_to_blog( $current_blog_id );
3815 }
3816 } else if ( fs_request_is_action( 'reset_deactivation_snoozing' ) ) {
3817 check_admin_referer( 'reset_deactivation_snoozing' );
3818
3819 self::reset_deactivation_snoozing();
3820 } else if ( fs_request_is_action( 'simulate_trial' ) ) {
3821 check_admin_referer( 'simulate_trial' );
3822
3823 $fs = freemius( fs_request_get( 'module_id' ) );
3824
3825 // Update SDK install to at least 24 hours before.
3826 $fs->_storage->install_timestamp = ( time() - WP_FS__TIME_24_HOURS_IN_SEC );
3827 // Unset the trial shown timestamp.
3828 unset( $fs->_storage->trial_promotion_shown );
3829 } else if ( fs_request_is_action( 'simulate_network_upgrade' ) ) {
3830 check_admin_referer( 'simulate_network_upgrade' );
3831
3832 $fs = freemius( fs_request_get( 'module_id' ) );
3833
3834 self::set_network_upgrade_mode( $fs->_storage );
3835 } else if ( fs_request_is_action( 'delete_install' ) ) {
3836 check_admin_referer( 'delete_install' );
3837
3838 self::_delete_site_by_slug(
3839 fs_request_get( 'slug' ),
3840 fs_request_get( 'module_type' ),
3841 true,
3842 fs_request_get( 'blog_id', null )
3843 );
3844 } else if ( fs_request_is_action( 'delete_user' ) ) {
3845 check_admin_referer( 'delete_user' );
3846
3847 self::delete_user( fs_request_get( 'user_id' ) );
3848 } else if ( fs_request_is_action( 'download_logs' ) ) {
3849 check_admin_referer( 'download_logs' );
3850
3851 $download_url = FS_Logger::download_db_logs(
3852 fs_request_get( 'filters', false, 'post' )
3853 );
3854
3855 if ( false === $download_url ) {
3856 wp_die( 'Oops... there was an error while generating the logs download file. Please try again and if it doesn\'t work contact support@freemius.com.' );
3857 }
3858
3859 fs_redirect( $download_url );
3860 } else if ( fs_request_is_action( 'migrate_options_to_network' ) ) {
3861 check_admin_referer( 'migrate_options_to_network' );
3862
3863 self::migrate_options_to_network();
3864 }
3865 }
3866
3867 /**
3868 * @author Leo Fajardo (@leorw)
3869 * @since 2.5.0
3870 *
3871 * @return array
3872 */
3873 static function get_all_modules_sites() {
3874 self::$_static_logger->entrance();
3875
3876 $sites_by_type = array(
3877 WP_FS__MODULE_TYPE_PLUGIN => array(),
3878 WP_FS__MODULE_TYPE_THEME => array(),
3879 );
3880
3881 $module_types = array_keys( $sites_by_type );
3882
3883 if ( ! is_multisite() ) {
3884 foreach ( $module_types as $type ) {
3885 $sites_by_type[ $type ] = self::get_all_sites( $type );
3886
3887 foreach ( $sites_by_type[ $type ] as $slug => $install ) {
3888 $sites_by_type[ $type ][ $slug ] = array( $install );
3889 }
3890 }
3891 } else {
3892 $sites = self::get_sites();
3893
3894 foreach ( $sites as $site ) {
3895 $blog_id = self::get_site_blog_id( $site );
3896
3897 foreach ( $module_types as $type ) {
3898 $installs = self::get_all_sites( $type, $blog_id );
3899
3900 foreach ( $installs as $slug => $install ) {
3901 if ( ! isset( $sites_by_type[ $type ][ $slug ] ) ) {
3902 $sites_by_type[ $type ][ $slug ] = array();
3903 }
3904
3905 $install->blog_id = $blog_id;
3906
3907 $sites_by_type[ $type ][ $slug ][] = $install;
3908 }
3909
3910 }
3911 }
3912 }
3913
3914 return $sites_by_type;
3915 }
3916
3917 /**
3918 * @author Vova Feldman (@svovaf)
3919 * @since 1.0.8
3920 */
3921 static function _debug_page_render() {
3922 self::$_static_logger->entrance();
3923
3924 $all_modules_sites = self::get_all_modules_sites();
3925
3926 $licenses_by_module_type = self::get_all_licenses_by_module_type();
3927
3928 $vars = array(
3929 'plugin_sites' => $all_modules_sites[ WP_FS__MODULE_TYPE_PLUGIN ],
3930 'theme_sites' => $all_modules_sites[ WP_FS__MODULE_TYPE_THEME ],
3931 'users' => self::get_all_users(),
3932 'addons' => self::get_all_addons(),
3933 'account_addons' => self::get_all_account_addons(),
3934 'plugin_licenses' => $licenses_by_module_type[ WP_FS__MODULE_TYPE_PLUGIN ],
3935 'theme_licenses' => $licenses_by_module_type[ WP_FS__MODULE_TYPE_THEME ]
3936 );
3937
3938 fs_enqueue_local_style( 'fs_debug', '/admin/debug.css' );
3939 fs_require_once_template( 'debug.php', $vars );
3940 }
3941
3942 #endregion
3943
3944 #----------------------------------------------------------------------------------
3945 #region Connectivity Issues
3946 #----------------------------------------------------------------------------------
3947
3948 /**
3949 * Check if Freemius should be turned on for the current plugin install.
3950 *
3951 * Note:
3952 * $this->_is_on is updated in has_api_connectivity()
3953 *
3954 * @author Vova Feldman (@svovaf)
3955 * @since 1.0.9
3956 *
3957 * @return bool
3958 */
3959 function is_on() {
3960 self::$_static_logger->entrance();
3961
3962 if ( is_object( $this->_site ) && ! $this->is_registered() ) {
3963 return false;
3964 }
3965
3966 if ( isset( $this->_is_on ) ) {
3967 return $this->_is_on;
3968 }
3969
3970 // If already installed or pending then sure it's on :)
3971 if ( $this->is_registered() || $this->is_pending_activation() ) {
3972 $this->_is_on = true;
3973
3974 return true;
3975 }
3976
3977 return false;
3978 }
3979
3980 /**
3981 * @author Vova Feldman (@svovaf)
3982 * @since 1.1.7.3
3983 *
3984 * @param bool $flush_if_no_connectivity
3985 *
3986 * @return bool
3987 */
3988 private function should_run_connectivity_test( $flush_if_no_connectivity = false ) {
3989 if ( ! isset( $this->_storage->connectivity_test ) ) {
3990 // Connectivity test was never executed, or cache was cleared.
3991 return true;
3992 }
3993
3994 if ( WP_FS__PING_API_ON_IP_OR_HOST_CHANGES ) {
3995 if ( WP_FS__IS_HTTP_REQUEST ) {
3996 if ( $_SERVER['HTTP_HOST'] != $this->_storage->connectivity_test['host'] ) {
3997 // Domain changed.
3998 return true;
3999 }
4000
4001 if ( WP_FS__REMOTE_ADDR != $this->_storage->connectivity_test['server_ip'] ) {
4002 // Server IP changed.
4003 return true;
4004 }
4005 }
4006 }
4007
4008 if ( $this->_storage->connectivity_test['is_connected'] &&
4009 $this->_storage->connectivity_test['is_active']
4010 ) {
4011 // API connected and Freemius is active - no need to run connectivity check.
4012 return false;
4013 }
4014
4015 if ( $flush_if_no_connectivity ) {
4016 /**
4017 * If explicitly asked to flush when no connectivity - do it only
4018 * if at least 10 sec passed from the last API connectivity test.
4019 */
4020 return ( isset( $this->_storage->connectivity_test['timestamp'] ) &&
4021 ( WP_FS__SCRIPT_START_TIME - $this->_storage->connectivity_test['timestamp'] ) > 10 );
4022 }
4023
4024 /**
4025 * @since 1.1.7 Don't check for connectivity on plugin downgrade.
4026 */
4027 $version = $this->get_plugin_version();
4028 if ( version_compare( $version, $this->_storage->connectivity_test['version'], '>' ) ) {
4029 // If it's a plugin version upgrade and Freemius is off or no connectivity, run connectivity test.
4030 return true;
4031 }
4032
4033 return false;
4034 }
4035
4036 /**
4037 * @author Leo Fajardo (@leorw)
4038 * @since 2.5.4
4039 *
4040 * @param bool $is_update
4041 *
4042 * @return bool
4043 */
4044 private function should_turn_fs_on( $is_update = true ) {
4045 if (
4046 empty( $this->_plugin->opt_in_moderation ) ||
4047 ! is_array( $this->_plugin->opt_in_moderation )
4048 ) {
4049 return true;
4050 }
4051
4052 $optin_config = $this->_plugin->opt_in_moderation;
4053
4054 if (
4055 WP_FS__IS_LOCALHOST &&
4056 ( ! isset( $optin_config['localhost'] ) || false !== $optin_config['localhost'] )
4057 ) {
4058 return true;
4059 }
4060
4061 $optin_config_key = $is_update ?
4062 'updates' :
4063 'new';
4064
4065 if ( ! isset( $optin_config[ $optin_config_key ] ) ) {
4066 return true;
4067 }
4068
4069 $visibility_percentage = $optin_config[ $optin_config_key ];
4070
4071 if ( 0 == $visibility_percentage ) {
4072 return false;
4073 }
4074
4075 if ( ! is_numeric( $visibility_percentage ) ) {
4076 return true;
4077 }
4078
4079 $min = 1;
4080 $max = 100;
4081
4082 if ( function_exists( 'random_int' ) ) {
4083 $random = random_int( $min, $max );
4084 } else {
4085 $random = rand( $min, $max );
4086 }
4087
4088 return ( $random <= $visibility_percentage );
4089 }
4090
4091 /**
4092 * Check if there's any connectivity issue to Freemius API.
4093 *
4094 * @author Vova Feldman (@svovaf)
4095 * @since 1.0.9
4096 *
4097 * @param bool $flush_if_no_connectivity
4098 *
4099 * @return bool|null
4100 */
4101 function has_api_connectivity( $flush_if_no_connectivity = false ) {
4102 $this->_logger->entrance();
4103
4104 if ( isset( $this->_has_api_connection ) && ( $this->_has_api_connection || ! $flush_if_no_connectivity ) ) {
4105 return $this->_has_api_connection;
4106 }
4107
4108 if ( WP_FS__SIMULATE_NO_API_CONNECTIVITY &&
4109 isset( $this->_storage->connectivity_test ) &&
4110 true === $this->_storage->connectivity_test['is_connected']
4111 ) {
4112 $this->clear_connectivity_info();
4113 }
4114
4115 if ( ! $this->should_run_connectivity_test( $flush_if_no_connectivity ) ) {
4116 $this->_has_api_connection = $this->_storage->connectivity_test['is_connected'];
4117 /**
4118 * @since 1.1.6 During dev mode, if there's connectivity - turn Freemius on regardless the configuration.
4119 *
4120 * @since 1.2.1.5 If the user running the premium version then ignore the 'is_active' flag and turn Freemius on to enable license key activation.
4121 */
4122 $this->_is_on = $this->_storage->connectivity_test['is_active'] ||
4123 $this->is_premium() ||
4124 ( WP_FS__DEV_MODE && $this->_has_api_connection && ! WP_FS__SIMULATE_FREEMIUS_OFF );
4125
4126 return $this->_has_api_connection;
4127 }
4128
4129 if (
4130 ! empty( $this->_storage->connectivity_test ) &&
4131 isset( $this->_storage->connectivity_test['is_active'] )
4132 ) {
4133 $is_active = $this->_storage->connectivity_test['is_active'];
4134 } else {
4135 $is_active = $this->should_turn_fs_on( $this->apply_filters( 'is_plugin_update', $this->is_plugin_update() ) );
4136
4137 $this->store_connectivity_info( (object) array( 'is_active' => $is_active ), null );
4138 }
4139
4140 if ( $is_active ) {
4141 $this->_is_on = true;
4142 }
4143
4144 return $this->_has_api_connection;
4145 }
4146
4147 /**
4148 * @author Leo Fajardo (@leorw)
4149 * @since 2.5.4
4150 */
4151 private function clear_connectivity_info() {
4152 unset( $this->_storage->connectivity_test );
4153
4154 FS_Api::clear_force_http_flag();
4155 }
4156
4157 /**
4158 * @author Vova Feldman (@svovaf)
4159 * @since 1.1.7.4
4160 *
4161 * @param object $pong
4162 * @param bool|null $is_connected
4163 */
4164 private function store_connectivity_info( $pong, $is_connected ) {
4165 $this->_logger->entrance();
4166
4167 $version = $this->get_plugin_version();
4168
4169 if ( false === $is_connected || WP_FS__SIMULATE_FREEMIUS_OFF ) {
4170 $is_active = false;
4171 } else {
4172 $is_active = ( isset( $pong->is_active ) && true == $pong->is_active );
4173 }
4174
4175 $is_active = $this->apply_filters(
4176 'is_on',
4177 $is_active,
4178 $this->is_plugin_update(),
4179 $version
4180 );
4181
4182 $this->_storage->connectivity_test = array(
4183 'is_connected' => $is_connected,
4184 'host' => $_SERVER['HTTP_HOST'],
4185 'server_ip' => WP_FS__REMOTE_ADDR,
4186 'is_active' => $is_active,
4187 'timestamp' => WP_FS__SCRIPT_START_TIME,
4188 // Last version with connectivity attempt.
4189 'version' => $version,
4190 );
4191
4192 $this->_has_api_connection = $is_connected;
4193 $this->_is_on = $is_active || ( WP_FS__DEV_MODE && $is_connected && ! WP_FS__SIMULATE_FREEMIUS_OFF );
4194 }
4195
4196 /**
4197 * @author Leo Fajardo (@leorw)
4198 * @since 2.5.4
4199 *
4200 * @param bool $is_connected
4201 */
4202 private function update_connectivity_info( $is_connected ) {
4203 $this->store_connectivity_info(
4204 // This is true since we update the connection info only after a successful opt-in or license activation which means that Freemius has already been on even before the process.
4205 (object) array( 'is_active' => true ),
4206 $is_connected
4207 );
4208 }
4209
4210 /**
4211 * Force turning Freemius on.
4212 *
4213 * @author Vova Feldman (@svovaf)
4214 * @since 1.1.8.1
4215 *
4216 * @return bool TRUE if successfully turned on.
4217 */
4218 private function turn_on() {
4219 $this->_logger->entrance();
4220
4221 if ( $this->is_on() || ! isset( $this->_storage->connectivity_test['is_active'] ) ) {
4222 return false;
4223 }
4224
4225 $updated_connectivity = $this->_storage->connectivity_test;
4226 $updated_connectivity['is_active'] = true;
4227 $updated_connectivity['timestamp'] = WP_FS__SCRIPT_START_TIME;
4228 $this->_storage->connectivity_test = $updated_connectivity;
4229
4230 $this->_is_on = true;
4231
4232 return true;
4233 }
4234
4235 /**
4236 * Anonymous and unique site identifier (Hash).
4237 *
4238 * @author Vova Feldman (@svovaf)
4239 * @since 1.1.0
4240 *
4241 * @param null|int $blog_id Since 2.0.0
4242 *
4243 * @return string
4244 */
4245 function get_anonymous_id( $blog_id = null ) {
4246 $unique_id = self::$_accounts->get_option( 'unique_id', null, $blog_id );
4247
4248 if ( empty( $unique_id ) || ! is_string( $unique_id ) ) {
4249 $key = self::get_unfiltered_site_url( $blog_id, true );
4250
4251 $secure_auth = defined( 'SECURE_AUTH_KEY' ) ? SECURE_AUTH_KEY : '';
4252 if ( empty( $secure_auth ) ||
4253 false !== strpos( $secure_auth, ' ' ) ||
4254 'put your unique phrase here' === $secure_auth
4255 ) {
4256 // Protect against default auth key.
4257 $secure_auth = md5( microtime() );
4258 }
4259
4260 /**
4261 * Base the unique identifier on the WP secure authentication key. Which
4262 * turns the key into a secret anonymous identifier. This will help us
4263 * to avoid duplicate installs generation on the backend upon opt-in.
4264 *
4265 * @author Vova Feldman (@svovaf)
4266 * @since 1.2.3
4267 */
4268 $unique_id = md5( $key . $secure_auth );
4269
4270 self::$_accounts->set_option( 'unique_id', $unique_id, true, $blog_id );
4271 }
4272
4273 $this->_logger->departure( $unique_id );
4274
4275 return $unique_id;
4276 }
4277
4278 /**
4279 * Returns anonymous network ID.
4280 *
4281 * @since 2.4.3
4282 *
4283 * @return string
4284 */
4285 function get_anonymous_network_id() {
4286 return $this->get_anonymous_id( get_network()->site_id );
4287 }
4288
4289 /**
4290 * @author Vova Feldman (@svovaf)
4291 * @since 1.1.7.4
4292 *
4293 * @return \WP_User
4294 */
4295 static function _get_current_wp_user() {
4296 self::require_pluggable_essentials();
4297 self::wp_cookie_constants();
4298
4299 return wp_get_current_user();
4300 }
4301
4302 /**
4303 * Define cookie constants which are required by Freemius::_get_current_wp_user() since
4304 * it uses wp_get_current_user() which needs the cookie constants set. When a plugin
4305 * is network activated the cookie constants are only configured after the network
4306 * plugins activation, therefore, if we don't define those constants WP will throw
4307 * PHP warnings/notices.
4308 *
4309 * @author Vova Feldman (@svovaf)
4310 * @since 2.1.1
4311 */
4312 private static function wp_cookie_constants() {
4313 if ( defined( 'LOGGED_IN_COOKIE' ) &&
4314 ( defined( 'AUTH_COOKIE' ) || defined( 'SECURE_AUTH_COOKIE' ) )
4315 ) {
4316 return;
4317 }
4318
4319 /**
4320 * Used to guarantee unique hash cookies
4321 *
4322 * @since 1.5.0
4323 */
4324 if ( ! defined( 'COOKIEHASH' ) ) {
4325 $siteurl = get_site_option( 'siteurl' );
4326 if ( $siteurl ) {
4327 define( 'COOKIEHASH', md5( $siteurl ) );
4328 } else {
4329 define( 'COOKIEHASH', '' );
4330 }
4331 }
4332
4333 if ( ! defined( 'LOGGED_IN_COOKIE' ) ) {
4334 define( 'LOGGED_IN_COOKIE', 'wordpress_logged_in_' . COOKIEHASH );
4335 }
4336
4337 /**
4338 * @since 2.5.0
4339 */
4340 if ( ! defined( 'AUTH_COOKIE' ) ) {
4341 define( 'AUTH_COOKIE', 'wordpress_' . COOKIEHASH );
4342 }
4343
4344 /**
4345 * @since 2.6.0
4346 */
4347 if ( ! defined( 'SECURE_AUTH_COOKIE' ) ) {
4348 define( 'SECURE_AUTH_COOKIE', 'wordpress_sec_' . COOKIEHASH );
4349 }
4350 }
4351
4352 /**
4353 * @author Vova Feldman (@svovaf)
4354 * @since 2.1.0
4355 *
4356 * @return int
4357 */
4358 static function get_current_wp_user_id() {
4359 $wp_user = self::_get_current_wp_user();
4360
4361 return $wp_user->ID;
4362 }
4363
4364 /**
4365 * @author Vova Feldman (@svovaf)
4366 * @since 1.2.1.7
4367 *
4368 * @param string $email
4369 *
4370 * @return bool
4371 */
4372 static function is_valid_email( $email ) {
4373 if ( false === filter_var( $email, FILTER_VALIDATE_EMAIL ) ) {
4374 return false;
4375 }
4376
4377 $parts = explode( '@', $email );
4378
4379 if ( 2 !== count( $parts ) || empty( $parts[1] ) ) {
4380 return false;
4381 }
4382
4383 $blacklist = array(
4384 'admin.',
4385 'webmaster.',
4386 'localhost.',
4387 'dev.',
4388 'development.',
4389 'test.',
4390 'stage.',
4391 'staging.',
4392 );
4393
4394 // Make sure domain is not one of the blacklisted.
4395 foreach ( $blacklist as $invalid ) {
4396 if ( 0 === strpos( $parts[1], $invalid ) ) {
4397 return false;
4398 }
4399 }
4400
4401 // Get the UTF encoded domain name.
4402 $domain = idn_to_ascii( $parts[1] ) . '.';
4403
4404 return ( checkdnsrr( $domain, 'MX' ) || checkdnsrr( $domain, 'A' ) );
4405 }
4406
4407 #endregion
4408
4409 #----------------------------------------------------------------------------------
4410 #region Email
4411 #----------------------------------------------------------------------------------
4412
4413 /**
4414 * Generates and sends an HTML email with customizable sections.
4415 *
4416 * @author Leo Fajardo (@leorw)
4417 * @since 1.1.2
4418 *
4419 * @param string $to_address
4420 * @param string $subject
4421 * @param array $sections
4422 * @param array $headers
4423 *
4424 * @return bool Whether the email contents were sent successfully.
4425 */
4426 private function send_email(
4427 $to_address,
4428 $subject,
4429 $sections = array(),
4430 $headers = array()
4431 ) {
4432 $default_sections = $this->get_email_sections();
4433
4434 // Insert new sections or replace the default email sections.
4435 if ( is_array( $sections ) && ! empty( $sections ) ) {
4436 foreach ( $sections as $section_id => $custom_section ) {
4437 if ( ! isset( $default_sections[ $section_id ] ) ) {
4438 // If the section does not exist, add it.
4439 $default_sections[ $section_id ] = $custom_section;
4440 } else {
4441 // If the section already exists, override it.
4442 $current_section = $default_sections[ $section_id ];
4443
4444 // Replace the current section's title if a custom section title exists.
4445 if ( isset( $custom_section['title'] ) ) {
4446 $current_section['title'] = $custom_section['title'];
4447 }
4448
4449 // Insert new rows under the current section or replace the default rows.
4450 if ( isset( $custom_section['rows'] ) && is_array( $custom_section['rows'] ) && ! empty( $custom_section['rows'] ) ) {
4451 foreach ( $custom_section['rows'] as $row_id => $row ) {
4452 $current_section['rows'][ $row_id ] = $row;
4453 }
4454 }
4455
4456 $default_sections[ $section_id ] = $current_section;
4457 }
4458 }
4459 }
4460
4461 $vars = array( 'sections' => $default_sections );
4462 $message = fs_get_template( 'email.php', $vars );
4463
4464 // Set the type of email to HTML.
4465 $headers[] = 'Content-type: text/html; charset=UTF-8';
4466
4467 $header_string = implode( "\r\n", $headers );
4468
4469 return wp_mail(
4470 $to_address,
4471 $subject,
4472 $message,
4473 $header_string
4474 );
4475 }
4476
4477 /**
4478 * Generates the data for the sections of the email content.
4479 *
4480 * @author Leo Fajardo (@leorw)
4481 * @since 1.1.2
4482 *
4483 * @return array
4484 */
4485 private function get_email_sections() {
4486 // Retrieve the current user's information so that we can get the user's email, first name, and last name below.
4487 $current_user = self::_get_current_wp_user();
4488
4489 // Retrieve the cURL version information so that we can get the version number below.
4490 $curl_version_information = curl_version();
4491
4492 $active_plugin = self::get_active_plugins();
4493
4494 // Generate the list of active plugins separated by new line.
4495 $active_plugin_string = '';
4496 foreach ( $active_plugin as $plugin ) {
4497 $active_plugin_string .= sprintf(
4498 '<a href="%s">%s</a> [v%s]<br>',
4499 $plugin['PluginURI'],
4500 $plugin['Name'],
4501 $plugin['Version']
4502 );
4503 }
4504
4505 $server_ip = WP_FS__REMOTE_ADDR;
4506
4507 // Add PHP info for deeper investigation.
4508 ob_start();
4509 phpinfo();
4510 $php_info = ob_get_clean();
4511
4512 $api_domain = substr( FS_API__ADDRESS, strpos( FS_API__ADDRESS, ':' ) + 3 );
4513
4514 // Generate the default email sections.
4515 $sections = array(
4516 'sdk' => array(
4517 'title' => 'SDK',
4518 'rows' => array(
4519 'fs_version' => array( 'FS Version', $this->version ),
4520 'curl_version' => array( 'cURL Version', $curl_version_information['version'] )
4521 )
4522 ),
4523 'plugin' => array(
4524 'title' => ucfirst( $this->get_module_type() ),
4525 'rows' => array(
4526 'name' => array( 'Name', $this->get_plugin_name() ),
4527 'version' => array( 'Version', $this->get_plugin_version() )
4528 )
4529 ),
4530 'api' => array(
4531 'title' => 'API Subdomain',
4532 'rows' => array(
4533 'dns' => array(
4534 'DNS_CNAME',
4535 function_exists( 'dns_get_record' ) ?
4536 var_export( dns_get_record( $api_domain, DNS_CNAME ), true ) :
4537 'dns_get_record() disabled/blocked'
4538 ),
4539 'ip' => array(
4540 'IP',
4541 function_exists( 'gethostbyname' ) ?
4542 gethostbyname( $api_domain ) :
4543 'gethostbyname() disabled/blocked'
4544 ),
4545 ),
4546 ),
4547 'site' => array(
4548 'title' => 'Site',
4549 'rows' => array(
4550 'unique_id' => array( 'Unique ID', $this->get_anonymous_id() ),
4551 'address' => array( 'Address', site_url() ),
4552 'host' => array(
4553 'HTTP_HOST',
4554 ( ! empty( $_SERVER['HTTP_HOST'] ) ? $_SERVER['HTTP_HOST'] : '' )
4555 ),
4556 'hosting' => array(
4557 'Hosting Company' => fs_request_has( 'hosting_company' ) ?
4558 fs_request_get( 'hosting_company' ) :
4559 'Unknown',
4560 ),
4561 'server_addr' => array(
4562 'SERVER_ADDR',
4563 '<a href="http://www.projecthoneypot.org/ip_' . $server_ip . '">' . $server_ip . '</a>'
4564 )
4565 )
4566 ),
4567 'user' => array(
4568 'title' => 'User',
4569 'rows' => array(
4570 'email' => array( 'Email', $current_user->user_email ),
4571 'first' => array( 'First', $current_user->user_firstname ),
4572 'last' => array( 'Last', $current_user->user_lastname )
4573 )
4574 ),
4575 'plugins' => array(
4576 'title' => 'Plugins',
4577 'rows' => array(
4578 'active_plugins' => array( 'Active Plugins', $active_plugin_string )
4579 )
4580 ),
4581 'php_info' => array(
4582 'title' => 'PHP Info',
4583 'rows' => array(
4584 'info' => array( $php_info )
4585 ),
4586 )
4587 );
4588
4589 // Allow the sections to be modified by other code.
4590 $sections = $this->apply_filters( 'email_template_sections', $sections );
4591
4592 return $sections;
4593 }
4594
4595 #endregion
4596
4597 #----------------------------------------------------------------------------------
4598 #region Initialization
4599 #----------------------------------------------------------------------------------
4600
4601 /**
4602 * Init plugin's Freemius instance.
4603 *
4604 * @author Vova Feldman (@svovaf)
4605 * @since 1.0.1
4606 *
4607 * @param number $id
4608 * @param string $public_key
4609 * @param bool $is_live
4610 * @param bool $is_premium
4611 */
4612 function init( $id, $public_key, $is_live = true, $is_premium = true ) {
4613 $this->_logger->entrance();
4614
4615 $this->dynamic_init( array(
4616 'id' => $id,
4617 'public_key' => $public_key,
4618 'is_live' => $is_live,
4619 'is_premium' => $is_premium,
4620 ) );
4621 }
4622
4623 /**
4624 * Dynamic initiator, originally created to support initiation
4625 * with parent_id for add-ons.
4626 *
4627 * @author Vova Feldman (@svovaf)
4628 * @since 1.0.6
4629 *
4630 * @param array $plugin_info
4631 *
4632 * @throws Freemius_Exception
4633 */
4634 function dynamic_init( array $plugin_info ) {
4635 $this->_logger->entrance();
4636
4637 $this->parse_settings( $plugin_info );
4638
4639 $this->register_after_settings_parse_hooks();
4640
4641 /**
4642 * If anonymous but there's already a user entity and the user's site is associated with a valid license or trial period, update the anonymous mode accordingly.
4643 *
4644 * @todo Remove this entire `if` block after several releases as starting from this version, the anonymous mode will already be updated accordingly after a purchase.
4645 */
4646 if ( $this->is_anonymous() ) {
4647 $is_network_level = ( $this->_is_network_active && fs_is_network_admin() );
4648
4649 if (
4650 ! $is_network_level ||
4651 FS_Site::is_valid_id( $this->_storage->network_install_blog_id )
4652 ) {
4653 if ( $this->is_paying_or_trial() ) {
4654 $this->reset_anonymous_mode( $is_network_level );
4655 }
4656 } else {
4657 $network = get_network();
4658
4659 if ( is_object( $network ) ) {
4660 $main_blog_id = $network->site_id;
4661 $first_install = $this->get_install_by_blog_id( $main_blog_id );
4662
4663 if ( is_object( $first_install ) ) {
4664 $this->_storage->network_install_blog_id = $main_blog_id;
4665 $this->_storage->network_user_id = $first_install->user_id;
4666 }
4667 }
4668 }
4669 }
4670
4671 if ( $this->should_stop_execution() ) {
4672 return;
4673 }
4674
4675 if ( ! $this->is_registered() ) {
4676 if ( $this->is_anonymous() ) {
4677 // If user skipped, no need to test connectivity.
4678 $this->_has_api_connection = true;
4679 $this->_is_on = true;
4680 } else {
4681 if ( false === $this->has_api_connectivity() ) {
4682 return;
4683 } else {
4684 if ( $this->_anonymous_mode ) {
4685 // Simulate anonymous mode.
4686 $this->_is_anonymous = true;
4687 }
4688 }
4689 }
4690 }
4691
4692 /**
4693 * This should be executed even if Freemius is off for the core module,
4694 * otherwise, the add-ons dialog box won't work properly. This is especially
4695 * relevant when the developer decided to turn FS off for existing users.
4696 *
4697 * @author Vova Feldman (@svovaf)
4698 */
4699 if ( $this->is_user_in_admin() &&
4700 'plugin-information' === fs_request_get( 'tab', false ) &&
4701 $this->should_use_freemius_updater_and_dialog() &&
4702 (
4703 ( $this->is_addon() && $this->get_slug() == fs_request_get( 'plugin', false ) ) ||
4704 ( $this->has_addons() && $this->get_id() == fs_request_get( 'parent_plugin_id', false ) )
4705 )
4706 ) {
4707 require_once WP_FS__DIR_INCLUDES . '/fs-plugin-info-dialog.php';
4708
4709 new FS_Plugin_Info_Dialog( $this->is_addon() ? $this->get_parent_instance() : $this );
4710 }
4711
4712 // Check if Freemius is on for the current plugin.
4713 // This MUST be executed after all the plugin variables has been loaded.
4714 if ( ! $this->is_registered() && ! $this->is_on() ) {
4715 return;
4716 }
4717
4718 if ( $this->has_api_connectivity() ) {
4719 if ( self::is_cron() ) {
4720 $this->hook_callback_to_sync_cron();
4721 } else if ( $this->is_user_in_admin() ) {
4722 /**
4723 * Schedule daily data sync cron if:
4724 *
4725 * 1. User opted-in (for tracking).
4726 * 2. If skipped, but later upgraded (opted-in via upgrade).
4727 *
4728 * @author Vova Feldman (@svovaf)
4729 * @since 1.1.7.3
4730 *
4731 */
4732 if ( $this->is_registered() && $this->is_tracking_allowed() ) {
4733 $this->maybe_schedule_sync_cron();
4734 }
4735
4736 /**
4737 * Check if requested for manual blocking background sync.
4738 */
4739 if ( fs_request_has( 'background_sync' ) ) {
4740 self::require_pluggable_essentials();
4741 self::wp_cookie_constants();
4742
4743 $this->run_manual_sync();
4744 }
4745 }
4746 }
4747
4748 if ( $this->is_registered() ) {
4749 FS_Clone_Manager::instance()->maybe_resolve_new_subsite_install_automatically( $this );
4750
4751 $this->hook_callback_to_install_sync();
4752 }
4753
4754 if ( $this->is_addon() ) {
4755 if ( $this->is_parent_plugin_installed() ) {
4756 // Link to parent FS.
4757 $this->_parent = self::get_instance_by_id( $this->_plugin->parent_plugin_id );
4758
4759 // Get parent plugin reference.
4760 $this->_parent_plugin = $this->_parent->get_plugin();
4761 }
4762 }
4763
4764 if ( $this->is_user_in_admin() ) {
4765 if ( $this->is_registered() && fs_request_has( 'purchase_completed' ) ) {
4766 $this->_admin_notices->add_sticky(
4767 sprintf(
4768 /* translators: %s: License type (e.g. you have a professional license) */
4769 $this->get_text_inline( 'You have purchased a %s license.', 'you-have-x-license' ),
4770 fs_request_get( 'purchased_plan' )
4771 ) .
4772 sprintf(
4773 $this->get_text_inline(" The %s's %sdownload link%s, license key, and installation instructions have been sent to %s. If you can't find the email after 5 min, please check your spam box.", 'post-purchase-email-sent-message' ),
4774 $this->get_module_label( true ),
4775 ( FS_Plugin::is_valid_id( $this->get_bundle_id() ) ? "products' " : '' ),
4776 ( FS_Plugin::is_valid_id( $this->get_bundle_id() ) ? 's' : '' ),
4777 sprintf(
4778 '<strong>%s</strong>',
4779 fs_request_get( 'purchase_email' )
4780 )
4781 ),
4782 'plan_purchased',
4783 $this->get_text_x_inline( 'Yee-haw', 'interjection expressing joy or exuberance', 'yee-haw' ) . '!'
4784 );
4785 }
4786
4787 if ( $this->is_addon() ) {
4788 if ( ! $this->is_parent_plugin_installed() ) {
4789 $parent_name = $this->get_option( $plugin_info, 'parent_name', null );
4790
4791 if ( isset( $plugin_info['parent'] ) ) {
4792 $parent_name = $this->get_option( $plugin_info['parent'], 'name', null );
4793 }
4794
4795 $this->_admin_notices->add(
4796 ( ! empty( $parent_name ) ?
4797 sprintf( $this->get_text_x_inline( '%s cannot run without %s.', 'addonX cannot run without pluginY', 'addon-x-cannot-run-without-y' ), $this->get_plugin_name(), $parent_name ) :
4798 sprintf( $this->get_text_x_inline( '%s cannot run without the plugin.', 'addonX cannot run...', 'addon-x-cannot-run-without-parent' ), $this->get_plugin_name() )
4799 ),
4800 $this->get_text_x_inline( 'Oops', 'exclamation', 'oops' ) . '...',
4801 'error'
4802 );
4803
4804 return;
4805 } else {
4806 $is_network_admin = fs_is_network_admin();
4807
4808 if ( ! $this->_parent->is_registered() && $this->is_registered() ) {
4809 // If add-on activated and parent not, automatically install parent for the user.
4810 $this->activate_parent_account( $this->_parent );
4811 } else if (
4812 $this->_parent->is_registered() &&
4813 ! $this->is_registered() &&
4814 /**
4815 * If not registered for add-on and the following conditions for the add-on are met, activate add-on account.
4816 * * Network active and in network admin - network activate add-on account.
4817 * * Network active and not in network admin - activate add-on account for the current blog.
4818 * * Not network active and not in network admin - activate add-on account for the current blog.
4819 *
4820 * If not registered for add-on, not network active, and in network admin, do not handle the add-on activation.
4821 *
4822 * @author Leo Fajardo (@leorw)
4823 * @since 2.3.0
4824 */
4825 ( $this->is_network_active() || ! $is_network_admin )
4826 ) {
4827 $premium_license = null;
4828
4829 if (
4830 ! $this->has_free_plan() &&
4831 $this->is_bundle_license_auto_activation_enabled() &&
4832 $this->_parent->is_activated_with_bundle_license()
4833 ) {
4834 /**
4835 * If the add-on has no free plan, try to activate the account only when there's a bundle license.
4836 *
4837 * @author Leo Fajardo (@leorw)
4838 * @since 2.4.0
4839 */
4840 $bundle_license = $this->get_active_parent_license( $this->_parent->_get_license()->secret_key, false );
4841
4842 if (
4843 is_object( $bundle_license ) &&
4844 ! empty( $bundle_license->products ) &&
4845 in_array( $this->get_id(), $bundle_license->products )
4846 ) {
4847 $premium_license = $bundle_license;
4848 }
4849 }
4850
4851 if ( $this->has_free_plan() || is_object( $premium_license) ) {
4852 // If parent plugin activated, automatically install add-on for the user.
4853 $this->_activate_addon_account(
4854 $this->_parent,
4855 ( $this->is_network_active() && $is_network_admin ) ?
4856 true :
4857 get_current_blog_id(),
4858 $premium_license
4859 );
4860 }
4861 }
4862
4863 // @todo This should be only executed on activation. It should be migrated to register_activation_hook() together with other activation related logic.
4864 if ( $this->is_premium() ) {
4865 // Remove add-on download admin-notice.
4866 $this->_parent->_admin_notices->remove_sticky( array(
4867 'addon_plan_upgraded_' . $this->_slug,
4868 'no_addon_license_' . $this->_slug,
4869 ) );
4870 }
4871
4872 // $this->deactivate_premium_only_addon_without_license();
4873 }
4874 }
4875
4876 add_action( 'admin_init', array( &$this, '_admin_init_action' ) );
4877
4878 // if ( $this->is_registered() ||
4879 // $this->is_anonymous() ||
4880 // $this->is_pending_activation()
4881 // ) {
4882 // $this->_init_admin();
4883 // }
4884 }
4885
4886 /**
4887 * Should be called outside `$this->is_user_in_admin()` scope
4888 * because the updater has some logic that needs to be executed
4889 * during AJAX calls.
4890 *
4891 * Currently, we need to hook to the `http_request_host_is_external` filter.
4892 * In the future, there might be additional logic added.
4893 *
4894 * @author Vova Feldman
4895 * @since 1.2.1.6
4896 */
4897 if (
4898 $this->should_use_freemius_updater_and_dialog() &&
4899 (
4900 $this->is_premium() ||
4901 /**
4902 * If not premium but the premium version is installed, also instantiate the updater so that the
4903 * plugin information dialog of the premium version will have the information from the server.
4904 *
4905 * @author Leo Fajardo (@leorw)
4906 * @since 2.2.3
4907 */
4908 ( file_exists( fs_normalize_path( WP_PLUGIN_DIR . '/' . $this->premium_plugin_basename() ) ) )
4909 ) &&
4910 $this->has_release_on_freemius() &&
4911 ( ! $this->is_unresolved_clone( true ) )
4912 ) {
4913 FS_Plugin_Updater::instance( $this );
4914 }
4915
4916 $this->do_action( 'initiated' );
4917
4918 if ( $this->_storage->prev_is_premium !== $this->_plugin->is_premium ) {
4919 if ( isset( $this->_storage->prev_is_premium ) ) {
4920 $this->apply_filters(
4921 'after_code_type_change',
4922 // New code type.
4923 $this->_plugin->is_premium
4924 );
4925 } else {
4926 // Set for code type for the first time.
4927 $this->_storage->prev_is_premium = $this->_plugin->is_premium;
4928 }
4929 }
4930
4931 if ( ! $this->is_addon() ) {
4932 if ( $this->is_registered() ) {
4933 // Fix for upgrade from versions < 1.0.9.
4934 if ( ! isset( $this->_storage->activation_timestamp ) ) {
4935 $this->_storage->activation_timestamp = WP_FS__SCRIPT_START_TIME;
4936 }
4937
4938 $this->do_action( 'after_init_plugin_registered' );
4939 } else if ( $this->is_anonymous() ) {
4940 $this->do_action( 'after_init_plugin_anonymous' );
4941 } else if ( $this->is_pending_activation() ) {
4942 $this->do_action( 'after_init_plugin_pending_activations' );
4943 }
4944 } else {
4945 if ( $this->is_registered() ) {
4946 $this->do_action( 'after_init_addon_registered' );
4947 } else if ( $this->is_anonymous() ) {
4948 $this->do_action( 'after_init_addon_anonymous' );
4949 } else if ( $this->is_pending_activation() ) {
4950 $this->do_action( 'after_init_addon_pending_activations' );
4951 }
4952 }
4953 }
4954
4955 /**
4956 * @author Leo Fajardo (@leorw)
4957 * @since 2.2.3
4958 *
4959 * @return bool
4960 */
4961 private function should_use_freemius_updater_and_dialog() {
4962 return (
4963 /**
4964 * Allow updater and dialog when the `fs_allow_updater_and_dialog` URL query param exists and has `true`
4965 * value, or when the current page is not the "Add Plugins" page (/plugin-install.php) and the `action`
4966 * URL query param doesn't exist or its value is not `install-plugin` so that there will be no conflicts
4967 * with the .org plugins' functionalities (e.g. installation from the "Add Plugins" page and viewing
4968 * plugin details from .org).
4969 */
4970 ( true === fs_request_get_bool( 'fs_allow_updater_and_dialog' ) ) ||
4971 (
4972 ! self::is_plugin_install_page() &&
4973 // Disallow updater and dialog when installing a plugin, otherwise .org "add-on" plugins will be affected.
4974 ( 'install-plugin' !== fs_request_get( 'action' ) )
4975 )
4976 );
4977 }
4978
4979 /**
4980 * @param string[] $permissions
4981 * @param bool $is_enabled
4982 * @param int|null $blog_id
4983 *
4984 * @return true|object `true` on success, API error object on failure.
4985 */
4986 private function update_site_permissions( array $permissions, $is_enabled, $blog_id = null ) {
4987 $this->_logger->entrance();
4988
4989 $params = array(
4990 'permissions' => implode( ',', $permissions ),
4991 'is_enabled' => $is_enabled,
4992 );
4993
4994 $current_blog_id = get_current_blog_id();
4995 $is_blog_switched = false;
4996 if ( is_numeric( $blog_id ) && $current_blog_id != $blog_id ) {
4997 $is_blog_switched = $this->switch_to_blog( $blog_id );
4998 }
4999
5000 $result = $this->api_site_call( '/permissions.json', 'put', $params );
5001
5002 if ( $is_blog_switched ) {
5003 $this->switch_to_blog( $current_blog_id );
5004 }
5005
5006 if (
5007 ! $this->is_api_result_object( $result ) ||
5008 ! isset( $result->install_id )
5009 ) {
5010 $this->_logger->api_error( $result );
5011
5012 return $result;
5013 }
5014
5015 return true;
5016 }
5017
5018 /**
5019 * @param string[] $permissions
5020 * @param bool $is_enabled
5021 * @param bool $has_site_delegated_connection
5022 *
5023 * @return true|object `true` on success, API error object on failure.
5024 */
5025 private function update_network_permissions(
5026 array $permissions,
5027 $is_enabled,
5028 &$has_site_delegated_connection
5029 ) {
5030 $this->_logger->entrance();
5031
5032 $install_id_2_blog_id = array();
5033 $install_by_blog_id = $this->get_blog_install_map();
5034
5035 $has_site_delegated_connection = false;
5036
5037 foreach ( $install_by_blog_id as $blog_id => $install ) {
5038 if ( $this->is_site_delegated_connection( $blog_id ) ) {
5039 // Only update permissions of non-delegated installs.
5040 $has_site_delegated_connection = true;
5041 continue;
5042 }
5043
5044 $install_id_2_blog_id[ $install->id ] = $blog_id;
5045 }
5046
5047 if ( empty( $install_id_2_blog_id ) ) {
5048 return true;
5049 }
5050
5051 $params = array(
5052 'permissions' => implode( ',', $permissions ),
5053 'is_enabled' => $is_enabled,
5054 'install_ids' => implode( ',', array_keys( $install_id_2_blog_id ) ),
5055 );
5056
5057 // Send update to FS.
5058 $result = $this->get_current_or_network_user_api_scope()->call(
5059 "/plugins/{$this->_module_id}/installs/permissions.json",
5060 'put',
5061 $params
5062 );
5063
5064 if ( ! $this->is_api_result_object( $result, 'installs_metadata' ) ) {
5065 $this->_logger->api_error( $result );
5066
5067 return $result;
5068 }
5069
5070 return true;
5071 }
5072
5073 /**
5074 * @param mixed $result
5075 *
5076 * @return string
5077 */
5078 private function get_api_error_message( $result ) {
5079 $error_message = sprintf( $this->get_text_inline( 'There was an unexpected API error while processing your request. Please try again in a few minutes and if it still doesn\'t work, contact the %s\'s author with the following:',
5080 'unexpected-api-error' ), $this->_module_type ) . ' ';
5081
5082 if (
5083 $this->is_api_error( $result ) &&
5084 isset( $result->error )
5085 ) {
5086 $code = empty( $result->error->code ) ? '' : " Code: {$result->error->code}";
5087
5088 $error_message .= "<b>{$result->error->message}{$code}</b>";
5089 } else {
5090 $error_message .= var_export( $result, true );
5091 }
5092
5093 return $error_message;
5094 }
5095
5096 /**
5097 * @author Vova Feldman (@svovaf)
5098 * @since 2.5.1
5099 */
5100 function _toggle_permission_tracking_callback() {
5101 $this->_logger->entrance();
5102
5103 $this->check_ajax_referer( 'toggle_permission_tracking' );
5104
5105 if ( ! $this->is_registered( true ) ) {
5106 self::shoot_ajax_failure( 'User never opted-in.' );
5107 }
5108
5109 $is_enabled = fs_request_get_bool( 'is_enabled' );
5110 $permissions = fs_request_get( 'permissions' );
5111
5112 if ( ! is_string( $permissions ) ) {
5113 self::shoot_ajax_failure( 'The permissions param must be a string.' );
5114 }
5115
5116 $permissions = explode( ',', $permissions );
5117
5118 $result = $this->toggle_permission_tracking( $permissions, $is_enabled );
5119
5120 if ( true !== $result ) {
5121 self::shoot_ajax_failure( $this->get_api_error_message( $result ) );
5122 }
5123
5124 self::shoot_ajax_success();
5125 }
5126
5127 /**
5128 * @param string[] $permissions
5129 * @param bool $is_enabled
5130 * @param int|null $blog_id
5131 *
5132 * @return bool|mixed `true` if updated successfully or no update is needed.
5133 */
5134 private function toggle_permission_tracking( $permissions, $is_enabled, $blog_id = null ) {
5135 if ( ! $this->is_registered( true ) ) {
5136 // User never opted-in.
5137 return false;
5138 }
5139
5140 // Check if permissions are already set as needed.
5141 if ( FS_Permission_Manager::instance( $this )->are_permissions( $permissions, $is_enabled, $blog_id ) ) {
5142 /**
5143 * Note:
5144 * When running on the network admin, there's no need to iterate through all the installs individually since network opt-in permissions are managed for ALL non-delegated installs through a single option (per permission) on the network-level storage.
5145 */
5146 return true;
5147 }
5148
5149 $api_managed_permissions = array_intersect(
5150 $permissions,
5151 FS_Permission_Manager::get_api_managed_permission_ids()
5152 );
5153
5154 if (
5155 in_array( FS_Permission_Manager::PERMISSION_ESSENTIALS, $permissions ) &&
5156 ! in_array( FS_Permission_Manager::PERMISSION_SITE, $permissions )
5157 ) {
5158 $api_managed_permissions[] = FS_Permission_Manager::PERMISSION_SITE;
5159 }
5160
5161 if ( ! empty( $api_managed_permissions ) ) {
5162 $has_site_delegated_connection = false;
5163
5164 if (
5165 ! $is_enabled &&
5166 ! in_array( FS_Permission_Manager::PERMISSION_EXTENSIONS, $api_managed_permissions ) &&
5167 false === FS_Permission_Manager::instance( $this )->is_extensions_tracking_allowed( $blog_id )
5168 ) {
5169 /**
5170 * If we are turning off a permission and the extensions permission is off too, enrich the permissions update request to also turn off extensions tracking, as currently when opting in with extensions tracking disabled the extensions tracking is off but the API isn't aware of it.
5171 *
5172 * @todo Remove this entire `if` after implementing granular opt-in that also sends the permissions to the API when opting in.
5173 */
5174 $api_managed_permissions[] = FS_Permission_Manager::PERMISSION_EXTENSIONS;
5175 }
5176
5177 if ( is_null( $blog_id ) && fs_is_network_admin() ) {
5178 $result = $this->update_network_permissions(
5179 $api_managed_permissions,
5180 $is_enabled,
5181 $has_site_delegated_connection
5182 );
5183 } else {
5184 $result = $this->update_site_permissions(
5185 $api_managed_permissions,
5186 $is_enabled,
5187 $blog_id
5188 );
5189 }
5190
5191 if ( true !== $result ) {
5192 return $result;
5193 }
5194
5195 if ( in_array( FS_Permission_Manager::PERMISSION_SITE, $api_managed_permissions ) ) {
5196 if ( $is_enabled ) {
5197 $this->schedule_sync_cron();
5198 } else {
5199 $this->clear_sync_cron( ! $has_site_delegated_connection );
5200 }
5201 }
5202
5203 if ( in_array( FS_Permission_Manager::PERMISSION_USER, $api_managed_permissions ) ) {
5204 $this->toggle_user_permission( $is_enabled, $blog_id );
5205 }
5206 }
5207
5208 $this->update_tracking_permissions(
5209 $permissions,
5210 $is_enabled,
5211 $blog_id
5212 );
5213
5214 return true;
5215 }
5216
5217 /**
5218 * @param bool $is_enabled
5219 * @param int|null $blog_id
5220 */
5221 private function toggle_user_permission( $is_enabled, $blog_id = null ) {
5222 $network_or_blog_ids = is_numeric( $blog_id ) ?
5223 $blog_id :
5224 fs_is_network_admin();
5225
5226 if ( $is_enabled ) {
5227 $this->reset_anonymous_mode( $network_or_blog_ids );
5228 } else {
5229 $this->skip_connection( $network_or_blog_ids );
5230 }
5231 }
5232
5233 /**
5234 * Opt-in back into usage tracking.
5235 *
5236 * Note: This will only work if the user opted-in previously.
5237 *
5238 * Returns:
5239 * 1. FALSE - If the user never opted-in.
5240 * 2. TRUE - If successfully opted-in back to usage tracking.
5241 * 3. object - API result on failure.
5242 *
5243 * @author Leo Fajardo (@leorw)
5244 * @since 1.2.1.5
5245 *
5246 * @bool $is_enabled
5247 *
5248 * @return bool|object
5249 */
5250 private function toggle_site_tracking( $is_enabled, $blog_id = null ) {
5251 $this->_logger->entrance();
5252
5253 return $this->toggle_permission_tracking(
5254 FS_Permission_Manager::instance( $this )->get_site_tracking_permission_names(),
5255 $is_enabled,
5256 $blog_id
5257 );
5258 }
5259
5260 /**
5261 * If user opted-in and later disabled usage-tracking,
5262 * re-allow tracking for licensing and updates.
5263 *
5264 * @author Leo Fajardo (@leorw)
5265 * @since 1.2.1.5
5266 *
5267 * @param bool $is_context_single_site
5268 */
5269 private function reconnect_locally( $is_context_single_site = false ) {
5270 $this->_logger->entrance();
5271
5272 if ( ! $this->is_registered() ) {
5273 return;
5274 }
5275
5276 if ( ! fs_is_network_admin() || $is_context_single_site ) {
5277 if ( $this->is_tracking_prohibited() ) {
5278 FS_Permission_Manager::instance( $this )->update_site_tracking( true );
5279 }
5280 } else {
5281 $installs_map = $this->get_blog_install_map();
5282 foreach ( $installs_map as $blog_id => $install ) {
5283 /**
5284 * @var FS_Site $install
5285 */
5286 if ( ! $this->is_tracking_allowed( $blog_id, $install ) ) {
5287 FS_Permission_Manager::instance( $this )->update_site_tracking( true, $blog_id );
5288 }
5289 }
5290 }
5291 }
5292
5293 /**
5294 * Update permission tracking flags. When updating in a network context, in addition to updating the network-level flags, also update the permissions on the site-level for all non-delegated sites.
5295 *
5296 * @param string[] $permissions
5297 * @param bool $is_enabled
5298 * @param int|null $blog_id
5299 *
5300 * @return array
5301 */
5302 private function update_tracking_permissions( $permissions, $is_enabled, $blog_id = null ) {
5303 // Alias.
5304 $permission_manager = FS_Permission_Manager::instance( $this );
5305
5306 $network_or_blog_ids = is_numeric( $blog_id ) ?
5307 $blog_id :
5308 fs_is_network_admin();
5309
5310 if ( true === $network_or_blog_ids ) {
5311 // Update the permission for all non-delegated sub-sites.
5312 $blog_ids = $this->get_non_delegated_blog_ids();
5313
5314 // Add the network-level to the array, to update the permission on the network-level storage.
5315 array_unshift( $blog_ids, null );
5316 }
5317 else
5318 {
5319 if ( false === $network_or_blog_ids ) {
5320 $network_or_blog_ids = null;
5321 }
5322
5323 $blog_ids = is_array( $network_or_blog_ids ) ?
5324 $network_or_blog_ids :
5325 array( $network_or_blog_ids );
5326 }
5327
5328 $result = array();
5329 foreach ( $permissions as $permission ) {
5330 $permission = trim( $permission );
5331 $is_permission_supported = true;
5332
5333 foreach ( $blog_ids as $id ) {
5334 $is_permission_supported = $permission_manager->update_permission_tracking_flag(
5335 $permission,
5336 $is_enabled,
5337 $id
5338 );
5339 }
5340
5341 if ( ! $is_permission_supported ) {
5342 $permission = 'no_match';
5343 }
5344
5345 $result[ $permission ] = $is_enabled;
5346 }
5347
5348 return $result;
5349 }
5350
5351 /**
5352 * Parse plugin's settings (as defined by the plugin dev).
5353 *
5354 * @author Vova Feldman (@svovaf)
5355 * @since 1.1.7.3
5356 *
5357 * @param array $plugin_info
5358 *
5359 * @throws \Freemius_Exception
5360 */
5361 private function parse_settings( &$plugin_info ) {
5362 $this->_logger->entrance();
5363
5364 $id = $this->get_numeric_option( $plugin_info, 'id', false );
5365 $public_key = $this->get_option( $plugin_info, 'public_key', false );
5366 $secret_key = $this->get_option( $plugin_info, 'secret_key', null );
5367 $parent_id = $this->get_numeric_option( $plugin_info, 'parent_id', null );
5368 $parent_name = $this->get_option( $plugin_info, 'parent_name', null );
5369
5370 /**
5371 * @author Vova Feldman (@svovaf)
5372 * @since 1.1.9 Try to pull secret key from external config.
5373 */
5374 if ( is_null( $secret_key ) && defined( "WP_FS__{$this->_slug}_SECRET_KEY" ) ) {
5375 $secret_key = constant( "WP_FS__{$this->_slug}_SECRET_KEY" );
5376 }
5377
5378 if ( isset( $plugin_info['parent'] ) ) {
5379 $parent_id = $this->get_numeric_option( $plugin_info['parent'], 'id', null );
5380 // $parent_slug = $this->get_option( $plugin_info['parent'], 'slug', null );
5381 // $parent_public_key = $this->get_option( $plugin_info['parent'], 'public_key', null );
5382 // $parent_name = $this->get_option( $plugin_info['parent'], 'name', null );
5383 }
5384
5385 if ( false === $id ) {
5386 throw new Freemius_Exception( array(
5387 'error' => array(
5388 'type' => 'ParameterNotSet',
5389 'message' => 'Plugin id parameter is not set.',
5390 'code' => 'plugin_id_not_set',
5391 'http' => 500,
5392 )
5393 ) );
5394 }
5395 if ( false === $public_key ) {
5396 throw new Freemius_Exception( array(
5397 'error' => array(
5398 'type' => 'ParameterNotSet',
5399 'message' => 'Plugin public_key parameter is not set.',
5400 'code' => 'plugin_public_key_not_set',
5401 'http' => 500,
5402 )
5403 ) );
5404 }
5405
5406 $plugin = ( $this->_plugin instanceof FS_Plugin ) ?
5407 $this->_plugin :
5408 new FS_Plugin();
5409
5410 $premium_suffix = $this->get_option( $plugin_info, 'premium_suffix', '(Premium)' );
5411
5412 $plugin->update( array(
5413 'id' => $id,
5414 'type' => $this->get_option( $plugin_info, 'type', $this->_module_type ),
5415 'public_key' => $public_key,
5416 'slug' => $this->_slug,
5417 'premium_slug' => $this->get_option( $plugin_info, 'premium_slug', "{$this->_slug}-premium" ),
5418 'parent_plugin_id' => $parent_id,
5419 'version' => $this->get_plugin_version(),
5420 'title' => $this->get_plugin_name( $premium_suffix ),
5421 'file' => $this->_plugin_basename,
5422 'is_premium' => $this->get_bool_option( $plugin_info, 'is_premium', true ),
5423 'premium_suffix' => $premium_suffix,
5424 'is_live' => $this->get_bool_option( $plugin_info, 'is_live', true ),
5425 'affiliate_moderation' => $this->get_option( $plugin_info, 'has_affiliation' ),
5426 'bundle_id' => $this->get_option( $plugin_info, 'bundle_id', null ),
5427 'bundle_public_key' => $this->get_option( $plugin_info, 'bundle_public_key', null ),
5428 'opt_in_moderation' => $this->get_option( $plugin_info, 'opt_in', null ),
5429 ) );
5430
5431 if ( $plugin->is_updated() ) {
5432 // Update plugin details.
5433 $this->_plugin = FS_Plugin_Manager::instance( $this->_module_id )->store( $plugin );
5434 }
5435 // Set the secret key after storing the plugin, we don't want to store the key in the storage.
5436 $this->_plugin->secret_key = $secret_key;
5437
5438 /**
5439 * If the product is network integrated and activated and the current view is in the network level Admin dashboard, if the product's network-level menu located differently from the sub-site level, then use the network menu details (when set).
5440 *
5441 * @author Vova Feldman
5442 * @since 2.4.5
5443 */
5444 if ( $this->is_network_active() && fs_is_network_admin() ) {
5445 if ( isset( $plugin_info['menu_network'] ) &&
5446 is_array( $plugin_info['menu_network'] ) &&
5447 ! empty( $plugin_info['menu_network'] )
5448 ) {
5449 $plugin_info['menu'] = $plugin_info['menu_network'];
5450 }
5451 }
5452
5453 if ( ! isset( $plugin_info['menu'] ) ) {
5454 $plugin_info['menu'] = array();
5455
5456 if ( ! empty( $this->_storage->sdk_last_version ) &&
5457 version_compare( $this->_storage->sdk_last_version, '1.1.2', '<=' )
5458 ) {
5459 // Backward compatibility to 1.1.2
5460 $plugin_info['menu']['slug'] = isset( $plugin_info['menu_slug'] ) ?
5461 $plugin_info['menu_slug'] :
5462 $this->_slug;
5463 }
5464 }
5465
5466 $this->_menu = FS_Admin_Menu_Manager::instance(
5467 $this->_module_id,
5468 $this->_module_type,
5469 $this->get_unique_affix()
5470 );
5471
5472 $this->_menu->init( $plugin_info['menu'], $this->is_addon() );
5473
5474 $this->_has_addons = $this->get_bool_option( $plugin_info, 'has_addons', false );
5475 $this->_has_paid_plans = $this->get_bool_option( $plugin_info, 'has_paid_plans', true );
5476 $this->_has_premium_version = $this->get_bool_option( $plugin_info, 'has_premium_version', $this->_has_paid_plans );
5477 $this->_ignore_pending_mode = $this->get_bool_option( $plugin_info, 'ignore_pending_mode', false );
5478 $this->_is_org_compliant = $this->get_bool_option( $plugin_info, 'is_org_compliant', true );
5479 $this->_is_premium_only = $this->get_bool_option( $plugin_info, 'is_premium_only', false );
5480 if ( $this->_is_premium_only ) {
5481 // If premium only plugin, disable anonymous mode.
5482 $this->_enable_anonymous = false;
5483 $this->_anonymous_mode = false;
5484 } else {
5485 $this->_enable_anonymous = $this->get_bool_option( $plugin_info, 'enable_anonymous', true );
5486 $this->_anonymous_mode = $this->get_bool_option( $plugin_info, 'anonymous_mode', false );
5487 }
5488 $this->_permissions = $this->get_option( $plugin_info, 'permissions', array() );
5489 $this->_is_bundle_license_auto_activation_enabled = $this->get_option( $plugin_info, 'bundle_license_auto_activation', false );
5490
5491 if ( ! empty( $plugin_info['trial'] ) ) {
5492 $this->_trial_days = $this->get_numeric_option(
5493 $plugin_info['trial'],
5494 'days',
5495 // Default to 0 - trial without days specification.
5496 0
5497 );
5498
5499 $this->_is_trial_require_payment = $this->get_bool_option( $plugin_info['trial'], 'is_require_payment', false );
5500 }
5501
5502 $this->_navigation = $this->get_option(
5503 $plugin_info,
5504 'navigation',
5505 $this->is_free_wp_org_theme() ?
5506 self::NAVIGATION_TABS :
5507 self::NAVIGATION_MENU
5508 );
5509 }
5510
5511 /**
5512 * @param string[] $options
5513 * @param string $key
5514 * @param mixed $default
5515 *
5516 * @return bool
5517 */
5518 private function get_option( &$options, $key, $default = false ) {
5519 return ! empty( $options[ $key ] ) ? $options[ $key ] : $default;
5520 }
5521
5522 private function get_bool_option( &$options, $key, $default = false ) {
5523 return isset( $options[ $key ] ) && is_bool( $options[ $key ] ) ? $options[ $key ] : $default;
5524 }
5525
5526 private function get_numeric_option( &$options, $key, $default = false ) {
5527 return isset( $options[ $key ] ) && is_numeric( $options[ $key ] ) ? $options[ $key ] : $default;
5528 }
5529
5530 /**
5531 * Gate keeper.
5532 *
5533 * @author Vova Feldman (@svovaf)
5534 * @since 1.1.7.3
5535 *
5536 * @return bool
5537 */
5538 private function should_stop_execution() {
5539 if ( empty( $this->_storage->was_plugin_loaded ) ) {
5540 /**
5541 * Don't execute Freemius until plugin was fully loaded at least once,
5542 * to give the opportunity for the activation hook to run before pinging
5543 * the API for connectivity test. This logic is relevant for the
5544 * identification of new plugin install vs. plugin update.
5545 *
5546 * @author Vova Feldman (@svovaf)
5547 * @since 1.1.9
5548 */
5549 return true;
5550 }
5551
5552 if ( $this->is_activation_mode() ) {
5553 if ( ! is_admin() ) {
5554 /**
5555 * If in activation mode, don't execute Freemius outside the admin dashboard.
5556 *
5557 * @author Vova Feldman (@svovaf)
5558 * @since 1.1.7.3
5559 */
5560 return true;
5561 }
5562
5563 if ( ! WP_FS__IS_HTTP_REQUEST ) {
5564 /**
5565 * If in activation and executed without HTTP context (e.g. CLI, Cronjob),
5566 * then don't start Freemius.
5567 *
5568 * @author Vova Feldman (@svovaf)
5569 * @since 1.1.6.3
5570 *
5571 * @link https://wordpress.org/support/topic/errors-in-the-freemius-class-when-running-in-wordpress-in-cli
5572 */
5573 return true;
5574 }
5575
5576 if ( self::is_cron() ) {
5577 /**
5578 * If in activation mode, don't execute Freemius during wp crons
5579 * (wp crons have HTTP context - called as HTTP request).
5580 *
5581 * @author Vova Feldman (@svovaf)
5582 * @since 1.1.7.3
5583 */
5584 return true;
5585 }
5586
5587 if ( self::is_ajax() ) {
5588 /**
5589 * During activation, if running in AJAX mode, unless there's a sticky
5590 * connectivity issue notice, don't run Freemius.
5591 *
5592 * @author Vova Feldman (@svovaf)
5593 * @since 1.1.7.3
5594 */
5595 return true;
5596 }
5597 }
5598
5599 return false;
5600 }
5601
5602 /**
5603 * Triggered after code type has changed.
5604 *
5605 * @author Vova Feldman (@svovaf)
5606 * @since 1.1.9.1
5607 */
5608 function _after_code_type_change() {
5609 $this->_logger->entrance();
5610
5611 if ( $this->is_theme() ) {
5612 // Expire the cache of the previous tabs since the theme may
5613 // have setting updates after code type has changed.
5614 $this->_cache->expire( 'tabs' );
5615 $this->_cache->expire( 'tabs_stylesheets' );
5616 }
5617
5618 if ( $this->is_registered() ) {
5619 if ( ! $this->is_addon() ) {
5620 add_action(
5621 is_admin() ? 'admin_init' : 'init',
5622 array( &$this, '_plugin_code_type_changed' )
5623 );
5624 }
5625
5626 if ( $this->is_premium() ) {
5627 // Purge cached payments after switching to the premium version.
5628 // @todo This logic doesn't handle purging the cache for serviceware module upgrade.
5629 $this->get_api_user_scope()->purge_cache( "/plugins/{$this->_module_id}/payments.json?include_addons=true" );
5630 }
5631 }
5632 }
5633
5634 /**
5635 * Handles plugin's code type change (free <--> premium).
5636 *
5637 * @author Vova Feldman (@svovaf)
5638 * @since 1.0.9
5639 */
5640 function _plugin_code_type_changed() {
5641 $this->_logger->entrance();
5642
5643 if ( $this->is_premium() ) {
5644 $this->reconnect_locally();
5645
5646 // Activated premium code.
5647 $this->do_action( 'after_premium_version_activation' );
5648
5649 // Remove all sticky messages related to download of the premium version.
5650 $this->_admin_notices->remove_sticky( array(
5651 'trial_started',
5652 'plan_upgraded',
5653 'plan_changed',
5654 'license_activated',
5655 ) );
5656
5657 $notice = '';
5658 if ( ! $this->is_only_premium() ) {
5659 $notice = sprintf( $this->get_text_inline( 'Premium %s version was successfully activated.', 'premium-activated-message' ), $this->_module_type );
5660 }
5661
5662 $license_notice = $this->get_license_network_activation_notice();
5663 if ( ! empty( $license_notice ) ) {
5664 $notice .= ' ' . $license_notice;
5665 }
5666
5667 if ( ! empty( $notice ) ) {
5668 $this->_admin_notices->add_sticky(
5669 trim( $notice ),
5670 'premium_activated',
5671 $this->get_text_x_inline( 'W00t',
5672 'Used to express elation, enthusiasm, or triumph (especially in electronic communication).', 'woot' ) . '!'
5673 );
5674 }
5675 } else {
5676 // Remove sticky message related to premium code activation.
5677 $this->_admin_notices->remove_sticky( 'premium_activated' );
5678
5679 // Activated free code (after had the premium before).
5680 $this->do_action( 'after_free_version_reactivation' );
5681
5682 if ( $this->is_paying() && ! $this->is_premium() ) {
5683 $this->add_complete_upgrade_instructions_notice(
5684 sprintf(
5685 /* translators: %s: License type (e.g. you have a professional license) */
5686 $this->get_text_inline( 'You have a %s license.', 'you-have-x-license' ),
5687 $this->get_plan_title()
5688 ),
5689 'plan_upgraded'
5690 );
5691 }
5692 }
5693
5694 // Schedule code type changes event.
5695 $this->schedule_install_sync();
5696
5697 /**
5698 * Unregister the uninstall hook for the other version of the plugin (with different code type) to avoid
5699 * triggering a fatal error when uninstalling that plugin. For example, after deactivating the "free" version
5700 * of a specific plugin, its uninstall hook should be unregistered after the "premium" version has been
5701 * activated. If we don't do that, a fatal error will occur when we try to uninstall the "free" version since
5702 * the main file of the "free" version will be loaded first before calling the hooked callback. Since the
5703 * free and premium versions are almost identical (same class or have same functions), a fatal error like
5704 * "Cannot redeclare class MyClass" or "Cannot redeclare my_function()" will occur.
5705 */
5706 $this->unregister_uninstall_hook();
5707
5708 $this->clear_module_main_file_cache();
5709
5710 // Update is_premium of latest version.
5711 $this->_storage->prev_is_premium = $this->_plugin->is_premium;
5712 }
5713
5714 #endregion
5715
5716 #----------------------------------------------------------------------------------
5717 #region Add-ons
5718 #----------------------------------------------------------------------------------
5719
5720 /**
5721 * Check if add-on installed and activated on site.
5722 *
5723 * @author Vova Feldman (@svovaf)
5724 * @since 1.0.6
5725 *
5726 * @param string|number $id_or_slug
5727 * @param bool|null $is_premium Since 1.2.1.7 can check for specified add-on version.
5728 *
5729 * @return bool
5730 */
5731 function is_addon_activated( $id_or_slug, $is_premium = null ) {
5732 $this->_logger->entrance();
5733
5734 $addon_id = self::get_module_id( $id_or_slug );
5735 $is_activated = self::has_instance( $addon_id );
5736
5737 if ( ! $is_activated ) {
5738 return false;
5739 }
5740
5741 if ( is_bool( $is_premium ) ) {
5742 // Check if the specified code version is activate.
5743 $addon = $this->get_addon_instance( $addon_id );
5744 $is_activated = ( $is_premium === $addon->is_premium() );
5745 }
5746
5747 return $is_activated;
5748 }
5749
5750 /**
5751 * Check if add-on was connected to install
5752 *
5753 * @author Vova Feldman (@svovaf)
5754 * @since 1.1.7
5755 *
5756 * @param string|number $id_or_slug
5757 *
5758 * @return bool
5759 */
5760 function is_addon_connected( $id_or_slug ) {
5761 $this->_logger->entrance();
5762
5763 $sites = self::get_all_sites( WP_FS__MODULE_TYPE_PLUGIN );
5764
5765 $addon_id = self::get_module_id( $id_or_slug );
5766 $addon = $this->get_addon( $addon_id );
5767 $slug = $addon->slug;
5768 if ( ! isset( $sites[ $slug ] ) ) {
5769 return false;
5770 }
5771
5772 $site = $sites[ $slug ];
5773
5774 $plugin = FS_Plugin_Manager::instance( $addon_id )->get();
5775
5776 if ( $plugin->parent_plugin_id != $this->_plugin->id ) {
5777 // The given slug do NOT belong to any of the plugin's add-ons.
5778 return false;
5779 }
5780
5781 return ( is_object( $site ) &&
5782 is_numeric( $site->id ) &&
5783 is_numeric( $site->user_id ) &&
5784 FS_Plugin_Plan::is_valid_id( $site->plan_id )
5785 );
5786 }
5787
5788 /**
5789 * Determines if add-on installed.
5790 *
5791 * NOTE: This is a heuristic and only works if the folder/file named as the slug.
5792 *
5793 * @author Vova Feldman (@svovaf)
5794 * @since 1.0.6
5795 *
5796 * @param string|number $id_or_slug
5797 *
5798 * @return bool
5799 */
5800 function is_addon_installed( $id_or_slug ) {
5801 $this->_logger->entrance();
5802
5803 $addon_id = self::get_module_id( $id_or_slug );
5804
5805 return file_exists( fs_normalize_path( WP_PLUGIN_DIR . '/' . $this->get_addon_basename( $addon_id ) ) );
5806 }
5807
5808 /**
5809 * Get add-on basename.
5810 *
5811 * @author Vova Feldman (@svovaf)
5812 * @since 1.0.6
5813 *
5814 * @param string|number $id_or_slug
5815 *
5816 * @return string
5817 */
5818 function get_addon_basename( $id_or_slug ) {
5819 $addon_id = self::get_module_id( $id_or_slug );
5820
5821 if ( $this->is_addon_activated( $addon_id ) ) {
5822 return self::instance( $addon_id )->get_plugin_basename();
5823 }
5824
5825 $addon = $this->get_addon( $addon_id );
5826 $premium_basename = "{$addon->premium_slug}/{$addon->slug}.php";
5827
5828 if ( file_exists( fs_normalize_path( WP_PLUGIN_DIR . '/' . $premium_basename ) ) ) {
5829 return $premium_basename;
5830 }
5831
5832 $all_plugins = $this->get_all_plugins();
5833
5834 foreach ( $all_plugins as $basename => $data ) {
5835 if ( $addon->slug === $data['slug'] ||
5836 $addon->premium_slug === $data['slug']
5837 ) {
5838 return $basename;
5839 }
5840 }
5841
5842 $free_basename = "{$addon->slug}/{$addon->slug}.php";
5843
5844 return $free_basename;
5845 }
5846
5847 /**
5848 * Get installed add-ons instances.
5849 *
5850 * @author Vova Feldman (@svovaf)
5851 * @since 1.0.6
5852 *
5853 * @return Freemius[]
5854 */
5855 function get_installed_addons() {
5856 if ( $this->is_addon() ) {
5857 // Add-on cannot have add-ons.
5858 return array();
5859 }
5860
5861 $installed_addons = array();
5862
5863 foreach ( self::$_instances as $instance ) {
5864 if ( $instance->is_addon_of( $this->_plugin->id ) ) {
5865 $installed_addons[] = $instance;
5866 }
5867 }
5868
5869 return $installed_addons;
5870 }
5871
5872 /**
5873 * Check if any add-ons of the plugin are installed.
5874 *
5875 * @author Leo Fajardo (@leorw)
5876 * @since 1.1.1
5877 *
5878 * @return bool
5879 */
5880 function has_installed_addons() {
5881 if ( ! $this->has_addons() ) {
5882 return false;
5883 }
5884
5885 foreach ( self::$_instances as $instance ) {
5886 if ( $instance->is_addon() && is_object( $instance->_parent_plugin ) ) {
5887 if ( $this->_plugin->id == $instance->_parent_plugin->id ) {
5888 return true;
5889 }
5890 }
5891 }
5892
5893 return false;
5894 }
5895
5896 /**
5897 * Tell Freemius that the current plugin is an add-on.
5898 *
5899 * @author Vova Feldman (@svovaf)
5900 * @since 1.0.6
5901 *
5902 * @param number $parent_plugin_id The parent plugin ID
5903 */
5904 function init_addon( $parent_plugin_id ) {
5905 $this->_plugin->parent_plugin_id = $parent_plugin_id;
5906 }
5907
5908 /**
5909 * @author Vova Feldman (@svovaf)
5910 * @since 1.0.6
5911 *
5912 * @return bool
5913 */
5914 function is_addon() {
5915 return (
5916 isset( $this->_plugin->parent_plugin_id ) &&
5917 is_numeric( $this->_plugin->parent_plugin_id )
5918 );
5919 }
5920
5921 /**
5922 * @author Vova Feldman (@svovaf)
5923 * @since 2.3.2
5924 *
5925 * @param number $parent_product_id
5926 *
5927 * @return bool
5928 */
5929 function is_addon_of( $parent_product_id ) {
5930 return (
5931 $this->is_addon() &&
5932 $parent_product_id == $this->_plugin->parent_plugin_id
5933 );
5934 }
5935
5936 /**
5937 * Deactivate add-on if it's premium only and the user does't have a valid license.
5938 *
5939 * @param bool $is_after_trial_cancel
5940 *
5941 * @return bool If add-on was deactivated.
5942 */
5943 private function deactivate_premium_only_addon_without_license( $is_after_trial_cancel = false ) {
5944 if ( ! $this->has_free_plan() &&
5945 ! $this->has_features_enabled_license() &&
5946 ! $this->_has_premium_license()
5947 ) {
5948 if ( $this->is_registered() ) {
5949 // IF wrapper is turned off because activation_timestamp is currently only stored for plugins (not addons).
5950 // if (empty($this->_storage->activation_timestamp) ||
5951 // (WP_FS__SCRIPT_START_TIME - $this->_storage->activation_timestamp) > 30
5952 // ) {
5953 /**
5954 * @todo When it's first fail, there's no reason to try and re-sync because the licenses were just synced after initial activation.
5955 *
5956 * Retry syncing the user add-on licenses.
5957 */
5958 // Sync licenses.
5959 $this->_sync_licenses();
5960 // }
5961
5962 // Try to activate premium license.
5963 $this->_activate_license( true );
5964 }
5965
5966 if ( ! $this->has_free_plan() &&
5967 ! $this->has_features_enabled_license() &&
5968 ! $this->_has_premium_license()
5969 ) {
5970 // @todo Check if deactivate plugins also call the deactivation hook.
5971
5972 $this->_parent->_admin_notices->add_sticky(
5973 sprintf(
5974 ( $is_after_trial_cancel ?
5975 $this->_parent->get_text_inline(
5976 '%s free trial was successfully cancelled. Since the add-on is premium only it was automatically deactivated. If you like to use it in the future, you\'ll have to purchase a license.',
5977 'addon-trial-cancelled-message'
5978 ) :
5979 $this->_parent->get_text_inline(
5980 '%s is a premium only add-on. You have to purchase a license first before activating the plugin.',
5981 'addon-no-license-message'
5982 )
5983 ),
5984 '<b>' . $this->_plugin->title . '</b>'
5985 ) . ' ' . sprintf(
5986 '<a href="%s" aria-label="%s" class="button button-primary" style="margin-left: 10px; vertical-align: middle;">%s &nbsp;&#10140;</a>',
5987 $this->_parent->addon_url( $this->_slug ),
5988 esc_attr( sprintf( $this->_parent->get_text_inline( 'More information about %s', 'more-information-about-x' ), $this->_plugin->title ) ),
5989 $this->_parent->get_text_inline( 'Purchase License', 'purchase-license' )
5990 ),
5991 'no_addon_license_' . $this->_slug,
5992 ( $is_after_trial_cancel ? '' : $this->_parent->get_text_x_inline( 'Oops', 'exclamation', 'oops' ) . '...' ),
5993 ( $is_after_trial_cancel ? 'success' : 'error' )
5994 );
5995
5996 deactivate_plugins( array( $this->_plugin_basename ), true );
5997
5998 return true;
5999 }
6000 }
6001
6002 return false;
6003 }
6004
6005 #endregion
6006
6007 #----------------------------------------------------------------------------------
6008 #region Sandbox
6009 #----------------------------------------------------------------------------------
6010
6011 /**
6012 * Set Freemius into sandbox mode for debugging.
6013 *
6014 * @author Vova Feldman (@svovaf)
6015 * @since 1.0.4
6016 *
6017 * @param string $secret_key
6018 */
6019 function init_sandbox( $secret_key ) {
6020 $this->_plugin->secret_key = $secret_key;
6021
6022 // Update plugin details.
6023 FS_Plugin_Manager::instance( $this->_module_id )->update( $this->_plugin, true );
6024 }
6025
6026 /**
6027 * Check if running payments in sandbox mode.
6028 *
6029 * @author Vova Feldman (@svovaf)
6030 * @since 1.0.4
6031 *
6032 * @return bool
6033 */
6034 function is_payments_sandbox() {
6035 return ( ! $this->is_live() ) || isset( $this->_plugin->secret_key );
6036 }
6037
6038 #endregion
6039
6040 /**
6041 * Check if running test vs. live plugin.
6042 *
6043 * @author Vova Feldman (@svovaf)
6044 * @since 1.0.5
6045 *
6046 * @return bool
6047 */
6048 function is_live() {
6049 return $this->_plugin->is_live;
6050 }
6051
6052 /**
6053 * Check if super-admin skipped connection for all sites in the network.
6054 *
6055 * @author Vova Feldman (@svovaf)
6056 * @since 2.0.0
6057 */
6058 function is_network_anonymous() {
6059 if ( ! $this->_is_network_active ) {
6060 return false;
6061 }
6062
6063 $is_anonymous_ms = $this->_storage->get( 'is_anonymous_ms' );
6064
6065 if ( empty( $is_anonymous_ms ) ) {
6066 return false;
6067 }
6068
6069 return $is_anonymous_ms['is'];
6070 }
6071
6072 /**
6073 * Check if super-admin opted-in for all sites in the network.
6074 *
6075 * @author Vova Feldman (@svovaf)
6076 * @since 2.0.0
6077 */
6078 function is_network_connected() {
6079 if ( ! $this->_is_network_active ) {
6080 return false;
6081 }
6082
6083 return $this->_storage->get( 'is_network_connected' );
6084 }
6085
6086 /**
6087 * Check if the user skipped connecting the account with Freemius.
6088 *
6089 * @author Vova Feldman (@svovaf)
6090 * @since 1.0.7
6091 *
6092 * @return bool
6093 */
6094 function is_anonymous() {
6095 if ( ! isset( $this->_is_anonymous ) ) {
6096 if ( $this->is_network_anonymous() ) {
6097 $this->_is_anonymous = true;
6098 } else if ( fs_is_network_admin() ) {
6099 /**
6100 * When not-network-anonymous, yet, running in the network admin, consider as anonymous only when ALL non-delegated sites are set to anonymous.
6101 */
6102 $non_delegated_sites = $this->get_non_delegated_blog_ids();
6103
6104 foreach ( $non_delegated_sites as $blog_id ) {
6105 $is_anonymous = $this->_storage->get( 'is_anonymous', false, $blog_id );
6106
6107 if ( empty( $is_anonymous ) || false === $is_anonymous[ 'is' ] ) {
6108 $this->_is_anonymous = false;
6109 break;
6110 }
6111 }
6112
6113 if ( false !== $this->_is_anonymous ) {
6114 $this->_is_anonymous = true;
6115 }
6116 } else {
6117 if ( ! isset( $this->_storage->is_anonymous ) ) {
6118 // Not skipped.
6119 $this->_is_anonymous = false;
6120 } else if ( is_bool( $this->_storage->is_anonymous ) ) {
6121 // For back compatibility, since the variable was boolean before.
6122 $this->_is_anonymous = $this->_storage->is_anonymous;
6123
6124 // Upgrade stored data format to 1.1.3 format.
6125 $this->set_anonymous_mode( $this->_storage->is_anonymous );
6126 } else {
6127 // Version 1.1.3 and later.
6128 $this->_is_anonymous = $this->_storage->is_anonymous['is'];
6129 }
6130 }
6131 }
6132
6133 return $this->_is_anonymous;
6134 }
6135
6136 /**
6137 * Check if the user skipped the connection of a specified site.
6138 *
6139 * @author Vova Feldman (@svovaf)
6140 * @since 2.0.0
6141 *
6142 * @param int $blog_id
6143 *
6144 * @return bool
6145 */
6146 function is_anonymous_site( $blog_id = 0 ) {
6147 if ( $this->is_network_anonymous() ) {
6148 return true;
6149 }
6150
6151 $is_anonymous = $this->_storage->get( 'is_anonymous', false, $blog_id );
6152
6153 if ( empty( $is_anonymous ) ) {
6154 return false;
6155 }
6156
6157 return $is_anonymous['is'];
6158 }
6159
6160 /**
6161 * Check if user connected his account and install pending email activation.
6162 *
6163 * @author Vova Feldman (@svovaf)
6164 * @since 1.0.7
6165 *
6166 * @return bool
6167 */
6168 function is_pending_activation() {
6169 return $this->_storage->get( 'is_pending_activation', false );
6170 }
6171
6172 /**
6173 * @author Leo Fajardo (@leorw)
6174 * @since 2.5.0
6175 */
6176 private function clear_pending_activation_mode() {
6177 // Remove the pending activation sticky notice (if it still exists).
6178 $this->_admin_notices->remove_sticky( 'activation_pending' );
6179
6180 // Clear the plugin's pending activation mode.
6181 unset( $this->_storage->is_pending_activation );
6182 }
6183
6184 /**
6185 * Check if plugin must be WordPress.org compliant.
6186 *
6187 * @since 1.0.7
6188 *
6189 * @return bool
6190 */
6191 function is_org_repo_compliant() {
6192 return $this->_is_org_compliant;
6193 }
6194
6195 #--------------------------------------------------------------------------------
6196 #region WP Cron Common
6197 #--------------------------------------------------------------------------------
6198
6199 /**
6200 * @author Vova Feldman (@svovaf)
6201 * @since 2.0.0
6202 *
6203 * @param string $name Cron name.
6204 *
6205 * @return object
6206 */
6207 private function get_cron_data( $name ) {
6208 $this->_logger->entrance( $name );
6209
6210 /**
6211 * @var object $cron_data
6212 */
6213 return $this->_storage->get( "{$name}_cron", null );
6214 }
6215
6216 /**
6217 * @author Vova Feldman (@svovaf)
6218 * @since 2.0.0
6219 *
6220 * @param string $name Cron name.
6221 */
6222 private function clear_cron_data( $name ) {
6223 $this->_logger->entrance( $name );
6224
6225 $this->_storage->remove( "{$name}_cron" );
6226 }
6227
6228 /**
6229 * @author Vova Feldman (@svovaf)
6230 * @since 2.0.0
6231 *
6232 * @param string $name Cron name.
6233 * @param int $cron_blog_id The cron executing blog ID.
6234 */
6235 private function set_cron_data( $name, $cron_blog_id = 0 ) {
6236 $this->_logger->entrance( $name );
6237
6238 $this->_storage->store( "{$name}_cron", (object) array(
6239 'version' => $this->get_plugin_version(),
6240 'blog_id' => $cron_blog_id,
6241 'sdk_version' => $this->version,
6242 'timestamp' => WP_FS__SCRIPT_START_TIME,
6243 'on' => true,
6244 ) );
6245 }
6246
6247 /**
6248 * Get the cron's executing blog ID.
6249 *
6250 * @author Vova Feldman (@svovaf)
6251 * @since 2.0.0
6252 *
6253 * @param string $name Cron name.
6254 *
6255 * @return int
6256 */
6257 private function get_cron_blog_id( $name ) {
6258 $this->_logger->entrance( $name );
6259
6260 if ( ! is_multisite() ) {
6261 // Not a multisite.
6262 return 0;
6263 }
6264
6265 $cron_data = $this->get_cron_data( $name );
6266
6267 return ( is_object( $cron_data ) && is_numeric( $cron_data->blog_id ) ) ?
6268 $cron_data->blog_id :
6269 0;
6270 }
6271
6272 /**
6273 * @author Vova Feldman (@svovaf)
6274 * @since 2.0.0
6275 *
6276 * @param string $name Cron name.
6277 *
6278 * @return bool
6279 */
6280 private function is_cron_on( $name ) {
6281 $this->_logger->entrance( $name );
6282
6283 /**
6284 * @var object $cron_data
6285 */
6286 $cron_data = $this->get_cron_data( $name );
6287
6288 return ( ! is_null( $cron_data ) && true === $cron_data->on );
6289 }
6290
6291 /**
6292 * Unix timestamp for previous cron execution or false if never executed.
6293 *
6294 * @author Vova Feldman (@svovaf)
6295 * @since 2.0.0
6296 *
6297 * @param string $name Cron name.
6298 *
6299 * @return int|false
6300 */
6301 private function cron_last_execution( $name ) {
6302 $this->_logger->entrance( $name );
6303
6304 return $this->_storage->get( "{$name}_timestamp" );
6305 }
6306
6307 /**
6308 * Set cron execution time to now.
6309 *
6310 * @author Vova Feldman (@svovaf)
6311 * @since 2.0.0
6312 *
6313 * @param string $name Cron name.
6314 */
6315 private function set_cron_execution_timestamp( $name ) {
6316 $this->_logger->entrance( $name );
6317
6318 $this->_storage->store( "{$name}_timestamp", time() );
6319 }
6320
6321 /**
6322 * Sets the keepalive time to now.
6323 *
6324 * @author Leo Fajardo (@leorw)
6325 * @since 2.2.3
6326 *
6327 * @param bool|null $use_network_level_storage
6328 */
6329 private function set_keepalive_timestamp( $use_network_level_storage = null ) {
6330 $this->_logger->entrance();
6331
6332 $this->_storage->store( 'keepalive_timestamp', time(), $use_network_level_storage );
6333 }
6334
6335 /**
6336 * Check if cron was executed in the last $period of seconds.
6337 *
6338 * @author Vova Feldman (@svovaf)
6339 * @since 2.0.0
6340 *
6341 * @param string $name Cron name.
6342 * @param int $period In seconds
6343 *
6344 * @return bool
6345 */
6346 private function is_cron_executed( $name, $period = WP_FS__TIME_24_HOURS_IN_SEC ) {
6347 $this->_logger->entrance( $name );
6348
6349 $last_execution = $this->cron_last_execution( $name );
6350
6351 if ( ! is_numeric( $last_execution ) ) {
6352 return false;
6353 }
6354
6355 return ( $last_execution > ( WP_FS__SCRIPT_START_TIME - $period ) );
6356 }
6357
6358 /**
6359 * WP Cron is executed on a site level. When running in a multisite network environment
6360 * with the network integration activated, for optimization reasons, we are consolidating
6361 * the installs data sync cron to be executed only from a single site.
6362 *
6363 * @author Vova Feldman (@svovaf)
6364 * @since 2.0.0
6365 *
6366 * @param int $except_blog_id Target any except the excluded blog ID.
6367 *
6368 * @return int
6369 */
6370 private function get_cron_target_blog_id( $except_blog_id = 0 ) {
6371 if ( ! is_multisite() ) {
6372 return 0;
6373 }
6374
6375 if ( $this->_is_network_active ) {
6376 $network_install_blog_id = $this->_storage->network_install_blog_id;
6377
6378 if (
6379 is_numeric( $network_install_blog_id ) &&
6380 $except_blog_id != $network_install_blog_id &&
6381 self::is_site_active( $network_install_blog_id )
6382 ) {
6383 // Try to run cron from the main network blog.
6384 $install = $this->get_install_by_blog_id( $network_install_blog_id );
6385
6386 if (
6387 is_object( $install ) &&
6388 $this->is_tracking_allowed( $network_install_blog_id, $install )
6389 ) {
6390 return $network_install_blog_id;
6391 }
6392 }
6393 }
6394
6395 // Get first opted-in blog ID with active tracking.
6396 $installs = $this->get_blog_install_map();
6397 foreach ( $installs as $blog_id => $install ) {
6398 if ( $except_blog_id != $blog_id &&
6399 self::is_site_active( $blog_id ) &&
6400 $this->is_tracking_allowed( $blog_id, $install )
6401 ) {
6402 return $blog_id;
6403 }
6404 }
6405
6406 return 0;
6407 }
6408
6409 /**
6410 * @author Vova Feldman (@svovaf)
6411 * @since 2.0.0
6412 *
6413 * @param string $name Cron name.
6414 * @param string $action_tag Callback action tag.
6415 * @param bool $is_network_clear If set to TRUE, clear sync cron even if there are installs that are still connected.
6416 */
6417 private function clear_cron( $name, $action_tag = '', $is_network_clear = false ) {
6418 $this->_logger->entrance( $name );
6419
6420 if ( ! $this->is_cron_on( $name ) ) {
6421 return;
6422 }
6423
6424 $clear_cron = true;
6425 if ( ! $is_network_clear && $this->_is_network_active ) {
6426 $installs = $this->get_blog_install_map();
6427
6428 foreach ( $installs as $blog_id => $install ) {
6429 /**
6430 * @var FS_Site $install
6431 */
6432 if ( $this->is_tracking_allowed( $blog_id, $install ) ) {
6433 $clear_cron = false;
6434 break;
6435 }
6436 }
6437 }
6438
6439 if ( ! $clear_cron ) {
6440 return;
6441 }
6442
6443 $cron_blog_id = $this->get_cron_blog_id( $name );
6444
6445 $this->clear_cron_data( $name );
6446
6447 if ( 0 < $cron_blog_id ) {
6448 switch_to_blog( $cron_blog_id );
6449 }
6450
6451 if ( empty( $action_tag ) ) {
6452 $action_tag = $name;
6453 }
6454
6455 wp_clear_scheduled_hook( $this->get_action_tag( $action_tag ) );
6456
6457 if ( 0 < $cron_blog_id ) {
6458 restore_current_blog();
6459 }
6460 }
6461
6462 /**
6463 * Unix timestamp for next cron execution or false if not scheduled.
6464 *
6465 * @author Vova Feldman (@svovaf)
6466 * @since 2.0.0
6467 *
6468 * @param string $name Cron name.
6469 * @param string $action_tag Callback action tag.
6470 *
6471 * @return int|false
6472 */
6473 private function get_next_scheduled_cron( $name, $action_tag = '' ) {
6474 $this->_logger->entrance( $name );
6475
6476 if ( ! $this->is_cron_on( $name ) ) {
6477 return false;
6478 }
6479
6480 $cron_blog_id = $this->get_cron_blog_id( $name );
6481
6482 if ( 0 < $cron_blog_id ) {
6483 switch_to_blog( $cron_blog_id );
6484 }
6485
6486 if ( empty( $action_tag ) ) {
6487 $action_tag = $name;
6488 }
6489
6490 $next_scheduled = wp_next_scheduled( $this->get_action_tag( $action_tag ) );
6491
6492 if ( 0 < $cron_blog_id ) {
6493 restore_current_blog();
6494 }
6495
6496 return $next_scheduled;
6497 }
6498
6499 /**
6500 * @author Vova Feldman (@svovaf)
6501 * @since 2.0.0
6502 *
6503 * @param string $name Cron name.
6504 * @param string $action_tag Callback action tag.
6505 * @param string $recurrence 'single' or 'daily'.
6506 * @param int $start_at Defaults to now.
6507 * @param bool $randomize_start If true, schedule first job randomly during the next 12 hours. Otherwise, schedule job to start right away.
6508 * @param int $except_blog_id Target any except the excluded blog ID.
6509 */
6510 private function schedule_cron(
6511 $name,
6512 $action_tag = '',
6513 $recurrence = 'single',
6514 $start_at = WP_FS__SCRIPT_START_TIME,
6515 $randomize_start = true,
6516 $except_blog_id = 0
6517 ) {
6518 $this->_logger->entrance( $name );
6519
6520 $this->clear_cron( $name, $action_tag, true );
6521
6522 $cron_blog_id = $this->get_cron_target_blog_id( $except_blog_id );
6523
6524 if ( is_multisite() && 0 == $cron_blog_id ) {
6525 // Don't schedule cron since couldn't find a target blog.
6526 return;
6527 }
6528
6529 if ( 0 < $cron_blog_id ) {
6530 switch_to_blog( $cron_blog_id );
6531 }
6532
6533 if ( 'daily' === $recurrence ) {
6534 if ( $randomize_start ) {
6535 // Schedule first sync with a random 12 hour time range from now.
6536 $start_at += rand( 0, ( WP_FS__TIME_24_HOURS_IN_SEC / 2 ) );
6537 }
6538
6539 // Schedule daily WP cron.
6540 wp_schedule_event(
6541 $start_at,
6542 'daily',
6543 $this->get_action_tag( $action_tag )
6544 );
6545 } else if ( 'single' === $recurrence ) {
6546 // Schedule single cron.
6547 wp_schedule_single_event(
6548 $start_at,
6549 $this->get_action_tag( $action_tag )
6550 );
6551 }
6552
6553 $this->set_cron_data( $name, $cron_blog_id );
6554
6555 if ( 0 < $cron_blog_id ) {
6556 restore_current_blog();
6557 }
6558 }
6559
6560 /**
6561 * Consolidated cron execution for performance optimization. The max number of API requests is based on the number of unique opted-in users.
6562 * that doesn't halt page loading.
6563 *
6564 * @author Vova Feldman (@svovaf)
6565 * @since 2.0.0
6566 *
6567 * @param string $name Cron name.
6568 * @param callable $callable The function that should be executed.
6569 */
6570 private function execute_cron( $name, $callable ) {
6571 $this->_logger->entrance( $name );
6572
6573 // Store the last time data sync was executed.
6574 $this->set_cron_execution_timestamp( $name );
6575
6576 // Check if API is temporary down.
6577 if ( FS_Api::is_temporary_down() ) {
6578 return;
6579 }
6580
6581 // @todo Add logic that identifies API latency, and reschedule the next background sync randomly between 8-16 hours.
6582
6583 $users_2_blog_ids = array();
6584
6585 if ( ! is_multisite() ) {
6586 // Add dummy blog.
6587 $users_2_blog_ids[0] = array( 0 );
6588 } else {
6589 $installs = $this->get_blog_install_map();
6590 foreach ( $installs as $blog_id => $install ) {
6591 if ( $this->is_tracking_allowed( $blog_id, $install ) ) {
6592 if ( ! isset( $users_2_blog_ids[ $install->user_id ] ) ) {
6593 $users_2_blog_ids[ $install->user_id ] = array();
6594 }
6595
6596 $users_2_blog_ids[ $install->user_id ][] = $blog_id;
6597 }
6598 }
6599 }
6600
6601 $current_blog_id = get_current_blog_id();
6602
6603 foreach ( $users_2_blog_ids as $user_id => $blog_ids ) {
6604 if ( 0 < $blog_ids[0] ) {
6605 $this->switch_to_blog( $blog_ids[0] );
6606 }
6607
6608 call_user_func_array( $callable, array( $blog_ids, ( is_multisite() ? $current_blog_id : null ) ) );
6609
6610 foreach ( $blog_ids as $blog_id ) {
6611 $this->do_action( "after_{$name}_cron", $blog_id );
6612 }
6613 }
6614
6615 if ( is_multisite() ) {
6616 $this->switch_to_blog( $current_blog_id, fs_is_network_admin() ? $this->get_network_install() : null );
6617
6618 $this->do_action( "after_{$name}_cron_multisite" );
6619 }
6620 }
6621
6622 #endregion
6623
6624 #----------------------------------------------------------------------------------
6625 #region Daily Sync Cron
6626 #----------------------------------------------------------------------------------
6627
6628
6629 /**
6630 * @author Vova Feldman (@svovaf)
6631 * @since 2.0.0
6632 *
6633 * @return bool
6634 */
6635 private function is_sync_cron_scheduled() {
6636 return $this->is_cron_on( 'sync' );
6637 }
6638
6639 /**
6640 * Get the sync cron's executing blog ID.
6641 *
6642 * @author Vova Feldman (@svovaf)
6643 * @since 2.0.0
6644 *
6645 * @return int
6646 */
6647 private function get_sync_cron_blog_id() {
6648 return $this->get_cron_blog_id( 'sync' );
6649 }
6650
6651 /**
6652 * @author Vova Feldman (@svovaf)
6653 * @since 1.1.7.3
6654 */
6655 private function run_manual_sync() {
6656 if ( ! $this->is_user_admin() ) {
6657 return;
6658 }
6659
6660 // Run manual sync.
6661 $this->_sync_cron();
6662
6663 // Reschedule next cron to run 24 hours from now (performance optimization).
6664 $this->schedule_sync_cron( time() + WP_FS__TIME_24_HOURS_IN_SEC, false );
6665 }
6666
6667 /**
6668 * Data sync cron job. Replaces the background sync non blocking HTTP request
6669 * that doesn't halt page loading.
6670 *
6671 * @author Vova Feldman (@svovaf)
6672 * @since 1.1.7.3
6673 * @since 2.0.0 Consolidate all the data sync into the same cron for performance optimization. The max number of API requests is based on the number of unique opted-in users.
6674 */
6675 function _sync_cron() {
6676 $this->_logger->entrance();
6677
6678 $this->execute_cron( 'sync', array( &$this, '_sync_cron_method' ) );
6679 }
6680
6681 /**
6682 * The actual data sync cron logic.
6683 *
6684 * @author Vova Feldman (@svovaf)
6685 * @since 2.0.0
6686 *
6687 * @param int[] $blog_ids
6688 * @param int|null $current_blog_id @since 2.2.3. This is passed from the `execute_cron` method and used by the
6689 * `_sync_plugin_license` method in order to switch to the previous blog when sending
6690 * updates for a single site in case `execute_cron` has switched to a different blog.
6691 */
6692 function _sync_cron_method( array $blog_ids, $current_blog_id = null ) {
6693 if ( $this->is_registered() ) {
6694 if ( $this->has_paid_plan() ) {
6695 // Initiate background plan sync.
6696 $this->_sync_license( true, false, $current_blog_id );
6697
6698 if ( $this->is_paying() ) {
6699 // Check for premium plugin updates.
6700 $this->check_updates( true );
6701 }
6702 } else {
6703 // Sync install(s) (only if something changed locally).
6704 if ( 1 < count( $blog_ids ) ) {
6705 $this->sync_installs();
6706 } else {
6707 $this->sync_install();
6708 }
6709
6710 $this->maybe_sync_install_user();
6711 }
6712 }
6713 }
6714
6715 /**
6716 * Check if sync was executed in the last $period of seconds.
6717 *
6718 * @author Vova Feldman (@svovaf)
6719 * @since 1.1.7.3
6720 *
6721 * @param int $period In seconds
6722 *
6723 * @return bool
6724 */
6725 private function is_sync_executed( $period = WP_FS__TIME_24_HOURS_IN_SEC ) {
6726 return $this->is_cron_executed( 'sync', $period );
6727 }
6728
6729 /**
6730 * @author Vova Feldman (@svovaf)
6731 * @since 1.1.7.3
6732 *
6733 * @return bool
6734 */
6735 private function is_sync_cron_on() {
6736 return $this->is_cron_on( 'sync' );
6737 }
6738
6739 /**
6740 * @author Leo Fajardo (@leorw)
6741 * @since 2.5.0
6742 */
6743 private function maybe_schedule_sync_cron() {
6744 $next_schedule = $this->next_sync_cron();
6745
6746 // The event is properly scheduled, so no need to reschedule it.
6747 if (
6748 is_numeric( $next_schedule ) &&
6749 $next_schedule > time()
6750 ) {
6751 return;
6752 }
6753
6754 $this->schedule_sync_cron();
6755 }
6756
6757 /**
6758 * @author Vova Feldman (@svovaf)
6759 * @since 1.1.7.3
6760 *
6761 * @param int $start_at Defaults to now.
6762 * @param bool $randomize_start If true, schedule first job randomly during the next 12 hours. Otherwise, schedule job to start right away.
6763 * @param int $except_blog_id Since 2.0.0 when running in a multisite network environment, the cron execution is consolidated. This param allows excluding excluded specified blog ID from being the cron executor.
6764 */
6765 private function schedule_sync_cron(
6766 $start_at = WP_FS__SCRIPT_START_TIME,
6767 $randomize_start = true,
6768 $except_blog_id = 0
6769 ) {
6770 $this->schedule_cron(
6771 'sync',
6772 'data_sync',
6773 'daily',
6774 $start_at,
6775 $randomize_start,
6776 $except_blog_id
6777 );
6778 }
6779
6780 /**
6781 * Add the actual sync function to the cron job hook.
6782 *
6783 * @author Vova Feldman (@svovaf)
6784 * @since 1.1.7.3
6785 */
6786 private function hook_callback_to_sync_cron() {
6787 $this->add_action( 'data_sync', array( &$this, '_sync_cron' ) );
6788 }
6789
6790 /**
6791 * @author Vova Feldman (@svovaf)
6792 * @since 1.1.7.3
6793 *
6794 * @param bool $is_network_clear Since 2.0.0 If set to TRUE, clear sync cron even if there are installs that are still connected.
6795 */
6796 private function clear_sync_cron( $is_network_clear = false ) {
6797 $this->_logger->entrance();
6798
6799 $this->clear_cron( 'sync', 'data_sync', $is_network_clear );
6800 }
6801
6802 /**
6803 * Unix timestamp for next sync cron execution or false if not scheduled.
6804 *
6805 * @author Vova Feldman (@svovaf)
6806 * @since 1.1.7.3
6807 *
6808 * @return int|false
6809 */
6810 function next_sync_cron() {
6811 return $this->get_next_scheduled_cron( 'sync', 'data_sync' );
6812 }
6813
6814 /**
6815 * Unix timestamp for previous sync cron execution or false if never executed.
6816 *
6817 * @author Vova Feldman (@svovaf)
6818 * @since 1.1.7.3
6819 *
6820 * @return int|false
6821 */
6822 function last_sync_cron() {
6823 return $this->cron_last_execution( 'sync' );
6824 }
6825
6826 #endregion Daily Sync Cron ------------------------------------------------------------------
6827
6828 #----------------------------------------------------------------------------------
6829 #region Async Install Sync
6830 #----------------------------------------------------------------------------------
6831
6832 /**
6833 * @author Vova Feldman (@svovaf)
6834 * @since 1.1.7.3
6835 *
6836 * @return bool
6837 */
6838 private function is_install_sync_scheduled() {
6839 return $this->is_cron_on( 'install_sync' );
6840 }
6841
6842 /**
6843 * Get the sync cron's executing blog ID.
6844 *
6845 * @author Vova Feldman (@svovaf)
6846 * @since 2.0.0
6847 *
6848 * @return int
6849 */
6850 private function get_install_sync_cron_blog_id() {
6851 return $this->get_cron_blog_id( 'install_sync' );
6852 }
6853
6854 /**
6855 * Instead of running blocking install sync event, execute non blocking scheduled wp-cron.
6856 *
6857 * @author Vova Feldman (@svovaf)
6858 * @since 1.1.7.3
6859 *
6860 * @param int $except_blog_id Since 2.0.0 when running in a multisite network environment, the cron execution is consolidated. This param allows excluding excluded specified blog ID from being the cron executor.
6861 */
6862 private function schedule_install_sync( $except_blog_id = 0 ) {
6863 if ( $this->is_clone() ) {
6864 return;
6865 }
6866
6867 $this->schedule_cron( 'install_sync', 'install_sync', 'single', WP_FS__SCRIPT_START_TIME, false, $except_blog_id );
6868 }
6869
6870 /**
6871 * Unix timestamp for previous install sync cron execution or false if never executed.
6872 *
6873 * @todo There's some very strange bug that $this->_storage->install_sync_timestamp value is not being updated. But for sure the sync event is working.
6874 *
6875 * @author Vova Feldman (@svovaf)
6876 * @since 1.1.7.3
6877 *
6878 * @return int|false
6879 */
6880 function last_install_sync() {
6881 return $this->cron_last_execution( 'install_sync' );
6882 }
6883
6884 /**
6885 * Unix timestamp for next install sync cron execution or false if not scheduled.
6886 *
6887 * @author Vova Feldman (@svovaf)
6888 * @since 1.1.7.3
6889 *
6890 * @return int|false
6891 */
6892 function next_install_sync() {
6893 return $this->get_next_scheduled_cron( 'install_sync', 'install_sync' );
6894 }
6895
6896 /**
6897 * Add the actual install sync function to the cron job hook.
6898 *
6899 * @author Vova Feldman (@svovaf)
6900 * @since 1.1.7.3
6901 */
6902 private function hook_callback_to_install_sync() {
6903 $this->add_action( 'install_sync', array( &$this, '_run_sync_install' ) );
6904 }
6905
6906 /**
6907 * @author Vova Feldman (@svovaf)
6908 * @since 1.1.7.3
6909 *
6910 * @param bool $is_network_clear Since 2.0.0 If set to TRUE, clear sync cron even if there are installs that are still connected.
6911 */
6912 private function clear_install_sync_cron( $is_network_clear = false ) {
6913 $this->_logger->entrance();
6914
6915 $this->clear_cron( 'install_sync', 'install_sync', $is_network_clear );
6916 }
6917
6918 /**
6919 * @author Vova Feldman (@svovaf)
6920 * @since 1.1.7.3
6921 * @since 2.0.0 Consolidate all the data sync into the same cron for performance optimization. The max number of API requests is based on the number of unique opted-in users.
6922 */
6923 public function _run_sync_install() {
6924 $this->_logger->entrance();
6925
6926 $this->execute_cron( 'sync', array( &$this, '_sync_install_cron_method' ) );
6927 }
6928
6929 /**
6930 * The actual install(s) sync cron logic.
6931 *
6932 * @author Vova Feldman (@svovaf)
6933 * @since 2.0.0
6934 *
6935 * @param int[] $blog_ids
6936 * @param int|null $current_blog_id
6937 */
6938 function _sync_install_cron_method( array $blog_ids, $current_blog_id = null ) {
6939 if ( $this->is_registered() ) {
6940 if ( 1 < count( $blog_ids ) ) {
6941 $this->sync_installs( array(), true );
6942 } else {
6943 $this->sync_install( array(), true );
6944 }
6945
6946 $this->maybe_sync_install_user();
6947 }
6948 }
6949
6950 #endregion Async Install Sync ------------------------------------------------------------------
6951
6952 /**
6953 * Show a notice that activation is currently pending.
6954 *
6955 * @todo Add some sort of mechanism to allow users to update the email address they would like to opt-in with when $is_suspicious_email is true.
6956 *
6957 * @author Vova Feldman (@svovaf)
6958 * @since 1.0.7
6959 *
6960 * @param bool|string $email_address
6961 * @param bool $is_pending_trial Since 1.2.1.5
6962 * @param bool $is_suspicious_email Since 2.5.0 Set to true when there's an indication that email address the user opted in with is fake/dummy/placeholder.
6963 * @param bool $has_upgrade_context Since 2.5.3
6964 * @param bool $support_email_address Since 2.5.3
6965 */
6966 function _add_pending_activation_notice(
6967 $email_address = false,
6968 $is_pending_trial = false,
6969 $is_suspicious_email = false,
6970 $has_upgrade_context = false,
6971 $support_email_address = false
6972 ) {
6973 if ( ! is_string( $email_address ) ) {
6974 $current_user = self::_get_current_wp_user();
6975 $email_address = $current_user->user_email;
6976 }
6977
6978 $formatted_message_args = array(
6979 "<b>{$this->get_plugin_name()}</b>",
6980 "<b>{$email_address}</b>",
6981 );
6982
6983 if ( ! $has_upgrade_context || ! fs_is_network_admin() ) {
6984 /* translators: %3$s: action (e.g.: "start the trial" or "complete the opt-in") */
6985 $formatted_message = $this->get_text_inline( 'You should receive a confirmation email for %1$s to your mailbox at %2$s. Please make sure you click the button in that email to %3$s.', 'pending-activation-message' );
6986
6987 $formatted_message_args[] = $is_pending_trial ?
6988 $this->get_text_inline( 'start the trial', 'start-the-trial' ) :
6989 $this->get_text_inline( 'complete the opt-in', 'complete-the-opt-in' );
6990
6991 $notice_title = $this->get_text_inline( 'Thanks!', 'thanks' );
6992 } else {
6993 /* translators: %3$s: What the user is expected to receive via email (e.g.: "the installation instructions" or "a license key") */
6994 $formatted_message = $this->get_text_inline( 'You should receive %3$s for %1$s to your mailbox at %2$s in the next 5 minutes.' );
6995
6996 if ( $this->has_release_on_freemius() ) {
6997 $formatted_message_args[] = $this->get_text_x_inline(
6998 'the installation instructions',
6999 'Part of the message telling the user what they should receive via email.',
7000 'the-installation-instructions-phrase'
7001 );
7002 } else {
7003 $formatted_message_args[] = $this->get_text_x_inline(
7004 'a license key',
7005 'Part of the message telling the user what they should receive via email.',
7006 'a-license-key-phrase'
7007 );
7008
7009 $formatted_message .= ( ' ' . sprintf(
7010 /* translators: %s: activation link (e.g.: <a>Click here</a>) */
7011 $this->get_text_inline( '%s to activate the license once you get it.', 'license-activation-link-message' ),
7012 sprintf(
7013 '<b><a href="%s">%s</a></b>',
7014 $this->get_activation_url( array(
7015 'fs_action' => 'reset_pending_activation_mode',
7016 'require_license' => 'true',
7017 'fs_unique_affix' => $this->get_unique_affix(),
7018 ) ),
7019 $this->get_text_x_inline( 'Click here', 'Part of an activation link message.', 'click-here' )
7020 )
7021 ) );
7022 }
7023
7024 $formatted_message_args[] = ( ! empty( $support_email_address ) ) ?
7025 ( "<b>{$support_email_address}</b>" ) :
7026 $this->get_text_x_inline(
7027 "the product's support email address",
7028 'Part of the message that tells the user to check their spam folder for a specific email.',
7029 'product-support-email-address-phrase'
7030 );
7031
7032 $formatted_message .= ( ' ' . $this->get_text_inline( 'If you didn\'t get the email, try checking your spam folder or search for emails from %4$s.', 'check-spam-folder-message' ) );
7033
7034 $notice_title = $this->get_text_inline( 'Thanks for upgrading.', 'after-upgrade-thank-you-message' );
7035 }
7036
7037 $this->_admin_notices->add_sticky(
7038 vsprintf( $formatted_message, $formatted_message_args ),
7039 'activation_pending',
7040 $notice_title
7041 );
7042 }
7043
7044 /**
7045 * Check if currently in plugin activation.
7046 *
7047 * @author Vova Feldman (@svovaf)
7048 * @since 1.1.4
7049 *
7050 * @return bool
7051 */
7052 function is_plugin_activation() {
7053 $result = get_transient( "fs_{$this->_module_type}_{$this->_slug}_activated" );
7054
7055 return !empty($result);
7056 }
7057
7058 /**
7059 *
7060 * NOTE: admin_menu action executed before admin_init.
7061 *
7062 * @author Vova Feldman (@svovaf)
7063 * @since 1.0.7
7064 */
7065 function _admin_init_action() {
7066 $is_migration = $this->is_migration();
7067
7068 /**
7069 * Automatically redirect to connect/activation page after plugin activation.
7070 *
7071 * @since 1.1.7 Do NOT redirect to opt-in when running in network admin mode.
7072 */
7073 if ( $this->is_plugin_activation() ) {
7074 delete_transient( "fs_{$this->_module_type}_{$this->_slug}_activated" );
7075
7076 if ( isset( $_GET['activate-multi'] ) ) {
7077 /**
7078 * Don't redirect if activating multiple plugins at once (bulk activation).
7079 */
7080 } else if (
7081 self::is_deactivation_snoozed() &&
7082 (
7083 // Either running the free code base.
7084 ! $this->is_premium() ||
7085 // Or if has a free version.
7086 ! $this->is_only_premium() ||
7087 // If premium only, don't redirect if license is activated.
7088 ( $this->is_registered() && ! $this->can_use_premium_code() )
7089 )
7090 ) {
7091 /**
7092 * Don't redirect if activating during the deactivation snooze period (aka troubleshooting), unless activating a paid product version that the admin didn't enter its license key yet.
7093 */
7094 } else if ( ! $is_migration ) {
7095 $this->_redirect_on_activation_hook();
7096 return;
7097 }
7098 }
7099
7100 if ( $is_migration ) {
7101 return;
7102 }
7103
7104 if ( fs_request_is_action( $this->get_unique_affix() . '_skip_activation' ) ) {
7105 check_admin_referer( $this->get_unique_affix() . '_skip_activation' );
7106
7107 $this->skip_connection( fs_is_network_admin() );
7108
7109 fs_redirect( $this->get_after_activation_url( 'after_skip_url' ) );
7110 }
7111
7112 if ( $this->is_network_activation_mode() &&
7113 fs_request_is_action( $this->get_unique_affix() . '_delegate_activation' )
7114 ) {
7115 check_admin_referer( $this->get_unique_affix() . '_delegate_activation' );
7116
7117 $this->delegate_connection();
7118
7119 fs_redirect( $this->get_after_activation_url( 'after_delegation_url' ) );
7120 }
7121
7122 $this->_add_upgrade_action_link();
7123
7124 if ( ! ( ! $this->_is_network_active && fs_is_network_admin() ) &&
7125 (
7126 ( true === $this->_storage->require_license_activation ) ||
7127 // Not registered nor anonymous.
7128 ( ! $this->is_registered() && ! $this->is_anonymous() ) ||
7129 // OR, network level and in network upgrade mode.
7130 ( fs_is_network_admin() && $this->_is_network_active && $this->is_network_upgrade_mode() )
7131 )
7132 ) {
7133 if ( ! $this->is_pending_activation() ) {
7134 if ( ! $this->is_activation_page() ) {
7135 /**
7136 * If a user visits any other admin page before activating the premium-only theme with a valid
7137 * license, reactivate the previous theme.
7138 *
7139 * @author Leo Fajardo (@leorw)
7140 * @since 1.2.2
7141 */
7142 if ( $this->is_theme() &&
7143 ! $this->has_settings_menu() &&
7144 ! isset( $_REQUEST['fs_action'] ) &&
7145 $this->can_activate_previous_theme()
7146 ) {
7147 if ( $this->is_only_premium() ) {
7148 $this->activate_previous_theme();
7149 return;
7150 }
7151
7152 if ( true === $this->_storage->require_license_activation ) {
7153 $this->_storage->require_license_activation = false;
7154 }
7155 }
7156
7157 if ( ! fs_is_network_admin() &&
7158 $this->is_network_activation_mode() &&
7159 ! $this->is_delegated_connection()
7160 ) {
7161 return;
7162 }
7163
7164 if ( $this->is_plugin_new_install() || $this->is_only_premium() ) {
7165 if ( ! $this->_anonymous_mode &&
7166 ( ! $this->is_addon() || ! $this->_parent->is_anonymous() ) ) {
7167 // Show notice for new plugin installations.
7168 $this->_admin_notices->add(
7169 sprintf(
7170 $this->get_text_inline( 'You are just one step away - %s', 'you-are-step-away' ),
7171 sprintf( '<b><a href="%s">%s</a></b>',
7172 $this->get_activation_url( array(), ! $this->is_delegated_connection() ),
7173 sprintf( $this->get_text_x_inline( 'Complete "%s" Activation Now',
7174 '%s - plugin name. As complete "PluginX" activation now', 'activate-x-now' ), $this->get_plugin_name() )
7175 )
7176 ),
7177 '',
7178 'update-nag'
7179 );
7180 }
7181 } else {
7182 if ( $this->should_add_sticky_optin_notice() ) {
7183 $this->add_sticky_optin_admin_notice();
7184 }
7185
7186 if ( $this->has_filter( 'optin_pointer_element' ) ) {
7187 // Don't show admin nag if plugin update.
7188 wp_enqueue_script( 'wp-pointer' );
7189 wp_enqueue_style( 'wp-pointer' );
7190
7191 $this->_enqueue_connect_essentials();
7192
7193 add_action( 'admin_print_footer_scripts', array(
7194 $this,
7195 '_add_connect_pointer_script'
7196 ) );
7197 }
7198 }
7199 }
7200 }
7201
7202 if ( $this->show_opt_in_on_themes_page() &&
7203 $this->is_activation_page()
7204 ) {
7205 $this->_show_theme_activation_optin_dialog();
7206 }
7207 }
7208 }
7209
7210 /**
7211 * @author Vova Feldman (@svovaf)
7212 * @since 2.0.0
7213 *
7214 * @return bool
7215 */
7216 private function should_add_sticky_optin_notice() {
7217 if ( $this->is_addon() && $this->_parent->is_anonymous() ) {
7218 return false;
7219 }
7220
7221 if ( fs_is_network_admin() ) {
7222 if ( ! $this->_is_network_active ) {
7223 return false;
7224 }
7225
7226 if ( ! $this->is_network_activation_mode() ) {
7227 return false;
7228 }
7229
7230 return ! isset( $this->_storage->sticky_optin_added_ms );
7231 }
7232
7233 if ( ! $this->is_activation_mode() ) {
7234 return false;
7235 }
7236
7237 // If running from a blog admin and delegated the connection.
7238 return ! isset( $this->_storage->sticky_optin_added );
7239 }
7240
7241 /**
7242 * @author Leo Fajardo (@leorw)
7243 * @since 2.0.0
7244 */
7245 private function add_sticky_optin_admin_notice() {
7246 if ( ! $this->_is_network_active || ! fs_is_network_admin() ) {
7247 $this->_storage->sticky_optin_added = true;
7248 } else {
7249 $this->_storage->sticky_optin_added_ms = true;
7250 }
7251
7252 // Show notice for new plugin installations.
7253 $this->_admin_notices->add_sticky(
7254 sprintf(
7255 $this->get_text_inline( 'We made a few tweaks to the %s, %s', 'few-plugin-tweaks' ),
7256 $this->_module_type,
7257 sprintf( '<b><a href="%s">%s</a></b>',
7258 $this->get_activation_url(),
7259 sprintf( $this->get_text_inline( 'Opt in to make "%s" better!', 'optin-x-now' ), $this->get_plugin_name() )
7260 )
7261 ),
7262 'connect_account',
7263 '',
7264 'update-nag'
7265 );
7266 }
7267
7268 /**
7269 * Enqueue connect requires scripts and styles.
7270 *
7271 * @author Vova Feldman (@svovaf)
7272 * @since 1.1.4
7273 */
7274 function _enqueue_connect_essentials() {
7275 wp_enqueue_script( 'jquery' );
7276 wp_enqueue_script( 'json2' );
7277
7278 fs_enqueue_local_script( 'postmessage', 'nojquery.ba-postmessage.min.js' );
7279 fs_enqueue_local_script( 'fs-postmessage', 'postmessage.js' );
7280 }
7281
7282 /**
7283 * Add connect / opt-in pointer.
7284 *
7285 * @author Vova Feldman (@svovaf)
7286 * @since 1.1.4
7287 */
7288 function _add_connect_pointer_script() {
7289 $vars = array( 'id' => $this->_module_id );
7290 $pointer_content = fs_get_template( 'connect.php', $vars );
7291 ?>
7292 <script type="text/javascript">// <![CDATA[
7293 jQuery(document).ready(function ($) {
7294 if ('undefined' !== typeof(jQuery().pointer)) {
7295
7296 var element = <?php echo $this->apply_filters( 'optin_pointer_element', '$("#non_existing_element");' ) ?>;
7297
7298 if (element.length > 0) {
7299 var optin = $(element).pointer($.extend(true, {}, {
7300 content : <?php echo json_encode( $pointer_content ) ?>,
7301 position : {
7302 edge : 'left',
7303 align: 'center'
7304 },
7305 buttons : function () {
7306 // Don't show pointer buttons.
7307 return '';
7308 },
7309 pointerWidth: 482
7310 }, <?php echo $this->apply_filters( 'optin_pointer_options_json', '{}' ) ?>));
7311
7312 <?php
7313 echo $this->apply_filters( 'optin_pointer_execute', "
7314
7315 optin.pointer('open');
7316
7317 // Tag the opt-in pointer with custom class.
7318 $('.wp-pointer #fs_connect')
7319 .parents('.wp-pointer.wp-pointer-top')
7320 .addClass('fs-opt-in-pointer');
7321
7322 ", 'element', 'optin' ) ?>
7323 }
7324 }
7325 });
7326 // ]]></script>
7327 <?php
7328 }
7329
7330 /**
7331 * Return current page's URL.
7332 *
7333 * @author Vova Feldman (@svovaf)
7334 * @since 1.0.7
7335 *
7336 * @return string
7337 */
7338 static function current_page_url() {
7339 $url = 'http';
7340
7341 if ( isset( $_SERVER["HTTPS"] ) ) {
7342 if ( $_SERVER["HTTPS"] == "on" ) {
7343 $url .= "s";
7344 }
7345 }
7346 $url .= "://";
7347 if ( $_SERVER["SERVER_PORT"] != "80" ) {
7348 $url .= $_SERVER["SERVER_NAME"] . ":" . $_SERVER["SERVER_PORT"] . $_SERVER["REQUEST_URI"];
7349 } else {
7350 $url .= $_SERVER["SERVER_NAME"] . $_SERVER["REQUEST_URI"];
7351 }
7352
7353 return esc_url( $url );
7354 }
7355
7356 /**
7357 * Check if the current page is the plugin's main admin settings page.
7358 *
7359 * @author Vova Feldman (@svovaf)
7360 * @since 1.0.7
7361 *
7362 * @return bool
7363 */
7364 function _is_plugin_page() {
7365 return fs_is_plugin_page( $this->_menu->get_raw_slug() ) ||
7366 fs_is_plugin_page( $this->_slug );
7367 }
7368
7369 /* Events
7370 ------------------------------------------------------------------------------------------------------------------*/
7371 /**
7372 * Delete site install from Database.
7373 *
7374 * @author Vova Feldman (@svovaf)
7375 * @since 1.0.1
7376 *
7377 * @param bool $store
7378 * @param int|null $blog_id Since 2.0.0
7379 *
7380 * @return false|int The install ID if deleted. Otherwise, FALSE (when install not exist).
7381 */
7382 function _delete_site( $store = true, $blog_id = null ) {
7383 return self::_delete_site_by_slug( $this->_slug, $this->_module_type, $store, $blog_id );
7384 }
7385
7386 /**
7387 * Delete site install from Database.
7388 *
7389 * @author Vova Feldman (@svovaf)
7390 * @since 1.2.2.7
7391 *
7392 * @param string $slug
7393 * @param string $module_type
7394 * @param bool $store
7395 * @param int|null $blog_id Since 2.0.0
7396 *
7397 * @return false|int The install ID if deleted. Otherwise, FALSE (when install not exist).
7398 */
7399 static function _delete_site_by_slug( $slug, $module_type, $store = true, $blog_id = null ) {
7400 $sites = self::get_all_sites( $module_type, $blog_id );
7401
7402 $install_id = false;
7403
7404 if ( isset( $sites[ $slug ] ) ) {
7405 if ( is_object( $sites[ $slug ] ) ) {
7406 $install_id = $sites[ $slug ]->id;
7407 }
7408
7409 unset( $sites[ $slug ] );
7410
7411 self::set_account_option_by_module( $module_type, 'sites', $sites, $store, $blog_id );
7412 }
7413
7414 return $install_id;
7415 }
7416
7417 /**
7418 * Delete user.
7419 *
7420 * @author Vova Feldman (@svovaf)
7421 * @since 2.0.0
7422 *
7423 * @param number $user_id
7424 * @param bool $store
7425 *
7426 * @return false|int The user ID if deleted. Otherwise, FALSE (when install not exist).
7427 */
7428 private static function delete_user( $user_id, $store = true ) {
7429 $users = self::get_all_users();
7430
7431 if ( ! is_array( $users ) || ! isset( $users[ $user_id ] ) ) {
7432 return false;
7433 }
7434
7435 unset( $users[ $user_id ] );
7436
7437 self::$_accounts->set_option( 'users', $users, $store );
7438
7439 return $user_id;
7440 }
7441
7442 /**
7443 * Delete plugin's plans information.
7444 *
7445 * @param bool $store Flush to Database if true.
7446 * @param bool $keep_associated_plans If set to false, delete all plans, even if a plan is associated with an install.
7447 *
7448 * @author Vova Feldman (@svovaf)
7449 * @since 1.0.9
7450 */
7451 private function _delete_plans( $store = true, $keep_associated_plans = true ) {
7452 $this->_logger->entrance();
7453
7454 $plans = self::get_all_plans( $this->_module_type );
7455
7456 $plans_to_keep = array();
7457
7458 if ( $keep_associated_plans ) {
7459 $plans_ids_to_keep = $this->get_plans_ids_associated_with_installs();
7460 foreach ( $plans_ids_to_keep as $plan_id ) {
7461 $plan = self::_get_plan_by_id( $plan_id );
7462 if ( is_object( $plan ) ) {
7463 $plans_to_keep[] = self::_encrypt_entity( $plan );
7464 }
7465 }
7466 }
7467
7468 if ( ! empty( $plans_to_keep ) ) {
7469 $plans[ $this->_slug ] = $plans_to_keep;
7470 } else {
7471 unset( $plans[ $this->_slug ] );
7472 }
7473
7474 $this->set_account_option( 'plans', $plans, $store );
7475 }
7476
7477 /**
7478 * Delete all plugin licenses.
7479 *
7480 * @author Vova Feldman (@svovaf)
7481 * @since 1.0.9
7482 *
7483 * @param bool $store
7484 */
7485 private function _delete_licenses( $store = true ) {
7486 $this->_logger->entrance();
7487
7488 $all_licenses = self::get_all_licenses();
7489
7490 unset( $all_licenses[ $this->_module_id ] );
7491
7492 self::$_accounts->set_option( 'all_licenses', $all_licenses, $store );
7493 }
7494
7495 /**
7496 * Check if Freemius was added on new plugin installation.
7497 *
7498 * @author Vova Feldman (@svovaf)
7499 * @since 1.1.5
7500 *
7501 * @return bool
7502 */
7503 function is_plugin_new_install() {
7504 return isset( $this->_storage->is_plugin_new_install ) &&
7505 $this->_storage->is_plugin_new_install;
7506 }
7507
7508 /**
7509 * Check if it's the first plugin release that is running Freemius.
7510 *
7511 * @author Vova Feldman (@svovaf)
7512 * @since 1.2.1.5
7513 *
7514 * @return bool
7515 */
7516 function is_first_freemius_powered_version() {
7517 return empty( $this->_storage->plugin_last_version );
7518 }
7519
7520 /**
7521 * @author Leo Fajardo (@leorw)
7522 * @since 1.2.2
7523 *
7524 * @return bool|string
7525 */
7526 private function get_previous_theme_slug() {
7527 return isset( $this->_storage->previous_theme ) ?
7528 $this->_storage->previous_theme :
7529 false;
7530 }
7531
7532 /**
7533 * @author Leo Fajardo (@leorw)
7534 * @since 1.2.2
7535 *
7536 * @return bool
7537 */
7538 private function can_activate_previous_theme() {
7539 return $this->can_activate_theme( $this->get_previous_theme_slug() );
7540 }
7541
7542 /**
7543 * @author Leo Fajardo (@leorw)
7544 * @since 2.5.0
7545 *
7546 * @return bool
7547 */
7548 private function can_activate_theme( $slug ) {
7549 if ( false !== $slug && current_user_can( 'switch_themes' ) ) {
7550 $theme_instance = wp_get_theme( $slug );
7551
7552 return $theme_instance->exists();
7553 }
7554
7555 return false;
7556 }
7557
7558 /**
7559 * @author Leo Fajardo (@leorw)
7560 * @since 1.2.2
7561 */
7562 private function activate_previous_theme() {
7563 switch_theme( $this->get_previous_theme_slug() );
7564 unset( $this->_storage->previous_theme );
7565
7566 global $pagenow;
7567 if ( 'themes.php' === $pagenow ) {
7568 /**
7569 * Refresh the active theme information.
7570 *
7571 * @author Leo Fajardo (@leorw)
7572 * @since 1.2.2
7573 */
7574 fs_redirect( $this->admin_url( $pagenow ) );
7575 }
7576 }
7577
7578 /**
7579 * @author Leo Fajardo (@leorw)
7580 * @since 1.2.2
7581 *
7582 * @return string
7583 */
7584 function get_previous_theme_activation_url() {
7585 if ( ! $this->can_activate_previous_theme() ) {
7586 return '';
7587 }
7588
7589 /**
7590 * Activation URL
7591 *
7592 * @author Leo Fajardo (@leorw)
7593 * @since 1.2.2
7594 */
7595 return wp_nonce_url(
7596 $this->admin_url( 'themes.php?action=activate&stylesheet=' . urlencode( $this->get_previous_theme_slug() ) ),
7597 'switch-theme_' . $this->get_previous_theme_slug()
7598 );
7599 }
7600
7601 /**
7602 * Saves the slug of the previous theme if it still exists so that it can be used by the logic in the opt-in
7603 * form that decides whether to add a close button to the opt-in dialog or not. So after a premium-only theme is
7604 * activated, the close button will appear and will reactivate the previous theme if clicked. If the previous
7605 * theme doesn't exist, then there will be no close button.
7606 *
7607 * @author Leo Fajardo (@leorw)
7608 * @since 1.2.2
7609 *
7610 * @param string $slug_or_name Old theme's slug or name.
7611 * @param bool|WP_Theme $old_theme WP_Theme instance of the old theme if it still exists.
7612 */
7613 function _activate_theme_event_hook( $slug_or_name, $old_theme = false ) {
7614 $this->_storage->previous_theme = ( false !== $old_theme ) ?
7615 $old_theme->get_stylesheet() :
7616 $slug_or_name;
7617
7618 $this->_activate_plugin_event_hook();
7619 }
7620
7621 /**
7622 * Plugin activated hook.
7623 *
7624 * @author Vova Feldman (@svovaf)
7625 * @since 1.0.1
7626 *
7627 * @uses FS_Api
7628 */
7629 function _activate_plugin_event_hook() {
7630 $this->_logger->entrance( 'slug = ' . $this->_slug );
7631
7632 if ( ! $this->is_user_admin() ) {
7633 return;
7634 }
7635
7636 $this->unregister_uninstall_hook();
7637
7638 // Clear API cache on activation.
7639 FS_Api::clear_cache();
7640
7641 $is_premium_version_activation = $this->is_plugin() ?
7642 ( current_filter() !== ( 'activate_' . $this->_free_plugin_basename ) ) :
7643 $this->is_premium();
7644
7645 if ( $is_premium_version_activation && $this->is_pending_activation() ) {
7646 $this->clear_pending_activation_mode();
7647 }
7648
7649 $this->_logger->info( 'Activating ' . ( $is_premium_version_activation ? 'premium' : 'free' ) . ' plugin version.' );
7650
7651 if ( $this->is_plugin() ) {
7652 // This logic is relevant only to plugins since both the free and premium versions of a plugin can be active at the same time.
7653 // 1. If running in the activation of the FREE module, get the basename of the PREMIUM.
7654 // 2. If running in the activation of the PREMIUM module, get the basename of the FREE.
7655 $other_version_basename = $is_premium_version_activation ?
7656 $this->_free_plugin_basename :
7657 $this->premium_plugin_basename();
7658
7659 if ( ! $this->_is_network_active ) {
7660 /**
7661 * Themes are always network activated, but the ACTUAL activation is per site.
7662 *
7663 * During the activation, the plugin isn't yet active, therefore,
7664 * _is_network_active will be set to false even if it's a network level
7665 * activation. So we need to fix that by looking at the is_network_admin() value.
7666 *
7667 * @author Vova Feldman
7668 */
7669 $this->_is_network_active = (
7670 $this->_is_multisite_integrated &&
7671 fs_is_network_admin()
7672 );
7673 }
7674
7675 /**
7676 * If the other module version is active, deactivate it.
7677 *
7678 * is_plugin_active() checks if the plugin is active on the site or the network level and
7679 * deactivate_plugins() deactivates the plugin whether it's activated on the site or network level.
7680 *
7681 * @author Leo Fajardo (@leorw)
7682 * @since 1.2.2
7683 */
7684 if (
7685 is_plugin_active( $other_version_basename ) &&
7686 $this->apply_filters( 'deactivate_on_activation', true )
7687 ) {
7688 deactivate_plugins( $other_version_basename );
7689 }
7690 }
7691
7692 if ( $this->is_registered() ) {
7693 if ( $is_premium_version_activation ) {
7694 $this->reconnect_locally();
7695 }
7696
7697
7698 // Schedule re-activation event and sync.
7699 // $this->sync_install( array(), true );
7700 $this->schedule_install_sync();
7701
7702 // If activating the premium module version, add an admin notice to congratulate for an upgrade completion.
7703 if ( $is_premium_version_activation ) {
7704 $this->_admin_notices->add(
7705 sprintf( $this->get_text_inline( 'The upgrade of %s was successfully completed.', 'successful-version-upgrade-message' ), sprintf( '<b>%s</b>', $this->_plugin->title ) ),
7706 $this->get_text_x_inline( 'W00t',
7707 'Used to express elation, enthusiasm, or triumph (especially in electronic communication).', 'woot' ) . '!'
7708 );
7709 }
7710 } else if ( $this->is_anonymous() ) {
7711 if ( isset( $this->_storage->is_anonymous_ms ) && $this->_storage->is_anonymous_ms['is'] ) {
7712 $plugin_version = $this->_storage->is_anonymous_ms['version'];
7713 $network = true;
7714 } else {
7715 $plugin_version = isset( $this->_storage->is_anonymous ) ?
7716 $this->_storage->is_anonymous['version'] :
7717 null;
7718 $network = false;
7719 }
7720
7721 /**
7722 * Reset "skipped" click cache on the following:
7723 * 1. Freemius DEV mode.
7724 * 2. WordPress DEBUG mode.
7725 * 3. If a plugin and the user skipped the exact same version before.
7726 *
7727 * @since 1.2.2.7 Ulrich Pogson (@grapplerulrich) asked to not reset the SKIPPED flag if the exact same THEME version was activated before unless the developer is running with WP_DEBUG on, or Freemius debug mode on (WP_FS__DEV_MODE).
7728 *
7729 * @todo 4. If explicitly asked to retry after every activation.
7730 */
7731 if ( WP_FS__DEV_MODE ||
7732 (
7733 ( $this->is_plugin() || ( defined( 'WP_DEBUG' ) && WP_DEBUG ) ) &&
7734 $this->get_plugin_version() == $plugin_version
7735 )
7736 ) {
7737 $this->reset_anonymous_mode( $network );
7738 }
7739 }
7740
7741 $is_trial_or_has_features_enabled_license = ( $this->is_trial() || $this->has_features_enabled_license() );
7742
7743 if ( $this->is_addon() && ! $is_trial_or_has_features_enabled_license ) {
7744 /**
7745 * When activating an add-on, try to also activate a license.
7746 *
7747 * @author Leo Fajardo (@leorw)
7748 * @since 2.3.0
7749 */
7750 if ( ! $this->_is_network_active ) {
7751 $this->maybe_activate_addon_license();
7752 } else {
7753 $this->maybe_network_activate_addon_license();
7754 }
7755
7756 /**
7757 * Avoid redirecting to the license activation screen after automatically activating an add-on license.
7758 *
7759 * @author Leo Fajardo (@leorw)
7760 * @since 2.3.0
7761 */
7762 $is_trial_or_has_features_enabled_license = ( $this->is_trial() || $this->has_features_enabled_license() );
7763
7764 if ( $is_trial_or_has_features_enabled_license && true === $this->_storage->require_license_activation ) {
7765 $this->_storage->require_license_activation = false;
7766 }
7767 }
7768
7769 if (
7770 $is_premium_version_activation &&
7771 (
7772 ( ! $this->is_registered() && $this->is_anonymous() ) ||
7773 (
7774 $this->is_registered() &&
7775 ! $is_trial_or_has_features_enabled_license
7776 )
7777 )
7778 ) {
7779 $this->_storage->require_license_activation = true;
7780 }
7781
7782 if ( ! isset( $this->_storage->is_plugin_new_install ) ) {
7783 /**
7784 * If no previous version of plugin's version exist, it means that it's either
7785 * the first time that the plugin installed on the site, or the plugin was installed
7786 * before but didn't have Freemius integrated.
7787 *
7788 * Since register_activation_hook() do NOT fires on updates since 3.1, and only fires
7789 * on manual activation via the dashboard, is_plugin_activation() is TRUE
7790 * only after immediate activation.
7791 *
7792 * @since 1.1.4
7793 * @link https://make.wordpress.org/core/2010/10/27/plugin-activation-hooks-no-longer-fire-for-updates/
7794 */
7795 $this->_storage->is_plugin_new_install = empty( $this->_storage->plugin_last_version );
7796 }
7797
7798 /**
7799 * Also flush when activating the premium version so that even if Freemius was off before, the API
7800 * connectivity test can be run again.
7801 *
7802 * @author Leo Fajardo (@leorw)
7803 * @since 2.2.3.1
7804 */
7805 $has_api_connectivity = $this->has_api_connectivity( WP_FS__DEV_MODE || $is_premium_version_activation );
7806
7807 if ( ! $this->_anonymous_mode &&
7808 ( false !== $has_api_connectivity ) &&
7809 ! $this->_isAutoInstall
7810 ) {
7811 // Store hint that the plugin was just activated to enable auto-redirection to settings.
7812 set_transient( "fs_{$this->_module_type}_{$this->_slug}_activated", true, 60 );
7813 }
7814
7815 /**
7816 * Activation hook is executed after the plugin's main file is loaded, therefore,
7817 * after the plugin was loaded. The logic is located at activate_plugin()
7818 * ./wp-admin/includes/plugin.php.
7819 *
7820 * @author Vova Feldman (@svovaf)
7821 * @since 1.1.9
7822 */
7823 $this->_storage->was_plugin_loaded = true;
7824 }
7825
7826 /**
7827 * @author Leo Fajardo (@leorw)
7828 * @since 2.3.0
7829 */
7830 private function maybe_activate_addon_license() {
7831 $parent_fs = $this->get_parent_instance();
7832
7833 if (
7834 ! is_object( $parent_fs ) ||
7835 ( ! $parent_fs->is_registered() && ! $parent_fs->is_network_registered() )
7836 ) {
7837 // Try to activate a license only if the parent plugin is active and has a valid `install`.
7838 return;
7839 }
7840
7841 $license = $this->get_active_parent_license();
7842 if ( ! is_object( $license ) ) {
7843 return;
7844 }
7845
7846 if (
7847 $this->is_bundle_license_auto_activation_enabled() &&
7848 ! empty( $license->products )
7849 ) {
7850 $this->activate_bundle_license( $license );
7851
7852 return;
7853 }
7854
7855 if ( ! $this->is_registered() ) {
7856 // Opt in with a license key.
7857 $this->opt_in(
7858 $parent_fs->get_current_or_network_user()->email,
7859 false,
7860 false,
7861 $license->secret_key
7862 );
7863 } else {
7864 // Activate the license.
7865 $install = $this->api_site_call(
7866 '/',
7867 'put',
7868 array( 'license_key' => $this->apply_filters( 'license_key', $license->secret_key ) )
7869 );
7870
7871 if ( ! FS_Api::is_api_error( $install ) ) {
7872 $this->_sync_addon_license( $this->get_id(), true );
7873 }
7874 }
7875 }
7876
7877 /**
7878 * @author Leo Fajardo (@leorw)
7879 * @since 2.3.0
7880 *
7881 * @param FS_Plugin_License $license
7882 */
7883 private function maybe_network_activate_addon_license( $license = null ) {
7884 $parent_fs = $this->get_parent_instance();
7885 if ( ! is_object( $parent_fs ) || ( ! $parent_fs->is_registered() && ! $parent_fs->is_network_registered() ) ) {
7886 // Try to activate a license only if the parent plugin is active and has a valid `install`.
7887 return;
7888 }
7889
7890 $license = ( ! is_null( $license ) ) ?
7891 $license :
7892 $this->get_active_parent_license();
7893
7894 if ( ! is_object( $license ) ) {
7895 return;
7896 }
7897
7898 if (
7899 $this->is_bundle_license_auto_activation_enabled() &&
7900 ! empty( $license->products )
7901 ) {
7902 $this->activate_bundle_license( $license );
7903
7904 return;
7905 }
7906
7907 if ( ! $this->is_network_registered() ) {
7908 $sites = $this->get_sites_for_network_level_optin();
7909
7910 if ( count( $sites ) > $license->left() ) {
7911 // If the add-on is network active, try to activate the license only if it can be activated on all sites.
7912 return;
7913 }
7914
7915 // Opt in with a license key.
7916 $this->opt_in(
7917 $parent_fs->get_user()->email,
7918 false,
7919 false,
7920 $license->secret_key,
7921 false,
7922 false,
7923 false,
7924 null,
7925 $sites
7926 );
7927 } else {
7928 $blog_2_install_map = array();
7929 $site_ids = array();
7930
7931 $all_sites = Freemius::get_sites();
7932
7933 foreach ( $all_sites as $site ) {
7934 $blog_id = Freemius::get_site_blog_id( $site );
7935 $install = $this->get_install_by_blog_id( $blog_id );
7936
7937 if ( is_object( $install ) && FS_Plugin_License::is_valid_id( $install->license_id ) ) {
7938 // Skip license activation for installs that are already associated with a license.
7939 continue;
7940 }
7941
7942 if ( is_object( $install ) ) {
7943 $blog_2_install_map[ $blog_id ] = $install;
7944 } else {
7945 $site_ids[] = $blog_id;
7946 }
7947 }
7948
7949 if ( ( count( $blog_2_install_map ) + count( $site_ids ) ) > $license->left() ) {
7950 return;
7951 }
7952
7953 $user = $this->get_current_or_network_user();
7954
7955 if ( ! empty( $blog_2_install_map ) ) {
7956 $result = $this->activate_license_on_many_installs( $user, $license->secret_key, $blog_2_install_map );
7957
7958 if ( true !== $result ) {
7959 return;
7960 }
7961 }
7962
7963 if ( ! empty( $site_ids ) ) {
7964 $this->activate_license_on_many_sites( $user, $license->secret_key, $site_ids );
7965 }
7966 }
7967 }
7968
7969 /**
7970 * Tries to activate a bundle license for all supported products if the current product is activated with a bundle license. This is called after activating an available license (not via the license activation dialog but by clicking on a license activation button) for a product via its "Account" page.
7971 *
7972 * @author Leo Fajardo (@leorw)
7973 * @since 2.4.0
7974 *
7975 * @param FS_Plugin_License $license
7976 * @param array $sites
7977 * @param int $blog_id
7978 */
7979 private function maybe_activate_bundle_license( FS_Plugin_License $license = null, $sites = array(), $blog_id = 0 ) {
7980 if ( ! is_object( $license ) && $this->has_active_valid_license() ) {
7981 $license = $this->_license;
7982 }
7983
7984 if ( ! is_object( $license ) ) {
7985 return;
7986 }
7987
7988 $parent_license = ( ! empty( $license->products ) ) ?
7989 $license :
7990 $this->get_active_parent_license( $license->secret_key );
7991
7992 if ( is_object( $parent_license ) ) {
7993 $this->activate_bundle_license( $parent_license, $sites, $blog_id );
7994 }
7995 }
7996
7997 /**
7998 * Try to activate a bundle license for all the bundle products installed on the site.
7999 * (1) If a child product install already has a license, the bundle license won't be activated.
8000 * (2) On multi-site networks, if the attempt to activate the bundle license is triggered from the network admin, the bundle license activation will only work for non-delegated sites and only if none of them is associated with a license. Even if one of the sites has the product installed with a license key, skip the bundle license activation for the product.
8001 * (3) On multi-site networks, if the attempt to activate the bundle license is triggered from a site-level admin, only activate the license if the product is site-level activated or delegated, and the product installation is not yet associated with a license.
8002 *
8003 * @author Leo Fajardo (@leorw)
8004 * @since 2.4.0
8005 *
8006 * @param FS_Plugin_License $license
8007 * @param array $sites
8008 * @param int $current_blog_id
8009 */
8010 private function activate_bundle_license( $license, $sites = array(), $current_blog_id = 0 ) {
8011 $is_network_admin = fs_is_network_admin();
8012
8013 $installs_by_blog_map = array();
8014 $site_info_by_blog_map = array();
8015
8016 /**
8017 * Try to activate the license for all supported products.
8018 *
8019 * @author Leo Fajardo
8020 */
8021 foreach ( $license->products as $product_id ) {
8022 $fs = self::get_instance_by_id( $product_id );
8023
8024 if ( ! is_object( $fs ) ) {
8025 continue;
8026 }
8027
8028 if ( ! $fs->has_paid_plan() ) {
8029 continue;
8030 }
8031
8032 if (
8033 ! $fs->is_addon() &&
8034 ! FS_Plan_Manager::instance()->has_paid_plan( $fs->_plans )
8035 ) {
8036 /**
8037 * The parent product can be free-only but can have its `has_paid_plan` flag set to `true` when
8038 * there is a context bundle.
8039 */
8040 continue;
8041 }
8042
8043 if ( $current_blog_id > 0 ) {
8044 $fs->switch_to_blog( $current_blog_id );
8045 }
8046
8047 if ( $fs->has_active_valid_license() ) {
8048 continue;
8049 }
8050
8051 if ( ! $is_network_admin || $current_blog_id > 0 ) {
8052 if ( $fs->is_network_active() && ! $fs->is_delegated_connection( $current_blog_id ) ) {
8053 // Do not try to activate the license in the site level if the product is network active and the connection was not delegated.
8054 continue;
8055 }
8056 } else {
8057 if ( ! $fs->is_network_active() ) {
8058 // Do not try to activate the license in the network level if the product is not network active.
8059 continue;
8060 }
8061
8062 if ( $fs->is_network_delegated_connection() ) {
8063 // Do not try to activate the license in the network level if the activation has been delegated to site admins.
8064 continue;
8065 }
8066
8067 $has_install_with_license = false;
8068
8069 // Collection of sites that have an install entity that is not activated with a license or non-delegated sites that have no install entity, or both types of site.
8070 $filtered_sites = array();
8071
8072 if ( empty( $sites ) ) {
8073 $all_sites = self::get_sites();
8074
8075 foreach ( $all_sites as $site ) {
8076 $sites[] = array( 'blog_id' => self::get_site_blog_id( $site ) );
8077 }
8078 } else {
8079 // Populate the map here to avoid calling `$fs->get_site_info( $site );` in the other `for` loop below.
8080 foreach ( $sites as $site ) {
8081 if ( ! isset( $site['blog_id'] ) || ! is_numeric( $site['blog_id'] ) ) {
8082 continue;
8083 }
8084
8085 $site_info_by_blog_map[ $site['blog_id'] ] = $site;
8086 }
8087 }
8088
8089 foreach ( $sites as $site ) {
8090 if ( ! isset( $site['blog_id'] ) || ! is_numeric( $site['blog_id'] ) ) {
8091 continue;
8092 }
8093
8094 $blog_id = $site['blog_id'];
8095
8096 if ( ! isset( $installs_by_blog_map[ $blog_id ] ) ) {
8097 $installs_by_blog_map[ $blog_id ] = self::get_all_sites( $fs->get_module_type(), $blog_id );
8098 }
8099
8100 $installs = $installs_by_blog_map[ $blog_id ];
8101 $install = null;
8102
8103 if ( isset( $installs[ $fs->get_slug() ] ) ) {
8104 $install = $installs[ $fs->get_slug() ];
8105
8106 if (
8107 is_object( $install ) &&
8108 (
8109 ! FS_Site::is_valid_id( $install->id ) ||
8110 ! FS_User::is_valid_id( $install->user_id ) ||
8111 ! FS_Plugin_Plan::is_valid_id( $install->plan_id )
8112 )
8113 ) {
8114 $install = null;
8115 }
8116 }
8117
8118 if (
8119 is_object( $install ) &&
8120 FS_Plugin_License::is_valid_id( $install->license_id )
8121 ) {
8122 $has_install_with_license = true;
8123 break;
8124 }
8125
8126 if ( $fs->is_site_delegated_connection( $blog_id ) ) {
8127 // Site activation delegated, don't activate bundle license on the site in the network admin.
8128 continue;
8129 }
8130
8131 if ( ! isset( $site_info_by_blog_map[ $blog_id ] ) ) {
8132 $site_info_by_blog_map[ $blog_id ] = $fs->get_site_info( $site );
8133 }
8134
8135 $filtered_sites[] = $site_info_by_blog_map[ $blog_id ];
8136 }
8137
8138 if ( $has_install_with_license || empty( $filtered_sites ) ) {
8139 // Do not try to activate the license at the network level if there's any install with a license or there's no site to activate the license on.
8140 continue;
8141 }
8142
8143 $sites = $filtered_sites;
8144 }
8145
8146 $fs->activate_migrated_license(
8147 $license->secret_key,
8148 null,
8149 null,
8150 $sites,
8151 ( $current_blog_id > 0 ? $current_blog_id : null )
8152 );
8153 }
8154 }
8155
8156 /**
8157 * Returns a parent license that can be activated for the context product.
8158 *
8159 * @author Leo Fajardo (@leorw)
8160 * @since 2.3.0
8161 *
8162 * @param string|null $license_key
8163 * @param bool $flush
8164 *
8165 * @return FS_Plugin_License
8166 */
8167 function get_active_parent_license( $license_key = null, $flush = true ) {
8168 $parent_licenses_endpoint = "/plugins/{$this->get_id()}/parent_licenses.json?filter=activatable";
8169
8170 $fs = $this;
8171
8172 if ( $this->is_addon() ) {
8173 $parent_instance = $this->get_parent_instance();
8174
8175 if ( is_object( $parent_instance ) && $parent_instance->is_registered() ) {
8176 $fs = $parent_instance;
8177 }
8178 }
8179
8180 $foreign_licenses = $fs->get_foreign_licenses_info(
8181 self::get_all_licenses( $this->get_parent_id() )
8182 );
8183
8184 if ( ! empty ( $foreign_licenses ) ) {
8185 $foreign_licenses = array(
8186 // Prefix with `+` to tell the server to include foreign licenses in the licenses collection.
8187 'ids' => ( urlencode( '+' ) . implode( ',', $foreign_licenses['ids'] ) ),
8188 'license_keys' => implode( ',', array_map( 'urlencode', $foreign_licenses['license_keys'] ) )
8189 );
8190
8191 $parent_licenses_endpoint = add_query_arg( $foreign_licenses, $parent_licenses_endpoint );
8192 }
8193
8194 $result = $fs->get_current_or_network_user_api_scope()->get( $parent_licenses_endpoint, $flush );
8195
8196 if (
8197 ! $this->is_api_result_object( $result, 'licenses' ) ||
8198 ! is_array( $result->licenses ) ||
8199 empty( $result->licenses )
8200 ) {
8201 return null;
8202 }
8203
8204 $parent_license = null;
8205
8206 if ( empty( $license_key ) ) {
8207 $parent_license = $result->licenses[0];
8208 } else {
8209 foreach ( $result->licenses as $license ) {
8210 if ( $license_key === $license->secret_key ) {
8211 $parent_license = $license;
8212 break;
8213 }
8214 }
8215 }
8216
8217 if ( ! is_null( $parent_license ) ) {
8218 $parent_license = new FS_Plugin_License( $parent_license );
8219 }
8220
8221 return $parent_license;
8222 }
8223
8224 /**
8225 * @author Leo Fajardo (@leorw)
8226 * @since 2.3.0
8227 *
8228 * @return array
8229 */
8230 function get_sites_for_network_level_optin() {
8231 $sites = array();
8232 $all_sites = self::get_sites();
8233
8234 foreach ( $all_sites as $site ) {
8235 $blog_id = self::get_site_blog_id( $site );
8236
8237 if ( ! $this->is_site_delegated_connection( $blog_id ) &&
8238 ! $this->is_installed_on_site( $blog_id )
8239 ) {
8240 $sites[] = $this->get_site_info( $site );
8241 }
8242 }
8243
8244 return $sites;
8245 }
8246
8247 /**
8248 * Delete account.
8249 *
8250 * @author Vova Feldman (@svovaf)
8251 * @since 1.0.3
8252 *
8253 * @param bool $check_user Enforce checking if user have plugins activation privileges.
8254 */
8255 function delete_account_event( $check_user = true ) {
8256 $this->_logger->entrance( 'slug = ' . $this->_slug );
8257
8258 if ( $check_user && ! $this->is_user_admin() ) {
8259 return;
8260 }
8261
8262 $this->do_action( 'before_account_delete' );
8263
8264 // Clear all admin notices.
8265 $this->_admin_notices->clear_all_sticky( false );
8266
8267 $this->_delete_site( false );
8268
8269 $delete_network_common_data = true;
8270
8271 if ( $this->_is_network_active ) {
8272 $installs = $this->get_blog_install_map();
8273
8274 // Don't delete common network data unless no other installs left.
8275 $delete_network_common_data = empty( $installs );
8276 }
8277
8278 if ( $delete_network_common_data ) {
8279 $this->_delete_plans( false );
8280
8281 $this->_delete_licenses( false );
8282
8283 // Delete add-ons related to plugin's account.
8284 $this->_delete_account_addons( false );
8285 }
8286
8287 // @todo Delete plans and licenses of add-ons.
8288
8289 self::$_accounts->store();
8290
8291 /**
8292 * IMPORTANT:
8293 * Clear crons must be executed before clearing all storage.
8294 * Otherwise, the cron will not be cleared.
8295 */
8296 if ( $delete_network_common_data ) {
8297 $this->clear_sync_cron();
8298 }
8299
8300 $this->clear_install_sync_cron();
8301
8302 // Clear all storage data.
8303 $this->_storage->clear_all( true, array(
8304 'is_delegated_connection',
8305 'connectivity_test',
8306 'is_on',
8307 ), false );
8308
8309 // Send delete event.
8310 $this->get_api_site_scope()->call( '/', 'delete' );
8311
8312 $this->do_action( 'after_account_delete' );
8313 }
8314
8315 /**
8316 * Delete network level account.
8317 *
8318 * @author Vova Feldman (@svovaf)
8319 * @since 2.0.0
8320 *
8321 * @param bool $check_user Enforce checking if user have plugins activation privileges.
8322 */
8323 function delete_network_account_event( $check_user = true ) {
8324 $this->_logger->entrance( 'slug = ' . $this->_slug );
8325
8326 if ( $check_user && ! $this->is_user_admin() ) {
8327 return;
8328 }
8329
8330 $this->do_action( 'before_network_account_delete' );
8331
8332 // Clear all admin notices.
8333 $this->_admin_notices->clear_all_sticky();
8334
8335 $this->_delete_plans( false, false );
8336
8337 $this->_delete_licenses( false );
8338
8339 // Delete add-ons related to plugin's account.
8340 $this->_delete_account_addons( false );
8341
8342 // @todo Delete plans and licenses of add-ons.
8343
8344 self::$_accounts->store( true );
8345
8346 /**
8347 * IMPORTANT:
8348 * Clear crons must be executed before clearing all storage.
8349 * Otherwise, the cron will not be cleared.
8350 */
8351 $this->clear_sync_cron( true );
8352 $this->clear_install_sync_cron( true );
8353
8354 $sites = self::get_sites();
8355
8356 $install_ids = array();
8357 foreach ( $sites as $site ) {
8358 $blog_id = self::get_site_blog_id( $site );
8359
8360 if ( $this->is_site_delegated_connection( $blog_id ) ) {
8361 continue;
8362 }
8363
8364 $install_id = $this->_delete_site( true, $blog_id );
8365
8366 // Clear all storage data.
8367 $this->_storage->clear_all( true, array( 'connectivity_test' ), $blog_id );
8368
8369 if ( FS_Site::is_valid_id( $install_id ) ) {
8370 $install_ids[] = $install_id;
8371 }
8372
8373 switch_to_blog( $blog_id );
8374
8375 $this->do_action( 'after_account_delete' );
8376
8377 restore_current_blog();
8378 }
8379
8380 $this->_storage->clear_all( true, array(
8381 'connectivity_test',
8382 'is_on',
8383 ), true );
8384
8385 // Send delete event.
8386 if ( ! empty( $install_ids ) ) {
8387 $result = $this->get_current_or_network_user_api_scope()->call( "/plugins/{$this->_module_id}/installs.json?ids=" . implode( ',', $install_ids ), 'delete' );
8388 }
8389
8390 $this->do_action( 'after_network_account_delete' );
8391 }
8392
8393 /**
8394 * Plugin deactivation hook.
8395 *
8396 * @author Vova Feldman (@svovaf)
8397 * @since 1.0.1
8398 */
8399 function _deactivate_plugin_hook() {
8400 $this->_logger->entrance( 'slug = ' . $this->_slug );
8401
8402 if ( ! $this->is_user_admin() ) {
8403 return;
8404 }
8405
8406 $is_network_deactivation = fs_is_network_admin();
8407 $storage_keys_for_removal = array();
8408
8409 $this->_admin_notices->clear_all_sticky();
8410
8411 $storage_keys_for_removal[] = 'sticky_optin_added';
8412 if ( isset( $this->_storage->sticky_optin_added ) ) {
8413 unset( $this->_storage->sticky_optin_added );
8414 }
8415
8416 if ( ! isset( $this->_storage->is_plugin_new_install ) ) {
8417 // Remember that plugin was already installed.
8418 $this->_storage->is_plugin_new_install = false;
8419 }
8420
8421 // Hook to plugin uninstall.
8422 register_uninstall_hook( $this->_plugin_main_file_path, array( 'Freemius', '_uninstall_plugin_hook' ) );
8423
8424 $this->clear_module_main_file_cache();
8425 $this->clear_sync_cron( $this->_is_network_active );
8426 $this->clear_install_sync_cron();
8427
8428 if ( $this->is_registered() ) {
8429 if ( $this->is_premium() && ! $this->has_active_valid_license() ) {
8430 FS_Plugin_Updater::instance( $this )->delete_update_data();
8431 }
8432
8433 if ( $is_network_deactivation ) {
8434 // Send deactivation event.
8435 $this->sync_installs( array(
8436 'is_active' => false,
8437 ) );
8438 } else {
8439 // Send deactivation event.
8440 $this->sync_install( array(
8441 'is_active' => false,
8442 ) );
8443 }
8444 } else {
8445 if ( false === $this->has_api_connectivity() && ! $this->is_premium() ) {
8446 // Reset connectivity test cache.
8447 $this->clear_connectivity_info();
8448
8449 $storage_keys_for_removal[] = 'connectivity_test';
8450 }
8451 }
8452
8453 if ( $is_network_deactivation ) {
8454 if ( isset( $this->_storage->sticky_optin_added_ms ) ) {
8455 unset( $this->_storage->sticky_optin_added_ms );
8456 }
8457
8458 if ( ! empty( $storage_keys_for_removal ) ) {
8459 $sites = self::get_sites();
8460
8461 foreach ( $sites as $site ) {
8462 $blog_id = self::get_site_blog_id( $site );
8463
8464 foreach ( $storage_keys_for_removal as $key ) {
8465 $this->_storage->remove( $key, false, $blog_id );
8466 }
8467
8468 $this->_storage->save( $blog_id );
8469 }
8470 }
8471 }
8472
8473 // Clear API cache on deactivation.
8474 FS_Api::clear_cache();
8475
8476 $this->remove_sdk_reference();
8477 }
8478
8479 /**
8480 * @author Vova Feldman (@svovaf)
8481 * @since 1.1.6
8482 */
8483 private function remove_sdk_reference() {
8484 global $fs_active_plugins;
8485
8486 foreach ( $fs_active_plugins->plugins as $sdk_path => $data ) {
8487 if ( $this->_plugin_basename == $data->plugin_path ) {
8488 unset( $fs_active_plugins->plugins[ $sdk_path ] );
8489 break;
8490 }
8491 }
8492
8493 fs_fallback_to_newest_active_sdk();
8494 }
8495
8496 /**
8497 * @author Vova Feldman (@svovaf)
8498 * @since 1.1.3
8499 *
8500 * @param bool $is_anonymous
8501 * @param bool|int $network_or_blog_id Since 2.0.0
8502 */
8503 private function set_anonymous_mode( $is_anonymous = true, $network_or_blog_id = 0 ) {
8504 // Store information regarding skip to try and opt-in the user
8505 // again in the future.
8506 $skip_info = array(
8507 'is' => $is_anonymous,
8508 'timestamp' => WP_FS__SCRIPT_START_TIME,
8509 'version' => $this->get_plugin_version(),
8510 );
8511
8512 if ( true === $network_or_blog_id ) {
8513 $this->_storage->is_anonymous_ms = $skip_info;
8514 } else {
8515 $this->_storage->store( 'is_anonymous', $skip_info, $network_or_blog_id );
8516 }
8517
8518 $this->network_upgrade_mode_completed();
8519
8520 // Update anonymous mode cache.
8521 $this->_is_anonymous = $is_anonymous;
8522 }
8523
8524 /**
8525 * @author Vova Feldman (@svovaf)
8526 * @since 2.5.1
8527 *
8528 * @param bool|int $network_or_blog_id
8529 */
8530 private function unset_anonymous_mode( $network_or_blog_id = 0 ) {
8531 if ( true === $network_or_blog_id ) {
8532 unset( $this->_storage->is_anonymous_ms );
8533 } else {
8534 $this->_storage->remove( 'is_anonymous', true, $network_or_blog_id );
8535 }
8536 }
8537
8538 /**
8539 * @author Vova Feldman (@svovaf)
8540 * @since 2.0.0
8541 *
8542 * @param int $blog_id Site ID.
8543 * @param int $user_id User ID.
8544 * @param string $domain Site domain.
8545 * @param string $path Site path.
8546 * @param int $network_id Network ID. Only relevant on multi-network installations.
8547 * @param array $meta Metadata. Used to set initial site options.
8548 *
8549 * @uses Freemius::is_license_network_active() to check if the context license was network activated by the super-admin.
8550 * @uses Freemius::is_network_connected() to check if the super-admin network opted-in.
8551 * @uses Freemius::is_network_anonymous() to check if the super-admin network skipped.
8552 * @uses Freemius::is_network_delegated_connection() to check if the super-admin network delegated the connection to the site admins.
8553 */
8554 public function _after_new_blog_callback( $blog_id, $user_id, $domain, $path, $network_id, $meta ) {
8555 $this->_logger->entrance();
8556
8557 if ( ! $this->_is_network_active ) {
8558 FS_Clone_Manager::instance()->store_blog_install_info( $blog_id );
8559 return;
8560 }
8561
8562 $site = null;
8563 $new_blog_id = $blog_id;
8564
8565 if ( $this->is_premium() &&
8566 $this->is_network_connected() &&
8567 is_object( $this->_license ) &&
8568 $this->_license->can_activate( FS_Site::is_localhost_by_address( $domain ) ) &&
8569 $this->is_license_network_active( $blog_id )
8570 ) {
8571 /**
8572 * Running the premium version, the license was network activated, and the license can also be activated on the current site -> so try to opt-in with the license key.
8573 */
8574 $current_blog_id = get_current_blog_id();
8575 $license = clone $this->_license;
8576
8577 $this->switch_to_blog( $blog_id );
8578
8579 // Opt-in with network user.
8580 $this->install_with_user(
8581 $this->get_network_user(),
8582 $license->secret_key,
8583 false,
8584 false,
8585 false
8586 );
8587
8588 if ( is_object( $this->_site ) ) {
8589 if ( $this->_site->license_id == $license->id ) {
8590 /**
8591 * If the license was activated successfully, sync the license data from the remote server.
8592 */
8593 $this->_license = $license;
8594 $this->sync_site_license();
8595 }
8596 }
8597
8598 $site = $this->_site;
8599
8600 $this->switch_to_blog( $current_blog_id );
8601
8602 if ( is_object( $site ) ) {
8603 FS_Clone_Manager::instance()->store_blog_install_info( $blog_id, $site );
8604
8605 // Already connected (with or without a license), so no need to continue.
8606 return;
8607 }
8608 }
8609
8610 if ( $this->is_network_anonymous() ) {
8611 /**
8612 * Opt-in was network skipped so automatically skip the opt-in for the new site.
8613 */
8614 $this->skip_site_connection( $blog_id );
8615 } else if ( $this->is_network_delegated_connection() ) {
8616 /**
8617 * Opt-in was network delegated so automatically delegate the opt-in for the new site's admin.
8618 */
8619 $this->delegate_site_connection( $blog_id );
8620 } else if ( $this->is_network_connected() ) {
8621 /**
8622 * Opt-in was network activated so automatically opt-in with the network user and new site admin.
8623 */
8624 $current_blog_id = get_current_blog_id();
8625
8626 $this->switch_to_blog( $blog_id );
8627
8628 // Opt-in with network user.
8629 $this->install_with_user(
8630 $this->get_network_user(),
8631 false,
8632 false,
8633 false,
8634 false
8635 );
8636
8637 $site = $this->_site;
8638
8639 $this->switch_to_blog( $current_blog_id );
8640 } else {
8641 /**
8642 * If the super-admin mixed different options (connect, skip, delegated):
8643 * a) If at least one site connection was delegated, then automatically delegate connection.
8644 * b) Otherwise, it means that at least one site was skipped and at least one site was connected. For a simplified UX in the initial release of the multisite network integration, skip the connection for the newly created site. If the super-admin will want to opt-in they can still do that from the network level Account page.
8645 */
8646 $has_delegated_site = false;
8647
8648 $sites = self::get_sites();
8649 foreach ( $sites as $wp_site ) {
8650 $blog_id = self::get_site_blog_id( $wp_site );
8651
8652 if ( $this->is_site_delegated_connection( $blog_id ) ) {
8653 $has_delegated_site = true;
8654 break;
8655 }
8656 }
8657
8658 if ( $has_delegated_site ) {
8659 $this->delegate_site_connection( $blog_id );
8660 } else {
8661 $this->skip_site_connection( $blog_id );
8662 }
8663 }
8664
8665 /**
8666 * Store the new blog's information even if there's no install so that when a clone install is stored in the new blog's storage, we can try to resolve it automatically.
8667 *
8668 * @author Leo Fajardo (@leorw)
8669 * @since 2.5.0
8670 */
8671 FS_Clone_Manager::instance()->store_blog_install_info( $new_blog_id, $site );
8672 }
8673
8674 /**
8675 * @author Vova Feldman (@svovaf)
8676 * @since 2.5.0
8677 *
8678 * @param \WP_Site $new_site
8679 * @param array $args
8680 */
8681 public function _after_wp_initialize_site_callback( WP_Site $new_site, $args ) {
8682 $this->_logger->entrance();
8683
8684 $this->_after_new_blog_callback(
8685 $new_site->id,
8686 // Dummy user ID (not in use).
8687 0,
8688 $new_site->domain,
8689 $new_site->path,
8690 $new_site->network_id,
8691 // Dummy meta, not in use.
8692 array()
8693 );
8694 }
8695
8696 /**
8697 * @author Vova Feldman (@svovaf)
8698 * @since 1.1.3
8699 *
8700 * @param bool|int|int[] $network_or_blog_ids Since 2.0.0.
8701 */
8702 private function reset_anonymous_mode( $network_or_blog_ids = false ) {
8703 if ( true === $network_or_blog_ids ) {
8704 $this->unset_anonymous_mode( true );
8705
8706 if ( fs_is_network_admin() ) {
8707 $this->_is_anonymous = null;
8708 }
8709
8710 // Rest anonymous mode for all non-delegated sub-sites.
8711 $blog_ids = $this->get_non_delegated_blog_ids();
8712 }
8713 else
8714 {
8715 if ( false === $network_or_blog_ids ) {
8716 $network_or_blog_ids = 0;
8717 }
8718
8719 $blog_ids = is_array( $network_or_blog_ids ) ?
8720 $network_or_blog_ids :
8721 array( $network_or_blog_ids );
8722
8723 foreach ( $blog_ids as $blog_id ) {
8724 if ( 0 === $blog_id || get_current_blog_id() == $blog_id ) {
8725 $this->_is_anonymous = null;
8726 }
8727 }
8728 }
8729
8730 foreach ( $blog_ids as $blog_id ) {
8731 $this->unset_anonymous_mode( $blog_id );
8732 }
8733
8734 /**
8735 * Ensure that this field is also "false", otherwise, if the current module's type is "theme" and the module
8736 * has no menus, the opt-in popup will not be shown immediately (in this case, the user will have to click
8737 * on the admin notice that contains the opt-in link in order to trigger the opt-in popup).
8738 *
8739 * @author Leo Fajardo (@leorw)
8740 * @since 1.2.2
8741 */
8742 if ( ! $this->_is_network_active ) {
8743 $this->_is_anonymous = null;
8744 }
8745 }
8746
8747 /**
8748 * @author Leo Fajardo (@leorw)
8749 * @since 2.5.3
8750 */
8751 private function update_license_required_permissions_if_anonymous() {
8752 if ( ! $this->is_anonymous() ) {
8753 return;
8754 }
8755
8756 $this->reset_anonymous_mode( fs_is_network_admin() );
8757
8758 FS_Permission_Manager::instance( $this )->update_permissions_tracking_flag( array(
8759 'essentials' => true,
8760 'events' => true,
8761 'diagnostic' => false,
8762 'extensions' => false,
8763 'site' => false,
8764 ) );
8765 }
8766
8767 /**
8768 * This is used to ensure that before redirecting to the opt-in page after resetting the anonymous mode or
8769 * deleting the account in the network level, the URL of the page to redirect to is correct.
8770 *
8771 * @author Leo Fajardo (@leorw)
8772 *
8773 * @since 2.1.3
8774 */
8775 private function maybe_set_slug_and_network_menu_exists_flag() {
8776 if ( ! empty( $this->_dynamically_added_top_level_page_hook_name ) ) {
8777 $this->_menu->set_slug_and_network_menu_exists_flag( $this->_menu->has_menu() ?
8778 $this->_menu->get_slug() :
8779 $this->_slug
8780 );
8781 }
8782 }
8783
8784 /**
8785 * Clears the anonymous mode and redirects to the opt-in screen.
8786 *
8787 * @author Vova Feldman (@svovaf)
8788 * @since 1.1.7
8789 */
8790 function connect_again() {
8791 if ( ! $this->is_anonymous() && ! $this->is_pending_activation() ) {
8792 return;
8793 }
8794
8795 if ( $this->is_anonymous() ) {
8796 $this->reset_anonymous_mode( fs_is_network_admin() );
8797 }
8798
8799 $activation_url_params = array();
8800
8801 if ( $this->is_pending_activation() ) {
8802 $this->clear_pending_activation_mode();
8803
8804 if ( fs_request_get_bool( 'require_license' ) ) {
8805 $activation_url_params['require_license'] = true;
8806 }
8807 }
8808
8809 $this->maybe_set_slug_and_network_menu_exists_flag();
8810
8811 fs_redirect( $this->get_activation_url( $activation_url_params ) );
8812 }
8813
8814 /**
8815 * Skip account connect, and set anonymous mode.
8816 *
8817 * @author Vova Feldman (@svovaf)
8818 * @since 1.1.1
8819 *
8820 * @param bool|int|int[] $network_or_blog_ids Since 2.5.1
8821 */
8822 function skip_connection( $network_or_blog_ids = false ) {
8823 $this->_logger->entrance();
8824
8825 $this->_admin_notices->remove_sticky( 'connect_account' );
8826
8827 if ( true === $network_or_blog_ids ) {
8828 $this->set_anonymous_mode( true, true );
8829
8830 if ( fs_is_network_admin() ) {
8831 $this->_is_anonymous = null;
8832 }
8833
8834 // Rest anonymous mode for all non-delegated sub-sites.
8835 $blog_ids = $this->get_non_delegated_blog_ids();
8836 }
8837 else
8838 {
8839 if ( false === $network_or_blog_ids ) {
8840 $network_or_blog_ids = 0;
8841 }
8842
8843 $blog_ids = is_array( $network_or_blog_ids ) ?
8844 $network_or_blog_ids :
8845 array( $network_or_blog_ids );
8846
8847 foreach ( $blog_ids as $blog_id ) {
8848 if ( 0 === $blog_id || get_current_blog_id() == $blog_id ) {
8849 $this->_is_anonymous = null;
8850 }
8851 }
8852 }
8853
8854 foreach ( $blog_ids as $blog_id ) {
8855 $this->skip_site_connection( $blog_id );
8856 }
8857
8858 $this->network_upgrade_mode_completed();
8859 }
8860
8861 /**
8862 * Skip connection for specific site in the network.
8863 *
8864 * @author Vova Feldman (@svovaf)
8865 * @since 2.0.0
8866 *
8867 * @param int|null $blog_id
8868 * @param bool $send_skip
8869 */
8870 private function skip_site_connection( $blog_id = null ) {
8871 $this->_logger->entrance();
8872
8873 $this->_admin_notices->remove_sticky( 'connect_account', $blog_id );
8874
8875 $this->set_anonymous_mode( true, $blog_id );
8876 }
8877
8878 /**
8879 * Plugin version update hook.
8880 *
8881 * @author Vova Feldman (@svovaf)
8882 * @since 1.0.4
8883 */
8884 private function update_plugin_version_event() {
8885 $this->_logger->entrance();
8886
8887 if ( ! $this->is_registered() ) {
8888 return;
8889 }
8890
8891 $this->schedule_install_sync();
8892 // $this->sync_install( array(), true );
8893 }
8894
8895 /**
8896 * Generate an MD5 signature of a plugins collection.
8897 * This helper methods used to identify changes in a plugins collection.
8898 *
8899 * @author Vova Feldman (@svovaf)
8900 * @since 2.0.0
8901 *
8902 * @param array [string]array $plugins
8903 *
8904 * @return string
8905 */
8906 private function get_plugins_thumbprint( $plugins ) {
8907 ksort( $plugins );
8908
8909 $thumbprint = '';
8910 foreach ( $plugins as $basename => $data ) {
8911 $thumbprint .= $data['slug'] . ',' .
8912 $data['Version'] . ',' .
8913 ( $data['is_active'] ? '1' : '0' ) . ';';
8914 }
8915
8916 return md5( $thumbprint );
8917 }
8918
8919 /**
8920 * Return a list of modified plugins since the last sync.
8921 *
8922 * Note:
8923 * There's no point to store a plugins counter since even if the number of
8924 * plugins didn't change, we still need to check if the versions are all the
8925 * same and the activity state is similar.
8926 *
8927 * @author Vova Feldman (@svovaf)
8928 * @since 1.1.8
8929 *
8930 * @return array|false
8931 */
8932 private function get_plugins_data_for_api() {
8933 // Alias.
8934 $site_active_plugins_option_name = 'active_plugins';
8935 $network_plugins_option_name = 'all_plugins';
8936
8937 /**
8938 * Collection of all site level active plugins.
8939 */
8940 $site_active_plugins_cache = self::$_accounts->get_option( $site_active_plugins_option_name );
8941
8942 if ( ! is_object( $site_active_plugins_cache ) ) {
8943 $site_active_plugins_cache = (object) array(
8944 'timestamp' => '',
8945 'md5' => '',
8946 'plugins' => array(),
8947 );
8948 }
8949
8950 $time = time();
8951
8952 if ( ! empty( $site_active_plugins_cache->timestamp ) &&
8953 ( $time - $site_active_plugins_cache->timestamp ) < WP_FS__TIME_5_MIN_IN_SEC
8954 ) {
8955 // Don't send plugin updates if last update was in the past 5 min.
8956 return false;
8957 }
8958
8959 // Write timestamp to lock the logic.
8960 $site_active_plugins_cache->timestamp = $time;
8961 self::$_accounts->set_option( $site_active_plugins_option_name, $site_active_plugins_cache, true );
8962
8963 // Reload options from DB.
8964 self::$_accounts->load( true );
8965 $site_active_plugins_cache = self::$_accounts->get_option( $site_active_plugins_option_name );
8966
8967 if ( $time != $site_active_plugins_cache->timestamp ) {
8968 // If timestamp is different, then another thread captured the lock.
8969 return false;
8970 }
8971
8972 /**
8973 * Collection of all plugins (network level).
8974 */
8975 $network_plugins_cache = self::$_accounts->get_option( $network_plugins_option_name );
8976
8977 if ( ! is_object( $network_plugins_cache ) ) {
8978 $network_plugins_cache = (object) array(
8979 'timestamp' => '',
8980 'md5' => '',
8981 'plugins' => array(),
8982 );
8983 }
8984
8985 // Check if there's a change in plugins.
8986 $network_plugins = self::get_network_plugins();
8987 $site_active_plugins = self::get_site_active_plugins();
8988
8989 $network_plugins_thumbprint = $this->get_plugins_thumbprint( $network_plugins );
8990 $site_active_plugins_thumbprint = $this->get_plugins_thumbprint( $site_active_plugins );
8991
8992 // Check if plugins status changed (version or active/inactive).
8993 $network_plugins_changed = ( $network_plugins_cache->md5 !== $network_plugins_thumbprint );
8994 $site_active_plugins_changed = ( $site_active_plugins_cache->md5 !== $site_active_plugins_thumbprint );
8995
8996 if ( ! $network_plugins_changed &&
8997 ! $site_active_plugins_changed
8998 ) {
8999 // No changes.
9000 return array();
9001 }
9002
9003 $plugins_update_data = array();
9004
9005 foreach ( $network_plugins_cache->plugins as $basename => $data ) {
9006 if ( ! isset( $network_plugins[ $basename ] ) ) {
9007 // Plugin uninstalled.
9008 $uninstalled_plugin_data = $data;
9009 $uninstalled_plugin_data['is_active'] = false;
9010 $uninstalled_plugin_data['is_uninstalled'] = true;
9011 $plugins_update_data[] = $uninstalled_plugin_data;
9012
9013 unset( $network_plugins[ $basename ] );
9014
9015 unset( $network_plugins_cache->plugins[ $basename ] );
9016 unset( $site_active_plugins_cache->plugins[ $basename ] );
9017
9018 continue;
9019 }
9020
9021 $was_active = $data['is_active'] ||
9022 ( isset( $site_active_plugins_cache->plugins[ $basename ] ) &&
9023 true === $site_active_plugins_cache->plugins[ $basename ]['is_active'] );
9024 $is_active = $network_plugins[ $basename ]['is_active'] ||
9025 ( isset( $site_active_plugins[ $basename ] ) &&
9026 $site_active_plugins[ $basename ]['is_active'] );
9027
9028 if ( ! isset( $site_active_plugins_cache->plugins[ $basename ] ) &&
9029 isset( $site_active_plugins[ $basename ] )
9030 ) {
9031 // Plugin was site level activated.
9032 $site_active_plugins_cache->plugins[ $basename ] = $network_plugins[ $basename ];
9033 $site_active_plugins_cache->plugins[ $basename ]['is_active'] = true;
9034 } else if ( isset( $site_active_plugins_cache->plugins[ $basename ] ) &&
9035 ! isset( $site_active_plugins[ $basename ] )
9036 ) {
9037 // Plugin was site level deactivated.
9038 unset( $site_active_plugins_cache->plugins[ $basename ] );
9039 }
9040
9041 $prev_version = $data['version'];
9042 $current_version = $network_plugins[ $basename ]['Version'];
9043
9044 if ( $was_active !== $is_active || $prev_version !== $current_version ) {
9045 // Plugin activated or deactivated, or version changed.
9046
9047 if ( $was_active !== $is_active ) {
9048 if ( $data['is_active'] != $network_plugins[ $basename ]['is_active'] ) {
9049 $network_plugins_cache->plugins[ $basename ]['is_active'] = $data['is_active'];
9050 }
9051 }
9052
9053 if ( $prev_version !== $current_version ) {
9054 $network_plugins_cache->plugins[ $basename ]['Version'] = $current_version;
9055 }
9056
9057 $updated_plugin_data = $data;
9058 $updated_plugin_data['is_active'] = $is_active;
9059 $updated_plugin_data['version'] = $current_version;
9060 $updated_plugin_data['title'] = $network_plugins[ $basename ]['Name'];
9061 $plugins_update_data[] = $updated_plugin_data;
9062 }
9063 }
9064
9065 // Find new plugins that weren't yet seen before.
9066 foreach ( $network_plugins as $basename => $data ) {
9067 if ( ! isset( $network_plugins_cache->plugins[ $basename ] ) ) {
9068 // New plugin.
9069 $new_plugin = array(
9070 'slug' => $data['slug'],
9071 'version' => $data['Version'],
9072 'title' => $data['Name'],
9073 'is_active' => $data['is_active'],
9074 'is_uninstalled' => false,
9075 );
9076
9077 $network_plugins_cache->plugins[ $basename ] = $new_plugin;
9078
9079 $is_site_level_active = (
9080 isset( $site_active_plugins[ $basename ] ) &&
9081 $site_active_plugins[ $basename ]['is_active']
9082 );
9083
9084 /**
9085 * If not network active, set the activity status based on the site-level plugin status.
9086 */
9087 if ( ! $new_plugin['is_active'] ) {
9088 $new_plugin['is_active'] = $is_site_level_active;
9089 }
9090
9091 $plugins_update_data[] = $new_plugin;
9092
9093 if ( isset( $site_active_plugins[ $basename ] ) ) {
9094 $site_active_plugins_cache->plugins[ $basename ] = $new_plugin;
9095 $site_active_plugins_cache->plugins[ $basename ]['is_active'] = $is_site_level_active;
9096 }
9097 }
9098 }
9099
9100 $site_active_plugins_cache->md5 = $site_active_plugins_thumbprint;
9101 $site_active_plugins_cache->timestamp = $time;
9102 self::$_accounts->set_option( $site_active_plugins_option_name, $site_active_plugins_cache, true );
9103
9104 $network_plugins_cache->md5 = $network_plugins_thumbprint;
9105 $network_plugins_cache->timestamp = $time;
9106 self::$_accounts->set_option( $network_plugins_option_name, $network_plugins_cache, true );
9107
9108 return $plugins_update_data;
9109 }
9110
9111 /**
9112 * Return a list of modified themes since the last sync.
9113 *
9114 * Note:
9115 * There's no point to store a themes counter since even if the number of
9116 * themes didn't change, we still need to check if the versions are all the
9117 * same and the activity state is similar.
9118 *
9119 * @author Vova Feldman (@svovaf)
9120 * @since 1.1.8
9121 *
9122 * @return array|false
9123 */
9124 private function get_themes_data_for_api() {
9125 // Alias.
9126 $option_name = 'all_themes';
9127
9128 $all_cached_themes = self::$_accounts->get_option( $option_name );
9129
9130 if ( ! is_object( $all_cached_themes ) ) {
9131 $all_cached_themes = (object) array(
9132 'timestamp' => '',
9133 'md5' => '',
9134 'themes' => array(),
9135 );
9136 }
9137
9138 $time = time();
9139
9140 if ( ! empty( $all_cached_themes->timestamp ) &&
9141 ( $time - $all_cached_themes->timestamp ) < WP_FS__TIME_5_MIN_IN_SEC
9142 ) {
9143 // Don't send theme updates if last update was in the past 5 min.
9144 return false;
9145 }
9146
9147 // Write timestamp to lock the logic.
9148 $all_cached_themes->timestamp = $time;
9149 self::$_accounts->set_option( $option_name, $all_cached_themes, true );
9150
9151 // Reload options from DB.
9152 self::$_accounts->load( true );
9153 $all_cached_themes = self::$_accounts->get_option( $option_name );
9154
9155 if ( $time != $all_cached_themes->timestamp ) {
9156 // If timestamp is different, then another thread captured the lock.
9157 return false;
9158 }
9159
9160 // Get active theme.
9161 $active_theme = wp_get_theme();
9162 $active_theme_stylesheet = $active_theme->get_stylesheet();
9163
9164 // Check if there's a change in themes.
9165 $all_themes = wp_get_themes();
9166
9167 // Check if themes changed.
9168 ksort( $all_themes );
9169
9170 $themes_signature = '';
9171 foreach ( $all_themes as $slug => $data ) {
9172 $is_active = ( $slug === $active_theme_stylesheet );
9173 $themes_signature .= $slug . ',' .
9174 $data->version . ',' .
9175 ( $is_active ? '1' : '0' ) . ';';
9176 }
9177
9178 // Check if themes status changed (version or active/inactive).
9179 $themes_changed = ( $all_cached_themes->md5 !== md5( $themes_signature ) );
9180
9181 $themes_update_data = array();
9182
9183 if ( $themes_changed ) {
9184 // Change in themes, report changes.
9185
9186 // Update existing themes info.
9187 foreach ( $all_cached_themes->themes as $slug => $data ) {
9188 $is_active = ( $slug === $active_theme_stylesheet );
9189
9190 if ( ! isset( $all_themes[ $slug ] ) ) {
9191 // Plugin uninstalled.
9192 $uninstalled_theme_data = $data;
9193 $uninstalled_theme_data['is_active'] = false;
9194 $uninstalled_theme_data['is_uninstalled'] = true;
9195 $themes_update_data[] = $uninstalled_theme_data;
9196
9197 unset( $all_themes[ $slug ] );
9198 unset( $all_cached_themes->themes[ $slug ] );
9199 } else if ( $data['is_active'] !== $is_active ||
9200 $data['version'] !== $all_themes[ $slug ]->version
9201 ) {
9202 // Plugin activated or deactivated, or version changed.
9203
9204 $all_cached_themes->themes[ $slug ]['is_active'] = $is_active;
9205 $all_cached_themes->themes[ $slug ]['version'] = $all_themes[ $slug ]->version;
9206
9207 $themes_update_data[] = $all_cached_themes->themes[ $slug ];
9208 }
9209 }
9210
9211 // Find new themes that weren't yet seen before.
9212 foreach ( $all_themes as $slug => $data ) {
9213 if ( ! isset( $all_cached_themes->themes[ $slug ] ) ) {
9214 $is_active = ( $slug === $active_theme_stylesheet );
9215
9216 // New plugin.
9217 $new_plugin = array(
9218 'slug' => $slug,
9219 'version' => $data->version,
9220 'title' => $data->name,
9221 'is_active' => $is_active,
9222 'is_uninstalled' => false,
9223 );
9224
9225 $themes_update_data[] = $new_plugin;
9226 $all_cached_themes->themes[ $slug ] = $new_plugin;
9227 }
9228 }
9229
9230 $all_cached_themes->md5 = md5( $themes_signature );
9231 $all_cached_themes->timestamp = time();
9232 self::$_accounts->set_option( $option_name, $all_cached_themes, true );
9233 }
9234
9235 return $themes_update_data;
9236 }
9237
9238 /**
9239 * Get site data for API install request.
9240 *
9241 * @author Vova Feldman (@svovaf)
9242 * @since 1.1.2
9243 *
9244 * @param string[] $override
9245 * @param bool $include_plugins Since 1.1.8 by default include plugin changes.
9246 * @param bool $include_themes Since 1.1.8 by default include plugin changes.
9247 * @param bool $include_blog_data Since 2.3.0 by default include the current blog's data (language, title, and URL).
9248 *
9249 * @return array
9250 */
9251 private function get_install_data_for_api(
9252 array $override,
9253 $include_plugins = true,
9254 $include_themes = true,
9255 $include_blog_data = true
9256 ) {
9257 // Alias.
9258 $permissions = FS_Permission_Manager::instance( $this );
9259
9260 if ( $permissions->is_extensions_tracking_allowed() ) {
9261 if ( ! defined( 'WP_FS__TRACK_PLUGINS' ) || false !== WP_FS__TRACK_PLUGINS ) {
9262 /**
9263 * @since 1.1.8 Also send plugin updates.
9264 */
9265 if ( $include_plugins && ! isset( $override['plugins'] ) ) {
9266 $plugins = $this->get_plugins_data_for_api();
9267 if ( ! empty( $plugins ) ) {
9268 $override['plugins'] = $plugins;
9269 }
9270 }
9271 }
9272
9273 if ( ! defined( 'WP_FS__TRACK_THEMES' ) || false !== WP_FS__TRACK_THEMES ) {
9274 /**
9275 * @since 1.1.8 Also send themes updates.
9276 */
9277 if ( $include_themes && ! isset( $override['themes'] ) ) {
9278 $themes = $this->get_themes_data_for_api();
9279 if ( ! empty( $themes ) ) {
9280 $override['themes'] = $themes;
9281 }
9282 }
9283 }
9284 }
9285
9286 $versions = $this->get_versions();
9287
9288 $blog_data = array();
9289 if ( $include_blog_data ) {
9290 $blog_data['url'] = self::get_unfiltered_site_url();
9291
9292 if ( $permissions->is_diagnostic_tracking_allowed() ) {
9293 $blog_data = array_merge( $blog_data, array(
9294 'language' => self::get_sanitized_language(),
9295 'title' => get_bloginfo( 'name' ),
9296 ) );
9297 }
9298 }
9299
9300 return array_merge( $versions, $blog_data, array(
9301 'version' => $this->get_plugin_version(),
9302 'is_premium' => $this->is_premium(),
9303 // Special params.
9304 'is_active' => true,
9305 'is_uninstalled' => false,
9306 ), $override );
9307 }
9308
9309 /**
9310 * Update installs details.
9311 *
9312 * @todo V1 of multiste network support doesn't support plugin and theme data sending.
9313 *
9314 * @author Vova Feldman (@svovaf)
9315 * @since 2.0.0
9316 *
9317 * @param string[] string $override
9318 * @param bool $only_diff
9319 * @param bool $is_keepalive
9320 * @param bool $include_plugins Since 1.1.8 by default include plugin changes.
9321 * @param bool $include_themes Since 1.1.8 by default include plugin changes.
9322 *
9323 * @return array
9324 */
9325 private function get_installs_data_for_api(
9326 array $override,
9327 $only_diff = false,
9328 $is_keepalive = false,
9329 $include_plugins = true,
9330 $include_themes = true
9331 ) {
9332 /**
9333 * @since 1.1.8 Also send plugin updates.
9334 */
9335 // if ( $include_plugins && ! isset( $override['plugins'] ) ) {
9336 // $plugins = $this->get_plugins_data_for_api();
9337 // if ( ! empty( $plugins ) ) {
9338 // $override['plugins'] = $plugins;
9339 // }
9340 // }
9341 /**
9342 * @since 1.1.8 Also send themes updates.
9343 */
9344 // if ( $include_themes && ! isset( $override['themes'] ) ) {
9345 // $themes = $this->get_themes_data_for_api();
9346 // if ( ! empty( $themes ) ) {
9347 // $override['themes'] = $themes;
9348 // }
9349 // }
9350
9351 // Common properties.
9352 $versions = $this->get_versions();
9353 $common = array_merge( $versions, array(
9354 'version' => $this->get_plugin_version(),
9355 'is_premium' => $this->is_premium(),
9356 ), $override );
9357
9358
9359 $is_common_diff_for_any_site = false;
9360 $common_diff_union = array();
9361
9362 $installs_data = array();
9363
9364 $sites = self::get_sites();
9365
9366 $subsite_data_for_api_by_install_id = array();
9367 $install_url_by_install_id = array();
9368 $subsite_registration_date_by_install_id = array();
9369
9370 foreach ( $sites as $site ) {
9371 $blog_id = self::get_site_blog_id( $site );
9372
9373 $install = $this->get_install_by_blog_id( $blog_id );
9374
9375 if ( is_object( $install ) ) {
9376 if ( $install->user_id != $this->_user->id ) {
9377 // Install belongs to a different owner.
9378 continue;
9379 }
9380
9381 if ( ! $this->is_tracking_allowed( $blog_id, $install ) ) {
9382 // Don't send updates regarding opted-out installs.
9383 continue;
9384 }
9385
9386 $install_data = $this->get_site_info( $site, true );
9387
9388 if ( FS_Clone_Manager::instance()->is_temporary_duplicate_by_blog_id( $install_data['blog_id'] ) ) {
9389 continue;
9390 }
9391
9392 $uid = $install_data['uid'];
9393 $url = $install_data['url'];
9394 $registration_date = $install_data['registration_date'];
9395
9396 if ( isset( $subsite_data_for_api_by_install_id[ $install->id ] ) ) {
9397 $clone_subsite_data = $subsite_data_for_api_by_install_id[ $install->id ];
9398 $clone_install_url = $install_url_by_install_id[ $install->id ];
9399 $clone_subsite_registration_date = $subsite_registration_date_by_install_id[ $install->id ];
9400
9401 $skip = false;
9402
9403 if (
9404 ! empty( $install_data['registration_date'] ) &&
9405 ! empty( $clone_subsite_registration_date )
9406 ) {
9407 /**
9408 * If the current subsite was created after the other subsite that is also linked to the same install ID, we assume that it's a clone (not the original), and therefore, would skip its processing.
9409 *
9410 * @author Leo Fajardo (@leorw)
9411 * @since 2.5.1
9412 */
9413 $skip = ( strtotime( $install_data['registration_date'] ) > strtotime( $clone_subsite_registration_date ) );
9414 } else if (
9415 /**
9416 * If we already have an install with the same URL as the subsite it's stored in, skip the current subsite. Otherwise, replace the existing install's data with the current subsite's install's data if the URLs match.
9417 *
9418 * @author Leo Fajardo (@leorw)
9419 * @since 2.5.0
9420 */
9421 fs_strip_url_protocol( untrailingslashit( $clone_install_url ) ) === fs_strip_url_protocol( untrailingslashit( $clone_subsite_data['url'] ) ) ||
9422 fs_strip_url_protocol( untrailingslashit( $install->url ) ) !== fs_strip_url_protocol( untrailingslashit( $url ) )
9423 ) {
9424 $skip = true;
9425 }
9426
9427 if ( $skip ) {
9428 // Store the skipped subsite's ID so that the clone resolution manager can try to resolve the clone install that is stored in that subsite later on.
9429 FS_Clone_Manager::instance()->store_blog_install_info( $blog_id );
9430 continue;
9431 }
9432 }
9433
9434 unset( $install_data['blog_id'] );
9435 unset( $install_data['uid'] );
9436 unset( $install_data['url'] );
9437 unset( $install_data['registration_date'] );
9438
9439 $install_data['is_active'] = $this->is_active_for_site( $blog_id );
9440 $install_data['is_uninstalled'] = $install->is_uninstalled;
9441
9442 $common_diff = null;
9443 $is_common_diff = false;
9444 if ( $only_diff ) {
9445 $install_data = $this->get_install_diff_for_api( $install_data, $install, $override );
9446 $common_diff = $this->get_install_diff_for_api( $common, $install, $override );
9447
9448 $is_common_diff = ! empty( $common_diff );
9449
9450 if ( $is_common_diff ) {
9451 foreach ( $common_diff as $k => $v ) {
9452 if ( ! isset( $common_diff_union[ $k ] ) ) {
9453 $common_diff_union[ $k ] = $v;
9454 }
9455 }
9456 }
9457
9458 $is_common_diff_for_any_site = $is_common_diff_for_any_site || $is_common_diff;
9459 }
9460
9461 if ( ! empty( $install_data ) || $is_common_diff || $is_keepalive ) {
9462 // Add install ID and site unique ID.
9463 $install_data['id'] = $install->id;
9464 $install_data['uid'] = $uid;
9465 $install_data['url'] = $url;
9466
9467 $subsite_data_for_api_by_install_id[ $install->id ] = $install_data;
9468 $install_url_by_install_id[ $install->id ] = $install->url;
9469 $subsite_registration_date_by_install_id[ $install->id ] = $registration_date;
9470 }
9471 }
9472 }
9473
9474 restore_current_blog();
9475
9476 $installs_data = array_merge(
9477 $installs_data,
9478 array_values( $subsite_data_for_api_by_install_id )
9479 );
9480
9481 if ( 0 < count( $installs_data ) && ( $is_common_diff_for_any_site || ! $only_diff ) ) {
9482 if ( ! $only_diff ) {
9483 $installs_data[] = $common;
9484 } else if ( ! empty( $common_diff_union ) ) {
9485 $installs_data[] = $common_diff_union;
9486 }
9487 }
9488
9489 foreach ( $installs_data as &$data ) {
9490 $data = (object) $data;
9491 }
9492
9493 return $installs_data;
9494 }
9495
9496 /**
9497 * Compare site actual data to the stored install data and return the differences for an API data sync.
9498 *
9499 * @author Vova Feldman (@svovaf)
9500 * @since 2.0.0
9501 *
9502 * @param array $site
9503 * @param FS_Site $install
9504 * @param string[] string $override
9505 *
9506 * @return array
9507 */
9508 private function get_install_diff_for_api( $site, $install, $override = array() ) {
9509 $diff = array();
9510 $special = array();
9511 $special_override = false;
9512
9513 foreach ( $site as $p => $v ) {
9514 if ( property_exists( $install, $p ) ) {
9515 if ( ( is_bool( $install->{$p} ) || ! empty( $install->{$p} ) ) &&
9516 $install->{$p} != $v
9517 ) {
9518 $val = self::get_api_sanitized_property( $p, $v );
9519
9520 if ( $install->{$p} != $val ) {
9521 $install->{$p} = $val;
9522 $diff[ $p ] = $val;
9523 }
9524 }
9525 } else {
9526 $special[ $p ] = $v;
9527
9528 if ( isset( $override[ $p ] ) ||
9529 'plugins' === $p ||
9530 'themes' === $p
9531 ) {
9532 $special_override = true;
9533 }
9534 }
9535 }
9536
9537 if ( $special_override || 0 < count( $diff ) ) {
9538 // Add special params only if has at least one
9539 // standard param, or if explicitly requested to
9540 // override a special param or a param which is not exist
9541 // in the install object.
9542 $diff = array_merge( $diff, $special );
9543 }
9544
9545 return $diff;
9546 }
9547
9548 /**
9549 * @author Leo Fajardo (@leorw)
9550 * @since 2.5.1
9551 */
9552 private function send_pending_clone_update_once() {
9553 $this->_logger->entrance();
9554
9555 if ( ! empty( $this->_storage->clone_id ) ) {
9556 return;
9557 }
9558
9559 $install_clone = $this->get_api_site_scope()->call(
9560 '/clones',
9561 'post',
9562 array( 'site_url' => self::get_unfiltered_site_url() )
9563 );
9564
9565 if ( $this->is_api_result_entity( $install_clone ) ) {
9566 $this->_storage->clone_id = $install_clone->id;
9567 }
9568 }
9569
9570 /**
9571 * @author Leo Fajardo (@leorw)
9572 * @since 2.5.1
9573 *
9574 * @param string $resolution_type
9575 * @param FS_Site $clone_context_install
9576 */
9577 function send_clone_resolution_update( $resolution_type, $clone_context_install ) {
9578 $this->_logger->entrance();
9579
9580 if ( empty( $this->_storage->clone_id ) ) {
9581 return;
9582 }
9583
9584 $new_install_id = null;
9585 $current_site = null;
9586
9587 $flush = false;
9588
9589 /**
9590 * If the current site is now different from the context install before the clone resolution, we need to override `$this->_site` so that the API call below will be made with the right install scope entity.
9591 */
9592 if ( $clone_context_install->id != $this->_site->id ) {
9593 $new_install_id = $this->_site->id;
9594 $current_site = $this->_site;
9595 $this->_site = $clone_context_install;
9596
9597 $flush = true;
9598 }
9599
9600 $this->get_api_site_scope( $flush )->call(
9601 "/clones/{$this->_storage->clone_id}",
9602 'put',
9603 array(
9604 'resolution' => $resolution_type,
9605 'new_install_id' => $new_install_id,
9606 )
9607 );
9608
9609 if ( is_object( $current_site ) ) {
9610 /**
9611 * Ensure that the install scope entity is updated back to the previous install entity.
9612 */
9613 $this->_site = $current_site;
9614
9615 // Restore the previous install scope entity of the API.
9616 $this->get_api_site_scope( true );
9617 }
9618 }
9619
9620 /**
9621 * Update install only if changed.
9622 *
9623 * @author Vova Feldman (@svovaf)
9624 * @since 1.0.9
9625 *
9626 * @param string[] string $override
9627 * @param bool $flush
9628 * @param bool $is_two_way_sync @since 2.5.0 If true and there's a successful API request, the install sync cron will be cleared.
9629 *
9630 * @return false|object|string
9631 */
9632 private function send_install_update( $override = array(), $flush = false, $is_two_way_sync = false ) {
9633 $this->_logger->entrance();
9634
9635 $check_properties = $this->get_install_data_for_api( $override );
9636
9637 if ( $flush ) {
9638 $params = $check_properties;
9639 } else {
9640 $params = $this->get_install_diff_for_api( $check_properties, $this->_site, $override );
9641 }
9642
9643 if ( empty( $params ) ) {
9644 $keepalive_only_update = $this->should_send_keepalive_update();
9645
9646 if ( ! $keepalive_only_update ) {
9647 /**
9648 * There are no updates to send including keepalive.
9649 *
9650 * @author Leo Fajardo (@leorw)
9651 * @since 2.2.3
9652 */
9653 return false;
9654 }
9655 }
9656
9657 if ( $is_two_way_sync ) {
9658 /**
9659 * Update last install sync timestamp during a two-way sync call as we expect that updates are sent during this call.
9660 *
9661 * @author Leo Fajardo (@leorw)
9662 * @since 2.2.3
9663 */
9664 if ( ! is_multisite() ) {
9665 // Update last install sync timestamp.
9666 $this->set_cron_execution_timestamp( 'install_sync' );
9667 }
9668
9669 $params['uid'] = $this->get_anonymous_id();
9670 }
9671
9672 $this->set_keepalive_timestamp();
9673
9674 // Send updated values to FS.
9675 $site = $this->api_site_call( '/', 'put', $params, true );
9676
9677 if ( $is_two_way_sync && $this->is_api_result_entity( $site ) ) {
9678 /**
9679 * Clear scheduled install sync after a two-way sync call.
9680 *
9681 * @author Leo Fajardo (@leorw)
9682 * @since 2.2.3
9683 */
9684 if ( ! is_multisite() ) {
9685 // I successfully sent install update, clear scheduled sync if exist.
9686 $this->clear_install_sync_cron();
9687 }
9688 }
9689
9690 return $site;
9691 }
9692
9693 /**
9694 * Update installs only if changed.
9695 *
9696 * @author Vova Feldman (@svovaf)
9697 * @since 2.0.0
9698 *
9699 * @param string[] string $override
9700 * @param bool $flush
9701 * @param bool $is_two_way_sync @since 2.5.0 If true and there's a successful API request, the install sync cron will be cleared.
9702 *
9703 * @return false|object|string
9704 */
9705 private function send_installs_update( $override = array(), $flush = false, $is_two_way_sync = false ) {
9706 $this->_logger->entrance();
9707
9708 /**
9709 * Pass `true` to use the network level storage since the update is for many installs.
9710 *
9711 * @author Leo Fajardo (@leorw)
9712 * @since 2.2.3
9713 */
9714 $should_send_keepalive = $this->should_send_keepalive_update( true );
9715
9716 $installs_data = $this->get_installs_data_for_api( $override, ! $flush, $should_send_keepalive );
9717
9718 if ( empty( $installs_data ) ) {
9719 return false;
9720 }
9721
9722 if ( $is_two_way_sync ) {
9723 // Update last install sync timestamp during a two-way sync call as we expect that updates are sent during this call.
9724 $this->set_cron_execution_timestamp( 'install_sync' );
9725 }
9726
9727 /**
9728 * Pass `true` to use the network level storage since the update is for many installs.
9729 *
9730 * @author Leo Fajardo (@leorw)
9731 * @since 2.2.3
9732 */
9733 $this->set_keepalive_timestamp( true );
9734
9735 // Send updated values to FS.
9736 $result = $this->get_api_user_scope()->call( "/plugins/{$this->_plugin->id}/installs.json", 'put', $installs_data );
9737
9738 if ( $is_two_way_sync && $this->is_api_result_object( $result, 'installs' ) ) {
9739 // I successfully sent a two-way installs update, clear the scheduled install sync if it exists.
9740 $this->clear_install_sync_cron();
9741 }
9742
9743 return $result;
9744 }
9745
9746 /**
9747 * @author Leo Fajardo (@leorw)
9748 *
9749 * @param bool|null $use_network_level_storage
9750 *
9751 * @return bool
9752 */
9753 private function should_send_keepalive_update( $use_network_level_storage = null ) {
9754 $keepalive_timestamp = $this->_storage->get( 'keepalive_timestamp', 0, $use_network_level_storage );
9755
9756 if ( $keepalive_timestamp < ( time() - WP_FS__TIME_WEEK_IN_SEC ) ) {
9757 // If updated more than 7 days ago, trigger a keepalive and update the time it was triggered.
9758 return true;
9759 } else {
9760 // If updated 7 days ago or less, "flip a coin", if the value is 7 trigger a keepalive and update the last time it was triggered.
9761 return ( 7 == rand( 1, 7 ) );
9762 }
9763 }
9764
9765 /**
9766 * Syncs the install owner's data if needed (i.e., if the install owner is different from the loaded user).
9767 *
9768 * @author Leo Fajardo (@leorw)
9769 * @since 2.3.2
9770 */
9771 private function maybe_sync_install_user() {
9772 if ( $this->_user->id == $this->_site->user_id ) {
9773 return;
9774 }
9775
9776 // Fetch user data and store if found.
9777 $this->sync_user_by_current_install();
9778 }
9779
9780 /**
9781 * Update install only if changed.
9782 *
9783 * @author Vova Feldman (@svovaf)
9784 * @since 1.0.9
9785 *
9786 * @param string[] string $override
9787 * @param bool $flush
9788 */
9789 function sync_install( $override = array(), $flush = false ) {
9790 $this->_logger->entrance();
9791
9792 $site = $this->send_install_update( $override, $flush, true );
9793
9794 if ( false === $site ) {
9795 // No sync required.
9796 return;
9797 }
9798
9799 if ( ! $this->is_api_result_entity( $site ) ) {
9800 // Failed to sync, don't update locally.
9801 return;
9802 }
9803
9804 $this->_site = new FS_Site( $site );
9805
9806 $this->_store_site( true );
9807 }
9808
9809 /**
9810 * Update install only if changed.
9811 *
9812 * @author Vova Feldman (@svovaf)
9813 * @since 1.0.9
9814 *
9815 * @param string[] string $override
9816 * @param bool $flush
9817 */
9818 private function sync_installs( $override = array(), $flush = false ) {
9819 $this->_logger->entrance();
9820
9821 $result = $this->send_installs_update( $override, $flush, true );
9822
9823 if ( false === $result ) {
9824 // No sync required.
9825 return;
9826 }
9827
9828 if ( ! $this->is_api_result_object( $result, 'installs' ) ) {
9829 // Failed to sync, don't update locally.
9830 return;
9831 }
9832
9833 $address_to_blog_map = $this->get_address_to_blog_map();
9834
9835 foreach ( $result->installs as $install ) {
9836 $this->_site = new FS_Site( $install );
9837
9838 $address = trailingslashit( fs_strip_url_protocol( $install->url ) );
9839 $blog_id = $address_to_blog_map[ $address ];
9840
9841 $this->_store_site( true, $blog_id );
9842 }
9843 }
9844
9845 /**
9846 * Track install's custom event.
9847 *
9848 * IMPORTANT:
9849 * Custom event tracking is currently only supported for specific clients.
9850 * If you are not one of them, please don't use this method. If you will,
9851 * the API will simply ignore your request based on the plugin ID.
9852 *
9853 * Need custom tracking for your plugin or theme?
9854 * If you are interested in custom event tracking please contact yo@freemius.com
9855 * for further details.
9856 *
9857 * @author Vova Feldman (@svovaf)
9858 * @since 1.2.1
9859 *
9860 * @param string $name Event name.
9861 * @param array $properties Associative key/value array with primitive values only
9862 * @param bool $process_at A valid future date-time in the following format Y-m-d H:i:s.
9863 * @param bool $once If true, event will be tracked only once. IMPORTANT: Still trigger the API call.
9864 *
9865 * @return object|false Event data or FALSE on failure.
9866 *
9867 * @throws \Freemius_InvalidArgumentException
9868 */
9869 public function track_event( $name, $properties = array(), $process_at = false, $once = false ) {
9870 $this->_logger->entrance( http_build_query( array( 'name' => $name, 'once' => $once ) ) );
9871
9872 if ( ! $this->is_registered() ) {
9873 return false;
9874 }
9875
9876 $event = array( 'type' => $name );
9877
9878 if ( is_numeric( $process_at ) && $process_at > time() ) {
9879 $event['process_at'] = $process_at;
9880 }
9881
9882 if ( $once ) {
9883 $event['once'] = true;
9884 }
9885
9886 if ( ! empty( $properties ) ) {
9887 // Verify associative array values are primitive.
9888 foreach ( $properties as $k => $v ) {
9889 if ( ! is_scalar( $v ) ) {
9890 throw new Freemius_InvalidArgumentException( 'The $properties argument must be an associative key/value array with primitive values only.' );
9891 }
9892 }
9893
9894 $event['properties'] = $properties;
9895 }
9896
9897 $result = $this->get_api_site_scope()->call( 'events.json', 'post', $event );
9898
9899 return $this->is_api_error( $result ) ?
9900 false :
9901 $result;
9902 }
9903
9904 /**
9905 * Track install's custom event only once, but it still triggers the API call.
9906 *
9907 * IMPORTANT:
9908 * Custom event tracking is currently only supported for specific clients.
9909 * If you are not one of them, please don't use this method. If you will,
9910 * the API will simply ignore your request based on the plugin ID.
9911 *
9912 * Need custom tracking for your plugin or theme?
9913 * If you are interested in custom event tracking please contact yo@freemius.com
9914 * for further details.
9915 *
9916 * @author Vova Feldman (@svovaf)
9917 * @since 1.2.1
9918 *
9919 * @param string $name Event name.
9920 * @param array $properties Associative key/value array with primitive values only
9921 * @param bool $process_at A valid future date-time in the following format Y-m-d H:i:s.
9922 *
9923 * @return object|false Event data or FALSE on failure.
9924 *
9925 * @throws \Freemius_InvalidArgumentException
9926 *
9927 * @user Freemius::track_event()
9928 */
9929 public function track_event_once( $name, $properties = array(), $process_at = false ) {
9930 return $this->track_event( $name, $properties, $process_at, true );
9931 }
9932
9933 /**
9934 * Plugin uninstall hook.
9935 *
9936 * @author Vova Feldman (@svovaf)
9937 * @since 1.0.1
9938 *
9939 * @param bool $check_user Enforce checking if user have plugins activation privileges.
9940 */
9941 function _uninstall_plugin_event( $check_user = true ) {
9942 $this->_logger->entrance( 'slug = ' . $this->_slug );
9943
9944 if ( $check_user && ! current_user_can( 'activate_plugins' ) ) {
9945 return;
9946 }
9947
9948 $params = array();
9949 $uninstall_reason = null;
9950 if ( isset( $this->_storage->uninstall_reason ) ) {
9951 $uninstall_reason = $this->_storage->uninstall_reason;
9952 $params['reason_id'] = $uninstall_reason->id;
9953 $params['reason_info'] = $uninstall_reason->info;
9954 }
9955
9956 if ( ! $this->is_registered() ) {
9957 // Send anonymous uninstall event only if user submitted a feedback.
9958 if ( isset( $uninstall_reason ) ) {
9959 if ( isset( $uninstall_reason->is_anonymous ) && ! $uninstall_reason->is_anonymous ) {
9960 $this->opt_in( false, false, false, false, true );
9961 } else {
9962 $params['uid'] = $this->get_anonymous_id();
9963 $this->get_api_plugin_scope()->call( 'uninstall.json', 'put', $params );
9964 }
9965 }
9966 } else {
9967 $params = array_merge( $params, array(
9968 'is_active' => false,
9969 'is_uninstalled' => true,
9970 ) );
9971
9972 if ( $this->_is_network_active ) {
9973 // Send uninstall event.
9974 $this->send_installs_update( $params );
9975 } else {
9976 // Send uninstall event and handle the result.
9977 $this->sync_install( $params );
9978 }
9979 }
9980
9981 // @todo Decide if we want to delete plugin information from db.
9982 }
9983
9984 /**
9985 * Set the basename of the current product and hook _activate_plugin_event_hook() to the activation action.
9986 *
9987 * @author Vova Feldman (@svovaf)
9988 * @since 2.2.1
9989 *
9990 * @param string $is_premium
9991 * @param string $caller
9992 *
9993 * @return string
9994 */
9995 function set_basename( $is_premium, $caller ) {
9996 $basename = plugin_basename( $caller );
9997
9998 $current_basename = $is_premium ?
9999 $this->_premium_plugin_basename :
10000 $this->_free_plugin_basename;
10001
10002 if ( $current_basename == $basename ) {
10003 // Basename value set correctly.
10004 return;
10005 }
10006
10007 if ( $is_premium ) {
10008 $this->_premium_plugin_basename = $basename;
10009 } else {
10010 $this->_free_plugin_basename = $basename;
10011 }
10012
10013 $plugin_dir = dirname( $this->_plugin_dir_path ) . '/';
10014
10015 register_activation_hook(
10016 $plugin_dir . $basename,
10017 array( &$this, '_activate_plugin_event_hook' )
10018 );
10019 }
10020
10021 /**
10022 * @author Vova Feldman (@svovaf)
10023 * @since 1.1.1
10024 * @since 2.2.1 If the context product is in its premium version, use the current module's basename, even if it was renamed.
10025 *
10026 * @return string
10027 */
10028 function premium_plugin_basename() {
10029 if ( ! isset( $this->_premium_plugin_basename ) ) {
10030 $this->_premium_plugin_basename = $this->is_premium() ?
10031 // The product is premium, so use the current basename.
10032 $this->_plugin_basename :
10033 $this->get_premium_slug() . '/' . basename( $this->_free_plugin_basename );
10034 }
10035
10036 return $this->_premium_plugin_basename;
10037 }
10038
10039 /**
10040 * Uninstall plugin hook. Called only when connected his account with Freemius for active sites tracking.
10041 *
10042 * @author Vova Feldman (@svovaf)
10043 * @since 1.0.2
10044 */
10045 public static function _uninstall_plugin_hook() {
10046 self::_load_required_static();
10047
10048 self::$_static_logger->entrance();
10049
10050 if ( ! current_user_can( 'activate_plugins' ) ) {
10051 return;
10052 }
10053
10054 $plugin_file = substr( current_filter(), strlen( 'uninstall_' ) );
10055
10056 self::$_static_logger->info( 'plugin = ' . $plugin_file );
10057
10058 define( 'WP_FS__UNINSTALL_MODE', true );
10059
10060 $fs = self::get_instance_by_file( $plugin_file );
10061
10062 if ( is_object( $fs ) ) {
10063 $fs->remove_sdk_reference();
10064
10065 self::require_plugin_essentials();
10066
10067 if ( is_plugin_active( $fs->_free_plugin_basename ) ||
10068 is_plugin_active( $fs->premium_plugin_basename() )
10069 ) {
10070 // Deleting Free or Premium plugin version while the other version still installed.
10071 return;
10072 }
10073
10074 if (
10075 ! $fs->is_clone() &&
10076 /**
10077 * If there's a context install, run this method only when there's also a context user (e.g., when cloning a subsite of a multisite network into a single-site installation, it's possible for an install to be associated with a non-existing user entity; we want Freemius to be off in this case, while we are trying to recover the user).
10078 *
10079 * @author Leo Fajardo
10080 */
10081 ( ! is_object( $fs->_site ) || $fs->is_registered() )
10082 ) {
10083 $fs->_uninstall_plugin_event();
10084 }
10085
10086 $fs->do_action( 'after_uninstall' );
10087 }
10088 }
10089
10090 #----------------------------------------------------------------------------------
10091 #region Plugin Information
10092 #----------------------------------------------------------------------------------
10093
10094 /**
10095 * Load WordPress core plugin.php essential module.
10096 *
10097 * @author Vova Feldman (@svovaf)
10098 * @since 1.1.1
10099 */
10100 private static function require_plugin_essentials() {
10101 if ( ! function_exists( 'get_plugins' ) ) {
10102 self::$_static_logger->log( 'Including wp-admin/includes/plugin.php...' );
10103
10104 require_once ABSPATH . 'wp-admin/includes/plugin.php';
10105 }
10106 }
10107
10108 /**
10109 * Load WordPress core pluggable.php module.
10110 *
10111 * @author Vova Feldman (@svovaf)
10112 * @since 1.1.2
10113 */
10114 private static function require_pluggable_essentials() {
10115 if ( ! function_exists( 'wp_get_current_user' ) ) {
10116 require_once ABSPATH . 'wp-includes/pluggable.php';
10117 }
10118 }
10119
10120 /**
10121 * Return plugin data.
10122 *
10123 * @author Vova Feldman (@svovaf)
10124 * @since 1.0.1
10125 *
10126 * @param bool $reparse_plugin_metadata
10127 *
10128 * @return array
10129 */
10130 function get_plugin_data( $reparse_plugin_metadata = false ) {
10131 if ( ! isset( $this->_plugin_data ) || $reparse_plugin_metadata ) {
10132 self::require_plugin_essentials();
10133
10134 if ( $this->is_plugin() ) {
10135 /**
10136 * @author Vova Feldman (@svovaf)
10137 * @since 1.2.0 When using get_plugin_data() do NOT translate plugin data.
10138 *
10139 * @link https://github.com/Freemius/wordpress-sdk/issues/77
10140 */
10141 $plugin_data = get_plugin_data(
10142 $this->_plugin_main_file_path,
10143 false,
10144 false
10145 );
10146 } else {
10147 $theme_data = wp_get_theme();
10148
10149 if ( $this->_plugin_basename !== $theme_data->get_stylesheet() && is_child_theme() ) {
10150 $parent_theme = $theme_data->parent();
10151
10152 if ( ( $parent_theme instanceof WP_Theme ) && $this->_plugin_basename === $parent_theme->get_stylesheet() ) {
10153 $theme_data = $parent_theme;
10154 }
10155 }
10156
10157 $plugin_data = array(
10158 'Name' => $theme_data->get( 'Name' ),
10159 'Version' => $theme_data->get( 'Version' ),
10160 'Author' => $theme_data->get( 'Author' ),
10161 'Description' => $theme_data->get( 'Description' ),
10162 'PluginURI' => $theme_data->get( 'ThemeURI' ),
10163 );
10164 }
10165
10166 $this->_plugin_data = $plugin_data;
10167 }
10168
10169 return $this->_plugin_data;
10170 }
10171
10172 /**
10173 * @author Vova Feldman (@svovaf)
10174 * @since 1.0.1
10175 * @since 1.2.2.5 If slug not set load slug by module ID.
10176 *
10177 * @return string Plugin slug.
10178 */
10179 function get_slug() {
10180 if ( ! isset( $this->_slug ) ) {
10181 $id_slug_type_path_map = self::$_accounts->get_option( 'id_slug_type_path_map', array() );
10182 $this->_slug = $id_slug_type_path_map[ $this->_module_id ]['slug'];
10183 }
10184
10185 return $this->_slug;
10186 }
10187
10188 /**
10189 * @author Leo Fajardo (@leorw)
10190 * @since 2.2.1
10191 *
10192 * @return string
10193 */
10194 function get_premium_slug() {
10195 return ( is_object( $this->_plugin ) && ! empty( $this->_plugin->premium_slug ) ) ?
10196 $this->_plugin->premium_slug :
10197 "{$this->_slug}-premium";
10198 }
10199
10200 /**
10201 * Retrieve the desired folder name for the product.
10202 *
10203 * @author Vova Feldman (@svovaf)
10204 * @since 1.2.1.7
10205 *
10206 * @return string Plugin slug.
10207 */
10208 function get_target_folder_name() {
10209 return $this->can_use_premium_code() ?
10210 $this->_plugin->premium_slug :
10211 $this->_slug;
10212 }
10213
10214 /**
10215 * @author Vova Feldman (@svovaf)
10216 * @since 1.0.1
10217 *
10218 * @return number Plugin ID.
10219 */
10220 function get_id() {
10221 return $this->_plugin->id;
10222 }
10223
10224 /**
10225 * @author Leo Fajardo (@leorw)
10226 * @since 2.2.4
10227 *
10228 * @return number|null Bundle ID.
10229 */
10230 function get_bundle_id() {
10231 return ( isset( $this->_plugin->bundle_id ) && FS_Plugin::is_valid_id( $this->_plugin->bundle_id ) ) ?
10232 $this->_plugin->bundle_id :
10233 null;
10234 }
10235
10236 /**
10237 * @author Vova Feldman (@svovaf)
10238 * @since 2.3.1
10239 *
10240 * @return string|null Bundle public key.
10241 */
10242 function get_bundle_public_key() {
10243 return isset( $this->_plugin->bundle_public_key ) ?
10244 $this->_plugin->bundle_public_key :
10245 null;
10246 }
10247
10248 /**
10249 * Get whether the SDK has been initiated in the context of a Bundle.
10250 *
10251 * This will return true, if `bundle_id` is present in the SDK init parameters.
10252 *
10253 * ```php
10254 * $my_fs = fs_dynamic_init( array(
10255 * // ...
10256 * 'bundle_id' => 'XXXX', // Will return true since we have bundle id.
10257 * 'bundle_public_key' => 'pk_XXXX',
10258 * ) );
10259 * ```
10260 *
10261 * @author Swashata Ghosh (@swashata)
10262 * @since 2.5.0
10263 *
10264 * @return bool True if we are running in bundle context, false otherwise.
10265 */
10266 private function has_bundle_context() {
10267 return ! is_null( $this->get_bundle_id() );
10268 }
10269
10270 /**
10271 * @author Vova Feldman (@svovaf)
10272 * @since 1.2.1.5
10273 *
10274 * @return string Freemius SDK version
10275 */
10276 function get_sdk_version() {
10277 return $this->version;
10278 }
10279
10280 /**
10281 * @author Vova Feldman (@svovaf)
10282 * @since 1.2.1.5
10283 *
10284 * @return number Parent plugin ID (if parent exist).
10285 */
10286 function get_parent_id() {
10287 return $this->is_addon() ?
10288 $this->get_parent_instance()->get_id() :
10289 $this->_plugin->id;
10290 }
10291
10292 /**
10293 * @author Vova Feldman (@svovaf)
10294 * @since 2.3.1
10295 *
10296 * @return string
10297 */
10298 function get_usage_tracking_terms_url() {
10299 return $this->apply_filters(
10300 'usage_tracking_terms_url',
10301 "https://freemius.com/wordpress/usage-tracking/{$this->_plugin->id}/{$this->_slug}/"
10302 );
10303 }
10304
10305 /**
10306 * @author Vova Feldman (@svovaf)
10307 * @since 2.3.1
10308 *
10309 * @return string
10310 */
10311 function get_eula_url() {
10312 return $this->apply_filters(
10313 'eula_url',
10314 "https://freemius.com/product/{$this->_plugin->id}/{$this->_slug}/legal/eula/"
10315 );
10316 }
10317
10318 /**
10319 * @author Vova Feldman (@svovaf)
10320 * @since 1.0.1
10321 *
10322 * @return string Plugin public key.
10323 */
10324 function get_public_key() {
10325 return $this->_plugin->public_key;
10326 }
10327
10328 /**
10329 * Will be available only on sandbox mode.
10330 *
10331 * @author Vova Feldman (@svovaf)
10332 * @since 1.0.4
10333 *
10334 * @return mixed Plugin secret key.
10335 */
10336 function get_secret_key() {
10337 return $this->_plugin->secret_key;
10338 }
10339
10340 /**
10341 * @author Vova Feldman (@svovaf)
10342 * @since 1.1.1
10343 *
10344 * @return bool
10345 */
10346 function has_secret_key() {
10347 return ! empty( $this->_plugin->secret_key );
10348 }
10349
10350 /**
10351 * @author Vova Feldman (@svovaf)
10352 * @since 1.0.9
10353 *
10354 * @param string|bool $premium_suffix
10355 *
10356 * @return string
10357 */
10358 function get_plugin_name( $premium_suffix = false ) {
10359 $this->_logger->entrance();
10360
10361 /**
10362 * This `if-else` can be squeezed into a single `if` but I intentionally split it for code readability.
10363 *
10364 * @author Vova Feldman
10365 */
10366 if ( ! isset( $this->_plugin_name ) ) {
10367 // Name is not yet set.
10368 $this->set_name( $premium_suffix );
10369 } else if (
10370 ! empty( $premium_suffix ) &&
10371 ( ! is_object( $this->_plugin ) || $this->_plugin->premium_suffix !== $premium_suffix )
10372 ) {
10373 // Name is already set, but there's a change in the premium suffix.
10374 $this->set_name( $premium_suffix );
10375 }
10376
10377 return $this->_plugin_name;
10378 }
10379
10380 /**
10381 * Calculates and stores the product's name. This helper function was created specifically for get_plugin_name() just to make the code clearer.
10382 *
10383 * @author Vova Feldman (@svovaf)
10384 * @since 2.2.1
10385 *
10386 * @param string $premium_suffix
10387 */
10388 private function set_name( $premium_suffix = '' ) {
10389 $plugin_data = $this->get_plugin_data();
10390
10391 // Get name.
10392 $this->_plugin_name = $plugin_data['Name'];
10393
10394 if ( is_string( $premium_suffix ) ) {
10395 $premium_suffix = trim( $premium_suffix );
10396
10397 if ( ! empty( $premium_suffix ) ) {
10398 // Check if plugin name contains " (premium)" or a custom suffix and remove it.
10399 $suffix = ( ' ' . strtolower( $premium_suffix ) );
10400 $suffix_len = strlen( $suffix );
10401
10402 if ( strlen( $plugin_data['Name'] ) > $suffix_len &&
10403 $suffix === substr( strtolower( $plugin_data['Name'] ), - $suffix_len )
10404 ) {
10405 $this->_plugin_name = substr( $plugin_data['Name'], 0, - $suffix_len );
10406 }
10407 }
10408 }
10409
10410 $this->_logger->departure( 'Name = ' . $this->_plugin_name );
10411 }
10412
10413 /**
10414 * @author Vova Feldman (@svovaf)
10415 * @since 1.0.0
10416 *
10417 * @param bool $reparse_plugin_metadata
10418 *
10419 * @return string
10420 */
10421 function get_plugin_version( $reparse_plugin_metadata = false ) {
10422 $this->_logger->entrance();
10423
10424 $plugin_data = $this->get_plugin_data( $reparse_plugin_metadata );
10425
10426 $this->_logger->departure( 'Version = ' . $plugin_data['Version'] );
10427
10428 return $this->apply_filters( 'plugin_version', $plugin_data['Version'] );
10429 }
10430
10431 /**
10432 * @author Vova Feldman (@svovaf)
10433 * @since 1.2.1.7
10434 *
10435 * @return string
10436 */
10437 function get_plugin_title() {
10438 $this->_logger->entrance();
10439
10440 $title = $this->_plugin->title;
10441
10442 return $this->apply_filters( 'plugin_title', $title );
10443 }
10444
10445 /**
10446 * @author Vova Feldman (@svovaf)
10447 * @since 1.2.2.7
10448 *
10449 * @param bool $lowercase
10450 *
10451 * @return string
10452 */
10453 function get_module_label( $lowercase = false ) {
10454 $label = $this->is_addon() ?
10455 $this->get_text_inline( 'Add-On', 'addon' ) :
10456 ( $this->is_plugin() ?
10457 $this->get_text_inline( 'Plugin', 'plugin' ) :
10458 $this->get_text_inline( 'Theme', 'theme' ) );
10459
10460 if ( $lowercase ) {
10461 $label = strtolower( $label );
10462 }
10463
10464 return $label;
10465 }
10466
10467 /**
10468 * @author Vova Feldman (@svovaf)
10469 * @since 1.0.4
10470 *
10471 * @return string
10472 */
10473 function get_plugin_basename() {
10474 if ( ! isset( $this->_plugin_basename ) ) {
10475 if ( $this->is_plugin() ) {
10476 $this->_plugin_basename = plugin_basename( $this->_plugin_main_file_path );
10477 } else {
10478 $this->_plugin_basename = basename( dirname( $this->_plugin_main_file_path ) );
10479 }
10480 }
10481
10482 return $this->_plugin_basename;
10483 }
10484
10485 function get_plugin_folder_name() {
10486 $this->_logger->entrance();
10487
10488 $plugin_folder = $this->_plugin_basename;
10489
10490 while ( '.' !== dirname( $plugin_folder ) ) {
10491 $plugin_folder = dirname( $plugin_folder );
10492 }
10493
10494 $this->_logger->departure( 'Folder Name = ' . $plugin_folder );
10495
10496 return $plugin_folder;
10497 }
10498
10499 #endregion ------------------------------------------------------------------
10500
10501 /* Account
10502 ------------------------------------------------------------------------------------------------------------------*/
10503
10504 /**
10505 * Find plugin's slug by plugin's basename.
10506 *
10507 * @author Vova Feldman (@svovaf)
10508 * @since 1.0.9
10509 *
10510 * @param string $plugin_base_name
10511 *
10512 * @return false|string
10513 */
10514 private static function find_slug_by_basename( $plugin_base_name ) {
10515 $file_slug_map = self::$_accounts->get_option( 'file_slug_map', array() );
10516
10517 if ( ! array( $file_slug_map ) || ! isset( $file_slug_map[ $plugin_base_name ] ) ) {
10518 return false;
10519 }
10520
10521 return $file_slug_map[ $plugin_base_name ];
10522 }
10523
10524 /**
10525 * Store the map between the plugin's basename to the slug.
10526 *
10527 * @author Vova Feldman (@svovaf)
10528 * @since 1.0.9
10529 */
10530 private function store_file_slug_map() {
10531 $file_slug_map = self::$_accounts->get_option( 'file_slug_map', array() );
10532
10533 if ( ! array( $file_slug_map ) ) {
10534 $file_slug_map = array();
10535 }
10536
10537 if ( ! isset( $file_slug_map[ $this->_plugin_basename ] ) ||
10538 $file_slug_map[ $this->_plugin_basename ] !== $this->_slug
10539 ) {
10540 $file_slug_map[ $this->_plugin_basename ] = $this->_slug;
10541 self::$_accounts->set_option( 'file_slug_map', $file_slug_map, true );
10542 }
10543 }
10544
10545 /**
10546 * @return array[number]FS_User
10547 */
10548 static function get_all_users() {
10549 $users = self::maybe_get_entities_account_option( 'users', array() );
10550
10551 if ( ! is_array( $users ) ) {
10552 $users = array();
10553 }
10554
10555 return $users;
10556 }
10557
10558 /**
10559 * @param string $module_type
10560 * @param null|int $blog_id Since 2.0.0
10561 *
10562 * @return array[string]FS_Site
10563 */
10564 private static function get_all_sites(
10565 $module_type = WP_FS__MODULE_TYPE_PLUGIN,
10566 $blog_id = null,
10567 $is_backup = false
10568 ) {
10569 $sites = self::get_account_option(
10570 ( $is_backup ? 'prev_' : '' ) . 'sites',
10571 $module_type,
10572 $blog_id
10573 );
10574
10575 if ( ! is_array( $sites ) ) {
10576 $sites = array();
10577 }
10578
10579 return $sites;
10580 }
10581
10582 /**
10583 * @author Leo Fajardo (@leorw)
10584 *
10585 * @since 1.2.2
10586 *
10587 * @param string $option_name
10588 * @param string $module_type
10589 * @param null|int $network_level_or_blog_id Since 2.0.0
10590 *
10591 * @return mixed
10592 */
10593 private static function get_account_option( $option_name, $module_type = null, $network_level_or_blog_id = null ) {
10594 if ( ! is_null( $module_type ) && WP_FS__MODULE_TYPE_PLUGIN !== $module_type ) {
10595 $option_name = $module_type . '_' . $option_name;
10596 }
10597
10598 return self::maybe_get_entities_account_option( $option_name, array(), $network_level_or_blog_id );
10599 }
10600
10601 /**
10602 * @author Leo Fajardo (@leorw)
10603 *
10604 * @since 1.2.2
10605 *
10606 * @param string $option_name
10607 * @param mixed $option_value
10608 * @param bool $store
10609 * @param null|int $network_level_or_blog_id Since 2.0.0
10610 */
10611 private function set_account_option( $option_name, $option_value, $store, $network_level_or_blog_id = null ) {
10612 self::set_account_option_by_module(
10613 $this->_module_type,
10614 $option_name,
10615 $option_value,
10616 $store,
10617 $network_level_or_blog_id
10618 );
10619 }
10620
10621 /**
10622 * @author Vova Feldman (@svovaf)
10623 *
10624 * @since 1.2.2.7
10625 *
10626 * @param string $module_type
10627 * @param string $option_name
10628 * @param mixed $option_value
10629 * @param bool $store
10630 * @param null|int $network_level_or_blog_id Since 2.0.0
10631 */
10632 private static function set_account_option_by_module(
10633 $module_type,
10634 $option_name,
10635 $option_value,
10636 $store,
10637 $network_level_or_blog_id = null
10638 ) {
10639 if ( WP_FS__MODULE_TYPE_PLUGIN != $module_type ) {
10640 $option_name = $module_type . '_' . $option_name;
10641 }
10642
10643 self::$_accounts->set_option( $option_name, $option_value, $store, $network_level_or_blog_id );
10644 }
10645
10646 /**
10647 * This method can also return non-entity or non-entities collection option like the `user_id_license_ids_map` option.
10648 *
10649 * @author Leo Fajardo (@leorw)
10650 * @since 2.3.1
10651 *
10652 * @param string $option_name
10653 * @param mixed $default
10654 * @param null|bool|int $network_level_or_blog_id When an integer, use the given blog storage. When `true` use the multisite storage (if there's a network). When `false`, use the current context blog storage. When `null`, the decision which storage to use (MS vs. Current S) will be handled internally and determined based on the $option (based on self::$_SITE_LEVEL_PARAMS).
10655 *
10656 * @return mixed|FS_Plugin[]|FS_User[]|FS_Site[]|FS_Plugin_License[]|FS_Plugin_Plan[]|FS_Plugin_Tag[]
10657 */
10658 private static function maybe_get_entities_account_option( $option_name, $default = null, $network_level_or_blog_id = null ) {
10659 $option = self::$_accounts->get_option( $option_name, $default, $network_level_or_blog_id );
10660
10661 $class_name = '';
10662
10663 if ( fs_starts_with( $option_name, WP_FS__MODULE_TYPE_THEME . '_' ) ) {
10664 $option_name = str_replace( WP_FS__MODULE_TYPE_THEME . '_', '', $option_name );
10665 }
10666
10667 switch ( $option_name ) {
10668 case 'plugins':
10669 case 'themes':
10670 case 'addons':
10671 $class_name = FS_Plugin::get_class_name();
10672 break;
10673 case 'users':
10674 $class_name = FS_User::get_class_name();
10675 break;
10676 case 'sites':
10677 $class_name = FS_Site::get_class_name();
10678 break;
10679 case 'licenses':
10680 case 'all_licenses':
10681 $class_name = FS_Plugin_License::get_class_name();
10682 break;
10683 case 'plans':
10684 $class_name = FS_Plugin_Plan::get_class_name();
10685 break;
10686 case 'updates':
10687 $class_name = FS_Plugin_Tag::get_class_name();
10688 break;
10689 }
10690
10691 if ( empty( $class_name ) ) {
10692 return $option;
10693 }
10694
10695 return fs_get_entities( $option, $class_name );
10696 }
10697
10698 /**
10699 * @author Vova Feldman (@svovaf)
10700 * @since 1.0.6
10701 *
10702 * @param number|null $module_id
10703 *
10704 * @return FS_Plugin_License[]
10705 */
10706 private static function get_all_licenses( $module_id = null ) {
10707 $licenses = self::get_account_option( 'all_licenses' );
10708
10709 if ( ! is_array( $licenses ) ) {
10710 $licenses = array();
10711 }
10712
10713 if ( is_null( $module_id ) ) {
10714 return $licenses;
10715 }
10716
10717 $licenses = isset( $licenses[ $module_id ] ) ?
10718 $licenses[ $module_id ] :
10719 array();
10720
10721 return $licenses;
10722 }
10723
10724 /**
10725 * @author Leo Fajardo (@leorw)
10726 * @since 2.0.0
10727 *
10728 * @return array
10729 */
10730 private static function get_all_licenses_by_module_type() {
10731 $licenses = self::get_account_option( 'all_licenses' );
10732
10733 $licenses_by_module_type = array(
10734 WP_FS__MODULE_TYPE_PLUGIN => array(),
10735 WP_FS__MODULE_TYPE_THEME => array()
10736 );
10737
10738 if ( ! is_array( $licenses ) ) {
10739 return $licenses_by_module_type;
10740 }
10741
10742 foreach ( $licenses as $module_id => $module_licenses ) {
10743 $fs = self::get_instance_by_id( $module_id );
10744 if ( false === $fs ) {
10745 continue;
10746 }
10747
10748 $licenses_by_module_type[ $fs->_module_type ] = array_merge( $licenses_by_module_type[ $fs->_module_type ], $module_licenses );
10749 }
10750
10751 return $licenses_by_module_type;
10752 }
10753
10754 /**
10755 * @author Leo Fajardo (@leorw)
10756 * @since 2.0.0
10757 *
10758 * @param number $module_id
10759 * @param number|null $user_id
10760 *
10761 * @return array
10762 */
10763 private static function get_user_id_license_ids_map( $module_id, $user_id = null ) {
10764 $all_modules_user_id_license_ids_map = self::get_account_option( 'user_id_license_ids_map' );
10765
10766 if ( ! is_array( $all_modules_user_id_license_ids_map ) ) {
10767 $all_modules_user_id_license_ids_map = array();
10768 }
10769
10770 $user_id_license_ids_map = isset( $all_modules_user_id_license_ids_map[ $module_id ] ) ?
10771 $all_modules_user_id_license_ids_map[ $module_id ] :
10772 array();
10773
10774 if ( FS_User::is_valid_id( $user_id ) ) {
10775 $user_id_license_ids_map = isset( $user_id_license_ids_map[ $user_id ] ) ?
10776 $user_id_license_ids_map[ $user_id ] :
10777 array();
10778 }
10779
10780 return $user_id_license_ids_map;
10781 }
10782
10783 /**
10784 * @author Leo Fajardo (@leorw)
10785 * @since 2.0.0
10786 *
10787 * @param array $new_user_id_license_ids_map
10788 * @param number $module_id
10789 * @param number|null $user_id
10790 */
10791 private static function store_user_id_license_ids_map( $new_user_id_license_ids_map, $module_id, $user_id = null ) {
10792 $all_modules_user_id_license_ids_map = self::get_account_option( 'user_id_license_ids_map' );
10793 if ( ! is_array( $all_modules_user_id_license_ids_map ) ) {
10794 $all_modules_user_id_license_ids_map = array();
10795 }
10796
10797 if ( ! isset( $all_modules_user_id_license_ids_map[ $module_id ] ) ) {
10798 $all_modules_user_id_license_ids_map[ $module_id ] = array();
10799 }
10800
10801 if ( FS_User::is_valid_id( $user_id ) ) {
10802 $all_modules_user_id_license_ids_map[ $module_id ][ $user_id ] = $new_user_id_license_ids_map;
10803 } else {
10804 $all_modules_user_id_license_ids_map[ $module_id ] = $new_user_id_license_ids_map;
10805 }
10806
10807 self::$_accounts->set_option( 'user_id_license_ids_map', $all_modules_user_id_license_ids_map, true );
10808 }
10809
10810 /**
10811 * Get a collection of the user's linked license IDs.
10812 *
10813 * @author Vova Feldman (@svovaf)
10814 * @since 2.0.0
10815 *
10816 * @param number $user_id
10817 *
10818 * @return number[]
10819 */
10820 private function get_user_linked_license_ids( $user_id ) {
10821 return self::get_user_id_license_ids_map( $this->_module_id, $user_id );
10822 }
10823
10824 /**
10825 * Override the user's linked license IDs with a new IDs collection.
10826 *
10827 * @author Vova Feldman (@svovaf)
10828 * @since 2.0.0
10829 *
10830 * @param number $user_id
10831 * @param number[] $license_ids
10832 */
10833 private function set_user_linked_license_ids( $user_id, array $license_ids ) {
10834 self::store_user_id_license_ids_map( $license_ids, $this->_module_id, $user_id );
10835 }
10836
10837 /**
10838 * Link a specified license ID to a given user.
10839 *
10840 * @author Vova Feldman (@svovaf)
10841 * @since 2.0.0
10842 *
10843 * @param number $license_id
10844 * @param number $user_id
10845 */
10846 private function link_license_2_user( $license_id, $user_id ) {
10847 $license_ids = $this->get_user_linked_license_ids( $user_id );
10848
10849 if ( in_array( $license_id, $license_ids ) ) {
10850 // License already linked.
10851 return;
10852 }
10853
10854 $license_ids[] = $license_id;
10855
10856 $this->set_user_linked_license_ids( $user_id, $license_ids );
10857 }
10858
10859 /**
10860 * @param string|bool $module_type
10861 *
10862 * @return FS_Plugin_Plan[]
10863 */
10864 private static function get_all_plans( $module_type = false ) {
10865 $plans = self::get_account_option( 'plans', $module_type );
10866
10867 if ( ! is_array( $plans ) ) {
10868 $plans = array();
10869 }
10870
10871 return $plans;
10872 }
10873
10874 /**
10875 * @author Vova Feldman (@svovaf)
10876 * @since 1.0.4
10877 *
10878 * @return FS_Plugin_Tag[]
10879 */
10880 private static function get_all_updates() {
10881 $updates = self::maybe_get_entities_account_option( 'updates', array() );
10882
10883 if ( ! is_array( $updates ) ) {
10884 $updates = array();
10885 }
10886
10887 return $updates;
10888 }
10889
10890 /**
10891 * @author Vova Feldman (@svovaf)
10892 * @since 1.0.6
10893 *
10894 * @return array<number,FS_Plugin[]>|false
10895 */
10896 private static function get_all_addons() {
10897 $addons = self::maybe_get_entities_account_option( 'addons', array() );
10898
10899 if ( ! is_array( $addons ) ) {
10900 $addons = array();
10901 }
10902
10903 return $addons;
10904 }
10905
10906 /**
10907 * @author Vova Feldman (@svovaf)
10908 * @since 1.0.6
10909 *
10910 * @return number[]|false
10911 */
10912 private static function get_all_account_addons() {
10913 $addons = self::$_accounts->get_option( 'account_addons', array() );
10914
10915 if ( ! is_array( $addons ) ) {
10916 $addons = array();
10917 }
10918
10919 return $addons;
10920 }
10921
10922 /**
10923 * Check if user has connected his account (opted-in).
10924 *
10925 * Note:
10926 * If the user opted-in and opted-out on a later stage,
10927 * this will still return true. If you want to check if the
10928 * user is currently opted-in, use:
10929 * `$fs->is_registered() && $fs->is_tracking_allowed()`
10930 *
10931 * @author Vova Feldman (@svovaf)
10932 * @since 1.0.1
10933 *
10934 * @param bool $ignore_anonymous_state Since 2.5.1
10935 *
10936 * @return bool
10937 */
10938 function is_registered( $ignore_anonymous_state = false ) {
10939 return (
10940 is_object( $this->_user ) &&
10941 (
10942 $this->is_premium() ||
10943 $ignore_anonymous_state ||
10944 ! $this->is_anonymous()
10945 )
10946 );
10947 }
10948
10949 /**
10950 * Returns TRUE if the user opted-in and didn't disconnect (opt-out).
10951 *
10952 * @author Leo Fajardo (@leorw)
10953 * @since 1.2.1.5
10954 *
10955 * @return bool
10956 */
10957 function is_tracking_allowed( $blog_id = null, $install = null ) {
10958 if ( is_null( $install ) ) {
10959 $install = is_null( $blog_id ) ?
10960 $this->_site :
10961 $this->get_install_by_blog_id( $blog_id );
10962 }
10963
10964 return (
10965 is_object( $install ) &&
10966 FS_Permission_Manager::instance( $this )->is_homepage_url_tracking_allowed( $blog_id )
10967 );
10968 }
10969
10970 /**
10971 * Returns TRUE if the user never opted-in or manually opted-out.
10972 *
10973 * @author Vova Feldman (@svovaf)
10974 * @since 1.2.1.5
10975 *
10976 * @param int|null $blog_id
10977 *
10978 * @return bool
10979 */
10980 function is_tracking_prohibited( $blog_id = null ) {
10981 return (
10982 ! $this->is_registered( true ) ||
10983 ! $this->is_tracking_allowed( $blog_id )
10984 );
10985 }
10986
10987 /**
10988 * @author Leo Fajardo (@leorw)
10989 * @since 2.4.0
10990 *
10991 * @return bool
10992 */
10993 function is_bundle_license_auto_activation_enabled() {
10994 return $this->is_addon() ?
10995 ( is_object( $this->_parent ) && $this->_parent->is_bundle_license_auto_activation_enabled() ) :
10996 $this->_is_bundle_license_auto_activation_enabled;
10997 }
10998
10999 /**
11000 * @author Vova Feldman (@svovaf)
11001 * @since 1.0.4
11002 *
11003 * @return FS_Plugin
11004 */
11005 function get_plugin() {
11006 return $this->_plugin;
11007 }
11008
11009 /**
11010 * @author Vova Feldman (@svovaf)
11011 * @since 1.0.3
11012 *
11013 * @return FS_User
11014 */
11015 function get_user() {
11016 return $this->_user;
11017 }
11018
11019 /**
11020 * @author Vova Feldman (@svovaf)
11021 * @since 1.0.3
11022 *
11023 * @return FS_Site
11024 */
11025 function get_site() {
11026 return $this->_site;
11027 }
11028
11029 /**
11030 * @author Leo Fajardo (@leorw)
11031 * @since 2.5.0
11032 */
11033 function store_site( $site ) {
11034 $this->_site = $site;
11035 $this->_store_site( true );
11036 }
11037
11038 /**
11039 * Deletes the current install with an option to back it up in case restoration will be needed (e.g., if the automatic clone resolution attempt fails).
11040 *
11041 * @author Leo Fajardo (@leorw)
11042 * @since 2.5.0
11043 */
11044 function delete_current_install( $back_up ) {
11045 // Back up and delete the unique ID.
11046 if ( $back_up ) {
11047 self::$_accounts->set_option( 'prev_unique_id', $this->get_anonymous_id() );
11048 }
11049
11050 self::$_accounts->set_option( 'unique_id', null );
11051
11052 if ( $back_up ) {
11053 // Back up the install before deleting it so that it can be restored later on if necessary (e.g., if the automatic clone resolution attempt fails).
11054 $this->back_up_site();
11055 }
11056
11057 $this->_delete_site();
11058 $this->_site = null;
11059 }
11060
11061 /**
11062 * @author Leo Fajardo (@leorw)
11063 * @since 2.5.0
11064 */
11065 function restore_backup_site() {
11066 self::$_accounts->set_option(
11067 'unique_id',
11068 self::$_accounts->get_option( 'prev_unique_id' )
11069 );
11070
11071 $sites = self::get_all_sites( $this->_module_type, null, true );
11072 $this->store_site( clone $sites[ $this->_slug ] );
11073 }
11074
11075 /**
11076 * Get plugin add-ons.
11077 *
11078 * @author Vova Feldman (@svovaf)
11079 * @since 1.0.6
11080 *
11081 * @since 1.1.7.3 If not yet loaded, fetch data from the API.
11082 *
11083 * @param bool $flush
11084 *
11085 * @return FS_Plugin[]|false
11086 */
11087 function get_addons( $flush = false ) {
11088 $this->_logger->entrance();
11089
11090 if ( ! $this->_has_addons ) {
11091 return false;
11092 }
11093
11094 $addons = $this->sync_addons( $flush );
11095
11096 return ( ! is_array( $addons ) || empty( $addons ) ) ?
11097 false :
11098 $addons;
11099 }
11100
11101 /**
11102 * @author Vova Feldman (@svovaf)
11103 * @since 1.0.6
11104 *
11105 * @return number[]|false
11106 */
11107 function get_account_addons() {
11108 $this->_logger->entrance();
11109
11110 $addons = self::get_all_account_addons();
11111
11112 if ( ! is_array( $addons ) ||
11113 ! isset( $addons[ $this->_plugin->id ] ) ||
11114 ! is_array( $addons[ $this->_plugin->id ] ) ||
11115 0 === count( $addons[ $this->_plugin->id ] )
11116 ) {
11117 return false;
11118 }
11119
11120 return $addons[ $this->_plugin->id ];
11121 }
11122
11123 /**
11124 * Check if user has any
11125 *
11126 * @author Vova Feldman (@svovaf)
11127 * @since 1.1.6
11128 *
11129 * @return bool
11130 */
11131 function has_account_addons() {
11132 $addons = $this->get_account_addons();
11133
11134 return is_array( $addons ) && ( 0 < count( $addons ) );
11135 }
11136
11137
11138 /**
11139 * Get add-on by ID (from local data).
11140 *
11141 * @author Vova Feldman (@svovaf)
11142 * @since 1.0.6
11143 *
11144 * @param number $id
11145 *
11146 * @return FS_Plugin|false
11147 */
11148 function get_addon( $id ) {
11149 $this->_logger->entrance();
11150
11151 $addons = $this->get_addons();
11152
11153 if ( is_array( $addons ) ) {
11154 foreach ( $addons as $addon ) {
11155 if ( $id == $addon->id ) {
11156 return $addon;
11157 }
11158 }
11159 }
11160
11161 return false;
11162 }
11163
11164 /**
11165 * Get add-on by slug (from local data).
11166 *
11167 * @author Vova Feldman (@svovaf)
11168 * @since 1.0.6
11169 *
11170 * @param string $slug
11171 *
11172 * @param bool $flush
11173 *
11174 * @return FS_Plugin|false
11175 */
11176 function get_addon_by_slug( $slug, $flush = false ) {
11177 $this->_logger->entrance();
11178
11179 $addons = $this->get_addons( $flush );
11180
11181 if ( is_array( $addons ) ) {
11182 foreach ( $addons as $addon ) {
11183 if ( $slug === $addon->slug ) {
11184 return $addon;
11185 }
11186 }
11187 }
11188
11189 return false;
11190 }
11191
11192 /**
11193 * @var array<number,object[]> {
11194 * @key number Add-on ID.
11195 * @val object[] The add-on's plans and prices object.
11196 * }
11197 */
11198 private $plans_and_pricing_by_addon_id;
11199
11200 /**
11201 * @author Leo Fajardo (@leorw)
11202 * @since 2.3.0
11203 *
11204 * @return array<number,object[]> {
11205 * @key number Add-on ID.
11206 * @val object[] The add-on's plans and prices object.
11207 * }
11208 */
11209 function _get_addons_plans_and_pricing_map_by_id() {
11210 if ( ! isset( $this->plans_and_pricing_by_addon_id ) ) {
11211 $result = $this->get_api_plugin_scope()->get( $this->add_show_pending( "/addons/pricing.json?type=visible" ) );
11212
11213 $plans_and_pricing_by_addon_id = array();
11214 if ( $this->is_api_result_object( $result, 'addons' ) ) {
11215 foreach ( $result->addons as $addon ) {
11216 $plans_and_pricing_by_addon_id[ $addon->id ] = $addon->plans;
11217 }
11218 }
11219
11220 $this->plans_and_pricing_by_addon_id = $plans_and_pricing_by_addon_id;
11221 }
11222
11223 return $this->plans_and_pricing_by_addon_id;
11224 }
11225
11226 /**
11227 * @author Leo Fajardo (@leorw)
11228 * @since 2.3.0
11229 *
11230 * @param number $addon_id
11231 * @param bool $is_installed
11232 *
11233 * @return array
11234 */
11235 function _get_addon_info( $addon_id, $is_installed ) {
11236 $addon = $this->get_addon( $addon_id );
11237
11238 if ( ! is_object( $addon ) ) {
11239 // Unexpected call.
11240 return array();
11241 }
11242
11243 $slug = $addon->slug;
11244
11245 $addon_storage = FS_Storage::instance( WP_FS__MODULE_TYPE_PLUGIN, $slug );
11246
11247 if ( ! fs_is_network_admin() ) {
11248 // Get blog-level activated installations.
11249 $sites = self::maybe_get_entities_account_option( 'sites', array() );
11250 } else {
11251 $sites = null;
11252
11253 if ( $this->is_addon_activated( $addon_id ) &&
11254 $this->get_addon_instance( $addon_id )->is_network_active()
11255 ) {
11256 if ( FS_Site::is_valid_id( $addon_storage->network_install_blog_id ) ) {
11257 // Get network-level activated installations.
11258 $sites = self::maybe_get_entities_account_option(
11259 'sites',
11260 array(),
11261 $addon_storage->network_install_blog_id
11262 );
11263 }
11264 }
11265 }
11266
11267 $addon_info = array(
11268 'is_connected' => false,
11269 'slug' => $slug,
11270 'title' => $addon->title,
11271 'is_whitelabeled' => $addon_storage->is_whitelabeled
11272 );
11273
11274 if ( ! $is_installed ) {
11275 $plans_and_pricing_by_addon_id = $this->_get_addons_plans_and_pricing_map_by_id();
11276
11277 if ( isset( $plans_and_pricing_by_addon_id[ $addon_id ] ) ) {
11278 $has_paid_plan = false;
11279 $plans = $plans_and_pricing_by_addon_id[ $addon_id ];
11280
11281 if ( is_array( $plans ) && count( $plans ) > 0 ) {
11282 foreach ( $plans as $plan ) {
11283 if ( isset( $plan->pricing ) &&
11284 is_array( $plan->pricing ) &&
11285 count( $plan->pricing ) > 0
11286 ) {
11287 $has_paid_plan = true;
11288 break;
11289 }
11290 }
11291 }
11292
11293 $addon_info['has_paid_plan'] = $has_paid_plan;
11294 }
11295 }
11296
11297 if ( ! is_array( $sites ) || ! isset( $sites[ $slug ] ) ) {
11298 return $addon_info;
11299 }
11300
11301 $site = $sites[ $slug ];
11302
11303 $addon_info['is_connected'] = (
11304 ( $addon->parent_plugin_id == $this->get_id() ) &&
11305 is_object( $site ) &&
11306 FS_Site::is_valid_id( $site->id ) &&
11307 FS_User::is_valid_id( $site->user_id ) &&
11308 FS_Plugin_Plan::is_valid_id( $site->plan_id )
11309 );
11310
11311 if ( $addon_info['is_connected'] && $is_installed ) {
11312 return $addon_info;
11313 }
11314
11315 $addon_info['site'] = $site;
11316
11317 $plugins_data = self::maybe_get_entities_account_option( WP_FS__MODULE_TYPE_PLUGIN . 's', array() );
11318 if ( isset( $plugins_data[ $slug ] ) ) {
11319 $plugin_data = $plugins_data[ $slug ];
11320
11321 $addon_info['version'] = $plugin_data->version;
11322 }
11323
11324 $all_plans = self::maybe_get_entities_account_option( 'plans', array() );
11325 if ( isset( $all_plans[ $slug ] ) ) {
11326 $plans = $all_plans[ $slug ];
11327
11328 foreach ( $plans as $plan ) {
11329 if ( $site->plan_id == Freemius::_decrypt( $plan->id ) ) {
11330 $addon_info['plan_name'] = Freemius::_decrypt( $plan->name );
11331 $addon_info['plan_title'] = Freemius::_decrypt( $plan->title );
11332 break;
11333 }
11334 }
11335 }
11336
11337 $licenses = self::maybe_get_entities_account_option( 'all_licenses', array() );
11338 if ( is_array( $licenses ) && isset( $licenses[ $addon_id ] ) ) {
11339 foreach ( $licenses[ $addon_id ] as $license ) {
11340 if ( $license->id == $site->license_id ) {
11341 $addon_info['license'] = $license;
11342 break;
11343 }
11344 }
11345 }
11346
11347 if ( isset( $addon_info['license'] ) ) {
11348 if ( isset( $addon_storage->subscriptions ) &&
11349 ! empty( $addon_storage->subscriptions )
11350 ) {
11351 $addon_subscriptions = fs_get_entities( $addon_storage->subscriptions, FS_Subscription::get_class_name() );
11352
11353 foreach ( $addon_subscriptions as $subscription ) {
11354 if ( $subscription->license_id == $site->license_id ) {
11355 $addon_info['subscription'] = $subscription;
11356 break;
11357 }
11358 }
11359 }
11360 }
11361
11362 return $addon_info;
11363 }
11364
11365 /**
11366 * @author Vova Feldman (@svovaf)
11367 * @since 2.0.0
11368 *
11369 * @param number $user_id
11370 *
11371 * @return FS_User
11372 */
11373 static function _get_user_by_id( $user_id ) {
11374 self::$_static_logger->entrance( "user_id = {$user_id}" );
11375
11376 $users = self::get_all_users();
11377
11378 if ( is_array( $users ) ) {
11379 if ( isset( $users[ $user_id ] ) &&
11380 $users[ $user_id ] instanceof FS_User &&
11381 $user_id == $users[ $user_id ]->id
11382 ) {
11383 return $users[ $user_id ];
11384 }
11385
11386 // If user wasn't found by the key, iterate over all the users collection.
11387 foreach ( $users as $user ) {
11388 /**
11389 * @var FS_User $user
11390 */
11391 if ( $user_id == $user->id ) {
11392 return $user;
11393 }
11394 }
11395 }
11396
11397 return null;
11398 }
11399
11400 /**
11401 * Checks if a Freemius user_id is associated with a super-admin.
11402 *
11403 * @author Vova Feldman (@svovaf)
11404 * @since 2.0.0
11405 *
11406 * @param number $user_id
11407 *
11408 * @return bool
11409 */
11410 private static function is_super_admin( $user_id ) {
11411 $is_super_admin = false;
11412
11413 $user = self::_get_user_by_id( $user_id );
11414
11415 if ( $user instanceof FS_User && ! empty( $user->email ) ) {
11416 self::require_pluggable_essentials();
11417
11418 $wp_user = get_user_by( 'email', $user->email );
11419
11420 if ( $wp_user instanceof WP_User ) {
11421 $super_admins = get_super_admins();
11422 $is_super_admin = ( is_array( $super_admins ) && in_array( $wp_user->user_login, $super_admins ) );
11423 }
11424 }
11425
11426 return $is_super_admin;
11427 }
11428
11429 #----------------------------------------------------------------------------------
11430 #region Plans & Licensing
11431 #----------------------------------------------------------------------------------
11432
11433 /**
11434 * Check if running premium plugin code.
11435 *
11436 * @author Vova Feldman (@svovaf)
11437 * @since 1.0.5
11438 *
11439 * @return bool
11440 */
11441 function is_premium() {
11442 /**
11443 * `$this->_plugin` will be `false` when `is_activation_mode` calls this method directly from the
11444 * `register_constructor_hooks` method.
11445 *
11446 * @author Leo Fajardo (@leorw)
11447 * @since 2.2.3
11448 */
11449 return is_object( $this->_plugin ) ?
11450 $this->_plugin->is_premium :
11451 false;
11452 }
11453
11454 /**
11455 * Get site's plan ID.
11456 *
11457 * @author Vova Feldman (@svovaf)
11458 * @since 1.0.2
11459 *
11460 * @return number
11461 */
11462 function get_plan_id() {
11463 return $this->_site->plan_id;
11464 }
11465
11466 /**
11467 * Get site's plan title.
11468 *
11469 * @author Vova Feldman (@svovaf)
11470 * @since 1.0.2
11471 *
11472 * @return string
11473 */
11474 function get_plan_title() {
11475 $plan = $this->get_plan();
11476
11477 return is_object( $plan ) ? $plan->title : 'PLAN_TITLE';
11478 }
11479
11480 /**
11481 * Get site's plan name.
11482 *
11483 * @author Vova Feldman (@svovaf)
11484 * @since 2.0.0
11485 *
11486 * @return string
11487 */
11488 function get_plan_name() {
11489 $plan = $this->get_plan();
11490
11491 return is_object( $plan ) ? $plan->name : 'PLAN_NAME';
11492 }
11493
11494 /**
11495 * @author Vova Feldman (@svovaf)
11496 * @since 1.0.9
11497 *
11498 * @return FS_Plugin_Plan|false
11499 */
11500 function get_plan() {
11501 if ( ! is_object( $this->_site ) ) {
11502 return false;
11503 }
11504
11505 return FS_Plugin_Plan::is_valid_id( $this->_site->plan_id ) ?
11506 $this->_get_plan_by_id( $this->_site->plan_id ) :
11507 false;
11508 }
11509
11510 /**
11511 * @author Vova Feldman (@svovaf)
11512 * @since 1.0.3
11513 *
11514 * @return bool
11515 */
11516 function is_trial() {
11517 $this->_logger->entrance();
11518
11519 if ( ! $this->is_registered( true ) || ! is_object( $this->_site ) ) {
11520 return false;
11521 }
11522
11523 return $this->_site->is_trial();
11524 }
11525
11526 /**
11527 * Check if currently in a trial with payment method (credit card or paypal).
11528 *
11529 * @author Vova Feldman (@svovaf)
11530 * @since 1.1.7
11531 *
11532 * @return bool
11533 */
11534 function is_paid_trial() {
11535 $this->_logger->entrance();
11536
11537 if ( ! $this->is_trial() ) {
11538 return false;
11539 }
11540
11541 if ( ! $this->has_active_valid_license() ) {
11542 return false;
11543 }
11544
11545 if ( $this->_site->trial_plan_id != $this->_license->plan_id ) {
11546 return false;
11547 }
11548
11549 /**
11550 * @var FS_Subscription $subscription
11551 */
11552 $subscription = $this->_get_subscription( $this->_license->id );
11553
11554 return ( is_object( $subscription ) && $subscription->is_active() );
11555 }
11556
11557 /**
11558 * Check if trial already utilized.
11559 *
11560 * @since 1.0.9
11561 *
11562 * @return bool
11563 */
11564 function is_trial_utilized() {
11565 $this->_logger->entrance();
11566
11567 if ( ! $this->is_registered() ) {
11568 return false;
11569 }
11570
11571 return $this->_site->is_trial_utilized();
11572 }
11573
11574 /**
11575 * Get trial plan information (if in trial).
11576 *
11577 * @author Vova Feldman (@svovaf)
11578 * @since 1.0.9
11579 *
11580 * @return bool|FS_Plugin_Plan
11581 */
11582 function get_trial_plan() {
11583 $this->_logger->entrance();
11584
11585 if ( ! $this->is_trial() ) {
11586 return false;
11587 }
11588
11589 // Try to load plan from local cache.
11590 $trial_plan = $this->_get_plan_by_id( $this->_site->trial_plan_id );
11591
11592 if ( ! is_object( $trial_plan ) ) {
11593 $trial_plan = $this->_fetch_site_plan( $this->_site->trial_plan_id );
11594
11595 /**
11596 * If managed to fetch the plan, add it to the plans collection.
11597 */
11598 if ( $trial_plan instanceof FS_Plugin_Plan ) {
11599 if ( ! is_array( $this->_plans ) ) {
11600 $this->_plans = array();
11601 }
11602
11603 $this->_plans[] = $trial_plan;
11604 $this->_store_plans();
11605 }
11606 }
11607
11608 if ( $trial_plan instanceof FS_Plugin_Plan ) {
11609 return $trial_plan;
11610 }
11611
11612 /**
11613 * If for some reason failed to get the trial plan, fallback to a dummy name and title.
11614 */
11615 $trial_plan = new FS_Plugin_Plan();
11616 $trial_plan->id = $this->_site->trial_plan_id;
11617 $trial_plan->name = 'pro';
11618 $trial_plan->title = 'Pro';
11619
11620 return $trial_plan;
11621 }
11622
11623 /**
11624 * Check if the user has an activate, non-expired license on current plugin's install.
11625 *
11626 * @since 1.0.9
11627 *
11628 * @return bool
11629 */
11630 function is_paying() {
11631 $this->_logger->entrance();
11632
11633 if ( ! $this->is_registered( true ) ) {
11634 return false;
11635 }
11636
11637 if ( ! $this->has_paid_plan() ) {
11638 return false;
11639 }
11640
11641 return (
11642 ! $this->is_trial() &&
11643 'free' !== $this->get_plan_name() &&
11644 $this->has_active_valid_license()
11645 );
11646 }
11647
11648 /**
11649 * @author Vova Feldman (@svovaf)
11650 * @since 1.0.4
11651 *
11652 * @return bool
11653 */
11654 function is_free_plan() {
11655 if ( ! $this->is_registered() ) {
11656 return true;
11657 }
11658
11659 if ( ! $this->has_paid_plan() ) {
11660 return true;
11661 }
11662
11663 return (
11664 'free' === $this->get_plan_name() ||
11665 ! $this->has_features_enabled_license()
11666 );
11667 }
11668
11669 /**
11670 * @author Vova Feldman (@svovaf)
11671 * @since 1.0.5
11672 *
11673 * @return bool
11674 */
11675 function _has_premium_license() {
11676 $this->_logger->entrance();
11677
11678 $premium_license = $this->_get_available_premium_license();
11679
11680 return ( false !== $premium_license );
11681 }
11682
11683 /**
11684 * Check if user has any licenses associated with the plugin (including expired or blocking).
11685 *
11686 * @author Vova Feldman (@svovaf)
11687 * @since 1.1.7.3
11688 *
11689 * @param bool $including_foreign
11690 *
11691 * @return bool
11692 */
11693 function has_any_license( $including_foreign = true ) {
11694 if ( ! is_array( $this->_licenses ) || 0 === count( $this->_licenses ) ) {
11695 return false;
11696 }
11697
11698 if ( $including_foreign ) {
11699 return true;
11700 }
11701
11702 foreach ( $this->_licenses as $license ) {
11703 if ( $this->_user->id == $license->user_id ) {
11704 return true;
11705 }
11706 }
11707
11708 return false;
11709 }
11710
11711 /**
11712 * @author Vova Feldman (@svovaf)
11713 * @since 1.0.5
11714 *
11715 * @param bool|null $is_localhost
11716 *
11717 * @return FS_Plugin_License|false
11718 */
11719 function _get_available_premium_license( $is_localhost = null ) {
11720 $this->_logger->entrance();
11721
11722 $licenses = $this->get_available_premium_licenses( $is_localhost );
11723 if ( ! empty( $licenses ) ) {
11724 return $licenses[0];
11725 }
11726
11727 return false;
11728 }
11729
11730 /**
11731 * @author Vova Feldman (@svovaf)
11732 * @since 1.0.5
11733 *
11734 * @param bool|null $is_localhost
11735 *
11736 * @return FS_Plugin_License[]
11737 */
11738 function get_available_premium_licenses( $is_localhost = null ) {
11739 $this->_logger->entrance();
11740
11741 $licenses = array();
11742 if ( ! $this->has_paid_plan() ) {
11743 return $licenses;
11744 }
11745
11746 if ( is_array( $this->_licenses ) ) {
11747 foreach ( $this->_licenses as $license ) {
11748 if ( ! $license->can_activate( $is_localhost ) ) {
11749 continue;
11750 }
11751
11752 $licenses[] = $license;
11753 }
11754 }
11755
11756 return $licenses;
11757 }
11758
11759 /**
11760 * Sync local plugin plans with remote server.
11761 *
11762 * IMPORTANT: If for some reason a site is associated with deleted plan, we'll preserve the plan's information and append it as the last plan. This means that if plan is deleted, the is_plan() method will ALWAYS return true for any given argument (it becomes the most inclusive plan).
11763 *
11764 * @author Vova Feldman (@svovaf)
11765 * @since 1.0.5
11766 *
11767 * @return FS_Plugin_Plan[]|object
11768 */
11769 function _sync_plans() {
11770 $plans = $this->_fetch_plugin_plans();
11771
11772 if ( $this->is_array_instanceof( $plans, 'FS_Plugin_Plan' ) ) {
11773 $plans_map = array();
11774 foreach ( $plans as $plan ) {
11775 $plans_map[ $plan->id ] = true;
11776 }
11777
11778 $plans_ids_to_keep = $this->get_plans_ids_associated_with_installs();
11779
11780 foreach ( $plans_ids_to_keep as $plan_id ) {
11781 if ( isset( $plans_map[ $plan_id ] ) ) {
11782 continue;
11783 }
11784
11785 $missing_plan = self::_get_plan_by_id( $plan_id );
11786
11787 if ( is_object( $missing_plan ) ) {
11788 $plans[] = $missing_plan;
11789 }
11790 }
11791
11792 $this->_plans = $plans;
11793 $this->_store_plans();
11794 }
11795
11796 $this->do_action( 'after_plans_sync', $plans );
11797
11798 return $this->_plans;
11799 }
11800
11801 /**
11802 * Check if specified plan exists locally. If not, fetch it and store it.
11803 *
11804 * @author Vova Feldman (@svovaf)
11805 * @since 2.0.0
11806 *
11807 * @param number $plan_id
11808 *
11809 * @return \FS_Plugin_Plan|object The plan entity or the API error object on failure.
11810 */
11811 private function sync_plan_if_not_exist( $plan_id ) {
11812 $plan = self::_get_plan_by_id( $plan_id );
11813
11814 if ( is_object( $plan ) ) {
11815 // Plan already exists.
11816 return $plan;
11817 }
11818
11819 $plan = $this->fetch_plan_by_id( $plan_id );
11820
11821 if ( $plan instanceof FS_Plugin_Plan ) {
11822 $this->_plans[] = $plan;
11823 $this->_store_plans();
11824
11825 return $plan;
11826 }
11827
11828 return $plan;
11829 }
11830
11831 /**
11832 * Check if specified license exists locally. If not, fetch it and store it.
11833 *
11834 * @author Vova Feldman (@svovaf)
11835 * @since 2.0.0
11836 *
11837 * @param number $license_id
11838 * @param string $license_key
11839 *
11840 * @return \FS_Plugin_Plan|object The plan entity or the API error object on failure.
11841 */
11842 private function sync_license_if_not_exist( $license_id, $license_key ) {
11843 $license = $this->_get_license_by_id( $license_id );
11844
11845 if ( is_object( $license ) ) {
11846 // License already exists.
11847 return $license;
11848 }
11849
11850 $license = $this->fetch_license_by_key( $license_id, $license_key );
11851
11852 if ( $license instanceof FS_Plugin_License ) {
11853 $this->_licenses[] = $license;
11854
11855 $this->set_license( $license );
11856
11857 $this->_store_licenses();
11858
11859 return $license;
11860 }
11861
11862 return $license;
11863 }
11864
11865 /**
11866 * Get a collection of unique plan IDs that are associated with any installs in the network.
11867 *
11868 * @author Leo Fajardo (@leorw)
11869 * @since 2.0.0
11870 *
11871 * @return number[]
11872 */
11873 private function get_plans_ids_associated_with_installs() {
11874 if ( ! is_multisite() ) {
11875 if ( ! is_object( $this->_site ) ||
11876 ! FS_Plugin_Plan::is_valid_id( $this->_site->plan_id )
11877 ) {
11878 return array();
11879 }
11880
11881 return array( $this->_site->plan_id );
11882 }
11883
11884 $plan_ids = array();
11885 $sites = self::get_sites();
11886 foreach ( $sites as $site ) {
11887 $blog_id = self::get_site_blog_id( $site );
11888 $install = $this->get_install_by_blog_id( $blog_id );
11889
11890 if ( ! is_object( $install ) ||
11891 ! FS_Plugin_Plan::is_valid_id( $install->plan_id )
11892 ) {
11893 continue;
11894 }
11895
11896 $plan_ids[ $install->plan_id ] = true;
11897 }
11898
11899 return array_keys( $plan_ids );
11900 }
11901
11902 /**
11903 * Get a collection of unique license IDs that are associated with any installs in the network.
11904 *
11905 * @author Leo Fajardo (@leorw)
11906 * @since 2.0.0
11907 *
11908 * @return number[]
11909 */
11910 private function get_license_ids_associated_with_installs() {
11911 if ( ! $this->_is_network_active ) {
11912 if ( ! is_object( $this->_site ) ||
11913 ! FS_Plugin_License::is_valid_id( $this->_site->license_id )
11914 ) {
11915 return array();
11916 }
11917
11918 return array( $this->_site->license_id );
11919 }
11920
11921 $license_ids = array();
11922 $sites = self::get_sites();
11923 foreach ( $sites as $site ) {
11924 $blog_id = self::get_site_blog_id( $site );
11925 $install = $this->get_install_by_blog_id( $blog_id );
11926
11927 if ( ! is_object( $install ) ||
11928 ! FS_Plugin_License::is_valid_id( $install->license_id )
11929 ) {
11930 continue;
11931 }
11932
11933 $license_ids[ $install->license_id ] = true;
11934 }
11935
11936 return array_keys( $license_ids );
11937 }
11938
11939 /**
11940 * @author Vova Feldman (@svovaf)
11941 * @since 1.0.5
11942 *
11943 * @param number $id
11944 *
11945 * @return FS_Plugin_Plan|false
11946 */
11947 function _get_plan_by_id( $id ) {
11948 $this->_logger->entrance();
11949
11950 if ( ! is_array( $this->_plans ) || 0 === count( $this->_plans ) ) {
11951 $this->_sync_plans();
11952 }
11953
11954 foreach ( $this->_plans as $plan ) {
11955 if ( $id == $plan->id ) {
11956 return $plan;
11957 }
11958 }
11959
11960 return false;
11961 }
11962
11963 /**
11964 * @author Vova Feldman (@svovaf)
11965 * @since 1.1.8.1
11966 *
11967 * @param string $name
11968 *
11969 * @return FS_Plugin_Plan|false
11970 */
11971 private function get_plan_by_name( $name ) {
11972 $this->_logger->entrance();
11973
11974 if ( ! is_array( $this->_plans ) || 0 === count( $this->_plans ) ) {
11975 $this->_sync_plans();
11976 }
11977
11978 foreach ( $this->_plans as $plan ) {
11979 if ( $name == $plan->name ) {
11980 return $plan;
11981 }
11982 }
11983
11984 return false;
11985 }
11986
11987 /**
11988 * Sync local licenses with remote server.
11989 *
11990 * @author Vova Feldman (@svovaf)
11991 * @since 1.0.6
11992 *
11993 * @param number|bool $site_license_id
11994 * @param number|null $blog_id
11995 *
11996 * @return FS_Plugin_License[]|object
11997 */
11998 function _sync_licenses( $site_license_id = false, $blog_id = null ) {
11999 $this->_logger->entrance();
12000
12001 $is_network_admin = fs_is_network_admin();
12002
12003 if ( $is_network_admin && is_null( $blog_id ) ) {
12004 $all_licenses = self::get_all_licenses( $this->_module_id );
12005 } else {
12006 $all_licenses = $this->get_user_licenses( $this->_user->id );
12007 }
12008
12009 $foreign_licenses = $this->get_foreign_licenses_info( $all_licenses, $site_license_id );
12010
12011 $all_licenses_map = array();
12012 foreach ( $all_licenses as $license ) {
12013 $all_licenses_map[ $license->id ] = true;
12014 }
12015
12016 $licenses = $this->_fetch_licenses( false, $site_license_id, $foreign_licenses, $blog_id );
12017
12018 if ( $this->is_array_instanceof( $licenses, 'FS_Plugin_License' ) ) {
12019 $licenses_map = array();
12020 foreach ( $licenses as $license ) {
12021 $licenses_map[ $license->id ] = true;
12022 }
12023
12024 // $license_ids_to_keep = $this->get_license_ids_associated_with_installs();
12025 // foreach ( $license_ids_to_keep as $license_id ) {
12026 // if ( isset( $licenses_map[ $license_id ] ) ) {
12027 // continue;
12028 // }
12029 //
12030 // $missing_license = self::_get_license_by_id( $license_id, false );
12031 // if ( is_object( $missing_license ) ) {
12032 // $licenses[] = $missing_license;
12033 // $licenses_map[ $missing_license->id ] = true;
12034 // }
12035 // }
12036
12037 $user_license_ids = $this->get_user_linked_license_ids( $this->_user->id );
12038
12039 foreach ( $user_license_ids as $key => $license_id ) {
12040 if ( ! isset( $licenses_map[ $license_id ] ) ) {
12041 // Remove access to licenses that no longer exist.
12042 unset( $user_license_ids[ $key ] );
12043 }
12044 }
12045
12046 if ( ! empty( $user_license_ids ) ) {
12047 foreach ( $licenses_map as $license_id => $value ) {
12048 if ( ! isset( $all_licenses_map[ $license_id ] ) ) {
12049 // Associate new licenses with the user who triggered the license syncing.
12050 $user_license_ids[] = $license_id;
12051 }
12052 }
12053
12054 $user_license_ids = array_unique( $user_license_ids );
12055 } else {
12056 $user_license_ids = array_keys( $licenses_map );
12057 }
12058
12059 if ( ! $is_network_admin || ! is_null( $blog_id ) ) {
12060 $user_licenses = array();
12061 foreach ( $licenses as $license ) {
12062 if ( ! in_array( $license->id, $user_license_ids ) ) {
12063 continue;
12064 }
12065
12066 $user_licenses[] = $license;
12067 }
12068
12069 $this->_licenses = $user_licenses;
12070 } else {
12071 $this->_licenses = $licenses;
12072 }
12073
12074 $this->set_user_linked_license_ids( $this->_user->id, $user_license_ids );
12075
12076 $this->_store_licenses( true, $this->_module_id, $licenses );
12077 }
12078
12079 // Update current license.
12080 if ( is_object( $this->_license ) ) {
12081 $license = $this->_get_license_by_id( $this->_license->id );
12082
12083 if ( is_object( $license ) ) {
12084 /**
12085 * `$license` can be `false` in case a user change action has just been completed and this method
12086 * has synced the `$this->_licenses` collection for the new user. In this case, the
12087 * `$this->_licenses` collection may have only the newly activated license that is associated with
12088 * the new user. `set_license` will eventually be called in the same request by the logic that
12089 * follows outside this method which will detect that the install's license has been updated, and
12090 * then `_update_site_license` will be called which in turn will call `set_license`.
12091 *
12092 * @author Leo Fajardo (@leorw)
12093 * @since 2.3.2
12094 */
12095 $this->set_license( $license );
12096 }
12097 }
12098
12099 return $this->_licenses;
12100 }
12101
12102 /**
12103 * @author Vova Feldman (@svovaf)
12104 * @since 1.0.5
12105 *
12106 * @param number $id
12107 * @param bool $sync_licenses
12108 *
12109 * @return FS_Plugin_License|false
12110 */
12111 function _get_license_by_id( $id, $sync_licenses = true ) {
12112 $this->_logger->entrance();
12113
12114 if ( ! FS_Plugin_License::is_valid_id( $id ) ) {
12115 return false;
12116 }
12117
12118 /**
12119 * When running from the network level admin and opted-in from the network,
12120 * check if the license exists in the network user licenses collection.
12121 *
12122 * @author Vova Feldman (@svovaf)
12123 * @since 2.0.0
12124 */
12125 if ( fs_is_network_admin() &&
12126 $this->is_network_registered() &&
12127 ( ! is_object( $this->_user ) || $this->_storage->network_user_id != $this->_user->id )
12128 ) {
12129 $licenses = $this->get_user_licenses( $this->_storage->network_user_id );
12130
12131 foreach ( $licenses as $license ) {
12132 if ( $id == $license->id ) {
12133 return $license;
12134 }
12135 }
12136 }
12137
12138 if ( ! $this->has_any_license() && $sync_licenses ) {
12139 $this->_sync_licenses( $id );
12140 }
12141
12142 if ( is_array( $this->_licenses ) ) {
12143 foreach ( $this->_licenses as $license ) {
12144 if ( $id == $license->id ) {
12145 return $license;
12146 }
12147 }
12148 }
12149
12150 return false;
12151 }
12152
12153 /**
12154 * Get license by ID. Unlike _get_license_by_id(), this method only checks the local storage and return any license, whether it's associated with the current context user/install or not.
12155 *
12156 * @author Vova Feldman (@svovaf)
12157 * @since 2.0.0
12158 *
12159 * @param number $id
12160 *
12161 * @return FS_Plugin_License
12162 */
12163 private function get_license_by_id( $id ) {
12164 $licenses = self::get_all_licenses( $this->_module_id );
12165
12166 if ( is_array( $licenses ) && ! empty( $licenses ) ) {
12167 foreach ( $licenses as $license ) {
12168 if ( $id == $license->id ) {
12169 return $license;
12170 }
12171 }
12172 }
12173
12174 return null;
12175 }
12176
12177 /**
12178 * Synchronize the site's context license by fetching the license form the API and updating the local data with it.
12179 *
12180 * @author Vova Feldman (@svovaf)
12181 * @since 2.0.0
12182 *
12183 * @return \FS_Plugin_License|mixed
12184 */
12185 private function sync_site_license() {
12186 $api = $this->get_api_user_scope();
12187
12188 $result = $api->get( "/licenses/{$this->_license->id}.json?license_key=" . urlencode( $this->_license->secret_key ), true );
12189
12190 if ( ! $this->is_api_result_entity( $result ) ) {
12191 return $result;
12192 }
12193
12194 $license = $this->_update_site_license( new FS_Plugin_License( $result ) );
12195 $this->_store_licenses();
12196
12197 return $license;
12198 }
12199
12200 /**
12201 * Get all user's available licenses for the current module.
12202 *
12203 * @author Vova Feldman (@svovaf)
12204 * @since 2.0.0
12205 *
12206 * @param number $user_id
12207 *
12208 * @return FS_Plugin_License[]
12209 */
12210 private function get_user_licenses( $user_id ) {
12211 $all_licenses = self::get_all_licenses( $this->_module_id );
12212 if ( empty( $all_licenses ) ) {
12213 return array();
12214 }
12215
12216 $user_license_ids = $this->get_user_linked_license_ids( $user_id );
12217 if ( empty( $user_license_ids ) ) {
12218 return array();
12219 }
12220
12221 $licenses = array();
12222 foreach ( $all_licenses as $license ) {
12223 if ( in_array( $license->id, $user_license_ids ) ) {
12224 $licenses[] = $license;
12225 }
12226 }
12227
12228 return $licenses;
12229 }
12230
12231 /**
12232 * Checks if the context license is network activated except on the given blog ID.
12233 *
12234 * @author Vova Feldman (@svovaf)
12235 * @since 2.0.0
12236 *
12237 * @param int $except_blog_id
12238 *
12239 * @return bool
12240 */
12241 private function is_license_network_active( $except_blog_id = 0 ) {
12242 $this->_logger->entrance();
12243
12244 if ( ! is_object( $this->_license ) ) {
12245 return false;
12246 }
12247
12248 $sites = self::get_sites();
12249
12250 if ( $this->_license->total_activations() < ( count( $sites ) - 1 ) ) {
12251 // There are more sites than the number of activations, so license cannot be network activated.
12252 return false;
12253 }
12254
12255 foreach ( $sites as $site ) {
12256 $blog_id = self::get_site_blog_id( $site );
12257
12258 if ( $except_blog_id == $blog_id ) {
12259 // Skip excluded blog.
12260 continue;
12261 }
12262
12263 $install = $this->get_install_by_blog_id( $blog_id );
12264
12265 if ( is_object( $install ) && $install->license_id != $this->_license->id ) {
12266 return false;
12267 }
12268 }
12269
12270 return true;
12271 }
12272
12273 /**
12274 * Checks if license can be activated on all the network sites (opted-in or skipped) that are not yet associated with a license. If possible, try to make the activation, if not return false.
12275 *
12276 * Notice: On success, this method will also update the license activations counters (without updating the license in the storage).
12277 *
12278 * @author Vova Feldman (@svovaf)
12279 * @since 2.0.0
12280 *
12281 * @param \FS_User $user
12282 * @param \FS_Plugin_License $license
12283 *
12284 * @return bool
12285 */
12286 private function try_activate_license_on_network( FS_User $user, FS_Plugin_License $license ) {
12287 $this->_logger->entrance();
12288
12289 $result = $this->can_activate_license_on_network( $license );
12290
12291 if ( false === $result ) {
12292 return false;
12293 }
12294
12295 $installs_without_license = $result['installs'];
12296 if ( ! empty( $installs_without_license ) ) {
12297 $this->activate_license_on_many_installs( $user, $license->secret_key, $installs_without_license );
12298 }
12299
12300 $disconnected_site_ids = $result['sites'];
12301 if ( ! empty( $disconnected_site_ids ) ) {
12302 $this->activate_license_on_many_sites( $user, $license->secret_key, $disconnected_site_ids );
12303 }
12304
12305 $this->link_license_2_user( $license->id, $user->id );
12306
12307 // Sync license after activations.
12308 $license->activated += $result['production_count'];
12309 $license->activated_local += $result['localhost_count'];
12310
12311 // $this->_store_licenses()
12312
12313 return true;
12314 }
12315
12316 /**
12317 * Checks if the given license can be activated on the whole network.
12318 *
12319 * @author Vova Feldman (@svovaf)
12320 * @since 2.0.0
12321 *
12322 * @param \FS_Plugin_License $license
12323 *
12324 * @return false|array {
12325 * @type array[int]FS_Site $installs Blog ID to install map.
12326 * @type int[] $sites Non-connected blog IDs.
12327 * @type int $production_count Production sites count.
12328 * @type int $localhost_count Production sites count.
12329 * }
12330 */
12331 private function can_activate_license_on_network( FS_Plugin_License $license ) {
12332 $sites = self::get_sites();
12333
12334 $production_count = 0;
12335 $localhost_count = 0;
12336
12337 $installs_without_license = array();
12338 $disconnected_site_ids = array();
12339
12340 foreach ( $sites as $site ) {
12341 $blog_id = self::get_site_blog_id( $site );
12342 $install = $this->get_install_by_blog_id( $blog_id );
12343
12344 if ( is_object( $install ) ) {
12345 if ( FS_Plugin_License::is_valid_id( $install->license_id ) ) {
12346 // License already activated on the install.
12347 continue;
12348 }
12349
12350 $url = $install->url;
12351
12352 $installs_without_license[ $blog_id ] = $install;
12353 } else {
12354 $url = is_object( $site ) ?
12355 $site->siteurl :
12356 self::get_unfiltered_site_url( $blog_id );
12357
12358 $disconnected_site_ids[] = $blog_id;
12359 }
12360
12361 if ( FS_Site::is_localhost_by_address( $url ) ) {
12362 $localhost_count ++;
12363 } else {
12364 $production_count ++;
12365 }
12366 }
12367
12368 if ( ! $license->can_activate_bulk( $production_count, $localhost_count ) ) {
12369 return false;
12370 }
12371
12372 return array(
12373 'installs' => $installs_without_license,
12374 'sites' => $disconnected_site_ids,
12375 'production_count' => $production_count,
12376 'localhost_count' => $localhost_count,
12377 );
12378 }
12379
12380 /**
12381 * Activate a given license on a collection of installs.
12382 *
12383 * @author Vova Feldman (@svovaf)
12384 * @since 2.0.0
12385 *
12386 * @param \FS_User $user
12387 * @param string $license_key
12388 * @param array $blog_2_install_map {
12389 * @key int Blog ID.
12390 * @value FS_Site Blog's associated install.
12391 * }
12392 *
12393 * @return mixed|true
12394 */
12395 private function activate_license_on_many_installs(
12396 FS_User $user,
12397 $license_key,
12398 array $blog_2_install_map
12399 ) {
12400 $params = array(
12401 array( 'license_key' => $this->apply_filters( 'license_key', $license_key ) )
12402 );
12403
12404 $install_2_blog_map = array();
12405 foreach ( $blog_2_install_map as $blog_id => $install ) {
12406 $params[] = array( 'id' => $install->id );
12407
12408 $install_2_blog_map[ $install->id ] = $blog_id;
12409 }
12410
12411 $result = $this->get_api_user_scope_by_user( $user )->call(
12412 "plugins/{$this->_plugin->id}/installs.json",
12413 'PUT',
12414 $params
12415 );
12416
12417 if ( ! $this->is_api_result_object( $result, 'installs' ) ) {
12418 return $result;
12419 }
12420
12421 foreach ( $result->installs as $r_install ) {
12422 $install = new FS_Site( $r_install );
12423 $install->is_disconnected = false;
12424
12425 // Update install.
12426 $this->_store_site(
12427 true,
12428 $install_2_blog_map[ $r_install->id ],
12429 $install
12430 );
12431 }
12432
12433 return true;
12434 }
12435
12436 /**
12437 * Activate a given license on a collection of blogs/sites that are not yet opted-in.
12438 *
12439 * @author Vova Feldman (@svovaf)
12440 * @since 2.3.1
12441 *
12442 * @param \FS_User $user
12443 * @param string $license_key
12444 *
12445 * @return true|mixed True if successful, otherwise, the API result.
12446 */
12447 private function activate_license_on_site( FS_User $user, $license_key ) {
12448 return $this->activate_license_on_many_sites( $user, $license_key );
12449 }
12450
12451 /**
12452 * Activate a given license on a collection of blogs/sites that are not yet opted-in.
12453 *
12454 * @author Vova Feldman (@svovaf)
12455 * @since 2.0.0
12456 *
12457 * @param \FS_User $user
12458 * @param string $license_key
12459 * @param int[] $site_ids
12460 *
12461 * @return true|mixed True if successful, otherwise, the API result.
12462 */
12463 private function activate_license_on_many_sites(
12464 FS_User $user,
12465 $license_key,
12466 array $site_ids = array()
12467 ) {
12468 $sites = array();
12469 foreach ( $site_ids as $site_id ) {
12470 $sites[] = $this->get_site_info( array( 'blog_id' => $site_id ) );
12471 }
12472
12473 // Install the plugin.
12474 $result = $this->create_installs_with_user(
12475 $user,
12476 $license_key,
12477 false,
12478 $sites,
12479 false,
12480 true
12481 );
12482
12483 if ( ! $this->is_api_result_entity( $result ) &&
12484 ! $this->is_api_result_object( $result, 'installs' )
12485 ) {
12486 return $result;
12487 }
12488
12489 $installs = array();
12490
12491 if ( $this->is_api_result_entity( $result ) ) {
12492 $install = new FS_Site( $result );
12493
12494 $this->_user = $user;
12495
12496 $this->_store_site( true, null, $install );
12497
12498 $this->_site = $install;
12499
12500 $this->reset_anonymous_mode();
12501 } else {
12502 foreach ( $result->installs as $install ) {
12503 $installs[] = new FS_Site( $install );
12504 }
12505
12506 // Map site addresses to their blog IDs.
12507 $address_to_blog_map = $this->get_address_to_blog_map();
12508
12509 $first_blog_id = null;
12510
12511 foreach ( $installs as $install ) {
12512 $address = trailingslashit( fs_strip_url_protocol( $install->url ) );
12513 $blog_id = $address_to_blog_map[ $address ];
12514
12515 $this->_store_site( true, $blog_id, $install );
12516
12517 $this->reset_anonymous_mode( $blog_id );
12518
12519 if ( is_null( $first_blog_id ) ) {
12520 $first_blog_id = $blog_id;
12521 }
12522 }
12523
12524 if ( ! FS_Site::is_valid_id( $this->_storage->network_install_blog_id ) ) {
12525 $this->_storage->network_install_blog_id = $first_blog_id;
12526 }
12527 }
12528
12529 return true;
12530 }
12531
12532 /**
12533 * Sync site's license with user licenses.
12534 *
12535 * @author Vova Feldman (@svovaf)
12536 * @since 1.0.6
12537 *
12538 * @param FS_Plugin_License|null $new_license
12539 *
12540 * @return FS_Plugin_License|null
12541 */
12542 function _update_site_license( $new_license ) {
12543 $this->_logger->entrance();
12544
12545 /**
12546 * In case this call will be removed in the future, the `_sync_licenses()` method needs to be updated
12547 * accordingly so that it will also handle the case when an ownership change is done via license
12548 * activation.
12549 *
12550 * @author Leo Fajardo (@leorw)
12551 * @since 2.3.2
12552 */
12553 $this->set_license( $new_license );
12554
12555 if ( ! is_object( $new_license ) ) {
12556 $this->_site->license_id = null;
12557 $this->_sync_site_subscription( null );
12558
12559 return $this->_license;
12560 }
12561
12562 $this->_site->license_id = $this->_license->id;
12563
12564 if ( ! is_array( $this->_licenses ) ) {
12565 $this->_licenses = array();
12566 }
12567
12568 $is_license_found = false;
12569 for ( $i = 0, $len = count( $this->_licenses ); $i < $len; $i ++ ) {
12570 if ( $new_license->id == $this->_licenses[ $i ]->id ) {
12571 $this->_licenses[ $i ] = $new_license;
12572
12573 $is_license_found = true;
12574 break;
12575 }
12576 }
12577
12578 // If new license just append.
12579 if ( ! $is_license_found ) {
12580 $this->_licenses[] = $new_license;
12581 }
12582
12583 $this->_sync_site_subscription( $new_license );
12584
12585 return $this->_license;
12586 }
12587
12588 /**
12589 * @author Vova Feldman (@svovaf)
12590 * @since 2.3.1
12591 *
12592 * @param \FS_Plugin_License $license
12593 */
12594 private function set_license( FS_Plugin_License $license = null ) {
12595 $this->_license = $license;
12596
12597 $this->maybe_update_whitelabel_flag( $license );
12598 }
12599
12600 /**
12601 * @author Leo Fajardo (@leorw)
12602 * @since 2.3.1
12603 *
12604 * @param FS_Plugin_License $license
12605 */
12606 private function maybe_update_whitelabel_flag( $license ) {
12607 $is_whitelabeled = isset( $this->_storage->is_whitelabeled ) ?
12608 $this->_storage->is_whitelabeled :
12609 false;
12610
12611 if ( is_object( $license ) ) {
12612 $license_user = self::_get_user_by_id( $license->user_id );
12613
12614 if ( ! is_object( $license_user ) ) {
12615 // If foreign license, do not update the `is_whitelabeled` flag.
12616 return;
12617 }
12618
12619 if ( $this->is_addon() ) {
12620 /**
12621 * Store the last license data to the parent's storage since it's needed only when showing the
12622 * "Start Debug" dialog which is triggered from the "Account" page. This way, there's no need to
12623 * iterate over the add-ons just to get the last license data.
12624 */
12625 $this->get_parent_instance()->store_last_activated_license_data( $license, $license_user );
12626 } else {
12627 $this->store_last_activated_license_data( $license );
12628 }
12629
12630 if ( $license->is_whitelabeled ) {
12631 // Activated a developer license, data should be hidden.
12632 $is_whitelabeled = true;
12633 } else if ( $this->is_registered() && $this->_user->id == $license->user_id ) {
12634 // The account owner activated a regular license key, no need to hide the data.
12635 $is_whitelabeled = false;
12636 }
12637 }
12638
12639 $this->_storage->is_whitelabeled = $is_whitelabeled;
12640
12641 // Reset the whitelabeled status after update.
12642 $this->is_whitelabeled = null;
12643 if ( $this->is_addon() ) {
12644 $parent_fs = $this->get_parent_instance();
12645
12646 if ( is_object( $parent_fs ) ) {
12647 $parent_fs->is_whitelabeled = null;
12648 }
12649 }
12650 }
12651
12652 /**
12653 * @author Leo Fajardo (@leorw)
12654 * @since 2.3.1
12655 *
12656 * @param FS_Plugin_License $license
12657 * @param FS_User $license_user
12658 */
12659 private function store_last_activated_license_data( FS_Plugin_License $license, $license_user = null ) {
12660 if ( ! is_object( $license_user ) ) {
12661 $this->_storage->last_license_key = md5( $license->secret_key );
12662 $this->_storage->last_license_user_id = null;
12663 } else {
12664 $this->_storage->last_license_user_key = md5( $license_user->secret_key );
12665 $this->_storage->last_license_user_id = $license_user->id;
12666 }
12667 }
12668
12669 /**
12670 * @author Leo Fajardo (@leorw)
12671 * @since 2.3.1
12672 *
12673 * @param bool $ignore_data_debug_mode
12674 *
12675 * @return bool
12676 */
12677 function is_whitelabeled_by_flag( $ignore_data_debug_mode = false ) {
12678 if ( true !== $this->_storage->is_whitelabeled ) {
12679 return false;
12680 } else if ( $ignore_data_debug_mode ) {
12681 return true;
12682 }
12683
12684 $fs = $this->is_addon() ?
12685 $this->get_parent_instance() :
12686 $this;
12687
12688 return ! $fs->is_data_debug_mode();
12689 }
12690
12691 /**
12692 * @author Leo Fajardo (@leorw)
12693 * @since 2.3.1
12694 *
12695 * @return number
12696 */
12697 function get_last_license_user_id() {
12698 return ( FS_User::is_valid_id( $this->_storage->last_license_user_id ) ) ?
12699 $this->_storage->last_license_user_id :
12700 null;
12701 }
12702
12703 /**
12704 * @author Leo Fajardo (@leorw)
12705 * @since 2.3.1
12706 *
12707 * @param int $blog_id
12708 * @param bool $ignore_data_debug_mode
12709 *
12710 * @return bool
12711 */
12712 function is_whitelabeled( $ignore_data_debug_mode = false, $blog_id = null ) {
12713 if ( ! is_null( $blog_id ) ) {
12714 $this->switch_to_blog( $blog_id );
12715 }
12716
12717 if ( ! is_null( $this->is_whitelabeled ) ) {
12718 $is_whitelabeled = $this->is_whitelabeled;
12719 } else {
12720 $is_whitelabeled = false;
12721
12722 $is_whitelabeled_flag = $this->is_whitelabeled_by_flag( true );
12723
12724 if ( ! $this->has_addons() ) {
12725 $is_whitelabeled = $is_whitelabeled_flag;
12726 } else if ( $is_whitelabeled_flag ) {
12727 $is_whitelabeled = true;
12728 } else {
12729 if ( $this->is_registered() || $this->is_premium() ) {
12730 $addon_ids = $this->get_updated_account_addons();
12731 } else {
12732 $addons = self::get_all_addons();
12733
12734 $plugin_addons = isset( $addons[ $this->_plugin->id ] ) ?
12735 $addons[ $this->_plugin->id ] :
12736 array();
12737
12738 $addon_ids = array();
12739 foreach ( $plugin_addons as $addon ) {
12740 $addon_ids[] = $addon->id;
12741 }
12742 }
12743
12744 $installed_addons = $this->get_installed_addons();
12745 foreach ( $installed_addons as $fs_addon ) {
12746 $addon_ids[] = $fs_addon->get_id();
12747 }
12748
12749 if ( ! empty( $addon_ids ) ) {
12750 $addon_ids = array_unique( $addon_ids );
12751
12752 $is_network_level = (
12753 fs_is_network_admin() &&
12754 $this->is_network_active()
12755 );
12756
12757 foreach ( $addon_ids as $addon_id ) {
12758 $addon = $this->get_addon( $addon_id );
12759
12760 if ( ! is_object( $addon ) ) {
12761 continue;
12762 }
12763
12764 $addon_storage = FS_Storage::instance( WP_FS__MODULE_TYPE_PLUGIN, $addon->slug );
12765 $fs_addon = $this->is_addon_activated( $addon_id ) ?
12766 self::get_addon_instance( $addon_id ) :
12767 null;
12768
12769 $was_addon_network_activated = false;
12770
12771 if ( is_object( $fs_addon ) ) {
12772 $was_addon_network_activated = $fs_addon->is_network_active();
12773 } else if ( $is_network_level ) {
12774 $was_addon_network_activated = $addon_storage->get( 'was_plugin_loaded', false, true );
12775 }
12776
12777 $network_delegated_connection = (
12778 $was_addon_network_activated &&
12779 $addon_storage->get( 'is_delegated_connection', false, true )
12780 );
12781
12782 if (
12783 $is_network_level &&
12784 ( ! $was_addon_network_activated || $network_delegated_connection )
12785 ) {
12786 $sites = self::get_sites();
12787
12788 /**
12789 * If in network admin area and the add-on was not network-activated or network-activated
12790 * and network-delegated, find any add-on whose is_whitelabeled flag is true.
12791 */
12792 foreach ( $sites as $site ) {
12793 $site_info = $this->get_site_info( $site );
12794
12795 if ( $addon_storage->get( 'is_whitelabeled', false, $site_info['blog_id'] ) ) {
12796 $is_whitelabeled = true;
12797 break;
12798 }
12799 }
12800
12801 if ( $is_whitelabeled ) {
12802 break;
12803 }
12804 } else {
12805 /**
12806 * This will be executed when any of the following is met:
12807 * 1. Add-on was network-activated, not network-delegated, and in network admin area.
12808 * 2. Add-on was network-activated, network-delegated, and in site admin area.
12809 * 3. Add-on was not network-activated and in site admin area.
12810 */
12811 if ( true === $addon_storage->is_whitelabeled ) {
12812 $is_whitelabeled = true;
12813 break;
12814 }
12815 }
12816 }
12817 }
12818 }
12819
12820 $this->is_whitelabeled = $is_whitelabeled;
12821
12822 if ( ! $is_whitelabeled || ! $this->is_data_debug_mode() ) {
12823 $this->_admin_notices->remove_sticky( 'data_debug_mode_enabled' );
12824 }
12825
12826 if ( ! is_null( $blog_id ) ) {
12827 $this->restore_current_blog();
12828 }
12829 }
12830
12831 return (
12832 $is_whitelabeled &&
12833 ( $ignore_data_debug_mode || ! $this->is_data_debug_mode() )
12834 );
12835 }
12836
12837 /**
12838 * Sync site's subscription.
12839 *
12840 * @author Vova Feldman (@svovaf)
12841 * @since 1.0.9
12842 *
12843 * @param FS_Plugin_License|null $license
12844 *
12845 * @return bool|\FS_Subscription
12846 */
12847 private function _sync_site_subscription( $license ) {
12848 if ( ! is_object( $license ) ) {
12849 $this->delete_unused_subscriptions();
12850
12851 return false;
12852 }
12853
12854 // Load subscription details if not lifetime.
12855 $subscription = $license->is_lifetime() ?
12856 false :
12857 $this->_fetch_site_license_subscription();
12858
12859 if ( is_object( $subscription ) && ! isset( $subscription->error ) ) {
12860 $this->store_subscription( $subscription );
12861 } else {
12862 $this->delete_unused_subscriptions();
12863 }
12864
12865 return $subscription;
12866 }
12867
12868 /**
12869 * @author Vova Feldman (@svovaf)
12870 * @since 1.0.6
12871 *
12872 * @return bool|\FS_Plugin_License
12873 */
12874 function _get_license() {
12875 if ( ! fs_is_network_admin() || is_object( $this->_license ) ) {
12876 return $this->_license;
12877 }
12878
12879 return $this->_get_available_premium_license();
12880 }
12881
12882 /**
12883 * @param number $license_id
12884 *
12885 * @return null|\FS_Subscription
12886 */
12887 function _get_subscription( $license_id ) {
12888 if ( ! isset( $this->_storage->subscriptions ) ||
12889 empty( $this->_storage->subscriptions )
12890 ) {
12891 return null;
12892 }
12893
12894 foreach ( fs_get_entities( $this->_storage->subscriptions, FS_Subscription::get_class_name() ) as $subscription ) {
12895 if ( $subscription->license_id == $license_id ) {
12896 return $subscription;
12897 }
12898 }
12899
12900 return null;
12901 }
12902
12903 /**
12904 * @author Leo Fajardo (@leorw)
12905 * @since 2.0.0
12906 *
12907 * @param FS_Subscription $subscription
12908 */
12909 function store_subscription( FS_Subscription $subscription ) {
12910 if ( ! isset( $this->_storage->subscriptions ) ) {
12911 $this->_storage->subscriptions = array();
12912 }
12913
12914 if ( empty( $this->_storage->subscriptions ) || ! is_multisite() ) {
12915 $this->_storage->subscriptions = array( $subscription );
12916
12917 return;
12918 }
12919
12920 $subscriptions = fs_get_entities( $this->_storage->subscriptions, FS_Subscription::get_class_name() );
12921
12922 $updated_subscription = false;
12923 foreach ( $subscriptions as $key => $existing_subscription ) {
12924 if ( $existing_subscription->id == $subscription->id ) {
12925 $subscriptions[ $key ] = $subscription;
12926 $updated_subscription = true;
12927 break;
12928 }
12929 }
12930
12931 if ( ! $updated_subscription ) {
12932 $subscriptions[] = $subscription;
12933 }
12934
12935 $this->_storage->subscriptions = $subscriptions;
12936 }
12937
12938 /**
12939 * @author Leo Fajardo (@leorw)
12940 * @since 2.0.0
12941 */
12942 function delete_unused_subscriptions() {
12943 if ( ! isset( $this->_storage->subscriptions ) ||
12944 empty( $this->_storage->subscriptions ) ||
12945 // Clean up only if there are already at least 3 subscriptions.
12946 ( count( $this->_storage->subscriptions ) < 3 )
12947 ) {
12948 return;
12949 }
12950
12951 if ( ! is_multisite() ) {
12952 // If not multisite, there should only be 1 subscription, so just clear the array.
12953 $this->_storage->subscriptions = array();
12954
12955 return;
12956 }
12957
12958 $subscriptions_to_keep_by_license_id_map = array();
12959 $sites = self::get_sites();
12960 foreach ( $sites as $site ) {
12961 $blog_id = self::get_site_blog_id( $site );
12962 $install = $this->get_install_by_blog_id( $blog_id );
12963
12964 if ( ! is_object( $install ) ||
12965 ! FS_Plugin_License::is_valid_id( $install->license_id )
12966 ) {
12967 continue;
12968 }
12969
12970 $subscriptions_to_keep_by_license_id_map[ $install->license_id ] = true;
12971 }
12972
12973 if ( empty( $subscriptions_to_keep_by_license_id_map ) ) {
12974 $this->_storage->subscriptions = array();
12975
12976 return;
12977 }
12978
12979 foreach ( $this->_storage->subscriptions as $key => $subscription ) {
12980 if ( ! isset( $subscriptions_to_keep_by_license_id_map[ $subscription->license_id ] ) ) {
12981 unset( $this->_storage->subscriptions[ $key ] );
12982 }
12983 }
12984 }
12985
12986 /**
12987 * @author Vova Feldman (@svovaf)
12988 * @since 1.0.2
12989 *
12990 * @param string $plan Plan name
12991 * @param bool $exact If true, looks for exact plan. If false, also check "higher" plans.
12992 *
12993 * @return bool
12994 */
12995 function is_plan( $plan, $exact = false ) {
12996 $this->_logger->entrance();
12997
12998 if ( ! $this->is_registered() ) {
12999 return false;
13000 }
13001
13002 $plan = strtolower( $plan );
13003
13004 $current_plan_name = $this->get_plan_name();
13005
13006 if ( $current_plan_name === $plan ) {
13007 // Exact plan.
13008 return true;
13009 } else if ( $exact ) {
13010 // Required exact, but plans are different.
13011 return false;
13012 }
13013
13014 $current_plan_order = - 1;
13015 $required_plan_order = PHP_INT_MAX;
13016 for ( $i = 0, $len = count( $this->_plans ); $i < $len; $i ++ ) {
13017 if ( $plan === $this->_plans[ $i ]->name ) {
13018 $required_plan_order = $i;
13019 } else if ( $current_plan_name === $this->_plans[ $i ]->name ) {
13020 $current_plan_order = $i;
13021 }
13022 }
13023
13024 return ( $current_plan_order > $required_plan_order );
13025 }
13026
13027 /**
13028 * Check if module has only one plan.
13029 *
13030 * @author Vova Feldman (@svovaf)
13031 * @since 1.2.1.7
13032 *
13033 * @param bool $double_check In some cases developers prefer to release their paid offering as premium-only, even though there is a free version. For those cases, looking at the 'is_premium_only' value isn't enough because the result will return false even when the product has only signle paid plan.
13034 *
13035 * @return bool
13036 */
13037 function is_single_plan( $double_check = false ) {
13038 $this->_logger->entrance();
13039
13040 if ( ! $this->is_registered() ||
13041 ! is_array( $this->_plans ) ||
13042 0 === count( $this->_plans )
13043 ) {
13044 return true;
13045 }
13046
13047 $has_free_plan = $this->has_free_plan();
13048
13049 if ( ! $has_free_plan && $double_check ) {
13050 foreach ( $this->_plans as $plan ) {
13051 if ( $plan->is_free() ) {
13052 $has_free_plan = true;
13053 break;
13054 }
13055 }
13056 }
13057
13058 return ( 1 === ( count( $this->_plans ) - ( $has_free_plan ? 1 : 0 ) ) );
13059 }
13060
13061 /**
13062 * Check if plan based on trial. If not in trial mode, should return false.
13063 *
13064 * @since 1.0.9
13065 *
13066 * @param string $plan Plan name
13067 * @param bool $exact If true, looks for exact plan. If false, also check "higher" plans.
13068 *
13069 * @return bool
13070 */
13071 function is_trial_plan( $plan, $exact = false ) {
13072 $this->_logger->entrance();
13073
13074 if ( ! $this->is_registered() ) {
13075 return false;
13076 }
13077
13078 if ( ! $this->is_trial() ) {
13079 return false;
13080 }
13081
13082 $trial_plan = $this->get_trial_plan();
13083
13084 if ( $trial_plan->name === $plan ) {
13085 // Exact plan.
13086 return true;
13087 } else if ( $exact ) {
13088 // Required exact, but plans are different.
13089 return false;
13090 }
13091
13092 $current_plan_order = - 1;
13093 $required_plan_order = - 1;
13094 for ( $i = 0, $len = count( $this->_plans ); $i < $len; $i ++ ) {
13095 if ( $plan === $this->_plans[ $i ]->name ) {
13096 $required_plan_order = $i;
13097 } else if ( $trial_plan->name === $this->_plans[ $i ]->name ) {
13098 $current_plan_order = $i;
13099 }
13100 }
13101
13102 return ( $current_plan_order > $required_plan_order );
13103 }
13104
13105 /**
13106 * Check if plugin has any paid plans.
13107 *
13108 * @author Vova Feldman (@svovaf)
13109 * @since 1.0.7
13110 *
13111 * @return bool
13112 */
13113 function has_paid_plan() {
13114 return $this->_has_paid_plans ||
13115 FS_Plan_Manager::instance()->has_paid_plan( $this->_plans );
13116 }
13117
13118 /**
13119 * Check if plugin has any plan with a trail.
13120 *
13121 * @author Vova Feldman (@svovaf)
13122 * @since 1.0.9
13123 *
13124 * @return bool
13125 */
13126 function has_trial_plan() {
13127 /**
13128 * @author Vova Feldman(@svovaf)
13129 * @since 1.2.1.5
13130 *
13131 * Allow setting a trial from the SDK without calling the API.
13132 * But, if the user did opt-in, continue using the real data from the API.
13133 */
13134 if ( $this->_trial_days >= 0 ) {
13135 return true;
13136 }
13137
13138 return $this->_storage->get( 'has_trial_plan', false );
13139 }
13140
13141 /**
13142 * Check if plugin has any free plan, or is it premium only.
13143 *
13144 * Note: If no plans configured, assume plugin is free.
13145 *
13146 * @author Vova Feldman (@svovaf)
13147 * @since 1.0.7
13148 *
13149 * @return bool
13150 */
13151 function has_free_plan() {
13152 return ! $this->is_only_premium();
13153 }
13154
13155 /**
13156 * Displays a license activation dialog box when the user clicks on the "Activate License"
13157 * or "Change License" link on the plugins
13158 * page.
13159 *
13160 * @author Leo Fajardo (@leorw)
13161 * @since 1.1.9
13162 */
13163 function _add_license_activation_dialog_box() {
13164 $vars = array(
13165 'id' => $this->_module_id,
13166 );
13167
13168 fs_require_template( 'forms/license-activation.php', $vars );
13169 fs_require_template( 'forms/resend-key.php', $vars );
13170 }
13171
13172 /**
13173 * Displays an email address update dialog box when the user clicks on the email address "Edit" button on the "Account" page.
13174 *
13175 * @author Leo Fajardo (@leorw)
13176 * @since 2.5.0
13177 */
13178 function _add_email_address_update_dialog_box() {
13179 $vars = array( 'id' => $this->_module_id );
13180
13181 fs_require_template( 'forms/email-address-update.php', $vars );
13182 }
13183
13184 /**
13185 * @author Leo Fajardo (@leorw)
13186 * @since 2.5.0
13187 */
13188 function _add_email_address_update_option() {
13189 if ( ! $this->should_handle_user_change() ) {
13190 return;
13191 }
13192
13193 // Add email address update AJAX handler.
13194 $this->add_ajax_action( 'update_email_address', array( &$this, '_email_address_update_ajax_handler' ) );
13195 }
13196
13197 /**
13198 * @author Leo Fajardo (@leorw)
13199 * @since 2.5.0
13200 */
13201 function _email_address_update_ajax_handler() {
13202 $this->check_ajax_referer( 'update_email_address' );
13203
13204 $new_email_address = fs_request_get( 'email_address' );
13205 $transfer_type = fs_request_get( 'transfer_type' );
13206
13207 $result = $this->update_email( $new_email_address );
13208
13209 if ( ! FS_Api::is_api_error( $result ) ) {
13210 self::shoot_ajax_success();
13211 }
13212
13213 $error = '';
13214
13215 if ( FS_Api::is_api_error_object( $result ) ) {
13216 switch ( $result->error->code ) {
13217 case 'user_exist':
13218 case 'account_verification_required':
13219 $error = array(
13220 'code' => 'change_ownership',
13221 'url' => $this->get_account_url( 'change_owner', array(
13222 'state' => 'init',
13223 'candidate_email' => $new_email_address,
13224 'transfer_type' => $transfer_type,
13225 ) ),
13226 );
13227
13228 break;
13229 }
13230 }
13231
13232 if ( empty( $error ) ) {
13233 $error = is_object( $result ) ?
13234 var_export( $result->error, true ) :
13235 $result;
13236 }
13237
13238 self::shoot_ajax_failure( $error );
13239 }
13240
13241 /**
13242 * Returns a collection of IDs of installs that are associated with the context product and its add-ons, and activated with foreign licenses.
13243 *
13244 * @author Leo Fajardo (@leorw)
13245 * @since 2.3.2
13246 *
13247 * @return number[]
13248 */
13249 function get_installs_ids_with_foreign_licenses() {
13250 $installs = array();
13251
13252 if (
13253 is_object( $this->_license ) &&
13254 $this->_site->user_id != $this->_license->user_id
13255 ) {
13256 $installs[] = $this->_site->id;
13257 }
13258
13259 /**
13260 * Also try to get foreign licenses for the context product's add-ons.
13261 */
13262 $installs_by_slug_map = $this->get_parent_and_addons_installs_info();
13263
13264 foreach ( $installs_by_slug_map as $slug => $install_info ) {
13265 if ( $slug == $this->get_slug() ) {
13266 continue;
13267 }
13268
13269 $install = $install_info['install'];
13270 $license = $install_info['license'];
13271
13272 if (
13273 is_object( $license ) &&
13274 $install->user_id != $license->user_id
13275 ) {
13276 $installs[] = $install->id;
13277 }
13278 }
13279
13280 return $installs;
13281 }
13282
13283 /**
13284 * Displays the "Change User" dialog box when the user clicks on the "Change User" button on the "Account" page.
13285 *
13286 * @author Leo Fajardo (@leorw)
13287 * @since 2.3.2
13288 *
13289 * @param number[] $install_ids
13290 */
13291 function _add_user_change_dialog_box( $install_ids ) {
13292 $vars = array(
13293 'id' => $this->_module_id,
13294 'license_owners' => $this->fetch_installs_licenses_owners_data( $install_ids )
13295 );
13296
13297 fs_require_template( 'forms/user-change.php', $vars );
13298 }
13299
13300 /**
13301 * @author Leo Fajardo (@leorw)
13302 * @since 2.3.1
13303 */
13304 function _add_data_debug_mode_dialog_box() {
13305 $vars = array(
13306 'id' => $this->_module_id,
13307 );
13308
13309 fs_require_template( 'forms/data-debug-mode.php', $vars );
13310 }
13311
13312 /**
13313 * Displays a subscription cancellation dialog box when the user clicks on the "Deactivate License"
13314 * link on the "Account" page or deactivates a plugin and there's an active subscription that is
13315 * either associated with a non-lifetime single-site license or non-lifetime multisite license that
13316 * is only activated on a single production site.
13317 *
13318 * @author Leo Fajardo (@leorw)
13319 * @since 2.2.1
13320 *
13321 * @param bool $is_license_deactivation
13322 *
13323 * @return array
13324 */
13325 function _get_subscription_cancellation_dialog_box_template_params( $is_license_deactivation = false ) {
13326 if ( fs_is_network_admin() ) {
13327 // Subscription cancellation dialog box is currently not supported for multisite networks.
13328 return array();
13329 }
13330
13331 if ( $this->is_whitelabeled() ) {
13332 return array();
13333 }
13334
13335 $license = $this->_get_license();
13336
13337 /**
13338 * If the installation is associated with a non-lifetime license, which is either a single-site or only activated on a single production site (or zero), and connected to an active subscription, suggest the customer to cancel the subscription upon deactivation.
13339 *
13340 * @author Leo Fajardo (@leorw) (Comment added by Vova Feldman @svovaf)
13341 * @since 2.2.1
13342 */
13343 if ( ! is_object( $license ) ||
13344 $license->is_lifetime() ||
13345 ( ! $license->is_single_site() && $license->activated > 1 )
13346 ) {
13347 return array();
13348 }
13349
13350 /**
13351 * @var FS_Subscription $subscription
13352 */
13353 $subscription = $this->_get_subscription( $license->id );
13354 if ( ! is_object( $subscription ) || ! $subscription->is_active() ) {
13355 return array();
13356 }
13357
13358 return array(
13359 'id' => $this->_module_id,
13360 'license' => $license,
13361 'has_trial' => $this->is_paid_trial(),
13362 'is_license_deactivation' => $is_license_deactivation,
13363 );
13364 }
13365
13366 /**
13367 * @author Leo Fajardo (@leorw)
13368 * @since 2.0.2
13369 */
13370 function _add_premium_version_upgrade_selection_dialog_box() {
13371 $modules_update = get_site_transient( $this->is_theme() ? 'update_themes' : 'update_plugins' );
13372 if ( ! isset( $modules_update->response[ $this->_plugin_basename ] ) ) {
13373 return;
13374 }
13375
13376 $vars = array(
13377 'id' => $this->_module_id,
13378 'new_version' => is_object( $modules_update->response[ $this->_plugin_basename ] ) ?
13379 $modules_update->response[ $this->_plugin_basename ]->new_version :
13380 $modules_update->response[ $this->_plugin_basename ]['new_version']
13381 );
13382
13383 fs_require_template( 'forms/premium-versions-upgrade-metadata.php', $vars );
13384 fs_require_once_template( 'forms/premium-versions-upgrade-handler.php', $vars );
13385 }
13386
13387 /**
13388 * Displays the opt-out dialog box when the user clicks on the "Opt Out" link on the "Plugins"
13389 * page.
13390 *
13391 * @author Leo Fajardo (@leorw)
13392 * @since 1.2.1.5
13393 */
13394 function _add_optout_dialog() {
13395 if ( $this->is_theme() ) {
13396 $vars = null;
13397 fs_require_once_template( '/js/jquery.content-change.php', $vars );
13398 }
13399
13400 $vars = array( 'id' => $this->_module_id );
13401 fs_require_template( 'forms/optout.php', $vars );
13402 }
13403
13404 /**
13405 * Prepare page to include all required UI and logic for the license activation dialog.
13406 *
13407 * @author Vova Feldman (@svovaf)
13408 * @since 1.2.0
13409 */
13410 function _add_license_activation() {
13411 if ( $this->is_migration() ) {
13412 return;
13413 }
13414
13415 if ( ! $this->is_user_admin() ) {
13416 // Only admins can activate a license.
13417 return;
13418 }
13419
13420 if ( ! $this->has_paid_plan() ) {
13421 // Module doesn't have any paid plans.
13422 return;
13423 }
13424
13425 if (
13426 $this->has_premium_version() &&
13427 ! $this->is_premium() &&
13428 /**
13429 * Also handle the case when an upgrade was made using the free version.
13430 *
13431 * @author Leo Fajardo (@leorw)
13432 * @since 2.3.2
13433 */
13434 ! is_object( $this->_get_license() )
13435 ) {
13436 // Only add license activation logic to the premium version, or in case of a serviceware plugin, also in the free version.
13437 return;
13438 }
13439
13440 // Add license activation link and AJAX request handler.
13441 if ( self::is_plugins_page() ) {
13442 $is_network_admin = fs_is_network_admin();
13443
13444 if (
13445 ( $is_network_admin && $this->is_network_active() && ! $this->is_network_delegated_connection() ) ||
13446 ( ! $is_network_admin && ( ! $this->is_network_active() || $this->is_delegated_connection() ) )
13447 ) {
13448 if (
13449 $this->is_premium() ||
13450 ( $this->has_paid_plan() && ! $this->has_premium_version() )
13451 ) {
13452 /**
13453 * @since 1.2.0 Add license action link only on plugins page.
13454 */
13455 $this->_add_license_action_link();
13456 }
13457 }
13458 }
13459
13460 // Add license activation AJAX callback.
13461 $this->add_ajax_action( 'activate_license', array( &$this, '_activate_license_ajax_action' ) );
13462
13463 // Add resend license AJAX callback.
13464 $this->add_ajax_action( 'resend_license_key', array( &$this, '_resend_license_key_ajax_action' ) );
13465 }
13466
13467 /**
13468 * Prepares page to include all required UI and logic for the "Change User" dialog.
13469 *
13470 * @author Leo Fajardo (@leorw)
13471 * @since 2.3.2
13472 */
13473 function _add_user_change_option() {
13474 if ( ! $this->should_handle_user_change() ) {
13475 return;
13476 }
13477
13478 $installs_ids_with_foreign_licenses = $this->get_installs_ids_with_foreign_licenses();
13479
13480 if ( empty( $installs_ids_with_foreign_licenses ) ) {
13481 // Handle user change only when the parent product or one of its add-ons is activated with a foreign license.
13482 return;
13483 }
13484
13485 // Add user change AJAX handler.
13486 $this->add_ajax_action( 'change_user', array( &$this, '_user_change_ajax_action' ) );
13487 }
13488
13489 /**
13490 * @author Leo Fajardo (@leorw)
13491 * @since 2.3.2
13492 */
13493 function should_handle_user_change() {
13494 if ( ! $this->is_user_admin() ) {
13495 // Only admins can change user.
13496 return false;
13497 }
13498
13499 if ( $this->is_addon() ) {
13500 return false;
13501 }
13502
13503 if ( ! $this->is_registered() ) {
13504 return false;
13505 }
13506
13507 if (
13508 $this->is_network_active() &&
13509 ( fs_is_network_admin() || ! $this->is_site_delegated_connection() )
13510 ) {
13511 // Handle only on site-level "Account" section for now.
13512 return false;
13513 }
13514
13515 return true;
13516 }
13517
13518 /**
13519 * @author Leo Fajardo (@leorw)
13520 * @since 2.0.2
13521 */
13522 function _add_premium_version_upgrade_selection() {
13523 if ( ! $this->is_user_admin() ) {
13524 return;
13525 }
13526
13527 if ( ! $this->is_premium() || $this->has_any_active_valid_license() ) {
13528 // This is relevant only to the free versions and premium versions without an active license.
13529 return;
13530 }
13531
13532 if ( self::is_updates_page() || ( $this->is_plugin() && self::is_plugins_page() ) ) {
13533 $this->_add_premium_version_upgrade_selection_action();
13534 }
13535 }
13536
13537 /**
13538 * @author Edgar Melkonyan
13539 * @since 2.4.1
13540 *
13541 * @throws Freemius_Exception
13542 */
13543 function _toggle_whitelabel_mode_ajax_handler() {
13544 $this->_logger->entrance();
13545
13546 $this->check_ajax_referer( 'toggle_whitelabel_mode' );
13547
13548 if ( ! $this->is_user_admin() ) {
13549 // Only for admins.
13550 self::shoot_ajax_failure();
13551 }
13552
13553 $license = $this->get_api_user_scope()->call(
13554 "/licenses/{$this->_site->license_id}.json",
13555 'put',
13556 array( 'is_whitelabeled' => ! $this->_license->is_whitelabeled )
13557 );
13558
13559 if ( ! $this->is_api_result_entity( $license ) ) {
13560 self::shoot_ajax_failure(
13561 FS_Api::is_api_error_object( $license ) ?
13562 $license->error->message :
13563 fs_text_inline( "An unknown error has occurred while trying to toggle the license's white-label mode.", 'unknown-error-occurred', $this->get_slug() )
13564 );
13565 }
13566
13567 $this->_license->is_whitelabeled = $license->is_whitelabeled;
13568 $this->_store_licenses();
13569
13570 $this->_sync_license();
13571
13572 if ( ! $license->is_whitelabeled ) {
13573 $this->_admin_notices->remove_sticky( 'license_whitelabeled' );
13574 } else {
13575 $this->_admin_notices->add_sticky(
13576 sprintf(
13577 $this->get_text_inline(
13578 'Your %s license was flagged as white-labeled to hide sensitive information from the WP Admin (e.g. your email, license key, prices, billing address & invoices). If you ever wish to revert it back, you can easily do it through your %s. If this was a mistake you can also %s.',
13579 'license_whitelabeled'
13580 ),
13581 "<strong>{$this->get_plugin_title()}</strong>",
13582 sprintf( '<a href="https://users.freemius.com" target="_blank">%s</a>', $this->get_text_inline( 'User Dashboard', 'user-dashboard' ) ),
13583 sprintf( '<a href="#" class="fs-toggle-whitelabel-mode">%s</a>', $this->get_text_inline( 'revert it now', 'revert-it-now' ) )
13584 ),
13585 'license_whitelabeled'
13586 );
13587 }
13588
13589 self::shoot_ajax_response( array( 'success' => true ) );
13590 }
13591
13592 /**
13593 * @author Leo Fajardo (@leorw)
13594 * @since 2.3.0
13595 */
13596 function _add_beta_mode_update_handler() {
13597 if ( ! $this->is_user_admin() ) {
13598 return;
13599 }
13600
13601 if ( ! $this->is_premium() ) {
13602 return;
13603 }
13604
13605 $this->add_ajax_action( 'set_beta_mode', array( &$this, '_set_beta_mode_ajax_handler' ) );
13606 }
13607
13608 /**
13609 * @author Leo Fajardo (@leorw)
13610 * @since 2.3.0
13611 */
13612 function _set_beta_mode_ajax_handler() {
13613 $this->_logger->entrance();
13614
13615 $this->check_ajax_referer( 'set_beta_mode' );
13616
13617 if ( ! $this->is_user_admin() ) {
13618 // Only for admins.
13619 self::shoot_ajax_failure();
13620 }
13621
13622 $is_beta = trim( fs_request_get( 'is_beta', '', 'post' ) );
13623
13624 if ( empty( $is_beta ) || ! in_array( $is_beta, array( 'true', 'false' ) ) ) {
13625 self::shoot_ajax_failure();
13626 }
13627
13628 $site = $this->api_site_call(
13629 '',
13630 'put',
13631 array(
13632 'is_beta' => ( 'true' == $is_beta ),
13633 'fields' => 'is_beta'
13634 )
13635 );
13636
13637 if ( ! $this->is_api_result_entity( $site ) ) {
13638 self::shoot_ajax_failure(
13639 FS_Api::is_api_error_object( $site ) ?
13640 $site->error->message :
13641 fs_text_inline( "An unknown error has occurred while trying to set the user's beta mode.", 'unknown-error-occurred', $this->get_slug() )
13642 );
13643 }
13644
13645 $this->_site->is_beta = $site->is_beta;
13646 $this->_store_site();
13647
13648 self::shoot_ajax_response( array( 'success' => true ) );
13649 }
13650
13651 /**
13652 * License activation WP AJAX handler.
13653 *
13654 * @author Leo Fajardo (@leorw)
13655 * @since 1.1.9
13656 *
13657 * @uses Freemius::activate_license()
13658 */
13659 function _activate_license_ajax_action() {
13660 $this->_logger->entrance();
13661
13662 $this->check_ajax_referer( 'activate_license' );
13663
13664 $license_key = trim( fs_request_get( 'license_key' ) );
13665
13666 if ( empty( $license_key ) ) {
13667 exit;
13668 }
13669
13670 $sites = fs_is_network_admin() ?
13671 fs_request_get( 'sites', array(), 'post' ) :
13672 array();
13673
13674 $result = $this->activate_license(
13675 $license_key,
13676 $sites,
13677 fs_request_get_bool( 'is_marketing_allowed', null ),
13678 fs_request_get( 'blog_id', null ),
13679 fs_request_get( 'module_id', null, 'post' ),
13680 fs_request_get( 'user_id', null ),
13681 fs_request_get_bool( 'is_extensions_tracking_allowed', null ),
13682 fs_request_get_bool( 'is_diagnostic_tracking_allowed', null )
13683 );
13684
13685 if (
13686 $result['success'] &&
13687 $this->is_bundle_license_auto_activation_enabled()
13688 ) {
13689 $license = new FS_Plugin_License();
13690 $license->secret_key = $license_key;
13691
13692 $this->maybe_activate_bundle_license( $license, $sites );
13693 }
13694
13695 echo json_encode( $result );
13696
13697 exit;
13698 }
13699
13700 /**
13701 * User change WP AJAX handler.
13702 *
13703 * @author Leo Fajardo (@leorw)
13704 * @since 2.3.2
13705 */
13706 function _user_change_ajax_action() {
13707 $this->_logger->entrance();
13708
13709 $this->check_ajax_referer( 'change_user' );
13710
13711 $new_email_address = trim( fs_request_get( 'email_address', '' ) );
13712 $new_user_id = fs_request_get( 'user_id' );
13713
13714 if ( empty( $new_email_address ) && ! FS_User::is_valid_id( $new_user_id ) ) {
13715 self::shoot_ajax_failure( fs_text_inline( 'Invalid new user ID or email address.', 'invalid-new-user-id-or-email', $this->get_slug() ) );
13716 }
13717
13718 $params = array();
13719
13720 if ( ! empty( $new_email_address ) ) {
13721 $params['user_email'] = $new_email_address;
13722 } else {
13723 $params['user_id'] = $new_user_id;
13724 }
13725
13726 $installs_info_by_slug_map = $this->get_parent_and_addons_installs_info();
13727 $install_ids = array();
13728
13729 foreach ( $installs_info_by_slug_map as $slug => $install_info ) {
13730 $install_ids[ $slug ] = $install_info['install']->id;
13731 }
13732
13733 $params['install_ids'] = implode( ',', array_values( $install_ids ) );
13734
13735 $install = $this->get_api_site_scope()->call( $this->add_show_pending( '/' ), 'put', $params );
13736
13737 if ( FS_Api::is_api_error( $install ) ) {
13738 $error = '';
13739
13740 if ( is_object( $install ) ) {
13741 switch ( $install->error->code ) {
13742 case 'user_exist':
13743 $error = (
13744 $this->get_text_x_inline( 'Oops', 'exclamation', 'oops' ) . '...' .
13745 $this->get_text_inline( 'Sorry, we could not complete the email update. Another user with the same email is already registered.', 'user-exist-message' ) . ' ' .
13746 sprintf( $this->get_text_inline( 'If you would like to give up the ownership of the %s\'s account to %s click the Change Ownership button.', 'user-exist-message_ownership' ), $this->_module_type, '<b>' . $new_email_address . '</b>' ) .
13747 sprintf(
13748 '<a style="line-height: 40px;" href="%s"><button class="button button-primary">%s &nbsp;&#10140;</button></a>',
13749 $this->get_account_url( 'change_owner', array(
13750 'state' => 'init',
13751 'candidate_email' => $new_email_address
13752 ) ),
13753 $this->get_text_inline( 'Change Ownership', 'change-ownership' )
13754 )
13755 );
13756 break;
13757 }
13758 }
13759
13760 if ( empty( $error ) ) {
13761 $error = FS_Api::is_api_error_object( $install ) ?
13762 $install->error->message :
13763 var_export( $install->error, true );
13764 }
13765
13766 self::shoot_ajax_failure( $error );
13767 } else {
13768 if (
13769 // If successful ownership change.
13770 $this->get_user()->id != $install->user_id ||
13771 ! empty( $new_email_address )
13772 ) {
13773 $this->complete_ownership_change_by_license( $install->user_id, $install_ids );
13774 }
13775 }
13776
13777 self::shoot_ajax_success();
13778 }
13779
13780 /**
13781 * @author Leo Fajardo (@leorw)
13782 * @since 2.3.2.14
13783 */
13784 function starting_migration() {
13785 if ( ! empty( $this->_storage->license_migration ) ) {
13786 // Do not overwrite the data if already set.
13787 return;
13788 }
13789
13790 $this->_storage->license_migration = array(
13791 'is_migrating' => true,
13792 'start_timestamp' => time()
13793 );
13794 }
13795
13796 /**
13797 * @author Leo Fajardo (@leorw)
13798 * @since 2.3.2.14
13799 */
13800 function is_migration() {
13801 if ( $this->is_addon() ) {
13802 return $this->get_parent_instance()->is_migration();
13803 }
13804
13805 if ( empty( $this->_storage->license_migration ) ) {
13806 return false;
13807 }
13808
13809 if ( ! $this->_storage->license_migration['is_migrating'] ) {
13810 return false;
13811 }
13812
13813 return (
13814 // Return `true` if the migration is within 5 minutes from the starting time.
13815 ( time() - $this->_storage->license_migration['start_timestamp'] ) <= WP_FS__TIME_5_MIN_IN_SEC
13816 );
13817 }
13818
13819 /**
13820 *
13821 * A helper method to activate migrated licenses. If the product is network activated and integrated, the method will network activate the license.
13822 *
13823 * @author Vova Feldman (@svovaf)
13824 * @since 2.3.0
13825 *
13826 * @param string $license_key
13827 * @param null|bool $is_marketing_allowed
13828 * @param null|number $plugin_id
13829 * @param array $sites
13830 * @param int $blog_id
13831 *
13832 * @return array {
13833 * @var bool $success
13834 * @var string $error
13835 * @var string $next_page
13836 * }
13837 *
13838 * @uses Freemius::activate_license()
13839 */
13840 function activate_migrated_license(
13841 $license_key,
13842 $is_marketing_allowed = null,
13843 $plugin_id = null,
13844 $sites = array(),
13845 $blog_id = null
13846 ) {
13847 $this->_logger->entrance();
13848
13849 $result = $this->activate_license(
13850 $license_key,
13851 ( empty( $sites ) && is_null( $blog_id ) && $this->is_network_active() ) ?
13852 $this->get_sites_for_network_level_optin() :
13853 $sites,
13854 $is_marketing_allowed,
13855 $blog_id,
13856 $plugin_id
13857 );
13858
13859 // No need to show the sticky after license activation notice after migrating a license.
13860 $this->_admin_notices->remove_sticky( 'plan_upgraded' );
13861
13862 return $result;
13863 }
13864
13865 /**
13866 * @author Leo Fajardo (@leorw)
13867 * @since 2.3.1
13868 *
13869 * @return string
13870 */
13871 function get_pricing_js_path() {
13872 if ( ! isset( $this->_pricing_js_path ) ) {
13873 $pricing_js_path = $this->apply_filters( 'freemius_pricing_js_path', '' );
13874
13875 if ( empty( $pricing_js_path ) ) {
13876 global $fs_active_plugins;
13877
13878 foreach ( $fs_active_plugins->plugins as $sdk_path => $data ) {
13879 if ( $data->plugin_path == $this->get_plugin_basename() ) {
13880 $plugin_or_theme_root_dir = ( $this->is_plugin() ? WP_PLUGIN_DIR : get_theme_root( get_stylesheet() ) );
13881
13882 $pricing_js_path = $plugin_or_theme_root_dir
13883 . '/'
13884 // The basename will be `plugins`, `themes`, or the basename of a custom plugins or themes directory.
13885 . str_replace( '../' . basename( $plugin_or_theme_root_dir ) . '/', '', $sdk_path )
13886 . '/includes/freemius-pricing/freemius-pricing.js';
13887
13888 break;
13889 }
13890 }
13891 }
13892
13893 $this->_pricing_js_path = $pricing_js_path;
13894 }
13895
13896 return $this->_pricing_js_path;
13897 }
13898
13899 /**
13900 * @author Leo Fajardo (@leorw)
13901 * @since 2.3.1
13902 *
13903 * @return bool
13904 */
13905 function should_use_external_pricing() {
13906 if ( is_null( $this->_use_external_pricing ) ) {
13907 $pricing_js_path = $this->get_pricing_js_path();
13908
13909 $this->_use_external_pricing = ( empty( $pricing_js_path ) || ! file_exists( $pricing_js_path ) );
13910 }
13911
13912 return $this->_use_external_pricing;
13913 }
13914
13915 /**
13916 * The implementation of this method was previously in `_activate_license_ajax_action()`.
13917 *
13918 * @author Vova Feldman (@svovaf)
13919 * @since 2.2.4
13920 * @since 2.0.0 When a super-admin that hasn't connected before is network activating a license and excluding some of the sites for the license activation, go over the unselected sites in the network and if a site is not connected, skipped, nor delegated, if it's a freemium product then just skip the connection for the site, if it's a premium only product, delegate the connection and license activation to the site admin (Vova Feldman @svovaf).
13921 * @param string $license_key
13922 * @param array $sites
13923 * @param null|bool $is_marketing_allowed
13924 * @param null|int $blog_id
13925 * @param null|number $plugin_id
13926 * @param null|number $license_owner_id
13927 * @param bool|null $is_extensions_tracking_allowed
13928 * @param bool|null $is_diagnostic_tracking_allowed Since 2.5.0.2 to allow license activation with minimal data footprint.
13929 *
13930 *
13931 * @return array {
13932 * @var bool $success
13933 * @var string $error
13934 * @var string $next_page
13935 * }
13936 */
13937 private function activate_license(
13938 $license_key,
13939 $sites = array(),
13940 $is_marketing_allowed = null,
13941 $blog_id = null,
13942 $plugin_id = null,
13943 $license_owner_id = null,
13944 $is_extensions_tracking_allowed = null,
13945 $is_diagnostic_tracking_allowed = null
13946 ) {
13947 $this->_logger->entrance();
13948
13949 $license_key = trim( $license_key );
13950
13951 $is_network_activation_or_migration = (
13952 fs_is_network_admin() ||
13953 ( ! empty( $sites ) && $this->is_migration() )
13954 );
13955
13956 if ( ! $is_network_activation_or_migration ) {
13957 // If the license activation is executed outside the context of a network admin, ignore the sites collection.
13958 $sites = array();
13959 }
13960
13961 $fs = ( empty($plugin_id) || $plugin_id == $this->_module_id ) ?
13962 $this :
13963 $this->get_addon_instance( $plugin_id );
13964
13965 FS_Permission_Manager::instance( $this )->update_permissions_tracking_flag( array(
13966 FS_Permission_Manager::PERMISSION_DIAGNOSTIC => $is_diagnostic_tracking_allowed,
13967 FS_Permission_Manager::PERMISSION_EXTENSIONS => $is_extensions_tracking_allowed,
13968 ) );
13969
13970 $error = false;
13971 $next_page = false;
13972
13973 $has_valid_blog_id = is_numeric( $blog_id );
13974
13975 $user = null;
13976
13977 if ( $fs->is_addon() && $fs->get_parent_instance()->is_registered() ) {
13978 /**
13979 * When activating an add-on's license and the parent is opted-in, activate the license with the parent's opted-in user context.
13980 *
13981 * @author Vova Feldman (@svovaf)
13982 */
13983 $user = $fs->get_parent_instance()->get_current_or_network_user();
13984 } else if ( $fs->is_registered() ) {
13985 $user = $fs->get_current_or_network_user();
13986 }
13987
13988 if ( $has_valid_blog_id ) {
13989 /**
13990 * If a specific blog ID was provided, activate the license only on the specific blog that is associated with the given blog ID.
13991 *
13992 * @author Leo Fajardo (@leorw)
13993 */
13994 $fs->switch_to_blog( $blog_id );
13995 }
13996
13997 if ( is_object( $user ) ) {
13998 $result = true;
13999
14000 if ( $is_network_activation_or_migration && ! $has_valid_blog_id ) {
14001 // If no specific blog ID was provided, activate the license for all sites in the network.
14002 $blog_2_install_map = array();
14003 $site_ids = array();
14004
14005 foreach ( $sites as $site ) {
14006 if ( ! isset( $site['blog_id'] ) || ! is_numeric( $site['blog_id'] ) ) {
14007 continue;
14008 }
14009
14010 $install = $fs->get_install_by_blog_id( $site['blog_id'] );
14011
14012 if ( is_object( $install ) ) {
14013 $blog_2_install_map[ $site['blog_id'] ] = $install;
14014 } else {
14015 $site_ids[] = $site['blog_id'];
14016 }
14017 }
14018
14019 if ( ! empty( $blog_2_install_map ) ) {
14020 $result = $fs->activate_license_on_many_installs( $user, $license_key, $blog_2_install_map );
14021 }
14022
14023 if ( true === $result && ! empty( $site_ids ) ) {
14024 $result = $fs->activate_license_on_many_sites( $user, $license_key, $site_ids );
14025 }
14026 } else {
14027 if ( $fs->is_registered() ) {
14028 $params = array(
14029 'license_key' => $fs->apply_filters( 'license_key', $license_key )
14030 );
14031
14032 $install_ids = array();
14033
14034 $change_owner = FS_User::is_valid_id( $license_owner_id );
14035
14036 if ( $change_owner ) {
14037 $params['user_id'] = $license_owner_id;
14038
14039 $installs_info_by_slug_map = $fs->get_parent_and_addons_installs_info();
14040
14041 foreach ( $installs_info_by_slug_map as $slug => $install_info ) {
14042 $install_ids[ $slug ] = $install_info['install']->id;
14043 }
14044
14045 $params['install_ids'] = implode( ',', array_values( $install_ids ) );
14046 }
14047
14048 $api = $fs->get_api_site_scope();
14049
14050 $result = $api->call( $fs->add_show_pending( '/' ), 'put', $params );
14051
14052 if ( ! FS_Api::is_api_error( $result ) ) {
14053 $install = $result;
14054
14055 $fs->reconnect_locally( $has_valid_blog_id );
14056
14057 if (
14058 $change_owner &&
14059 // If successful ownership change.
14060 $fs->get_user()->id != $install->user_id
14061 ) {
14062 $fs->complete_ownership_change_by_license( $install->user_id, $install_ids );
14063 }
14064 }
14065 } else /* ( $fs->is_addon() && $fs->get_parent_instance()->is_registered() ) */ {
14066 $result = $fs->activate_license_on_site( $user, $license_key );
14067 }
14068 }
14069
14070 if ( true !== $result && ! FS_Api::is_api_result_entity( $result ) ) {
14071 if ( FS_Api::is_blocked( $result ) ) {
14072 $result->error->message = $this->generate_api_blocked_notice_message_from_result( $result );
14073 }
14074
14075 $error = FS_Api::is_api_error_object( $result ) ?
14076 $result->error->message :
14077 var_export( $result, true );
14078 } else {
14079 $fs->network_upgrade_mode_completed();
14080
14081 $fs->_user = $user;
14082
14083 if ( fs_is_network_admin() && ! $has_valid_blog_id ) {
14084 $fs->_site = $fs->get_network_install();
14085 }
14086
14087 $fs->_sync_license( true, $has_valid_blog_id );
14088
14089 $this->maybe_sync_install_user();
14090
14091 $next_page = $fs->is_addon() ?
14092 $fs->get_parent_instance()->get_account_url() :
14093 $fs->get_after_activation_url( 'after_connect_url' );
14094 }
14095 } else {
14096 $next_page = $fs->opt_in(
14097 false,
14098 false,
14099 false,
14100 $license_key,
14101 false,
14102 false,
14103 false,
14104 $is_marketing_allowed,
14105 $sites
14106 );
14107
14108 if ( isset( $next_page->error ) ) {
14109 $error = $next_page->error;
14110 } else {
14111 if ( $is_network_activation_or_migration ) {
14112 /**
14113 * Get the list of sites that were just opted-in (and license activated).
14114 * This is an optimization for the next part below saving some DB queries.
14115 */
14116 $connected_sites = array();
14117 foreach ( $sites as $site ) {
14118 if ( isset( $site['blog_id'] ) && is_numeric( $site['blog_id'] ) ) {
14119 $connected_sites[ $site['blog_id'] ] = true;
14120 }
14121 }
14122
14123 $all_sites = self::get_sites();
14124 $pending_blog_ids = array();
14125
14126 /**
14127 * Check if there are any sites that are not connected, skipped, nor delegated. For every site that falls into that category, if the product is freemium, skip the connection. If the product is premium only, delegate the connection to the site administrator.
14128 *
14129 * @author Vova Feldman (@svovaf)
14130 */
14131 foreach ( $all_sites as $site ) {
14132 $blog_id = self::get_site_blog_id( $site );
14133
14134 if ( isset( $connected_sites[ $blog_id ] ) ) {
14135 // Site was just connected.
14136 continue;
14137 }
14138
14139 if ( $fs->is_installed_on_site( $blog_id ) ) {
14140 // Site was already connected before.
14141 continue;
14142 }
14143
14144 if ( $fs->is_site_delegated_connection( $blog_id ) ) {
14145 // Site's connection was delegated.
14146 continue;
14147 }
14148
14149 if ( $fs->is_anonymous_site( $blog_id ) ) {
14150 // Site connection was already skipped.
14151 continue;
14152 }
14153
14154 $pending_blog_ids[] = $blog_id;
14155 }
14156
14157 if ( ! empty( $pending_blog_ids ) ) {
14158 if ( $fs->is_freemium() && $fs->is_enable_anonymous() ) {
14159 $fs->skip_connection( $pending_blog_ids );
14160 } else {
14161 $fs->delegate_connection( $pending_blog_ids );
14162 }
14163 }
14164 }
14165 }
14166 }
14167
14168 if ( false === $error && true === $fs->_storage->require_license_activation ) {
14169 $fs->_storage->require_license_activation = false;
14170 }
14171
14172 $result = array(
14173 'success' => ( false === $error )
14174 );
14175
14176 if ( false !== $error ) {
14177 $result['error'] = $fs->apply_filters( 'opt_in_error_message', $error );
14178 } else {
14179 if ( $fs->is_addon() || $fs->has_addons() ) {
14180 /**
14181 * Purge the valid user licenses cache so that when the "Account" or the "Add-Ons" page is loaded,
14182 * an updated valid user licenses collection will be fetched from the server which is used to also
14183 * update the account add-ons (add-ons the user has licenses for).
14184 *
14185 * @author Leo Fajardo (@leorw)
14186 * @since 2.2.4
14187 */
14188 $fs->purge_valid_user_licenses_cache();
14189 }
14190
14191 $result['next_page'] = $next_page;
14192 }
14193
14194 return $result;
14195 }
14196
14197 /**
14198 * @author Leo Fajardo (@leorw)
14199 * @since 2.3.2
14200 *
14201 * @return array {
14202 * @key string Product slug.
14203 * @value array {
14204 * @property FS_Site $site
14205 * @property FS_Plugin_License $license
14206 * }
14207 * }
14208 */
14209 private function get_parent_and_addons_installs_info() {
14210 $fs = $this->is_addon() ?
14211 $this->get_parent_instance() :
14212 $this;
14213
14214 $installed_addons_ids = array();
14215
14216 $installed_addons_instances = $fs->get_installed_addons();
14217 foreach ( $installed_addons_instances as $instance ) {
14218 $installed_addons_ids[] = $instance->get_id();
14219 }
14220
14221 $addons_ids = array_unique( array_merge(
14222 $installed_addons_ids,
14223 $fs->get_updated_account_addons()
14224 ) );
14225
14226 // Add parent product info.
14227 $installs_info_by_slug_map = array(
14228 $fs->get_slug() => array(
14229 'install' => $fs->get_site(),
14230 'license' => $fs->_get_license()
14231 )
14232 );
14233
14234 foreach ( $addons_ids as $addon_id ) {
14235 $is_installed = isset( $installed_addons_ids_map[ $addon_id ] );
14236
14237 $addon_info = $fs->_get_addon_info( $addon_id, $is_installed );
14238
14239 if ( ! isset( $addon_info['is_connected'] ) || ! $addon_info['is_connected'] ) {
14240 // Add-on is not associated with an install entity.
14241 continue;
14242 }
14243
14244 $installs_info_by_slug_map[ $addon_info['slug'] ] = array(
14245 'install' => $addon_info['site'],
14246 'license' => isset( $addon_info['license'] ) ?
14247 $addon_info['license'] :
14248 null
14249 );
14250 }
14251
14252 return $installs_info_by_slug_map;
14253 }
14254
14255 /**
14256 * @author Leo Fajardo (@leorw)
14257 * @since 1.2.3.1
14258 */
14259 function _network_activate_ajax_action() {
14260 $this->_logger->entrance();
14261
14262 $this->check_ajax_referer( 'network_activate' );
14263
14264 $plugin_id = fs_request_get( 'module_id', '', 'post' );
14265 $fs = ( $plugin_id == $this->_module_id ) ?
14266 $this :
14267 $this->get_addon_instance( $plugin_id );
14268
14269 $error = false;
14270
14271 $sites = fs_request_get( 'sites', array(), 'post' );
14272 if ( is_array( $sites ) && ! empty( $sites ) ) {
14273 $sites_by_action = array(
14274 'allow' => array(),
14275 'delegate' => array(),
14276 'skip' => array()
14277 );
14278
14279 foreach ( $sites as $site ) {
14280 $sites_by_action[ $site['action'] ][] = $site;
14281 }
14282
14283 $total_sites = count( $sites );
14284 $total_sites_to_delegate = count( $sites_by_action['delegate'] );
14285
14286 $next_page = '';
14287
14288 $has_any_install = fs_request_get_bool( 'has_any_install' );
14289
14290 if ( $total_sites === $total_sites_to_delegate &&
14291 ! $this->is_network_upgrade_mode() &&
14292 ! $has_any_install
14293 ) {
14294 $this->delegate_connection();
14295 } else {
14296 if ( ! empty( $sites_by_action['delegate'] ) ) {
14297 $this->delegate_connection( self::get_sites_blog_ids( $sites_by_action['delegate'] ) );
14298 }
14299
14300 if ( ! empty( $sites_by_action['skip'] ) ) {
14301 $this->skip_connection( self::get_sites_blog_ids( $sites_by_action['skip'] ) );
14302 }
14303
14304 if ( empty( $sites_by_action['allow'] ) ) {
14305 if ( $has_any_install ) {
14306 $first_install = $fs->find_first_install();
14307
14308 if ( ! is_null( $first_install ) ) {
14309 $fs->_site = $first_install['install'];
14310 $fs->_storage->network_install_blog_id = $first_install['blog_id'];
14311
14312 $fs->_user = self::_get_user_by_id( $fs->_site->user_id );
14313 $fs->_storage->network_user_id = $fs->_user->id;
14314 }
14315 }
14316 } else {
14317 if ( ! $fs->is_registered() || ! $this->_is_network_active ) {
14318 $next_page = $fs->opt_in(
14319 false,
14320 false,
14321 false,
14322 false,
14323 false,
14324 false,
14325 false,
14326 fs_request_get_bool( 'is_marketing_allowed', null ),
14327 $sites_by_action['allow']
14328 );
14329 } else {
14330 $next_page = $fs->install_with_user(
14331 $this->get_network_user(),
14332 false,
14333 false,
14334 false,
14335 true,
14336 $sites_by_action['allow']
14337 );
14338 }
14339
14340 if ( is_object( $next_page ) && isset( $next_page->error ) ) {
14341 $error = $next_page->error;
14342 }
14343 }
14344 }
14345
14346 if ( empty( $next_page ) ) {
14347 $next_page = $this->get_after_activation_url( 'after_network_activation_url' );
14348 }
14349 } else {
14350 $error = $this->get_text_inline( 'Invalid site details collection.', 'invalid_site_details_collection' );
14351 }
14352
14353 $result = array(
14354 'success' => ( false === $error )
14355 );
14356
14357 if ( false !== $error ) {
14358 $result['error'] = $error;
14359 } else {
14360 $result['next_page'] = $next_page;
14361 }
14362
14363 echo json_encode( $result );
14364
14365 exit;
14366 }
14367
14368 /**
14369 * Billing update AJAX callback.
14370 *
14371 * @author Vova Feldman (@svovaf)
14372 * @since 1.2.1.5
14373 */
14374 function _update_billing_ajax_action() {
14375 $this->_logger->entrance();
14376
14377 $this->check_ajax_referer( 'update_billing' );
14378
14379 if ( ! $this->is_user_admin() ) {
14380 // Only for admins.
14381 self::shoot_ajax_failure();
14382 }
14383
14384 $billing = fs_request_get( 'billing' );
14385
14386 $api = $this->get_api_user_scope();
14387 $result = $api->call( '/billing.json', 'put', array_merge( $billing, array(
14388 'plugin_id' => $this->get_parent_id(),
14389 ) ) );
14390
14391 if ( ! $this->is_api_result_entity( $result ) ) {
14392 self::shoot_ajax_failure();
14393 }
14394
14395 // Purge cached billing.
14396 $this->get_api_user_scope()->purge_cache( 'billing.json' );
14397
14398 self::shoot_ajax_success();
14399 }
14400
14401 /**
14402 * Trial start for anonymous users (AJAX callback).
14403 *
14404 * @author Vova Feldman (@svovaf)
14405 * @since 1.2.1.5
14406 */
14407 function _start_trial_ajax_action() {
14408 $this->_logger->entrance();
14409
14410 $this->check_ajax_referer( 'start_trial' );
14411
14412 if ( ! $this->is_user_admin() ) {
14413 // Only for admins.
14414 self::shoot_ajax_failure();
14415 }
14416
14417 $trial_data = fs_request_get( 'trial' );
14418
14419 $next_page = $this->opt_in(
14420 false,
14421 false,
14422 false,
14423 false,
14424 false,
14425 $trial_data['plan_id']
14426 );
14427
14428 if ( is_object( $next_page ) && $this->is_api_error( $next_page ) ) {
14429 self::shoot_ajax_failure(
14430 isset( $next_page->error ) ?
14431 $next_page->error->message :
14432 var_export( $next_page, true )
14433 );
14434 }
14435
14436 $this->shoot_ajax_success( array(
14437 'next_page' => $next_page,
14438 ) );
14439 }
14440
14441 /**
14442 * @author Leo Fajardo (@leorw)
14443 * @since 1.2.0
14444 */
14445 function _resend_license_key_ajax_action() {
14446 $this->_logger->entrance();
14447
14448 $this->check_ajax_referer( 'resend_license_key' );
14449
14450 $email_address = sanitize_email( trim( fs_request_get( 'email', '', 'post' ) ) );
14451
14452 if ( empty( $email_address ) ) {
14453 exit;
14454 }
14455
14456 $error = false;
14457
14458 $api = $this->get_api_plugin_scope();
14459 $result = $api->call( '/licenses/resend.json', 'post',
14460 array(
14461 'email' => $email_address,
14462 'url' => home_url(),
14463 )
14464 );
14465
14466 if ( is_object( $result ) && isset( $result->error ) ) {
14467 $error = $result->error;
14468
14469 if ( in_array( $error->code, array( 'invalid_email', 'no_user' ) ) ) {
14470 $error = $this->get_text_inline( "We couldn't find your email address in the system, are you sure it's the right address?", 'email-not-found' );
14471 } else if ( 'no_license' === $error->code ) {
14472 $error = $this->get_text_inline( "We can't see any active licenses associated with that email address, are you sure it's the right address?", 'no-active-licenses' );
14473 } else {
14474 $error = $error->message;
14475 }
14476 }
14477
14478 $licenses = array(
14479 'success' => ( false === $error )
14480 );
14481
14482 if ( false !== $error ) {
14483 $licenses['error'] = sprintf( '%s... %s', $this->get_text_x_inline( 'Oops', 'exclamation', 'oops' ), strtolower( $error ) );
14484 }
14485
14486 echo json_encode( $licenses );
14487
14488 exit;
14489 }
14490
14491 /**
14492 * @author Vova Feldman (@svovaf)
14493 * @since 1.2.1.8
14494 *
14495 * @var string
14496 */
14497 private static $_pagenow;
14498
14499 /**
14500 * Get current page or the referer if executing a WP AJAX request.
14501 *
14502 * @author Vova Feldman (@svovaf)
14503 * @since 1.2.1.8
14504 *
14505 * @return string
14506 */
14507 static function get_current_page() {
14508 if ( ! isset( self::$_pagenow ) ) {
14509 global $pagenow;
14510 if ( empty( $pagenow ) && is_admin() && is_multisite() ) {
14511 /**
14512 * It appears that `$pagenow` is not yet initialized in some network admin pages when this method
14513 * is called, so initialize it here using some pieces of code from `wp-includes/vars.php`.
14514 *
14515 * @author Leo Fajardo (@leorw)
14516 * @since 2.2.3
14517 */
14518 if ( is_network_admin() ) {
14519 preg_match( '#/wp-admin/network/?(.*?)$#i', $_SERVER['PHP_SELF'], $self_matches );
14520 } else if ( is_user_admin() ) {
14521 preg_match( '#/wp-admin/user/?(.*?)$#i', $_SERVER['PHP_SELF'], $self_matches );
14522 } else {
14523 preg_match( '#/wp-admin/?(.*?)$#i', $_SERVER['PHP_SELF'], $self_matches );
14524 }
14525
14526 $pagenow = $self_matches[1];
14527 $pagenow = trim( $pagenow, '/' );
14528 $pagenow = preg_replace( '#\?.*?$#', '', $pagenow );
14529 if ( '' === $pagenow || 'index' === $pagenow || 'index.php' === $pagenow ) {
14530 $pagenow = 'index.php';
14531 } else {
14532 preg_match( '#(.*?)(/|$)#', $pagenow, $self_matches );
14533 $pagenow = strtolower( $self_matches[1] );
14534 if ( '.php' !== substr($pagenow, -4, 4) )
14535 $pagenow .= '.php'; // for Options +Multiviews: /wp-admin/themes/index.php (themes.php is queried)
14536 }
14537 }
14538
14539 self::$_pagenow = $pagenow;
14540
14541 if ( self::is_ajax() &&
14542 'admin-ajax.php' === $pagenow
14543 ) {
14544 $referer = fs_get_raw_referer();
14545
14546 if ( is_string( $referer ) ) {
14547 $parts = explode( '?', $referer );
14548
14549 self::$_pagenow = basename( $parts[0] );
14550 }
14551 }
14552 }
14553
14554 return self::$_pagenow;
14555 }
14556
14557 /**
14558 * Helper method to check if user in the plugins page.
14559 *
14560 * @author Vova Feldman (@svovaf)
14561 * @since 1.2.1.5
14562 *
14563 * @return bool
14564 */
14565 static function is_plugins_page() {
14566 return ( 'plugins.php' === self::get_current_page() );
14567 }
14568
14569 /**
14570 * @author Leo Fajardo (@leorw)
14571 * @since 2.2.3
14572 *
14573 * @return bool
14574 */
14575 static function is_plugin_install_page() {
14576 return ( 'plugin-install.php' === self::get_current_page() );
14577 }
14578
14579 /**
14580 * @author Leo Fajardo (@leorw)
14581 * @since 2.0.2
14582 *
14583 * @return bool
14584 */
14585 static function is_updates_page() {
14586 return ( 'update-core.php' === self::get_current_page() );
14587 }
14588
14589 /**
14590 * Helper method to check if user in the themes page.
14591 *
14592 * @author Vova Feldman (@svovaf)
14593 * @since 1.2.2.6
14594 *
14595 * @return bool
14596 */
14597 static function is_themes_page() {
14598 return ( 'themes.php' === self::get_current_page() );
14599 }
14600
14601 #----------------------------------------------------------------------------------
14602 #region Affiliation
14603 #----------------------------------------------------------------------------------
14604
14605 /**
14606 * @author Leo Fajardo (@leorw)
14607 * @since 1.2.3
14608 *
14609 * @return bool
14610 */
14611 function has_affiliate_program() {
14612 if ( ! is_object( $this->_plugin ) ) {
14613 return false;
14614 }
14615
14616 return $this->_plugin->has_affiliate_program();
14617 }
14618
14619 /**
14620 * Get Plugin ID under which we will track affiliate application.
14621 *
14622 * This could either be the Bundle ID or the main plugin ID.
14623 *
14624 * @return number Bundle ID if developer has provided one, else the main plugin ID.
14625 */
14626 private function get_plugin_id_for_affiliate_terms() {
14627 return $this->has_bundle_context() ?
14628 $this->get_bundle_id() :
14629 $this->_plugin->id;
14630 }
14631
14632 /**
14633 * @author Leo Fajardo (@leorw)
14634 * @since 1.2.4
14635 */
14636 private function fetch_affiliate_terms() {
14637 if ( ! is_object( $this->plugin_affiliate_terms ) ) {
14638 /**
14639 * In case we have a bundle set in SDK configuration, we would like to use that for affiliates, not the main plugin.
14640 */
14641 $plugins_api = $this->has_bundle_context() ?
14642 $this->get_api_bundle_scope() :
14643 $this->get_api_plugin_scope();
14644
14645 $affiliate_terms = $plugins_api->get( '/aff.json?type=affiliation', false );
14646
14647 /**
14648 * At this point, we intentionally don't fallback to the main plugin, because the developer has chosen to use bundle. So it makes sense the affiliate program should be in context to the bundle too.
14649 */
14650 if ( ! $this->is_api_result_entity( $affiliate_terms ) ) {
14651 return;
14652 }
14653
14654 $this->plugin_affiliate_terms = new FS_AffiliateTerms( $affiliate_terms );
14655 }
14656 }
14657
14658 /**
14659 * @author Leo Fajardo (@leorw)
14660 * @since 1.2.4
14661 */
14662 private function fetch_affiliate_and_custom_terms() {
14663 if ( ! empty( $this->_storage->affiliate_application_data ) ) {
14664 $application_data = $this->_storage->affiliate_application_data;
14665 $flush = ( ! isset( $application_data['status'] ) || 'pending' === $application_data['status'] );
14666
14667 $plugin_id_for_affiliate = $this->get_plugin_id_for_affiliate_terms();
14668
14669 $users_api = $this->get_api_user_scope();
14670 $result = $users_api->get( "/plugins/{$plugin_id_for_affiliate}/aff/{$this->plugin_affiliate_terms->id}/affiliates.json", $flush );
14671 if ( $this->is_api_result_object( $result, 'affiliates' ) ) {
14672 if ( ! empty( $result->affiliates ) ) {
14673 $affiliate = new FS_Affiliate( $result->affiliates[0] );
14674
14675 if ( ! isset( $application_data['status'] ) || $application_data['status'] !== $affiliate->status ) {
14676 $application_data['status'] = $affiliate->status;
14677 $this->_storage->affiliate_application_data = $application_data;
14678 }
14679
14680 if ( $affiliate->is_using_custom_terms ) {
14681 $affiliate_terms = $users_api->get( "/plugins/{$this->_plugin->id}/affiliates/{$affiliate->id}/aff/{$affiliate->custom_affiliate_terms_id}.json", $flush );
14682 if ( $this->is_api_result_entity( $affiliate_terms ) ) {
14683 $this->custom_affiliate_terms = new FS_AffiliateTerms( $affiliate_terms );
14684 }
14685 }
14686
14687 $this->affiliate = $affiliate;
14688 }
14689 }
14690 }
14691 }
14692
14693 /**
14694 * @author Leo Fajardo (@leorw)
14695 * @since 1.2.3
14696 */
14697 private function fetch_affiliate_and_terms() {
14698 $this->_logger->entrance();
14699
14700 $this->fetch_affiliate_terms();
14701 $this->fetch_affiliate_and_custom_terms();
14702 }
14703
14704 /**
14705 * @author Leo Fajardo (@leorw)
14706 * @since 1.2.3
14707 *
14708 * @return FS_Affiliate
14709 */
14710 function get_affiliate() {
14711 return $this->affiliate;
14712 }
14713
14714
14715 /**
14716 * @author Leo Fajardo (@leorw)
14717 * @since 1.2.3
14718 *
14719 * @return FS_AffiliateTerms
14720 */
14721 function get_affiliate_terms() {
14722 return is_object( $this->custom_affiliate_terms ) ?
14723 $this->custom_affiliate_terms :
14724 $this->plugin_affiliate_terms;
14725 }
14726
14727 /**
14728 * @author Leo Fajardo (@leorw)
14729 * @since 1.2.3
14730 */
14731 function _submit_affiliate_application() {
14732 $this->_logger->entrance();
14733
14734 $this->check_ajax_referer( 'submit_affiliate_application' );
14735
14736 if ( ! $this->is_user_admin() ) {
14737 // Only for admins.
14738 self::shoot_ajax_failure();
14739 }
14740
14741 $affiliate = fs_request_get( 'affiliate' );
14742
14743 if ( empty( $affiliate['promotion_methods'] ) ) {
14744 unset( $affiliate['promotion_methods'] );
14745 }
14746
14747 if ( ! empty( $affiliate['additional_domains'] ) ) {
14748 $affiliate['additional_domains'] = array_unique( $affiliate['additional_domains'] );
14749 }
14750
14751 if ( ! $this->is_registered() ) {
14752 // Opt in but don't track usage.
14753 $next_page = $this->opt_in(
14754 false,
14755 false,
14756 false,
14757 false,
14758 false,
14759 false,
14760 true
14761 );
14762
14763 if ( is_object( $next_page ) && $this->is_api_error( $next_page ) ) {
14764 self::shoot_ajax_failure(
14765 isset( $next_page->error ) ?
14766 $next_page->error->message :
14767 var_export( $next_page, true )
14768 );
14769 } else if ( $this->is_pending_activation() ) {
14770 self::shoot_ajax_failure( $this->get_text_inline( 'Account is pending activation. Please check your email and click the link to activate your account and then submit the affiliate form again.', 'account-is-pending-activation' ) );
14771 }
14772 }
14773
14774 $this->fetch_affiliate_terms();
14775
14776 $plugin_id_for_affiliate = $this->get_plugin_id_for_affiliate_terms();
14777
14778 $api = $this->get_api_user_scope();
14779 $result = $api->call(
14780 ( "/plugins/{$plugin_id_for_affiliate}/aff/{$this->plugin_affiliate_terms->id}/affiliates.json" ),
14781 'post',
14782 $affiliate
14783 );
14784
14785 if ( $this->is_api_error( $result ) ) {
14786 self::shoot_ajax_failure(
14787 isset( $result->error ) ?
14788 $result->error->message :
14789 var_export( $result, true )
14790 );
14791 } else {
14792 if ( $this->_admin_notices->has_sticky( 'affiliate_program' ) ) {
14793 $this->_admin_notices->remove_sticky( 'affiliate_program' );
14794 }
14795
14796 $affiliate_application_data = array(
14797 'status' => 'pending',
14798 'stats_description' => $affiliate['stats_description'],
14799 'promotion_method_description' => $affiliate['promotion_method_description'],
14800 );
14801
14802 if ( ! empty( $affiliate['promotion_methods'] ) ) {
14803 $affiliate_application_data['promotion_methods'] = $affiliate['promotion_methods'];
14804 }
14805
14806 if ( ! empty( $affiliate['domain'] ) ) {
14807 $affiliate_application_data['domain'] = $affiliate['domain'];
14808 }
14809
14810 if ( ! empty( $affiliate['additional_domains'] ) ) {
14811 $affiliate_application_data['additional_domains'] = $affiliate['additional_domains'];
14812 }
14813
14814 $this->_storage->affiliate_application_data = $affiliate_application_data;
14815 }
14816
14817 // Purge cached affiliate.
14818 $api->purge_cache( 'affiliate.json' );
14819
14820 self::shoot_ajax_success( $result );
14821 }
14822
14823 /**
14824 * @author Leo Fajardo (@leorw)
14825 * @since 1.2.3
14826 *
14827 * @return array|null
14828 */
14829 function get_affiliate_application_data() {
14830 if ( empty( $this->_storage->affiliate_application_data ) ) {
14831 return null;
14832 }
14833
14834 return $this->_storage->affiliate_application_data;
14835 }
14836
14837 #endregion Affiliation ------------------------------------------------------------
14838
14839 #----------------------------------------------------------------------------------
14840 #region URL Generators
14841 #----------------------------------------------------------------------------------
14842
14843 /**
14844 * Alias to pricing_url().
14845 *
14846 * @author Vova Feldman (@svovaf)
14847 * @since 1.0.2
14848 *
14849 * @uses pricing_url()
14850 *
14851 * @param string $period Billing cycle
14852 * @param bool $is_trial
14853 *
14854 * @return string
14855 */
14856 function get_upgrade_url( $period = WP_FS__PERIOD_ANNUALLY, $is_trial = false ) {
14857 return $this->pricing_url( $period, $is_trial );
14858 }
14859
14860 /**
14861 * @author Vova Feldman (@svovaf)
14862 * @since 1.0.9
14863 *
14864 * @uses get_upgrade_url()
14865 *
14866 * @return string
14867 */
14868 function get_trial_url() {
14869 return $this->get_upgrade_url( WP_FS__PERIOD_ANNUALLY, true );
14870 }
14871
14872 /**
14873 * @author Leo Fajardo (@leorw)
14874 * @since 2.1.4
14875 *
14876 * @param string $new_version
14877 *
14878 * @return string
14879 */
14880 function version_upgrade_checkout_link( $new_version ) {
14881 if ( ! is_object( $this->_license ) ) {
14882 $url = $this->pricing_url();
14883
14884 $purchase_license_text = $this->get_text_inline( 'Buy a license now', 'buy-license-now' );
14885 } else {
14886 $subscription = $this->_get_subscription( $this->_license->id );
14887
14888 $url = $this->checkout_url(
14889 is_object( $subscription ) ?
14890 ( 1 == $subscription->billing_cycle ? WP_FS__PERIOD_MONTHLY : WP_FS__PERIOD_ANNUALLY ) :
14891 WP_FS__PERIOD_LIFETIME,
14892 false,
14893 array( 'licenses' => $this->_license->quota )
14894 );
14895
14896 $purchase_license_text = $this->get_text_inline( 'Renew your license now', 'renew-license-now' );
14897 }
14898
14899 return sprintf(
14900 $this->get_text_inline( '%s to access version %s security & feature updates, and support.', 'x-for-updates-and-support' ),
14901 sprintf(
14902 '<a href="%s">%s</a>',
14903 $this->apply_filters( 'update_notice_checkout_url', $url ),
14904 $purchase_license_text
14905 ),
14906 $new_version
14907 );
14908 }
14909
14910 /**
14911 * Plugin's pricing URL.
14912 *
14913 * @author Vova Feldman (@svovaf)
14914 * @since 1.0.4
14915 *
14916 * @param string $billing_cycle Billing cycle
14917 *
14918 * @param bool $is_trial
14919 *
14920 * @return string
14921 */
14922 function pricing_url( $billing_cycle = WP_FS__PERIOD_ANNUALLY, $is_trial = false ) {
14923 $this->_logger->entrance();
14924
14925 $params = array(
14926 'billing_cycle' => $billing_cycle
14927 );
14928
14929 if ( $is_trial ) {
14930 $params['trial'] = 'true';
14931 }
14932
14933 $url = $this->is_addon() ?
14934 $this->_parent->addon_url( $this->_slug ) :
14935 $this->_get_admin_page_url( 'pricing', $params );
14936
14937 return $this->apply_filters( 'pricing_url', $url );
14938 }
14939
14940 /**
14941 * Checkout page URL.
14942 *
14943 * @author Vova Feldman (@svovaf)
14944 * @since 1.0.6
14945 *
14946 * @param string $billing_cycle Billing cycle
14947 * @param bool $is_trial
14948 * @param array $extra (optional) Extra parameters, override other query params.
14949 * @param bool|null $network
14950 *
14951 * @return string
14952 */
14953 function checkout_url(
14954 $billing_cycle = WP_FS__PERIOD_ANNUALLY,
14955 $is_trial = false,
14956 $extra = array(),
14957 $network = null
14958 ) {
14959 $this->_logger->entrance();
14960
14961 $params = array(
14962 'checkout' => 'true',
14963 'billing_cycle' => $billing_cycle,
14964 );
14965
14966 if ( $is_trial ) {
14967 $params['trial'] = 'true';
14968 }
14969
14970 /**
14971 * Params in extra override other params.
14972 */
14973 $params = array_merge( $params, $extra );
14974
14975 return $this->apply_filters( 'checkout_url', $this->_get_admin_page_url( 'pricing', $params, $network ) );
14976 }
14977
14978 /**
14979 * Add-on checkout URL.
14980 *
14981 * @author Vova Feldman (@svovaf)
14982 * @since 1.1.7
14983 *
14984 * @param number $addon_id
14985 * @param number $pricing_id
14986 * @param string $billing_cycle
14987 * @param bool $is_trial
14988 * @param bool|null $network
14989 *
14990 * @return string
14991 */
14992 function addon_checkout_url(
14993 $addon_id,
14994 $pricing_id,
14995 $billing_cycle = WP_FS__PERIOD_ANNUALLY,
14996 $is_trial = false,
14997 $network = null
14998 ) {
14999 return $this->checkout_url( $billing_cycle, $is_trial, array(
15000 'plugin_id' => $addon_id,
15001 'pricing_id' => $pricing_id,
15002 ), $network );
15003 }
15004
15005 #endregion
15006
15007 #endregion ------------------------------------------------------------------
15008
15009 /**
15010 * Check if plugin has any add-ons.
15011 *
15012 * @author Vova Feldman (@svovaf)
15013 * @since 1.0.5
15014 *
15015 * @since 1.1.7.3 Base logic only on the parameter provided by the developer in the init function.
15016 *
15017 * @return bool
15018 */
15019 function has_addons() {
15020 $this->_logger->entrance();
15021
15022 return $this->_has_addons;
15023 }
15024
15025 /**
15026 * Check if plugin can work in anonymous mode.
15027 *
15028 * @author Vova Feldman (@svovaf)
15029 * @since 1.0.9
15030 *
15031 * @return bool
15032 *
15033 * @deprecated Please use is_enable_anonymous() instead.
15034 */
15035 function enable_anonymous() {
15036 return $this->_enable_anonymous;
15037 }
15038
15039 /**
15040 * Check if plugin can work in anonymous mode.
15041 *
15042 * @author Vova Feldman (@svovaf)
15043 * @since 1.1.9
15044 *
15045 * @return bool
15046 */
15047 function is_enable_anonymous() {
15048 return $this->_enable_anonymous;
15049 }
15050
15051 /**
15052 * Check if plugin is premium only (no free plans).
15053 *
15054 * @author Vova Feldman (@svovaf)
15055 * @since 1.1.9
15056 *
15057 * @return bool
15058 */
15059 function is_only_premium() {
15060 return $this->_is_premium_only;
15061 }
15062
15063 /**
15064 * Checks if the plugin's type is "plugin". The other type is "theme".
15065 *
15066 * @author Leo Fajardo (@leorw)
15067 * @since 1.2.2
15068 *
15069 * @return bool
15070 */
15071 function is_plugin() {
15072 return ( WP_FS__MODULE_TYPE_PLUGIN === $this->_module_type );
15073 }
15074
15075 /**
15076 * @author Leo Fajardo (@leorw)
15077 * @since 1.2.2
15078 *
15079 * @return string
15080 */
15081 function get_module_type() {
15082 if ( ! isset( $this->_module_type ) ) {
15083 $id_slug_type_path_map = self::$_accounts->get_option( 'id_slug_type_path_map', array() );
15084 $this->_module_type = $id_slug_type_path_map[ $this->_module_id ]['type'];
15085 }
15086
15087 return $this->_module_type;
15088 }
15089
15090 /**
15091 * @author Leo Fajardo (@leorw)
15092 * @since 1.2.2
15093 *
15094 * @return string
15095 */
15096 function get_plugin_main_file_path() {
15097 return $this->_plugin_main_file_path;
15098 }
15099
15100 /**
15101 * Check if module has a premium code version.
15102 *
15103 * Serviceware module might be freemium without any
15104 * premium code version, where the paid features
15105 * are all part of the service.
15106 *
15107 * @author Vova Feldman (@svovaf)
15108 * @since 1.2.1.6
15109 *
15110 * @return bool
15111 */
15112 function has_premium_version() {
15113 return $this->_has_premium_version;
15114 }
15115
15116 /**
15117 * Check if feature supported with current site's plan.
15118 *
15119 * @author Vova Feldman (@svovaf)
15120 * @since 1.0.1
15121 *
15122 * @todo IMPLEMENT
15123 *
15124 * @param number $feature_id
15125 *
15126 * @throws Exception
15127 */
15128 function is_feature_supported( $feature_id ) {
15129 throw new Exception( 'not implemented' );
15130 }
15131
15132 /**
15133 * @author Vova Feldman (@svovaf)
15134 * @since 1.0.1
15135 *
15136 * @return bool Is running in SSL/HTTPS
15137 */
15138 function is_ssl() {
15139 return WP_FS__IS_HTTPS;
15140 }
15141
15142 /**
15143 * @author Vova Feldman (@svovaf)
15144 * @since 1.0.9
15145 *
15146 * @return bool Is running in AJAX call.
15147 *
15148 * @link http://wordpress.stackexchange.com/questions/70676/how-to-check-if-i-am-in-admin-ajax
15149 */
15150 static function is_ajax() {
15151 return ( defined( 'DOING_AJAX' ) && DOING_AJAX );
15152 }
15153
15154 /**
15155 * Check if it's an AJAX call targeted for the current module.
15156 *
15157 * @author Vova Feldman (@svovaf)
15158 * @since 1.2.0
15159 *
15160 * @param array|string $actions Collection of AJAX actions.
15161 *
15162 * @return bool
15163 */
15164 function is_ajax_action( $actions ) {
15165 // Verify it's an ajax call.
15166 if ( ! self::is_ajax() ) {
15167 return false;
15168 }
15169
15170 // Verify the call is relevant for the plugin.
15171 if ( $this->_module_id != fs_request_get( 'module_id' ) ) {
15172 return false;
15173 }
15174
15175 // Verify it's one of the specified actions.
15176 if ( is_string( $actions ) ) {
15177 $actions = explode( ',', $actions );
15178 }
15179
15180 if ( is_array( $actions ) && 0 < count( $actions ) ) {
15181 $ajax_action = fs_request_get( 'action' );
15182
15183 foreach ( $actions as $action ) {
15184 if ( $ajax_action === $this->get_action_tag( $action ) ) {
15185 return true;
15186 }
15187 }
15188 }
15189
15190 return false;
15191 }
15192
15193 /**
15194 * Check if it's an AJAX call targeted for current request.
15195 *
15196 * @author Vova Feldman (@svovaf)
15197 * @since 1.2.0
15198 *
15199 * @param array|string $actions Collection of AJAX actions.
15200 * @param number|null $module_id
15201 *
15202 * @return bool
15203 */
15204 static function is_ajax_action_static( $actions, $module_id = null ) {
15205 // Verify it's an ajax call.
15206 if ( ! self::is_ajax() ) {
15207 return false;
15208 }
15209
15210
15211 if ( ! empty( $module_id ) ) {
15212 // Verify the call is relevant for the plugin.
15213 if ( $module_id != fs_request_get( 'module_id' ) ) {
15214 return false;
15215 }
15216 }
15217
15218 // Verify it's one of the specified actions.
15219 if ( is_string( $actions ) ) {
15220 $actions = explode( ',', $actions );
15221 }
15222
15223 if ( is_array( $actions ) && 0 < count( $actions ) ) {
15224 $ajax_action = fs_request_get( 'action' );
15225
15226 foreach ( $actions as $action ) {
15227 if ( $ajax_action === self::get_ajax_action_static( $action, $module_id ) ) {
15228 return true;
15229 }
15230 }
15231 }
15232
15233 return false;
15234 }
15235
15236 /**
15237 * @author Vova Feldman (@svovaf)
15238 * @since 1.1.7
15239 *
15240 * @return bool
15241 */
15242 static function is_cron() {
15243 return ( defined( 'DOING_CRON' ) && DOING_CRON );
15244 }
15245
15246 /**
15247 * @author Leo Fajardo (@leorw)
15248 * @since 2.5.0
15249 *
15250 * @return bool
15251 */
15252 static function is_admin_post() {
15253 return ( 'admin-post.php' === self::get_current_page() );
15254 }
15255
15256 /**
15257 * Check if a real user is visiting the admin dashboard.
15258 *
15259 * @author Vova Feldman (@svovaf)
15260 * @since 1.1.7
15261 *
15262 * @return bool
15263 */
15264 function is_user_in_admin() {
15265 return (
15266 is_admin() &&
15267 ! self::is_ajax() &&
15268 ! self::is_cron() &&
15269 ! self::is_admin_post()
15270 );
15271 }
15272
15273 /**
15274 * Check if a real user is in the customizer view.
15275 *
15276 * @author Vova Feldman (@svovaf)
15277 * @since 1.2.2.7
15278 *
15279 * @return bool
15280 */
15281 static function is_customizer() {
15282 return is_customize_preview();
15283 }
15284
15285 /**
15286 * Check if running in HTTPS and if site's plan matching the specified plan.
15287 *
15288 * @param string $plan
15289 * @param bool $exact
15290 *
15291 * @return bool
15292 */
15293 function is_ssl_and_plan( $plan, $exact = false ) {
15294 return ( $this->is_ssl() && $this->is_plan( $plan, $exact ) );
15295 }
15296
15297 /**
15298 * Construct plugin's settings page URL.
15299 *
15300 * @author Vova Feldman (@svovaf)
15301 * @since 1.0.4
15302 *
15303 * @param string $page
15304 * @param array $params
15305 * @param bool|null $network
15306 *
15307 * @return string
15308 */
15309 function _get_admin_page_url( $page = '', $params = array(), $network = null ) {
15310 if ( is_null( $network ) ) {
15311 $network = (
15312 $this->_is_network_active &&
15313 ( fs_is_network_admin() || ! $this->is_delegated_connection() )
15314 );
15315 }
15316
15317 if ( 0 < count( $params ) ) {
15318 foreach ( $params as $k => $v ) {
15319 $params[ $k ] = urlencode( $v );
15320 }
15321 }
15322
15323 $page_param = $this->_menu->get_slug( $page );
15324
15325 if ( empty( $page ) &&
15326 // Show the opt-in as an overlay for free wp.org themes or themes without any settings page.
15327 $this->show_opt_in_on_themes_page()
15328 ) {
15329 $params[ $this->get_unique_affix() . '_show_optin' ] = 'true';
15330
15331 return add_query_arg(
15332 $params,
15333 $this->admin_url( 'themes.php', 'admin', $network )
15334 );
15335 }
15336
15337 if ( ! $this->has_settings_menu() ) {
15338 if ( ! empty( $page ) ) {
15339 // Module doesn't have a setting page, but since the request is for
15340 // a specific Freemius page, use the admin.php path.
15341 return add_query_arg( array_merge( $params, array(
15342 'page' => $page_param,
15343 ) ), $this->admin_url( 'admin.php', 'admin', $network ) );
15344 } else {
15345 if ( $this->is_activation_mode() ) {
15346 /**
15347 * @author Vova Feldman
15348 * @since 1.2.1.6
15349 *
15350 * If plugin doesn't have a settings page, create one for the opt-in screen.
15351 */
15352 return add_query_arg( array_merge( $params, array(
15353 'page' => $this->_slug,
15354 ) ), $this->admin_url( 'admin.php', 'admin', $network ) );
15355 } else {
15356 // Plugin without a settings page.
15357 return add_query_arg(
15358 $params,
15359 $this->admin_url( 'plugins.php', 'admin', $network )
15360 );
15361 }
15362 }
15363 }
15364
15365 // Module has a submenu settings page.
15366 if ( ! $this->_menu->is_top_level() ) {
15367 $parent_slug = $this->_menu->get_parent_slug();
15368 $menu_file = ( false !== strpos( $parent_slug, '.php' ) ) ?
15369 $parent_slug :
15370 'admin.php';
15371
15372 return add_query_arg( array_merge( $params, array(
15373 'page' => $page_param,
15374 ) ), $this->admin_url( $menu_file, 'admin', $network ) );
15375 }
15376
15377 // Module has a top level CPT settings page.
15378 if ( $this->_menu->is_cpt() ) {
15379 if ( empty( $page ) && $this->is_activation_mode() ) {
15380 return add_query_arg( array_merge( $params, array(
15381 'page' => $page_param
15382 ) ), $this->admin_url( 'admin.php', 'admin', $network ) );
15383 } else {
15384 if ( ! empty( $page ) ) {
15385 $params['page'] = $page_param;
15386 }
15387
15388 return add_query_arg(
15389 $params,
15390 $this->admin_url( $this->_menu->get_raw_slug(), 'admin', $network )
15391 );
15392 }
15393 }
15394
15395 // Module has a custom top level settings page.
15396 return add_query_arg( array_merge( $params, array(
15397 'page' => $page_param,
15398 ) ), $this->admin_url( 'admin.php', 'admin', $network ) );
15399 }
15400
15401 #--------------------------------------------------------------------------------
15402 #region Multisite
15403 #--------------------------------------------------------------------------------
15404
15405 /**
15406 * @author Leo Fajardo (@leorw)
15407 * @since 2.0.0
15408 *
15409 * @return bool
15410 */
15411 function is_network_active() {
15412 return $this->_is_network_active;
15413 }
15414
15415 /**
15416 * Delegate activation for the given sites in the network (or all sites if `null`) to site admins.
15417 *
15418 * @author Leo Fajardo (@leorw)
15419 * @since 2.0.0
15420 *
15421 * @param bool|int[] $all_or_blog_ids
15422 */
15423 private function delegate_connection( $all_or_blog_ids = true ) {
15424 $this->_logger->entrance();
15425
15426 $this->_admin_notices->remove_sticky( 'connect_account' );
15427
15428 if ( true === $all_or_blog_ids ) {
15429 // All sites delegation.
15430 $this->_storage->store( 'is_delegated_connection', true, true );
15431 } else {
15432 // Specified sites delegation.
15433 foreach ( $all_or_blog_ids as $blog_id ) {
15434 $this->delegate_site_connection( $blog_id );
15435 }
15436 }
15437
15438 $this->network_upgrade_mode_completed();
15439 }
15440
15441 /**
15442 * Delegate specific network site conncetion to the site admin.
15443 *
15444 * @author Vova Feldman (@svovaf)
15445 * @since 2.0.0
15446 *
15447 * @param int $blog_id
15448 */
15449 private function delegate_site_connection( $blog_id ) {
15450 $this->_storage->store( 'is_delegated_connection', true, $blog_id );
15451 }
15452
15453 /**
15454 * Check if super-admin delegated the connection of ALL sites to the site admins.
15455 *
15456 * @author Vova Feldman (@svovaf)
15457 * @since 2.0.0
15458 *
15459 * @return bool
15460 */
15461 function is_network_delegated_connection() {
15462 if ( ! $this->_is_network_active ) {
15463 return false;
15464 }
15465
15466 return $this->_storage->get( 'is_delegated_connection', false, true );
15467 }
15468
15469 /**
15470 * @author Leo Fajardo (@leorw)
15471 * @since 2.0.0
15472 *
15473 * @param int $blog_id
15474 *
15475 * @return bool
15476 */
15477 function is_site_delegated_connection( $blog_id = 0 ) {
15478 if ( ! $this->_is_network_active ) {
15479 return false;
15480 }
15481
15482 if ( 0 == $blog_id ) {
15483 $blog_id = get_current_blog_id();
15484 }
15485
15486 return $this->_storage->get( 'is_delegated_connection', false, $blog_id );
15487 }
15488
15489 /**
15490 * Check if delegated the connection. When running within the network admin,
15491 * and haven't specified the blog ID, checks if network level delegated. If running
15492 * within a site admin or specified a blog ID, check if delegated the connection for
15493 * the current context site.
15494 *
15495 * If executed outside the the admin, check if delegated the connection
15496 * for the current context site OR the whole network.
15497 *
15498 * @author Vova Feldman (@svovaf)
15499 * @since 2.0.0
15500 *
15501 * @param int $blog_id If set, checks if network delegated or blog specific delegated.
15502 *
15503 * @return bool
15504 */
15505 function is_delegated_connection( $blog_id = 0 ) {
15506 if ( ! $this->_is_network_active ) {
15507 return false;
15508 }
15509
15510 if ( fs_is_network_admin() && 0 == $blog_id ) {
15511 return $this->is_network_delegated_connection();
15512 }
15513
15514 return (
15515 $this->is_network_delegated_connection() ||
15516 $this->is_site_delegated_connection( $blog_id )
15517 );
15518 }
15519
15520 /**
15521 * Check if the current module is active for the site.
15522 *
15523 * @author Vova Feldman (@svovaf)
15524 * @since 2.0.0
15525 *
15526 * @param int $blog_id
15527 *
15528 * @return bool
15529 */
15530 function is_active_for_site( $blog_id ) {
15531 if ( ! is_multisite() ) {
15532 // Not a multisite and this code is executed, means that the plugin is active.
15533 return true;
15534 }
15535
15536 if ( $this->is_theme() ) {
15537 // All themes are site level activated.
15538 return true;
15539 }
15540
15541 if ( $this->_is_network_active ) {
15542 // Plugin was network activated so it's active.
15543 return true;
15544 }
15545
15546 return in_array( $this->_plugin_basename, (array) get_blog_option( $blog_id, 'active_plugins', array() ) );
15547 }
15548
15549 /**
15550 * @todo Implement pagination when accessing the subsites collection.
15551 *
15552 * @author Leo Fajardo (@leorw)
15553 * @since 2.0.0
15554 *
15555 * @param int $limit Default to 1,000
15556 * @param int $offset Default to 0
15557 *
15558 * @return array Active & public sites collection.
15559 */
15560 static function get_sites( $limit = 1000, $offset = 0 ) {
15561 if ( ! is_multisite() ) {
15562 return array();
15563 }
15564
15565 /**
15566 * For consistency with get_blog_list() which only return active public sites.
15567 *
15568 * @author Vova Feldman (@svovaf)
15569 */
15570 $args = array(
15571 /**
15572 * Commented out in order to handle the migration of site options whether the site is public or not.
15573 *
15574 * @author Leo Fajardo (@leorw)
15575 * @since 2.2.1
15576 */
15577 // 'public' => 1,
15578 'archived' => 0,
15579 'mature' => 0,
15580 'spam' => 0,
15581 'deleted' => 0,
15582 'number' => $limit,
15583 'offset' => $offset,
15584 );
15585
15586 return get_sites( $args );
15587 }
15588
15589 /**
15590 * Checks if a given blog is active.
15591 *
15592 * @author Vova Feldman (@svovaf)
15593 * @since 2.0.0
15594 *
15595 * @param $blog_id
15596 *
15597 * @return bool
15598 */
15599 private static function is_site_active( $blog_id ) {
15600 global $wpdb;
15601
15602 $blog_info = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM {$wpdb->blogs} WHERE blog_id = %d", $blog_id ) );
15603
15604 if ( ! is_object( $blog_info ) ) {
15605 return false;
15606 }
15607
15608 return (
15609 true == $blog_info->public &&
15610 false == $blog_info->archived &&
15611 false == $blog_info->mature &&
15612 false == $blog_info->spam &&
15613 false == $blog_info->deleted
15614 );
15615 }
15616
15617 /**
15618 * Get a mapping between the site addresses to their blog IDs.
15619 *
15620 * @author Vova Feldman (@svovaf)
15621 * @since 2.0.0
15622 *
15623 * @return array {
15624 * @key string Site address without protocol with a trailing slash.
15625 * @value int Site's blog ID.
15626 * }
15627 */
15628 private function get_address_to_blog_map() {
15629 $sites = self::get_sites();
15630
15631 // Map site addresses to their blog IDs.
15632 $address_to_blog_map = array();
15633 foreach ( $sites as $site ) {
15634 $blog_id = self::get_site_blog_id( $site );
15635 $address = self::get_unfiltered_site_url( $blog_id, true, true );
15636 $address_to_blog_map[ $address ] = $blog_id;
15637 }
15638
15639 return $address_to_blog_map;
15640 }
15641
15642 /**
15643 * Get a mapping between the site addresses to their blog IDs.
15644 *
15645 * @author Vova Feldman (@svovaf)
15646 * @since 2.0.0
15647 *
15648 * @return array {
15649 * @key int Site's blog ID.
15650 * @value FS_Site Associated install.
15651 * }
15652 */
15653 function get_blog_install_map() {
15654 $sites = self::get_sites();
15655
15656 // Map site blog ID to its install.
15657 $install_map = array();
15658
15659 foreach ( $sites as $site ) {
15660 $blog_id = self::get_site_blog_id( $site );
15661 $install = $this->get_install_by_blog_id( $blog_id );
15662
15663 if ( is_object( $install ) ) {
15664 $install_map[ $blog_id ] = $install;
15665 }
15666 }
15667
15668 return $install_map;
15669 }
15670
15671 /**
15672 * @author Vova Feldman (@svovaf)
15673 * @since 2.5.1
15674 *
15675 * @param bool|null $is_delegated When `true`, returns only connection delegated blog IDs. When `false`, only non-delegated blog IDs.
15676 *
15677 * @return int[]
15678 */
15679 private function get_blog_ids( $is_delegated = null ) {
15680 $blog_ids = array();
15681
15682 $sites = self::get_sites();
15683 foreach ( $sites as $site ) {
15684 $blog_id = self::get_site_blog_id( $site );
15685
15686 if (
15687 is_null( $is_delegated ) ||
15688 $is_delegated === $this->is_site_delegated_connection( $blog_id )
15689 ) {
15690 $blog_ids[] = $blog_id;
15691 }
15692 }
15693
15694 return $blog_ids;
15695 }
15696
15697 /**
15698 * @author Vova Feldman (@svovaf)
15699 * @since 2.5.1
15700 *
15701 * @return int[]
15702 */
15703 private function get_non_delegated_blog_ids() {
15704 return $this->get_blog_ids( false );
15705 }
15706
15707 /**
15708 * Gets a map of module IDs that the given user has opted-in to.
15709 *
15710 * @author Leo Fajardo (@leorw)
15711 * @since 2.1.0
15712 *
15713 * @param number $fs_user_id
15714 *
15715 * @return array {
15716 * @key number $plugin_id
15717 * @value bool Always true.
15718 * }
15719 */
15720 private static function get_user_opted_in_module_ids_map( $fs_user_id ) {
15721 self::$_static_logger->entrance();
15722
15723 if ( ! is_multisite() ) {
15724 $installs = array_merge(
15725 self::get_all_sites( WP_FS__MODULE_TYPE_PLUGIN ),
15726 self::get_all_sites( WP_FS__MODULE_TYPE_THEME )
15727 );
15728 } else {
15729 $sites = self::get_sites();
15730
15731 $installs = array();
15732 foreach ( $sites as $site ) {
15733 $blog_id = self::get_site_blog_id( $site );
15734
15735 $installs = array_merge(
15736 $installs,
15737 self::get_all_sites( WP_FS__MODULE_TYPE_PLUGIN, $blog_id ),
15738 self::get_all_sites( WP_FS__MODULE_TYPE_THEME, $blog_id )
15739 );
15740 }
15741 }
15742
15743 $module_ids_map = array();
15744 foreach ( $installs as $install ) {
15745 if ( is_object( $install ) &&
15746 FS_Site::is_valid_id( $install->id ) &&
15747 FS_User::is_valid_id( $install->user_id ) &&
15748 ( $install->user_id == $fs_user_id )
15749 ) {
15750 $module_ids_map[ $install->plugin_id ] = true;
15751 }
15752 }
15753
15754 return $module_ids_map;
15755 }
15756
15757 /**
15758 * @author Leo Fajardo (@leorw)
15759 *
15760 * @return null|array {
15761 * 'install' => FS_Site Module's install,
15762 * 'blog_id' => string The associated blog ID.
15763 * }
15764 */
15765 function find_first_install() {
15766 $sites = self::get_sites();
15767
15768 foreach ( $sites as $site ) {
15769 $blog_id = self::get_site_blog_id( $site );
15770 $install = $this->get_install_by_blog_id( $blog_id );
15771
15772 if ( is_object( $install ) ) {
15773 return array(
15774 'install' => $install,
15775 'blog_id' => $blog_id
15776 );
15777 }
15778 }
15779
15780 return null;
15781 }
15782
15783 /**
15784 * Switches the Freemius site level context to a specified blog.
15785 *
15786 * @author Vova Feldman (@svovaf)
15787 * @since 2.0.0
15788 *
15789 * @param int $blog_id
15790 * @param FS_Site $install
15791 * @param bool $flush
15792 *
15793 * @return bool Since 2.3.1 returns if a switch was made.
15794 */
15795 function switch_to_blog( $blog_id, FS_Site $install = null, $flush = false ) {
15796 if ( ! is_numeric( $blog_id ) ) {
15797 return false;
15798 }
15799
15800 if ( ! $flush && $blog_id == $this->_context_is_network_or_blog_id ) {
15801 return false;
15802 }
15803
15804 switch_to_blog( $blog_id );
15805 $this->_context_is_network_or_blog_id = $blog_id;
15806
15807 self::$_accounts->set_site_blog_context( $blog_id );
15808 $this->_storage->set_site_blog_context( $blog_id );
15809 $this->_storage->set_network_active( $this->_is_network_active, $this->is_delegated_connection( $blog_id ) );
15810
15811 $this->_site = is_object( $install ) ?
15812 $install :
15813 $this->get_install_by_blog_id( $blog_id );
15814
15815 $this->_user = false;
15816 $this->_licenses = false;
15817 $this->_license = null;
15818 $this->is_whitelabeled = null;
15819
15820 if ( is_object( $this->_site ) ) {
15821 // Try to fetch user from install.
15822 $this->_user = self::_get_user_by_id( $this->_site->user_id );
15823
15824 if ( ! is_object( $this->_user ) &&
15825 FS_User::is_valid_id( $this->_storage->prev_user_id )
15826 ) {
15827 // Try to fetch previously saved user.
15828 $this->_user = self::_get_user_by_id( $this->_storage->prev_user_id );
15829
15830 if ( ! is_object( $this->_user ) ) {
15831 // Fallback to network's user.
15832 $this->_user = $this->get_network_user();
15833 }
15834 }
15835
15836 $all_plugin_licenses = self::get_all_licenses( $this->_module_id );
15837
15838 if ( ! empty( $all_plugin_licenses ) ) {
15839 if ( ! FS_Plugin_License::is_valid_id( $this->_site->license_id ) ) {
15840 $this->_license = null;
15841 } else {
15842 $license_found = false;
15843 foreach ( $all_plugin_licenses as $license ) {
15844 if ( $license->id == $this->_site->license_id ) {
15845 // License found.
15846 $this->_license = $license;
15847 $license_found = true;
15848 break;
15849 }
15850 }
15851
15852 if ( $license_found ) {
15853 $this->link_license_2_user( $this->_license->id, $this->_user->id );
15854 }
15855 }
15856
15857 $this->_licenses = $this->get_user_licenses( $this->_user->id );
15858 }
15859 }
15860
15861 unset( $this->_site_api );
15862 unset( $this->_user_api );
15863
15864 return true;
15865 }
15866
15867 /**
15868 * Restore the blog context to the blog that originally loaded the module.
15869 *
15870 * @author Vova Feldman (@svovaf)
15871 * @since 2.0.0
15872 */
15873 function restore_current_blog() {
15874 $this->switch_to_blog( $this->_blog_id );
15875 }
15876
15877 /**
15878 * @author Vova Feldman (@svovaf)
15879 * @since 2.0.0
15880 *
15881 * @param array|WP_Site $site
15882 *
15883 * @return int
15884 */
15885 static function get_site_blog_id( &$site ) {
15886 return ( $site instanceof WP_Site ) ?
15887 $site->blog_id :
15888 ( is_object( $site ) && isset( $site->userblog_id ) ?
15889 $site->userblog_id :
15890 $site['blog_id'] );
15891 }
15892
15893 /**
15894 * @author Vova Feldman (@svovaf)
15895 * @since 2.5.1
15896 *
15897 * @param WP_Site[]|array[] $sites
15898 *
15899 * @return int[]
15900 */
15901 static function get_sites_blog_ids( $sites ) {
15902 $blog_ids = array();
15903 foreach ( $sites as $site ) {
15904 $blog_ids[] = self::get_site_blog_id( $site );
15905 }
15906
15907 return $blog_ids;
15908 }
15909
15910 /**
15911 * @author Leo Fajardo (@leorw)
15912 * @since 2.0.0
15913 *
15914 * @param array|WP_Site|null $site
15915 * @param bool $load_registration Since 2.5.1 When set to `true` the method will attempt to return the subsite's registration date, regardless of the `$site` type and value. In most calls, the registration date will be returned anyway, even when the value is `false`. This param is purely for performance optimization.
15916 *
15917 * @return array
15918 */
15919 function get_site_info( $site = null, $load_registration = false ) {
15920 $this->_logger->entrance();
15921
15922 $switched = false;
15923
15924 $registration_date = null;
15925
15926 if ( is_null( $site ) ) {
15927 $url = self::get_unfiltered_site_url();
15928 $name = get_bloginfo( 'name' );
15929 $blog_id = null;
15930 } else {
15931 $blog_id = self::get_site_blog_id( $site );
15932
15933 if ( get_current_blog_id() != $blog_id ) {
15934 switch_to_blog( $blog_id );
15935 $switched = true;
15936 }
15937
15938 if ( $site instanceof WP_Site ) {
15939 $url = $site->siteurl;
15940 $name = $site->blogname;
15941 $registration_date = $site->registered;
15942 } else {
15943 $url = self::get_unfiltered_site_url( $blog_id );
15944 $name = get_bloginfo( 'name' );
15945 }
15946 }
15947
15948 if ( empty( $registration_date ) && $load_registration ) {
15949 $blog_details = get_blog_details( $blog_id, false );
15950
15951 if ( is_object( $blog_details ) && isset( $blog_details->registered ) ) {
15952 $registration_date = $blog_details->registered;
15953 }
15954 }
15955
15956 $info = array(
15957 'uid' => $this->get_anonymous_id( $blog_id ),
15958 'url' => $url,
15959 );
15960
15961 // Add these diagnostic information only if user allowed to track.
15962 if ( FS_Permission_Manager::instance( $this )->is_diagnostic_tracking_allowed() ) {
15963 $info = array_merge( $info, array(
15964 'title' => $name,
15965 'language' => self::get_sanitized_language(),
15966 ) );
15967 }
15968
15969 if ( is_numeric( $blog_id ) ) {
15970 $info['blog_id'] = $blog_id;
15971 }
15972
15973 if ( ! empty( $registration_date ) ) {
15974 $info[ 'registration_date' ] = $registration_date;
15975 }
15976
15977 if ( $switched ) {
15978 restore_current_blog();
15979 }
15980
15981 return $info;
15982 }
15983
15984 /**
15985 * Load the module's install based on the blog ID.
15986 *
15987 * @author Vova Feldman (@svovaf)
15988 * @since 2.0.0
15989 *
15990 * @param int|null $blog_id
15991 *
15992 * @return FS_Site
15993 */
15994 function get_install_by_blog_id( $blog_id = null ) {
15995 $installs = self::get_all_sites( $this->_module_type, $blog_id );
15996 $install = isset( $installs[ $this->_slug ] ) ? $installs[ $this->_slug ] : null;
15997
15998 if ( is_object( $install ) &&
15999 is_numeric( $install->id ) &&
16000 is_numeric( $install->user_id ) &&
16001 FS_Plugin_Plan::is_valid_id( $install->plan_id )
16002 ) {
16003 // Load site.
16004 $install = clone $install;
16005 }
16006
16007 return $install;
16008 }
16009
16010 /**
16011 * Check if module is installed on a specified site.
16012 *
16013 * @author Vova Feldman (@svovaf)
16014 * @since 2.0.0
16015 *
16016 * @param int|null $blog_id
16017 *
16018 * @return bool
16019 */
16020 function is_installed_on_site( $blog_id = null ) {
16021 $installs = self::get_all_sites( $this->_module_type, $blog_id );
16022 $install = isset( $installs[ $this->_slug ] ) ? $installs[ $this->_slug ] : null;
16023
16024 return (
16025 is_object( $install ) &&
16026 is_numeric( $install->id ) &&
16027 is_numeric( $install->user_id ) &&
16028 FS_Plugin_Plan::is_valid_id( $install->plan_id )
16029 );
16030 }
16031
16032 /**
16033 * Check if super-admin connected at least one site via the network opt-in.
16034 *
16035 * @author Vova Feldman (@svovaf)
16036 * @since 2.0.0
16037 *
16038 * @return bool
16039 */
16040 function is_network_registered() {
16041 if ( ! $this->_is_network_active ) {
16042 return false;
16043 }
16044
16045 return FS_User::is_valid_id( $this->_storage->network_user_id );
16046 }
16047
16048 /**
16049 * Returns the main user associated with the network.
16050 *
16051 * @author Vova Feldman (@svovaf)
16052 * @since 2.0.0
16053 *
16054 * @return FS_User
16055 */
16056 function get_network_user() {
16057 if ( ! $this->_is_network_active ) {
16058 return null;
16059 }
16060
16061 return FS_User::is_valid_id( $this->_storage->network_user_id ) ?
16062 self::_get_user_by_id( $this->_storage->network_user_id ) :
16063 null;
16064 }
16065
16066 /**
16067 * Returns the current context user or the network's main user.
16068 *
16069 * @author Vova Feldman (@svovaf)
16070 * @since 2.0.0
16071 *
16072 * @return FS_User
16073 */
16074 function get_current_or_network_user() {
16075 return ( $this->_user instanceof FS_User ) ?
16076 $this->_user :
16077 $this->get_network_user();
16078 }
16079
16080 /**
16081 * Returns the main install associated with the network.
16082 *
16083 * @author Vova Feldman (@svovaf)
16084 * @since 2.0.0
16085 *
16086 * @return FS_Site
16087 */
16088 function get_network_install() {
16089 if ( ! $this->_is_network_active ) {
16090 return null;
16091 }
16092
16093 return FS_Site::is_valid_id( $this->_storage->network_install_blog_id ) ?
16094 $this->get_install_by_blog_id( $this->_storage->network_install_blog_id ) :
16095 null;
16096 }
16097
16098 /**
16099 * Returns the blog ID that is associated with the main install.
16100 *
16101 * @author Leo Fajardo (@leorw)
16102 * @since 2.0.0
16103 *
16104 * @return int|null
16105 */
16106 function get_network_install_blog_id() {
16107 if ( ! $this->_is_network_active ) {
16108 return null;
16109 }
16110
16111 return FS_Site::is_valid_id( $this->_storage->network_install_blog_id ) ?
16112 $this->_storage->network_install_blog_id :
16113 null;
16114 }
16115
16116 /**
16117 * Returns the current context install or the network's main install.
16118 *
16119 * @author Vova Feldman (@svovaf)
16120 * @since 2.0.0
16121 *
16122 * @return FS_Site
16123 */
16124 function get_current_or_network_install() {
16125 return ( $this->_site instanceof FS_Site ) ?
16126 $this->_site :
16127 $this->get_network_install();
16128 }
16129
16130 /**
16131 * Check if executing a site level action from the network level admin.
16132 *
16133 * @author Vova Feldman (@svovaf)
16134 * @since 2.0.0
16135 *
16136 * @return false|int If yes, return the requested blog ID.
16137 */
16138 private function is_network_level_site_specific_action() {
16139 if ( ! $this->_is_network_active ) {
16140 return false;
16141 }
16142
16143 if ( ! fs_is_network_admin() ) {
16144 return false;
16145 }
16146
16147 $blog_id = fs_request_get( 'blog_id', '' );
16148
16149 return is_numeric( $blog_id ) ? $blog_id : false;
16150 }
16151
16152 /**
16153 * Check if executing an action from the network level admin.
16154 *
16155 * @author Vova Feldman (@svovaf)
16156 * @since 2.0.0
16157 *
16158 * @return bool
16159 */
16160 private function is_network_level_action() {
16161 return ( $this->_is_network_active && fs_is_network_admin() );
16162 }
16163
16164 /**
16165 * Needs to be executed after site deactivation, archive, deletion, or flag as spam.
16166 * The logic updates the network level user and blog, and reschedule the crons if the cron executing site matching the site that is no longer publicly active.
16167 *
16168 * @author Vova Feldman (@svovaf)
16169 * @since 2.0.0
16170 *
16171 * @param int $context_blog_id
16172 */
16173 private function update_multisite_data_after_site_deactivation( $context_blog_id = 0 ) {
16174 $this->_logger->entrance();
16175
16176 if ( $this->_is_network_active ) {
16177 if ( $context_blog_id == $this->_storage->network_install_blog_id ) {
16178 $installs_map = $this->get_blog_install_map();
16179
16180 foreach ( $installs_map as $blog_id => $install ) {
16181 /**
16182 * @var FS_Site $install
16183 */
16184 if ( $context_blog_id == $blog_id ) {
16185 continue;
16186 }
16187
16188 if ( $install->user_id != $this->_storage->network_user_id ) {
16189 continue;
16190 }
16191
16192 // Switch reference to a blog that is opted-in and belong to the same super-admin.
16193 $this->_storage->network_install_blog_id = $blog_id;
16194 break;
16195 }
16196 }
16197 }
16198
16199 if ( ! $this->is_registered() ) {
16200 return;
16201 }
16202
16203 if ( $this->is_sync_cron_scheduled() &&
16204 $context_blog_id == $this->get_sync_cron_blog_id()
16205 ) {
16206 $this->schedule_sync_cron( WP_FS__SCRIPT_START_TIME, true, $context_blog_id );
16207 }
16208
16209 if ( $this->is_install_sync_scheduled() &&
16210 $context_blog_id == $this->get_install_sync_cron_blog_id()
16211 ) {
16212 $this->schedule_install_sync( $context_blog_id );
16213 }
16214 }
16215
16216 /**
16217 * Executed after site deactivation, archive, or flag as spam.
16218 *
16219 * @author Vova Feldman (@svovaf)
16220 * @since 2.0.0
16221 *
16222 * @param int $context_blog_id
16223 */
16224 public function _after_site_deactivated_callback( $context_blog_id = 0 ) {
16225 $this->_logger->entrance();
16226
16227 $install = $this->get_install_by_blog_id( $context_blog_id );
16228
16229 if ( ! is_object( $install ) ) {
16230 // Site not connected.
16231 return;
16232 }
16233
16234 $this->update_multisite_data_after_site_deactivation( $context_blog_id );
16235
16236 if ( ! $this->is_registered() ) {
16237 return;
16238 }
16239
16240 $current_blog_id = get_current_blog_id();
16241
16242 $this->switch_to_blog( $context_blog_id );
16243
16244 // Send deactivation event.
16245 $this->sync_install( array(
16246 'is_active' => false,
16247 ) );
16248
16249 $this->switch_to_blog( $current_blog_id );
16250 }
16251
16252 /**
16253 * Executed after site deletion.
16254 *
16255 * @author Vova Feldman (@svovaf)
16256 * @since 2.0.0
16257 *
16258 * @param int $context_blog_id
16259 * @param bool $drop True if site's database tables should be dropped. Default is false.
16260 */
16261 public function _after_site_deleted_callback( $context_blog_id = 0, $drop = false ) {
16262 $this->_logger->entrance();
16263
16264 $install = $this->get_install_by_blog_id( $context_blog_id );
16265
16266 if ( ! is_object( $install ) ) {
16267 // Site not connected.
16268 return;
16269 }
16270
16271 $this->update_multisite_data_after_site_deactivation( $context_blog_id );
16272
16273 if ( ! $this->is_registered() ) {
16274 return;
16275 }
16276
16277 $current_blog_id = get_current_blog_id();
16278
16279 $this->switch_to_blog( $context_blog_id );
16280
16281 if ( $drop ) {
16282 // Delete install if dropping site DB.
16283 $this->delete_account_event();
16284 } else {
16285 // Send deactivation event.
16286 $this->sync_install( array(
16287 'is_active' => false,
16288 ) );
16289 }
16290
16291 $this->switch_to_blog( $current_blog_id );
16292 }
16293
16294 /**
16295 * Executed after site deletion, called from wp_delete_site
16296 *
16297 * @author Dario Curvino (@dudo)
16298 * @since 2.5.0
16299 *
16300 * @param WP_Site $old_site
16301 */
16302 public function _after_wpsite_deleted_callback( WP_Site $old_site ) {
16303 $this->_logger->entrance();
16304
16305 $this->_after_site_deleted_callback( $old_site->blog_id, true );
16306 }
16307
16308 /**
16309 * Executed after site re-activation.
16310 *
16311 * @author Vova Feldman (@svovaf)
16312 * @since 2.0.0
16313 *
16314 * @param int $context_blog_id
16315 */
16316 public function _after_site_reactivated_callback( $context_blog_id = 0 ) {
16317 $this->_logger->entrance();
16318
16319 $install = $this->get_install_by_blog_id( $context_blog_id );
16320
16321 if ( ! is_object( $install ) ) {
16322 // Site not connected.
16323 return;
16324 }
16325
16326 if ( ! self::is_site_active( $context_blog_id ) ) {
16327 // Site not yet active (can be in spam mode, archived, deleted...).
16328 return;
16329 }
16330
16331 $current_blog_id = get_current_blog_id();
16332
16333 $this->switch_to_blog( $context_blog_id );
16334
16335 // Send re-activation event.
16336 $this->sync_install( array(
16337 'is_active' => true,
16338 ) );
16339
16340 $this->switch_to_blog( $current_blog_id );
16341 }
16342
16343 #endregion Multisite
16344
16345 /**
16346 * @author Leo Fajardo (@leorw)
16347 *
16348 * @param string $path
16349 * @param string $scheme
16350 * @param bool $network
16351 *
16352 * @return string
16353 */
16354 private function admin_url( $path = '', $scheme = 'admin', $network = true ) {
16355 return ( $this->_is_network_active && $network ) ?
16356 network_admin_url( $path, $scheme ) :
16357 admin_url( $path, $scheme );
16358 }
16359
16360 /**
16361 * Check if currently in a specified admin page.
16362 *
16363 * @author Vova Feldman (@svovaf)
16364 * @since 1.2.2.7
16365 *
16366 * @param string $page
16367 *
16368 * @return bool
16369 */
16370 function is_admin_page( $page ) {
16371 return ( $this->_menu->get_slug( $page ) === fs_request_get( 'page', '', 'get' ) );
16372 }
16373
16374 /**
16375 * Check if currently in the product's main admin page.
16376 *
16377 * @author Vova Feldman (@svovaf)
16378 * @since 2.3.1
16379 *
16380 * @return bool
16381 */
16382 function is_main_admin_page() {
16383 return $this->is_admin_page( '' );
16384 }
16385
16386 /**
16387 * Get module's main admin setting page URL.
16388 *
16389 * @author Vova Feldman (@svovaf)
16390 * @since 1.2.2.7
16391 *
16392 * @return string
16393 */
16394 function main_menu_url() {
16395 return $this->_menu->main_menu_url();
16396 }
16397
16398 /**
16399 * Check if currently on the theme's setting page or
16400 * on any of the Freemius added pages (via tabs).
16401 *
16402 * @author Vova Feldman (@svovaf)
16403 * @since 1.2.2.7
16404 *
16405 * @return bool
16406 *
16407 * @deprecated Please use is_product_settings_page() instead;
16408 */
16409 function is_theme_settings_page() {
16410 return $this->is_product_settings_page();
16411 }
16412
16413 /**
16414 * Check if currently on the product's main setting page or on any of the Freemius added pages (via tabs).
16415 *
16416 * @author Vova Feldman (@svovaf)
16417 * @since 1.2.2.7
16418 *
16419 * @return bool
16420 */
16421 function is_product_settings_page() {
16422 $page = fs_request_get( 'page', '', 'get' );
16423 $menu_slug = $this->_menu->get_slug();
16424
16425 if ( $page === $menu_slug ) {
16426 return true;
16427 }
16428
16429 return fs_starts_with(
16430 // e.g., {$menu_slug}-account, {$menu_slug}-affiliation, etc.
16431 $page,
16432 ( $menu_slug . '-' )
16433 );
16434 }
16435
16436 /**
16437 * Plugin's account page + sync license URL.
16438 *
16439 * @author Vova Feldman (@svovaf)
16440 * @since 1.1.9.1
16441 *
16442 * @param bool|number $plugin_id
16443 * @param bool $add_action_nonce
16444 * @param array $params
16445 *
16446 * @return string
16447 */
16448 function _get_sync_license_url( $plugin_id = false, $add_action_nonce = true, $params = array() ) {
16449 if ( is_numeric( $plugin_id ) ) {
16450 $params['plugin_id'] = $plugin_id;
16451 }
16452
16453 return $this->get_account_url(
16454 $this->get_unique_affix() . '_sync_license',
16455 $params,
16456 $add_action_nonce
16457 );
16458 }
16459
16460 /**
16461 * Plugin's account URL.
16462 *
16463 * @author Vova Feldman (@svovaf)
16464 * @since 1.0.4
16465 *
16466 * @param bool|string $action
16467 * @param array $params
16468 *
16469 * @param bool $add_action_nonce
16470 *
16471 * @return string
16472 */
16473 function get_account_url( $action = false, $params = array(), $add_action_nonce = true ) {
16474 if ( is_string( $action ) ) {
16475 $params['fs_action'] = $action;
16476 }
16477
16478 self::require_pluggable_essentials();
16479
16480 return ( $add_action_nonce && is_string( $action ) ) ?
16481 fs_nonce_url( $this->_get_admin_page_url( 'account', $params ), $action ) :
16482 $this->_get_admin_page_url( 'account', $params );
16483 }
16484
16485 /**
16486 * @author Vova Feldman (@svovaf)
16487 * @since 1.2.0
16488 *
16489 * @param string $tab
16490 * @param bool $action
16491 * @param array $params
16492 * @param bool $add_action_nonce
16493 *
16494 * @return string
16495 *
16496 * @uses get_account_url()
16497 */
16498 function get_account_tab_url( $tab, $action = false, $params = array(), $add_action_nonce = true ) {
16499 $params['tab'] = $tab;
16500
16501 return $this->get_account_url( $action, $params, $add_action_nonce );
16502 }
16503
16504 /**
16505 * Plugin's account URL.
16506 *
16507 * @author Vova Feldman (@svovaf)
16508 * @since 1.0.4
16509 *
16510 * @param bool|string $topic
16511 * @param bool|string $message
16512 * @param bool|string $summary Since 2.5.1.
16513 *
16514 * @return string
16515 */
16516 function contact_url( $topic = false, $message = false, $summary = false ) {
16517 $params = array();
16518 if ( is_string( $topic ) ) {
16519 $params['topic'] = $topic;
16520 }
16521 if ( is_string( $message ) ) {
16522 $params['message'] = $message;
16523 }
16524
16525 if ( is_string( $summary ) ) {
16526 $params['summary'] = $summary;
16527 }
16528
16529 if ( $this->is_addon() ) {
16530 $params['addon_id'] = $this->get_id();
16531
16532 return $this->get_parent_instance()->_get_admin_page_url( 'contact', $params );
16533 } else {
16534 return $this->_get_admin_page_url( 'contact', $params );
16535 }
16536 }
16537
16538 /**
16539 * Add-on direct info URL.
16540 *
16541 * @author Vova Feldman (@svovaf)
16542 * @since 1.1.0
16543 *
16544 * @param string $slug
16545 *
16546 * @return string
16547 */
16548 function addon_url( $slug ) {
16549 return $this->_get_admin_page_url( 'addons', array(
16550 'slug' => $slug
16551 ) );
16552 }
16553
16554 /**
16555 * Add-ons URL.
16556 *
16557 * @author Vova Feldman (@svovaf)
16558 * @since 2.4.5
16559 *
16560 * @return string
16561 */
16562 function get_addons_url() {
16563 return $this->_get_admin_page_url( 'addons' );
16564 }
16565
16566 /* Logger
16567 ------------------------------------------------------------------------------------------------------------------*/
16568 /**
16569 * @param string $id
16570 * @param bool $prefix_slug
16571 *
16572 * @return FS_Logger
16573 */
16574 function get_logger( $id = '', $prefix_slug = true ) {
16575 return FS_Logger::get_logger( ( $prefix_slug ? $this->_slug : '' ) . ( ( ! $prefix_slug || empty( $id ) ) ? '' : '_' ) . $id );
16576 }
16577
16578 /**
16579 * Note: This method is used externally so don't delete it.
16580 *
16581 * @param $id
16582 * @param bool $load_options
16583 * @param bool $prefix_slug
16584 *
16585 * @return FS_Option_Manager
16586 */
16587 function get_options_manager( $id, $load_options = false, $prefix_slug = true ) {
16588 return FS_Option_Manager::get_manager( ( $prefix_slug ? $this->_slug : '' ) . ( ( ! $prefix_slug || empty( $id ) ) ? '' : '_' ) . $id, $load_options );
16589 }
16590
16591 /* Security
16592 ------------------------------------------------------------------------------------------------------------------*/
16593 private static function _encrypt( $str ) {
16594 if ( is_null( $str ) ) {
16595 return null;
16596 }
16597
16598 /**
16599 * The encrypt/decrypt functions are used to protect
16600 * the user from messing up with some of the sensitive
16601 * data stored for the module as a JSON in the database.
16602 *
16603 * I used the same suggested hack by the theme review team.
16604 * For more details, look at the function `Base64UrlDecode()`
16605 * in `./sdk/FreemiusBase.php`.
16606 *
16607 * @todo Remove this hack once the base64 error is removed from the Theme Check.
16608 *
16609 * @author Vova Feldman (@svovaf)
16610 * @since 1.2.2
16611 */
16612 $fn = 'base64' . '_encode';
16613
16614 return $fn( $str );
16615 }
16616
16617 static function _decrypt( $str ) {
16618 if ( is_null( $str ) ) {
16619 return null;
16620 }
16621
16622 /**
16623 * The encrypt/decrypt functions are used to protect
16624 * the user from messing up with some of the sensitive
16625 * data stored for the module as a JSON in the database.
16626 *
16627 * I used the same suggested hack by the theme review team.
16628 * For more details, look at the function `Base64UrlDecode()`
16629 * in `./sdk/FreemiusBase.php`.
16630 *
16631 * @todo Remove this hack once the base64 error is removed from the Theme Check.
16632 *
16633 * @author Vova Feldman (@svovaf)
16634 * @since 1.2.2
16635 */
16636 $fn = 'base64' . '_decode';
16637
16638 return $fn( $str );
16639 }
16640
16641 /**
16642 * @author Vova Feldman (@svovaf)
16643 * @since 1.0.5
16644 *
16645 * @param FS_Entity $entity
16646 *
16647 * @return FS_Entity Return an encrypted clone entity.
16648 */
16649 private static function _encrypt_entity( FS_Entity $entity ) {
16650 $clone = clone $entity;
16651 $props = get_object_vars( $entity );
16652
16653 foreach ( $props as $key => $val ) {
16654 $clone->{$key} = self::_encrypt( $val );
16655 }
16656
16657 return $clone;
16658 }
16659
16660 /**
16661 * @author Vova Feldman (@svovaf)
16662 * @since 1.0.5
16663 *
16664 * @param FS_Entity $entity
16665 *
16666 * @return FS_Entity Return an decrypted clone entity.
16667 */
16668 private static function decrypt_entity( FS_Entity $entity ) {
16669 $clone = clone $entity;
16670 $props = get_object_vars( $entity );
16671
16672 foreach ( $props as $key => $val ) {
16673 $clone->{$key} = self::_decrypt( $val );
16674 }
16675
16676 return $clone;
16677 }
16678
16679 /**
16680 * Tries to activate account based on POST params.
16681 *
16682 * @author Vova Feldman (@svovaf)
16683 * @since 1.0.2
16684 *
16685 * @deprecated Not in use, outdated.
16686 */
16687 function _activate_account() {
16688 if ( $this->is_registered() ) {
16689 // Already activated.
16690 return;
16691 }
16692
16693 self::_clean_admin_content_section();
16694
16695 if ( fs_request_is_action( 'activate' ) && fs_request_is_post() ) {
16696 // check_admin_referer( 'activate_' . $this->_plugin->public_key );
16697
16698 // Verify matching plugin details.
16699 if ( $this->_plugin->id != fs_request_get( 'plugin_id' ) || $this->_slug != fs_request_get( 'plugin_slug' ) ) {
16700 return;
16701 }
16702
16703 $user = new FS_User();
16704 $user->id = fs_request_get( 'user_id' );
16705 $user->public_key = fs_request_get( 'user_public_key' );
16706 $user->secret_key = fs_request_get( 'user_secret_key' );
16707 $user->email = fs_request_get( 'user_email' );
16708 $user->first = fs_request_get( 'user_first' );
16709 $user->last = fs_request_get( 'user_last' );
16710 $user->is_verified = fs_request_get_bool( 'user_is_verified' );
16711
16712 $site = new FS_Site();
16713 $site->id = fs_request_get( 'install_id' );
16714 $site->public_key = fs_request_get( 'install_public_key' );
16715 $site->secret_key = fs_request_get( 'install_secret_key' );
16716 $site->plan_id = fs_request_get( 'plan_id' );
16717
16718 $plans = array();
16719 $plans_data = json_decode( urldecode( fs_request_get( 'plans' ) ) );
16720 foreach ( $plans_data as $p ) {
16721 $plan = new FS_Plugin_Plan( $p );
16722 if ( $site->plan_id == $plan->id ) {
16723 $plan->title = fs_request_get( 'plan_title' );
16724 $plan->name = fs_request_get( 'plan_name' );
16725 }
16726
16727 $plans[] = $plan;
16728 }
16729
16730 $this->_set_account( $user, $site, $plans );
16731
16732 // Reload the page with the keys.
16733 fs_redirect( $this->_get_admin_page_url() );
16734 }
16735 }
16736
16737 /**
16738 * @author Vova Feldman (@svovaf)
16739 * @since 1.0.7
16740 *
16741 * @param string $email
16742 *
16743 * @return FS_User|false
16744 */
16745 static function _get_user_by_email( $email ) {
16746 self::$_static_logger->entrance();
16747
16748 $email = trim( strtolower( $email ) );
16749
16750 $users = self::get_all_users();
16751
16752 if ( is_array( $users ) ) {
16753 foreach ( $users as $user ) {
16754 if ( $email === trim( strtolower( $user->email ) ) ) {
16755 return $user;
16756 }
16757 }
16758 }
16759
16760 return false;
16761 }
16762
16763 #----------------------------------------------------------------------------------
16764 #region Account (Loading, Updates & Activation)
16765 #----------------------------------------------------------------------------------
16766
16767 /***
16768 * Load account information (user + site).
16769 *
16770 * @author Vova Feldman (@svovaf)
16771 * @since 1.0.1
16772 */
16773 private function _load_account() {
16774 $this->_logger->entrance();
16775
16776 $this->do_action( 'before_account_load' );
16777
16778 $users = self::get_all_users();
16779 $plans = self::get_all_plans( $this->_module_type );
16780
16781 if ( $this->_logger->is_on() && is_admin() ) {
16782 $this->_logger->log( 'users = ' . var_export( $users, true ) );
16783 $this->_logger->log( 'plans = ' . var_export( $plans, true ) );
16784 }
16785
16786 $site = fs_is_network_admin() ?
16787 $this->get_network_install() :
16788 $this->get_install_by_blog_id();
16789
16790 if ( fs_is_network_admin() &&
16791 $this->is_network_active() &&
16792 ! is_object( $site ) &&
16793 FS_Site::is_valid_id( $this->_storage->network_install_blog_id )
16794 ) {
16795 $first_install = $this->find_first_install();
16796
16797 if ( is_null( $first_install ) ) {
16798 unset( $this->_storage->network_install_blog_id );
16799 } else {
16800 $site = $first_install['install'];
16801 $this->_storage->network_install_blog_id = $first_install['blog_id'];
16802 }
16803 }
16804
16805 if ( is_object( $site ) &&
16806 is_numeric( $site->id ) &&
16807 is_numeric( $site->user_id ) &&
16808 FS_Plugin_Plan::is_valid_id( $site->plan_id )
16809 ) {
16810 // Load site.
16811 $this->_site = $site;
16812 }
16813
16814 $user = null;
16815 if ( fs_is_network_admin() && $this->_is_network_active ) {
16816 $user = $this->get_network_user();
16817 }
16818
16819 if ( is_object( $user ) ) {
16820 $this->_user = clone $user;
16821 } else if ( $this->_site ) {
16822 $user = self::_get_user_by_id( $this->_site->user_id );
16823
16824 if ( ! is_object( $user ) && FS_User::is_valid_id( $this->_storage->prev_user_id ) ) {
16825 /**
16826 * Try to load the previous owner. This recovery is used for the following use-case:
16827 * 1. Opt-in
16828 * 2. Cloning site1 to site2
16829 * 3. Ownership switch in site1 (same applies for site2)
16830 * 4. Install data sync on site2
16831 * 5. Now site2's install is associated with the new owner which does not exists locally.
16832 */
16833 $user = self::_get_user_by_id( $this->_storage->prev_user_id );
16834 }
16835
16836 if ( ! is_object( $user ) ) {
16837 /**
16838 * This is a special fault tolerance mechanism to handle a scenario that the user data is missing.
16839 */
16840 if (
16841 ! isset( $this->_storage->user_recovery_from_install_last_attempt_timestamp ) ||
16842 time() > ( $this->_storage->user_recovery_from_install_last_attempt_timestamp + FS_Clone_Manager::CLONE_RESOLUTION_MAX_EXECUTION_TIME )
16843 ) {
16844 $user = $this->sync_user_by_current_install();
16845 } else {
16846 return;
16847 }
16848
16849 if ( is_object( $user ) ) {
16850 $this->_storage->user_was_recovered_from_install = true;
16851 } else {
16852 $this->_storage->user_recovery_from_install_attempts = isset( $this->_storage->user_recovery_from_install_attempts ) ?
16853 ( $this->_storage->user_recovery_from_install_attempts + 1 ) :
16854 1;
16855
16856 if ( $this->_storage->user_recovery_from_install_attempts >= 3 ) {
16857 $this->delete_current_install( false );
16858 } else {
16859 $this->_storage->user_recovery_from_install_last_attempt_timestamp = time();
16860
16861 return;
16862 }
16863 }
16864 }
16865
16866 $this->_user = ( $user instanceof FS_User ) ?
16867 clone $user :
16868 null;
16869 }
16870
16871 if ( is_object( $this->_user ) ) {
16872 // Load licenses.
16873 $this->_licenses = $this->get_user_licenses( $this->_user->id );
16874 }
16875
16876 if ( is_object( $this->_site ) ) {
16877 // Load plans.
16878 $this->_plans = isset( $plans[ $this->_slug ] ) ?
16879 $plans[ $this->_slug ] :
16880 array();
16881
16882 if ( ! is_array( $this->_plans ) || empty( $this->_plans ) ) {
16883 $this->_sync_plans();
16884 } else {
16885 for ( $i = 0, $len = count( $this->_plans ); $i < $len; $i ++ ) {
16886 if ( $this->_plans[ $i ] instanceof FS_Plugin_Plan ) {
16887 $this->_plans[ $i ] = self::decrypt_entity( $this->_plans[ $i ] );
16888 } else {
16889 unset( $this->_plans[ $i ] );
16890 }
16891 }
16892 }
16893
16894 $this->_license = $this->_get_license_by_id( $this->_site->license_id );
16895
16896 if ( $this->_site->version != $this->get_plugin_version() ) {
16897 // If stored install version is different than current installed plugin version,
16898 // then update plugin version event.
16899 $this->update_plugin_version_event();
16900 }
16901 }
16902
16903 if ( true === $this->_storage->require_license_activation &&
16904 ! fs_request_get_bool( 'require_license', true )
16905 ) {
16906 $this->_storage->require_license_activation = false;
16907 }
16908
16909 if ( $this->is_theme() ) {
16910 $this->_register_account_hooks();
16911 }
16912
16913 if ( $this->is_user_in_admin() && $this->is_clone() ) {
16914 if ( empty( FS_Clone_Manager::instance()->get_clone_identification_timestamp() ) ) {
16915 FS_Clone_Manager::instance()->store_clone_identification_timestamp();
16916 }
16917
16918 FS_Clone_Manager::instance()->maybe_update_clone_resolution_support_flag( $this->_storage->sdk_last_version );
16919 $this->send_pending_clone_update_once();
16920 }
16921 }
16922
16923 /**
16924 * Special user recovery mechanism.
16925 *
16926 * @author Vova Feldman (@svovaf)
16927 * @since 2.0.0
16928 *
16929 * @param number|null $site_user_id
16930 *
16931 * @return \FS_User|mixed
16932 */
16933 private function sync_user_by_current_install( $site_user_id = null ) {
16934 $site_user_id = FS_Site::is_valid_id( $site_user_id ) ?
16935 $site_user_id :
16936 $this->_site->user_id;
16937
16938 $api = $this->get_api_site_scope();
16939
16940 $uid = $this->get_anonymous_id();
16941 $request_path = "/users/{$site_user_id}.json?uid={$uid}";
16942
16943 $result = $api->get( $request_path, false, WP_FS__TIME_10_MIN_IN_SEC );
16944
16945 if ( $this->is_api_result_entity( $result ) ) {
16946 $user = new FS_User( $result );
16947 $this->_user = $user;
16948 $this->_store_user();
16949
16950 return $user;
16951 }
16952
16953 $error_code = FS_Api::get_error_code( $result );
16954
16955 if ( in_array( $error_code, array( 'invalid_unique_id', 'user_cannot_be_recovered' ) ) ) {
16956 /**
16957 * Those API errors will continue coming and are not recoverable with the
16958 * current site's data. Therefore, extend the API call's cached result to 7 days.
16959 */
16960 $api->update_cache_expiration( $request_path, WP_FS__TIME_WEEK_IN_SEC );
16961 }
16962
16963 return $result;
16964 }
16965
16966 /**
16967 * @author Vova Feldman (@svovaf)
16968 * @since 1.0.1
16969 *
16970 * @param FS_User $user
16971 * @param FS_Site $site
16972 * @param bool|array $plans
16973 */
16974 private function _set_account( FS_User $user, FS_Site $site, $plans = false ) {
16975 $site->user_id = $user->id;
16976
16977 $this->_site = $site;
16978 $this->_user = $user;
16979 if ( false !== $plans ) {
16980 $this->_plans = $plans;
16981 }
16982
16983 $this->send_install_update();
16984
16985 $this->_store_account();
16986
16987 }
16988
16989 /**
16990 * Get a sanitized array with the WordPress version, SDK version, and PHP version.
16991 * Each version is trimmed after the 16th char.
16992 *
16993 * @author Vova Feldman (@svovaf)
16994 * @since 2.2.1
16995 *
16996 * @return array
16997 */
16998 private function get_versions() {
16999 $versions = array();
17000 $versions['sdk_version'] = $this->version;
17001
17002 // Collect these diagnostic information only if it's allowed.
17003 if ( FS_Permission_Manager::instance( $this )->is_diagnostic_tracking_allowed() ) {
17004 $versions['platform_version'] = get_bloginfo( 'version' );
17005 $versions['programming_language_version'] = phpversion();
17006 }
17007
17008 foreach ( $versions as $k => $version ) {
17009 $versions[ $k ] = self::get_api_sanitized_property( $k, $version );
17010 }
17011
17012 return $versions;
17013 }
17014
17015 /**
17016 * Get sanitized site language.
17017 *
17018 * @param string $language
17019 * @param int $max_len
17020 *
17021 * @since 2.5.1
17022 * @author Vova Feldman (@svovaf)
17023 *
17024 * @return string
17025 */
17026 private static function get_sanitized_language( $language = '', $max_len = self::LANGUAGE_MAX_CHARS ) {
17027 if ( empty( $language ) ) {
17028 $language = get_bloginfo( 'language' );
17029 }
17030
17031 return substr( $language, 0, $max_len );
17032 }
17033
17034 /**
17035 * Get core version stripped from pre-release and build.
17036 *
17037 * @since 2.5.1
17038 * @author Vova Feldman (@svovaf)
17039 *
17040 * @param string $version
17041 * @param int $parts
17042 * @param int $max_len
17043 * @param bool $include_pre_release
17044 *
17045 * @return string
17046 */
17047 private static function get_core_version(
17048 $version,
17049 $parts = 3,
17050 $max_len = self::VERSION_MAX_CHARS,
17051 $include_pre_release = false
17052 ) {
17053 if ( empty( $version ) ) {
17054 // Version is empty.
17055 return '';
17056 }
17057
17058 if ( is_numeric( $version ) ) {
17059 $is_float_version = is_float( $version );
17060
17061 $version = (string) $version;
17062
17063 /**
17064 * Casting a whole float number to a string cuts the decimal point. This part make sure to add the missing decimal part to the version.
17065 */
17066 if ( $is_float_version && false === strpos( $version, '.' ) ) {
17067 $version .= '.0';
17068 }
17069 }
17070
17071 if ( ! is_string( $version ) ) {
17072 return '';
17073 }
17074
17075 if ( $parts < 1 ) {
17076 return '';
17077 }
17078
17079 $pre_release_regex = $include_pre_release ?
17080 '(\-(alpha|beta|RC)([0-9]+)?)?' :
17081 '';
17082
17083 if ( 0 === preg_match( '/^([0-9]+(\.[0-9]+){0,' . ( $parts - 1 ) . '}' . $pre_release_regex . ')/i', $version, $matches ) ) {
17084 // Version is not starting with a digit.
17085 return '';
17086 }
17087
17088 return substr( $matches[1], 0, $max_len );
17089 }
17090
17091 /**
17092 * @param string $prop
17093 * @param mixed $val
17094 *
17095 * @return mixed
17096 *@author Vova Feldman (@svovaf)
17097 *
17098 * @since 2.5.1
17099 */
17100 private static function get_api_sanitized_property( $prop, $val ) {
17101 if ( ! is_string( $val ) || empty( $val ) ) {
17102 return $val;
17103 }
17104
17105 switch ( $prop ) {
17106 case 'programming_language_version':
17107 // Get core PHP version, which can have up to 3 parts (ignore pre-releases).
17108 return self::get_core_version( $val );
17109 case 'platform_version':
17110 // Get the exact WordPress version, which can have up to 3 parts (including pre-releases).
17111 return self::get_core_version( $val, 3, self::VERSION_MAX_CHARS, true );
17112 case 'sdk_version':
17113 // Get the exact SDK version, which can have up to 4 parts.
17114 return self::get_core_version( $val, 4 );
17115 case 'version':
17116 // Get the entire version but just limited in length.
17117 return substr( $val, 0, self::VERSION_MAX_CHARS );
17118 case 'language':
17119 return self::get_sanitized_language( $val );
17120 default:
17121 return $val;
17122 }
17123 }
17124
17125 /**
17126 * @author Leo Fajardo (@leorw)
17127 * @since 2.3.0
17128 *
17129 * @return bool
17130 */
17131 function has_beta_update() {
17132 return (
17133 ! empty( $this->_storage->beta_data ) &&
17134 ( true === $this->_storage->beta_data['is_beta'] ) &&
17135 version_compare( $this->_storage->beta_data['version'], $this->get_plugin_version(), '>' )
17136 );
17137 }
17138
17139 /**
17140 * @author Leo Fajardo (@leorw)
17141 * @since 2.3.0
17142 *
17143 * @return bool
17144 */
17145 function is_beta() {
17146 return (
17147 ! empty( $this->_storage->beta_data ) &&
17148 ( true === $this->_storage->beta_data['is_beta'] ) &&
17149 ( $this->get_plugin_version() === $this->_storage->beta_data['version'] )
17150 );
17151 }
17152
17153 /**
17154 * @author Vova Feldman (@svovaf)
17155 * @since 1.1.7.4
17156 *
17157 * @param array $override_with
17158 * @param bool|int|null $network_level_or_blog_id If true, return params for network level opt-in. If integer, get params for specified blog in the network.
17159 *
17160 * @return array
17161 */
17162 function get_opt_in_params( $override_with = array(), $network_level_or_blog_id = null ) {
17163 $this->_logger->entrance();
17164
17165 $current_user = self::_get_current_wp_user();
17166
17167 $activation_action = $this->get_unique_affix() . '_activate_new';
17168 $return_url = $this->is_anonymous() ?
17169 // If skipped already, then return to the account page.
17170 $this->get_account_url( $activation_action, array(), false ) :
17171 // Return to the module's main page.
17172 $this->get_after_activation_url( 'after_connect_url', array( 'fs_action' => $activation_action ) );
17173
17174 $versions = $this->get_versions();
17175
17176 $params = array_merge( $versions, array(
17177 'user_firstname' => $current_user->user_firstname,
17178 'user_lastname' => $current_user->user_lastname,
17179 'user_email' => $current_user->user_email,
17180 'plugin_slug' => $this->_slug,
17181 'plugin_id' => $this->get_id(),
17182 'plugin_public_key' => $this->get_public_key(),
17183 'plugin_version' => $this->get_plugin_version(),
17184 'return_url' => fs_nonce_url( $return_url, $activation_action ),
17185 'account_url' => fs_nonce_url( $this->_get_admin_page_url(
17186 'account',
17187 array( 'fs_action' => 'sync_user' )
17188 ), 'sync_user' ),
17189 'is_premium' => $this->is_premium(),
17190 'is_active' => true,
17191 'is_uninstalled' => false,
17192 'is_localhost' => WP_FS__IS_LOCALHOST,
17193 ) );
17194
17195 if ( $this->is_addon() ) {
17196 $parent_fs = $this->get_parent_instance();
17197
17198 $params['parent_plugin_slug'] = $parent_fs->_slug;
17199 $params['parent_plugin_id'] = $parent_fs->get_id();
17200 }
17201
17202 if ( true === $network_level_or_blog_id ) {
17203 if ( ! isset( $override_with['sites'] ) ) {
17204 $params['sites'] = $this->get_sites_for_network_level_optin();
17205 }
17206 } else {
17207 $site = is_numeric( $network_level_or_blog_id ) ?
17208 array( 'blog_id' => $network_level_or_blog_id ) :
17209 null;
17210
17211 $site = $this->get_site_info( $site );
17212
17213 $diagnostic_info = array();
17214 if ( FS_Permission_Manager::instance( $this )->is_diagnostic_tracking_allowed() ) {
17215 $diagnostic_info = array(
17216 'site_name' => $site['title'],
17217 'language' => self::get_sanitized_language( $site['language'] ),
17218 );
17219 }
17220
17221 $params = array_merge( $params, $diagnostic_info, array(
17222 'site_uid' => $site['uid'],
17223 'site_url' => $site['url'],
17224 ) );
17225 }
17226
17227 if ( $this->is_pending_activation() &&
17228 ! empty( $this->_storage->pending_license_key )
17229 ) {
17230 $params['license_key'] = $this->_storage->pending_license_key;
17231 }
17232
17233 if ( WP_FS__SKIP_EMAIL_ACTIVATION && $this->has_secret_key() ) {
17234 // Even though rand() is known for its security issues,
17235 // the timestamp adds another layer of protection.
17236 // It would be very hard for an attacker to get the secret key form here.
17237 // Plus, this should never run in production since the secret should never
17238 // be included in the production version.
17239 $params['ts'] = WP_FS__SCRIPT_START_TIME;
17240 $params['salt'] = md5( uniqid( rand() ) );
17241 $params['secure'] = md5(
17242 $params['ts'] .
17243 $params['salt'] .
17244 $this->get_secret_key()
17245 );
17246 }
17247
17248 if ( is_multisite() && function_exists( 'get_network' ) ) {
17249 $params['network_uid'] = $this->get_anonymous_network_id();
17250 }
17251
17252 return array_merge( $params, $override_with );
17253 }
17254
17255 /**
17256 * 1. If successful opt-in or pending activation returns the next page that the user should be redirected to.
17257 * 2. If there was an API error, return the API result.
17258 *
17259 * @author Vova Feldman (@svovaf)
17260 * @since 1.1.7.4
17261 *
17262 * @param string|bool $email
17263 * @param string|bool $first
17264 * @param string|bool $last
17265 * @param string|bool $license_key
17266 * @param bool $is_uninstall If "true", this means that the module is currently being uninstalled.
17267 * In this case, the user and site info will be sent to the server but no
17268 * data will be saved to the WP installation's database.
17269 * @param number|bool $trial_plan_id
17270 * @param bool $is_disconnected Whether to opt in without tracking.
17271 * @param null|bool $is_marketing_allowed
17272 * @param array $sites If network-level opt-in, an array of containing details of sites.
17273 * @param bool $redirect
17274 *
17275 * @return string|object
17276 * @use WP_Error
17277 */
17278 function opt_in(
17279 $email = false,
17280 $first = false,
17281 $last = false,
17282 $license_key = false,
17283 $is_uninstall = false,
17284 $trial_plan_id = false,
17285 $is_disconnected = false,
17286 $is_marketing_allowed = null,
17287 $sites = array(),
17288 $redirect = true
17289 ) {
17290 $this->_logger->entrance();
17291
17292 if ( false === $email ) {
17293 $current_user = self::_get_current_wp_user();
17294 $email = $current_user->user_email;
17295 }
17296
17297 /**
17298 * @since 1.2.1 If activating with license key, ignore the context-user
17299 * since the user will be automatically loaded from the license.
17300 */
17301 if ( empty( $license_key ) ) {
17302 // Clean up pending license if opt-ing in again.
17303 $this->_storage->remove( 'pending_license_key' );
17304
17305 if ( ! $is_uninstall ) {
17306 $fs_user = Freemius::_get_user_by_email( $email );
17307 if ( is_object( $fs_user ) && ! $this->is_pending_activation() ) {
17308 return $this->install_with_user(
17309 $fs_user,
17310 false,
17311 $trial_plan_id,
17312 $redirect,
17313 true,
17314 $sites
17315 );
17316 }
17317 }
17318 }
17319
17320 $user_info = array();
17321 if ( ! empty( $email ) ) {
17322 $user_info['user_email'] = $email;
17323 }
17324 if ( ! empty( $first ) ) {
17325 $user_info['user_firstname'] = $first;
17326 }
17327 if ( ! empty( $last ) ) {
17328 $user_info['user_lastname'] = $last;
17329 }
17330
17331 if ( ! empty( $sites ) ) {
17332 $is_network = true;
17333
17334 $user_info['sites'] = $sites;
17335 } else {
17336 $is_network = false;
17337 }
17338
17339 $params = $this->get_opt_in_params( $user_info, $is_network );
17340
17341 $filtered_license_key = false;
17342 if ( is_string( $license_key ) ) {
17343 $filtered_license_key = $this->apply_filters( 'license_key', $license_key );
17344 $params['license_key'] = $filtered_license_key;
17345 } else if ( FS_Plugin_Plan::is_valid_id( $trial_plan_id ) ) {
17346 $params['trial_plan_id'] = $trial_plan_id;
17347 }
17348
17349 if ( $is_uninstall ) {
17350 $params['uninstall_params'] = array(
17351 'reason_id' => $this->_storage->uninstall_reason->id,
17352 'reason_info' => $this->_storage->uninstall_reason->info
17353 );
17354 }
17355
17356 if ( isset( $params['license_key'] ) ) {
17357 $fs_user = Freemius::_get_user_by_email( $email );
17358
17359 if ( is_object( $fs_user ) ) {
17360 /**
17361 * If opting in with a context license and the context WP Admin user already opted in
17362 * before from the current site, add the user context security params to avoid the
17363 * unnecessary email activation when the context license is owned by the same context user.
17364 *
17365 * @author Leo Fajardo (@leorw)
17366 * @since 1.2.3
17367 */
17368 $params = array_merge( $params, FS_Security::instance()->get_context_params(
17369 $fs_user,
17370 false,
17371 'install_with_existing_user'
17372 ) );
17373 }
17374 }
17375
17376 if ( is_bool( $is_marketing_allowed ) ) {
17377 $params['is_marketing_allowed'] = $is_marketing_allowed;
17378 }
17379
17380 $params['is_disconnected'] = $is_disconnected;
17381 $params['format'] = 'json';
17382 $params['is_extensions_tracking_allowed'] = FS_Permission_Manager::instance( $this )->is_extensions_tracking_allowed();
17383 $params['is_diagnostic_tracking_allowed'] = FS_Permission_Manager::instance( $this )->is_diagnostic_tracking_allowed();
17384
17385 $request = array(
17386 'method' => 'POST',
17387 'body' => $params,
17388 'timeout' => 60,
17389 );
17390
17391 $url = $this->add_show_pending( WP_FS__ADDRESS . '/action/service/user/install/' );
17392 $response = self::safe_remote_post( $url, $request );
17393
17394 if ( is_wp_error( $response ) ) {
17395 /**
17396 * @var WP_Error $response
17397 */
17398 $result = new stdClass();
17399
17400 $error_code = $response->get_error_code();
17401 $error_type = str_replace( ' ', '', ucwords( str_replace( '_', ' ', $error_code ) ) );
17402
17403 $result->error = (object) array(
17404 'type' => $error_type,
17405 'message' => $response->get_error_message(),
17406 'code' => $error_code,
17407 'http' => 402
17408 );
17409
17410 $this->maybe_modify_api_curl_error_message( $result );
17411
17412 if ( FS_Api::is_blocked( $result ) ) {
17413 $result->error->message = $this->generate_api_blocked_notice_message_from_result( $result );
17414 }
17415
17416 $is_connected = null;
17417
17418 if ( empty( $license_key ) && $this->is_enable_anonymous() ) {
17419 $this->skip_connection( fs_is_network_admin() );
17420
17421 $is_connected = ( ! FS_Api::is_blocked( $result ) );
17422 }
17423
17424 $this->update_connectivity_info( $is_connected );
17425
17426 return $result;
17427 }
17428
17429 $this->update_connectivity_info( true );
17430
17431 // Module is being uninstalled, don't handle the returned data.
17432 if ( $is_uninstall ) {
17433 return true;
17434 }
17435
17436 /**
17437 * When json_decode() executed on PHP 5.2 with an invalid JSON, it will throw a PHP warning. Unfortunately, the new Theme Check doesn't allow PHP silencing and the theme review team isn't open to change that, therefore, instead of using `@json_decode()` we had to use the method without the `@` directive.
17438 *
17439 * @author Vova Feldman (@svovaf)
17440 * @since 1.2.3
17441 * @link https://themes.trac.wordpress.org/ticket/46134#comment:5
17442 * @link https://themes.trac.wordpress.org/ticket/46134#comment:9
17443 * @link https://themes.trac.wordpress.org/ticket/46134#comment:12
17444 * @link https://themes.trac.wordpress.org/ticket/46134#comment:14
17445 */
17446 $decoded = is_string( $response['body'] ) ?
17447 json_decode( $response['body'] ) :
17448 null;
17449
17450 if ( empty( $decoded ) ) {
17451 return false;
17452 }
17453
17454 if ( ! $this->is_api_result_object( $decoded ) ) {
17455 if ( ! empty( $params['license_key'] ) ) {
17456 // Pass the fully entered license key to the failure handler.
17457 $params['license_key'] = $license_key;
17458 }
17459
17460 return $is_uninstall ?
17461 $decoded :
17462 $this->apply_filters( 'after_install_failure', $decoded, $params );
17463 } else if ( isset( $decoded->pending_activation ) && $decoded->pending_activation ) {
17464 if ( $is_network ) {
17465 $site_ids = array();
17466 foreach ( $sites as $site ) {
17467 $site_ids[] = $site['blog_id'];
17468 }
17469
17470 /**
17471 * Store the sites so that they can be installed once the user has clicked on the activation link
17472 * in the email.
17473 *
17474 * @author Leo Fajardo (@leorw)
17475 */
17476 $this->_storage->pending_sites_info = array(
17477 'blog_ids' => $site_ids,
17478 'license_key' => $license_key,
17479 'trial_plan_id' => $trial_plan_id
17480 );
17481 }
17482
17483 // Pending activation, add message.
17484 return $this->set_pending_confirmation(
17485 ( isset( $decoded->email ) ?
17486 $decoded->email :
17487 true ),
17488 false,
17489 $filtered_license_key,
17490 ! empty( $params['trial_plan_id'] ),
17491 isset( $decoded->is_suspicious_email ) && $decoded->is_suspicious_email
17492 );
17493 } else if ( isset( $decoded->install_secret_key ) ) {
17494 return $this->install_with_new_user(
17495 $decoded->user_id,
17496 $decoded->user_public_key,
17497 $decoded->user_secret_key,
17498 ( isset( $decoded->is_marketing_allowed ) && ! is_null( $decoded->is_marketing_allowed ) ?
17499 $decoded->is_marketing_allowed :
17500 null ),
17501 ( isset( $decoded->is_extensions_tracking_allowed ) && ! is_null( $decoded->is_extensions_tracking_allowed ) ?
17502 $decoded->is_extensions_tracking_allowed :
17503 null ),
17504 ( isset( $decoded->is_diagnostic_tracking_allowed ) && ! is_null( $decoded->is_diagnostic_tracking_allowed ) ?
17505 $decoded->is_diagnostic_tracking_allowed :
17506 null ),
17507 $decoded->install_id,
17508 $decoded->install_public_key,
17509 $decoded->install_secret_key,
17510 false
17511 );
17512 } else if ( is_array( $decoded->installs ) ) {
17513 return $this->install_many_with_new_user(
17514 $decoded->user_id,
17515 $decoded->user_public_key,
17516 $decoded->user_secret_key,
17517 ( isset( $decoded->is_marketing_allowed ) && ! is_null( $decoded->is_marketing_allowed ) ?
17518 $decoded->is_marketing_allowed :
17519 null ),
17520 ( isset( $decoded->is_extensions_tracking_allowed ) && ! is_null( $decoded->is_extensions_tracking_allowed ) ?
17521 $decoded->is_extensions_tracking_allowed :
17522 null ),
17523 ( isset( $decoded->is_diagnostic_tracking_allowed ) && ! is_null( $decoded->is_diagnostic_tracking_allowed ) ?
17524 $decoded->is_diagnostic_tracking_allowed :
17525 null ),
17526 $decoded->installs,
17527 false
17528 );
17529 }
17530
17531 return $decoded;
17532 }
17533
17534 /**
17535 * Set user and site identities.
17536 *
17537 * @author Vova Feldman (@svovaf)
17538 * @since 1.0.9
17539 *
17540 * @param FS_User $user
17541 * @param FS_Site $site
17542 * @param bool $redirect
17543 * @param bool $auto_install Since 1.2.1.7 If `true` and setting up an account with a valid license, will
17544 * redirect (or return a URL) to the account page with a special parameter to
17545 * trigger the auto installation processes.
17546 *
17547 * @return string If redirect is `false`, returns the next page the user should be redirected to.
17548 */
17549 function setup_account(
17550 FS_User $user,
17551 FS_Site $site,
17552 $redirect = true,
17553 $auto_install = false
17554 ) {
17555 return $this->setup_network_account(
17556 $user,
17557 array( $site ),
17558 $redirect,
17559 $auto_install,
17560 false
17561 );
17562 }
17563
17564 /**
17565 * Set user and site identities.
17566 *
17567 * @author Vova Feldman (@svovaf)
17568 * @since 2.0.0
17569 *
17570 * @param FS_User $user
17571 * @param FS_Site[] $installs
17572 * @param bool $redirect
17573 * @param bool $auto_install Since 1.2.1.7 If `true` and setting up an account with a valid license, will redirect (or return a URL) to the account page with a special parameter to trigger the auto installation processes.
17574 * @param bool $is_network_level_opt_in
17575 *
17576 * @return string If redirect is `false`, returns the next page the user should be redirected to.
17577 */
17578 function setup_network_account(
17579 FS_User $user,
17580 array $installs,
17581 $redirect = true,
17582 $auto_install = false,
17583 $is_network_level_opt_in = true
17584 ) {
17585 $first_install = $installs[0];
17586
17587 $this->_user = $user;
17588 $this->_site = $first_install;
17589
17590 $this->_sync_plans();
17591
17592 if ( $this->_storage->handle_gdpr_admin_notice &&
17593 $this->should_handle_gdpr_admin_notice() &&
17594 FS_GDPR_Manager::instance()->should_show_opt_in_notice()
17595 ) {
17596 /**
17597 * Clear user lock after an opt-in.
17598 */
17599 require_once WP_FS__DIR_INCLUDES . '/class-fs-user-lock.php';
17600 FS_User_Lock::instance()->unlock();
17601 }
17602
17603 if ( 1 < count( $installs ) ) {
17604 // Only network level opt-in can have more than one install.
17605 $is_network_level_opt_in = true;
17606 }
17607
17608 $this->update_connectivity_info( true );
17609
17610 // $is_network_level_opt_in = self::is_ajax_action_static( 'network_activate', $this->_module_id );
17611 // If Freemius was OFF before, turn it on.
17612 $this->turn_on();
17613
17614 $this->handle_account_connection(
17615 $installs,
17616 ( ! $this->_is_network_active || ! $is_network_level_opt_in )
17617 );
17618
17619 if ( is_numeric( $first_install->license_id ) ) {
17620 $this->set_license( $this->_get_license_by_id( $first_install->license_id ) );
17621 }
17622
17623 $this->_admin_notices->remove_sticky( 'connect_account' );
17624
17625 if ( $this->is_pending_activation() || ! $this->has_settings_menu() ) {
17626 $this->clear_pending_activation_mode();
17627
17628 if ( ! $this->is_paying_or_trial() ) {
17629 $this->_admin_notices->add_sticky(
17630 sprintf( $this->get_text_inline( '%s opt-in was successfully completed.', 'plugin-x-activation-message' ), '<b>' . $this->get_plugin_name() . '</b>' ),
17631 'activation_complete'
17632 );
17633 }
17634 }
17635
17636 if ( $this->is_paying_or_trial() ) {
17637 if ( ! $this->is_premium() ||
17638 ! $this->has_premium_version() ||
17639 ! $this->has_settings_menu()
17640 ) {
17641 if ( $this->is_paying() ) {
17642 $this->add_complete_upgrade_instructions_notice(
17643 sprintf(
17644 $this->get_text_inline( 'Your account was successfully activated with the %s plan.', 'activation-with-plan-x-message' ),
17645 $this->get_plan_title()
17646 ),
17647 'plan_upgraded'
17648 );
17649 } else {
17650 $trial_plan = $this->get_trial_plan();
17651
17652 $this->add_complete_upgrade_instructions_notice(
17653 sprintf(
17654 $this->get_text_inline( 'Your trial has been successfully started.', 'trial-started-message' ),
17655 '<i>' . $this->get_plugin_name() . '</i>'
17656 ),
17657 'trial_started',
17658 $trial_plan->title
17659 );
17660 }
17661 }
17662
17663 $this->_admin_notices->remove_sticky( array(
17664 'trial_promotion',
17665 ) );
17666 }
17667
17668 $plugin_id = fs_request_get( 'plugin_id', false );
17669
17670 // Store activation time ONLY for plugins & themes (not add-ons).
17671 if ( ! is_numeric( $plugin_id ) || ( $plugin_id == $this->_plugin->id ) ) {
17672 if ( empty( $this->_storage->activation_timestamp ) ) {
17673 $this->_storage->activation_timestamp = WP_FS__SCRIPT_START_TIME;
17674 }
17675 }
17676
17677 $next_page = '';
17678
17679 $extra = array();
17680 if ( $auto_install ) {
17681 $extra['auto_install'] = 'true';
17682 }
17683
17684 if ( is_numeric( $plugin_id ) ) {
17685 /**
17686 * @author Leo Fajardo (@leorw)
17687 * @since 1.2.1.6
17688 *
17689 * Also sync the license after an anonymous user subscribes.
17690 */
17691 if ( $this->is_anonymous() || $plugin_id != $this->_plugin->id ) {
17692 // Add-on was installed - sync license right after install.
17693 $next_page = $this->_get_sync_license_url( $plugin_id, true, $extra );
17694 }
17695 } else {
17696 /**
17697 * @author Vova Feldman (@svovaf)
17698 * @since 1.1.9 If site installed with a valid license, sync license.
17699 */
17700 if ( $this->is_paying() ) {
17701 $this->_sync_plugin_license(
17702 true,
17703 // Installs data is already synced in the beginning of this method directly or via _set_account().
17704 false
17705 );
17706 }
17707
17708 // Reload the page with the keys.
17709 $next_page = $this->is_anonymous() ?
17710 // If user previously skipped, redirect to account page.
17711 $this->get_account_url( false, $extra ) :
17712 $this->get_after_activation_url( 'after_connect_url', array(), $is_network_level_opt_in );
17713 }
17714
17715 if ( ! empty( $next_page ) && $redirect ) {
17716 fs_redirect( $next_page );
17717 }
17718
17719 return $next_page;
17720 }
17721
17722 /**
17723 * Install plugin with new user information after approval.
17724 *
17725 * @author Vova Feldman (@svovaf)
17726 * @since 1.0.7
17727 */
17728 function _install_with_new_user() {
17729 $this->_logger->entrance();
17730
17731 if ( $this->is_registered() ) {
17732 return;
17733 }
17734
17735 $has_pending_activation_confirmation_param = fs_request_has( 'pending_activation' );
17736
17737 $this->update_license_required_permissions_if_anonymous();
17738
17739 if ( ( $this->is_plugin() && fs_request_is_action( $this->get_unique_affix() . '_activate_new' ) ) ||
17740 // @todo This logic should be improved because it's executed on every load of a theme.
17741 $this->is_theme()
17742 ) {
17743 // check_admin_referer( $this->_slug . '_activate_new' );
17744
17745 if ( fs_request_has( 'user_secret_key' ) ) {
17746 if ( fs_is_network_admin() && isset( $this->_storage->pending_sites_info ) ) {
17747 $pending_sites_info = $this->_storage->pending_sites_info;
17748
17749 $this->install_many_pending_with_user(
17750 fs_request_get( 'user_id' ),
17751 fs_request_get( 'user_public_key' ),
17752 fs_request_get( 'user_secret_key' ),
17753 fs_request_get_bool( 'is_marketing_allowed', null ),
17754 fs_request_get_bool( 'is_extensions_tracking_allowed', null ),
17755 fs_request_get_bool( 'is_diagnostic_tracking_allowed', null ),
17756 $pending_sites_info['blog_ids'],
17757 $pending_sites_info['license_key'],
17758 $pending_sites_info['trial_plan_id']
17759 );
17760 } else {
17761 $this->install_with_new_user(
17762 fs_request_get( 'user_id' ),
17763 fs_request_get( 'user_public_key' ),
17764 fs_request_get( 'user_secret_key' ),
17765 fs_request_get_bool( 'is_marketing_allowed', null ),
17766 fs_request_get_bool( 'is_extensions_tracking_allowed', null ),
17767 fs_request_get_bool( 'is_diagnostic_tracking_allowed', null ),
17768 fs_request_get( 'install_id' ),
17769 fs_request_get( 'install_public_key' ),
17770 fs_request_get( 'install_secret_key' ),
17771 true,
17772 fs_request_get_bool( 'auto_install' )
17773 );
17774 }
17775 } else if ( $has_pending_activation_confirmation_param ) {
17776 $this->set_pending_confirmation(
17777 fs_request_get( 'user_email' ),
17778 true,
17779 false,
17780 false,
17781 fs_request_get_bool( 'is_suspicious_email' ),
17782 fs_request_get_bool( 'has_upgrade_context' ),
17783 fs_request_get( 'support_email_address' )
17784 );
17785 }
17786 }
17787 }
17788
17789 /**
17790 * @author Vova Feldman (@svovaf)
17791 * @since 2.0.0
17792 *
17793 * @param number $id
17794 * @param string $public_key
17795 * @param string $secret_key
17796 *
17797 * @return \FS_User
17798 */
17799 private function setup_user( $id, $public_key, $secret_key ) {
17800 $user = self::_get_user_by_id( $id );
17801
17802 if ( is_object( $user ) ) {
17803 $this->_user = $user;
17804 } else {
17805 $user = new FS_User();
17806 $user->id = $id;
17807 $user->public_key = $public_key;
17808 $user->secret_key = $secret_key;
17809
17810 $this->_user = $user;
17811 $user_result = $this->get_api_user_scope()->get();
17812 $user = new FS_User( $user_result );
17813
17814 $this->_user = $user;
17815 $this->_store_user();
17816 }
17817
17818 return $user;
17819 }
17820
17821 /**
17822 * Install plugin with new user.
17823 *
17824 * @author Vova Feldman (@svovaf)
17825 * @since 1.1.7.4
17826 *
17827 * @param number $user_id
17828 * @param string $user_public_key
17829 * @param string $user_secret_key
17830 * @param bool|null $is_marketing_allowed
17831 * @param bool|null $is_extensions_tracking_allowed Since 2.3.2
17832 * @param bool|null $is_diagnostic_tracking_allowed Since 2.5.0.2
17833 * @param number $install_id
17834 * @param string $install_public_key
17835 * @param string $install_secret_key
17836 * @param bool $redirect
17837 * @param bool $auto_install Since 1.2.1.7 If `true` and setting up an account with a valid license, will redirect (or return a URL) to the account page with a special parameter to trigger the auto installation processes.
17838 *
17839 * @return string If redirect is `false`, returns the next page the user should be redirected to.
17840 */
17841 private function install_with_new_user(
17842 $user_id,
17843 $user_public_key,
17844 $user_secret_key,
17845 $is_marketing_allowed,
17846 $is_extensions_tracking_allowed,
17847 $is_diagnostic_tracking_allowed,
17848 $install_id,
17849 $install_public_key,
17850 $install_secret_key,
17851 $redirect = true,
17852 $auto_install = false
17853 ) {
17854 /**
17855 * This method is also executed after opting in with a license key since the
17856 * license can be potentially associated with a different owner.
17857 *
17858 * @since 2.0.0
17859 */
17860 $user = self::_get_user_by_id( $user_id );
17861
17862 if ( ! is_object( $user ) ) {
17863 $user = new FS_User();
17864 $user->id = $user_id;
17865 $user->public_key = $user_public_key;
17866 $user->secret_key = $user_secret_key;
17867
17868 $this->_user = $user;
17869 $user_result = $this->get_api_user_scope()->get();
17870 $user = new FS_User( $user_result );
17871 }
17872
17873 $this->_user = $user;
17874
17875 $site = new FS_Site();
17876 $site->id = $install_id;
17877 $site->public_key = $install_public_key;
17878 $site->secret_key = $install_secret_key;
17879
17880 $this->_site = $site;
17881 $site_result = $this->get_api_site_scope( true )->get();
17882 $site = new FS_Site( $site_result );
17883 $this->_site = $site;
17884
17885 if ( ! is_null( $is_marketing_allowed ) ) {
17886 $this->disable_opt_in_notice_and_lock_user();
17887 }
17888
17889 FS_Permission_Manager::instance( $this )->update_permissions_tracking_flag( array(
17890 FS_Permission_Manager::PERMISSION_DIAGNOSTIC => $is_diagnostic_tracking_allowed,
17891 FS_Permission_Manager::PERMISSION_EXTENSIONS => $is_extensions_tracking_allowed,
17892 ) );
17893
17894 return $this->setup_account(
17895 $this->_user,
17896 $this->_site,
17897 $redirect,
17898 $auto_install
17899 );
17900 }
17901
17902 /**
17903 * Install plugin with user.
17904 *
17905 * @author Leo Fajardo (@leorw)
17906 * @since 2.0.0
17907 *
17908 * @param number $user_id
17909 * @param string $user_public_key
17910 * @param string $user_secret_key
17911 * @param bool|null $is_marketing_allowed
17912 * @param bool|null $is_extensions_tracking_allowed Since 2.3.2
17913 * @param bool|null $is_diagnostic_tracking_allowed Since 2.5.0.2
17914 * @param array $site_ids
17915 * @param bool $license_key
17916 * @param bool $trial_plan_id
17917 * @param bool $redirect
17918 *
17919 * @return string If redirect is `false`, returns the next page the user should be redirected to.
17920 */
17921 private function install_many_pending_with_user(
17922 $user_id,
17923 $user_public_key,
17924 $user_secret_key,
17925 $is_marketing_allowed,
17926 $is_extensions_tracking_allowed,
17927 $is_diagnostic_tracking_allowed,
17928 $site_ids,
17929 $license_key = false,
17930 $trial_plan_id = false,
17931 $redirect = true
17932 ) {
17933 $user = $this->setup_user( $user_id, $user_public_key, $user_secret_key );
17934
17935 if ( ! is_null( $is_marketing_allowed ) ) {
17936 $this->disable_opt_in_notice_and_lock_user();
17937 }
17938
17939 FS_Permission_Manager::instance( $this )->update_permissions_tracking_flag( array(
17940 FS_Permission_Manager::PERMISSION_DIAGNOSTIC => $is_diagnostic_tracking_allowed,
17941 FS_Permission_Manager::PERMISSION_EXTENSIONS => $is_extensions_tracking_allowed,
17942 ) );
17943
17944 $sites = array();
17945 foreach ( $site_ids as $site_id ) {
17946 $sites[] = $this->get_site_info( array( 'blog_id' => $site_id ) );
17947 }
17948
17949 $this->install_with_user( $user, $license_key, $trial_plan_id, $redirect, true, $sites );
17950 }
17951
17952 /**
17953 * Multi-site install with a new user.
17954 *
17955 * @author Vova Feldman (@svovaf)
17956 * @since 2.0.0
17957 *
17958 * @param number $user_id
17959 * @param string $user_public_key
17960 * @param string $user_secret_key
17961 * @param bool|null $is_marketing_allowed
17962 * @param bool|null $is_extensions_tracking_allowed Since 2.3.2
17963 * @param bool|null $is_diagnostic_tracking_allowed Since 2.5.0.2
17964 * @param object[] $installs
17965 * @param bool $redirect
17966 * @param bool $auto_install Since 1.2.1.7 If `true` and setting up an account with a valid license, will redirect (or return a URL) to the account page with a special parameter to trigger the auto installation processes.
17967 *
17968 * @return string If redirect is `false`, returns the next page the user should be redirected to.
17969 */
17970 private function install_many_with_new_user(
17971 $user_id,
17972 $user_public_key,
17973 $user_secret_key,
17974 $is_marketing_allowed,
17975 $is_extensions_tracking_allowed,
17976 $is_diagnostic_tracking_allowed,
17977 array $installs,
17978 $redirect = true,
17979 $auto_install = false
17980 ) {
17981 $this->setup_user( $user_id, $user_public_key, $user_secret_key );
17982
17983 if ( ! is_null( $is_marketing_allowed ) ) {
17984 $this->disable_opt_in_notice_and_lock_user();
17985 }
17986
17987 FS_Permission_Manager::instance( $this )->update_permissions_tracking_flag( array(
17988 FS_Permission_Manager::PERMISSION_DIAGNOSTIC => $is_diagnostic_tracking_allowed,
17989 FS_Permission_Manager::PERMISSION_EXTENSIONS => $is_extensions_tracking_allowed,
17990 ) );
17991
17992 $install_ids = array();
17993
17994 foreach ( $installs as $install ) {
17995 $install_ids[] = $install->id;
17996 }
17997
17998 $items_per_request = 25;
17999 $left = count( $install_ids );
18000 $offset = 0;
18001
18002 $installs = array();
18003 while ( $left > 0 ) {
18004 $result = $this->get_api_user_scope()->get( "/plugins/{$this->_module_id}/installs.json?ids=" . implode( ',', array_slice( $install_ids, $offset, $items_per_request ) ) );
18005
18006 if ( ! $this->is_api_result_object( $result, 'installs' ) ) {
18007 // @todo Handle API error.
18008 }
18009
18010 $installs = array_merge( $installs, $result->installs );
18011
18012 $left -= $items_per_request;
18013 $offset += $items_per_request;
18014 }
18015
18016 foreach ( $installs as &$install ) {
18017 $install = new FS_Site( $install );
18018 }
18019
18020 return $this->setup_network_account(
18021 $this->_user,
18022 $installs,
18023 $redirect,
18024 $auto_install
18025 );
18026 }
18027
18028 /**
18029 * @author Vova Feldman (@svovaf)
18030 * @since 1.1.7.4
18031 *
18032 * @param string|bool $email
18033 * @param bool $redirect
18034 * @param string|bool $license_key Since 1.2.1.5
18035 * @param bool $is_pending_trial Since 1.2.1.5
18036 * @param bool $is_suspicious_email Since 2.5.0
18037 * @param bool $has_upgrade_context Since 2.5.3
18038 * @param bool|string $support_email_address Since 2.5.3
18039 *
18040 * @return string Since 1.2.1.5 if $redirect is `false`, return the pending activation page.
18041 */
18042 private function set_pending_confirmation(
18043 $email = false,
18044 $redirect = true,
18045 $license_key = false,
18046 $is_pending_trial = false,
18047 $is_suspicious_email = false,
18048 $has_upgrade_context = false,
18049 $support_email_address = false
18050 ) {
18051 $is_network_admin = fs_is_network_admin();
18052
18053 if ( $this->_ignore_pending_mode && ! $has_upgrade_context ) {
18054 /**
18055 * If explicitly asked to ignore pending mode, set to anonymous mode
18056 * if require confirmation before finalizing the opt-in except after completing a purchase (otherwise, in this case, they wouldn't see any notice telling them that they should receive their license key via email).
18057 *
18058 * @author Vova Feldman
18059 * @since 1.2.1.6
18060 */
18061 $this->skip_connection( $is_network_admin );
18062 } else {
18063 // Install must be activated via email since
18064 // user with the same email already exist.
18065 $this->_storage->is_pending_activation = true;
18066 $this->_add_pending_activation_notice(
18067 $email,
18068 $is_pending_trial,
18069 $is_suspicious_email,
18070 $has_upgrade_context,
18071 $support_email_address
18072 );
18073 }
18074
18075 if ( ! empty( $license_key ) ) {
18076 $this->_storage->pending_license_key = $license_key;
18077 }
18078
18079 // Remove the opt-in sticky notice.
18080 $this->_admin_notices->remove_sticky( array(
18081 'connect_account',
18082 'trial_promotion',
18083 ) );
18084
18085 $next_page = $this->get_after_activation_url( 'after_pending_connect_url' );
18086
18087 if ( $redirect ) {
18088 // Reload the page with a pending activation message.
18089 fs_redirect( $next_page );
18090 }
18091
18092 return $next_page;
18093 }
18094
18095 /**
18096 * Install plugin with current logged WP user info.
18097 *
18098 * @author Vova Feldman (@svovaf)
18099 * @since 1.0.7
18100 */
18101 function _install_with_current_user() {
18102 $this->_logger->entrance();
18103
18104 if ( $this->is_registered() ) {
18105 return;
18106 }
18107
18108 if ( fs_request_is_action( $this->get_unique_affix() . '_activate_existing' ) && fs_request_is_post() ) {
18109 // check_admin_referer( 'activate_existing_' . $this->_plugin->public_key );
18110
18111 /**
18112 * @author Vova Feldman (@svovaf)
18113 * @since 1.1.9 Add license key if given.
18114 */
18115 $license_key = fs_request_get( 'license_secret_key' );
18116
18117 FS_Permission_Manager::instance( $this )->update_permissions_tracking_flag( array(
18118 FS_Permission_Manager::PERMISSION_DIAGNOSTIC => fs_request_get_bool( 'is_diagnostic_tracking_allowed', null ),
18119 FS_Permission_Manager::PERMISSION_EXTENSIONS => fs_request_get_bool( 'is_extensions_tracking_allowed', null ),
18120 ) );
18121
18122 $this->install_with_current_user( $license_key );
18123 }
18124 }
18125
18126
18127 /**
18128 * @author Vova Feldman (@svovaf)
18129 * @since 1.1.7.4
18130 *
18131 * @param string|bool $license_key
18132 * @param number|bool $trial_plan_id
18133 * @param array $sites Since 2.0.0
18134 * @param bool $redirect
18135 *
18136 * @return object|string If redirect is `false`, returns the next page the user should be redirected to, or the API error object if failed to install.
18137 */
18138 function install_with_current_user(
18139 $license_key = false,
18140 $trial_plan_id = false,
18141 $sites = array(),
18142 $redirect = true
18143 ) {
18144 // Get current logged WP user.
18145 $current_user = self::_get_current_wp_user();
18146
18147 // Find the relevant FS user by the email.
18148 $user = self::_get_user_by_email( $current_user->user_email );
18149
18150 return $this->install_with_user( $user, $license_key, $trial_plan_id, $redirect, true, $sites );
18151 }
18152
18153 /**
18154 * @author Vova Feldman (@svovaf)
18155 * @since 2.0.0
18156 *
18157 * @param \FS_User $user
18158 * @param string|bool $license_key
18159 * @param number|bool $trial_plan_id
18160 * @param bool $redirect
18161 * @param bool $setup_account Since 2.0.0. When set to FALSE, executes a light installation without setting up the account as if it's the first opt-in.
18162 * @param array $sites Since 2.0.0. If not empty, should be a collection of site details for the bulk install API request.
18163 *
18164 * @return \FS_Site|object|string If redirect is `false`, returns the next page the user should be redirected to, or the API error object if failed to install. If $setup_account is set to `false`, return the newly created install.
18165 */
18166 function install_with_user(
18167 FS_User $user,
18168 $license_key = false,
18169 $trial_plan_id = false,
18170 $redirect = true,
18171 $setup_account = true,
18172 $sites = array()
18173 ) {
18174 // We have to set the user before getting user scope API handler.
18175 $this->_user = $user;
18176
18177 // Install the plugin.
18178 $result = $this->create_installs_with_user(
18179 $user,
18180 $license_key,
18181 $trial_plan_id,
18182 $sites,
18183 $redirect
18184 );
18185
18186 if ( ! $this->is_api_result_entity( $result ) &&
18187 ! $this->is_api_result_object( $result, 'installs' )
18188 ) {
18189 // @todo Handler potential API error of the $result
18190 }
18191
18192 if ( empty( $sites ) ) {
18193 $site = new FS_Site( $result );
18194 $this->_site = $site;
18195
18196 if ( ! $setup_account ) {
18197 $this->_store_site();
18198
18199 $this->sync_plan_if_not_exist( $site->plan_id );
18200
18201 if ( ! empty( $license_key ) && FS_Plugin_License::is_valid_id( $site->license_id ) ) {
18202 $this->sync_license_if_not_exist( $site->license_id, $license_key );
18203 }
18204
18205 $this->_admin_notices->remove_sticky( 'connect_account', false );
18206
18207 return $site;
18208 }
18209
18210 return $this->setup_account( $this->_user, $this->_site, $redirect );
18211 } else {
18212 $installs = array();
18213 foreach ( $result->installs as $install ) {
18214 $installs[] = new FS_Site( $install );
18215 }
18216
18217 return $this->setup_network_account(
18218 $user,
18219 $installs,
18220 $redirect
18221 );
18222 }
18223 }
18224
18225 /**
18226 * Initiate an API request to create a collection of installs.
18227 *
18228 * @author Vova Feldman (@svovaf)
18229 * @since 2.0.0
18230 *
18231 * @param \FS_User $user
18232 * @param bool $license_key
18233 * @param bool $trial_plan_id
18234 * @param array $sites
18235 * @param bool $redirect
18236 * @param bool $silent
18237 *
18238 * @return object|mixed
18239 */
18240 private function create_installs_with_user(
18241 FS_User $user,
18242 $license_key = false,
18243 $trial_plan_id = false,
18244 $sites = array(),
18245 $redirect = false,
18246 $silent = false
18247 ) {
18248 $extra_install_params = array(
18249 'uid' => $this->get_anonymous_id(),
18250 'is_disconnected' => false,
18251 );
18252
18253 if ( ! empty( $license_key ) ) {
18254 $extra_install_params['license_key'] = $this->apply_filters( 'license_key', $license_key );
18255
18256 if ( $silent ) {
18257 $extra_install_params['ignore_license_owner'] = true;
18258 }
18259 } else if ( FS_Plugin_Plan::is_valid_id( $trial_plan_id ) ) {
18260 $extra_install_params['trial_plan_id'] = $trial_plan_id;
18261 }
18262
18263 if ( ! empty( $sites ) ) {
18264 $extra_install_params['sites'] = $sites;
18265 }
18266
18267 $args = $this->get_install_data_for_api( $extra_install_params, false, false );
18268
18269 // Install the plugin.
18270 $result = $this->get_api_user_scope_by_user( $user )->call(
18271 "/plugins/{$this->get_id()}/installs.json",
18272 'post',
18273 $args
18274 );
18275
18276 if ( ! $this->is_api_result_entity( $result ) &&
18277 ! $this->is_api_result_object( $result, 'installs' )
18278 ) {
18279 if ( ! empty( $args['license_key'] ) ) {
18280 // Pass the fully entered license key to the failure handler.
18281 $args['license_key'] = $license_key;
18282 }
18283
18284 $result = $this->apply_filters( 'after_install_failure', $result, $args );
18285
18286 if ( ! $silent ) {
18287 $this->_admin_notices->add(
18288 sprintf( $this->get_text_inline( 'Couldn\'t activate %s.', 'could-not-activate-x' ), $this->get_plugin_name() ) . ' ' .
18289 $this->get_text_inline( 'Please contact us with the following message:', 'contact-us-with-error-message' ) . ' ' . '<b>' . $result->error->message . '</b>',
18290 $this->get_text_x_inline( 'Oops', 'exclamation', 'oops' ) . '...',
18291 'error'
18292 );
18293 }
18294
18295 if ( $redirect ) {
18296 /**
18297 * We set the user before getting the user scope API handler, so the user became temporarily
18298 * registered (`is_registered() = true`). Since the API returned an error and we will redirect,
18299 * we have to set the user to `null`, otherwise, the user will be redirected to the wrong
18300 * activation page based on the return value of `is_registered()`. In addition, in case the
18301 * context plugin doesn't have a settings menu and the default page is the `Plugins` page,
18302 * misleading plugin activation errors will be shown on the `Plugins` page.
18303 *
18304 * @author Leo Fajardo (@leorw)
18305 */
18306 $this->_user = null;
18307
18308 fs_redirect( $this->get_activation_url( array( 'error' => $result->error->message ) ) );
18309 }
18310 }
18311
18312 return $result;
18313 }
18314
18315 /**
18316 * Tries to activate add-on account based on parent plugin info.
18317 *
18318 * @author Vova Feldman (@svovaf)
18319 * @since 1.0.6
18320 *
18321 * @param Freemius $parent_fs
18322 * @param bool|int|null $network_level_or_blog_id True for network level opt-in and integer for opt-in for specified blog in the network.
18323 * @param FS_Plugin_License $bundle_license Since 2.4.0. If provided, this license will be activated for the add-on.
18324 */
18325 private function _activate_addon_account(
18326 Freemius $parent_fs,
18327 $network_level_or_blog_id = null,
18328 FS_Plugin_License $bundle_license = null
18329 ) {
18330 if ( $this->is_registered() ) {
18331 // Already activated.
18332 return;
18333 }
18334
18335 $permission_ids = FS_Permission_Manager::get_all_permission_ids();
18336 $permissions = array();
18337 foreach ( $permission_ids as $permission_id ) {
18338 $permissions[ $permission_id ] = FS_Permission_Manager::instance( $parent_fs )->is_permission( $permission_id, true );
18339 }
18340
18341 FS_Permission_Manager::instance( $this )->update_permissions_tracking_flag( $permissions );
18342
18343 /**
18344 * Do not override the `uid` if network-level opt-in since the call to `get_sites_for_network_level_optin()`
18345 * already returns the data for the current blog.
18346 *
18347 * @author Leo Fajardo (@leorw)
18348 * @since 2.3.0
18349 */
18350 $uid_param_to_override = ( true === $network_level_or_blog_id ) ?
18351 array() :
18352 array( 'uid' => $this->get_anonymous_id() );
18353
18354 $params = $this->get_install_data_for_api(
18355 $uid_param_to_override,
18356 false,
18357 false,
18358 /**
18359 * Do not include the data for the current blog if network-level opt-in since the call to `get_sites_for_network_level_optin`
18360 * already includes the data for it.
18361 *
18362 * @author Leo Fajardo (@leorw)
18363 * @since 2.3.0
18364 */
18365 ( true !== $network_level_or_blog_id )
18366 );
18367
18368 if ( true === $network_level_or_blog_id ) {
18369 $params['sites'] = $this->get_sites_for_network_level_optin();
18370
18371 if ( empty( $params['sites'] ) ) {
18372 return;
18373 }
18374 }
18375
18376 if ( is_object( $bundle_license ) ) {
18377 $params['license_key'] = $bundle_license->secret_key;
18378 }
18379
18380 // Activate add-on with parent plugin credentials.
18381 $result = $parent_fs->get_api_site_scope()->call(
18382 "/addons/{$this->_plugin->id}/installs.json",
18383 'post',
18384 $params
18385 );
18386
18387 if ( ! $this->is_api_result_object( $result, 'installs' ) ) {
18388 if ( is_object( $bundle_license ) ) {
18389 /**
18390 * When a license object is provided, it's an attempt by the SDK to activate a bundle license and not a user-initiated action, therefore, do not show any admin notice to avoid confusion (e.g.: the notice will show up just above the opt-in link). If the license activation fails, the admin will see an opt-in link instead.
18391 *
18392 * @author Leo Fajardo (@leorw)
18393 * @since 2.4.0
18394 */
18395 } else {
18396 $error_message = FS_Api::is_api_error_object( $result ) ?
18397 $result->error->message :
18398 $this->get_text_inline( 'An unknown error has occurred.', 'unknown-error' );
18399
18400 $this->_admin_notices->add(
18401 sprintf( $this->get_text_inline( 'Couldn\'t activate %s.', 'could-not-activate-x' ), $this->get_plugin_name() ) . ' ' .
18402 $this->get_text_inline( 'Please contact us with the following message:', 'contact-us-with-error-message' ) . ' ' . '<b>' . $error_message . '</b>',
18403 $this->get_text_x_inline( 'Oops', 'exclamation', 'oops' ) . '...',
18404 'error'
18405 );
18406 }
18407
18408 return;
18409 }
18410
18411 $addon_installs = $result->installs;
18412 foreach ( $addon_installs as $key => $addon_install ) {
18413 $addon_installs[ $key ] = new FS_Site( $addon_install );
18414 }
18415
18416 $first_install = $addon_installs[0];
18417
18418 // Get user information based on parent's plugin.
18419 $user = $parent_fs->get_user();
18420
18421 // First of all, set site and user info - otherwise we won't
18422 // be able to invoke API calls.
18423 $this->_site = $first_install;
18424 $this->_user = $user;
18425
18426 // Sync add-on plans.
18427 $this->_sync_plans();
18428
18429 $this->handle_account_connection( $addon_installs, ! fs_is_network_admin() );
18430
18431 // Get site's current plan.
18432 //$this->_site->plan = $this->_get_plan_by_id( $this->_site->plan->id );
18433
18434 // Sync licenses.
18435 $this->_sync_licenses();
18436
18437 if ( ! fs_is_network_admin() ) {
18438 // Try to activate premium license.
18439 $this->_activate_license( true, $bundle_license );
18440
18441 if ( is_object( $bundle_license ) ) {
18442 $this->maybe_activate_bundle_license( $bundle_license );
18443 }
18444 } else {
18445 if ( is_object( $bundle_license ) ) {
18446 $premium_license = $bundle_license;
18447 } else {
18448 $license_id = fs_request_get( 'license_id' );
18449
18450 if ( is_object( $this->_site ) &&
18451 FS_Plugin_License::is_valid_id( $license_id ) &&
18452 $license_id == $this->_site->license_id
18453 ) {
18454 // License is already activated.
18455 return;
18456 }
18457
18458 $premium_license = FS_Plugin_License::is_valid_id( $license_id ) ?
18459 $this->_get_license_by_id( $license_id ) :
18460 $this->_get_available_premium_license();
18461 }
18462
18463 if ( is_object( $premium_license ) ) {
18464 $this->maybe_network_activate_addon_license( $premium_license );
18465 }
18466 }
18467 }
18468
18469 /**
18470 * @author Leo Fajardo (@leorw)
18471 * @since 2.3.0
18472 *
18473 * @param FS_Site[] $installs
18474 * @param bool $is_site_level
18475 */
18476 private function handle_account_connection( $installs, $is_site_level ) {
18477 $first_install = $installs[0];
18478
18479 if ( $is_site_level ) {
18480 $this->_set_account( $this->_user, $first_install );
18481
18482 $this->do_action( 'after_account_connection', $this->_user, $first_install );
18483 } else {
18484 $this->_store_user();
18485
18486 // Map site addresses to their blog IDs.
18487 $address_to_blog_map = $this->get_address_to_blog_map();
18488
18489 $first_blog_id = null;
18490 $blog_2_install_map = array();
18491 foreach ( $installs as $install ) {
18492 $address = trailingslashit( fs_strip_url_protocol( $install->url ) );
18493 $blog_id = $address_to_blog_map[ $address ];
18494
18495 $this->_store_site( true, $blog_id, $install );
18496
18497 if ( is_null( $first_blog_id ) ) {
18498 $first_blog_id = $blog_id;
18499 }
18500
18501 $blog_2_install_map[ $blog_id ] = $install;
18502 }
18503
18504 if ( ! FS_User::is_valid_id( $this->_storage->network_user_id ) ||
18505 ! is_object( self::_get_user_by_id( $this->_storage->network_user_id ) )
18506 ) {
18507 // Store network user.
18508 $this->_storage->network_user_id = $this->_user->id;
18509 }
18510
18511 if ( ! FS_Site::is_valid_id( $this->_storage->network_install_blog_id ) ) {
18512 $this->_storage->network_install_blog_id = $first_blog_id;
18513 }
18514
18515 if ( count( $installs ) === count( $address_to_blog_map ) ) {
18516 // Super admin opted in for all sites in the network.
18517 $this->_storage->is_network_connected = true;
18518 }
18519
18520 $this->_store_licenses( false );
18521
18522 self::$_accounts->store();
18523
18524 // Don't sync the installs data on network upgrade
18525 if ( ! $this->network_upgrade_mode_completed() ) {
18526 $this->send_installs_update();
18527 }
18528
18529 $current_blog = get_current_blog_id();
18530
18531 foreach ( $blog_2_install_map as $blog_id => $install ) {
18532 $this->switch_to_blog( $blog_id );
18533
18534 $this->do_action( 'after_account_connection', $this->_user, $install );
18535 }
18536
18537 // Switch install context back to the first install.
18538 $this->switch_to_blog(
18539 $current_blog,
18540 $first_install,
18541 ( $this->_site->id != $first_install->id )
18542 );
18543
18544 $this->do_action( 'after_network_account_connection', $this->_user, $blog_2_install_map );
18545 }
18546 }
18547
18548 /**
18549 * Tries to activate parent account based on add-on's info.
18550 *
18551 * @author Vova Feldman (@svovaf)
18552 * @since 1.2.2.7
18553 *
18554 * @param Freemius $parent_fs
18555 */
18556 private function activate_parent_account( Freemius $parent_fs ) {
18557 if ( ! $this->is_addon() ) {
18558 // This is not an add-on.
18559 return;
18560 }
18561
18562 if ( $parent_fs->is_registered() ) {
18563 // Already activated.
18564 return;
18565 }
18566
18567 // Activate parent with add-on's user credentials.
18568 $parent_install = $this->get_api_user_scope()->call(
18569 "/plugins/{$parent_fs->_plugin->id}/installs.json",
18570 'post',
18571 $parent_fs->get_install_data_for_api( array(
18572 'uid' => $parent_fs->get_anonymous_id(),
18573 ), false, false )
18574 );
18575
18576 if ( isset( $parent_install->error ) ) {
18577 $this->_admin_notices->add(
18578 sprintf( $this->get_text_inline( 'Couldn\'t activate %s.', 'could-not-activate-x' ), $this->get_plugin_name() ) . ' ' .
18579 $this->get_text_inline( 'Please contact us with the following message:', 'contact-us-with-error-message' ) . ' ' . '<b>' . $parent_install->error->message . '</b>',
18580 $this->get_text_x_inline( 'Oops', 'exclamation', 'oops' ) . '...',
18581 'error'
18582 );
18583
18584 return;
18585 }
18586
18587 $parent_fs->_admin_notices->remove_sticky( 'connect_account' );
18588
18589 if ( $parent_fs->is_pending_activation() ) {
18590 $parent_fs->clear_pending_activation_mode();
18591 }
18592
18593 // Get user information based on parent's plugin.
18594 $user = $this->get_user();
18595
18596 // First of all, set site info - otherwise we won't
18597 // be able to invoke API calls.
18598 $parent_fs->_site = new FS_Site( $parent_install );
18599 $parent_fs->_user = $user;
18600
18601 // Sync add-on plans.
18602 $parent_fs->_sync_plans();
18603
18604 $parent_fs->update_license_required_permissions_if_anonymous();
18605
18606 $parent_fs->_set_account( $user, $parent_fs->_site );
18607 }
18608
18609 #endregion
18610
18611 #----------------------------------------------------------------------------------
18612 #region Admin Menu Items
18613 #----------------------------------------------------------------------------------
18614
18615 private $_menu_items = array();
18616
18617 /**
18618 * @author Vova Feldman (@svovaf)
18619 * @since 1.2.1.8
18620 *
18621 * @return array
18622 */
18623 function get_menu_items() {
18624 return $this->_menu_items;
18625 }
18626
18627 /**
18628 * @author Vova Feldman (@svovaf)
18629 * @since 1.0.7
18630 *
18631 * @return string
18632 */
18633 function get_menu_slug() {
18634 return $this->_menu->get_slug();
18635 }
18636
18637 /**
18638 * @author Vova Feldman (@svovaf)
18639 * @since 1.0.9
18640 */
18641 function _prepare_admin_menu() {
18642 // if ( ! $this->is_on() ) {
18643 // return;
18644 // }
18645
18646 if ( is_object( $this->_site ) && ! $this->is_registered() ) {
18647 return;
18648 }
18649
18650 /**
18651 * When running from a site admin with a network activated module and the connection
18652 * was NOT delegated and the user still haven't skipped or opted-in, then hide the
18653 * site level settings.
18654 *
18655 * @author Vova Feldman (@svovaf)
18656 * @since 2.0.0
18657 */
18658 $should_hide_site_admin_settings = (
18659 $this->_is_network_active &&
18660 ! fs_is_network_admin() &&
18661 ! $this->is_delegated_connection() &&
18662 ! $this->is_anonymous() &&
18663 ! $this->is_registered()
18664 );
18665
18666 $should_hide_site_admin_settings = $this->apply_filters( 'should_hide_site_admin_settings_on_network_activation_mode', $should_hide_site_admin_settings );
18667
18668 if ( ( false === $this->has_api_connectivity() && ! $this->is_enable_anonymous() ) ||
18669 $should_hide_site_admin_settings
18670 ) {
18671 $this->_menu->remove_menu_item( $should_hide_site_admin_settings );
18672 } else {
18673 $this->do_action( fs_is_network_admin() ?
18674 'before_network_admin_menu_init' :
18675 'before_admin_menu_init'
18676 );
18677
18678 $this->add_menu_action();
18679
18680 $this->add_network_menu_when_missing();
18681
18682 $this->add_submenu_items();
18683 }
18684 }
18685
18686 /**
18687 * Admin dashboard menu items modifications.
18688 *
18689 * NOTE: admin_menu action executed before admin_init.
18690 *
18691 * @author Vova Feldman (@svovaf)
18692 * @since 1.0.7
18693 *
18694 */
18695 private function add_menu_action() {
18696 if ( $this->is_activation_mode() ) {
18697 if ( $this->show_opt_in_on_setting_page() ) {
18698 $this->override_plugin_menu_with_activation();
18699 } else {
18700 /**
18701 * Handle theme opt-in when the opt-in form shows as a dialog box in the themes page.
18702 */
18703 if ( fs_request_is_action( $this->get_unique_affix() . '_activate_existing' ) ) {
18704 add_action( 'load-themes.php', array( &$this, '_install_with_current_user' ) );
18705 } else if ( fs_request_is_action( $this->get_unique_affix() . '_activate_new' ) ||
18706 fs_request_get_bool( 'pending_activation' )
18707 ) {
18708 add_action( 'load-themes.php', array( &$this, '_install_with_new_user' ) );
18709 }
18710 }
18711 } else {
18712 if ( ! $this->is_registered() ) {
18713 // If not registered try to install user.
18714 if ( fs_request_is_action( $this->get_unique_affix() . '_activate_new' ) ) {
18715 $this->_install_with_new_user();
18716 }
18717 } else if (
18718 fs_request_is_action( 'sync_user' ) &&
18719 ( ! $this->has_settings_menu() || $this->show_opt_in_on_themes_page() )
18720 ) {
18721 $this->_handle_account_user_sync();
18722 }
18723 }
18724 }
18725
18726 /**
18727 * @author Vova Feldman (@svovaf)
18728 * @since 1.0.1
18729 */
18730 function _redirect_on_clicked_menu_link() {
18731 $this->_logger->entrance();
18732
18733 $page = fs_request_get('page');
18734 $page = is_string($page) ? strtolower($page) : '';
18735
18736 $this->_logger->log( 'page = ' . $page );
18737
18738 foreach ( $this->_menu_items as $priority => $items ) {
18739 foreach ( $items as $item ) {
18740 if ( isset( $item['url'] ) ) {
18741 if ( $page === $this->_menu->get_slug( strtolower( $item['menu_slug'] ) ) ) {
18742 $this->_logger->log( 'Redirecting to ' . $item['url'] );
18743
18744 fs_redirect( $item['url'] );
18745 }
18746 }
18747 }
18748 }
18749 }
18750
18751 /**
18752 * Remove plugin's all admin menu items & pages, and replace with activation page.
18753 *
18754 * @author Vova Feldman (@svovaf)
18755 * @since 1.0.1
18756 */
18757 private function override_plugin_menu_with_activation() {
18758 $this->_logger->entrance();
18759
18760 $hook = false;
18761
18762 if ( ! $this->has_settings_menu() ) {
18763 // Add the opt-in page without a menu item.
18764 $hook = FS_Admin_Menu_Manager::add_subpage(
18765 '',
18766 $this->get_plugin_name(),
18767 $this->get_plugin_name(),
18768 'manage_options',
18769 $this->_slug,
18770 array( &$this, '_connect_page_render' )
18771 );
18772 } else if ( $this->_menu->is_top_level() ) {
18773 if ( $this->_menu->is_override_exact() ) {
18774 // Make sure the current page is matching the activation page.
18775 if ( ! $this->is_matching_url( $this->get_activation_url() ) ) {
18776 return;
18777 }
18778 }
18779
18780 $hook = $this->_menu->override_menu_item( array( &$this, '_connect_page_render' ) );
18781
18782 if ( false === $hook ) {
18783 // Create new menu item just for the opt-in.
18784 $hook = FS_Admin_Menu_Manager::add_page(
18785 $this->get_plugin_name(),
18786 $this->get_plugin_name(),
18787 'manage_options',
18788 $this->_menu->get_slug(),
18789 array( &$this, '_connect_page_render' )
18790 );
18791 }
18792 } else {
18793 $menus = array( $this->_menu->get_parent_slug() );
18794
18795 if ( $this->_menu->is_override_exact() ) {
18796 // Make sure the current page is matching the activation page.
18797 if ( ! $this->is_matching_url( $this->get_activation_url() ) ) {
18798 return;
18799 }
18800 }
18801
18802 foreach ( $menus as $parent_slug ) {
18803 $hook = $this->_menu->override_submenu_action(
18804 $parent_slug,
18805 $this->_menu->get_raw_slug(),
18806 array( &$this, '_connect_page_render' )
18807 );
18808
18809 if ( false !== $hook ) {
18810 // Found plugin's submenu item.
18811 break;
18812 }
18813 }
18814 }
18815
18816 if ( $this->is_activation_page() ) {
18817 // Clean admin page from distracting content.
18818 self::_clean_admin_content_section();
18819 }
18820
18821 if ( false !== $hook ) {
18822 if ( fs_request_is_action( $this->get_unique_affix() . '_activate_existing' ) ) {
18823 $this->_install_with_current_user();
18824 } else if ( fs_request_is_action( $this->get_unique_affix() . '_activate_new' ) ) {
18825 $this->_install_with_new_user();
18826 }
18827 }
18828 }
18829
18830 /**
18831 * If a plugin was network activated and connected but don't have a network
18832 * level settings, then add an artificial menu item for the Account and other
18833 * Freemius settings.
18834 *
18835 * @author Vova Feldman (@svovaf)
18836 * @since 2.0.0
18837 */
18838 private function add_network_menu_when_missing() {
18839 $this->_logger->entrance();
18840
18841 if ( ! $this->_is_network_active ) {
18842 // Plugin wasn't activated on the network level.
18843 return;
18844 }
18845
18846 if ( ! fs_is_network_admin() ) {
18847 // The context is not the network admin.
18848 return;
18849 }
18850
18851 if ( $this->_menu->has_network_menu() ) {
18852 // Plugin already has a network level menu.
18853 return;
18854 }
18855
18856 if ( $this->is_network_activation_mode() ) {
18857 /**
18858 * Do not add during activation mode, otherwise, there will be duplicate menus while the opt-in
18859 * screen is being shown.
18860 *
18861 * @author Leo Fajardo (@leorw)
18862 */
18863 return;
18864 }
18865
18866 if ( ! WP_FS__SHOW_NETWORK_EVEN_WHEN_DELEGATED ) {
18867 if ( $this->is_network_delegated_connection() ) {
18868 // Super-admin delegated the connection to the site admins.
18869 return;
18870 }
18871 }
18872
18873 if ( ! $this->_menu->has_menu() || $this->_menu->is_top_level() ) {
18874
18875 if ( $this->_menu->has_menu() ||
18876 ! $this->is_addon() ||
18877 $this->is_activation_mode()
18878 ) {
18879 $this->_dynamically_added_top_level_page_hook_name = $this->_menu->add_page_and_update(
18880 $this->get_plugin_name(),
18881 $this->get_plugin_name(),
18882 'manage_options',
18883 $this->_menu->has_menu() ? $this->_menu->get_slug() : $this->_slug
18884 );
18885 }
18886 } else {
18887 $this->_menu->add_subpage_and_update(
18888 $this->_menu->get_parent_slug(),
18889 $this->get_plugin_name(),
18890 $this->get_plugin_name(),
18891 'manage_options',
18892 $this->_menu->get_slug()
18893 );
18894 }
18895 }
18896
18897 /**
18898 * @author Leo Fajardo (@leorw)
18899 * @since 1.2.1
18900 *
18901 * return string
18902 */
18903 function get_top_level_menu_capability() {
18904 global $menu;
18905
18906 $top_level_menu_slug = $this->get_top_level_menu_slug();
18907
18908 foreach ( $menu as $menu_info ) {
18909 /**
18910 * The second element in the menu info array is the capability/role that has access to the menu and the
18911 * third element is the menu slug.
18912 */
18913 if ( $menu_info[2] === $top_level_menu_slug ) {
18914 return $menu_info[1];
18915 }
18916 }
18917
18918 return 'read';
18919 }
18920
18921 /**
18922 * @author Vova Feldman (@svovaf)
18923 * @since 1.0.0
18924 *
18925 * @return string
18926 */
18927 private function get_top_level_menu_slug() {
18928 return ( $this->is_addon() ?
18929 $this->get_parent_instance()->_menu->get_top_level_menu_slug() :
18930 $this->_menu->get_top_level_menu_slug() );
18931 }
18932
18933 /**
18934 * @author Vova Feldman (@svovaf)
18935 * @since 1.2.2.7
18936 *
18937 * @return string
18938 */
18939 function get_pricing_cta_label() {
18940 $label = $this->get_text_inline( 'Upgrade', 'upgrade' );
18941
18942 if ( $this->is_in_trial_promotion() &&
18943 ! $this->is_paying_or_trial()
18944 ) {
18945 // If running a trial promotion, modify the pricing to load the trial.
18946 $label = $this->get_text_inline( 'Start Trial', 'start-trial' );
18947 } else if ( $this->is_paying() ) {
18948 $label = $this->get_text_inline( 'Pricing', 'pricing' );
18949 }
18950
18951 return $label;
18952 }
18953
18954 /**
18955 * @author Vova Feldman (@svovaf)
18956 * @since 1.2.2.7
18957 *
18958 * @return bool
18959 */
18960 function is_pricing_page_visible() {
18961 return (
18962 // Has at least one paid plan.
18963 $this->has_paid_plan() &&
18964 // Didn't ask to hide the pricing page.
18965 $this->is_page_visible( 'pricing' ) &&
18966 // Don't have a valid active license or has more than one plan.
18967 ( ! $this->is_paying() || ! $this->is_single_plan( true ) )
18968 );
18969 }
18970
18971 /**
18972 * @author Leo Fajardo (@leorw)
18973 * @since 2.3.0
18974 *
18975 * @param bool $is_activation_mode
18976 *
18977 * @return bool
18978 */
18979 private function should_add_submenu_or_action_links( $is_activation_mode ) {
18980 if ( $this->is_addon() ) {
18981 // No submenu items or action links for add-ons.
18982 return false;
18983 }
18984
18985 if ( $this->show_opt_in_on_themes_page() ) {
18986 if ( ! fs_is_network_admin() ) {
18987 // Also add action links or submenu items when running in a free .org theme so the tabs will be visible.
18988 return true;
18989 }
18990 } else if ( $is_activation_mode ) {
18991 // Don't show submenu-items/tabs in activation mode, unless it's a wp.org theme.
18992 return false;
18993 }
18994
18995 if ( fs_is_network_admin() ) {
18996 /**
18997 * Add submenu items or action links to network level when plugin was network activated and the super
18998 * admin did NOT delegate the connection of all sites to site admins.
18999 */
19000 return (
19001 $this->_is_network_active &&
19002 ( WP_FS__SHOW_NETWORK_EVEN_WHEN_DELEGATED ||
19003 ! $this->is_network_delegated_connection() )
19004 );
19005 }
19006
19007 return ( ! $this->_is_network_active || $this->is_delegated_connection() );
19008 }
19009
19010 /**
19011 * Add default Freemius menu items.
19012 *
19013 * @author Vova Feldman (@svovaf)
19014 * @since 1.0.0
19015 * @since 1.2.2.7 Also add submenu items when running in a free .org theme so the tabs will be visible.
19016 */
19017 private function add_submenu_items() {
19018 $this->_logger->entrance();
19019
19020 $is_activation_mode = $this->is_activation_mode();
19021
19022 $add_submenu_items = $this->should_add_submenu_or_action_links( $is_activation_mode );
19023
19024 if ( $add_submenu_items ) {
19025 if ( $this->has_affiliate_program() ) {
19026 // Add affiliation page.
19027 $this->add_submenu_item(
19028 $this->get_text_inline( 'Affiliation', 'affiliation' ),
19029 array( &$this, '_affiliation_page_render' ),
19030 $this->get_plugin_name() . ' &ndash; ' . $this->get_text_inline( 'Affiliation', 'affiliation' ),
19031 'manage_options',
19032 'affiliation',
19033 'Freemius::_clean_admin_content_section',
19034 WP_FS__DEFAULT_PRIORITY,
19035 $this->is_submenu_item_visible( 'affiliation' )
19036 );
19037 }
19038 }
19039
19040 if ( $add_submenu_items ||
19041 ( $is_activation_mode &&
19042 $this->is_only_premium() &&
19043 $this->is_admin_page( 'account' ) &&
19044 fs_request_is_action( $this->get_unique_affix() . '_sync_license' )
19045 )
19046 ) {
19047 if ( ! WP_FS__DEMO_MODE && $this->is_registered() ) {
19048 $show_account = (
19049 $this->is_submenu_item_visible( 'account' ) &&
19050 /**
19051 * @since 1.2.2.7 Don't show the Account for free WP.org themes without any paid plans.
19052 */
19053 ( ! $this->is_free_wp_org_theme() || $this->has_paid_plan() )
19054 );
19055
19056 // Add user account page.
19057 $this->add_submenu_item(
19058 $this->get_text_inline( 'Account', 'account' ),
19059 array( &$this, '_account_page_render' ),
19060 $this->get_plugin_name() . ' &ndash; ' . $this->get_text_inline( 'Account', 'account' ),
19061 'manage_options',
19062 'account',
19063 array( &$this, '_account_page_load' ),
19064 WP_FS__DEFAULT_PRIORITY,
19065 ( $add_submenu_items && $show_account )
19066 );
19067 }
19068 }
19069
19070 if ( $add_submenu_items ) {
19071 if (! WP_FS__DEMO_MODE && ! $this->is_whitelabeled() ) {
19072 // Add contact page.
19073 $this->add_submenu_item(
19074 $this->get_text_inline( 'Contact Us', 'contact-us' ),
19075 array( &$this, '_contact_page_render' ),
19076 $this->get_plugin_name() . ' &ndash; ' . $this->get_text_inline( 'Contact Us', 'contact-us' ),
19077 'manage_options',
19078 'contact',
19079 'Freemius::_clean_admin_content_section',
19080 WP_FS__DEFAULT_PRIORITY,
19081 $this->is_submenu_item_visible( 'contact' )
19082 );
19083 }
19084
19085 if ( $this->has_addons() ) {
19086 $this->add_submenu_item(
19087 $this->get_text_inline( 'Add-Ons', 'add-ons' ),
19088 array( &$this, '_addons_page_render' ),
19089 $this->get_plugin_name() . ' &ndash; ' . $this->get_text_inline( 'Add-Ons', 'add-ons' ),
19090 'manage_options',
19091 'addons',
19092 array( &$this, '_addons_page_load' ),
19093 WP_FS__LOWEST_PRIORITY - 1,
19094 $this->is_submenu_item_visible( 'addons' )
19095 );
19096 }
19097 }
19098
19099 if ( $add_submenu_items ||
19100 ( $is_activation_mode && $this->is_only_premium() && $this->is_admin_page( 'pricing' ) )
19101 ) {
19102 if (! WP_FS__DEMO_MODE && ! $this->is_whitelabeled() ) {
19103 $show_pricing = (
19104 $this->is_submenu_item_visible( 'pricing' ) &&
19105 $this->is_pricing_page_visible()
19106 );
19107
19108 $pricing_cta_text = $this->get_pricing_cta_label();
19109 $pricing_class = 'upgrade-mode';
19110 if ( $show_pricing ) {
19111 if ( $this->is_in_trial_promotion() &&
19112 ! $this->is_paying_or_trial()
19113 ) {
19114 // If running a trial promotion, modify the pricing to load the trial.
19115 $pricing_class = 'trial-mode';
19116 } else if ( $this->is_paying() ) {
19117 $pricing_class = '';
19118 }
19119 }
19120
19121 // Add upgrade/pricing page.
19122 $this->add_submenu_item(
19123 $pricing_cta_text . '&nbsp;&nbsp;' . ( is_rtl() ? $this->get_text_x_inline( '&#x2190;', 'ASCII arrow left icon', 'symbol_arrow-left' ) : $this->get_text_x_inline( '&#x27a4;', 'ASCII arrow right icon', 'symbol_arrow-right' ) ),
19124 array( &$this, '_pricing_page_render' ),
19125 $this->get_plugin_name() . ' &ndash; ' . $this->get_text_x_inline( 'Pricing', 'noun', 'pricing' ),
19126 'manage_options',
19127 'pricing',
19128 'Freemius::_clean_admin_content_section',
19129 WP_FS__LOWEST_PRIORITY,
19130 ( $add_submenu_items && $show_pricing ),
19131 $pricing_class
19132 );
19133 }
19134 }
19135
19136 if ( ! $is_activation_mode || ( true !== $this->_storage->require_license_activation ) ) {
19137 /**
19138 * Add the other menu items if there are any when not in activation mode or license activation is not
19139 * required (license activation is required for registered or anonymous users after activating the
19140 * premium version when the site is not in trial mode or there's no active valid license).
19141 *
19142 * @author Leo Fajardo (@leorw)
19143 * @since 2.2.1
19144 */
19145 if ( 0 < count( $this->_menu_items ) ) {
19146 if ( ! $this->_menu->is_top_level() ) {
19147 fs_enqueue_local_style( 'fs_common', '/admin/common.css' );
19148
19149 // Append submenu items right after the plugin's submenu item.
19150 $this->order_sub_submenu_items();
19151 } else {
19152 // Append submenu items.
19153 $this->embed_submenu_items();
19154 }
19155 }
19156 }
19157 }
19158
19159 /**
19160 * Moved the actual submenu item additions to a separated function,
19161 * in order to support sub-submenu items when the plugin's settings
19162 * only have a submenu and not top-level menu item.
19163 *
19164 * @author Vova Feldman (@svovaf)
19165 * @since 1.1.4
19166 */
19167 private function embed_submenu_items() {
19168 $item_template = $this->_menu->is_top_level() ?
19169 '<span class="fs-submenu-item %s %s %s">%s</span>' :
19170 '<span class="fs-submenu-item fs-sub %s %s %s">%s</span>';
19171
19172 $top_level_menu_capability = $this->get_top_level_menu_capability();
19173
19174 ksort( $this->_menu_items );
19175
19176 $is_first_submenu_item = true;
19177
19178 foreach ( $this->_menu_items as $priority => $items ) {
19179 foreach ( $items as $item ) {
19180 $capability = ( ! empty( $item['capability'] ) ? $item['capability'] : $top_level_menu_capability );
19181
19182 $menu_item = sprintf(
19183 $item_template,
19184 $this->get_unique_affix(),
19185 $item['menu_slug'],
19186 ! empty( $item['class'] ) ? $item['class'] : '',
19187 $item['menu_title']
19188 );
19189
19190 $top_level_menu_slug = $this->get_top_level_menu_slug();
19191 $menu_slug = $this->_menu->get_slug( $item['menu_slug'] );
19192
19193 if ( ! isset( $item['url'] ) ) {
19194 $hook = FS_Admin_Menu_Manager::add_subpage(
19195 $item['show_submenu'] ?
19196 $top_level_menu_slug :
19197 '',
19198 $item['page_title'],
19199 $menu_item,
19200 $capability,
19201 $menu_slug,
19202 $item['render_function']
19203 );
19204
19205 if ( false !== $item['before_render_function'] ) {
19206 add_action( "load-$hook", $item['before_render_function'] );
19207 }
19208 } else {
19209 FS_Admin_Menu_Manager::add_subpage(
19210 $item['show_submenu'] ?
19211 $top_level_menu_slug :
19212 '',
19213 $item['page_title'],
19214 $menu_item,
19215 $capability,
19216 $menu_slug,
19217 array( $this, '' )
19218 );
19219 }
19220
19221 if ( $item['show_submenu'] && $is_first_submenu_item ) {
19222 if ( $this->_is_network_active && ! empty( $this->_dynamically_added_top_level_page_hook_name ) ) {
19223 /**
19224 * If the top-level menu has been dynamically created, remove the first submenu item that
19225 * WordPress automatically creates when there's no submenu item whose slug matches the
19226 * parent's. In the following example, the `Awesome Plugin` submenu item will be removed.
19227 *
19228 * Awesome Plugin
19229 * - Awesome Plugin <-- we want to remove this since there's no real setting page for the top-level
19230 *
19231 * @author Leo Fajardo (@leorw)
19232 */
19233 remove_submenu_page( $top_level_menu_slug, $top_level_menu_slug );
19234 }
19235
19236 $is_first_submenu_item = false;
19237 }
19238 }
19239 }
19240 }
19241
19242 /**
19243 * Re-order the submenu items so all Freemius added new submenu items
19244 * are added right after the plugin's settings submenu item.
19245 *
19246 * @author Vova Feldman (@svovaf)
19247 * @since 1.1.4
19248 */
19249 private function order_sub_submenu_items() {
19250 global $submenu;
19251
19252 $menu_slug = $this->_menu->get_top_level_menu_slug();
19253
19254 /**
19255 * Before "admin_menu" fires, WordPress will loop over the default submenus and remove pages for which the user
19256 * does not have permissions. So in case a plugin does not have top-level menu but does have submenus under any
19257 * of the default menus, only users that have the right role can access its sub-submenus (Account, Contact Us,
19258 * Support Forum, etc.) since $submenu[ $menu_slug ] will be empty if the user doesn't have permission.
19259 *
19260 * In case a plugin does not have submenus under any of the default menus but does have submenus under the menu
19261 * of another plugin, only users that have the right role can access its sub-submenus since we will use the
19262 * capability needed to access the parent menu as the capability for the submenus that we will add.
19263 */
19264 if ( empty( $submenu[ $menu_slug ] ) ) {
19265 return;
19266 }
19267
19268 $top_level_menu = &$submenu[ $menu_slug ];
19269
19270 $all_submenu_items_after = array();
19271
19272 $found_submenu_item = false;
19273
19274 foreach ( $top_level_menu as $submenu_id => $meta ) {
19275 if ( $found_submenu_item ) {
19276 // Remove all submenu items after the plugin's submenu item.
19277 $all_submenu_items_after[] = $meta;
19278 unset( $top_level_menu[ $submenu_id ] );
19279 }
19280
19281 if ( $this->_menu->get_raw_slug() === $meta[2] ) {
19282 // Found the submenu item, put all below.
19283 $found_submenu_item = true;
19284 continue;
19285 }
19286 }
19287
19288 // Embed all plugin's new submenu items.
19289 $this->embed_submenu_items();
19290
19291 // Start with specially high number to make sure it's appended.
19292 $i = max( 10000, max( array_keys( $top_level_menu ) ) + 1 );
19293 foreach ( $all_submenu_items_after as $meta ) {
19294 $top_level_menu[ $i ] = $meta;
19295 $i ++;
19296 }
19297
19298 // Sort submenu items.
19299 ksort( $top_level_menu );
19300 }
19301
19302 /**
19303 * Helper method to return the module's support forum URL.
19304 *
19305 * @author Vova Feldman (@svovaf)
19306 * @since 1.2.2.7
19307 *
19308 * @return string
19309 */
19310 function get_support_forum_url() {
19311 return $this->apply_filters( 'support_forum_url', "https://wordpress.org/support/{$this->_module_type}/{$this->_slug}" );
19312 }
19313
19314 /**
19315 * Displays the Support Forum link when enabled.
19316 *
19317 * Can be filtered like so:
19318 *
19319 * function _fs_show_support_menu( $is_visible, $menu_id ) {
19320 * if ( 'support' === $menu_id ) {
19321 * return _fs->is_registered();
19322 * }
19323 * return $is_visible;
19324 * }
19325 * _fs()->add_filter('is_submenu_visible', '_fs_show_support_menu', 10, 2);
19326 *
19327 */
19328 function _add_default_submenu_items() {
19329 if ( ! $this->is_on() ) {
19330 return;
19331 }
19332
19333 if ( ! $this->is_activation_mode() &&
19334 ( ( $this->_is_network_active && fs_is_network_admin() ) ||
19335 ( ! $this->_is_network_active && is_admin() ) )
19336 ) {
19337 $this->add_submenu_link_item(
19338 $this->apply_filters( 'support_forum_submenu', $this->get_text_inline( 'Support Forum', 'support-forum' ) ),
19339 $this->get_support_forum_url(),
19340 'wp-support-forum',
19341 null,
19342 50,
19343 $this->is_submenu_item_visible( 'support' )
19344 );
19345 }
19346 }
19347
19348 /**
19349 * @author Vova Feldman (@svovaf)
19350 * @since 1.0.1
19351 *
19352 * @param string $menu_title
19353 * @param callable $render_function
19354 * @param bool|string $page_title
19355 * @param string $capability
19356 * @param bool|string $menu_slug
19357 * @param bool|callable $before_render_function
19358 * @param int $priority
19359 * @param bool $show_submenu
19360 * @param string $class Since 1.2.1.5 can add custom classes to menu items.
19361 */
19362 function add_submenu_item(
19363 $menu_title,
19364 $render_function,
19365 $page_title = false,
19366 $capability = 'manage_options',
19367 $menu_slug = false,
19368 $before_render_function = false,
19369 $priority = WP_FS__DEFAULT_PRIORITY,
19370 $show_submenu = true,
19371 $class = ''
19372 ) {
19373 $this->_logger->entrance( 'Title = ' . $menu_title );
19374
19375 if ( $this->is_addon() ) {
19376 $parent_fs = $this->get_parent_instance();
19377
19378 if ( is_object( $parent_fs ) ) {
19379 $parent_fs->add_submenu_item(
19380 $menu_title,
19381 $render_function,
19382 $page_title,
19383 $capability,
19384 $menu_slug,
19385 $before_render_function,
19386 $priority,
19387 $show_submenu,
19388 $class
19389 );
19390
19391 return;
19392 }
19393 }
19394
19395 if ( ! isset( $this->_menu_items[ $priority ] ) ) {
19396 $this->_menu_items[ $priority ] = array();
19397 }
19398
19399 $this->_menu_items[ $priority ][] = array(
19400 'page_title' => is_string( $page_title ) ? $page_title : $menu_title,
19401 'menu_title' => $menu_title,
19402 'capability' => $capability,
19403 'menu_slug' => is_string( $menu_slug ) ? $menu_slug : strtolower( $menu_title ),
19404 'render_function' => $render_function,
19405 'before_render_function' => $before_render_function,
19406 'show_submenu' => $show_submenu,
19407 'class' => $class,
19408 );
19409 }
19410
19411 /**
19412 * @author Vova Feldman (@svovaf)
19413 * @since 1.0.1
19414 *
19415 * @param string $menu_title
19416 * @param string $url
19417 * @param bool $menu_slug
19418 * @param string $capability
19419 * @param int $priority
19420 * @param bool $show_submenu
19421 */
19422 function add_submenu_link_item(
19423 $menu_title,
19424 $url,
19425 $menu_slug = false,
19426 $capability = 'read',
19427 $priority = WP_FS__DEFAULT_PRIORITY,
19428 $show_submenu = true
19429 ) {
19430 $this->_logger->entrance( 'Title = ' . $menu_title . '; Url = ' . $url );
19431
19432 if ( $this->is_addon() ) {
19433 $parent_fs = $this->get_parent_instance();
19434
19435 if ( is_object( $parent_fs ) ) {
19436 $parent_fs->add_submenu_link_item(
19437 $menu_title,
19438 $url,
19439 $menu_slug,
19440 $capability,
19441 $priority,
19442 $show_submenu
19443 );
19444
19445 return;
19446 }
19447 }
19448
19449 if ( ! isset( $this->_menu_items[ $priority ] ) ) {
19450 $this->_menu_items[ $priority ] = array();
19451 }
19452
19453 $this->_menu_items[ $priority ][] = array(
19454 'menu_title' => $menu_title,
19455 'capability' => $capability,
19456 'menu_slug' => is_string( $menu_slug ) ? $menu_slug : strtolower( $menu_title ),
19457 'url' => $url,
19458 'page_title' => $menu_title,
19459 'render_function' => 'fs_dummy',
19460 'before_render_function' => '',
19461 'show_submenu' => $show_submenu,
19462 );
19463 }
19464
19465 #endregion ------------------------------------------------------------------
19466
19467 #--------------------------------------------------------------------------------
19468 #region Admin Notices
19469 #--------------------------------------------------------------------------------
19470
19471 /**
19472 * @author Vova Feldman (@svovaf)
19473 * @since 2.3.1
19474 *
19475 * @param string|string[] $ids
19476 * @param int|null $network_level_or_blog_id
19477 *
19478 * @uses FS_Admin_Notices::remove_sticky()
19479 */
19480 function remove_sticky( $ids, $network_level_or_blog_id = null ) {
19481 $this->_admin_notices->remove_sticky( $ids, $network_level_or_blog_id );
19482 }
19483
19484 #endregion
19485
19486 #--------------------------------------------------------------------------------
19487 #region Actions / Hooks / Filters
19488 #--------------------------------------------------------------------------------
19489
19490 /**
19491 * @author Vova Feldman (@svovaf)
19492 * @since 1.1.7
19493 *
19494 * @param string $tag
19495 *
19496 * @return string
19497 */
19498 public function get_action_tag( $tag ) {
19499 return self::get_action_tag_static( $tag, $this->_slug, $this->is_plugin() );
19500 }
19501
19502 /**
19503 * @author Vova Feldman (@svovaf)
19504 * @since 1.2.1.6
19505 *
19506 * @param string $tag
19507 * @param string $slug
19508 * @param bool $is_plugin
19509 *
19510 * @return string
19511 */
19512 static function get_action_tag_static( $tag, $slug = '', $is_plugin = true ) {
19513 $action = "fs_{$tag}";
19514
19515 if ( ! empty( $slug ) ) {
19516 $action .= '_' . self::get_module_unique_affix( $slug, $is_plugin );
19517 }
19518
19519 return $action;
19520 }
19521
19522 /**
19523 * Returns a string that can be used to generate a unique action name,
19524 * option name, HTML element ID, or HTML element class.
19525 *
19526 * @author Leo Fajardo (@leorw)
19527 * @since 1.2.2
19528 *
19529 * @return string
19530 */
19531 public function get_unique_affix() {
19532 return self::get_module_unique_affix( $this->_slug, $this->is_plugin() );
19533 }
19534
19535 /**
19536 * Returns a string that can be used to generate a unique action name,
19537 * option name, HTML element ID, or HTML element class.
19538 *
19539 * @author Vova Feldman (@svovaf)
19540 * @since 1.2.2.5
19541 *
19542 * @param string $slug
19543 * @param bool $is_plugin
19544 *
19545 * @return string
19546 */
19547 static function get_module_unique_affix( $slug, $is_plugin = true ) {
19548 $affix = $slug;
19549
19550 if ( ! $is_plugin ) {
19551 $affix .= '-' . WP_FS__MODULE_TYPE_THEME;
19552 }
19553
19554 return $affix;
19555 }
19556
19557 /**
19558 * @author Vova Feldman (@svovaf)
19559 * @since 1.2.1
19560 * @since 1.2.2.5 The AJAX action names are based on the module ID, not like the non-AJAX actions that are
19561 * based on the slug for backward compatibility.
19562 *
19563 * @param string $tag
19564 *
19565 * @return string
19566 */
19567 function get_ajax_action( $tag ) {
19568 return self::get_ajax_action_static( $tag, $this->_module_id );
19569 }
19570
19571 /**
19572 * @author Vova Feldman (@svovaf)
19573 * @since 1.2.1.7
19574 *
19575 * @param string $tag
19576 *
19577 * @return string
19578 */
19579 function get_ajax_security( $tag ) {
19580 return wp_create_nonce( $this->get_ajax_action( $tag ) );
19581 }
19582
19583 /**
19584 * @author Vova Feldman (@svovaf)
19585 * @since 1.2.1.7
19586 *
19587 * @param string $tag
19588 */
19589 function check_ajax_referer( $tag ) {
19590 check_ajax_referer( $this->get_ajax_action( $tag ), 'security' );
19591 }
19592
19593 /**
19594 * @author Vova Feldman (@svovaf)
19595 * @since 1.2.1.6
19596 * @since 1.2.2.5 The AJAX action names are based on the module ID, not like the non-AJAX actions that are
19597 * based on the slug for backward compatibility.
19598 *
19599 * @param string $tag
19600 * @param number|null $module_id
19601 *
19602 * @return string
19603 */
19604 static function get_ajax_action_static( $tag, $module_id = null ) {
19605 $action = "fs_{$tag}";
19606
19607 if ( ! empty( $module_id ) ) {
19608 $action .= "_{$module_id}";
19609 }
19610
19611 return $action;
19612 }
19613
19614 /**
19615 * Do action, specific for the current context plugin.
19616 *
19617 * @author Vova Feldman (@svovaf)
19618 * @since 1.0.1
19619 *
19620 * @param string $tag The name of the action to be executed.
19621 * @param mixed $arg,... Optional. Additional arguments which are passed on to the
19622 * functions hooked to the action. Default empty.
19623 *
19624 * @uses do_action()
19625 */
19626 function do_action( $tag, $arg = '' ) {
19627 $args = func_get_args();
19628
19629 $this->_logger->entrance( $tag );
19630
19631 call_user_func_array( 'do_action', array_merge(
19632 array( $this->get_action_tag( $tag ) ),
19633 array_slice( $args, 1 ) )
19634 );
19635 }
19636
19637 /**
19638 * Add action, specific for the current context plugin.
19639 *
19640 * @author Vova Feldman (@svovaf)
19641 * @since 1.0.1
19642 *
19643 * @param string $tag
19644 * @param callable $function_to_add
19645 * @param int $priority
19646 * @param int $accepted_args
19647 *
19648 * @uses add_action()
19649 */
19650 function add_action(
19651 $tag,
19652 $function_to_add,
19653 $priority = WP_FS__DEFAULT_PRIORITY,
19654 $accepted_args = 1
19655 ) {
19656 $this->_logger->entrance( $tag );
19657
19658 add_action( $this->get_action_tag( $tag ), $function_to_add, $priority, $accepted_args );
19659 }
19660
19661 /**
19662 * Add AJAX action, specific for the current context plugin.
19663 *
19664 * @author Vova Feldman (@svovaf)
19665 * @since 1.2.1
19666 *
19667 * @param string $tag
19668 * @param callable $function_to_add
19669 * @param int $priority
19670 *
19671 * @uses add_action()
19672 *
19673 * @return bool True if action added, false if no need to add the action since the AJAX call isn't matching.
19674 */
19675 function add_ajax_action(
19676 $tag,
19677 $function_to_add,
19678 $priority = WP_FS__DEFAULT_PRIORITY
19679 ) {
19680 $this->_logger->entrance( $tag );
19681
19682 return self::add_ajax_action_static(
19683 $tag,
19684 $function_to_add,
19685 $priority,
19686 $this->_module_id
19687 );
19688 }
19689
19690 /**
19691 * Add AJAX action.
19692 *
19693 * @author Vova Feldman (@svovaf)
19694 * @since 1.2.1.6
19695 *
19696 * @param string $tag
19697 * @param callable $function_to_add
19698 * @param int $priority
19699 * @param number|null $module_id
19700 *
19701 * @return bool True if action added, false if no need to add the action since the AJAX call isn't matching.
19702 * @uses add_action()
19703 *
19704 */
19705 static function add_ajax_action_static(
19706 $tag,
19707 $function_to_add,
19708 $priority = WP_FS__DEFAULT_PRIORITY,
19709 $module_id = null
19710 ) {
19711 self::$_static_logger->entrance( $tag );
19712
19713 if ( ! self::is_ajax_action_static( $tag, $module_id ) ) {
19714 return false;
19715 }
19716
19717 add_action(
19718 'wp_ajax_' . self::get_ajax_action_static( $tag, $module_id ),
19719 $function_to_add,
19720 $priority,
19721 0
19722 );
19723
19724 self::$_static_logger->info( "$tag AJAX callback action added." );
19725
19726 return true;
19727 }
19728
19729 /**
19730 * Send a JSON response back to an Ajax request.
19731 *
19732 * @author Vova Feldman (@svovaf)
19733 * @since 1.2.1.5
19734 *
19735 * @param mixed $response
19736 */
19737 static function shoot_ajax_response( $response ) {
19738 wp_send_json( $response );
19739 }
19740
19741 /**
19742 * Send a JSON response back to an Ajax request, indicating success.
19743 *
19744 * @author Vova Feldman (@svovaf)
19745 * @since 1.2.1.5
19746 *
19747 * @param mixed $data Data to encode as JSON, then print and exit.
19748 */
19749 static function shoot_ajax_success( $data = null ) {
19750 wp_send_json_success( $data );
19751 }
19752
19753 /**
19754 * Send a JSON response back to an Ajax request, indicating failure.
19755 *
19756 * @author Vova Feldman (@svovaf)
19757 * @since 1.2.1.5
19758 *
19759 * @param mixed $error Optional error message.
19760 */
19761 static function shoot_ajax_failure( $error = '' ) {
19762 $result = array( 'success' => false );
19763 if ( ! empty( $error ) ) {
19764 $result['error'] = $error;
19765 }
19766
19767 wp_send_json( $result );
19768 }
19769
19770 /**
19771 * Returns an AJAX URL with a special extra param to indicate whether the request was triggered from the network admin or blog admin.
19772 *
19773 * @author Vova Feldman (@svovaf)
19774 * @since 2.5.1
19775 *
19776 * @param string $wrap_with By default, returns the AJAX URL wrapped with single quotes.
19777 *
19778 * @return string
19779 */
19780 static function ajax_url( $wrap_with = "'") {
19781 if ( fs_is_network_admin() ) {
19782 $param_name = '_fs_network_admin';
19783 } else {
19784 $param_name = '_fs_blog_admin';
19785 }
19786
19787 $url = admin_url( 'admin-ajax.php', 'relative' );
19788 $url .= ( false === strpos( $url, '?' ) ) ? '?' : '&';
19789 $url .= "{$param_name}=true";
19790
19791 return "{$wrap_with}{$url}{$wrap_with}";
19792 }
19793
19794 /**
19795 * Apply filter, specific for the current context plugin.
19796 *
19797 * @author Vova Feldman (@svovaf)
19798 * @since 1.0.9
19799 *
19800 * @param string $tag The name of the filter hook.
19801 * @param mixed $value The value on which the filters hooked to `$tag` are applied on.
19802 *
19803 * @return mixed The filtered value after all hooked functions are applied to it.
19804 *
19805 * @uses apply_filters()
19806 */
19807 function apply_filters( $tag, $value ) {
19808 $args = func_get_args();
19809
19810 $this->_logger->entrance( $tag );
19811
19812 array_unshift( $args, $this->get_unique_affix() );
19813
19814 return call_user_func_array( 'fs_apply_filter', $args );
19815 }
19816
19817 /**
19818 * Add filter, specific for the current context plugin.
19819 *
19820 * @author Vova Feldman (@svovaf)
19821 * @since 1.0.9
19822 *
19823 * @param string $tag
19824 * @param callable $function_to_add
19825 * @param int $priority
19826 * @param int $accepted_args
19827 *
19828 * @uses add_filter()
19829 */
19830 function add_filter( $tag, $function_to_add, $priority = WP_FS__DEFAULT_PRIORITY, $accepted_args = 1 ) {
19831 $this->_logger->entrance( $tag );
19832
19833 add_filter( $this->get_action_tag( $tag ), $function_to_add, $priority, $accepted_args );
19834 }
19835
19836 /**
19837 * Check if has filter.
19838 *
19839 * @author Vova Feldman (@svovaf)
19840 * @since 1.1.4
19841 *
19842 * @param string $tag
19843 * @param callable|bool $function_to_check Optional. The callback to check for. Default false.
19844 *
19845 * @return false|int
19846 *
19847 * @uses has_filter()
19848 */
19849 function has_filter( $tag, $function_to_check = false ) {
19850 $this->_logger->entrance( $tag );
19851
19852 return has_filter( $this->get_action_tag( $tag ), $function_to_check );
19853 }
19854
19855 #endregion
19856
19857 /**
19858 * Override default i18n text phrases.
19859 *
19860 * @author Vova Feldman (@svovaf)
19861 * @since 1.1.6
19862 *
19863 * @param string[] string $key_value
19864 *
19865 * @uses fs_override_i18n()
19866 */
19867 function override_i18n( $key_value ) {
19868 fs_override_i18n( $key_value, $this->_slug );
19869 }
19870
19871 /* Account Page
19872 ------------------------------------------------------------------------------------------------------------------*/
19873 /**
19874 * Update site information.
19875 *
19876 * @author Vova Feldman (@svovaf)
19877 * @since 1.0.1
19878 *
19879 * @param bool $store Flush to Database if true.
19880 * @param null|int $network_level_or_blog_id Since 2.0.0
19881 * @param \FS_Site $site Since 2.0.0
19882 */
19883 private function _store_site( $store = true, $network_level_or_blog_id = null, FS_Site $site = null, $is_backup = false ) {
19884 $this->_logger->entrance();
19885
19886 if ( is_null( $site ) ) {
19887 $site = $this->_site;
19888 }
19889
19890 if ( !isset( $site ) || !is_object($site) || empty( $site->id ) ) {
19891 $this->_logger->error( "Empty install ID, can't store site." );
19892
19893 return;
19894 }
19895
19896 $site_clone = clone $site;
19897
19898 $sites = self::get_all_sites( $this->_module_type, $network_level_or_blog_id, $is_backup );
19899
19900 if (
19901 ! $is_backup &&
19902 is_object( $this->_user ) && $this->_user->id != $site->user_id
19903 ) {
19904 $this->sync_user_by_current_install( $site->user_id );
19905
19906 $prev_stored_user_id = $this->_storage->get( 'prev_user_id', false, $network_level_or_blog_id );
19907
19908 if ( empty( $prev_stored_user_id ) &&
19909 is_object($this->_user) && $this->_user->id != $site->user_id
19910 ) {
19911 /**
19912 * Store the current user ID as the previous user ID so that the previous user can be used
19913 * as the install's owner while the new owner's details are not yet available.
19914 *
19915 * This will be executed only in the `replica` site. For example, there are 2 sites, namely `original`
19916 * and `replica`, then an ownership change was initiated and completed in the `original`, the `replica`
19917 * will be using the previous user until it is updated again (e.g.: until the next clone of `original`
19918 * into `replica`.
19919 *
19920 * @author Leo Fajardo (@leorw)
19921 */
19922 $this->_storage->store( 'prev_user_id', $sites[ $this->_slug ]->user_id, $network_level_or_blog_id );
19923 }
19924 }
19925
19926 $sites[ $this->_slug ] = $site_clone;
19927
19928 $this->set_account_option(
19929 ( $is_backup ? 'prev_' : '' ) . 'sites',
19930 $sites,
19931 $store,
19932 $network_level_or_blog_id
19933 );
19934 }
19935
19936 /**
19937 * Stores the context site in the sites backup storage. This logic is used before deleting the site info so that it can be restored later on if necessary (e.g., if the automatic clone resolution attempt fails).
19938 *
19939 * @author Leo Fajardo (@leorw)
19940 * @since 2.5.0
19941 */
19942 private function back_up_site() {
19943 $this->_logger->entrance();
19944
19945 $site_clone = clone $this->_site;
19946
19947 $this->_store_site( true, null, $site_clone, true );
19948 }
19949
19950 /**
19951 * Update plugin's plans information.
19952 *
19953 * @author Vova Feldman (@svovaf)
19954 * @since 1.0.2
19955 *
19956 * @param bool $store Flush to Database if true.
19957 */
19958 private function _store_plans( $store = true ) {
19959 $this->_logger->entrance();
19960
19961 $plans = self::get_all_plans( $this->_module_type );
19962
19963 // Copy plans.
19964 $encrypted_plans = array();
19965 for ( $i = 0, $len = count( $this->_plans ); $i < $len; $i ++ ) {
19966 $encrypted_plans[] = self::_encrypt_entity( $this->_plans[ $i ] );
19967 }
19968
19969 $plans[ $this->_slug ] = $encrypted_plans;
19970
19971 $this->set_account_option( 'plans', $plans, $store );
19972 }
19973
19974 /**
19975 * Update user's plugin licenses.
19976 *
19977 * @author Vova Feldman (@svovaf)
19978 * @since 1.0.5
19979 *
19980 * @param bool $store
19981 * @param number|bool $module_id
19982 * @param FS_Plugin_License[] $licenses
19983 */
19984 private function _store_licenses( $store = true, $module_id = false, $licenses = array() ) {
19985 $this->_logger->entrance();
19986
19987 $all_licenses = self::get_all_licenses();
19988
19989 if ( ! FS_Plugin::is_valid_id( $module_id ) ) {
19990 $module_id = $this->_module_id;
19991
19992 $user_licenses = is_array( $this->_licenses ) ?
19993 $this->_licenses :
19994 array();
19995
19996 if ( empty( $user_licenses ) ) {
19997 // If the context user doesn't have any license, don't update the licenses collection.
19998 return;
19999 }
20000
20001 $new_user_licenses_map = array();
20002 foreach ( $user_licenses as $user_license ) {
20003 $new_user_licenses_map[ $user_license->id ] = $user_license;
20004 }
20005
20006 self::store_user_id_license_ids_map( array_keys( $new_user_licenses_map ), $this->_module_id, $this->_user->id );
20007
20008 // Update user licenses.
20009 $licenses_to_update_count = count( $new_user_licenses_map );
20010 foreach ( $all_licenses[ $module_id ] as $key => $license ) {
20011 if ( 0 === $licenses_to_update_count ) {
20012 break;
20013 }
20014
20015 if ( isset( $new_user_licenses_map[ $license->id ] ) ) {
20016 // Update license.
20017 $all_licenses[ $module_id ][ $key ] = $new_user_licenses_map[ $license->id ];
20018 unset( $new_user_licenses_map[ $license->id ] );
20019
20020 $licenses_to_update_count --;
20021 }
20022 }
20023
20024 if ( ! empty( $new_user_licenses_map ) ) {
20025 // Add new licenses.
20026 $all_licenses[ $module_id ] = array_merge( array_values( $new_user_licenses_map ), $all_licenses[ $module_id ] );
20027 }
20028
20029 $licenses = $all_licenses[ $module_id ];
20030 }
20031
20032 if ( ! isset( $all_licenses[ $module_id ] ) ) {
20033 $all_licenses[ $module_id ] = array();
20034 }
20035
20036 $all_licenses[ $module_id ] = $licenses;
20037
20038 self::$_accounts->set_option( 'all_licenses', $all_licenses, $store );
20039 }
20040
20041 /**
20042 * Update user information.
20043 *
20044 * @author Vova Feldman (@svovaf)
20045 * @since 1.0.1
20046 *
20047 * @param bool $store Flush to Database if true.
20048 */
20049 private function _store_user( $store = true ) {
20050 $this->_logger->entrance();
20051
20052 if ( empty( $this->_user->id ) ) {
20053 $this->_logger->error( "Empty user ID, can't store user." );
20054
20055 return;
20056 }
20057
20058 $users = self::get_all_users();
20059 $users[ $this->_user->id ] = $this->_user;
20060 self::$_accounts->set_option( 'users', $users, $store );
20061 }
20062
20063 /**
20064 * Update new updates information.
20065 *
20066 * @author Vova Feldman (@svovaf)
20067 * @since 1.0.4
20068 *
20069 * @param FS_Plugin_Tag|null $update
20070 * @param bool $store Flush to Database if true.
20071 * @param bool|number $plugin_id
20072 */
20073 private function _store_update( $update, $store = true, $plugin_id = false ) {
20074 $this->_logger->entrance();
20075
20076 if ( $update instanceof FS_Plugin_Tag ) {
20077 $update->updated = time();
20078 }
20079
20080 if ( ! is_numeric( $plugin_id ) ) {
20081 $plugin_id = $this->_plugin->id;
20082 }
20083
20084 $updates = self::get_all_updates();
20085 $updates[ $plugin_id ] = $update;
20086 self::$_accounts->set_option( 'updates', $updates, $store );
20087 }
20088
20089 /**
20090 * Update new updates information.
20091 *
20092 * @author Vova Feldman (@svovaf)
20093 * @since 1.0.6
20094 *
20095 * @param FS_Plugin[] $plugin_addons
20096 * @param bool $store Flush to Database if true.
20097 */
20098 private function _store_addons( $plugin_addons, $store = true ) {
20099 $this->_logger->entrance();
20100
20101 $addons = self::get_all_addons();
20102 $addons[ $this->_plugin->id ] = $plugin_addons;
20103 self::$_accounts->set_option( 'addons', $addons, $store );
20104 }
20105
20106 /**
20107 * Delete plugin's associated add-ons.
20108 *
20109 * @author Vova Feldman (@svovaf)
20110 * @since 1.0.8
20111 *
20112 * @param bool $store
20113 *
20114 * @return bool
20115 */
20116 private function _delete_account_addons( $store = true ) {
20117 $all_addons = self::get_all_account_addons();
20118
20119 if ( ! isset( $all_addons[ $this->_plugin->id ] ) ) {
20120 return false;
20121 }
20122
20123 unset( $all_addons[ $this->_plugin->id ] );
20124
20125 self::$_accounts->set_option( 'account_addons', $all_addons, $store );
20126
20127 return true;
20128 }
20129
20130 /**
20131 * Update account add-ons list.
20132 *
20133 * @author Vova Feldman (@svovaf)
20134 * @since 1.0.6
20135 *
20136 * @param FS_Plugin[] $addons
20137 * @param bool $store Flush to Database if true.
20138 */
20139 private function _store_account_addons( $addons, $store = true ) {
20140 $this->_logger->entrance();
20141
20142 $all_addons = self::get_all_account_addons();
20143 $all_addons[ $this->_plugin->id ] = $addons;
20144 self::$_accounts->set_option( 'account_addons', $all_addons, $store );
20145 }
20146
20147 /**
20148 * Purges the cache for the valid user licenses API call so that when the `Account` or `Add-Ons` page is loaded,
20149 * the valid user licenses will be fetched again and the account add-ons may be updated.
20150 *
20151 * @author Leo Fajardo (@leorw)
20152 * @since 2.2.4
20153 */
20154 private function purge_valid_user_licenses_cache() {
20155 if ( ! $this->is_registered() ) {
20156 return;
20157 }
20158
20159 $this->get_api_user_scope()->purge_cache( $this->get_valid_user_licenses_endpoint() );
20160 }
20161
20162 /**
20163 * @author Leo Fajardo (@leorw)
20164 * @since 2.3.0
20165 *
20166 * @param array $all_licenses
20167 * @param number|null $site_license_id
20168 * @param bool $include_parent_licenses
20169 *
20170 * @return array
20171 */
20172 private function get_foreign_licenses_info( $all_licenses, $site_license_id = null, $include_parent_licenses = false ) {
20173 $foreign_licenses = array(
20174 'ids' => array(),
20175 'license_keys' => array()
20176 );
20177
20178 $parent_license_ids_map = array();
20179
20180 foreach ( $all_licenses as $license ) {
20181 if ( $license->user_id == $this->_user->id || $license->id == $site_license_id ) {
20182 continue;
20183 }
20184
20185 $foreign_licenses['ids'][] = $license->id;
20186 $foreign_licenses['license_keys'][] = $license->secret_key;
20187
20188 if (
20189 $include_parent_licenses &&
20190 is_object( $this->_license ) &&
20191 FS_Plugin_License::is_valid_id( $this->_license->parent_license_id ) &&
20192 ! isset( $parent_license_ids_map[ $this->_license->parent_license_id ] )
20193 ) {
20194 /**
20195 * Include the parent license's info only if it has not been included before since child licenses
20196 * can have the same parent license.
20197 */
20198 $foreign_licenses['ids'][] = $this->_license->parent_license_id;
20199 $foreign_licenses['license_keys'][] = $license->secret_key;
20200
20201 $parent_license_ids_map[ $this->_license->parent_license_id ] = true;
20202 }
20203 }
20204
20205 if ( empty( $foreign_licenses['ids'] ) ) {
20206 $foreign_licenses = array();
20207 }
20208
20209 return $foreign_licenses;
20210 }
20211
20212 /**
20213 * @author Leo Fajardo (@leorw)
20214 * @since 2.3.0
20215 *
20216 * @return string
20217 */
20218 private function get_valid_user_licenses_endpoint() {
20219 $user_licenses_endpoint = '/licenses.json?type=active' .
20220 ( FS_Plugin::is_valid_id( $this->get_bundle_id() ) ? '&is_enriched=true' : '' );
20221
20222 $foreign_licenses = $this->get_foreign_licenses_info( self::get_all_licenses( $this->_module_id ), null, true );
20223
20224 if ( ! empty ( $foreign_licenses ) ) {
20225 $foreign_licenses = array(
20226 // Prefix with `+` to tell the server to include foreign licenses in the licenses collection.
20227 'ids' => ( urlencode( '+' ) . implode( ',', $foreign_licenses['ids'] ) ),
20228 'license_keys' => implode( ',', array_map( 'urlencode', $foreign_licenses['license_keys'] ) )
20229 );
20230
20231 $user_licenses_endpoint = add_query_arg( $foreign_licenses, $user_licenses_endpoint );
20232 }
20233
20234 return $user_licenses_endpoint;
20235 }
20236
20237 /**
20238 * Fetches active licenses that are enriched with product type if there's a context `bundle_id` and bundle
20239 * licenses enriched with product IDs if there are any. From the licenses, the `get_updated_account_addons`
20240 * method filters out non–add-on product IDs and stores the add-on IDs.
20241 *
20242 * @author Leo Fajardo (@leorw)
20243 * @since 2.2.4
20244 *
20245 * @return stdClass[] array
20246 */
20247 private function fetch_valid_user_licenses() {
20248 $this->_logger->entrance();
20249
20250 $result = $this->get_api_user_scope()->get( $this->get_valid_user_licenses_endpoint() );
20251
20252 if ( ! $this->is_api_result_object( $result, 'licenses' ) ||
20253 ! is_array( $result->licenses )
20254 ) {
20255 return array();
20256 }
20257
20258 return $result->licenses;
20259 }
20260
20261 /**
20262 * @author Leo Fajardo (@leorw)
20263 * @since 2.2.4
20264 *
20265 * @return number[] Account add-on IDs.
20266 */
20267 function get_updated_account_addons() {
20268 $addons = $this->get_addons();
20269 if ( empty( $addons ) ) {
20270 return array();
20271 }
20272
20273 $account_addons = $this->get_account_addons();
20274 if ( ! is_array( $account_addons ) ) {
20275 $account_addons = array();
20276 }
20277
20278 $user_licenses = $this->is_registered() ?
20279 $this->fetch_valid_user_licenses() :
20280 array();
20281
20282 if ( empty( $user_licenses ) ) {
20283 return $account_addons;
20284 }
20285
20286 $addon_ids = array();
20287 foreach ( $addons as $addon ) {
20288 $addon_ids[] = $addon->id;
20289 }
20290
20291 $license_product_ids = array();
20292
20293 foreach ( $user_licenses as $license ) {
20294 if ( isset( $license->plugin_type ) && 'bundle' === $license->plugin_type ) {
20295 $license_product_ids = array_merge( $license_product_ids, $license->products );
20296 } else {
20297 $license_product_ids[] = $license->plugin_id;
20298 }
20299 }
20300
20301 // Filter out non–add-on IDs.
20302 $new_account_addons = array_intersect( $addon_ids, $license_product_ids );
20303 if ( count( $new_account_addons ) !== count( $account_addons ) ) {
20304 $this->_store_account_addons( array_unique( $new_account_addons ) );
20305 }
20306
20307 return $new_account_addons;
20308 }
20309
20310 /**
20311 * Store account params in the Database.
20312 *
20313 * @author Vova Feldman (@svovaf)
20314 * @since 1.0.1
20315 *
20316 * @param null|int $blog_id Since 2.0.0
20317 */
20318 private function _store_account( $blog_id = null ) {
20319 $this->_logger->entrance();
20320
20321 $this->_store_site( false, $blog_id );
20322 $this->_store_user( false );
20323 $this->_store_plans( false );
20324 $this->_store_licenses( false );
20325
20326 self::$_accounts->store( $blog_id );
20327 }
20328
20329 /**
20330 * Sync user's information.
20331 *
20332 * @author Vova Feldman (@svovaf)
20333 * @since 1.0.3
20334 * @uses FS_Api
20335 */
20336 private function _handle_account_user_sync() {
20337 $this->_logger->entrance();
20338
20339 $api = $this->get_api_user_scope();
20340
20341 // Get user's information.
20342 $user = $api->get( '/', true );
20343
20344 if ( isset( $user->id ) ) {
20345 $this->_user->first = $user->first;
20346 $this->_user->last = $user->last;
20347 $this->_user->email = $user->email;
20348
20349 $is_menu_item_account_visible = $this->is_submenu_item_visible( 'account' );
20350
20351 if ( $user->is_verified &&
20352 ( ! isset( $this->_user->is_verified ) || false === $this->_user->is_verified )
20353 ) {
20354 $this->_user->is_verified = true;
20355
20356 $this->do_action( 'account_email_verified', $user->email );
20357
20358 $this->_admin_notices->add(
20359 $this->get_text_inline( 'Your email has been successfully verified - you are AWESOME!', 'email-verified-message' ),
20360 $this->get_text_x_inline( 'Right on', 'a positive response', 'right-on' ) . '!',
20361 'success',
20362 // Make admin sticky if account menu item is invisible,
20363 // since the page will be auto redirected to the plugin's
20364 // main settings page, and the non-sticky message
20365 // will disappear.
20366 ! $is_menu_item_account_visible,
20367 'email_verified'
20368 );
20369 }
20370
20371 // Flush user details to DB.
20372 $this->_store_user();
20373
20374 $this->do_action( 'after_account_user_sync', $user );
20375
20376 /**
20377 * If account menu item is hidden, redirect to plugin's main settings page.
20378 *
20379 * @author Vova Feldman (@svovaf)
20380 * @since 1.1.6
20381 *
20382 * @link https://github.com/Freemius/wordpress-sdk/issues/6
20383 */
20384 if ( ! $is_menu_item_account_visible ) {
20385 fs_redirect( $this->_get_admin_page_url() );
20386 }
20387 }
20388 }
20389
20390 /**
20391 * @author Vova Feldman (@svovaf)
20392 * @since 1.0.9
20393 * @uses FS_Api
20394 *
20395 * @param number|bool $license_id
20396 *
20397 * @return FS_Subscription|object|bool
20398 */
20399 private function _fetch_site_license_subscription( $license_id = false ) {
20400 $this->_logger->entrance();
20401 $api = $this->get_api_site_scope();
20402
20403 if ( ! is_numeric( $license_id ) ) {
20404 $license_id = FS_Plugin_License::is_valid_id( $this->_license->parent_license_id ) ?
20405 $this->_license->parent_license_id :
20406 $this->_license->id;
20407 }
20408
20409 $result = $api->get( "/licenses/{$license_id}/subscriptions.json", true );
20410
20411 return ! isset( $result->error ) ?
20412 ( ( is_array( $result->subscriptions ) && 0 < count( $result->subscriptions ) ) ?
20413 new FS_Subscription( $result->subscriptions[0] ) :
20414 false
20415 ) :
20416 $result;
20417 }
20418
20419 /**
20420 * @author Vova Feldman (@svovaf)
20421 * @since 1.0.4
20422 * @uses FS_Api
20423 *
20424 * @param number|bool $plan_id
20425 *
20426 * @return FS_Plugin_Plan|object
20427 */
20428 private function _fetch_site_plan( $plan_id = false ) {
20429 $this->_logger->entrance();
20430 $api = $this->get_api_site_scope();
20431
20432 if ( ! is_numeric( $plan_id ) ) {
20433 $plan_id = $this->_site->plan_id;
20434 }
20435
20436 $plan = $api->get( "/plans/{$plan_id}.json", true );
20437
20438 return ! isset( $plan->error ) ? new FS_Plugin_Plan( $plan ) : $plan;
20439 }
20440
20441 /**
20442 * @author Vova Feldman (@svovaf)
20443 * @since 1.0.5
20444 * @uses FS_Api
20445 *
20446 * @return FS_Plugin_Plan[]|object
20447 */
20448 private function _fetch_plugin_plans() {
20449 $this->_logger->entrance();
20450 $api = $this->get_current_or_network_user_api_scope();
20451
20452 /**
20453 * @since 1.2.3 When running in DEV mode, retrieve pending plans as well.
20454 */
20455 $result = $api->get( $this->add_show_pending( "/plugins/{$this->_module_id}/plans.json" ), true );
20456
20457 if ( $this->is_api_result_object( $result, 'plans' ) && is_array( $result->plans ) ) {
20458 for ( $i = 0, $len = count( $result->plans ); $i < $len; $i ++ ) {
20459 $result->plans[ $i ] = new FS_Plugin_Plan( $result->plans[ $i ] );
20460 }
20461
20462 $result = $result->plans;
20463 }
20464
20465 return $result;
20466 }
20467
20468 /**
20469 * @author Vova Feldman (@svovaf)
20470 * @since 2.0.0
20471 *
20472 * @param number $plan_id
20473 *
20474 * @return \FS_Plugin_Plan|object
20475 */
20476 private function fetch_plan_by_id( $plan_id ) {
20477 $this->_logger->entrance();
20478 $api = $this->get_current_or_network_user_api_scope();
20479
20480 $result = $api->get( "/plugins/{$this->_module_id}/plans/{$plan_id}.json", true );
20481
20482 return $this->is_api_result_entity( $result ) ?
20483 new FS_Plugin_Plan( $result ) :
20484 $result;
20485 }
20486
20487 /**
20488 * @author Vova Feldman (@svovaf)
20489 * @since 1.0.5
20490 * @uses FS_Api
20491 *
20492 * @param number|bool $plugin_id
20493 * @param number|bool $site_license_id
20494 * @param array $foreign_licenses @since 2.0.0. This is used by network-activated plugins.
20495 * @param number|null $blog_id
20496 *
20497 * @return FS_Plugin_License[]|object
20498 */
20499 private function _fetch_licenses(
20500 $plugin_id = false,
20501 $site_license_id = false,
20502 $foreign_licenses = array(),
20503 $blog_id = null
20504 ) {
20505 $this->_logger->entrance();
20506
20507 $api = $this->get_api_user_scope();
20508
20509 if ( ! is_numeric( $plugin_id ) ) {
20510 $plugin_id = $this->_plugin->id;
20511 }
20512
20513 $user_licenses_endpoint = "/plugins/{$plugin_id}/licenses.json?is_enriched=true";
20514 if ( ! empty ( $foreign_licenses ) ) {
20515 $foreign_licenses = array(
20516 // Prefix with `+` to tell the server to include foreign licenses in the licenses collection.
20517 'ids' => ( urlencode( '+' ) . implode( ',', $foreign_licenses['ids'] ) ),
20518 'license_keys' => implode( ',', array_map( 'urlencode', $foreign_licenses['license_keys'] ) )
20519 );
20520
20521 $user_licenses_endpoint = add_query_arg( $foreign_licenses, $user_licenses_endpoint );
20522 }
20523
20524 $result = $api->get( $user_licenses_endpoint, true );
20525
20526 $is_site_license_synced = false;
20527
20528 $api_errors = array();
20529
20530 if ( $this->is_api_result_object( $result, 'licenses' ) &&
20531 is_array( $result->licenses )
20532 ) {
20533 for ( $i = 0, $len = count( $result->licenses ); $i < $len; $i ++ ) {
20534 $result->licenses[ $i ] = new FS_Plugin_License( $result->licenses[ $i ] );
20535
20536 if ( ( ! $is_site_license_synced ) && is_numeric( $site_license_id ) ) {
20537 $is_site_license_synced = ( $site_license_id == $result->licenses[ $i ]->id );
20538 }
20539 }
20540
20541 $result = $result->licenses;
20542 } else {
20543 $api_errors[] = $result;
20544 $result = array();
20545 }
20546
20547 if ( ! $is_site_license_synced ) {
20548 if ( ! is_null( $blog_id ) ) {
20549 /**
20550 * If blog ID is not null, the request is for syncing of the license of a single site via the
20551 * network-level "Account" page.
20552 *
20553 * @author Leo Fajardo (@leorw)
20554 */
20555 $this->switch_to_blog( $blog_id );
20556 }
20557
20558 $api = $this->get_api_site_scope();
20559
20560 if ( is_numeric( $site_license_id ) ) {
20561 // Try to retrieve a foreign license that is linked to the install.
20562 $api_result = $api->call( '/licenses.json?is_enriched=true' );
20563
20564 if ( $this->is_api_result_object( $api_result, 'licenses' ) &&
20565 is_array( $api_result->licenses )
20566 ) {
20567 $licenses = $api_result->licenses;
20568
20569 if ( ! empty( $licenses ) ) {
20570 $result[] = new FS_Plugin_License( $licenses[0] );
20571 }
20572 } else {
20573 $api_errors[] = $api_result;
20574 }
20575 } else if (
20576 is_object( $this->_license ) &&
20577 /**
20578 * Sync only if the license belongs to the context plugin. `$plugin_id` can be an add-on ID while
20579 * the FS instance that does the syncing is the parent FS instance.
20580 *
20581 * @author Leo Fajardo (@leorw)
20582 * @since 2.3.0
20583 */
20584 $this->_license->plugin_id == $plugin_id
20585 ) {
20586 $is_license_in_result = false;
20587 if ( ! empty( $result ) ) {
20588 foreach ( $result as $license ) {
20589 if ( $license->id == $this->_license->id ) {
20590 $is_license_in_result = true;
20591 break;
20592 }
20593 }
20594 }
20595
20596 if ( ! $is_license_in_result ) {
20597 // Fetch foreign license by ID and license key.
20598 $license = $api->get( "/licenses/{$this->_license->id}.json?license_key=" .
20599 urlencode( $this->_license->secret_key ) . '&is_enriched=true' );
20600
20601 if ( $this->is_api_result_entity( $license ) ) {
20602 $result[] = new FS_Plugin_License( $license );
20603 } else {
20604 $api_errors[] = $license;
20605 }
20606 }
20607 }
20608
20609 if ( ! is_null( $blog_id ) ) {
20610 $this->switch_to_blog( $this->_storage->network_install_blog_id );
20611 }
20612 }
20613
20614 if ( is_array( $result ) && 0 < count( $result ) ) {
20615 // If found at least one license, return license collection even if there are errors.
20616 return $result;
20617 }
20618
20619 if ( ! empty( $api_errors ) ) {
20620 // If found any errors and no licenses, return first error.
20621 return $api_errors[0];
20622 }
20623
20624 // Fallback to empty licenses list.
20625 return $result;
20626 }
20627
20628 /**
20629 * @author Vova Feldman (@svovaf)
20630 * @since 2.0.0
20631 *
20632 * @param number $license_id
20633 * @param string $license_key
20634 *
20635 * @return \FS_Plugin_License|object
20636 */
20637 private function fetch_license_by_key( $license_id, $license_key ) {
20638 $this->_logger->entrance();
20639
20640 $api = $this->get_current_or_network_user_api_scope();
20641
20642 $result = $api->get( "/licenses/{$license_id}.json?license_key=" . urlencode( $license_key ) );
20643
20644 return $this->is_api_result_entity( $result ) ?
20645 new FS_Plugin_License( $result ) :
20646 $result;
20647 }
20648
20649 /**
20650 * @author Vova Feldman (@svovaf)
20651 * @since 1.2.0
20652 * @uses FS_Api
20653 *
20654 * @param number|bool $plugin_id
20655 * @param bool $flush
20656 *
20657 * @return FS_Payment[]|object
20658 */
20659 function _fetch_payments( $plugin_id = false, $flush = false ) {
20660 $this->_logger->entrance();
20661
20662 $api = $this->get_api_user_scope();
20663
20664 if ( ! is_numeric( $plugin_id ) ) {
20665 $plugin_id = $this->_plugin->id;
20666 }
20667
20668 $include_bundles = (
20669 is_object( $this->_plugin ) &&
20670 FS_Plugin::is_valid_id( $this->_plugin->bundle_id )
20671 );
20672
20673 $result = $api->get(
20674 "/plugins/{$plugin_id}/payments.json?include_addons=true" . ($include_bundles ? '&include_bundles=true' : ''),
20675 $flush
20676 );
20677
20678 if ( ! isset( $result->error ) ) {
20679 for ( $i = 0, $len = count( $result->payments ); $i < $len; $i ++ ) {
20680 $result->payments[ $i ] = new FS_Payment( $result->payments[ $i ] );
20681 }
20682 $result = $result->payments;
20683 }
20684
20685 return $result;
20686 }
20687
20688 /**
20689 * @author Vova Feldman (@svovaf)
20690 * @since 1.2.1.5
20691 * @uses FS_Api
20692 *
20693 * @param bool $flush
20694 *
20695 * @return \FS_Billing|mixed
20696 */
20697 function _fetch_billing( $flush = false ) {
20698 require_once WP_FS__DIR_INCLUDES . '/entities/class-fs-billing.php';
20699
20700 $billing = $this->get_api_user_scope()->get( 'billing.json', $flush );
20701
20702 if ( $this->is_api_result_entity( $billing ) ) {
20703 $billing = new FS_Billing( $billing );
20704 }
20705
20706 return $billing;
20707 }
20708
20709 /**
20710 * @author Vova Feldman (@svovaf)
20711 * @since 1.0.5
20712 *
20713 * @param FS_Plugin_License[] $licenses
20714 * @param number $module_id
20715 */
20716 private function _update_licenses( $licenses, $module_id ) {
20717 $this->_logger->entrance();
20718
20719 if ( is_array( $licenses ) ) {
20720 for ( $i = 0, $len = count( $licenses ); $i < $len; $i ++ ) {
20721 $licenses[ $i ]->updated = time();
20722 }
20723 }
20724
20725 $this->_store_licenses( true, $module_id, $licenses );
20726 }
20727
20728 /**
20729 * @author Vova Feldman (@svovaf)
20730 * @since 1.0.4
20731 *
20732 * @param bool|number $plugin_id
20733 * @param bool $flush Since 1.1.7.3
20734 * @param int $expiration Since 1.2.2.7
20735 * @param bool|string $newer_than Since 2.2.1
20736 *
20737 * @return object|false New plugin tag info if exist.
20738 */
20739 private function _fetch_newer_version( $plugin_id = false, $flush = true, $expiration = WP_FS__TIME_24_HOURS_IN_SEC, $newer_than = false ) {
20740 $latest_tag = $this->_fetch_latest_version( $plugin_id, $flush, $expiration, $newer_than );
20741
20742 if ( ! is_object( $latest_tag ) ) {
20743 return false;
20744 }
20745
20746 $plugin_version = $this->get_plugin_version();
20747
20748 // Check if version is actually newer.
20749 $has_new_version =
20750 // If it's an non-installed add-on then always return latest.
20751 ( $this->_is_addon_id( $plugin_id ) && ! $this->is_addon_activated( $plugin_id ) ) ||
20752 // Compare versions.
20753 version_compare( $plugin_version, $latest_tag->version, '<' );
20754
20755 $this->_logger->departure( $has_new_version ? 'Found newer plugin version ' . $latest_tag->version : 'No new version' );
20756
20757 $is_latest_version_beta = ( 'beta' === $latest_tag->release_mode );
20758
20759 $this->_storage->beta_data = array(
20760 'is_beta' => $is_latest_version_beta,
20761 'version' => $latest_tag->version
20762 );
20763
20764 return $has_new_version ? $latest_tag : false;
20765 }
20766
20767 /**
20768 * @author Vova Feldman (@svovaf)
20769 * @since 1.0.5
20770 *
20771 * @param bool|number $plugin_id
20772 * @param bool $flush Since 1.1.7.3
20773 * @param int $expiration Since 1.2.2.7
20774 * @param bool|string $newer_than Since 2.2.1
20775 *
20776 * @return bool|FS_Plugin_Tag
20777 */
20778 function get_update( $plugin_id = false, $flush = true, $expiration = WP_FS__TIME_24_HOURS_IN_SEC, $newer_than = false ) {
20779 $this->_logger->entrance();
20780
20781 if ( ! is_numeric( $plugin_id ) ) {
20782 $plugin_id = $this->_plugin->id;
20783 }
20784
20785 $this->check_updates( true, $plugin_id, $flush, $expiration, $newer_than );
20786 $updates = $this->get_all_updates();
20787
20788 return isset( $updates[ $plugin_id ] ) && is_object( $updates[ $plugin_id ] ) ? $updates[ $plugin_id ] : false;
20789 }
20790
20791 /**
20792 * Check if site assigned with active license.
20793 *
20794 * @author Vova Feldman (@svovaf)
20795 * @since 1.0.6
20796 *
20797 * @deprecated Please use has_active_valid_license() instead because license can be cancelled.
20798 */
20799 function has_active_license() {
20800 return (
20801 is_object( $this->_license ) &&
20802 is_numeric( $this->_license->id ) &&
20803 ! $this->_license->is_expired()
20804 );
20805 }
20806
20807 /**
20808 * Check if site assigned with active & valid (not expired) license.
20809 *
20810 * @author Vova Feldman (@svovaf)
20811 * @since 1.2.1
20812 *
20813 * @param bool $check_expiration
20814 */
20815 function has_active_valid_license( $check_expiration = true ) {
20816 return self::is_active_valid_license( $this->_license, $check_expiration );
20817 }
20818
20819 /**
20820 * @author Leo Fajardo (@leorw)
20821 * @since 2.3.1
20822 */
20823 function is_data_debug_mode() {
20824 if ( is_null( $this->is_whitelabeled ) || ! $this->is_whitelabeled ) {
20825 return false;
20826 }
20827
20828 $fs = $this->is_addon() ?
20829 $this->get_parent_instance() :
20830 $this;
20831
20832 if ( $fs->is_network_active() && fs_is_network_admin() ) {
20833 $is_developer_license_debug_mode = get_site_transient( "fs_{$this->get_id()}_data_debug_mode" );
20834 } else {
20835 $is_developer_license_debug_mode = get_transient( "fs_{$this->get_id()}_data_debug_mode" );
20836 }
20837
20838 return ( 'true' === $is_developer_license_debug_mode );
20839 }
20840
20841 /**
20842 * @author Leo Fajardo (@leorw)
20843 * @since 2.3.1
20844 */
20845 function _set_data_debug_mode() {
20846 if ( ! $this->is_whitelabeled( true ) ) {
20847 return;
20848 }
20849
20850 $license_or_user_key = fs_request_get( 'license_or_user_key' );
20851
20852 $transient_value = ( ! empty( $license_or_user_key ) ) ?
20853 'true' :
20854 'false';
20855
20856 if ( 'true' === $transient_value ) {
20857 $stored_key = $this->_storage->get( ! FS_User::is_valid_id( $this->_storage->last_license_user_id ) ?
20858 'last_license_key' :
20859 'last_license_user_key'
20860 );
20861
20862 if ( md5( $license_or_user_key ) !== $stored_key ) {
20863 $this->shoot_ajax_failure( sprintf(
20864 '%s... %s',
20865 $this->get_text_x_inline( 'Oops', 'exclamation', 'oops' ),
20866 $this->get_text_inline(
20867 'seems like the key you entered doesn\'t match our records.',
20868 'developer-or-license-not-found'
20869 )
20870 ) );
20871 }
20872 }
20873
20874 if ( $this->is_network_active() && fs_is_network_admin() ) {
20875 set_site_transient(
20876 "fs_{$this->get_id()}_data_debug_mode",
20877 $transient_value,
20878 WP_FS__TIME_24_HOURS_IN_SEC / 24
20879 );
20880 } else {
20881 set_transient(
20882 "fs_{$this->get_id()}_data_debug_mode",
20883 $transient_value,
20884 WP_FS__TIME_24_HOURS_IN_SEC / 24
20885 );
20886 }
20887
20888 if ( 'true' === $transient_value ) {
20889 $this->_admin_notices->add_sticky(
20890 $this->get_text_inline(
20891 'Debug mode was successfully enabled and will be automatically disabled in 60 min. You can also disable it earlier by clicking the "Stop Debug" link.',
20892 'data_debug_mode_enabled'
20893 ),
20894 'data_debug_mode_enabled'
20895 );
20896 }
20897
20898 $this->shoot_ajax_success();
20899 }
20900
20901 /**
20902 * Check if a given license is active & valid (not expired).
20903 *
20904 * @author Vova Feldman (@svovaf)
20905 * @since 2.1.3
20906 *
20907 * @param FS_Plugin_License $license
20908 * @param bool $check_expiration
20909 *
20910 * @return bool
20911 */
20912 private static function is_active_valid_license( $license, $check_expiration = true ) {
20913 return (
20914 is_object( $license ) &&
20915 FS_Plugin_License::is_valid_id( $license->id ) &&
20916 $license->is_active() &&
20917 ( ! $check_expiration || $license->is_valid() )
20918 );
20919 }
20920
20921 /**
20922 * Checks if there's any site that is associated with an active & valid license.
20923 * This logic is used to determine if the admin can download the premium code base from a network level admin.
20924 *
20925 * @author Vova Feldman (@svovaf)
20926 * @since 2.1.3
20927 *
20928 * @return bool
20929 */
20930 function has_any_active_valid_license() {
20931 if ( ! fs_is_network_admin() ) {
20932 return $this->has_active_valid_license();
20933 }
20934
20935 $installs = $this->get_blog_install_map();
20936 $all_plugin_licenses = self::get_all_licenses( $this->_module_id );
20937
20938 foreach ( $installs as $blog_id => $install ) {
20939 if ( ! FS_Plugin_License::is_valid_id( $install->license_id ) ) {
20940 continue;
20941 }
20942
20943 foreach ( $all_plugin_licenses as $license ) {
20944 if ( $license->id == $install->license_id ) {
20945 if ( self::is_active_valid_license( $license ) ) {
20946 return true;
20947 }
20948 }
20949 }
20950 }
20951
20952 return false;
20953 }
20954
20955 /**
20956 * Check if site assigned with license with enabled features.
20957 *
20958 * @author Vova Feldman (@svovaf)
20959 * @since 1.0.6
20960 *
20961 * @return bool
20962 */
20963 function has_features_enabled_license() {
20964 return (
20965 is_object( $this->_license ) &&
20966 is_numeric( $this->_license->id ) &&
20967 $this->_license->is_features_enabled()
20968 );
20969 }
20970
20971 /**
20972 * Checks if the product is activated with a bundle license.
20973 *
20974 * @author Leo Fajardo (@leorw)
20975 * @since 2.4.0
20976 *
20977 * @return bool
20978 */
20979 function is_activated_with_bundle_license() {
20980 if ( ! $this->has_features_enabled_license() ) {
20981 return false;
20982 }
20983
20984 return FS_Plugin_License::is_valid_id( $this->_license->parent_license_id );
20985 }
20986
20987 /**
20988 * Check if user is a trial or have feature enabled license.
20989 *
20990 * @author Vova Feldman (@svovaf)
20991 * @since 1.1.7
20992 *
20993 * @return bool
20994 */
20995 function can_use_premium_code() {
20996 return $this->is_trial() || $this->has_features_enabled_license();
20997 }
20998
20999 /**
21000 * Checks if the current user can activate plugins or switch themes. Note that this method should only be used
21001 * after the `init` action is triggered because it is using `current_user_can()` which is only functional after
21002 * the context user is authenticated.
21003 *
21004 * @author Leo Fajardo (@leorw)
21005 * @since 1.2.2
21006 *
21007 * @return bool
21008 */
21009 function is_user_admin() {
21010 /**
21011 * Require a super-admin when network activated, running from the network level OR if
21012 * running from the site level but not delegated the opt-in.
21013 *
21014 * @author Vova Feldman (@svovaf)
21015 * @since 2.0.0
21016 */
21017 if ( $this->_is_network_active &&
21018 ( fs_is_network_admin() || ! $this->is_delegated_connection() )
21019 ) {
21020 return is_super_admin();
21021 }
21022
21023 return ( $this->is_plugin() && current_user_can( is_multisite() ? 'manage_options' : 'activate_plugins' ) )
21024 || ( $this->is_theme() && current_user_can( 'switch_themes' ) );
21025 }
21026
21027 /**
21028 * Sync site's plan.
21029 *
21030 * @author Vova Feldman (@svovaf)
21031 * @since 1.0.3
21032 *
21033 * @uses FS_Api
21034 *
21035 * @param bool $background Hints the method if it's a background sync. If false, it means that was initiated by
21036 * the admin.
21037 * @param bool $is_context_single_site @since 2.0.0. This is used when syncing a license for a single install from the
21038 * network-level "Account" page.
21039 * @param int|null $current_blog_id @since 2.2.3. This is passed from the `execute_cron` method and used by the
21040 * `_sync_plugin_license` method in order to switch to the previous blog when sending
21041 * updates for a single site in case `execute_cron` has switched to a different blog.
21042 */
21043 private function _sync_license( $background = false, $is_context_single_site = false, $current_blog_id = null ) {
21044 $this->_logger->entrance();
21045
21046 $plugin_id = fs_request_get( 'plugin_id', $this->get_id() );
21047
21048 $is_addon_sync = ( ! $this->_plugin->is_addon() && $plugin_id != $this->get_id() );
21049
21050 if ( $is_addon_sync ) {
21051 $this->_sync_addon_license( $plugin_id, $background );
21052 } else {
21053 $this->_sync_plugin_license( $background, true, $is_context_single_site, $current_blog_id );
21054 }
21055
21056 $this->do_action( 'after_account_plan_sync', $this->get_plan_name() );
21057 }
21058
21059 /**
21060 * Sync plugin's add-on license.
21061 *
21062 * @author Vova Feldman (@svovaf)
21063 * @since 1.0.6
21064 * @uses FS_Api
21065 *
21066 * @param number $addon_id
21067 * @param bool $background
21068 */
21069 private function _sync_addon_license( $addon_id, $background ) {
21070 $this->_logger->entrance();
21071
21072 if ( $this->is_addon_activated( $addon_id ) ) {
21073 // If already installed, use add-on sync.
21074 $fs_addon = self::get_instance_by_id( $addon_id );
21075
21076 if (
21077 // Add-on is network activated and network integrated.
21078 $fs_addon->is_network_active() ||
21079 // Background sync cron.
21080 self::is_cron() ||
21081 // Add-on is not network activated or not network integrated.
21082 ! fs_is_network_admin()
21083 ) {
21084 $fs_addon->_sync_license( $background );
21085
21086 return;
21087 }
21088 }
21089
21090 // Validate add-on exists.
21091 $addon = $this->get_addon( $addon_id );
21092
21093 if ( ! is_object( $addon ) ) {
21094 return;
21095 }
21096
21097 // Add add-on into account add-ons.
21098 $account_addons = $this->get_account_addons();
21099 if ( ! is_array( $account_addons ) ) {
21100 $account_addons = array();
21101 }
21102 $account_addons[] = $addon->id;
21103 $account_addons = array_unique( $account_addons );
21104 $this->_store_account_addons( $account_addons );
21105
21106 // Load add-on licenses.
21107 $licenses = $this->_fetch_licenses( $addon->id );
21108
21109 // Sync add-on licenses.
21110 if ( $this->is_array_instanceof( $licenses, 'FS_Plugin_License' ) ) {
21111 $this->_update_licenses( $licenses, $addon->id );
21112
21113 if ( ! $this->is_addon_installed( $addon->id ) && FS_License_Manager::has_premium_license( $licenses ) ) {
21114 $plans_result = $this->get_api_site_or_plugin_scope()->get( $this->add_show_pending( "/addons/{$addon_id}/plans.json" ) );
21115
21116 if ( ! isset( $plans_result->error ) ) {
21117 $plans = array();
21118 foreach ( $plans_result->plans as $plan ) {
21119 $plans[] = new FS_Plugin_Plan( $plan );
21120 }
21121
21122 $this->_admin_notices->add_sticky(
21123 sprintf(
21124 ( FS_Plan_Manager::instance()->has_free_plan( $plans ) ?
21125 $this->get_text_inline( 'Your %s Add-on plan was successfully upgraded.', 'addon-successfully-upgraded-message' ) :
21126 /* translators: %s:product name, e.g. Facebook add-on was successfully... */
21127 $this->get_text_inline( '%s Add-on was successfully purchased.', 'addon-successfully-purchased-message' ) ),
21128 $addon->title
21129 ) . ' ' . $this->get_latest_download_link(
21130 $this->get_text_inline( 'Download the latest version', 'download-latest-version' ),
21131 $addon_id
21132 ),
21133 'addon_plan_upgraded_' . $addon->slug,
21134 $this->get_text_x_inline( 'Yee-haw', 'interjection expressing joy or exuberance', 'yee-haw' ) . '!'
21135 );
21136 }
21137 }
21138 }
21139 }
21140
21141 /**
21142 * Sync site's plugin plan.
21143 *
21144 * @author Vova Feldman (@svovaf)
21145 * @since 1.0.6
21146 * @uses FS_Api
21147 *
21148 * @param bool $background Hints the method if it's a background sync. If false, it means that was initiated by the admin.
21149 * @param bool $send_installs_update Since 2.0.0
21150 * @param bool $is_context_single_site Since 2.0.0. This is used when sending an update for a single install and
21151 * syncing its license from the network-level "Account" page (e.g.: after
21152 * activating a license only for the single install).
21153 * @param int|null $current_blog_id Since 2.2.3. This is passed from the `execute_cron` method so that it
21154 * can be used here to switch to the previous blog in case `execute_cron`
21155 * has switched to a different blog.
21156 */
21157 private function _sync_plugin_license(
21158 $background = false,
21159 $send_installs_update = true,
21160 $is_context_single_site = false,
21161 $current_blog_id = null
21162 ) {
21163 $this->_logger->entrance();
21164
21165 $plan_change = 'none';
21166
21167 $is_site_level_sync = ( $is_context_single_site || fs_is_blog_admin() || ! $this->_is_network_active );
21168
21169 if ( ! $send_installs_update ) {
21170 $site = $this->_site;
21171 } else {
21172 /**
21173 * Sync site info.
21174 *
21175 * @todo This line will execute install sync on a daily basis, even if running the free version (for opted-in users). The reason we want to keep it that way is for cases when the user was a paying customer, then there was a failure in subscription payment, and then after some time the payment was successful. This could be heavily optimized. For example, we can skip the $flush if the current install was never associated with a paid version.
21176 */
21177 if ( $is_site_level_sync ) {
21178 /**
21179 * Switch to the previous blog since `execute_cron` may have switched to a different blog.
21180 *
21181 * @author Leo Fajardo (@leorw)
21182 * @since 2.2.3
21183 */
21184 if ( is_numeric( $current_blog_id ) ) {
21185 $this->switch_to_blog( $current_blog_id );
21186 }
21187
21188 $result = $this->send_install_update( array(), true, true );
21189 $is_valid = $this->is_api_result_entity( $result );
21190 } else {
21191 $result = $this->send_installs_update( array(), true, true );
21192 $is_valid = $this->is_api_result_object( $result, 'installs' );
21193 }
21194
21195 if ( ! $is_valid ) {
21196 if ( $is_context_single_site ) {
21197 // Switch back to the main blog so that the following logic will have the right entities.
21198 $this->switch_to_blog( $this->_storage->network_install_blog_id );
21199 }
21200
21201 // Show API message only if not background sync or if paying customer.
21202 if ( ! $background || $this->is_paying() ) {
21203 // Try to ping API to see if not blocked.
21204 if ( FS_Api::is_blocked( $result ) ) {
21205 /**
21206 * @author Vova Feldman (@svovaf)
21207 * @since 1.1.6 Only show message related to one of the Freemius powered plugins. Once it will be resolved it will fix the issue for all plugins anyways. There's no point to scare users with multiple error messages.
21208 */
21209 if ( ! self::$_global_admin_notices->has_sticky( 'api_blocked' ) ) {
21210 // Add notice immediately if not a background sync.
21211 $add_notice = ( ! $background );
21212
21213 if ( ! $add_notice ) {
21214 $counter = (int) get_transient( '_fs_api_connection_retry_counter' );
21215
21216 // We only want to add the notice after 3 consecutive failures.
21217 $add_notice = ( 3 <= $counter );
21218
21219 if ( ! $add_notice ) {
21220 /**
21221 * Update counter transient only if notice shouldn't be added. If it is added the transient will be reset anyway, because the retries mechanism should only start counting if the admin isn't aware of the connectivity issue.
21222 *
21223 * Also, since the background sync happens once a day, setting the transient expiration for a week should be enough to count 3 failures, if there's an actual connectivity issue.
21224 */
21225 set_transient( '_fs_api_connection_retry_counter', $counter + 1, WP_FS__TIME_WEEK_IN_SEC );
21226 }
21227 }
21228
21229 // Add notice instantly for not-background sync and only after 3 failed attempts for background sync.
21230 if ( $add_notice ) {
21231 self::$_global_admin_notices->add(
21232 $this->generate_api_blocked_notice_message_from_result( $result ),
21233 '',
21234 'error',
21235 $background,
21236 'api_blocked'
21237 );
21238
21239 add_action( 'admin_footer', array( 'Freemius', '_add_api_connectivity_notice_handler_js' ) );
21240
21241 // Notice was just shown, reset connectivity counter.
21242 delete_transient( '_fs_api_connection_retry_counter' );
21243 }
21244 }
21245 } else if ( is_object( $result ) ) {
21246 // Authentication params are broken.
21247 $this->_admin_notices->add(
21248 $this->get_text_inline( 'It seems like one of the authentication parameters is wrong. Update your Public Key, Secret Key & User ID, and try again.', 'wrong-authentication-param-message' ) . '<br> ' . $this->get_text_inline( 'Error received from the server:', 'server-error-message' ) . var_export( $result->error, true ),
21249 '',
21250 'error'
21251 );
21252 }
21253 }
21254
21255 // No reason to continue with license sync while there are API issues.
21256 return;
21257 }
21258
21259 // API is working now. Delete the transient and start afresh.
21260 delete_transient('_fs_api_connection_retry_counter');
21261
21262 if ( $is_site_level_sync ) {
21263 $site = new FS_Site( $result );
21264 } else {
21265 // Map site addresses to their blog IDs.
21266 $address_to_blog_map = $this->get_address_to_blog_map();
21267
21268 // Find the current context install.
21269 $site = null;
21270 foreach ( $result->installs as $install ) {
21271 if ( $install->id == $this->_site->id ) {
21272 $site = new FS_Site( $install );
21273 } else {
21274 $address = trailingslashit( fs_strip_url_protocol( $install->url ) );
21275 $blog_id = $address_to_blog_map[ $address ];
21276
21277 $this->_store_site( true, $blog_id, new FS_Site( $install ) );
21278 }
21279 }
21280 }
21281
21282 // Sync plans.
21283 $this->_sync_plans();
21284 }
21285
21286 // Remove sticky API connectivity message.
21287 self::$_global_admin_notices->remove_sticky( 'api_blocked' );
21288
21289 if ( ! $this->has_paid_plan() ) {
21290 $this->_site = $site;
21291 $this->_store_site(
21292 true,
21293 $is_site_level_sync ?
21294 null :
21295 $this->get_network_install_blog_id()
21296 );
21297 } else {
21298 $context_blog_id = 0;
21299
21300 if ( $is_context_single_site ) {
21301 $context_blog_id = get_current_blog_id();
21302
21303 // Switch back to the main blog in order to properly sync the license.
21304 $this->switch_to_blog( $this->_storage->network_install_blog_id );
21305 }
21306
21307 /**
21308 * Sync licenses. Pass the site's license ID so that the foreign licenses will be fetched if the license
21309 * associated with that ID is not included in the user's licenses collection.
21310 */
21311 $this->_sync_licenses(
21312 $site->license_id,
21313 ( $is_context_single_site ?
21314 $context_blog_id :
21315 null
21316 )
21317 );
21318
21319 if ( $is_context_single_site ) {
21320 $this->switch_to_blog( $context_blog_id );
21321 }
21322
21323 // Check if plan / license changed.
21324 if ( $site->plan_id != $this->_site->plan_id ||
21325 // Check if trial started.
21326 $site->trial_plan_id != $this->_site->trial_plan_id ||
21327 $site->trial_ends != $this->_site->trial_ends ||
21328 // Check if license changed.
21329 $site->license_id != $this->_site->license_id
21330 ) {
21331 if ( $site->is_trial() && ( ! $this->_site->is_trial() || $site->trial_ends != $this->_site->trial_ends ) ) {
21332 // New trial started.
21333 $this->_site = $site;
21334 $plan_change = 'trial_started';
21335
21336 // For trial with subscription use-case.
21337 $new_license = is_null( $site->license_id ) ? null : $this->_get_license_by_id( $site->license_id );
21338
21339 if ( is_object( $new_license ) && $new_license->is_valid() ) {
21340 $this->_site = $site;
21341 $this->_update_site_license( $new_license );
21342 $this->_store_licenses();
21343
21344 $this->_sync_site_subscription( $this->_license );
21345 }
21346 } else if ( $this->_site->is_trial() && ! $site->is_trial() && ! is_numeric( $site->license_id ) ) {
21347 // Was in trial, but now trial expired and no license ID.
21348 // New trial started.
21349 $this->_site = $site;
21350 $plan_change = 'trial_expired';
21351 } else {
21352 $is_free = $this->is_free_plan();
21353
21354 // Make sure license exist and not expired.
21355 $new_license = is_null( $site->license_id ) ?
21356 null :
21357 $this->_get_license_by_id( $site->license_id );
21358
21359 if ( $is_free && is_null( $new_license ) && $this->has_any_license() && $this->_license->is_cancelled ) {
21360 // License cancelled.
21361 $this->_site = $site;
21362 $this->_update_site_license( $new_license );
21363 $this->_store_licenses();
21364
21365 $plan_change = 'cancelled';
21366 } else if ( $is_free && ( ( ! is_object( $new_license ) || $new_license->is_expired() ) ) ) {
21367 // The license is expired, so ignore upgrade method.
21368 $this->_site = $site;
21369 } else {
21370 // License changed.
21371 $this->_site = $site;
21372
21373 /**
21374 * IMPORTANT:
21375 * The line below should be executed before trying to activate the license on the rest of the network, otherwise, the license' activation counters may be out of sync + there's no need to activate the license on the context site since it's already activated on it.
21376 *
21377 * @author Vova Feldman (@svovaf)
21378 * @since 2.0.0
21379 */
21380 $this->_update_site_license( $new_license );
21381
21382 if ( ! $is_context_single_site &&
21383 fs_is_network_admin() &&
21384 $this->_is_network_active &&
21385 $new_license->quota > 1 &&
21386 get_blog_count() > 1
21387 ) {
21388 // See if license can activated on all sites.
21389 if ( ! $this->try_activate_license_on_network( $this->_user, $new_license ) ) {
21390 if ( ! fs_request_get_bool( 'auto_install' ) ) {
21391 // Open the license activation dialog box on the account page.
21392 add_action( 'admin_footer', array(
21393 &$this,
21394 '_open_license_activation_dialog_box'
21395 ) );
21396 }
21397 }
21398 }
21399
21400 $this->_store_licenses();
21401
21402 $plan_change = $is_free ?
21403 ( $this->is_only_premium() ? 'activated' : 'upgraded' ) :
21404 ( is_object( $new_license ) ?
21405 'changed' :
21406 'downgraded' );
21407 }
21408 }
21409
21410 // Store updated site info.
21411 $this->_store_site(
21412 true,
21413 $is_site_level_sync ?
21414 null :
21415 $this->get_network_install_blog_id()
21416 );
21417 } else {
21418 if ( ! is_object( $this->_license ) ) {
21419 $this->maybe_update_whitelabel_flag(
21420 FS_Plugin_License::is_valid_id( $site->license_id ) ?
21421 $this->get_license_by_id( $site->license_id ) :
21422 null
21423 );
21424 } else {
21425 $this->maybe_update_whitelabel_flag( $this->_license );
21426
21427 if ( $this->_license->is_expired() ) {
21428 if ( ! $this->has_features_enabled_license() ) {
21429 $this->_deactivate_license();
21430 $plan_change = 'downgraded';
21431 } else {
21432 $last_time_expired_license_notice_was_shown = $this->_storage->get( 'expired_license_notice_shown', 0 );
21433
21434 if ( time() - ( 14 * WP_FS__TIME_24_HOURS_IN_SEC ) >= $last_time_expired_license_notice_was_shown ) {
21435 /**
21436 * Show the expired license notice every 14 days.
21437 *
21438 * @author Leo Fajardo (@leorw)
21439 * @since 2.3.1
21440 */
21441 $plan_change = 'expired';
21442 }
21443 }
21444 }
21445 }
21446
21447 if ( is_numeric( $site->license_id ) && is_object( $this->_license ) ) {
21448 $this->_sync_site_subscription( $this->_license );
21449 }
21450 }
21451
21452 if ( ! $this->is_addon() &&
21453 $this->_site->is_beta() !== $site->is_beta()
21454 ) {
21455 // Beta flag updated.
21456 $this->_site = $site;
21457
21458 $this->_store_site(
21459 true,
21460 $is_site_level_sync ?
21461 null :
21462 $this->get_network_install_blog_id()
21463 );
21464 }
21465
21466 if ( $this->is_addon() || $this->has_addons() ) {
21467 /**
21468 * Purge the valid user licenses cache so that when the "Account" or the "Add-Ons" page is loaded,
21469 * an updated valid user licenses collection will be fetched from the server which is used to also
21470 * update the account add-ons (add-ons the user has licenses for).
21471 *
21472 * @author Leo Fajardo (@leorw)
21473 * @since 2.2.4
21474 */
21475 $this->purge_valid_user_licenses_cache();
21476 }
21477 }
21478
21479 $hmm_text = $this->get_text_x_inline( 'Hmm', 'something somebody says when they are thinking about what you have just said.', 'hmm' ) . '...';
21480
21481 if ( $this->apply_filters( 'has_paid_plan_account', $this->has_paid_plan() ) ) {
21482 switch ( $plan_change ) {
21483 case 'none':
21484 if ( ! $background && is_admin() ) {
21485 $plan = $this->is_trial() ?
21486 $this->get_trial_plan() :
21487 $this->get_plan();
21488
21489 if ( $plan->is_free() ) {
21490 $this->_admin_notices->add(
21491 sprintf(
21492 $this->get_text_inline( 'It looks like you are still on the %s plan. If you did upgrade or change your plan, it\'s probably an issue on our side - sorry.', 'plan-did-not-change-message' ),
21493 '<i><b>' . $plan->title . ( $this->is_trial() ? ' ' . $this->get_text_x_inline( 'Trial', 'trial period', 'trial' ) : '' ) . '</b></i>'
21494 ) . ' ' . sprintf(
21495 '<a href="%s">%s</a>',
21496 $this->contact_url(
21497 'bug',
21498 sprintf( $this->get_text_inline( 'I have upgraded my account but when I try to Sync the License, the plan remains %s.', 'plan-did-not-change-email-message' ),
21499 strtoupper( $plan->name )
21500 )
21501 ),
21502 $this->get_text_inline( 'Please contact us here', 'contact-us-here' )
21503 ),
21504 $hmm_text
21505 );
21506 }
21507 }
21508 break;
21509 case 'upgraded':
21510 case 'activated':
21511 $this->add_after_plan_activation_or_upgrade_instructions_notice( 'upgraded' === $plan_change );
21512
21513 $this->_admin_notices->remove_sticky( array(
21514 'trial_started',
21515 'trial_promotion',
21516 'trial_expired',
21517 'activation_complete',
21518 'license_expired',
21519 ) );
21520 break;
21521 case 'changed':
21522 $this->_admin_notices->add_sticky(
21523 sprintf(
21524 $this->get_text_inline( 'Your plan was successfully changed to %s.', 'plan-changed-to-x-message' ),
21525 $this->get_plan_title()
21526 ),
21527 'plan_changed'
21528 );
21529
21530 $this->_admin_notices->remove_sticky( array(
21531 'trial_started',
21532 'trial_promotion',
21533 'trial_expired',
21534 'activation_complete',
21535 ) );
21536 break;
21537 case 'downgraded':
21538 $this->_admin_notices->add_sticky(
21539 ($this->has_free_plan() ?
21540 sprintf( $this->get_text_inline( 'Your license has expired. You can still continue using the free %s forever.', 'license-expired-blocking-message' ), $this->_module_type ) :
21541 /* translators: %1$s: product title; %2$s, %3$s: wrapping HTML anchor element; %4$s: 'plugin', 'theme', or 'add-on'. */
21542 sprintf( $this->get_text_inline( 'Your license has expired. %1$sUpgrade now%2$s to continue using the %3$s without interruptions.', 'license-expired-blocking-message_premium-only' ), sprintf('<a href="%s">', $this->pricing_url()), '</a>', $this->get_module_label(true) ) ),
21543 'license_expired',
21544 $hmm_text
21545 );
21546 $this->_admin_notices->remove_sticky( 'plan_upgraded' );
21547 break;
21548 case 'cancelled':
21549 $this->_admin_notices->add(
21550 $this->get_text_inline( 'Your license has been cancelled. If you think it\'s a mistake, please contact support.', 'license-cancelled' ) . ' ' .
21551 sprintf(
21552 '<a href="%s">%s</a>',
21553 $this->contact_url( 'bug' ),
21554 $this->get_text_inline( 'Please contact us here', 'contact-us-here' )
21555 ),
21556 $hmm_text,
21557 'error'
21558 );
21559 $this->_admin_notices->remove_sticky( 'plan_upgraded' );
21560 break;
21561 case 'expired':
21562 $this->_admin_notices->add_sticky(
21563 sprintf( $this->get_text_inline( 'Your license has expired. You can still continue using all the %s features, but you\'ll need to renew your license to continue getting updates and support.', 'license-expired-non-blocking-message' ), $this->get_plan()->title ),
21564 'license_expired',
21565 $hmm_text
21566 );
21567
21568 $this->_storage->expired_license_notice_shown = WP_FS__SCRIPT_START_TIME;
21569
21570 $this->_admin_notices->remove_sticky( 'plan_upgraded' );
21571 break;
21572 case 'trial_started':
21573 $this->add_complete_upgrade_instructions_notice(
21574 sprintf(
21575 $this->get_text_inline( 'Your trial has been successfully started.', 'trial-started-message' ),
21576 '<i>' . $this->get_plugin_name() . '</i>'
21577 ),
21578 'trial_started',
21579 $this->get_trial_plan()->title
21580 );
21581
21582 $this->_admin_notices->remove_sticky( array(
21583 'trial_promotion',
21584 ) );
21585 break;
21586 case 'trial_expired':
21587 $this->_admin_notices->add_sticky(
21588 ($this->has_free_plan() ?
21589 $this->get_text_inline( 'Your free trial has expired. You can still continue using all our free features.', 'trial-expired-message' ) :
21590 /* translators: %1$s: product title; %2$s, %3$s: wrapping HTML anchor element; %4$s: 'plugin', 'theme', or 'add-on'. */
21591 sprintf( $this->get_text_inline( 'Your free trial has expired. %1$sUpgrade now%2$s to continue using the %3$s without interruptions.', 'trial-expired-message_premium-only' ), sprintf('<a href="%s">', $this->pricing_url()), '</a>', $this->get_module_label(true))),
21592 'trial_expired',
21593 $hmm_text
21594 );
21595 $this->_admin_notices->remove_sticky( array(
21596 'trial_started',
21597 'trial_promotion',
21598 'plan_upgraded',
21599 ) );
21600 break;
21601 }
21602 }
21603
21604 if ( 'none' !== $plan_change ) {
21605 if (
21606 ! is_object( $this->_license ) ||
21607 ! $this->_license->is_whitelabeled
21608 ) {
21609 $this->_admin_notices->remove_sticky( 'license_whitelabeled' );
21610 }
21611
21612 $this->do_action( 'after_license_change', $plan_change, $this->get_plan() );
21613 }
21614 }
21615
21616 /**
21617 * @author Leo Fajardo (@leorw)
21618 * @since 2.5.4
21619 *
21620 * @param mixed $result
21621 *
21622 * @return string
21623 */
21624 private function generate_api_blocked_notice_message_from_result( $result ) {
21625 $api_domains = $this->apply_filters( 'api_domains', array(
21626 'api.freemius.com',
21627 'wp.freemius.com',
21628 ) );
21629
21630 $api_domains_list_items = '';
21631
21632 foreach( $api_domains as $api_domain ) {
21633 $api_domains_list_items .= "<li>{$api_domain}</li>";
21634 }
21635
21636 $error_message = sprintf(
21637 $this->get_text_inline( 'Your server is blocking the access to Freemius\' API, which is crucial for %1$s synchronization. Please contact your host to whitelist the following domains:%2$s', 'server-blocking-access' ),
21638 $this->get_plugin_name(),
21639 "<ol>{$api_domains_list_items}</ol><a href='#' class='fs-api-request-error-show-details-link'>" . $this->get_text_inline( 'Show error details', 'show-error-details' ) . " <span class='dashicons dashicons-arrow-down-alt2'></span></a>"
21640 );
21641
21642 $error_message =
21643 "<div>{$error_message}</div>" .
21644 '<div class="fs-api-request-error-details" style="display: none">' .
21645 '<strong>' . $this->get_text_inline( 'Error received from the server:', 'server-error-message' ) . '</strong><br>' .
21646 $result->error->message .
21647 '</div>';
21648
21649 return $error_message;
21650 }
21651
21652 /**
21653 * Include the required JS at the footer of the admin to trigger the license activation dialog box.
21654 *
21655 * @author Vova Feldman (@svovaf)
21656 * @since 2.0.0
21657 */
21658 public function _open_license_activation_dialog_box() {
21659 $vars = array( 'license_id' => $this->_site->license_id );
21660 fs_require_once_template( 'js/open-license-activation.php', $vars );
21661 }
21662
21663 /**
21664 * @author Vova Feldman (@svovaf)
21665 * @since 1.0.5
21666 *
21667 * @param bool $background
21668 * @param FS_Plugin_License|null $premium_license
21669 */
21670 protected function _activate_license( $background = false, $premium_license = null ) {
21671 $this->_logger->entrance();
21672
21673 if ( is_null( $premium_license ) ) {
21674 $license_id = fs_request_get( 'license_id' );
21675
21676 if ( is_object( $this->_site ) &&
21677 FS_Plugin_License::is_valid_id( $license_id ) &&
21678 $license_id == $this->_site->license_id
21679 ) {
21680 // License is already activated.
21681 return;
21682 }
21683
21684 $premium_license = FS_Plugin_License::is_valid_id( $license_id ) ?
21685 $this->_get_license_by_id( $license_id ) :
21686 $this->_get_available_premium_license();
21687 }
21688
21689 if ( ! is_object( $premium_license ) ) {
21690 return;
21691 }
21692
21693 if ( ! is_object( $this->_site ) ) {
21694 // Not yet opted-in.
21695 $user = $this->get_current_or_network_user();
21696 if ( ! is_object( $user ) ) {
21697 $user = self::_get_user_by_id( $premium_license->user_id );
21698 }
21699
21700 if ( is_object( $user ) ) {
21701 $this->install_with_user( $user, $premium_license->secret_key, false, false, false );
21702 } else {
21703 $this->opt_in(
21704 false,
21705 false,
21706 false,
21707 $premium_license->secret_key
21708 );
21709
21710 return;
21711 }
21712 }
21713
21714
21715 /**
21716 * If the premium license is already associated with the install, just
21717 * update the license reference (activation is not required).
21718 *
21719 * @since 1.1.9
21720 */
21721 if ( $premium_license->id == $this->_site->license_id ) {
21722 // License is already activated.
21723 $this->_update_site_license( $premium_license );
21724 $this->_store_account();
21725
21726 return;
21727 }
21728
21729 if ( $this->_site->user_id != $premium_license->user_id ) {
21730 $api_request_params = array( 'license_key' => $premium_license->secret_key );
21731 } else {
21732 $api_request_params = array();
21733 }
21734
21735 $api = $this->get_api_site_scope();
21736 $license = $api->call( "/licenses/{$premium_license->id}.json?is_enriched=true", 'put', $api_request_params );
21737
21738 if ( ! $this->is_api_result_entity( $license ) ) {
21739 if ( ! $background ) {
21740 $this->_admin_notices->add( sprintf(
21741 '%s %s',
21742 $this->get_text_inline( 'It looks like the license could not be activated.', 'license-activation-failed-message' ),
21743 ( is_object( $license ) && isset( $license->error ) ?
21744 $license->error->message :
21745 sprintf( '%s<br><code>%s</code>',
21746 $this->get_text_inline( 'Error received from the server:', 'server-error-message' ),
21747 var_export( $license, true )
21748 )
21749 )
21750 ),
21751 $this->get_text_x_inline( 'Hmm', 'something somebody says when they are thinking about what you have just said.', 'hmm' ) . '...',
21752 'error'
21753 );
21754 }
21755
21756 return;
21757 }
21758
21759 $premium_license = new FS_Plugin_License( $license );
21760
21761 // Updated site plan.
21762 $site = $this->get_api_site_scope()->get( '/', true );
21763 if ( $this->is_api_result_entity( $site ) ) {
21764 $this->_site = new FS_Site( $site );
21765 }
21766 $this->_update_site_license( $premium_license );
21767
21768 $this->_store_account();
21769
21770 if ( $this->is_addon() || $this->has_addons() ) {
21771 /**
21772 * Purge the valid user licenses cache so that when the "Account" or the "Add-Ons" page is loaded,
21773 * an updated valid user licenses collection will be fetched from the server which is used to also
21774 * update the account add-ons (add-ons the user has licenses for).
21775 *
21776 * @author Leo Fajardo (@leorw)
21777 * @since 2.2.4
21778 */
21779 $this->purge_valid_user_licenses_cache();
21780 }
21781
21782 if ( ! $background ) {
21783 $this->add_complete_upgrade_instructions_notice(
21784 $this->get_text_inline( 'Your license was successfully activated.', 'license-activated-message' ),
21785 'license_activated'
21786 );
21787 }
21788
21789 $this->_admin_notices->remove_sticky( array(
21790 'trial_promotion',
21791 'license_expired',
21792 ) );
21793 }
21794
21795 /**
21796 * @author Vova Feldman (@svovaf)
21797 * @since 1.0.5
21798 *
21799 * @param bool $show_notice
21800 */
21801 protected function _deactivate_license( $show_notice = true ) {
21802 $this->_logger->entrance();
21803
21804 $hmm_text = $this->get_text_x_inline( 'Hmm', 'something somebody says when they are thinking about what you have just said.', 'hmm' ) . '...';
21805
21806 if ( ! FS_Plugin_License::is_valid_id( $this->_site->license_id ) ) {
21807 $this->_admin_notices->add(
21808 sprintf( $this->get_text_inline( 'It looks like your site currently doesn\'t have an active license.', 'no-active-license-message' ), $this->get_plan_title() ),
21809 $hmm_text
21810 );
21811
21812 return;
21813 }
21814
21815 $api = $this->get_api_site_scope();
21816 $license = $api->call( "/licenses/{$this->_site->license_id}.json", 'delete' );
21817
21818 $this->handle_license_deactivation_result( $license, $hmm_text, $show_notice );
21819 }
21820
21821 /**
21822 * @author Leo Fajardo (@leorw)
21823 * @since 2.2.1
21824 *
21825 * @param FS_Plugin_License $license
21826 * @param bool|string $hmm_text
21827 * @param bool $show_notice
21828 */
21829 private function handle_license_deactivation_result( $license, $hmm_text = false, $show_notice = true ) {
21830 if ( isset( $license->error ) ) {
21831 $this->_admin_notices->add(
21832 $this->get_text_inline( 'It looks like the license deactivation failed.', 'license-deactivation-failed-message' ) . '<br> ' .
21833 $this->get_text_inline( 'Error received from the server:', 'server-error-message' ) . ' ' . var_export( $license->error, true ),
21834 $hmm_text,
21835 'error'
21836 );
21837
21838 return;
21839 }
21840
21841 // Update license cache.
21842 if ( is_array( $this->_licenses ) ) {
21843 for ( $i = 0, $len = count( $this->_licenses ); $i < $len; $i ++ ) {
21844 if ( $license->id == $this->_licenses[ $i ]->id ) {
21845 $this->_licenses[ $i ] = new FS_Plugin_License( $license );
21846 }
21847 }
21848 }
21849
21850 // Update site plan to default.
21851 $this->_sync_plans();
21852 $this->_site->plan_id = $this->_plans[0]->id;
21853 // Unlink license from site.
21854 $this->_update_site_license( null );
21855
21856 $this->_store_account();
21857
21858 if ( $show_notice ) {
21859 $this->_admin_notices->add(
21860 sprintf( $this->is_only_premium() ?
21861 $this->get_text_inline( 'Your %s license was successfully deactivated.', 'license-deactivation-message_premium-only' ) :
21862 $this->get_text_inline( 'Your license was successfully deactivated, you are back to the %s plan.', 'license-deactivation-message' ),
21863 $this->get_plan_title()
21864 ),
21865 $this->get_text_inline( 'O.K', 'ok' )
21866 );
21867 }
21868
21869 $this->_admin_notices->remove_sticky( array(
21870 'plan_upgraded',
21871 'license_activated',
21872 ) );
21873 }
21874
21875 /**
21876 * Site plan downgrade.
21877 *
21878 * @author Vova Feldman (@svovaf)
21879 * @since 1.0.4
21880 *
21881 * @return object
21882 *
21883 * @uses FS_Api
21884 */
21885 private function _downgrade_site() {
21886 $this->_logger->entrance();
21887
21888 $deactivate_license = fs_request_get_bool( 'deactivate_license' );
21889
21890 $api = $this->get_api_site_scope();
21891 $site = $api->call( 'downgrade.json', 'put', array( 'deactivate_license' => $deactivate_license ) );
21892
21893 $plan_downgraded = false;
21894 $plan = false;
21895 if ( $this->is_api_result_entity( $site ) ) {
21896 $prev_plan_id = $this->_site->plan_id;
21897
21898 // Update new site plan id.
21899 $this->_site->plan_id = $site->plan_id;
21900
21901 $plan = $this->get_plan();
21902 $subscription = $this->_sync_site_subscription( $this->_license );
21903
21904 // Plan downgraded if plan was changed or subscription was cancelled.
21905 $plan_downgraded = ( $plan instanceof FS_Plugin_Plan && $prev_plan_id != $plan->id ) ||
21906 ( is_object( $subscription ) && ! isset( $subscription->error ) && ! $subscription->is_active() );
21907 } else {
21908 // handle different error cases.
21909 $this->handle_license_deactivation_result(
21910 $site,
21911 $this->get_text_x_inline( 'Hmm', 'something somebody says when they are thinking about what you have just said.', 'hmm' ) . '...'
21912 );
21913 }
21914
21915 if ( ! $plan_downgraded ) {
21916 return (object) array(
21917 'error' => (object) array(
21918 'message' => $this->get_text_inline( 'Seems like we are having some temporary issue with your subscription cancellation. Please try again in few minutes.', 'subscription-cancellation-failure-message' )
21919 )
21920 );
21921 }
21922
21923 // Remove previous sticky message about upgrade (if exist).
21924 $this->_admin_notices->remove_sticky( 'plan_upgraded' );
21925
21926 $this->_admin_notices->add(
21927 sprintf( $this->get_text_inline( 'Your subscription was successfully cancelled. Your %s plan license will expire in %s.', 'plan-x-downgraded-message' ),
21928 $plan->title,
21929 human_time_diff( time(), strtotime( $this->_license->expiration ) )
21930 )
21931 );
21932
21933 // Store site updates.
21934 $this->_store_site();
21935
21936 if ( $deactivate_license &&
21937 ! FS_Plugin_License::is_valid_id( $site->license_id )
21938 ) {
21939 if ( $this->_site->is_localhost() ) {
21940 $this->_license->activated_local = max( 0, $this->_license->activated_local - 1 );
21941 } else {
21942 $this->_license->activated = max( 0, $this->_license->activated - 1 );
21943 }
21944
21945 // Handle successful license deactivation result.
21946 $this->handle_license_deactivation_result( $this->_license );
21947 }
21948
21949 return $site;
21950 }
21951
21952 /**
21953 * @author Vova Feldman (@svovaf)
21954 * @since 1.1.8.1
21955 *
21956 * @param bool|string $plan_name
21957 *
21958 * @return bool If trial was successfully started.
21959 */
21960 function start_trial( $plan_name = false ) {
21961 $this->_logger->entrance();
21962
21963 // Alias.
21964 $oops_text = $this->get_text_x_inline( 'Oops', 'exclamation', 'oops' ) . '...';
21965
21966 if ( $this->is_trial() ) {
21967 // Already in trial mode.
21968 $this->_admin_notices->add(
21969 sprintf( $this->get_text_inline( 'You are already running the %s in a trial mode.', 'in-trial-mode' ), $this->_module_type ),
21970 $oops_text,
21971 'error'
21972 );
21973
21974 return false;
21975 }
21976
21977 if ( $this->_site->is_trial_utilized() ) {
21978 // Trial was already utilized.
21979 $this->_admin_notices->add(
21980 $this->get_text_inline( 'You already utilized a trial before.', 'trial-utilized' ),
21981 $oops_text,
21982 'error'
21983 );
21984
21985 return false;
21986 }
21987
21988 if ( false !== $plan_name ) {
21989 $plan = $this->get_plan_by_name( $plan_name );
21990
21991 if ( false === $plan ) {
21992 // Plan doesn't exist.
21993 $this->_admin_notices->add(
21994 sprintf( $this->get_text_inline( 'Plan %s do not exist, therefore, can\'t start a trial.', 'trial-plan-x-not-exist' ), $plan_name ),
21995 $oops_text,
21996 'error'
21997 );
21998
21999 return false;
22000 }
22001
22002 if ( ! $plan->has_trial() ) {
22003 // Plan doesn't exist.
22004 $this->_admin_notices->add(
22005 sprintf( $this->get_text_inline( 'Plan %s does not support a trial period.', 'plan-x-no-trial' ), $plan_name ),
22006 $oops_text,
22007 'error'
22008 );
22009
22010 return false;
22011 }
22012 } else {
22013 if ( ! $this->has_trial_plan() ) {
22014 // None of the plans have a trial.
22015 $this->_admin_notices->add(
22016 sprintf( $this->get_text_inline( 'None of the %s\'s plans supports a trial period.', 'no-trials' ), $this->_module_type ),
22017 $oops_text,
22018 'error'
22019 );
22020
22021 return false;
22022 }
22023
22024 $plans_with_trial = FS_Plan_Manager::instance()->get_trial_plans( $this->_plans );
22025
22026 $plan = $plans_with_trial[0];
22027 }
22028
22029 $api = $this->get_api_site_scope();
22030 $plan = $api->call( "plans/{$plan->id}/trials.json", 'post' );
22031
22032 if ( ! $this->is_api_result_entity( $plan ) ) {
22033 // Some API error while trying to start the trial.
22034 $this->_admin_notices->add(
22035 $this->get_api_error_message( $plan ),
22036 $oops_text,
22037 'error'
22038 );
22039
22040 return false;
22041 }
22042
22043 // Sync license.
22044 $this->_sync_license();
22045
22046 return $this->is_trial();
22047 }
22048
22049 /**
22050 * Cancel site trial.
22051 *
22052 * @author Vova Feldman (@svovaf)
22053 * @since 1.0.9
22054 *
22055 * @return object
22056 *
22057 * @uses FS_Api
22058 */
22059 private function _cancel_trial() {
22060 $this->_logger->entrance();
22061
22062 if ( ! $this->is_trial() ) {
22063 return (object) array(
22064 'error' => (object) array(
22065 'message' => $this->get_text_inline( 'It looks like you are not in trial mode anymore so there\'s nothing to cancel :)', 'trial-cancel-no-trial-message' )
22066 )
22067 );
22068 }
22069
22070 $trial_plan = $this->get_trial_plan();
22071
22072 $api = $this->get_api_site_scope();
22073 $site = $api->call( 'trials.json', 'delete' );
22074
22075 $trial_cancelled = false;
22076
22077 if ( $this->is_api_result_entity( $site ) ) {
22078 $prev_trial_ends = $this->_site->trial_ends;
22079
22080 if ( $this->is_paid_trial() ) {
22081 $this->_license->expiration = $site->trial_ends;
22082 $this->_license->is_cancelled = true;
22083 $this->_update_site_license( $this->_license );
22084 $this->_store_licenses();
22085
22086 // Clear subscription reference.
22087 $this->_sync_site_subscription( null );
22088 }
22089
22090 // Update site info.
22091 $this->_site = new FS_Site( $site );
22092
22093 $trial_cancelled = ( $prev_trial_ends != $site->trial_ends );
22094 } else {
22095 // @todo handle different error cases.
22096 }
22097
22098 if ( ! $trial_cancelled ) {
22099 return (object) array(
22100 'error' => (object) array(
22101 'message' => $this->get_text_inline( 'Seems like we are having some temporary issue with your trial cancellation. Please try again in few minutes.', 'trial-cancel-failure-message' )
22102 )
22103 );
22104 }
22105
22106 // Remove previous sticky messages about upgrade or trial (if exist).
22107 $this->_admin_notices->remove_sticky( array(
22108 'trial_started',
22109 'trial_promotion',
22110 'plan_upgraded',
22111 ) );
22112
22113 // Store site updates.
22114 $this->_store_site();
22115
22116 if ( ! $this->is_addon() ||
22117 ! $this->deactivate_premium_only_addon_without_license( true )
22118 ) {
22119 $this->_admin_notices->add(
22120 sprintf( $this->get_text_inline( 'Your %s free trial was successfully cancelled.', 'trial-cancel-message' ), $trial_plan->title )
22121 );
22122 }
22123
22124 return $site;
22125 }
22126
22127 /**
22128 * @author Vova Feldman (@svovaf)
22129 * @since 1.0.6
22130 *
22131 * @param bool|number $plugin_id
22132 *
22133 * @return bool
22134 */
22135 private function _is_addon_id( $plugin_id ) {
22136 return is_numeric( $plugin_id ) && ( $this->get_id() != $plugin_id );
22137 }
22138
22139 /**
22140 * Check if user eligible to download premium version updates.
22141 *
22142 * @author Vova Feldman (@svovaf)
22143 * @since 1.0.6
22144 *
22145 * @return bool
22146 */
22147 private function _can_download_premium() {
22148 return $this->has_any_active_valid_license() ||
22149 ( $this->is_trial() && ! $this->get_trial_plan()->is_free() );
22150 }
22151
22152 /**
22153 *
22154 * @author Vova Feldman (@svovaf)
22155 * @since 1.0.6
22156 *
22157 * @param bool|number $addon_id
22158 * @param string $type "json" or "zip"
22159 *
22160 * @return string
22161 */
22162 private function _get_latest_version_endpoint( $addon_id = false, $type = 'json' ) {
22163
22164 $is_addon = $this->_is_addon_id( $addon_id );
22165
22166 $is_premium = null;
22167 if ( ! $is_addon ) {
22168 $is_premium = ( $this->is_premium() || $this->_can_download_premium() );
22169 } else if ( $this->is_addon_activated( $addon_id ) ) {
22170 $fs_addon = self::get_instance_by_id( $addon_id );
22171 $is_premium = ( $fs_addon->is_premium() || $fs_addon->_can_download_premium() );
22172 }
22173
22174 // If add-on, then append add-on ID.
22175 $endpoint = ( $is_addon ? "/addons/$addon_id" : '' ) .
22176 '/updates/latest.' . $type;
22177
22178 // If add-on and not yet activated, try to fetch based on server licensing.
22179 if ( is_bool( $is_premium ) ) {
22180 $endpoint = add_query_arg( 'is_premium', json_encode( $is_premium ), $endpoint );
22181 }
22182
22183 if ( $this->has_secret_key() ) {
22184 $endpoint = add_query_arg( 'type', 'all', $endpoint );
22185 } else if ( is_object( $this->_site ) && $this->_site->is_beta() ) {
22186 $endpoint = add_query_arg( 'type', 'beta', $endpoint );
22187 }
22188
22189 return $endpoint;
22190 }
22191
22192 /**
22193 * @author Vova Feldman (@svovaf)
22194 * @since 1.0.4
22195 *
22196 * @param bool|number $addon_id
22197 * @param bool $flush Since 1.1.7.3
22198 * @param int $expiration Since 1.2.2.7
22199 * @param bool|string $newer_than Since 2.2.1
22200 * @param bool|string $fetch_readme Since 2.2.1
22201 *
22202 * @return object|false Plugin latest tag info.
22203 */
22204 function _fetch_latest_version(
22205 $addon_id = false,
22206 $flush = true,
22207 $expiration = WP_FS__TIME_24_HOURS_IN_SEC,
22208 $newer_than = false,
22209 $fetch_readme = true
22210 ) {
22211 $this->_logger->entrance();
22212
22213 if ( $this->is_unresolved_clone( true ) ) {
22214 return false;
22215 }
22216
22217 $switch_to_blog_id = null;
22218
22219 /**
22220 * @since 1.1.7.3 Check for plugin updates from Freemius only if opted-in.
22221 * @since 1.1.7.4 Also check updates for add-ons.
22222 */
22223 if (
22224 ( ! $this->is_registered() || ! FS_Permission_Manager::instance( $this )->is_essentials_tracking_allowed() ) &&
22225 ! $this->_is_addon_id( $addon_id )
22226 ) {
22227 if ( ! is_multisite() ) {
22228 return false;
22229 }
22230
22231 $installs_map = $this->get_blog_install_map();
22232
22233 foreach ( $installs_map as $blog_id => $install ) {
22234 if ( ! FS_Permission_Manager::instance( $this )->is_essentials_tracking_allowed( $blog_id ) ) {
22235 continue;
22236 }
22237
22238 /**
22239 * @var FS_Site $install
22240 */
22241 if ( $install->is_trial() ) {
22242 $switch_to_blog_id = $blog_id;
22243 break;
22244 }
22245
22246 if ( FS_Plugin_License::is_valid_id( $install->license_id ) ) {
22247 $license = $this->get_license_by_id( $install->license_id );
22248
22249 if ( is_object( $license ) && $license->is_features_enabled() ) {
22250 $switch_to_blog_id = $blog_id;
22251 break;
22252 }
22253 }
22254 }
22255
22256 if ( is_null( $switch_to_blog_id ) ) {
22257 return false;
22258 }
22259 }
22260
22261 $current_blog_id = is_numeric( $switch_to_blog_id ) ?
22262 get_current_blog_id() :
22263 0;
22264
22265 if ( is_numeric( $switch_to_blog_id ) ) {
22266 $this->switch_to_blog( $switch_to_blog_id );
22267 }
22268
22269 $latest_version_endpoint = $this->_get_latest_version_endpoint( $addon_id, 'json' );
22270
22271 if ( ! empty( $newer_than ) ) {
22272 $latest_version_endpoint = add_query_arg( 'newer_than', $newer_than, $latest_version_endpoint );
22273 }
22274
22275 if ( true === $fetch_readme ) {
22276 $latest_version_endpoint = add_query_arg( 'readme', 'true', $latest_version_endpoint );
22277 }
22278
22279 $tag = $this->get_api_site_or_plugin_scope()->get(
22280 $latest_version_endpoint,
22281 $flush,
22282 $expiration
22283 );
22284
22285 if ( is_numeric( $switch_to_blog_id ) ) {
22286 $this->switch_to_blog( $current_blog_id );
22287 }
22288
22289 $latest_version = ( is_object( $tag ) && isset( $tag->version ) ) ? $tag->version : 'couldn\'t get';
22290
22291 $this->_logger->departure( 'Latest version ' . $latest_version );
22292
22293 return ( is_object( $tag ) && isset( $tag->version ) ) ? $tag : false;
22294 }
22295
22296 #----------------------------------------------------------------------------------
22297 #region Download Plugin
22298 #----------------------------------------------------------------------------------
22299
22300 /**
22301 * Download latest plugin version, based on plan.
22302 *
22303 * Not like _download_latest(), this will redirect the page
22304 * to secure download url to prevent dual download (from FS to WP server,
22305 * and then from WP server to the client / browser).
22306 *
22307 * @author Vova Feldman (@svovaf)
22308 * @since 1.0.9
22309 *
22310 * @param bool|number $plugin_id
22311 *
22312 * @uses FS_Api
22313 * @uses wp_redirect()
22314 */
22315 private function download_latest_directly( $plugin_id = false ) {
22316 $this->_logger->entrance();
22317
22318 wp_redirect( $this->get_latest_download_api_url( $plugin_id ) );
22319 }
22320
22321 /**
22322 * Get latest plugin FS API download URL.
22323 *
22324 * @author Vova Feldman (@svovaf)
22325 * @since 1.0.9
22326 *
22327 * @param bool|number $plugin_id
22328 *
22329 * @return string
22330 */
22331 private function get_latest_download_api_url( $plugin_id = false ) {
22332 $this->_logger->entrance();
22333
22334 $download_api_url = $this->get_api_site_scope()->get_signed_url(
22335 $this->_get_latest_version_endpoint( $plugin_id, 'zip' )
22336 );
22337
22338 return str_replace( 'http:', 'https:', $download_api_url );
22339 }
22340
22341 /**
22342 * Get payment invoice URL.
22343 *
22344 * @author Vova Feldman (@svovaf)
22345 * @since 1.2.0
22346 *
22347 * @param bool|number $payment_id
22348 *
22349 * @return string
22350 */
22351 function _get_invoice_api_url( $payment_id = false ) {
22352 $this->_logger->entrance();
22353
22354 $url = $this->get_api_user_scope()->get_signed_url(
22355 "/payments/{$payment_id}/invoice.pdf"
22356 );
22357
22358 if ( ! fs_starts_with( $url, 'https://' ) ) {
22359 // Always use HTTPS for invoices.
22360 $url = 'https' . substr( $url, 4 );
22361 }
22362
22363 return $url;
22364 }
22365
22366 /**
22367 * Get latest plugin download link.
22368 *
22369 * @author Vova Feldman (@svovaf)
22370 * @since 1.0.9
22371 *
22372 * @param string $label
22373 * @param bool|number $plugin_id
22374 *
22375 * @return string
22376 */
22377 private function get_latest_download_link( $label, $plugin_id = false ) {
22378 return sprintf(
22379 '<a target="_blank" rel="noopener" href="%s">%s</a>',
22380 $this->_get_latest_download_local_url( $plugin_id ),
22381 $label
22382 );
22383 }
22384
22385 /**
22386 * Get latest plugin download local URL.
22387 *
22388 * @author Vova Feldman (@svovaf)
22389 * @since 1.0.9
22390 *
22391 * @param bool|number $plugin_id
22392 *
22393 * @return string
22394 */
22395 function _get_latest_download_local_url( $plugin_id = false ) {
22396 // Add timestamp to protect from caching.
22397 $params = array( 'ts' => WP_FS__SCRIPT_START_TIME );
22398
22399 if ( ! empty( $plugin_id ) ) {
22400 $params['plugin_id'] = $plugin_id;
22401 } else if ( $this->is_addon() ) {
22402 $params['plugin_id'] = $this->get_id();
22403 }
22404
22405 $fs = $this->is_addon() ?
22406 $this->get_parent_instance() :
22407 $this;
22408
22409 return $this->apply_filters( 'download_latest_url', $fs->get_account_url( 'download_latest', $params ) );
22410 }
22411
22412 #endregion Download Plugin ------------------------------------------------------------------
22413
22414 /**
22415 * @author Vova Feldman (@svovaf)
22416 * @since 1.0.4
22417 *
22418 * @uses FS_Api
22419 *
22420 * @param bool $background Hints the method if it's a background updates check. If false, it means that
22421 * was initiated by the admin.
22422 * @param bool|number $plugin_id
22423 * @param bool $flush Since 1.1.7.3
22424 * @param int $expiration Since 1.2.2.7
22425 * @param bool|string $newer_than Since 2.2.1
22426 */
22427 private function check_updates(
22428 $background = false,
22429 $plugin_id = false,
22430 $flush = true,
22431 $expiration = WP_FS__TIME_24_HOURS_IN_SEC,
22432 $newer_than = false
22433 ) {
22434 $this->_logger->entrance();
22435
22436 // Check if there's a newer version for download.
22437 $new_version = $this->_fetch_newer_version( $plugin_id, $flush, $expiration, $newer_than );
22438
22439 $update = null;
22440 if ( is_object( $new_version ) ) {
22441 $update = new FS_Plugin_Tag( $new_version );
22442
22443 if ( ! $background ) {
22444 $this->_admin_notices->add(
22445 sprintf(
22446 /* translators: %s: Numeric version number (e.g. '2.1.9' */
22447 $this->get_text_inline( 'Version %s was released.', 'version-x-released' ) . ' ' . $this->get_text_inline( 'Please download %s.', 'please-download-x' ),
22448 $update->version,
22449 sprintf(
22450 '<a href="%s" target="_blank" rel="noopener">%s</a>',
22451 $this->get_account_url( 'download_latest' ),
22452 sprintf(
22453 /* translators: %s: plan name (e.g. latest "Professional" version) */
22454 $this->get_text_inline( 'the latest %s version here', 'latest-x-version' ),
22455 $this->get_plan_title()
22456 )
22457 )
22458 ),
22459 $this->get_text_inline( 'New', 'new' ) . '!'
22460 );
22461 }
22462 } else if ( false === $new_version && ! $background ) {
22463 $this->_admin_notices->add(
22464 $this->get_text_inline( 'Seems like you got the latest release.', 'you-have-latest' ),
22465 $this->get_text_inline( 'You are all good!', 'you-are-good' )
22466 );
22467 }
22468
22469 $this->_store_update( $update, true, $plugin_id );
22470 }
22471
22472 /**
22473 * @author Vova Feldman (@svovaf)
22474 * @since 1.0.4
22475 *
22476 * @param bool $flush Since 1.1.7.3 add 24 hour cache by default.
22477 *
22478 * @return FS_Plugin[]
22479 *
22480 * @uses FS_Api
22481 */
22482 private function sync_addons( $flush = false ) {
22483 $this->_logger->entrance();
22484
22485 $api = $this->get_api_site_or_plugin_scope();
22486
22487 $path = $this->add_show_pending( '/addons.json?enriched=true&count=50' );
22488
22489 /**
22490 * @since 1.2.1
22491 *
22492 * If there's a cached version of the add-ons and not asking
22493 * for a flush, just use the currently stored add-ons.
22494 */
22495 if ( ! $flush && $api->is_cached( $path ) ) {
22496 $addons = self::get_all_addons();
22497
22498 return isset( $addons[ $this->_plugin->id ] ) ?
22499 $addons[ $this->_plugin->id ] :
22500 array();
22501 }
22502
22503 $result = $api->get( $path, $flush );
22504
22505 $addons = array();
22506 if ( $this->is_api_result_object( $result, 'plugins' ) &&
22507 is_array( $result->plugins )
22508 ) {
22509 for ( $i = 0, $len = count( $result->plugins ); $i < $len; $i ++ ) {
22510 $addons[ $i ] = new FS_Plugin( $result->plugins[ $i ] );
22511 }
22512
22513 $this->_store_addons( $addons, true );
22514 }
22515
22516 return $addons;
22517 }
22518
22519 /**
22520 * Handle user email update.
22521 *
22522 * @author Vova Feldman (@svovaf)
22523 * @since 1.0.3
22524 * @uses FS_Api
22525 *
22526 * @param string $new_email
22527 *
22528 * @return object
22529 */
22530 private function update_email( $new_email ) {
22531 $this->_logger->entrance();
22532
22533 $api = $this->get_api_user_scope();
22534 $user = $api->call( "?plugin_id={$this->_plugin->id}&fields=id,email,is_verified", 'put', array(
22535 'email' => $new_email,
22536 'after_email_confirm_url' => $this->_get_admin_page_url(
22537 'account',
22538 array( 'fs_action' => 'sync_user' )
22539 ),
22540 ) );
22541
22542 if ( ! isset( $user->error ) ) {
22543 $this->_user->email = $user->email;
22544 $this->_user->is_verified = $user->is_verified;
22545 $this->_store_user();
22546 } else {
22547 // handle different error cases.
22548 }
22549
22550 return $user;
22551 }
22552
22553 #----------------------------------------------------------------------------------
22554 #region API Error Handling
22555 #----------------------------------------------------------------------------------
22556
22557 /**
22558 * @author Vova Feldman (@svovaf)
22559 * @since 1.1.1
22560 *
22561 * @param mixed $result
22562 *
22563 * @return bool Is API result contains an error.
22564 */
22565 private function is_api_error( $result ) {
22566 return FS_Api::is_api_error( $result );
22567 }
22568
22569 /**
22570 * Checks if given API result is a non-empty and not an error object.
22571 *
22572 * @author Vova Feldman (@svovaf)
22573 * @since 1.2.1.5
22574 *
22575 * @param mixed $result
22576 * @param string|null $required_property Optional property we want to verify that is set.
22577 *
22578 * @return bool
22579 */
22580 function is_api_result_object( $result, $required_property = null ) {
22581 return FS_Api::is_api_result_object( $result, $required_property );
22582 }
22583
22584 /**
22585 * Checks if given API result is a non-empty entity object with non-empty ID.
22586 *
22587 * @author Vova Feldman (@svovaf)
22588 * @since 1.2.1.5
22589 *
22590 * @param mixed $result
22591 *
22592 * @return bool
22593 */
22594 private function is_api_result_entity( $result ) {
22595 return FS_Api::is_api_result_entity( $result );
22596 }
22597
22598 #endregion
22599
22600 /**
22601 * Make sure a given argument is an array of a specific type.
22602 *
22603 * @author Vova Feldman (@svovaf)
22604 * @since 1.2.1.5
22605 *
22606 * @param mixed $array
22607 * @param string $class
22608 *
22609 * @return bool
22610 */
22611 private function is_array_instanceof( $array, $class ) {
22612 return ( is_array( $array ) && ( empty( $array ) || $array[0] instanceof $class ) );
22613 }
22614
22615 /**
22616 * Start install ownership change.
22617 *
22618 * @author Vova Feldman (@svovaf)
22619 * @since 1.1.1
22620 * @uses FS_Api
22621 *
22622 * @param string $candidate_email
22623 * @param string $transfer_type
22624 *
22625 * @return bool Is ownership change successfully initiated.
22626 */
22627 private function init_change_owner( $candidate_email, $transfer_type ) {
22628 $this->_logger->entrance();
22629
22630 $installs_info_by_slug_map = $this->get_parent_and_addons_installs_info();
22631 $install_ids = array();
22632
22633 foreach ( $installs_info_by_slug_map as $slug => $install_info ) {
22634 $install = $install_info['install'];
22635
22636 if ( $this->_user->id != $install->user_id ) {
22637 // Skip add-on installs that are not owned by the parent product's install's owner.
22638 continue;
22639 }
22640
22641 $install_ids[ $slug ] = $install->id;
22642 }
22643
22644 $api = $this->get_api_site_scope();
22645 $result = $api->call( "/users/{$this->_user->id}.json", 'put', array(
22646 'email' => $candidate_email,
22647 'transfer_type' => $transfer_type,
22648 'install_ids' => implode( ',', array_values( $install_ids ) ),
22649 'after_confirm_url' => $this->_get_admin_page_url(
22650 'account',
22651 array( 'fs_action' => 'change_owner' )
22652 ),
22653 ) );
22654
22655 return ! $this->is_api_error( $result );
22656 }
22657
22658 /**
22659 * Handle install ownership change.
22660 *
22661 * @author Vova Feldman (@svovaf)
22662 * @since 1.1.1
22663 * @uses FS_Api
22664 *
22665 * @return bool Was ownership change successfully complete.
22666 */
22667 private function complete_change_owner() {
22668 $this->_logger->entrance();
22669
22670 $install_ids = fs_request_get( 'install_ids' );
22671
22672 if ( ! empty( $install_ids ) ) {
22673 $install_ids = explode( ',', $install_ids );
22674
22675 foreach ( $install_ids as $key => $install_id ) {
22676 if ( ! FS_Site::is_valid_id( $install_id ) ) {
22677 unset( $install_ids[ $key ] );
22678 }
22679 }
22680 }
22681
22682 if ( ! is_array( $install_ids ) ) {
22683 $install_ids = array();
22684 }
22685
22686 $user = new FS_User();
22687 $user->id = fs_request_get( 'user_id' );
22688 $user->public_key = fs_request_get( 'user_public_key' );
22689 $user->secret_key = fs_request_get( 'user_secret_key' );
22690
22691 $prev_user = $this->_user;
22692 $this->_user = $user;
22693
22694 $result = $this->get_api_user_scope( true )->get(
22695 "/installs.json?install_ids=" . implode( ',', $install_ids )
22696 );
22697
22698 $current_blog_sites = self::get_all_sites( $this->get_module_type() );
22699
22700 if ( $this->is_api_result_object( $result, 'installs' ) ) {
22701 $site_id_slug_map = array();
22702
22703 foreach ( $current_blog_sites as $slug => $site ) {
22704 $site_id_slug_map[ $site->id ] = $slug;
22705 }
22706
22707 foreach ( $result->installs as $install ) {
22708 $site = new FS_Site( $install );
22709
22710 if ( ! isset( $site_id_slug_map[ $install->id ] ) ) {
22711 continue;
22712 }
22713
22714 $current_blog_sites[ $site_id_slug_map[ $install->id ] ] = clone $site;
22715
22716 if ( $this->_site->id == $site->id ) {
22717 $this->_site = $site;
22718 }
22719 }
22720 }
22721
22722 // Validate install's user and given user.
22723 if ( $user->id != $this->_site->user_id ) {
22724 $this->_user = $prev_user;
22725
22726 return false;
22727 }
22728
22729 $this->set_account_option( 'sites', $current_blog_sites, true );
22730
22731 // Fetch new user information.
22732 $user_result = $this->get_api_user_scope( true )->get();
22733 $user = new FS_User( $user_result );
22734 $this->_user = $user;
22735
22736 $this->_set_account( $user, $this->_site );
22737
22738 $remove_user = true;
22739 $all_modules_sites = self::get_all_modules_sites();
22740
22741 foreach ( $all_modules_sites as $sites_by_module_type ) {
22742 foreach ( $sites_by_module_type as $sites_by_slug ) {
22743 foreach ( $sites_by_slug as $site ) {
22744 if ( $prev_user->id == $site->user_id ) {
22745 $remove_user = false;
22746 break;
22747 }
22748 }
22749
22750 if ( ! $remove_user ) {
22751 break;
22752 }
22753 }
22754
22755 if ( ! $remove_user ) {
22756 break;
22757 }
22758 }
22759
22760 if ( $remove_user ) {
22761 $users = self::get_all_users();
22762
22763 if ( isset( $users[ $prev_user->id ] ) ) {
22764 unset( $users[ $prev_user->id ] );
22765 } else {
22766 // If the prev user wasn't found by the key, iterate over the users collection.
22767 foreach ( $users as $key => $user ) {
22768 if ( $user->id == $prev_user->id ) {
22769 unset( $users[ $key ] );
22770 break;
22771 }
22772 }
22773 }
22774
22775 $this->set_account_option( 'users', $users, true );
22776 }
22777
22778 return true;
22779 }
22780
22781 /**
22782 * Completes ownership change by license.
22783 *
22784 * @author Leo Fajardo (@leorw)
22785 * @since 2.3.2
22786 *
22787 * @param number $user_id
22788 * @param array[string]number $install_ids_by_slug_map
22789 *
22790 */
22791 private function complete_ownership_change_by_license( $user_id, $install_ids_by_slug_map ) {
22792 $this->_logger->entrance();
22793
22794 $this->sync_user_by_current_install( $user_id );
22795
22796 $result = $this->get_api_user_scope( true )->get(
22797 "/installs.json?install_ids=" . implode( ',', $install_ids_by_slug_map )
22798 );
22799
22800 if ( $this->is_api_result_object( $result, 'installs' ) ) {
22801 $sites = self::get_all_sites( $this->get_module_type() );
22802 $install_ids_by_slug_map = array_flip( $install_ids_by_slug_map );
22803
22804 foreach ( $result->installs as $install ) {
22805 $site = new FS_Site( $install );
22806
22807 $sites[ $install_ids_by_slug_map[ $site->id ] ] = clone $site;
22808 }
22809
22810 $this->set_account_option( 'sites', $sites, true );
22811 }
22812 }
22813
22814 /**
22815 * Handle user name update.
22816 *
22817 * @author Vova Feldman (@svovaf)
22818 * @since 1.0.9
22819 * @uses FS_Api
22820 *
22821 * @return object
22822 */
22823 private function update_user_name() {
22824 $this->_logger->entrance();
22825 $name = fs_request_get( 'fs_user_name_' . $this->get_unique_affix(), '' );
22826
22827 $api = $this->get_api_user_scope();
22828 $user = $api->call( "?plugin_id={$this->_plugin->id}&fields=id,first,last", 'put', array(
22829 'name' => $name,
22830 ) );
22831
22832 if ( ! isset( $user->error ) ) {
22833 $this->_user->first = $user->first;
22834 $this->_user->last = $user->last;
22835 $this->_store_user();
22836 } else {
22837 // handle different error cases.
22838
22839 }
22840
22841 return $user;
22842 }
22843
22844 /**
22845 * Verify user email.
22846 *
22847 * @author Vova Feldman (@svovaf)
22848 * @since 1.0.3
22849 * @uses FS_Api
22850 */
22851 private function verify_email() {
22852 $this->_handle_account_user_sync();
22853
22854 if ( $this->_user->is_verified() ) {
22855 return;
22856 }
22857
22858 $api = $this->get_api_site_scope();
22859 $result = $api->call( "/users/{$this->_user->id}/verify.json", 'put', array(
22860 'after_email_confirm_url' => $this->_get_admin_page_url(
22861 'account',
22862 array( 'fs_action' => 'sync_user' )
22863 )
22864 ) );
22865
22866 if ( ! isset( $result->error ) ) {
22867 $this->_admin_notices->add( sprintf(
22868 $this->get_text_inline( 'Verification mail was just sent to %s. If you can\'t find it after 5 min, please check your spam box.', 'verification-email-sent-message' ),
22869 sprintf( '<a href="mailto:%1$s">%2$s</a>', esc_url( $this->_user->email ), $this->_user->email )
22870 ) );
22871 } else {
22872 // handle different error cases.
22873
22874 }
22875 }
22876
22877 /**
22878 * @author Vova Feldman (@svovaf)
22879 * @since 1.1.2
22880 *
22881 * @param array $params
22882 * @param bool|null $network
22883 *
22884 * @return string
22885 */
22886 function get_activation_url( $params = array(), $network = null ) {
22887 if ( $this->is_addon() && $this->has_free_plan() ) {
22888 /**
22889 * @author Vova Feldman (@svovaf)
22890 * @since 1.2.1.7 Add-on's activation is the parent's module activation.
22891 */
22892 return $this->get_parent_instance()->get_activation_url( $params );
22893 }
22894
22895 return $this->apply_filters( 'connect_url', $this->_get_admin_page_url( '', $params, $network ) );
22896 }
22897
22898 /**
22899 * @author Vova Feldman (@svovaf)
22900 * @since 1.2.1.5
22901 *
22902 * @param array $params
22903 *
22904 * @return string
22905 */
22906 function get_reconnect_url( $params = array() ) {
22907 $params['fs_action'] = 'reset_anonymous_mode';
22908 $params['fs_unique_affix'] = $this->get_unique_affix();
22909
22910 return $this->get_activation_url( $params );
22911 }
22912
22913 /**
22914 * Get the URL of the page that should be loaded after the user connect
22915 * or skip in the opt-in screen.
22916 *
22917 * @author Vova Feldman (@svovaf)
22918 * @since 1.1.3
22919 *
22920 * @param string $filter Filter name.
22921 * @param array $params Since 1.2.2.7
22922 * @param bool|null $network
22923 *
22924 * @return string
22925 */
22926 function get_after_activation_url( $filter, $params = array(), $network = null ) {
22927 if ( $this->show_opt_in_on_themes_page() &&
22928 ( fs_request_has( 'pending_activation' ) ||
22929 // For cases when the first time path is set, even though it's a WP.org theme.
22930 fs_request_get_bool( $this->get_unique_affix() . '_show_optin' ) )
22931 ) {
22932 $first_time_path = '';
22933 } else {
22934 $first_time_path = $this->_menu->get_first_time_path(
22935 fs_is_network_admin() && $this->_is_network_active
22936 );
22937 }
22938
22939 if ( $this->_is_network_active &&
22940 fs_is_network_admin() &&
22941 ! $this->_menu->has_network_menu() &&
22942 $this->is_network_registered()
22943 ) {
22944 $target_url = $this->get_account_url();
22945 } else {
22946 // Default plugin's page.
22947 $target_url = $this->_get_admin_page_url( '', array(), $network );
22948 }
22949
22950 return add_query_arg( $params, $this->apply_filters(
22951 $filter,
22952 empty( $first_time_path ) ?
22953 $target_url :
22954 $first_time_path
22955 ) );
22956 }
22957
22958 /**
22959 * Handle account page updates / edits / actions.
22960 *
22961 * @author Vova Feldman (@svovaf)
22962 * @since 1.0.2
22963 *
22964 */
22965 private function _handle_account_edits() {
22966 if ( ! $this->is_user_admin() ) {
22967 return;
22968 }
22969
22970 $action = fs_get_action();
22971
22972 if ( empty( $action ) ) {
22973 return;
22974 }
22975
22976 $plugin_id = fs_request_get( 'plugin_id', $this->get_id() );
22977 $install_id = fs_request_get( 'install_id', '' );
22978
22979 // Alias.
22980 $oops_text = $this->get_text_x_inline( 'Oops', 'exclamation', 'oops' ) . '...';
22981
22982 $is_network_action = $this->is_network_level_action();
22983 $blog_id = $this->is_network_level_site_specific_action();
22984 $is_parent_plugin_action = ( $plugin_id == $this->get_id() );
22985
22986 if ( is_numeric( $blog_id ) ) {
22987 $this->switch_to_blog( $blog_id );
22988 } else {
22989 $blog_id = '';
22990 }
22991
22992 switch ( $action ) {
22993 case 'opt_in':
22994 check_admin_referer( trim( "{$action}:{$blog_id}:{$install_id}", ':' ) );
22995
22996 if ( $is_parent_plugin_action ) {
22997 if ( $is_network_action && ! empty( $blog_id ) ) {
22998 if ( ! $this->is_registered() ) {
22999 $this->install_with_user(
23000 $this->get_network_user(),
23001 false,
23002 false,
23003 false,
23004 false
23005 );
23006
23007 $this->_admin_notices->add(
23008 $this->get_text_inline( 'Site successfully opted in.', 'successful-opt-in' ),
23009 $this->get_text_inline( 'Awesome', 'awesome' )
23010 );
23011 }
23012 }
23013 }
23014 break;
23015
23016 case 'toggle_tracking':
23017 check_admin_referer( trim( "{$action}:{$blog_id}:{$install_id}", ':' ) );
23018
23019 if ( $is_parent_plugin_action ) {
23020 if ( $is_network_action && ! empty( $blog_id ) ) {
23021 if ( $this->is_registered( true ) ) {
23022 if ( $this->is_tracking_prohibited( $blog_id ) ) {
23023 if ( $this->toggle_site_tracking( true, $blog_id ) ) {
23024 $this->_admin_notices->add(
23025 sprintf( $this->get_text_inline( 'Sharing diagnostic data with %s helps to provide functionality that\'s more relevant to your website, avoid WordPress or PHP version incompatibilities that can break your website, and recognize which languages & regions the plugin should be translated and tailored to.', 'opt-out-message-appreciation' ), "<b>{$this->get_plugin_title()}</b>" ),
23026 $this->get_text_inline( 'Thank you!', 'thank-you' )
23027 );
23028 }
23029 } else {
23030 if ( $this->toggle_site_tracking( false, $blog_id ) ) {
23031 $install = $this->get_install_by_blog_id( $blog_id );
23032
23033 $this->_admin_notices->add(
23034 sprintf(
23035 $this->get_text_inline( 'Diagnostic data will no longer be sent from %s to %s.', 'opted-out-successfully' ),
23036 self::get_unfiltered_site_url( $blog_id, true ),
23037 "<b>{$this->get_plugin_title()}</b>"
23038 )
23039 );
23040 }
23041 }
23042 }
23043 }
23044 }
23045
23046 break;
23047
23048 case 'delete_account':
23049 check_admin_referer( trim( "{$action}:{$blog_id}:{$install_id}", ':' ) );
23050
23051 $is_network_deletion = $is_network_action && empty( $blog_id );
23052
23053 if ( $is_parent_plugin_action ) {
23054 // Delete add-on installs if have any.
23055 $installed_addons = $this->get_installed_addons();
23056 foreach ( $installed_addons as $fs_addon ) {
23057 if ( $is_network_deletion ) {
23058 $fs_addon->delete_network_account_event();
23059 } else {
23060 $fs_addon->delete_account_event();
23061 }
23062 }
23063
23064 if ( $is_network_deletion ) {
23065 $this->delete_network_account_event();
23066 } else {
23067 $this->delete_account_event();
23068 }
23069
23070 // Clear user and site.
23071 $this->_site = null;
23072 $this->_user = null;
23073
23074 $this->maybe_set_slug_and_network_menu_exists_flag();
23075
23076 fs_redirect( $this->get_activation_url() );
23077 } else {
23078 if ( $this->is_addon_activated( $plugin_id ) ) {
23079 $fs_addon = self::get_instance_by_id( $plugin_id );
23080
23081 if ( $is_network_deletion ) {
23082 $fs_addon->delete_network_account_event();
23083 } else {
23084 $fs_addon->delete_account_event();
23085 }
23086
23087 fs_redirect( $this->_get_admin_page_url( 'account' ) );
23088 }
23089 }
23090
23091 return;
23092
23093 case 'downgrade_account':
23094 if ( is_numeric( $blog_id ) ) {
23095 check_admin_referer( trim( "{$action}:{$blog_id}:{$install_id}", ':' ) );
23096 } else {
23097 check_admin_referer( $action );
23098 }
23099
23100 $switch_to_network_install_blog_after_cancellation = (
23101 is_numeric( $blog_id ) &&
23102 $plugin_id == $this->get_id() &&
23103 ! $this->is_trial()
23104 );
23105
23106 $result = $this->cancel_subscription_or_trial( $plugin_id );
23107 if ( $this->is_api_error( $result ) ) {
23108 $this->_admin_notices->add(
23109 $result->error->message,
23110 $this->get_text_x_inline( 'Oops', 'exclamation', 'oops' ) . '...',
23111 'error'
23112 );
23113 }
23114
23115 if ( $switch_to_network_install_blog_after_cancellation ) {
23116 $this->switch_to_blog( $this->_storage->network_install_blog_id );
23117 }
23118
23119 return;
23120
23121 case 'activate_license':
23122 check_admin_referer( trim( "{$action}:{$blog_id}:{$install_id}", ':' ) );
23123
23124 $fs = $this;
23125 if ( $plugin_id != $this->get_id() ) {
23126 $fs = $this->is_addon_activated( $plugin_id ) ?
23127 self::get_instance_by_id( $plugin_id ) :
23128 null;
23129 }
23130
23131 if ( is_object( $fs ) ) {
23132 $fs->_activate_license();
23133
23134 /**
23135 * Remove the product ID from `$_REQUEST` so that the syncing of the license for the other products will work properly.
23136 *
23137 * @author Leo Fajardo (@leorw)
23138 * @since 2.4.0
23139 */
23140 unset( $_REQUEST['plugin_id'] );
23141
23142 if ( $this->is_bundle_license_auto_activation_enabled() ) {
23143 $fs->maybe_activate_bundle_license( null, array(), is_numeric( $blog_id ) ? $blog_id : 0 );
23144 }
23145 }
23146
23147 return;
23148
23149 case 'deactivate_license':
23150 check_admin_referer( trim( "{$action}:{$blog_id}:{$install_id}", ':' ) );
23151
23152 if ( $plugin_id == $this->get_id() ) {
23153 $this->_deactivate_license();
23154
23155 if ( $this->is_only_premium() ) {
23156 // Clear user and site.
23157 $this->_site = null;
23158 $this->_user = null;
23159
23160 if ( ! $is_network_action ) {
23161 fs_redirect( $this->get_activation_url() );
23162 } else if ( is_numeric( $blog_id ) ) {
23163 $this->switch_to_blog( $this->_storage->network_install_blog_id );
23164 }
23165 }
23166 } else {
23167 if ( $this->is_addon_activated( $plugin_id ) ) {
23168 $fs_addon = self::get_instance_by_id( $plugin_id );
23169 $fs_addon->_deactivate_license();
23170 }
23171 }
23172
23173 return;
23174
23175 case 'check_updates':
23176 check_admin_referer( $action );
23177 $this->check_updates();
23178
23179 return;
23180
23181 case 'change_owner':
23182 $state = fs_request_get( 'state', 'init' );
23183 switch ( $state ) {
23184 case 'init':
23185 $candidate_email = fs_request_get( 'candidate_email' );
23186 $transfer_type = fs_request_get( 'transfer_type' );
23187
23188 if ( $this->init_change_owner( $candidate_email, $transfer_type ) ) {
23189 if ( 'transfer' === $transfer_type ) {
23190 $this->_admin_notices->add( sprintf( $this->get_text_inline( 'A confirmation email was just sent to %s. The email owner must confirm the update within the next 4 hours.', 'change-owner-request-sent-x-transfer' ), '<b>' . $this->_user->email . '</b>' ) );
23191 } else {
23192 $this->_admin_notices->add( sprintf( $this->get_text_inline( 'A confirmation email was just sent to %s. You must confirm the update within the next 4 hours. If you cannot find the email, please check your spam folder.', 'change-owner-request-sent-x' ), '<b>' . $this->_user->email . '</b>' ) );
23193 }
23194 }
23195 break;
23196 case 'owner_confirmed':
23197 $candidate_email = fs_request_get( 'candidate_email', '' );
23198
23199 $this->_admin_notices->add( sprintf( $this->get_text_inline( 'Thanks for confirming the ownership change. An email was just sent to %s for final approval.', 'change-owner-request_owner-confirmed' ), '<b>' . $candidate_email . '</b>' ) );
23200 break;
23201 case 'candidate_confirmed':
23202 if ( $this->complete_change_owner() ) {
23203 $this->_admin_notices->add_sticky(
23204 sprintf( $this->get_text_inline( '%s is the new owner of the account.', 'change-owner-request_candidate-confirmed' ), '<b>' . $this->_user->email . '</b>' ),
23205 'ownership_changed',
23206 $this->get_text_x_inline( 'Congrats', 'as congratulations', 'congrats' ) . '!'
23207 );
23208 } else {
23209 // @todo Handle failed ownership change message.
23210 }
23211 break;
23212 }
23213
23214 return;
23215
23216 case 'update_user_name':
23217 check_admin_referer( 'update_user_name' );
23218
23219 $result = $this->update_user_name();
23220
23221 if ( isset( $result->error ) ) {
23222 $this->_admin_notices->add(
23223 $this->get_text_inline( 'Please provide your full name.', 'name-update-failed-message' ),
23224 $oops_text,
23225 'error'
23226 );
23227 } else {
23228 $this->_admin_notices->add( $this->get_text_inline( 'Your name was successfully updated.', 'name-updated-message' ) );
23229 }
23230
23231 return;
23232
23233 #region Actions that might be called from external links (e.g. email)
23234
23235 case 'cancel_trial':
23236 $result = $this->cancel_subscription_or_trial( $plugin_id );
23237 if ( $this->is_api_error( $result ) ) {
23238 $this->_admin_notices->add(
23239 $result->error->message,
23240 $this->get_text_x_inline( 'Oops', 'exclamation', 'oops' ) . '...',
23241 'error'
23242 );
23243 }
23244
23245 return;
23246
23247 case 'verify_email':
23248 $this->verify_email();
23249
23250 return;
23251
23252 case 'sync_user':
23253 $this->_handle_account_user_sync();
23254
23255 return;
23256
23257 case $this->get_unique_affix() . '_sync_license':
23258 $this->_sync_license();
23259
23260 return;
23261
23262 case 'download_latest':
23263 $this->download_latest_directly( $plugin_id );
23264
23265 return;
23266
23267 #endregion
23268 }
23269
23270 if ( WP_FS__IS_POST_REQUEST ) {
23271 $properties = array( 'site_secret_key', 'site_id', 'site_public_key' );
23272 foreach ( $properties as $p ) {
23273 if ( 'update_' . $p === $action ) {
23274 check_admin_referer( $action );
23275
23276 $this->_logger->log( $action );
23277
23278 $site_property = substr( $p, strlen( 'site_' ) );
23279 $site_property_value = fs_request_get( 'fs_' . $p . '_' . $this->get_unique_affix(), '' );
23280 $this->get_site()->{$site_property} = $site_property_value;
23281
23282 // Store account after modification.
23283 $this->_store_site();
23284
23285 $this->do_action( 'account_property_edit', 'site', $site_property, $site_property_value );
23286
23287 $this->_admin_notices->add( sprintf(
23288 /* translators: %s: User's account property (e.g. email address, name) */
23289 $this->get_text_inline( 'You have successfully updated your %s.', 'x-updated' ),
23290 '<b>' . str_replace( '_', ' ', $p ) . '</b>'
23291 ) );
23292
23293 return;
23294 }
23295 }
23296 }
23297 }
23298
23299 /**
23300 * Account page resources load.
23301 *
23302 * @author Vova Feldman (@svovaf)
23303 * @since 1.0.6
23304 */
23305 function _account_page_load() {
23306 $this->_logger->entrance();
23307
23308 $this->_logger->info( var_export( $_REQUEST, true ) );
23309
23310 fs_enqueue_local_style( 'fs_account', '/admin/account.css' );
23311
23312 if ( $this->has_addons() ) {
23313 wp_enqueue_script( 'plugin-install' );
23314 add_thickbox();
23315
23316 function fs_addons_body_class( $classes ) {
23317 $classes .= ' plugins-php';
23318
23319 return $classes;
23320 }
23321
23322 add_filter( 'admin_body_class', 'fs_addons_body_class' );
23323 }
23324
23325 if ( $this->has_paid_plan() &&
23326 ! $this->has_any_license() &&
23327 ! $this->is_sync_executed() &&
23328 $this->is_tracking_allowed()
23329 ) {
23330 /**
23331 * If no licenses found and no sync job was executed during the last 24 hours,
23332 * just execute the sync job right away (blocking execution).
23333 *
23334 * @since 1.1.7.3
23335 */
23336 $this->run_manual_sync();
23337 }
23338
23339 $this->_handle_account_edits();
23340
23341 if (
23342 is_object( $this->_license ) &&
23343 $this->_license->user_id == $this->_user->id &&
23344 ! $this->is_whitelabeled( true )
23345 ) {
23346 $this->_admin_notices->add(
23347 sprintf(
23348 $this->get_text_inline( "Is this your client's site? %s if you wish to hide sensitive info like your email, license key, prices, billing address & invoices from the WP Admin.", 'license_not_whitelabeled' ),
23349 sprintf(
23350 '<a href="#" class="fs-toggle-whitelabel-mode">%s</a>',
23351 $this->get_text_inline( 'Click here', 'click-here' )
23352 )
23353 ),
23354 '',
23355 'success',
23356 false,
23357 'license_not_whitelabeled'
23358 );
23359 }
23360
23361 $this->do_action( 'account_page_load_before_departure' );
23362 }
23363
23364 /**
23365 * Renders the "Affiliation" page.
23366 *
23367 * @author Leo Fajardo (@leorw)
23368 * @since 1.2.3
23369 */
23370 function _affiliation_page_render() {
23371 $this->_logger->entrance();
23372
23373 $this->fetch_affiliate_and_terms();
23374
23375 fs_enqueue_local_style( 'fs_affiliation', '/admin/affiliation.css' );
23376
23377 $is_bundle_context = $this->has_bundle_context();
23378
23379 $plugin_title = $this->get_plugin_title();
23380
23381 if ( $is_bundle_context ) {
23382 $plugin_title = $this->plugin_affiliate_terms->plugin_title;
23383
23384 // Add the suffix "Bundle" only if the word is not present in the title itself.
23385 if ( false === mb_stripos( $plugin_title, fs_text_inline( 'Bundle', 'bundle' ) ) ) {
23386 $plugin_title = $this->apply_filters(
23387 'formatted_bundle_title',
23388 $plugin_title . ' ' . fs_text_inline( 'Bundle', 'bundle' )
23389 );
23390 }
23391 }
23392
23393 $vars = array(
23394 'id' => $this->_module_id,
23395 'plugin_title' => $plugin_title,
23396 );
23397 echo $this->apply_filters( "/forms/affiliation.php", fs_get_template( '/forms/affiliation.php', $vars ) );
23398 }
23399
23400
23401 /**
23402 * Render account page.
23403 *
23404 * @author Vova Feldman (@svovaf)
23405 * @since 1.0.0
23406 */
23407 function _account_page_render() {
23408 $this->_logger->entrance();
23409
23410 $template = 'account.php';
23411 $vars = array( 'id' => $this->_module_id );
23412
23413 /**
23414 * Added filter to the template to allow developers wrapping the template
23415 * in custom HTML (e.g. within a wizard/tabs).
23416 *
23417 * @author Vova Feldman (@svovaf)
23418 * @since 1.2.1.6
23419 */
23420 echo $this->apply_filters( "templates/{$template}", fs_get_template( $template, $vars ) );
23421 }
23422
23423 /**
23424 * Render account connect page.
23425 *
23426 * @author Vova Feldman (@svovaf)
23427 * @since 1.0.7
23428 */
23429 function _connect_page_render() {
23430 $this->_logger->entrance();
23431
23432 $vars = array( 'id' => $this->_module_id );
23433
23434 /**
23435 * Added filter to the template to allow developers wrapping the template
23436 * in custom HTML (e.g. within a wizard/tabs).
23437 *
23438 * @author Vova Feldman (@svovaf)
23439 * @since 1.2.1.6
23440 */
23441 echo $this->apply_filters( 'templates/connect.php', fs_get_template( 'connect.php', $vars ) );
23442 }
23443
23444 /**
23445 * Load required resources before add-ons page render.
23446 *
23447 * @author Vova Feldman (@svovaf)
23448 * @since 1.0.6
23449 */
23450 function _addons_page_load() {
23451 $this->_logger->entrance();
23452
23453 fs_enqueue_local_style( 'fs_addons', '/admin/add-ons.css' );
23454
23455 wp_enqueue_script( 'plugin-install' );
23456 add_thickbox();
23457
23458 function fs_addons_body_class( $classes ) {
23459 $classes .= ' plugins-php';
23460
23461 return $classes;
23462 }
23463
23464 add_filter( 'admin_body_class', 'fs_addons_body_class' );
23465
23466 if ( ! $this->is_registered() && $this->is_org_repo_compliant() ) {
23467 $this->_admin_notices->add(
23468 sprintf( $this->get_text_inline( 'Just letting you know that the add-ons information of %s is being pulled from an external server.', 'addons-info-external-message' ), '<b>' . $this->get_plugin_name() . '</b>' ),
23469 $this->get_text_x_inline( 'Heads up', 'advance notice of something that will need attention.', 'heads-up' ),
23470 'update-nag'
23471 );
23472 }
23473 }
23474
23475 /**
23476 * Render add-ons page.
23477 *
23478 * @author Vova Feldman (@svovaf)
23479 * @since 1.0.6
23480 */
23481 function _addons_page_render() {
23482 $this->_logger->entrance();
23483
23484 $vars = array( 'id' => $this->_module_id );
23485
23486 /**
23487 * Added filter to the template to allow developers wrapping the template
23488 * in custom HTML (e.g. within a wizard/tabs).
23489 *
23490 * @author Vova Feldman (@svovaf)
23491 * @since 1.2.1.6
23492 */
23493 echo $this->apply_filters( 'templates/add-ons.php', fs_get_template( 'add-ons.php', $vars ) );
23494 }
23495
23496 /* Pricing & Upgrade
23497 ------------------------------------------------------------------------------------------------------------------*/
23498 /**
23499 * Render pricing page.
23500 *
23501 * @author Vova Feldman (@svovaf)
23502 * @since 1.0.0
23503 */
23504 function _pricing_page_render() {
23505 $this->_logger->entrance();
23506
23507 $vars = array( 'id' => $this->_module_id );
23508
23509 if ( 'true' === fs_request_get( 'checkout', false ) ) {
23510 echo $this->apply_filters( 'templates/checkout.php', fs_get_template( 'checkout.php', $vars ) );
23511 } else {
23512 echo $this->apply_filters( 'templates/pricing.php', fs_get_template( 'pricing.php', $vars ) );
23513 }
23514 }
23515
23516 /**
23517 * @author Leo Fajardo (@leorw)
23518 * @since 2.3.1
23519 */
23520 function _maybe_add_pricing_ajax_handler() {
23521 if ( ! $this->should_use_external_pricing() ) {
23522 $this->add_ajax_action( 'pricing_ajax_action', array( &$this, '_fs_pricing_ajax_action_handler' ) );
23523 }
23524 }
23525
23526 /**
23527 * @author Leo Fajardo (@leorw)
23528 * @since 2.3.1
23529 */
23530 function _fs_pricing_ajax_action_handler() {
23531 $this->check_ajax_referer( 'pricing_ajax_action' );
23532
23533 $result = null;
23534 $pricing_action = fs_request_get( 'pricing_action' );
23535
23536 switch ( $pricing_action ) {
23537 case 'fetch_pricing_data':
23538 $params = array(
23539 'is_enriched' => true,
23540 'trial' => fs_request_get_bool( 'trial' ),
23541 'sandbox' => fs_request_get( 'sandbox' ),
23542 's_ctx_type' => fs_request_get( 's_ctx_type' ),
23543 's_ctx_id' => fs_request_get( 's_ctx_id' ),
23544 's_ctx_ts' => fs_request_get( 's_ctx_ts' ),
23545 's_ctx_secure' => fs_request_get( 's_ctx_secure' ),
23546 );
23547
23548 $bundle_id = $this->get_bundle_id();
23549 $bundle_public_key = $this->get_bundle_public_key();
23550
23551 $has_bundle_context = ( FS_Plugin::is_valid_id( $bundle_id ) && ! empty( $bundle_public_key ) );
23552
23553 if ( ! $has_bundle_context ) {
23554 $api = $this->get_api_plugin_scope();
23555 } else {
23556 $api = FS_Api::instance(
23557 $bundle_id,
23558 'plugin',
23559 $bundle_id,
23560 $bundle_public_key,
23561 ! $this->is_live(),
23562 false,
23563 $this->get_sdk_version()
23564 );
23565
23566 $params['plugin_id'] = $this->get_id();
23567 $params['plugin_public_key'] = $this->get_public_key();
23568 }
23569
23570 $result = $api->get( 'pricing.json?' . http_build_query( $params ) );
23571 break;
23572 case 'start_trial':
23573 $result = $this->opt_in(
23574 false,
23575 false,
23576 false,
23577 false,
23578 false,
23579 fs_request_get( 'plan_id' )
23580 );
23581 }
23582
23583 if ( is_object( $result ) && $this->is_api_error( $result ) ) {
23584 $this->_logger->api_error( $result );
23585
23586 self::shoot_ajax_failure(
23587 isset( $result->error ) ?
23588 ( is_string( $result->error ) ? $result->error : $result->error->message ) :
23589 var_export( $result, true )
23590 );
23591 }
23592
23593 $this->shoot_ajax_success( $result );
23594 }
23595
23596 #----------------------------------------------------------------------------------
23597 #region Contact Us
23598 #----------------------------------------------------------------------------------
23599
23600 /**
23601 * Render contact-us page.
23602 *
23603 * @author Vova Feldman (@svovaf)
23604 * @since 1.0.3
23605 */
23606 function _contact_page_render() {
23607 $this->_logger->entrance();
23608
23609 $vars = array( 'id' => $this->_module_id );
23610
23611 /**
23612 * Added filter to the template to allow developers wrapping the template
23613 * in custom HTML (e.g. within a wizard/tabs).
23614 *
23615 * @author Vova Feldman (@svovaf)
23616 * @since 2.1.3
23617 */
23618 echo $this->apply_filters( 'templates/contact.php', fs_get_template( 'contact.php', $vars ) );
23619 }
23620
23621 #endregion ------------------------------------------------------------------------
23622
23623 /**
23624 * Hide all admin notices to prevent distractions.
23625 *
23626 * @author Vova Feldman (@svovaf)
23627 * @since 1.0.3
23628 *
23629 * @uses remove_all_actions()
23630 */
23631 private static function _hide_admin_notices() {
23632 remove_all_actions( 'admin_notices' );
23633 remove_all_actions( 'network_admin_notices' );
23634 remove_all_actions( 'all_admin_notices' );
23635 remove_all_actions( 'user_admin_notices' );
23636 }
23637
23638 static function _clean_admin_content_section_hook() {
23639 $hide_admin_notices = true;
23640
23641 if ( fs_request_is_action( 'allow_clone_resolution_notice' ) ) {
23642 check_admin_referer( 'fs_allow_clone_resolution_notice' );
23643
23644 $hide_admin_notices = false;
23645 }
23646
23647 if ( $hide_admin_notices ) {
23648 self::_hide_admin_notices();
23649 }
23650
23651 // Hide footer.
23652 echo '<style>#wpfooter { display: none !important; }</style>';
23653 }
23654
23655 /**
23656 * Attach to admin_head hook to hide all admin notices.
23657 *
23658 * @author Vova Feldman (@svovaf)
23659 * @since 1.0.3
23660 */
23661 static function _clean_admin_content_section() {
23662 add_action( 'admin_head', 'Freemius::_clean_admin_content_section_hook' );
23663 }
23664
23665 /* CSS & JavaScript
23666 ------------------------------------------------------------------------------------------------------------------*/
23667 /* function _enqueue_script($handle, $src) {
23668 $url = plugins_url( substr( WP_FS__DIR_JS, strlen( $this->_plugin_dir_path ) ) . '/assets/js/' . $src );
23669
23670 $this->_logger->entrance( 'script = ' . $url );
23671
23672 wp_enqueue_script( $handle, $url );
23673 }*/
23674
23675 /* SDK
23676 ------------------------------------------------------------------------------------------------------------------*/
23677 private $_user_api;
23678
23679 /**
23680 *
23681 * @author Vova Feldman (@svovaf)
23682 * @since 1.0.2
23683 *
23684 * @param bool $flush
23685 *
23686 * @return FS_Api
23687 */
23688 function get_api_user_scope( $flush = false ) {
23689 if ( ! isset( $this->_user_api ) || $flush ) {
23690 $this->_user_api = $this->get_api_user_scope_by_user( $this->_user );
23691 }
23692
23693 return $this->_user_api;
23694 }
23695
23696 /**
23697 * @author Vova Feldman (@svovaf)
23698 * @since 2.0.0
23699 *
23700 * @param \FS_User $user
23701 *
23702 * @return \FS_Api
23703 */
23704 private function get_api_user_scope_by_user( FS_User $user ) {
23705 return FS_Api::instance(
23706 $this->_module_id,
23707 'user',
23708 $user->id,
23709 $user->public_key,
23710 ! $this->is_live(),
23711 $user->secret_key,
23712 $this->get_sdk_version()
23713 );
23714 }
23715
23716 /**
23717 *
23718 * @author Leo Fajardo (@leorw)
23719 * @since 2.0.0
23720 *
23721 * @param bool $flush
23722 *
23723 * @return FS_Api
23724 */
23725 private function get_current_or_network_user_api_scope( $flush = false ) {
23726 if ( ! $this->_is_network_active ||
23727 ( isset( $this->_user ) && $this->_user instanceof FS_User )
23728 ) {
23729 return $this->get_api_user_scope( $flush );
23730 }
23731
23732 $user = $this->get_current_or_network_user();
23733
23734 $this->_user_api = FS_Api::instance(
23735 $this->_module_id,
23736 'user',
23737 $user->id,
23738 $user->public_key,
23739 ! $this->is_live(),
23740 $user->secret_key,
23741 $this->get_sdk_version()
23742 );
23743
23744 return $this->_user_api;
23745 }
23746
23747 private $_site_api;
23748
23749 /**
23750 *
23751 * @author Vova Feldman (@svovaf)
23752 * @since 1.0.2
23753 *
23754 * @param bool $flush
23755 *
23756 * @return FS_Api
23757 */
23758 private function get_api_site_scope( $flush = false ) {
23759 if ( ! isset( $this->_site_api ) || $flush ) {
23760 $this->_site_api = FS_Api::instance(
23761 $this->_module_id,
23762 'install',
23763 $this->_site->id,
23764 $this->_site->public_key,
23765 ! $this->is_live(),
23766 $this->_site->secret_key,
23767 $this->get_sdk_version(),
23768 self::get_unfiltered_site_url()
23769 );
23770 }
23771
23772 return $this->_site_api;
23773 }
23774
23775 /**
23776 * @author Leo Fajardo (@leorw)
23777 * @since 2.5.0
23778 *
23779 * @param string $path
23780 * @param string $method
23781 * @param array $params
23782 * @param bool $flush_instance
23783 *
23784 * @return array|mixed|string|void
23785 * @throws Freemius_Exception
23786 */
23787 private function api_site_call( $path, $method = 'GET', $params = array(), $flush_instance = false ) {
23788 $result = $this->get_api_site_scope( $flush_instance )->call( $path, $method, $params );
23789
23790 /**
23791 * Checks if the local install's URL is different from the remote install's URL, update the local install if necessary, and then run the clone handler if the install's URL is different from the URL of the site.
23792 *
23793 * @author Leo Fajardo (@leorw)
23794 * @since 2.5.0
23795 */
23796 if (
23797 $this->is_registered() &&
23798 FS_Api::is_api_result_entity( $result ) &&
23799 isset( $result->url )
23800 ) {
23801 $stored_local_url = trailingslashit( $this->_site->url );
23802 $stored_remote_url = trailingslashit( $result->url );
23803
23804 if ( $stored_local_url !== $stored_remote_url ) {
23805 $this->_site->url = $result->url;
23806 $this->_store_site();
23807 }
23808
23809 if ( fs_strip_url_protocol( $stored_remote_url ) !== self::get_unfiltered_site_url( null, true, true ) ) {
23810 FS_Clone_Manager::instance()->maybe_run_clone_resolution();
23811 }
23812 }
23813
23814 return $result;
23815 }
23816
23817 private $_plugin_api;
23818
23819 /**
23820 * Get plugin public API scope.
23821 *
23822 * @author Vova Feldman (@svovaf)
23823 * @since 1.0.7
23824 *
23825 * @return FS_Api
23826 */
23827 function get_api_plugin_scope() {
23828 if ( ! isset( $this->_plugin_api ) ) {
23829 $this->_plugin_api = FS_Api::instance(
23830 $this->_module_id,
23831 'plugin',
23832 $this->_plugin->id,
23833 $this->_plugin->public_key,
23834 ! $this->is_live(),
23835 false,
23836 $this->get_sdk_version()
23837 );
23838 }
23839
23840 return $this->_plugin_api;
23841 }
23842
23843 /**
23844 * Get bundle public API scope.
23845 *
23846 * @author Vova Feldman (@svovaf)
23847 * @since 2.3.1
23848 *
23849 * @return FS_Api
23850 */
23851 function get_api_bundle_scope() {
23852 return FS_Api::instance(
23853 $this->get_bundle_id(),
23854 'plugin',
23855 $this->get_bundle_id(),
23856 $this->get_bundle_public_key(),
23857 ! $this->is_live(),
23858 false,
23859 $this->get_sdk_version()
23860 );
23861 }
23862
23863 /**
23864 * Get site API scope object (fallback to public plugin scope when not registered).
23865 *
23866 * @author Vova Feldman (@svovaf)
23867 * @since 1.0.7
23868 *
23869 * @return FS_Api
23870 */
23871 function get_api_site_or_plugin_scope() {
23872 return $this->is_registered() ?
23873 $this->get_api_site_scope() :
23874 $this->get_api_plugin_scope();
23875 }
23876
23877 /**
23878 * @author Leo Fajardo (@leorw)
23879 * @since 2.2.3.1
23880 *
23881 * @param object $result
23882 */
23883 private function maybe_modify_api_curl_error_message( $result ) {
23884 if (
23885 'cUrlMissing' !== $result->error->type &&
23886 ( 'CurlException' !== $result->error->type || CURLE_COULDNT_CONNECT != $result->error->code ) &&
23887 ( 'HttpRequestFailed' !== $result->error->type || false === strpos( $result->error->message, 'cURL error ' . CURLE_COULDNT_CONNECT ) )
23888 ) {
23889 return;
23890 }
23891
23892 $result->error->message = $this->esc_html_inline( 'We use PHP cURL library for the API calls, which is a very common library and usually installed and activated out of the box. Unfortunately, cURL is not activated (or disabled) on your server.', 'curl-missing-message' ) .
23893 ' ' .
23894 $this->esc_html_inline(
23895 sprintf(
23896 'Please contact your hosting provider and ask them to whitelist %s for external connection.',
23897 implode(
23898 ', ',
23899 $this->apply_filters( 'api_domains', array(
23900 'api.freemius.com',
23901 'wp.freemius.com'
23902 ) )
23903 )
23904 ),
23905 'connectivity-whitelist'
23906 ) .
23907 ' ' .
23908 sprintf(
23909 $this->esc_html_inline( 'Once you are done, deactivate the %s and activate it again.', 'connectivity-reactivate-module' ),
23910 $this->get_module_type()
23911 );
23912 }
23913
23914 /**
23915 * Show trial promotional notice (if any trial exist).
23916 *
23917 * @author Vova Feldman (@svovaf)
23918 * @since 1.0.9
23919 *
23920 * @param FS_Plugin_Plan[] $plans
23921 */
23922 function _check_for_trial_plans( $plans ) {
23923 /**
23924 * For some reason core's do_action() flattens arrays when it has a single object item. Therefore, we need to restructure the array as expected.
23925 *
23926 * @author Vova Feldman (@svovaf)
23927 * @since 2.1.2
23928 */
23929 if ( ! is_array( $plans ) && is_object( $plans ) ) {
23930 $plans = array( $plans );
23931 }
23932
23933 if ( ! $this->is_array_instanceof( $plans, 'FS_Plugin_Plan' ) ) {
23934 $plans = array();
23935 }
23936
23937 $this->_storage->has_trial_plan = FS_Plan_Manager::instance()->has_trial_plan( $plans );
23938 }
23939
23940 /**
23941 * During trial promotion the "upgrade" submenu item turns to
23942 * "start trial" to encourage the trial. Since we want to keep
23943 * the same menu item handler and there's no robust way to
23944 * add new arguments to the menu item link's querystring,
23945 * use JavaScript to find the menu item and update the href of
23946 * the link.
23947 *
23948 * @author Vova Feldman (@svovaf)
23949 * @since 1.2.1.5
23950 */
23951 function _fix_start_trial_menu_item_url() {
23952 $template_args = array( 'id' => $this->_module_id );
23953 fs_require_template( 'add-trial-to-pricing.php', $template_args );
23954 }
23955
23956 /**
23957 * Check if module is currently in a trial promotion mode.
23958 *
23959 * @author Vova Feldman (@svovaf)
23960 * @since 1.2.2.7
23961 *
23962 * @return bool
23963 */
23964 function is_in_trial_promotion() {
23965 return $this->_admin_notices->has_sticky( 'trial_promotion' );
23966 }
23967
23968 /**
23969 * Show trial promotional notice (if any trial exist).
23970 *
23971 * @author Vova Feldman (@svovaf)
23972 * @since 1.0.9
23973 *
23974 * @return bool If trial notice added.
23975 */
23976 function _add_trial_notice() {
23977 if ( ! $this->is_user_admin() ) {
23978 return false;
23979 }
23980
23981 if ( ! $this->is_user_in_admin() ) {
23982 return false;
23983 }
23984
23985 if ( $this->_is_network_active ) {
23986 if ( fs_is_network_admin() ) {
23987 // Network level trial is disabled at the moment.
23988 return false;
23989 }
23990
23991 if ( ! $this->is_delegated_connection() ) {
23992 // Only delegated sites should support trials.
23993 return false;
23994 }
23995 }
23996
23997 // Check if trial message is already shown.
23998 if ( $this->is_in_trial_promotion() ) {
23999 add_action( 'admin_footer', array( &$this, '_fix_start_trial_menu_item_url' ) );
24000
24001 $this->_menu->add_counter_to_menu_item( 1, 'fs-trial' );
24002
24003 return false;
24004 }
24005
24006 if ( $this->is_premium() && ! WP_FS__DEV_MODE ) {
24007 // Don't show trial if running the premium code, unless running in DEV mode.
24008 return false;
24009 }
24010
24011 if ( ! $this->has_trial_plan() ) {
24012 // No plans with trial.
24013 return false;
24014 }
24015
24016 if ( ! $this->apply_filters( 'show_trial', true ) ) {
24017 // Developer explicitly asked not to show the trial promo.
24018 return false;
24019 }
24020
24021 if ( $this->is_registered() ) {
24022 // Check if trial already utilized.
24023 if ( $this->_site->is_trial_utilized() ) {
24024 return false;
24025 }
24026
24027 if ( $this->is_paying_or_trial() ) {
24028 // Don't show trial if paying or already in trial.
24029 return false;
24030 }
24031 }
24032
24033 if ( $this->is_activation_mode() || $this->is_pending_activation() ) {
24034 // If not yet opted-in/skipped, or pending activation, don't show trial.
24035 return false;
24036 }
24037
24038 $last_time_trial_promotion_shown = $this->_storage->get( 'trial_promotion_shown', false );
24039 $was_promotion_shown_before = ( false !== $last_time_trial_promotion_shown );
24040
24041 // Show promotion if never shown before and 24 hours after initial activation with FS.
24042 if ( ! $was_promotion_shown_before &&
24043 $this->_storage->install_timestamp > ( time() - $this->apply_filters( 'show_first_trial_after_n_sec', WP_FS__TIME_24_HOURS_IN_SEC ) )
24044 ) {
24045 return false;
24046 }
24047
24048 // OR if promotion was shown before, try showing it every 30 days.
24049 if ( $was_promotion_shown_before &&
24050 $this->apply_filters( 'reshow_trial_after_every_n_sec', 30 * WP_FS__TIME_24_HOURS_IN_SEC ) > time() - $last_time_trial_promotion_shown
24051 ) {
24052 return false;
24053 }
24054
24055 $trial_period = $this->_trial_days;
24056 $require_payment = $this->_is_trial_require_payment;
24057 $trial_url = $this->get_trial_url();
24058 $plans_string = strtolower( $this->get_text_inline( 'Awesome', 'awesome' ) );
24059
24060 if ( $this->is_registered() ) {
24061 // If opted-in, override trial with up to date data from API.
24062 $trial_plans = FS_Plan_Manager::instance()->get_trial_plans( $this->_plans );
24063 $trial_plans_count = count( $trial_plans );
24064
24065 if ( 0 === $trial_plans_count ) {
24066 // If there's no plans with a trial just exit.
24067 return false;
24068 }
24069
24070 /**
24071 * @var FS_Plugin_Plan $paid_plan
24072 */
24073 $paid_plan = $trial_plans[0];
24074 $require_payment = $paid_plan->is_require_subscription;
24075 $trial_period = $paid_plan->trial_period;
24076
24077 $total_paid_plans = count( $this->_plans ) - ( FS_Plan_Manager::instance()->has_free_plan( $this->_plans ) ? 1 : 0 );
24078
24079 if ( $total_paid_plans !== $trial_plans_count ) {
24080 // Not all paid plans have a trial - generate a string of those that have it.
24081 for ( $i = 0; $i < $trial_plans_count; $i ++ ) {
24082 $plans_string .= sprintf(
24083 ' <a href="%s">%s</a>',
24084 $trial_url,
24085 $trial_plans[ $i ]->title
24086 );
24087
24088 if ( $i < $trial_plans_count - 2 ) {
24089 $plans_string .= ', ';
24090 } else if ( $i == $trial_plans_count - 2 ) {
24091 $plans_string .= ' and ';
24092 }
24093 }
24094 }
24095 }
24096
24097 $message = sprintf(
24098 $this->get_text_x_inline( 'Hey', 'exclamation', 'hey' ) . '! ' . $this->get_text_inline( 'How do you like %s so far? Test all our %s premium features with a %d-day free trial.', 'trial-x-promotion-message' ),
24099 sprintf( '<b>%s</b>', $this->get_plugin_name() ),
24100 $plans_string,
24101 $trial_period
24102 );
24103
24104 // "No Credit-Card Required" or "No Commitment for N Days".
24105 $cc_string = $require_payment ?
24106 sprintf( $this->get_text_inline( 'No commitment for %s days - cancel anytime!', 'no-commitment-for-x-days' ), $trial_period ) :
24107 $this->get_text_inline( 'No credit card required', 'no-cc-required' ) . '!';
24108
24109
24110 // Start trial button.
24111 $button = ' ' . sprintf(
24112 '<a style="margin-left: 10px; vertical-align: super;" href="%s"><button class="button button-primary">%s &nbsp;&#10140;</button></a>',
24113 $trial_url,
24114 $this->get_text_x_inline( 'Start free trial', 'call to action', 'start-free-trial' )
24115 );
24116
24117 $this->_admin_notices->add_sticky(
24118 $this->apply_filters( 'trial_promotion_message', "{$message} {$cc_string} {$button}" ),
24119 'trial_promotion',
24120 '',
24121 'promotion'
24122 );
24123
24124 $this->_storage->trial_promotion_shown = WP_FS__SCRIPT_START_TIME;
24125
24126 return true;
24127 }
24128
24129 /**
24130 * Lets users/customers know that the product has an affiliate program.
24131 *
24132 * @author Leo Fajardo (@leorw)
24133 * @since 1.2.2.11
24134 *
24135 * @return bool Returns true if the notice has been added.
24136 */
24137 function _add_affiliate_program_notice() {
24138 if ( ! $this->is_user_admin() ) {
24139 return false;
24140 }
24141
24142 if ( ! $this->is_user_in_admin() ) {
24143 return false;
24144 }
24145
24146 // Check if the notice is already shown.
24147 if ( $this->_admin_notices->has_sticky( 'affiliate_program' ) ) {
24148 return false;
24149 }
24150
24151 if (
24152 // Product has no affiliate program.
24153 ! $this->has_affiliate_program() ||
24154 // User has applied for an affiliate account.
24155 ! empty( $this->_storage->affiliate_application_data )
24156 ) {
24157 return false;
24158 }
24159
24160 if ( ! $this->apply_filters( 'show_affiliate_program_notice', true ) ) {
24161 // Developer explicitly asked not to show the notice about the affiliate program.
24162 return false;
24163 }
24164
24165 if ( $this->is_activation_mode() || $this->is_pending_activation() ) {
24166 // If not yet opted in/skipped, or pending activation, don't show the notice.
24167 return false;
24168 }
24169
24170 $last_time_notice_was_shown = $this->_storage->get( 'affiliate_program_notice_shown', false );
24171 $was_notice_shown_before = ( false !== $last_time_notice_was_shown );
24172
24173 /**
24174 * Do not show the notice if it was already shown before or less than 30 days have passed since the initial
24175 * activation with FS.
24176 */
24177 if ( $was_notice_shown_before ||
24178 $this->_storage->install_timestamp > ( time() - ( WP_FS__TIME_24_HOURS_IN_SEC * 30 ) )
24179 ) {
24180 return false;
24181 }
24182
24183 if ( ! $this->is_paying() &&
24184 FS_Plugin::AFFILIATE_MODERATION_CUSTOMERS == $this->_plugin->affiliate_moderation
24185 ) {
24186 // If the user is not a customer and the affiliate program is only for customers, don't show the notice.
24187 return false;
24188 }
24189
24190 $message = sprintf(
24191 $this->get_text_inline( 'Hey there, did you know that %s has an affiliate program? If you like the %s you can become our ambassador and earn some cash!', 'become-an-ambassador-admin-notice' ),
24192 sprintf( '<strong>%s</strong>', $this->get_plugin_name() ),
24193 $this->get_module_label( true )
24194 );
24195
24196 // HTML code for the "Learn more..." button.
24197 $button = ' ' . sprintf(
24198 '<a style="display: block; margin-top: 10px;" href="%s"><button class="button button-primary">%s &nbsp;&#10140;</button></a>',
24199 $this->_get_admin_page_url( 'affiliation' ),
24200 $this->get_text_inline( 'Learn more', 'learn-more' ) . '...'
24201 );
24202
24203 $this->_admin_notices->add_sticky(
24204 $this->apply_filters( 'affiliate_program_notice', "{$message} {$button}" ),
24205 'affiliate_program',
24206 '',
24207 'promotion'
24208 );
24209
24210 $this->_storage->affiliate_program_notice_shown = WP_FS__SCRIPT_START_TIME;
24211
24212 return true;
24213 }
24214
24215 /**
24216 * @author Vova Feldman (@svovaf)
24217 * @since 1.2.1.5
24218 */
24219 function _enqueue_common_css() {
24220 if ( $this->has_paid_plan() && ! $this->is_paying() ) {
24221 // Add basic CSS for admin-notices and menu-item colors.
24222 fs_enqueue_local_style( 'fs_common', '/admin/common.css' );
24223 }
24224 }
24225
24226 /**
24227 * @author Leo Fajardo (@leorw)
24228 * @since 1.2.2
24229 */
24230 function _show_theme_activation_optin_dialog() {
24231 fs_enqueue_local_style( 'fs_connect', '/admin/connect.css' );
24232
24233 add_action( 'admin_footer', array( &$this, '_add_fs_theme_activation_dialog' ) );
24234 }
24235
24236 /**
24237 * @author Leo Fajardo (@leorw)
24238 * @since 1.2.2
24239 */
24240 function _add_fs_theme_activation_dialog() {
24241 global $pagenow;
24242
24243 if ( 'themes.php' !== $pagenow ) {
24244 return;
24245 }
24246
24247 $vars = array( 'id' => $this->_module_id );
24248 fs_require_once_template( 'connect.php', $vars );
24249 }
24250
24251 /* Action Links
24252 ------------------------------------------------------------------------------------------------------------------*/
24253 private $_action_links_hooked = false;
24254 private $_action_links = array();
24255
24256 /**
24257 * Hook to plugin action links filter.
24258 *
24259 * @author Vova Feldman (@svovaf)
24260 * @since 1.0.0
24261 */
24262 private function hook_plugin_action_links() {
24263 $this->_logger->entrance();
24264
24265 $this->_action_links_hooked = true;
24266
24267 $this->_logger->log( 'Adding action links hooks.' );
24268
24269 // Add action link to settings page.
24270 add_filter( 'plugin_action_links_' . $this->_plugin_basename, array(
24271 &$this,
24272 '_modify_plugin_action_links_hook'
24273 ), WP_FS__DEFAULT_PRIORITY, 2 );
24274 add_filter( 'network_admin_plugin_action_links_' . $this->_plugin_basename, array(
24275 &$this,
24276 '_modify_plugin_action_links_hook'
24277 ), WP_FS__DEFAULT_PRIORITY, 2 );
24278 }
24279
24280 /**
24281 * Add plugin action link.
24282 *
24283 * @author Vova Feldman (@svovaf)
24284 * @since 1.0.0
24285 *
24286 * @param $label
24287 * @param $url
24288 * @param bool $external
24289 * @param int $priority
24290 * @param bool $key
24291 */
24292 function add_plugin_action_link( $label, $url, $external = false, $priority = WP_FS__DEFAULT_PRIORITY, $key = false ) {
24293 $this->_logger->entrance();
24294
24295 if ( ! isset( $this->_action_links[ $priority ] ) ) {
24296 $this->_action_links[ $priority ] = array();
24297 }
24298
24299 if ( false === $key ) {
24300 $key = preg_replace( "/[^A-Za-z0-9 ]/", '', strtolower( $label ) );
24301 }
24302
24303 $this->_action_links[ $priority ][] = array(
24304 'label' => $label,
24305 'href' => $url,
24306 'key' => $key,
24307 'external' => $external
24308 );
24309 }
24310
24311 /**
24312 * Adds Upgrade and Add-Ons links to the main Plugins page link actions collection.
24313 *
24314 * @author Vova Feldman (@svovaf)
24315 * @since 1.0.0
24316 */
24317 function _add_upgrade_action_link() {
24318 $this->_logger->entrance();
24319
24320 $is_activation_mode = $this->is_activation_mode();
24321
24322 $add_action_links = $this->should_add_submenu_or_action_links( $is_activation_mode );
24323
24324 /**
24325 * The following logic is based on the logic in `add_submenu_items()` method that decides when the "Upgrade"
24326 * and "Add-Ons" menus should be added.
24327 *
24328 * @author Leo Fajardo (@leorw)
24329 * @since 2.3.0
24330 */
24331 $add_upgrade_link = (
24332 $add_action_links ||
24333 ( $is_activation_mode && $this->is_only_premium() )
24334 ) && ! WP_FS__DEMO_MODE && ( ! $this->is_whitelabeled() );
24335
24336 $add_addons_link = ( $add_action_links && $this->has_addons() );
24337
24338 if ( ! $add_upgrade_link && ! $add_addons_link ) {
24339 return;
24340 }
24341
24342 if (
24343 $add_upgrade_link &&
24344 $this->is_pricing_page_visible() &&
24345 $this->is_submenu_item_visible( 'pricing' )
24346 ) {
24347 $this->add_plugin_action_link(
24348 $this->get_text_inline( 'Upgrade', 'upgrade' ),
24349 $this->get_upgrade_url(),
24350 false,
24351 7,
24352 'upgrade'
24353 );
24354 }
24355
24356 if (
24357 $add_addons_link &&
24358 $this->has_addons() &&
24359 $this->is_submenu_item_visible( 'addons' )
24360 ) {
24361 $this->add_plugin_action_link(
24362 $this->get_text_inline( 'Add-Ons', 'add-ons' ),
24363 $this->_get_admin_page_url( 'addons' ),
24364 false,
24365 9,
24366 'addons'
24367 );
24368 }
24369 }
24370
24371 /**
24372 * Adds "Activate License" or "Change License" link to the main Plugins page link actions collection.
24373 *
24374 * @author Leo Fajardo (@leorw)
24375 * @since 1.1.9
24376 */
24377 function _add_license_action_link() {
24378 $this->_logger->entrance();
24379
24380 if ( ! self::is_ajax() ) {
24381 // Inject license activation dialog UI and client side code.
24382 add_action( 'admin_footer', array( &$this, '_add_license_activation_dialog_box' ) );
24383 }
24384
24385 $link_text = $this->is_free_plan() ?
24386 $this->get_text_inline( 'Activate License', 'activate-license' ) :
24387 $this->get_text_inline( 'Change License', 'change-license' );
24388
24389 $this->add_plugin_action_link(
24390 $link_text,
24391 '#',
24392 false,
24393 11,
24394 ( 'activate-license ' . $this->get_unique_affix() )
24395 );
24396 }
24397
24398 /**
24399 * @author Leo Fajardo (@leorw)
24400 * @since 2.0.2
24401 */
24402 function _add_premium_version_upgrade_selection_action() {
24403 $this->_logger->entrance();
24404
24405 if ( ! self::is_ajax() ) {
24406 add_action( 'admin_footer', array( &$this, '_add_premium_version_upgrade_selection_dialog_box' ) );
24407 }
24408 }
24409
24410 /**
24411 * Adds "Opt In" or "Opt Out" link to the main "Plugins" page link actions collection.
24412 *
24413 * @author Leo Fajardo (@leorw)
24414 * @since 1.2.1.5
24415 */
24416 function _add_tracking_links() {
24417 if ( ! current_user_can( 'manage_options' ) ) {
24418 return;
24419 }
24420
24421 $this->_logger->entrance();
24422
24423 if ( $this->is_only_premium() && $this->is_free_plan() ) {
24424 // Don't add tracking links for premium-only products that were opted-in by relation (add-on or a parent product) before activating any license.
24425 return;
24426 }
24427
24428 if (
24429 $this->is_addon() &&
24430 ! $this->is_only_premium()
24431 ) {
24432 $parent = $this->get_parent_instance();
24433
24434 if ( is_object( $parent ) && $parent->is_anonymous() ) {
24435 return;
24436 }
24437 }
24438
24439 if ( fs_is_network_admin() ) {
24440 if ( ! $this->_is_network_active ) {
24441 // Don't add tracking links when browsing the network WP Admin and the plugin is not network active.
24442 return;
24443 } else if ( $this->is_network_delegated_connection() ) {
24444 // Don't add tracking links when browsing the network WP Admin and the activation has been delegated to site admins.
24445 return;
24446 }
24447 } else {
24448 if ( $this->_is_network_active && ! $this->is_delegated_connection() ) {
24449 // Don't add tracking links when browsing the sub-site WP Admin, the plugin is network active, and the connection was not delegated.
24450 return;
24451 }
24452 }
24453
24454 if ( fs_request_is_action_secure( $this->get_unique_affix() . '_reconnect' ) ) {
24455 if ( ! $this->is_registered() && $this->is_anonymous() ) {
24456 $this->connect_again();
24457
24458 return;
24459 }
24460 }
24461
24462 if ( ( $this->is_plugin() && ! self::is_plugins_page() ) ||
24463 ( $this->is_theme() && ! self::is_themes_page() )
24464 ) {
24465 // Only show tracking links on the plugins and themes pages.
24466 return;
24467 }
24468
24469 if (
24470 $this->is_activation_mode() &&
24471 $this->is_premium() &&
24472 ! $this->is_registered()
24473 ) {
24474 // If not yet registered and running the premium code base, a license activation link will already be shown.
24475 return;
24476 }
24477
24478 if ( $this->is_registered() && $this->is_tracking_allowed() ) {
24479 if ( ! $this->is_premium() && ! $this->is_enable_anonymous() ) {
24480 // If opted in and tracking is allowed, don't allow to opt out if not premium and anonymous mode is disabled.
24481 return;
24482 }
24483 }
24484
24485 if ( $this->add_ajax_action( 'toggle_permission_tracking', array( &$this, '_toggle_permission_tracking_callback' ) ) ) {
24486 return;
24487 }
24488
24489 $link_text_id = '';
24490 $url = '#';
24491
24492 if ( $this->is_registered( true ) ) {
24493 if ( $this->is_registered() && $this->is_tracking_allowed() ) {
24494 $link_text_id = $this->get_text_inline( 'Opt Out', 'opt-out' );
24495 } else {
24496 $link_text_id = $this->get_text_inline( 'Opt In', 'opt-in' );
24497 }
24498 } else if ( $this->is_anonymous() || $this->is_activation_mode() ) {
24499 /**
24500 * Show opt-in link only if skipped or in activation mode.
24501 */
24502 $link_text_id = $this->get_text_inline( 'Opt In', 'opt-in' );
24503
24504 $params = ! $this->is_anonymous() ?
24505 array() :
24506 array(
24507 'nonce' => wp_create_nonce( $this->get_unique_affix() . '_reconnect' ),
24508 'fs_action' => ( $this->get_unique_affix() . '_reconnect' ),
24509 );
24510
24511 $url = $this->get_activation_url( $params );
24512 }
24513
24514 add_action( 'admin_footer', array( &$this, '_add_optout_dialog' ) );
24515
24516 if ( ! empty( $link_text_id ) && $this->is_plugin() && self::is_plugins_page() ) {
24517 $this->add_plugin_action_link(
24518 $link_text_id,
24519 $url,
24520 false,
24521 13,
24522 "opt-in-or-opt-out {$this->_slug}"
24523 );
24524 }
24525 }
24526
24527 /**
24528 * Get the URL of the page that should be loaded right after the plugin activation.
24529 *
24530 * @author Vova Feldman (@svovaf)
24531 * @since 1.1.7.4
24532 *
24533 * @return string
24534 */
24535 function get_after_plugin_activation_redirect_url() {
24536 $url = false;
24537
24538 if ( ! $this->is_addon() || ! $this->has_free_plan() ) {
24539 $first_time_path = $this->_menu->get_first_time_path(
24540 fs_is_network_admin() && $this->_is_network_active
24541 );
24542
24543 if ( $this->is_activation_mode() ) {
24544 $url = $this->get_activation_url();
24545 } else if ( ! empty( $first_time_path ) ) {
24546 $url = $first_time_path;
24547 } else {
24548 $page = '';
24549 if ( ! empty( $this->_dynamically_added_top_level_page_hook_name ) ) {
24550 if ( $this->is_network_registered() ) {
24551 $page = 'account';
24552 } else if ( $this->is_pending_activation() || $this->is_network_anonymous() ) {
24553 $this->maybe_set_slug_and_network_menu_exists_flag();
24554 }
24555 }
24556
24557 $url = $this->_get_admin_page_url( $page );
24558 }
24559 } else {
24560 $plugin_fs = false;
24561
24562 if ( $this->is_parent_plugin_installed() ) {
24563 $plugin_fs = self::get_parent_instance();
24564 }
24565
24566 if ( is_object( $plugin_fs ) ) {
24567 if ( ! $plugin_fs->is_registered() ) {
24568 // Forward to parent plugin connect when parent not registered.
24569 $url = $plugin_fs->get_activation_url();
24570 } else {
24571 // Forward to account page.
24572 $url = $plugin_fs->_get_admin_page_url( 'account' );
24573 }
24574 }
24575 }
24576
24577 return $url;
24578 }
24579
24580 /**
24581 * Forward page to activation page.
24582 *
24583 * @author Vova Feldman (@svovaf)
24584 * @since 1.0.3
24585 */
24586 function _redirect_on_activation_hook() {
24587 if ( $this->apply_filters( 'redirect_on_activation', true ) ) {
24588 $url = $this->get_after_plugin_activation_redirect_url();
24589
24590 if ( is_string( $url ) ) {
24591 fs_redirect( $url );
24592 }
24593 }
24594 }
24595
24596 /**
24597 * Modify plugin's page action links collection.
24598 *
24599 * @author Vova Feldman (@svovaf)
24600 * @since 1.0.0
24601 *
24602 * @param array $links
24603 * @param $file
24604 *
24605 * @return array
24606 */
24607 function _modify_plugin_action_links_hook( $links, $file ) {
24608 $this->_logger->entrance();
24609
24610 $passed_deactivate = false;
24611 $deactivate_link = '';
24612 $before_deactivate = array();
24613 $after_deactivate = array();
24614 foreach ( $links as $key => $link ) {
24615 if ( 'deactivate' === $key ) {
24616 $deactivate_link = $link;
24617 $passed_deactivate = true;
24618 continue;
24619 }
24620
24621 if ( ! $passed_deactivate ) {
24622 $before_deactivate[ $key ] = $link;
24623 } else {
24624 $after_deactivate[ $key ] = $link;
24625 }
24626 }
24627
24628 ksort( $this->_action_links );
24629
24630 foreach ( $this->_action_links as $new_links ) {
24631 foreach ( $new_links as $link ) {
24632 $before_deactivate[ $link['key'] ] = '<a href="' . $link['href'] . '"' . ( $link['external'] ? ' target="_blank" rel="noopener"' : '' ) . '>' . $link['label'] . '</a>';
24633 }
24634 }
24635
24636 if ( ! empty( $deactivate_link ) ) {
24637 /**
24638 * This HTML element is used to identify the correct plugin when attaching an event to its Deactivate link.
24639 *
24640 * @since 1.2.1.6 Always show the deactivation feedback form since we added automatic free version deactivation upon premium code activation.
24641 */
24642 $deactivate_link .= '<i class="fs-module-id" data-module-id="' . $this->_module_id . '"></i>';
24643
24644 // Append deactivation link.
24645 $before_deactivate['deactivate'] = $deactivate_link;
24646 }
24647
24648 return array_merge( $before_deactivate, $after_deactivate );
24649 }
24650
24651 /**
24652 * Adds admin message.
24653 *
24654 * @author Vova Feldman (@svovaf)
24655 * @since 1.0.4
24656 *
24657 * @param string $message
24658 * @param string $title
24659 * @param string $type
24660 */
24661 function add_admin_message( $message, $title = '', $type = 'success' ) {
24662 $this->_admin_notices->add( $message, $title, $type );
24663 }
24664
24665 /**
24666 * Adds sticky admin message.
24667 *
24668 * @author Vova Feldman (@svovaf)
24669 * @since 1.1.0
24670 *
24671 * @param string $message
24672 * @param string $id
24673 * @param string $title
24674 * @param string $type
24675 */
24676 function add_sticky_admin_message( $message, $id, $title = '', $type = 'success' ) {
24677 $this->_admin_notices->add_sticky( $message, $id, $title, $type );
24678 }
24679
24680 /**
24681 * Check if the paid version of the module is installed.
24682 *
24683 * @author Vova Feldman (@svovaf)
24684 * @since 2.2.0
24685 *
24686 * @return bool
24687 */
24688 private function is_premium_version_installed() {
24689 $premium_plugin_basename = $this->premium_plugin_basename();
24690
24691 if ( $this->is_theme() ) {
24692 return $this->can_activate_theme( $this->get_premium_slug() );
24693 }
24694
24695 return file_exists( fs_normalize_path( WP_PLUGIN_DIR . '/' . $premium_plugin_basename ) );
24696 }
24697
24698 /**
24699 * Helper function that returns the final steps for the upgrade completion.
24700 *
24701 * If the module is already running the premium code, returns an empty string.
24702 *
24703 * @author Vova Feldman (@svovaf)
24704 * @since 1.2.1
24705 *
24706 * @param string $plan_title
24707 *
24708 * @return string
24709 */
24710 private function get_complete_upgrade_instructions( $plan_title = '' ) {
24711 $this->_logger->entrance();
24712
24713 $activate_license_string = $this->get_license_network_activation_notice();
24714
24715 if ( ! $this->has_premium_version() || $this->is_premium() ) {
24716 return '' . $activate_license_string;
24717 }
24718
24719 if ( empty( $plan_title ) ) {
24720 $plan_title = $this->get_plan_title();
24721 }
24722
24723 if ( $this->is_premium_version_installed() ) {
24724 /**
24725 * If the premium version is already installed, instead of showing the installation instructions,
24726 * tell the current user to activate it.
24727 *
24728 * @author Leo Fajardo (@leorw)
24729 * @since 2.2.1
24730 */
24731 $premium_theme_slug_or_plugin_basename = $this->is_theme() ?
24732 $this->get_premium_slug() :
24733 $this->premium_plugin_basename();
24734
24735 return sprintf(
24736 /* translators: %1$s: Product title; %2$s: Plan title */
24737 $this->get_text_inline( ' The paid version of %1$s is already installed. Please activate it to start benefiting the %2$s features. %3$s', 'activate-premium-version' ),
24738 sprintf( '<em>%s</em>', esc_html( $this->get_plugin_title() ) ),
24739 $plan_title,
24740 sprintf(
24741 '<a style="margin-left: 10px;" href="%s"><button class="button button-primary">%s</button></a>',
24742 ( $this->is_theme() ?
24743 wp_nonce_url( 'themes.php?action=activate&amp;stylesheet=' . $premium_theme_slug_or_plugin_basename, 'switch-theme_' . $premium_theme_slug_or_plugin_basename ) :
24744 wp_nonce_url( 'plugins.php?action=activate&amp;plugin=' . $premium_theme_slug_or_plugin_basename, 'activate-plugin_' . $premium_theme_slug_or_plugin_basename ) ),
24745 esc_html( sprintf(
24746 /* translators: %s: Plan title */
24747 $this->get_text_inline( 'Activate %s features', 'activate-x-features' ),
24748 $plan_title
24749 ) )
24750 )
24751 );
24752 } else {
24753 // @since 1.2.1.5 The free version is auto deactivated.
24754 $deactivation_step = version_compare( $this->version, '1.2.1.5', '<' ) ?
24755 ( '<li>' . $this->esc_html_inline( 'Deactivate the free version', 'deactivate-free-version' ) . '.</li>' ) :
24756 '';
24757
24758 return sprintf(
24759 ' %s: <ol><li>%s.</li>%s<li>%s (<a href="%s" target="_blank" rel="noopener">%s</a>).</li></ol>',
24760 $this->get_text_inline( 'Please follow these steps to complete the upgrade', 'follow-steps-to-complete-upgrade' ),
24761 ( empty( $activate_license_string ) ? '' : $activate_license_string . '</li><li>' ) .
24762 $this->get_latest_download_link( sprintf(
24763 /* translators: %s: Plan title */
24764 $this->get_text_inline( 'Download the latest %s version', 'download-latest-x-version' ),
24765 $plan_title
24766 ) ),
24767 $deactivation_step,
24768 $this->get_text_inline( 'Upload and activate the downloaded version', 'upload-and-activate' ),
24769 $this->apply_filters( 'upload_and_install_video_url', '//bit.ly/wp-' . $this->_module_type . '-upload' ),
24770 $this->get_text_inline( 'How to upload and activate?', 'howto-upload-activate' )
24771 );
24772 }
24773 }
24774
24775 /**
24776 * @author Leo Fajardo (@leorw)
24777 * @since 2.5.3
24778 *
24779 * @param string $message_before_the_instructions
24780 * @param string $message_id
24781 * @param string $plan_title
24782 */
24783 private function add_complete_upgrade_instructions_notice(
24784 $message_before_the_instructions,
24785 $message_id,
24786 $plan_title = ''
24787 ) {
24788 $this->_admin_notices->add_sticky(
24789 $message_before_the_instructions .
24790 $this->get_complete_upgrade_instructions( $plan_title ),
24791 $message_id,
24792 $this->get_text_x_inline( 'Yee-haw', 'interjection expressing joy or exuberance', 'yee-haw' ) . '!'
24793 );
24794 }
24795
24796 /**
24797 * @author Leo Fajardo (@leorw)
24798 * @since 2.5.3
24799 *
24800 * @param bool $is_upgrade
24801 */
24802 private function add_after_plan_activation_or_upgrade_instructions_notice( $is_upgrade = true ) {
24803 $this->add_complete_upgrade_instructions_notice(
24804 $is_upgrade ?
24805 $this->get_text_inline( 'Your plan was successfully upgraded.', 'plan-upgraded-message' ) :
24806 $this->get_text_inline( 'Your plan was successfully activated.', 'plan-activated-message' ),
24807 'plan_upgraded'
24808 );
24809 }
24810
24811 /**
24812 * @author Leo Fajardo (@leorw)
24813 * @since 2.1.0
24814 *
24815 * @param string $url
24816 * @param array $request
24817 */
24818 private static function enrich_request_for_debug( &$url, &$request ) {
24819 if ( WP_FS__DEBUG_SDK || isset( $_COOKIE['XDEBUG_SESSION'] ) ) {
24820 $url = add_query_arg( 'XDEBUG_SESSION_START', rand( 0, 9999999 ), $url );
24821 $url = add_query_arg( 'XDEBUG_SESSION', 'PHPSTORM', $url );
24822
24823 $request['cookies'] = array(
24824 new WP_Http_Cookie( array(
24825 'name' => 'XDEBUG_SESSION',
24826 'value' => 'PHPSTORM',
24827 ) )
24828 );
24829 }
24830 }
24831
24832 /**
24833 * @author Leo Fajardo (@leorw)
24834 * @since 2.1.0
24835 *
24836 * @param string $url
24837 * @param array $request
24838 * @param int $success_cache_expiration
24839 * @param int $failure_cache_expiration
24840 * @param bool $maybe_enrich_request_for_debug
24841 *
24842 * @return WP_Error|array
24843 */
24844 static function safe_remote_post(
24845 &$url,
24846 $request,
24847 $success_cache_expiration = 0,
24848 $failure_cache_expiration = 0,
24849 $maybe_enrich_request_for_debug = true
24850 ) {
24851 $should_cache = ($success_cache_expiration + $failure_cache_expiration > 0);
24852
24853 $cache_key = $should_cache ? md5( fs_strip_url_protocol($url) . json_encode( $request ) ) : false;
24854
24855 $response = (!WP_FS__DEBUG_SDK && ( false !== $cache_key )) ?
24856 get_transient( $cache_key ) :
24857 false;
24858
24859 if ( false === $response ) {
24860 if ( $maybe_enrich_request_for_debug ) {
24861 self::enrich_request_for_debug( $url, $request );
24862 }
24863
24864 if ( ! isset( $request['method'] ) ) {
24865 $request['method'] = 'POST';
24866 }
24867
24868 $response = FS_Api::remote_request( $url, $request );
24869
24870 if (
24871 'https://' === substr( $url, 0, 8 ) &&
24872 FS_Api::is_ssl_error_response( $response )
24873 ) {
24874 // Failed due to old version of cURL or Open SSL (SSLv3 is not supported by CloudFlare).
24875 $url = 'http://' . substr( $url, 8 );
24876
24877 $request['timeout'] = 15;
24878 $response = FS_Api::remote_request( $url, $request );
24879 }
24880
24881 if ( false !== $cache_key ) {
24882 set_transient(
24883 $cache_key,
24884 $response,
24885 ( ( $response instanceof WP_Error ) ?
24886 $failure_cache_expiration :
24887 $success_cache_expiration )
24888 );
24889 }
24890 }
24891
24892 return $response;
24893 }
24894
24895 /**
24896 * This method is used to enrich the after upgrade notice instructions when the upgraded
24897 * license cannot be activated network wide (license quota isn't large enough).
24898 *
24899 * @author Vova Feldman (@svovaf)
24900 * @since 2.0.0
24901 *
24902 * @return string
24903 */
24904 private function get_license_network_activation_notice() {
24905 if ( ! $this->_is_network_active ) {
24906 // Module isn't network level activated.
24907 return '';
24908 }
24909
24910 if ( ! fs_is_network_admin() ) {
24911 // Not network level admin.
24912 return '';
24913 }
24914
24915 if ( get_blog_count() == 1 ) {
24916 // There's only a single site in the network so if there's a context license it was already activated.
24917 return '';
24918 }
24919
24920 if ( ! is_object( $this->_license ) ) {
24921 // No context license.
24922 return '';
24923 }
24924
24925 if ( $this->_license->is_single_site() && 0 < $this->_license->activated ) {
24926 // License was already utilized (this is not 100% the case if all the network is localhost sites and the license can be utilized on unlimited localhost sites).
24927 return '';
24928 }
24929
24930 if ( $this->can_activate_license_on_network( $this->_license ) ) {
24931 // License can be activated on all the network, so probably, the license is already activate on all the network (that's how the after upgrade sync works).
24932 return '';
24933 }
24934
24935 return sprintf(
24936 $this->get_text_inline( '%sClick here%s to choose the sites where you\'d like to activate the license on.', 'network-choose-sites-for-license' ),
24937 '<a href="' . $this->get_account_url( false, array( 'activate_license' => 'true' ) ) . '">',
24938 '</a>'
24939 );
24940 }
24941
24942 /**
24943 * @author Vova Feldman (@svovaf)
24944 * @since 1.2.1.7
24945 *
24946 * @param string $key
24947 *
24948 * @return string
24949 */
24950 function get_text( $key ) {
24951 return fs_text( $key, $this->_slug );
24952 }
24953
24954 /**
24955 * @author Vova Feldman (@svovaf)
24956 * @since 1.2.3
24957 *
24958 * @param string $text Translatable string.
24959 * @param string $key String key for overrides.
24960 *
24961 * @return string
24962 */
24963 function get_text_inline( $text, $key = '' ) {
24964 return _fs_text_inline( $text, $key, $this->_slug );
24965 }
24966
24967 /**
24968 * @author Vova Feldman (@svovaf)
24969 * @since 1.2.3
24970 *
24971 * @param string $text Translatable string.
24972 * @param string $context Context information for the translators.
24973 * @param string $key String key for overrides.
24974 *
24975 * @return string
24976 */
24977 function get_text_x_inline( $text, $context, $key ) {
24978 return _fs_text_x_inline( $text, $context, $key, $this->_slug );
24979 }
24980
24981 /**
24982 * @author Vova Feldman (@svovaf)
24983 * @since 1.2.3
24984 *
24985 * @param string $text Translatable string.
24986 * @param string $key String key for overrides.
24987 *
24988 * @return string
24989 */
24990 function esc_html_inline( $text, $key ) {
24991 return esc_html( _fs_text_inline( $text, $key, $this->_slug ) );
24992 }
24993
24994 #----------------------------------------------------------------------------------
24995 #region Versioning
24996 #----------------------------------------------------------------------------------
24997
24998 /**
24999 * Check if Freemius in SDK upgrade mode.
25000 *
25001 * @author Vova Feldman (@svovaf)
25002 * @since 1.0.9
25003 *
25004 * @return bool
25005 */
25006 function is_sdk_upgrade_mode() {
25007 return isset( $this->_storage->sdk_upgrade_mode ) ?
25008 $this->_storage->sdk_upgrade_mode :
25009 false;
25010 }
25011
25012 /**
25013 * Turn SDK upgrade mode off.
25014 *
25015 * @author Vova Feldman (@svovaf)
25016 * @since 1.0.9
25017 */
25018 function set_sdk_upgrade_complete() {
25019 $this->_storage->sdk_upgrade_mode = false;
25020 }
25021
25022 /**
25023 * Check if plugin upgrade mode.
25024 *
25025 * @author Vova Feldman (@svovaf)
25026 * @since 1.0.9
25027 *
25028 * @return bool
25029 */
25030 function is_plugin_upgrade_mode() {
25031 return isset( $this->_storage->plugin_upgrade_mode ) ?
25032 $this->_storage->plugin_upgrade_mode :
25033 false;
25034 }
25035
25036 /**
25037 * Turn plugin upgrade mode off.
25038 *
25039 * @author Vova Feldman (@svovaf)
25040 * @since 1.0.9
25041 */
25042 function set_plugin_upgrade_complete() {
25043 $this->_storage->plugin_upgrade_mode = false;
25044
25045 $license_migration = ! empty( $this->_storage->license_migration ) ?
25046 $this->_storage->license_migration :
25047 array();
25048
25049 $license_migration['is_migrating'] = false;
25050
25051 $this->_storage->license_migration = $license_migration;
25052 }
25053
25054 #endregion
25055
25056 #----------------------------------------------------------------------------------
25057 #region Permissions
25058 #----------------------------------------------------------------------------------
25059
25060 /**
25061 * Check if specific permission requested.
25062 *
25063 * @author Vova Feldman (@svovaf)
25064 * @since 1.1.6
25065 *
25066 * @param string $permission
25067 *
25068 * @return bool
25069 */
25070 function is_permission_requested( $permission ) {
25071 return isset( $this->_permissions[ $permission ] ) && ( true === $this->_permissions[ $permission ] );
25072 }
25073
25074 #endregion
25075
25076 #----------------------------------------------------------------------------------
25077 #region Auto Activation
25078 #----------------------------------------------------------------------------------
25079
25080 /**
25081 * Hints the SDK if running an auto-installation.
25082 *
25083 * @var bool
25084 */
25085 private $_isAutoInstall = false;
25086
25087 /**
25088 * After upgrade callback to install and auto activate a plugin.
25089 * This code will only be executed on explicit request from the user,
25090 * following the practice Jetpack are using with their theme installations.
25091 *
25092 * @link https://make.wordpress.org/plugins/2017/03/16/clarification-of-guideline-8-executable-code-and-installs/
25093 *
25094 * @author Vova Feldman (@svovaf)
25095 * @since 1.2.1.7
25096 */
25097 function _install_premium_version_ajax_action() {
25098 $this->_logger->entrance();
25099
25100 $this->check_ajax_referer( 'install_premium_version' );
25101
25102 if ( ! $this->is_registered() ) {
25103 // Not registered.
25104 self::shoot_ajax_failure( array(
25105 'message' => $this->get_text_inline( 'Auto installation only works for opted-in users.', 'auto-install-error-not-opted-in' ),
25106 'code' => 'premium_installed',
25107 ) );
25108 }
25109
25110 $plugin_id = fs_request_get( 'target_module_id', $this->get_id() );
25111
25112 if ( ! FS_Plugin::is_valid_id( $plugin_id ) ) {
25113 // Invalid ID.
25114 self::shoot_ajax_failure( array(
25115 'message' => $this->get_text_inline( 'Invalid module ID.', 'auto-install-error-invalid-id' ),
25116 'code' => 'invalid_module_id',
25117 ) );
25118 }
25119
25120 if ( $plugin_id == $this->get_id() ) {
25121 if ( $this->is_premium() ) {
25122 // Already using the premium code version.
25123 self::shoot_ajax_failure( array(
25124 'message' => $this->get_text_inline( 'Premium version already active.', 'auto-install-error-premium-activated' ),
25125 'code' => 'premium_installed',
25126 ) );
25127 }
25128 if ( ! $this->can_use_premium_code() ) {
25129 // Don't have access to the premium code.
25130 self::shoot_ajax_failure( array(
25131 'message' => $this->get_text_inline( 'You do not have a valid license to access the premium version.', 'auto-install-error-invalid-license' ),
25132 'code' => 'invalid_license',
25133 ) );
25134 }
25135 if ( ! $this->has_release_on_freemius() ) {
25136 // Plugin is a serviceware, no premium code version.
25137 self::shoot_ajax_failure( array(
25138 'message' => $this->get_text_inline( 'Plugin is a "Serviceware" which means it does not have a premium code version.', 'auto-install-error-serviceware' ),
25139 'code' => 'premium_version_missing',
25140 ) );
25141 }
25142 } else {
25143 $addon = $this->get_addon( $plugin_id );
25144
25145 if ( ! is_object( $addon ) ) {
25146 // Invalid add-on ID.
25147 self::shoot_ajax_failure( array(
25148 'message' => $this->get_text_inline( 'Invalid module ID.', 'auto-install-error-invalid-id' ),
25149 'code' => 'invalid_module_id',
25150 ) );
25151 }
25152
25153 if ( $this->is_addon_activated( $plugin_id, true ) ) {
25154 // Premium add-on version is already activated.
25155 self::shoot_ajax_failure( array(
25156 'message' => $this->get_text_inline( 'Premium add-on version already installed.', 'auto-install-error-premium-addon-activated' ),
25157 'code' => 'premium_installed',
25158 ) );
25159 }
25160 }
25161
25162 $this->_isAutoInstall = true;
25163
25164 // Try to install and activate.
25165 $updater = FS_Plugin_Updater::instance( $this );
25166 $result = $updater->install_and_activate_plugin( $plugin_id );
25167
25168 if ( is_array( $result ) && ! empty( $result['message'] ) ) {
25169 self::shoot_ajax_failure( array(
25170 'message' => $result['message'],
25171 'code' => $result['code'],
25172 ) );
25173 }
25174
25175 self::shoot_ajax_success( $result );
25176 }
25177
25178 /**
25179 * Displays module activation dialog box after a successful upgrade
25180 * where the user explicitly requested to auto download and install
25181 * the premium version.
25182 *
25183 * @author Vova Feldman (@svovaf)
25184 * @since 1.2.1.7
25185 */
25186 function _add_auto_installation_dialog_box() {
25187 $this->_logger->entrance();
25188
25189 if ( ! $this->is_registered() ) {
25190 // Not registered.
25191 return;
25192 }
25193
25194 $plugin_id = fs_request_get( 'plugin_id', $this->get_id() );
25195
25196 if ( ! FS_Plugin::is_valid_id( $plugin_id ) ) {
25197 // Invalid module ID.
25198 return;
25199 }
25200
25201 if ( $plugin_id == $this->get_id() ) {
25202 if ( $this->is_premium() ) {
25203 // Already using the premium code version.
25204 return;
25205 }
25206 if ( ! $this->can_use_premium_code() ) {
25207 // Don't have access to the premium code.
25208 return;
25209 }
25210 if ( ! $this->has_release_on_freemius() ) {
25211 // Plugin is a serviceware, no premium code version.
25212 return;
25213 }
25214 } else {
25215 $addon = $this->get_addon( $plugin_id );
25216
25217 if ( ! is_object( $addon ) ) {
25218 // Invalid add-on ID.
25219 return;
25220 }
25221
25222 if ( $this->is_addon_activated( $plugin_id, true ) ) {
25223 // Premium add-on version is already activated.
25224 return;
25225 }
25226 }
25227
25228 $vars = array(
25229 'id' => $this->_module_id,
25230 'target_module_id' => $plugin_id,
25231 'slug' => $this->_slug,
25232 );
25233
25234 fs_require_template( 'auto-installation.php', $vars );
25235 }
25236
25237 #endregion
25238
25239 #--------------------------------------------------------------------------------
25240 #region Tabs Integration
25241 #--------------------------------------------------------------------------------
25242
25243 #region Module's Original Tabs
25244
25245 /**
25246 * Inject a JavaScript logic to capture the theme tabs HTML.
25247 *
25248 * @author Vova Feldman (@svovaf)
25249 * @since 1.2.2.7
25250 */
25251 function _tabs_capture() {
25252 $this->_logger->entrance();
25253
25254 if (
25255 ! $this->is_product_settings_page() ||
25256 ! $this->should_page_include_tabs() ||
25257 ! $this->is_matching_url( $this->main_menu_url() )
25258 ) {
25259 return;
25260 }
25261
25262 $params = array(
25263 'id' => $this->_module_id,
25264 );
25265
25266 fs_require_once_template( 'tabs-capture-js.php', $params );
25267 }
25268
25269 /**
25270 * Cache theme's tabs HTML for a week. The cache will also be set as expired
25271 * after version and type (free/premium) changes, in addition to the week period.
25272 *
25273 * @author Vova Feldman (@svovaf)
25274 * @since 1.2.2.7
25275 */
25276 function _store_tabs_ajax_action() {
25277 $this->_logger->entrance();
25278
25279 $this->check_ajax_referer( 'store_tabs' );
25280
25281 // Init filesystem if not yet initiated.
25282 WP_Filesystem();
25283
25284 // Get POST body HTML data.
25285 global $wp_filesystem;
25286 $tabs_html = $wp_filesystem->get_contents( "php://input" );
25287
25288 if ( is_string( $tabs_html ) ) {
25289 $tabs_html = trim( $tabs_html );
25290 }
25291
25292 if ( ! is_string( $tabs_html ) || empty( $tabs_html ) ) {
25293 self::shoot_ajax_failure();
25294 }
25295
25296 $this->_cache->set( 'tabs', $tabs_html, 7 * WP_FS__TIME_24_HOURS_IN_SEC );
25297
25298 self::shoot_ajax_success();
25299 }
25300
25301 /**
25302 * Cache theme's settings page custom styles. The cache will also be set as expired
25303 * after version and type (free/premium) changes, in addition to the week period.
25304 *
25305 * @author Vova Feldman (@svovaf)
25306 * @since 1.2.2.7
25307 */
25308 function _store_tabs_styles() {
25309 $this->_logger->entrance();
25310
25311 if (
25312 ! $this->is_product_settings_page() ||
25313 ! $this->should_page_include_tabs() ||
25314 ! $this->is_matching_url( $this->main_menu_url() )
25315 ) {
25316 return;
25317 }
25318
25319 $wp_styles = wp_styles();
25320
25321 $theme_styles_url = get_template_directory_uri();
25322
25323 $stylesheets = array();
25324 foreach ( $wp_styles->queue as $handler ) {
25325 if ( fs_starts_with( $handler, 'fs_' ) ) {
25326 // Assume that stylesheets that their handler starts with "fs_" belong to the SDK.
25327 continue;
25328 }
25329
25330 /**
25331 * @var _WP_Dependency $stylesheet
25332 */
25333 $stylesheet = $wp_styles->registered[ $handler ];
25334
25335 if ( fs_starts_with( $stylesheet->src, $theme_styles_url ) ) {
25336 $stylesheets[] = $stylesheet->src;
25337 }
25338 }
25339
25340 if ( ! empty( $stylesheets ) ) {
25341 $this->_cache->set( 'tabs_stylesheets', $stylesheets, 7 * WP_FS__TIME_24_HOURS_IN_SEC );
25342 }
25343 }
25344
25345 /**
25346 * Check if module's original settings page has any tabs.
25347 *
25348 * @author Vova Feldman (@svovaf)
25349 * @since 1.2.2.7
25350 *
25351 * @return bool
25352 */
25353 private function has_tabs() {
25354 return $this->_cache->has( 'tabs' );
25355 }
25356
25357 /**
25358 * Get module's settings page HTML content, starting
25359 * from the beginning of the <div class="wrap"> element,
25360 * until the tabs HTML (including).
25361 *
25362 * @author Vova Feldman (@svovaf)
25363 * @since 1.2.2.7
25364 *
25365 * @return string
25366 */
25367 private function get_tabs_html() {
25368 $this->_logger->entrance();
25369
25370 return $this->_cache->get( 'tabs' );
25371 }
25372
25373 /**
25374 * Check if page should include tabs.
25375 *
25376 * @author Vova Feldman (@svovaf)
25377 * @since 1.2.2.7
25378 *
25379 * @return bool
25380 */
25381 private function should_page_include_tabs() {
25382 if ( ! $this->has_settings_menu() ) {
25383 // Don't add tabs if no settings at all.
25384 return false;
25385 }
25386
25387 if ( self::NAVIGATION_TABS !== $this->_navigation ) {
25388 // Only add tabs to themes for now.
25389 return false;
25390 }
25391
25392 if ( $this->is_theme() && ! $this->has_paid_plan() && ! $this->has_addons() ) {
25393 // Only add tabs to monetizing themes.
25394 return false;
25395 }
25396
25397 if ( ! $this->is_product_settings_page() ) {
25398 // Only add tabs if browsing one of the product's setting pages.
25399 return false;
25400 }
25401
25402 if ( $this->is_activation_mode() && $this->is_activation_page() ) {
25403 // Don't include tabs in the activation page.
25404 return false;
25405 }
25406
25407 if ( $this->is_admin_page( 'pricing' ) && fs_request_get_bool( 'checkout' ) ) {
25408 // Don't add tabs on checkout page, we want to reduce distractions
25409 // as much as possible.
25410 return false;
25411 }
25412
25413 return true;
25414 }
25415
25416 /**
25417 * Add the tabs HTML before the setting's page content and
25418 * enqueue any required stylesheets.
25419 *
25420 * @author Vova Feldman (@svovaf)
25421 * @since 1.2.2.7
25422 *
25423 * @return bool If tabs were included.
25424 */
25425 function _add_tabs_before_content() {
25426 $this->_logger->entrance();
25427
25428 if ( ! $this->should_page_include_tabs() ) {
25429 return false;
25430 }
25431
25432 /**
25433 * Enqueue the original stylesheets that are included in the
25434 * theme settings page. That way, if the theme settings has
25435 * some custom _styled_ content above the tabs UI, this
25436 * will make sure that the styling is preserved.
25437 */
25438 $stylesheets = $this->_cache->get( 'tabs_stylesheets', array() );
25439 if ( is_array( $stylesheets ) ) {
25440 for ( $i = 0, $len = count( $stylesheets ); $i < $len; $i ++ ) {
25441 wp_enqueue_style( "fs_{$this->_module_id}_tabs_{$i}", $stylesheets[ $i ] );
25442 }
25443 }
25444
25445 // Cut closing </div> tag.
25446 echo substr( trim( $this->get_tabs_html() ), 0, - 6 );
25447
25448 return true;
25449 }
25450
25451 /**
25452 * Add the tabs closing HTML after the setting's page content.
25453 *
25454 * @author Vova Feldman (@svovaf)
25455 * @since 1.2.2.7
25456 *
25457 * @return bool If tabs closing HTML was included.
25458 */
25459 function _add_tabs_after_content() {
25460 $this->_logger->entrance();
25461
25462 if ( ! $this->should_page_include_tabs() ) {
25463 return false;
25464 }
25465
25466 echo '</div>';
25467
25468 return true;
25469 }
25470
25471 #endregion
25472
25473 /**
25474 * Add in-page JavaScript to inject the Freemius tabs into
25475 * the module's setting tabs section.
25476 *
25477 * @author Vova Feldman (@svovaf)
25478 * @since 1.2.2.7
25479 */
25480 function _add_freemius_tabs() {
25481 $this->_logger->entrance();
25482
25483 if ( ! $this->should_page_include_tabs() ) {
25484 return;
25485 }
25486
25487 $params = array( 'id' => $this->_module_id );
25488 fs_require_once_template( 'tabs.php', $params );
25489 }
25490
25491 #endregion
25492
25493 #--------------------------------------------------------------------------------
25494 #region Customizer Integration for Themes
25495 #--------------------------------------------------------------------------------
25496
25497 /**
25498 * @author Vova Feldman (@svovaf)
25499 * @since 1.2.2.7
25500 *
25501 * @param WP_Customize_Manager $customizer
25502 */
25503 function _customizer_register( $customizer ) {
25504 $this->_logger->entrance();
25505
25506 if ( $this->is_pricing_page_visible() ) {
25507 require_once WP_FS__DIR_INCLUDES . '/customizer/class-fs-customizer-upsell-control.php';
25508
25509 $customizer->add_section( 'freemius_upsell', array(
25510 'title' => '&#9733; ' . $this->get_text_inline( 'View paid features', 'view-paid-features' ),
25511 'priority' => 1,
25512 ) );
25513 $customizer->add_setting( 'freemius_upsell', array(
25514 'sanitize_callback' => 'esc_html',
25515 ) );
25516
25517 $customizer->add_control( new FS_Customizer_Upsell_Control( $customizer, 'freemius_upsell', array(
25518 'fs' => $this,
25519 'section' => 'freemius_upsell',
25520 'priority' => 100,
25521 ) ) );
25522 }
25523
25524 if ( $this->is_page_visible( 'contact' ) || $this->is_page_visible( 'support' ) ) {
25525 require_once WP_FS__DIR_INCLUDES . '/customizer/class-fs-customizer-support-section.php';
25526
25527 // Main Documentation Link In Customizer Root.
25528 $customizer->add_section( new FS_Customizer_Support_Section( $customizer, 'freemius_support', array(
25529 'fs' => $this,
25530 'priority' => 1000,
25531 ) ) );
25532 }
25533 }
25534
25535 #endregion
25536
25537 /**
25538 * If the theme has a paid version, add some custom
25539 * styling to the theme's premium version (if exists)
25540 * to highlight that it's the premium version of the
25541 * same theme, making it easier for identification
25542 * after the user upgrades and upload it to the site.
25543 *
25544 * @author Vova Feldman (@svovaf)
25545 * @since 1.2.2.7
25546 */
25547 function _style_premium_theme() {
25548 $this->_logger->entrance();
25549
25550 if ( ! self::is_themes_page() ) {
25551 // Only include in the themes page.
25552 return;
25553 }
25554
25555 if ( ! $this->has_paid_plan() ) {
25556 // Only include if has any paid plans.
25557 return;
25558 }
25559
25560 $params = null;
25561 fs_require_once_template( '/js/jquery.content-change.php', $params );
25562
25563 $params = array(
25564 'slug' => $this->_slug,
25565 'id' => $this->_module_id,
25566 );
25567
25568 fs_require_template( '/js/style-premium-theme.php', $params );
25569 }
25570
25571 /**
25572 * This method will return the absolute URL of the module's local icon.
25573 *
25574 * When you are running your plugin or theme on a **localhost** environment, if the icon
25575 * is not found in the local assets folder, try to fetch the icon URL from Freemius. If not set and
25576 * it's a plugin hosted on WordPress.org, try fetching the icon URL from wordpress.org.
25577 * If an icon is found, this method will automatically attempt to download the icon and store it
25578 * in /freemius/assets/img/{slug}.{png|jpg|gif|svg}.
25579 *
25580 * It's important to mention that this method is NOT phoning home since the developer will deploy
25581 * the product with the local icon in the assets folder. The download process just simplifies
25582 * the process for the developer.
25583 *
25584 * @author Vova Feldman (@svovaf)
25585 * @since 2.0.0
25586 *
25587 * @return string
25588 */
25589 function get_local_icon_url() {
25590 global $fs_active_plugins;
25591
25592 /**
25593 * @since 1.1.7.5
25594 */
25595 $local_path = $this->apply_filters( 'plugin_icon', false );
25596
25597 if ( is_string( $local_path ) ) {
25598 $icons = array( $local_path );
25599 } else {
25600 $img_dir = WP_FS__DIR_IMG;
25601
25602 // Locate the main assets folder.
25603 if ( 1 < count( $fs_active_plugins->plugins ) ) {
25604 $plugin_or_theme_img_dir = ( $this->is_plugin() ? WP_PLUGIN_DIR : get_theme_root( get_stylesheet() ) );
25605
25606 foreach ( $fs_active_plugins->plugins as $sdk_path => &$data ) {
25607 if ( $data->plugin_path == $this->get_plugin_basename() ) {
25608 $img_dir = $plugin_or_theme_img_dir
25609 . '/'
25610 /**
25611 * The basename will be `themes` or the basename of a custom themes directory.
25612 *
25613 * @author Leo Fajardo (@leorw)
25614 * @since 2.2.3
25615 */
25616 . str_replace( '../' . basename( $plugin_or_theme_img_dir ) . '/', '', $sdk_path )
25617 . '/assets/img';
25618
25619 break;
25620 }
25621 }
25622 }
25623
25624 // Try to locate the icon in the assets folder.
25625 $icons = glob( fs_normalize_path( $img_dir . "/{$this->_slug}.*" ) );
25626
25627 if ( ! is_array( $icons ) || 0 === count( $icons ) ) {
25628 if ( ! WP_FS__IS_LOCALHOST && $this->is_theme() ) {
25629 $icons = array(
25630 fs_normalize_path( $img_dir . '/theme-icon.png' )
25631 );
25632 } else {
25633 $icon_found = false;
25634 $local_path = fs_normalize_path( "{$img_dir}/{$this->_slug}.png" );
25635
25636 if ( ! function_exists( 'get_filesystem_method' ) ) {
25637 require_once ABSPATH . 'wp-admin/includes/file.php';
25638 }
25639
25640 $have_write_permissions = ( 'direct' === get_filesystem_method( array(), fs_normalize_path( $img_dir ) ) );
25641
25642 /**
25643 * IMPORTANT: THIS CODE WILL NEVER RUN AFTER THE PLUGIN IS IN THE REPO.
25644 *
25645 * This code will only be executed once during the testing
25646 * of the plugin in a local environment. The plugin icon file WILL
25647 * already exist in the assets folder when the plugin is deployed to
25648 * the repository.
25649 */
25650 if ( WP_FS__IS_LOCALHOST && $have_write_permissions ) {
25651 // Fetch icon from Freemius.
25652 $icon = $this->fetch_remote_icon_url();
25653
25654 // Fetch icon from WordPress.org.
25655 if ( empty( $icon ) && $this->is_plugin() && $this->is_org_repo_compliant() ) {
25656 if ( ! function_exists( 'plugins_api' ) ) {
25657 require_once ABSPATH . 'wp-admin/includes/plugin-install.php';
25658 }
25659
25660 $plugin_information = plugins_api( 'plugin_information', array(
25661 'slug' => $this->_slug,
25662 'fields' => array(
25663 'sections' => false,
25664 'tags' => false,
25665 'icons' => true
25666 )
25667 ) );
25668
25669 if (
25670 ! is_wp_error( $plugin_information )
25671 && isset( $plugin_information->icons )
25672 && ! empty( $plugin_information->icons )
25673 ) {
25674 /**
25675 * Get the smallest icon.
25676 *
25677 * @author Leo Fajardo (@leorw)
25678 * @since 1.2.2
25679 */
25680 $icon = end( $plugin_information->icons );
25681 }
25682 }
25683
25684 if ( ! empty( $icon ) ) {
25685 if ( 0 !== strpos( $icon, 'http' ) ) {
25686 $icon = 'http:' . $icon;
25687 }
25688
25689 /**
25690 * Get a clean file extension, e.g.: "jpg" and not "jpg?rev=1305765".
25691 *
25692 * @author Leo Fajardo (@leorw)
25693 * @since 1.2.2
25694 */
25695 $ext = pathinfo( strtok( $icon, '?' ), PATHINFO_EXTENSION );
25696
25697 $local_path = fs_normalize_path( "{$img_dir}/{$this->_slug}.{$ext}" );
25698
25699 // Try to download the icon.
25700 $icon_found = fs_download_image( $icon, $local_path );
25701 }
25702 }
25703
25704 if ( ! $icon_found ) {
25705 // No icons found, fallback to default icon.
25706 if ( $have_write_permissions ) {
25707 // If have write permissions, copy default icon.
25708 copy( fs_normalize_path( $img_dir . "/{$this->_module_type}-icon.png" ), $local_path );
25709 } else {
25710 // If doesn't have write permissions, use default icon path.
25711 $local_path = fs_normalize_path( $img_dir . "/{$this->_module_type}-icon.png" );
25712 }
25713 }
25714
25715 $icons = array( $local_path );
25716 }
25717 }
25718 }
25719
25720 $icon_dir = dirname( $icons[0] );
25721
25722 return fs_img_url( substr( $icons[0], strlen( $icon_dir ) ), $icon_dir );
25723 }
25724
25725 /**
25726 * Fetch module's extended info.
25727 *
25728 * @author Vova Feldman (@svovaf)
25729 * @since 2.0.0
25730 *
25731 * @return object|mixed
25732 */
25733 private function fetch_module_info() {
25734 return $this->get_api_plugin_scope()->get( 'info.json', false, WP_FS__TIME_WEEK_IN_SEC );
25735 }
25736
25737 /**
25738 * Fetch module's remote icon URL.
25739 *
25740 * @author Vova Feldman (@svovaf)
25741 * @since 2.0.0
25742 *
25743 * @return string
25744 */
25745 function fetch_remote_icon_url() {
25746 $info = $this->fetch_module_info();
25747
25748 return ( $this->is_api_result_object( $info, 'icon' ) && is_string( $info->icon ) ) ?
25749 $info->icon :
25750 '';
25751 }
25752
25753 #--------------------------------------------------------------------------------
25754 #region GDPR
25755 #--------------------------------------------------------------------------------
25756
25757 /**
25758 * @author Leo Fajardo (@leorw)
25759 * @since 2.1.0
25760 *
25761 * @param array $user_plugins
25762 *
25763 * @return string
25764 */
25765 private function get_gdpr_admin_notice_string( $user_plugins ) {
25766 $this->_logger->entrance();
25767
25768 $addons = self::get_all_addons();
25769
25770 foreach ( $user_plugins as $user_plugin ) {
25771 $has_addons = isset( $addons[ $user_plugin->id ] );
25772
25773 if ( WP_FS__MODULE_TYPE_PLUGIN === $user_plugin->type && ! $has_addons ) {
25774 if ( $this->_module_id == $user_plugin->id ) {
25775 $addons = $this->get_addons();
25776 $has_addons = ( ! empty( $addons ) );
25777 } else {
25778 $plugin_api = FS_Api::instance(
25779 $user_plugin->id,
25780 'plugin',
25781 $user_plugin->id,
25782 $user_plugin->public_key,
25783 ! $user_plugin->is_live,
25784 false,
25785 $this->get_sdk_version()
25786 );
25787
25788 $addons_result = $plugin_api->get( '/addons.json?enriched=true', true );
25789
25790 if ( $this->is_api_result_object( $addons_result, 'plugins' ) &&
25791 is_array( $addons_result->plugins ) &&
25792 ! empty( $addons_result->plugins )
25793 ) {
25794 $has_addons = true;
25795 }
25796 }
25797 }
25798
25799 $user_plugin->has_addons = $has_addons;
25800 }
25801
25802 $is_single_parent_product = ( 1 === count( $user_plugins ) );
25803
25804 $multiple_products_text = '';
25805
25806 if ( $is_single_parent_product ) {
25807 $single_parent_product = reset( $user_plugins );
25808
25809 $thank_you = sprintf(
25810 "<span data-plugin-id='%d'>%s</span>",
25811 $single_parent_product->id,
25812 sprintf(
25813 $single_parent_product->has_addons ?
25814 $this->get_text_inline( 'Thank you so much for using %s and its add-ons!', 'thank-you-for-using-product-and-its-addons' ) :
25815 $this->get_text_inline( 'Thank you so much for using %s!', 'thank-you-for-using-product' ),
25816 sprintf('<b><i>%s</i></b>', $single_parent_product->title)
25817 )
25818 );
25819
25820 $already_opted_in = sprintf(
25821 $this->get_text_inline( "You've already opted-in to our usage-tracking, which helps us keep improving the %s.", 'already-opted-in-to-product-usage-tracking' ),
25822 ( WP_FS__MODULE_TYPE_THEME === $single_parent_product->type ) ? WP_FS__MODULE_TYPE_THEME : WP_FS__MODULE_TYPE_PLUGIN
25823 );
25824 } else {
25825 $thank_you = $this->get_text_inline( 'Thank you so much for using our products!', 'thank-you-for-using-products' );
25826 $already_opted_in = $this->get_text_inline( "You've already opted-in to our usage-tracking, which helps us keep improving them.", 'already-opted-in-to-products-usage-tracking' );
25827
25828 $products_and_add_ons = '';
25829 foreach ( $user_plugins as $user_plugin ) {
25830 if ( ! empty( $products_and_add_ons ) ) {
25831 $products_and_add_ons .= ', ';
25832 }
25833
25834 if ( ! $user_plugin->has_addons ) {
25835 $products_and_add_ons .= sprintf(
25836 "<span data-plugin-id='%d'>%s</span>",
25837 $user_plugin->id,
25838 $user_plugin->title
25839 );
25840 } else {
25841 $products_and_add_ons .= sprintf(
25842 "<span data-plugin-id='%d'>%s</span>",
25843 $user_plugin->id,
25844 sprintf(
25845 $this->get_text_inline( '%s and its add-ons', 'product-and-its-addons' ),
25846 $user_plugin->title
25847 )
25848 );
25849 }
25850 }
25851
25852 $multiple_products_text = sprintf(
25853 "<small class='products'><strong>%s:</strong> %s</small>",
25854 $this->get_text_inline( 'Products', 'products' ),
25855 $products_and_add_ons
25856 );
25857 }
25858
25859 $actions = sprintf(
25860 '<ul><li>%s<span class="action-description"> - %s</span></li><li>%s<span class="action-description"> - %s</span></li></ul>',
25861 sprintf('<button class="button button-primary allow-marketing">%s</button>', $this->get_text_inline( 'Yes', 'yes' ) ),
25862 $this->get_text_inline( 'send me security & feature updates, educational content and offers.', 'send-updates' ),
25863 sprintf('<button class="button button-secondary">%s</button>', $this->get_text_inline( 'No', 'no' ) ),
25864 sprintf(
25865 $this->get_text_inline( 'do %sNOT%s send me security & feature updates, educational content and offers.', 'do-not-send-updates' ),
25866 '<span class="underlined">',
25867 '</span>'
25868 )
25869 );
25870
25871 return sprintf(
25872 '%s %s %s',
25873 $thank_you,
25874 $already_opted_in,
25875 sprintf( $this->get_text_inline( 'Due to the new %sEU General Data Protection Regulation (GDPR)%s compliance requirements it is required that you provide your explicit consent, again, confirming that you are onboard :-)', 'due-to-gdpr-compliance-requirements' ), '<a href="https://eugdpr.org/" target="_blank" rel="noopener noreferrer">', '</a>' ) .
25876 '<br><br>' .
25877 '<b>' . $this->get_text_inline( "Please let us know if you'd like us to contact you for security & feature updates, educational content, and occasional offers:", 'contact-for-updates' ) . '</b>' .
25878 $actions .
25879 ( $is_single_parent_product ? '' : $multiple_products_text )
25880 );
25881 }
25882
25883 /**
25884 * This method is called for opted-in users to fetch the is_marketing_allowed flag of the user for all the
25885 * plugins and themes they've opted in to.
25886 *
25887 * @author Leo Fajardo (@leorw)
25888 * @since 2.1.0
25889 *
25890 * @param string $user_email
25891 * @param string $license_key
25892 * @param array $plugin_ids
25893 * @param string|null $license_key
25894 *
25895 * @return array|false
25896 */
25897 private function fetch_user_marketing_flag_status_by_plugins( $user_email, $license_key, $plugin_ids ) {
25898 $request = array(
25899 'method' => 'POST',
25900 'body' => array(),
25901 'timeout' => WP_FS__DEBUG_SDK ? 60 : 30,
25902 );
25903
25904 if ( is_string( $user_email ) ) {
25905 $request['body']['email'] = $user_email;
25906 } else {
25907 $request['body']['license_key'] = $license_key;
25908 }
25909
25910 $result = array();
25911
25912 $url = WP_FS__ADDRESS . '/action/service/user_plugin/';
25913 $total_plugin_ids = count( $plugin_ids );
25914
25915 $plugin_ids_count_per_request = 10;
25916 for ( $i = 1; $i <= $total_plugin_ids; $i += $plugin_ids_count_per_request ) {
25917 $plugin_ids_set = array_slice( $plugin_ids, $i - 1, $plugin_ids_count_per_request );
25918
25919 $request['body']['plugin_ids'] = $plugin_ids_set;
25920
25921 $response = self::safe_remote_post(
25922 $url,
25923 $request,
25924 WP_FS__TIME_24_HOURS_IN_SEC,
25925 WP_FS__TIME_12_HOURS_IN_SEC
25926 );
25927
25928 if ( ! is_wp_error( $response ) ) {
25929 $decoded = is_string( $response['body'] ) ?
25930 json_decode( $response['body'] ) :
25931 null;
25932
25933 if (
25934 !is_object($decoded) ||
25935 !isset($decoded->success) ||
25936 true !== $decoded->success ||
25937 !isset( $decoded->data ) ||
25938 !is_array( $decoded->data )
25939 ) {
25940 return false;
25941 }
25942
25943 $result = array_merge( $result, $decoded->data );
25944 }
25945 }
25946
25947 return $result;
25948 }
25949
25950 /**
25951 * @author Leo Fajardo (@leorw)
25952 * @since 2.1.0
25953 */
25954 function _maybe_show_gdpr_admin_notice() {
25955 if ( ! $this->is_user_in_admin() ) {
25956 return;
25957 }
25958
25959 if ( ! $this->should_handle_gdpr_admin_notice() ) {
25960 return;
25961 }
25962
25963 if ( ! $this->is_user_admin() ) {
25964 return;
25965 }
25966
25967 require_once WP_FS__DIR_INCLUDES . '/class-fs-user-lock.php';
25968
25969 $lock = FS_User_Lock::instance();
25970
25971 /**
25972 * Try to acquire a 60-sec lock based on the WP user and thread/process ID.
25973 */
25974 if ( ! $lock->try_lock( 60 ) ) {
25975 return;
25976 }
25977
25978 /**
25979 * @var $current_wp_user WP_User
25980 */
25981 $current_wp_user = self::_get_current_wp_user();
25982
25983 /**
25984 * @var FS_User $current_fs_user
25985 */
25986 $current_fs_user = Freemius::_get_user_by_email( $current_wp_user->user_email );
25987
25988 $ten_years_in_sec = 10 * 365 * WP_FS__TIME_24_HOURS_IN_SEC;
25989
25990 if ( ! is_object( $current_fs_user ) ) {
25991 // 10-year lock.
25992 $lock->lock( $ten_years_in_sec );
25993
25994 return;
25995 }
25996
25997 $gdpr = FS_GDPR_Manager::instance();
25998
25999 if ( $gdpr->is_opt_in_notice_shown() ) {
26000 // 30-day lock.
26001 $lock->lock( 30 * WP_FS__TIME_24_HOURS_IN_SEC );
26002
26003 return;
26004 }
26005
26006 if ( ! $gdpr->should_show_opt_in_notice() ) {
26007 // 10-year lock.
26008 $lock->lock( $ten_years_in_sec );
26009
26010 return;
26011 }
26012
26013 $last_time_notice_shown = $gdpr->last_time_notice_was_shown();
26014 $was_notice_shown_before = ( false !== $last_time_notice_shown );
26015
26016 if ( $was_notice_shown_before &&
26017 30 * WP_FS__TIME_24_HOURS_IN_SEC > time() - $last_time_notice_shown
26018 ) {
26019 // If the notice was shown before, show it again after 30 days from the last time it was shown.
26020 return;
26021 }
26022
26023 /**
26024 * Find all plugin IDs that were installed by the current admin.
26025 */
26026 $plugin_ids_map = self::get_user_opted_in_module_ids_map( $current_fs_user->id );
26027
26028 if ( empty( $plugin_ids_map )) {
26029 $lock->lock( $ten_years_in_sec );
26030
26031 return;
26032 }
26033
26034 $user_plugins = $this->fetch_user_marketing_flag_status_by_plugins(
26035 $current_fs_user->email,
26036 null,
26037 array_keys( $plugin_ids_map )
26038 );
26039
26040 if ( empty( $user_plugins ) ) {
26041 $lock->lock(
26042 is_array($user_plugins) ?
26043 $ten_years_in_sec :
26044 // Lock for 24-hours on errors.
26045 WP_FS__TIME_24_HOURS_IN_SEC
26046 );
26047
26048 return;
26049 }
26050
26051 $has_unset_marketing_optin = false;
26052
26053 foreach ( $user_plugins as $user_plugin ) {
26054 if ( true == $user_plugin->is_marketing_allowed ) {
26055 unset( $plugin_ids_map[ $user_plugin->plugin_id ] );
26056 }
26057
26058 if ( ! $has_unset_marketing_optin && is_null( $user_plugin->is_marketing_allowed ) ) {
26059 $has_unset_marketing_optin = true;
26060 }
26061 }
26062
26063 if ( empty( $plugin_ids_map ) ||
26064 ( $was_notice_shown_before && ! $has_unset_marketing_optin )
26065 ) {
26066 $lock->lock( $ten_years_in_sec );
26067
26068 return;
26069 }
26070
26071 $modules = array_merge(
26072 array_values( self::maybe_get_entities_account_option( 'plugins', array() ) ),
26073 array_values( self::maybe_get_entities_account_option( 'themes', array() ) )
26074 );
26075
26076 foreach ( $modules as $module ) {
26077 if ( ! FS_Plugin::is_valid_id( $module->parent_plugin_id ) && isset( $plugin_ids_map[ $module->id ] ) ) {
26078 $plugin_ids_map[ $module->id ] = $module;
26079 }
26080 }
26081
26082 $plugin_title = null;
26083 if ( 1 === count( $plugin_ids_map ) ) {
26084 $module = reset( $plugin_ids_map );
26085 $plugin_title = $module->title;
26086 }
26087
26088 $gdpr->add_opt_in_sticky_notice(
26089 $this->get_gdpr_admin_notice_string( $plugin_ids_map ),
26090 $plugin_title
26091 );
26092
26093 $this->add_gdpr_optin_ajax_handler_and_style();
26094
26095 $gdpr->notice_was_just_shown();
26096
26097 // 30-day lock.
26098 $lock->lock( 30 * WP_FS__TIME_24_HOURS_IN_SEC );
26099 }
26100
26101 /**
26102 * Prevents the GDPR opt-in admin notice from being added if the user has already chosen to allow or not allow
26103 * marketing.
26104 *
26105 * @author Leo Fajardo (@leorw)
26106 * @since 2.1.0
26107 */
26108 private function disable_opt_in_notice_and_lock_user() {
26109 FS_GDPR_Manager::instance()->disable_opt_in_notice();
26110
26111 require_once WP_FS__DIR_INCLUDES . '/class-fs-user-lock.php';
26112
26113 // 10-year lock.
26114 FS_User_Lock::instance()->lock( 10 * 365 * WP_FS__TIME_24_HOURS_IN_SEC );
26115 }
26116
26117 /**
26118 * @author Leo Fajardo (@leorw)
26119 * @since 2.5.4
26120 */
26121 static function _add_api_connectivity_notice_handler_js() {
26122 fs_require_once_template( 'api-connectivity-message-js.php' );
26123 }
26124
26125 /**
26126 * @author Leo Fajardo (@leorw)
26127 * @since 2.1.0
26128 */
26129 function _add_gdpr_optin_js() {
26130 $vars = array( 'id' => $this->_module_id );
26131
26132 fs_require_once_template( 'gdpr-optin-js.php', $vars );
26133 }
26134
26135 /**
26136 * @author Leo Fajardo (@leorw)
26137 * @since 2.1.0
26138 */
26139 function enqueue_gdpr_optin_notice_style() {
26140 fs_enqueue_local_style( 'fs_gdpr_optin_notice', '/admin/gdpr-optin-notice.css' );
26141 }
26142
26143 /**
26144 * @author Leo Fajardo (@leorw)
26145 * @since 2.1.0
26146 */
26147 function _maybe_add_gdpr_optin_ajax_handler() {
26148 $this->add_ajax_action( 'fetch_is_marketing_required_flag_value', array( &$this, '_fetch_is_marketing_required_flag_value_ajax_action' ) );
26149
26150 if ( FS_GDPR_Manager::instance()->is_opt_in_notice_shown() ) {
26151 $this->add_gdpr_optin_ajax_handler_and_style();
26152 }
26153 }
26154
26155 /**
26156 * @author Leo Fajardo (@leorw)
26157 * @since 2.1.0
26158 */
26159 function _fetch_is_marketing_required_flag_value_ajax_action() {
26160 $this->_logger->entrance();
26161
26162 $this->check_ajax_referer( 'fetch_is_marketing_required_flag_value' );
26163
26164 $license_key = fs_request_get( 'license_key' );
26165
26166 if ( empty($license_key) ) {
26167 self::shoot_ajax_failure( $this->get_text_inline( 'License key is empty.', 'empty-license-key' ) );
26168 }
26169
26170 $user_plugins = $this->fetch_user_marketing_flag_status_by_plugins(
26171 null,
26172 $license_key,
26173 array( $this->_module_id )
26174 );
26175
26176 if ( ! is_array( $user_plugins ) ||
26177 empty($user_plugins) ||
26178 !isset($user_plugins[0]->plugin_id) ||
26179 $user_plugins[0]->plugin_id != $this->_module_id
26180 ) {
26181 /**
26182 * If faced an error or if the module ID do not match to the current module, ask for GDPR opt-in.
26183 *
26184 * @author Vova Feldman (@svovaf)
26185 */
26186 self::shoot_ajax_success( array(
26187 'is_marketing_allowed' => null,
26188 'license_owner_id' => null
26189 ) );
26190 }
26191
26192 self::shoot_ajax_success( array(
26193 'is_marketing_allowed' => $user_plugins[0]->is_marketing_allowed,
26194 'license_owner_id' => ( isset( $user_plugins[0]->license_owner_id ) ? $user_plugins[0]->license_owner_id : null )
26195 ) );
26196 }
26197
26198 /**
26199 * @author Leo Fajardo (@leorw)
26200 * @since 2.3.2
26201 *
26202 * @param number[] $install_ids
26203 *
26204 * @return array {
26205 * An array of objects containing the installs' licenses owners data.
26206 *
26207 * @property number $id User ID.
26208 * @property string $email User email (can be masked email).
26209 * }
26210 */
26211 private function fetch_installs_licenses_owners_data( $install_ids ) {
26212 $this->_logger->entrance();
26213
26214 $response = $this->get_api_user_scope()->get(
26215 '/licenses_owners.json?install_ids=' . implode( ',', $install_ids )
26216 );
26217
26218 $license_owners = array();
26219
26220 if ( $this->is_api_result_object( $response, 'owners' ) ) {
26221 $license_owners = $response->owners;
26222 }
26223
26224 return $license_owners;
26225 }
26226
26227 /**
26228 * @author Leo Fajardo (@leorw)
26229 * @since 2.1.0
26230 */
26231 private function add_gdpr_optin_ajax_handler_and_style() {
26232 // Add GDPR action AJAX callback.
26233 $this->add_ajax_action( 'gdpr_optin_action', array( &$this, '_gdpr_optin_ajax_action' ) );
26234
26235 add_action( 'admin_footer', array( &$this, '_add_gdpr_optin_js' ) );
26236 add_action( 'admin_enqueue_scripts', array( &$this, 'enqueue_gdpr_optin_notice_style' ) );
26237 }
26238
26239 /**
26240 * @author Leo Fajardo (@leorw)
26241 * @since 2.1.0
26242 */
26243 function _gdpr_optin_ajax_action() {
26244 $this->_logger->entrance();
26245
26246 $this->check_ajax_referer( 'gdpr_optin_action' );
26247
26248 if ( ! fs_request_has( 'is_marketing_allowed' ) || ! fs_request_has( 'plugin_ids' ) ) {
26249 self::shoot_ajax_failure();
26250 }
26251
26252 $current_wp_user = self::_get_current_wp_user();
26253
26254 $plugin_ids = fs_request_get( 'plugin_ids', array() );
26255 if ( ! is_array( $plugin_ids ) || empty( $plugin_ids ) ) {
26256 self::shoot_ajax_failure();
26257 }
26258
26259 $modules = array_merge(
26260 array_values( self::maybe_get_entities_account_option( 'plugins', array() ) ),
26261 array_values( self::maybe_get_entities_account_option( 'themes', array() ) )
26262 );
26263
26264 foreach ( $modules as $key => $module ) {
26265 if ( ! in_array( $module->id, $plugin_ids ) ) {
26266 unset( $modules[ $key ] );
26267 }
26268 }
26269
26270 if ( empty( $modules ) ) {
26271 self::shoot_ajax_failure();
26272 }
26273
26274 $user_api = $this->get_api_user_scope_by_user( Freemius::_get_user_by_email( $current_wp_user->user_email ) );
26275
26276 foreach ( $modules as $module ) {
26277 $user_api->call( "?plugin_id={$module->id}", 'put', array(
26278 'is_marketing_allowed' => ( true == fs_request_get_bool( 'is_marketing_allowed' ) )
26279 ) );
26280 }
26281
26282 FS_GDPR_Manager::instance()->remove_opt_in_notice();
26283
26284 require_once WP_FS__DIR_INCLUDES . '/class-fs-user-lock.php';
26285
26286 // 10-year lock.
26287 FS_User_Lock::instance()->lock( 10 * 365 * WP_FS__TIME_24_HOURS_IN_SEC );
26288
26289 self::shoot_ajax_success();
26290 }
26291
26292 /**
26293 * Checks if the GDPR admin notice should be handled. By default, this logic is off, unless the integrator adds the special 'handle_gdpr_admin_notice' filter.
26294 *
26295 * @author Vova Feldman (@svovaf)
26296 * @since 2.1.0
26297 *
26298 * @return bool
26299 */
26300 private function should_handle_gdpr_admin_notice() {
26301 return $this->apply_filters(
26302 'handle_gdpr_admin_notice',
26303 // Default to false.
26304 false
26305 );
26306 }
26307
26308 #endregion
26309
26310 #----------------------------------------------------------------------------------
26311 #region Marketing
26312 #----------------------------------------------------------------------------------
26313
26314 /**
26315 * Check if current user purchased any other plugins before.
26316 *
26317 * @author Vova Feldman (@svovaf)
26318 * @since 1.0.9
26319 *
26320 * @return bool
26321 */
26322 function has_purchased_before() {
26323 // TODO: Implement has_purchased_before() method.
26324 throw new Exception( 'not implemented' );
26325 }
26326
26327 /**
26328 * Check if current user classified as an agency.
26329 *
26330 * @author Vova Feldman (@svovaf)
26331 * @since 1.0.9
26332 *
26333 * @return bool
26334 */
26335 function is_agency() {
26336 // TODO: Implement is_agency() method.
26337 throw new Exception( 'not implemented' );
26338 }
26339
26340 /**
26341 * Check if current user classified as a developer.
26342 *
26343 * @author Vova Feldman (@svovaf)
26344 * @since 1.0.9
26345 *
26346 * @return bool
26347 */
26348 function is_developer() {
26349 // TODO: Implement is_developer() method.
26350 throw new Exception( 'not implemented' );
26351 }
26352
26353 /**
26354 * Check if current user classified as a business.
26355 *
26356 * @author Vova Feldman (@svovaf)
26357 * @since 1.0.9
26358 *
26359 * @return bool
26360 */
26361 function is_business() {
26362 // TODO: Implement is_business() method.
26363 throw new Exception( 'not implemented' );
26364 }
26365
26366 #endregion
26367
26368 #----------------------------------------------------------------------------------
26369 #region Helper
26370 #----------------------------------------------------------------------------------
26371
26372 /**
26373 * If running with a secret key, assume it's the developer and show pending plans as well.
26374 *
26375 * @author Vova Feldman (@svovaf)
26376 * @since 2.1.2
26377 *
26378 * @param string $path
26379 *
26380 * @return string
26381 */
26382 function add_show_pending( $path ) {
26383 if ( ! $this->has_secret_key() ) {
26384 return $path;
26385 }
26386
26387 return $path . ( false !== strpos( $path, '?' ) ? '&' : '?' ) . 'show_pending=true';
26388 }
26389
26390 #endregion
26391 }
26392