PluginProbe
Forumax – AI Powered Advanced Community Forum Plugin / 1.3.1
Forumax – AI Powered Advanced Community Forum Plugin v1.3.1
2.4.4 2.4.3 2.4.2 2.4.1 2.4.0 trunk 1.0.8 1.1.0 1.2.1 1.2.2 1.2.3 1.2.4 1.2.5 1.2.6 1.2.7 1.2.8 1.2.9 1.3.0 1.3.1 1.3.2 1.3.3 1.4.0 1.4.1 2.0.0 2.1.0 All 29 releases
bbp-core / vendor / fs / includes / class-freemius.php

class-freemius.php in Forumax – AI Powered Advanced Community Forum Plugin 1.3.1, at vendor/fs/includes/class-freemius.php

26,321 lines 990.6 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 2.9.1
114 * @var string|null Hints the SDK whether the plugin supports parallel activation mode, preventing the auto-deactivation of the free version when the premium version is activated, and vice versa.
115 */
116 private $_premium_plugin_basename_from_parallel_activation;
117
118 /**
119 * @since 1.1.7.5
120 * @var bool Hints the SDK if plugin should run in anonymous mode (only adds feedback form).
121 */
122 private $_anonymous_mode;
123
124 /**
125 * @since 1.1.9
126 * @var bool Hints the SDK if plugin have any free plans.
127 */
128 private $_is_premium_only;
129
130 /**
131 * @since 1.2.1.6
132 * @var bool Hints the SDK if plugin have premium code version at all.
133 */
134 private $_has_premium_version;
135
136 /**
137 * @since 1.2.1.6
138 * @var bool Hints the SDK if plugin should ignore pending mode by simulating a skip.
139 */
140 private $_ignore_pending_mode;
141
142 /**
143 * @since 1.0.8
144 * @var bool Hints the SDK if the plugin has any paid plans.
145 */
146 private $_has_paid_plans;
147
148 /**
149 * @since 1.2.1.5
150 * @var int Hints the SDK if the plugin offers a trial period. If negative, no trial, if zero - has a trial but
151 * without a specified period, if positive - the number of trial days.
152 */
153 private $_trial_days = - 1;
154
155 /**
156 * @since 1.2.1.5
157 * @var bool Hints the SDK if the trial requires a payment method or not.
158 */
159 private $_is_trial_require_payment = false;
160
161 /**
162 * @since 1.0.7
163 * @var bool Hints the SDK if the plugin is WordPress.org compliant.
164 */
165 private $_is_org_compliant;
166
167 /**
168 * @since 1.0.7
169 * @var bool Hints the SDK if the plugin is has add-ons.
170 */
171 private $_has_addons;
172
173 /**
174 * @since 2.4.5
175 * @var string Navigation type: 'menu' or 'tabs'.
176 */
177 private $_navigation;
178
179 const NAVIGATION_MENU = 'menu';
180 const NAVIGATION_TABS = 'tabs';
181
182 /**
183 * @since 1.1.6
184 * @var string[]bool.
185 */
186 private $_permissions;
187
188 /**
189 * @var FS_Storage
190 */
191 private $_storage;
192
193 /**
194 * @since 1.2.2.7
195 * @var FS_Cache_Manager
196 */
197 private $_cache;
198
199 /**
200 * @since 1.0.0
201 *
202 * @var FS_Logger
203 */
204 private $_logger;
205 /**
206 * @since 1.0.4
207 *
208 * @var FS_Plugin
209 */
210 private $_plugin = false;
211 /**
212 * @since 1.0.4
213 *
214 * @var FS_Plugin|false
215 */
216 private $_parent_plugin = false;
217 /**
218 * @since 1.1.1
219 *
220 * @var Freemius
221 */
222 private $_parent = false;
223 /**
224 * @since 1.0.1
225 *
226 * @var FS_User
227 */
228 private $_user = false;
229 /**
230 * @since 1.0.1
231 *
232 * @var FS_Site
233 */
234 private $_site = false;
235 /**
236 * @since 1.0.1
237 *
238 * @var FS_Plugin_License
239 */
240 private $_license;
241 /**
242 * @since 1.0.2
243 *
244 * @var FS_Plugin_Plan[]
245 */
246 private $_plans = false;
247 /**
248 * @var FS_Plugin_License[]
249 * @since 1.0.5
250 */
251 private $_licenses = false;
252
253 /**
254 * @since 1.0.1
255 *
256 * @var FS_Admin_Menu_Manager
257 */
258 private $_menu;
259
260 /**
261 * @var FS_Admin_Notices
262 */
263 private $_admin_notices;
264
265 /**
266 * @since 1.1.6
267 *
268 * @var FS_Admin_Notices
269 */
270 private static $_global_admin_notices;
271
272 /**
273 * @var FS_Logger
274 * @since 1.0.0
275 */
276 private static $_static_logger;
277
278 /**
279 * @var FS_Options
280 * @since 1.0.2
281 */
282 private static $_accounts;
283
284 /**
285 * @since 1.2.2
286 *
287 * @var number
288 */
289 private $_module_id;
290
291 /**
292 * @var Freemius[]
293 */
294 private static $_instances = array();
295
296 /**
297 * @since 1.2.3
298 *
299 * @var FS_Affiliate
300 */
301 private $affiliate = null;
302
303 /**
304 * @since 1.2.3
305 *
306 * @var FS_AffiliateTerms
307 */
308 private $plugin_affiliate_terms = null;
309
310 /**
311 * @since 1.2.3
312 *
313 * @var FS_AffiliateTerms
314 */
315 private $custom_affiliate_terms = null;
316
317 /**
318 * @since 2.0.0
319 *
320 * @var bool
321 */
322 private $_is_multisite_integrated;
323
324 /**
325 * @since 2.0.0
326 *
327 * @var bool True if the current request is for a network admin screen and the plugin is network active.
328 */
329 private $_is_network_active;
330
331 /**
332 * @since 2.0.0
333 *
334 * @var int|null The original blog ID the plugin was loaded with.
335 */
336 private $_blog_id = null;
337
338 /**
339 * @since 2.0.0
340 *
341 * @var int|null The current execution context. When true, run on network context. When int, run on the specified blog context.
342 */
343 private $_context_is_network_or_blog_id = null;
344
345 /**
346 * @since 2.0.0
347 *
348 * @var string
349 */
350 private $_dynamically_added_top_level_page_hook_name = '';
351
352 /**
353 * @author Leo Fajardo (@leorw)
354 * @since 2.3.1
355 *
356 * @var bool
357 */
358 private $is_whitelabeled;
359
360 /**
361 * @author Leo Fajardo (@leorw)
362 * @since 2.4.0
363 *
364 * @var bool
365 */
366 private $_is_bundle_license_auto_activation_enabled = false;
367
368 #region Uninstall Reasons IDs
369
370 const REASON_NO_LONGER_NEEDED = 1;
371 const REASON_FOUND_A_BETTER_PLUGIN = 2;
372 const REASON_NEEDED_FOR_A_SHORT_PERIOD = 3;
373 const REASON_BROKE_MY_SITE = 4;
374 const REASON_SUDDENLY_STOPPED_WORKING = 5;
375 const REASON_CANT_PAY_ANYMORE = 6;
376 const REASON_OTHER = 7;
377 const REASON_DIDNT_WORK = 8;
378 const REASON_DONT_LIKE_TO_SHARE_MY_INFORMATION = 9;
379 const REASON_COULDNT_MAKE_IT_WORK = 10;
380 const REASON_GREAT_BUT_NEED_SPECIFIC_FEATURE = 11;
381 const REASON_NOT_WORKING = 12;
382 const REASON_NOT_WHAT_I_WAS_LOOKING_FOR = 13;
383 const REASON_DIDNT_WORK_AS_EXPECTED = 14;
384 const REASON_TEMPORARY_DEACTIVATION = 15;
385
386 #endregion
387
388 /**
389 * @author Leo Fajardo (@leorw)
390 * @since 2.4.2
391 *
392 * @var string|null
393 */
394 private $_pricing_js_path = null;
395
396 const VERSION_MAX_CHARS = 16;
397 const LANGUAGE_MAX_CHARS = 8;
398
399 /* Ctor
400 ------------------------------------------------------------------------------------------------------------------*/
401
402 /**
403 * Main singleton instance.
404 *
405 * @author Vova Feldman (@svovaf)
406 * @since 1.0.0
407 *
408 * @param number $module_id
409 * @param string|bool $slug
410 * @param bool $is_init Since 1.2.1 Is initiation sequence.
411 */
412 private function __construct( $module_id, $slug = false, $is_init = false ) {
413 $main_file = false;
414
415 if ( $is_init && is_numeric( $module_id ) && is_string( $slug ) ) {
416 $main_file = $this->store_id_slug_type_path_map( $module_id, $slug );
417 }
418
419 $this->_module_id = $module_id;
420 $this->_slug = $this->get_slug();
421 $this->_module_type = $this->get_module_type();
422
423 $this->_blog_id = is_multisite() ? get_current_blog_id() : null;
424
425 $this->_storage = FS_Storage::instance( $this->_module_type, $this->_slug );
426
427 // If not set or 24 hours have already passed from the last time it's set, set the last load timestamp to the current time.
428 if (
429 ! isset( $this->_storage->last_load_timestamp ) ||
430 $this->_storage->last_load_timestamp < ( time() - ( WP_FS__TIME_24_HOURS_IN_SEC ) )
431 ) {
432 $this->_storage->last_load_timestamp = time();
433 }
434
435 $this->_cache = FS_Cache_Manager::get_manager( WP_FS___OPTION_PREFIX . "cache_{$module_id}" );
436
437 $this->_logger = FS_Logger::get_logger( WP_FS__SLUG . '_' . $this->get_unique_affix(), WP_FS__DEBUG_SDK, WP_FS__ECHO_DEBUG_SDK );
438
439 $this->_plugin_main_file_path = $this->_find_caller_plugin_file( $is_init, $main_file );
440 $this->_plugin_dir_path = plugin_dir_path( $this->_plugin_main_file_path );
441 $this->_plugin_basename = $this->get_plugin_basename();
442 $this->_free_plugin_basename = str_replace( '-premium/', '/', $this->_plugin_basename );
443
444 $this->_is_multisite_integrated = (
445 defined( "WP_FS__PRODUCT_{$module_id}_MULTISITE" ) &&
446 ( true === constant( "WP_FS__PRODUCT_{$module_id}_MULTISITE" ) )
447 );
448
449 $this->_is_network_active = (
450 is_multisite() &&
451 $this->_is_multisite_integrated &&
452 // Themes are always network activated, but the ACTUAL activation is per site.
453 $this->is_plugin() &&
454 (
455 is_plugin_active_for_network( $this->_plugin_basename ) ||
456 // Plugin network level activation or uninstall.
457 ( fs_is_network_admin() && is_plugin_inactive( $this->_plugin_basename ) )
458 )
459 );
460
461 $this->_storage->set_network_active(
462 $this->_is_network_active,
463 $this->is_delegated_connection()
464 );
465
466 if ( ! isset( $this->_storage->is_network_activated ) ) {
467 $this->_storage->is_network_activated = $this->_is_network_active;
468 }
469
470 if ( $this->_storage->is_network_activated != $this->_is_network_active ) {
471 // Update last activation level.
472 $this->_storage->is_network_activated = $this->_is_network_active;
473
474 $this->maybe_adjust_storage();
475 }
476
477 #region Migration
478
479 if ( is_multisite() ) {
480 /**
481 * If the install_timestamp exists on the site level but doesn't exist on the
482 * network level storage, it means that we need to process the storage with migration.
483 *
484 * 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.
485 *
486 * @author Vova Feldman (@svovaf)
487 * @since 2.0.0
488 */
489 if ( false === $this->_storage->get( 'install_timestamp', false, true ) &&
490 false !== $this->_storage->get( 'install_timestamp', false, false )
491 ) {
492 // Initiate storage migration.
493 $this->_storage->migrate_to_network();
494
495 // Migrate module cache to network level storage.
496 $this->_cache->migrate_to_network();
497 }
498 }
499
500 #endregion
501
502 $base_name_split = explode( '/', $this->_plugin_basename );
503 $this->_plugin_dir_name = $base_name_split[0];
504
505 if ( $this->_logger->is_on() ) {
506 $this->_logger->info( 'plugin_main_file_path = ' . $this->_plugin_main_file_path );
507 $this->_logger->info( 'plugin_dir_path = ' . $this->_plugin_dir_path );
508 $this->_logger->info( 'plugin_basename = ' . $this->_plugin_basename );
509 $this->_logger->info( 'free_plugin_basename = ' . $this->_free_plugin_basename );
510 $this->_logger->info( 'plugin_dir_name = ' . $this->_plugin_dir_name );
511 }
512
513 // Remember link between file to slug.
514 $this->store_file_slug_map();
515
516 // Store plugin's initial install timestamp.
517 if ( ! isset( $this->_storage->install_timestamp ) ) {
518 $this->_storage->install_timestamp = WP_FS__SCRIPT_START_TIME;
519 }
520
521 if ( ! is_object( $this->_plugin ) ) {
522 $this->_plugin = FS_Plugin_Manager::instance( $this->_module_id )->get();
523 }
524
525 $this->_admin_notices = FS_Admin_Notices::instance(
526 $this->_slug . ( $this->is_theme() ? ':theme' : '' ),
527 /**
528 * Ensure that the admin notice will always have a title by using the stored plugin title if available and
529 * retrieving the title via the "get_plugin_name" method if there is no stored plugin title available.
530 *
531 * @author Leo Fajardo (@leorw)
532 * @since 1.2.2
533 */
534 ( is_object( $this->_plugin ) && isset( $this->_plugin->title ) ?
535 $this->_plugin->title :
536 $this->get_plugin_name()
537 ),
538 $this->get_unique_affix()
539 );
540
541 if ( 'true' === fs_request_get( 'fs_clear_api_cache' ) ||
542 fs_request_is_action( 'restart_freemius' )
543 ) {
544 FS_Api::clear_cache();
545 $this->_cache->clear();
546 }
547
548 $this->register_constructor_hooks();
549
550 /**
551 * Starting from version 2.0.0, `FS_Site` entities no longer have the `plan` property and have `plan_id`
552 * instead. This should be called before calling `_load_account()`, otherwise, `$this->_site` will not be
553 * loaded in `_load_account` for versions of SDK starting from 2.0.0.
554 *
555 * @author Leo Fajardo (@leorw)
556 */
557 self::migrate_install_plan_to_plan_id( $this->_storage );
558
559 $this->_load_account();
560
561 $this->_version_updates_handler();
562 }
563
564 /**
565 * @author Leo Fajardo (@leorw)
566 * @since 2.3.0
567 */
568 private function maybe_adjust_storage() {
569 $install_timestamp = null;
570 $prev_is_premium = null;
571
572 $options_to_update = array();
573
574 $is_network_admin = fs_is_network_admin();
575
576 $network_install_timestamp = $this->_storage->get( 'install_timestamp', null, true );
577
578 if ( ! $is_network_admin ) {
579 if ( is_null( $network_install_timestamp ) ) {
580 // Plugin was not network-activated before.
581 return;
582 }
583
584 if ( is_null( $this->_storage->get( 'install_timestamp', null, false ) ) ) {
585 // Set the `install_timestamp` only if it's not yet set.
586 $install_timestamp = $network_install_timestamp;
587 }
588
589 $prev_is_premium = $this->_storage->get( 'prev_is_premium', null, true );
590 } else {
591 $current_wp_user = self::_get_current_wp_user();
592 $current_fs_user = self::_get_user_by_email( $current_wp_user->user_email );
593 $network_user_info = array();
594
595 $skips_count = 0;
596
597 $sites = self::get_sites();
598 $sites_count = count( $sites );
599
600 $blog_id_2_install_map = array();
601
602 $is_first_non_ignored_blog = true;
603
604 foreach ( $sites as $site ) {
605 $blog_id = self::get_site_blog_id( $site );
606
607 $blog_install_timestamp = $this->_storage->get( 'install_timestamp', null, $blog_id );
608
609 if ( is_null( $blog_install_timestamp ) ) {
610 // Plugin has not been installed on this blog.
611 continue;
612 }
613
614 $is_earlier_install = (
615 ! is_null( $install_timestamp ) &&
616 $blog_install_timestamp < $install_timestamp
617 );
618
619 $install = $this->get_install_by_blog_id( $blog_id );
620
621 $update_network_user_info = false;
622
623 if ( ! is_object( $install ) ) {
624 if ( ! $this->_storage->get( 'is_anonymous', false, $blog_id ) ) {
625 // The opt-in decision (whether to skip or opt in) is yet to be made.
626 continue;
627 }
628
629 $skips_count ++;
630 } else {
631 $blog_id_2_install_map[ $blog_id ] = $install;
632
633 if ( empty( $network_user_info ) ) {
634 // Set the network user info for the 1st time. Choose any user information whether or not it is for the current WP user.
635 $update_network_user_info = true;
636 }
637
638 if ( ! $update_network_user_info &&
639 is_object( $current_fs_user ) &&
640 $network_user_info['user_id'] != $current_fs_user->id &&
641 $install->user_id == $current_fs_user->id
642 ) {
643 // If an install that is owned by the current WP user is found, use its user information instead.
644 $update_network_user_info = true;
645 }
646
647 if ( ! $update_network_user_info &&
648 $is_earlier_install &&
649 ( ! is_object( $current_fs_user ) || $current_fs_user->id == $install->user_id )
650 ) {
651 // 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.
652 $update_network_user_info = true;
653 }
654 }
655
656 if ( $update_network_user_info ) {
657 $network_user_info = array(
658 'user_id' => $install->user_id,
659 'blog_id' => $blog_id
660 );
661 }
662
663 $site_prev_is_premium = $this->_storage->get( 'prev_is_premium', null, $blog_id );
664
665 if ( $is_first_non_ignored_blog ) {
666 $prev_is_premium = $site_prev_is_premium;
667
668 if ( is_null( $network_install_timestamp ) ) {
669 $install_timestamp = $blog_install_timestamp;
670 }
671
672 $is_first_non_ignored_blog = false;
673
674 continue;
675 }
676
677 if ( ! is_null( $prev_is_premium ) && $prev_is_premium !== $site_prev_is_premium ) {
678 // If a different `$site_prev_is_premium` value is found, do not include the option in the collection of options to update.
679 $prev_is_premium = null;
680 }
681
682 if ( $is_earlier_install ) {
683 // If an earlier install timestamp is found.
684 $install_timestamp = $blog_install_timestamp;
685 }
686 }
687
688 $installs_count = count( $blog_id_2_install_map );
689
690 if ( $sites_count === ( $installs_count + $skips_count ) ) {
691 if ( ! empty( $network_user_info ) ) {
692 $options_to_update['network_user_id'] = $network_user_info['user_id'];
693 $options_to_update['network_install_blog_id'] = $network_user_info['blog_id'];
694
695 foreach ( $blog_id_2_install_map as $blog_id => $install ) {
696 if ( $install->user_id == $network_user_info['user_id'] ) {
697 continue;
698 }
699
700 $this->_storage->store( 'is_delegated_connection', true, $blog_id );
701 }
702 }
703
704 if ( $sites_count === $skips_count ) {
705 /**
706 * Assume network-level skipping as the intended action if all actions identified were only
707 * skipping of the connection (i.e., no opt-ins and delegated connections so far).
708 */
709 $options_to_update['is_anonymous_ms'] = true;
710 } else if ( $sites_count === $installs_count ) {
711 /**
712 * Assume network-level opt-in as the intended action if all actions identified were only opt-ins
713 * (i.e., no delegation and skipping of the connections so far).
714 */
715 $options_to_update['is_network_connected'] = true;
716 }
717 }
718 }
719
720 if ( ! is_null( $install_timestamp ) ) {
721 $options_to_update['install_timestamp'] = $install_timestamp;
722 }
723
724 if ( ! is_null( $prev_is_premium ) ) {
725 $options_to_update['prev_is_premium'] = $prev_is_premium;
726 }
727
728 if ( ! empty( $options_to_update ) ) {
729 $this->adjust_storage( $options_to_update, $is_network_admin );
730 }
731 }
732
733 /**
734 * @author Leo Fajardo (@leorw)
735 * @since 2.3.0
736 *
737 * @param array $options
738 * @param bool $is_network_admin
739 */
740 private function adjust_storage( $options, $is_network_admin ) {
741 foreach ( $options as $name => $value ) {
742 $this->_storage->store( $name, $value, $is_network_admin ? true : null );
743 }
744 }
745
746 /**
747 * Checks whether this module has a settings menu.
748 *
749 * @author Leo Fajardo (@leorw)
750 * @since 1.2.2
751 *
752 * @return bool
753 */
754 function has_settings_menu() {
755 return ( $this->_is_network_active && fs_is_network_admin() ) ?
756 $this->_menu->has_network_menu() :
757 $this->_menu->has_menu();
758 }
759
760 /**
761 * 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.
762 *
763 * @author Vova Feldman (@svovaf)
764 * @since 2.4.5
765 *
766 * @return bool
767 */
768 function show_opt_in_on_themes_page() {
769 if ( ! $this->is_free_wp_org_theme() ) {
770 return false;
771 }
772
773 if ( ! $this->has_settings_menu() ) {
774 return true;
775 }
776
777 return $this->show_settings_with_tabs();
778 }
779
780 /**
781 * If `true` the opt-in should be shown on the product's main setting page.
782 *
783 * @author Vova Feldman (@svovaf)
784 * @since 2.4.5
785 *
786 * @return bool
787 *
788 * @uses show_opt_in_on_themes_page();
789 */
790 function show_opt_in_on_setting_page() {
791 return ! $this->show_opt_in_on_themes_page();
792 }
793
794 /**
795 * If `true` the settings should be shown using tabs.
796 *
797 * @author Vova Feldman (@svovaf)
798 * @since 2.4.5
799 *
800 * @return bool
801 */
802 function show_settings_with_tabs() {
803 return ( self::NAVIGATION_TABS === $this->_navigation );
804 }
805
806 /**
807 * Check if the context module is free wp.org theme.
808 *
809 * This method is helpful because:
810 * 1. wp.org themes are limited to a single submenu item,
811 * and sub-submenu items are most likely not allowed (never verified).
812 * 2. wp.org themes are not allowed to redirect the user
813 * after the theme activation, therefore, the agreed UX
814 * is showing the opt-in as a modal dialog box after
815 * activation (approved by @otto42, @emiluzelac, @greenshady, @grapplerulrich).
816 *
817 * @author Vova Feldman (@svovaf)
818 * @since 1.2.2.7
819 *
820 * @return bool
821 */
822 function is_free_wp_org_theme() {
823 return (
824 $this->is_theme() &&
825 $this->is_org_repo_compliant() &&
826 ! $this->is_premium()
827 );
828 }
829
830 /**
831 * Checks whether this a submenu item is visible.
832 *
833 * @author Vova Feldman (@svovaf)
834 * @since 1.2.2.6
835 * @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.
836 *
837 * @param string $slug
838 * @param bool $is_tabs_visibility_check This is used to decide if the associated tab should be shown or hidden.
839 *
840 * @return bool
841 */
842 function is_submenu_item_visible( $slug, $is_tabs_visibility_check = false ) {
843 if ( $this->is_admin_page( $slug ) ) {
844 /**
845 * It is the current context page, so show the submenu item
846 * so the user will have the right context page, even if it
847 * was set to hidden.
848 */
849 return true;
850 }
851
852 if ( ! $this->has_settings_menu() ) {
853 // No menu settings at all.
854 return false;
855 }
856
857 if (
858 ! $is_tabs_visibility_check &&
859 $this->is_org_repo_compliant() &&
860 $this->show_settings_with_tabs()
861 ) {
862 /**
863 * wp.org themes are limited to a single submenu item, and
864 * sub-submenu items are most likely not allowed (never verified).
865 */
866 return false;
867 }
868
869 return $this->_menu->is_submenu_item_visible( $slug );
870 }
871
872 /**
873 * Check if a Freemius page should be accessible via the UI.
874 *
875 * @author Vova Feldman (@svovaf)
876 * @since 1.2.2.7
877 *
878 * @param string $slug
879 *
880 * @return bool
881 */
882 function is_page_visible( $slug ) {
883 if ( $this->is_admin_page( $slug ) ) {
884 return true;
885 }
886
887 return $this->_menu->is_submenu_item_visible( $slug, true, true );
888 }
889
890 /**
891 * @author Vova Feldman (@svovaf)
892 * @since 1.0.9
893 */
894 private function _version_updates_handler() {
895 if ( ! isset( $this->_storage->sdk_version ) || $this->_storage->sdk_version != $this->version ) {
896 // Freemius version upgrade mode.
897 $this->_storage->sdk_last_version = $this->_storage->sdk_version;
898 $this->_storage->sdk_version = $this->version;
899
900 if ( empty( $this->_storage->sdk_last_version ) ||
901 version_compare( $this->_storage->sdk_last_version, $this->version, '<' )
902 ) {
903 $this->_storage->sdk_upgrade_mode = true;
904 $this->_storage->sdk_downgrade_mode = false;
905 } else {
906 $this->_storage->sdk_downgrade_mode = true;
907 $this->_storage->sdk_upgrade_mode = false;
908
909 }
910
911 $this->do_action( 'sdk_version_update', $this->_storage->sdk_last_version, $this->version );
912 }
913
914 $plugin_version = $this->get_plugin_version();
915 if ( ! isset( $this->_storage->plugin_version ) || $this->_storage->plugin_version != $plugin_version ) {
916 // Plugin version upgrade mode.
917 $this->_storage->plugin_last_version = $this->_storage->plugin_version;
918 $this->_storage->plugin_version = $plugin_version;
919
920 if ( empty( $this->_storage->plugin_last_version ) ||
921 version_compare( $this->_storage->plugin_last_version, $plugin_version, '<' )
922 ) {
923 $this->_storage->plugin_upgrade_mode = true;
924 $this->_storage->plugin_downgrade_mode = false;
925 } else {
926 $this->_storage->plugin_downgrade_mode = true;
927 $this->_storage->plugin_upgrade_mode = false;
928 }
929
930 if ( ! empty( $this->_storage->plugin_last_version ) ) {
931 // Different version of the plugin was installed before, therefore it's an update.
932 $this->_storage->is_plugin_new_install = false;
933 }
934
935 $this->do_action( 'plugin_version_update', $this->_storage->plugin_last_version, $plugin_version );
936 }
937 }
938
939 #--------------------------------------------------------------------------------
940 #region Data Migration on SDK Update
941 #--------------------------------------------------------------------------------
942
943 /**
944 * @author Vova Feldman (@svovaf)
945 * @since 1.1.5
946 *
947 * @param string $sdk_prev_version
948 * @param string $sdk_version
949 */
950 function _sdk_version_update( $sdk_prev_version, $sdk_version ) {
951 if ( empty( $sdk_prev_version ) ) {
952 return;
953 }
954
955 if (
956 version_compare( $sdk_prev_version, '2.5.1', '<' ) &&
957 version_compare( $sdk_version, '2.5.1', '>=' )
958 ) {
959 if ( $this->is_registered( true ) ) {
960 /**
961 * Migrate to new permissions layer.
962 */
963 require_once WP_FS__DIR_INCLUDES . '/supplements/fs-migration-2.5.1.php';
964
965 $install_by_blog_id = is_multisite() ?
966 $this->get_blog_install_map() :
967 array( 0 => $this->_site );
968
969 fs_migrate_251( $this, $install_by_blog_id );
970 }
971 }
972 }
973
974 /**
975 * @author Leo Fajardo (@leorw)
976 * @since 2.0.0
977 *
978 * @param \FS_Storage $storage
979 * @param bool|int|null $blog_id
980 */
981 private static function migrate_install_plan_to_plan_id( FS_Storage $storage, $blog_id = null ) {
982 if ( empty( $storage->sdk_version ) ) {
983 // New installation of the plugin, no need to upgrade.
984 return;
985 }
986
987 if ( ! version_compare( $storage->sdk_version, '2.0.0', '<' ) ) {
988 // Previous version is >= 2.0.0, so no need to migrate.
989 return;
990 }
991
992 // Alias.
993 $module_type = $storage->get_module_type();
994 $module_slug = $storage->get_module_slug();
995
996 $installs = self::get_all_sites( $module_type, $blog_id );
997 $install = isset( $installs[ $module_slug ] ) ? $installs[ $module_slug ] : null;
998
999 if ( ! is_object( $install ) ) {
1000 return;
1001 }
1002
1003 if ( isset( $install->plan ) && is_object( $install->plan ) ) {
1004 if ( isset( $install->plan->id ) && ! empty( $install->plan->id ) ) {
1005 $install->plan_id = self::_decrypt( $install->plan->id );
1006 }
1007
1008 unset( $install->plan );
1009
1010 $installs[ $module_slug ] = clone $install;
1011
1012 self::set_account_option_by_module(
1013 $module_type,
1014 'sites',
1015 $installs,
1016 true,
1017 $blog_id
1018 );
1019 }
1020 }
1021
1022 /**
1023 * @author Vova Feldman (@svovaf)
1024 * @since 1.2.2.7
1025 *
1026 * @param string $plugin_prev_version
1027 * @param string $plugin_version
1028 */
1029 function _after_version_update( $plugin_prev_version, $plugin_version ) {
1030 if ( $this->is_theme() ) {
1031 // Expire the cache of the previous tabs since the theme may
1032 // have setting updates.
1033 $this->_cache->expire( 'tabs' );
1034 $this->_cache->expire( 'tabs_stylesheets' );
1035 }
1036 }
1037
1038 /**
1039 * A special migration logic for the $_accounts, executed for all the plugins in the system:
1040 * - Moves some data to the network level storage.
1041 * - If the plugin's connection was skipped for all sites, set the plugin as if it was network skipped.
1042 * - If the plugin's connection was ignored for all sites, don't do anything in terms of the network connection.
1043 * - 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.
1044 * - 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.
1045 * - 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.
1046 *
1047 * @author Vova Feldman (@svovaf)
1048 * @since 2.0.0
1049 */
1050 private static function migrate_accounts_to_network() {
1051 $sites = self::get_sites();
1052 $sites_count = count( $sites );
1053 $connection_status = array();
1054 $plugin_slugs = array();
1055 foreach ( $sites as $site ) {
1056 $blog_id = self::get_site_blog_id( $site );
1057
1058 self::$_accounts->migrate_to_network( $blog_id );
1059
1060 /**
1061 * Build a list of all Freemius powered plugins slugs.
1062 */
1063 $id_slug_type_path_map = self::$_accounts->get_option( 'id_slug_type_path_map', array(), $blog_id );
1064 foreach ( $id_slug_type_path_map as $module_id => $data ) {
1065 if ( WP_FS__MODULE_TYPE_PLUGIN === $data['type'] ) {
1066 $plugin_slugs[ $data['slug'] ] = true;
1067 }
1068 }
1069
1070 $installs = self::get_account_option( 'sites', WP_FS__MODULE_TYPE_PLUGIN, $blog_id );
1071
1072 if ( is_array( $installs ) ) {
1073 foreach ( $installs as $slug => $install ) {
1074 if ( ! isset( $connection_status[ $slug ] ) ) {
1075 $connection_status[ $slug ] = array();
1076 }
1077
1078 if ( is_object( $install ) &&
1079 FS_Site::is_valid_id( $install->id ) &&
1080 FS_User::is_valid_id( $install->user_id )
1081 ) {
1082 $connection_status[ $slug ][ $blog_id ] = $install->user_id;
1083 }
1084 }
1085 }
1086 }
1087
1088 foreach ( $plugin_slugs as $slug => $true ) {
1089 if ( ! isset( $connection_status[ $slug ] ) ) {
1090 $connection_status[ $slug ] = array();
1091 }
1092
1093 foreach ( $sites as $site ) {
1094 $blog_id = self::get_site_blog_id( $site );
1095
1096 if ( isset( $connection_status[ $slug ][ $blog_id ] ) ) {
1097 continue;
1098 }
1099
1100 $storage = FS_Storage::instance( WP_FS__MODULE_TYPE_PLUGIN, $slug );
1101
1102 $is_anonymous = $storage->get( 'is_anonymous', null, $blog_id );
1103
1104 if ( ! is_null( $is_anonymous ) ) {
1105 // Since 1.1.3 is_anonymous is an array.
1106 if ( is_array( $is_anonymous ) && isset( $is_anonymous['is'] ) ) {
1107 $is_anonymous = $is_anonymous['is'];
1108 }
1109
1110 if ( is_bool( $is_anonymous ) && true === $is_anonymous ) {
1111 $connection_status[ $slug ][ $blog_id ] = 'skipped';
1112 }
1113 }
1114
1115 if ( ! isset( $connection_status[ $slug ][ $blog_id ] ) ) {
1116 $connection_status[ $slug ][ $blog_id ] = 'ignored';
1117 }
1118 }
1119 }
1120
1121 $super_admins = array();
1122
1123 foreach ( $connection_status as $slug => $blogs_status ) {
1124 $skips = 0;
1125 $ignores = 0;
1126 $connections = 0;
1127 $opted_in_users = array();
1128 $opted_in_super_admins = array();
1129
1130 $storage = FS_Storage::instance( WP_FS__MODULE_TYPE_PLUGIN, $slug );
1131
1132 foreach ( $blogs_status as $blog_id => $status_or_user_id ) {
1133 if ( 'skipped' === $status_or_user_id ) {
1134 $skips ++;
1135 } else if ( 'ignored' === $status_or_user_id ) {
1136 $ignores ++;
1137 } else if ( FS_User::is_valid_id( $status_or_user_id ) ) {
1138 $connections ++;
1139
1140 if ( ! isset( $opted_in_users[ $status_or_user_id ] ) ) {
1141 $opted_in_users[ $status_or_user_id ] = array();
1142 }
1143
1144 $opted_in_users[ $status_or_user_id ][] = $blog_id;
1145
1146 if ( isset( $super_admins[ $status_or_user_id ] ) ||
1147 self::is_super_admin( $status_or_user_id )
1148 ) {
1149 // Cache super-admin data.
1150 $super_admins[ $status_or_user_id ] = true;
1151
1152 // Remember opted-in super-admins for the plugin.
1153 $opted_in_super_admins[ $status_or_user_id ] = true;
1154 }
1155 }
1156 }
1157
1158 $main_super_admin_user_id = null;
1159 $all_migrated = false;
1160 if ( $sites_count == $skips ) {
1161 // All sites were skipped -> network skip by copying the anonymous mode from any of the sites.
1162 $storage->is_anonymous_ms = $storage->is_anonymous;
1163
1164 $all_migrated = true;
1165 } else if ( $sites_count == $ignores ) {
1166 // Don't do anything, still in activation mode.
1167
1168 $all_migrated = true;
1169 } else if ( 0 < count( $opted_in_super_admins ) ) {
1170 // Find the super-admin with the majority of installs.
1171 $max_installs_by_super_admin = 0;
1172 foreach ( $opted_in_super_admins as $user_id => $true ) {
1173 $installs_count = count( $opted_in_users[ $user_id ] );
1174
1175 if ( $installs_count > $max_installs_by_super_admin ) {
1176 $max_installs_by_super_admin = $installs_count;
1177 $main_super_admin_user_id = $user_id;
1178 }
1179 }
1180
1181 if ( $sites_count == $connections && 1 == count( $opted_in_super_admins ) ) {
1182 // Super-admin opted-in for all sites in the network.
1183 $storage->is_network_connected = true;
1184
1185 $all_migrated = true;
1186 }
1187
1188 // Store network user.
1189 $storage->network_user_id = $main_super_admin_user_id;
1190
1191 $storage->network_install_blog_id = ( $sites_count == $connections ) ?
1192 // Since all sites are opted-in, associating with the main site.
1193 get_current_blog_id() :
1194 // Associating with the 1st found opted-in site.
1195 $opted_in_users[ $main_super_admin_user_id ][0];
1196
1197 /**
1198 * Make sure we migrate the plan ID of the network install, otherwise, if after the migration
1199 * the 1st page that will be loaded is the network level WP Admin and $storage->network_install_blog_id
1200 * is different than the main site of the network, the $this->_site will not be set since the plan_id
1201 * will be empty.
1202 */
1203 $storage->migrate_to_network();
1204 self::migrate_install_plan_to_plan_id( $storage, $storage->network_install_blog_id );
1205 } else {
1206 // At least one opt-in. All the opt-in were created by a non-super-admin.
1207 if ( 0 == $ignores ) {
1208 // All sites were opted-in or skipped, all by non-super-admin. So delegate all.
1209 $storage->store( 'is_delegated_connection', true, true );
1210
1211 $all_migrated = true;
1212 }
1213 }
1214
1215 if ( ! $all_migrated ) {
1216 /**
1217 * Delegate all sites that were:
1218 * 1) Opted-in by a user that is NOT the main-super-admin.
1219 * 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.
1220 */
1221 foreach ( $blogs_status as $blog_id => $status_or_user_id ) {
1222 if ( $status_or_user_id == $main_super_admin_user_id ) {
1223 continue;
1224 }
1225
1226 if ( FS_User::is_valid_id( $status_or_user_id ) ||
1227 ( 'skipped' === $status_or_user_id && is_null( $main_super_admin_user_id ) )
1228 ) {
1229 $storage->store( 'is_delegated_connection', true, $blog_id );
1230 }
1231 }
1232 }
1233
1234
1235 if ( ( $connections + $skips > 0 ) ) {
1236 if ( $ignores > 0 ) {
1237 /**
1238 * If admin already opted-in or skipped in any of the network sites, and also
1239 * have sites which the connection decision was not yet taken, set this plugin
1240 * into network activation mode so the super-admin can choose what to do with
1241 * the rest of the sites.
1242 */
1243 self::set_network_upgrade_mode( $storage );
1244 }
1245 }
1246 }
1247 }
1248
1249 /**
1250 * Set a module into network upgrade mode.
1251 *
1252 * @author Vova Feldman (@svovaf)
1253 * @since 2.0.0
1254 *
1255 * @param \FS_Storage $storage
1256 *
1257 * @return bool
1258 */
1259 public static function set_network_upgrade_mode( FS_Storage $storage ) {
1260 return $storage->is_network_activation = true;
1261 }
1262
1263 /**
1264 * Will return true after upgrading to the SDK with the network level integration,
1265 * when the super-admin involvement is required regarding the rest of the sites.
1266 *
1267 * @author Vova Feldman (@svovaf)
1268 * @since 2.0.0
1269 *
1270 * @return bool
1271 */
1272 function is_network_upgrade_mode() {
1273 return $this->_storage->get( 'is_network_activation' );
1274 }
1275
1276 /**
1277 * Clear flag after the upgrade mode completion.
1278 *
1279 * @author Vova Feldman (@svovaf)
1280 * @since 2.0.0
1281 *
1282 * @return bool True if network activation was on and now completed.
1283 */
1284 private function network_upgrade_mode_completed() {
1285 if ( fs_is_network_admin() && $this->is_network_upgrade_mode() ) {
1286 $this->_storage->remove( 'is_network_activation' );
1287
1288 return true;
1289 }
1290
1291 return false;
1292 }
1293
1294 #endregion
1295
1296 /**
1297 * This action is connected to the 'plugins_loaded' hook and helps to determine
1298 * if this is a new plugin installation or a plugin update.
1299 *
1300 * There are 3 different use-cases:
1301 * 1) New plugin installation right with Freemius:
1302 * 1.1 _activate_plugin_event_hook() will be executed first
1303 * 1.2 Since $this->_storage->is_plugin_new_install is not set,
1304 * and $this->_storage->plugin_last_version is not set,
1305 * $this->_storage->is_plugin_new_install will be set to TRUE.
1306 * 1.3 When _plugins_loaded() will be executed, $this->_storage->is_plugin_new_install will
1307 * be already set to TRUE.
1308 *
1309 * 2) Plugin update, didn't have Freemius before, and now have the SDK:
1310 * 2.1 _activate_plugin_event_hook() will not be executed, because
1311 * the activation hook do NOT fires on updates since WP 3.1.
1312 * 2.2 When _plugins_loaded() will be executed, $this->_storage->is_plugin_new_install will
1313 * be empty, therefore, it will be set to FALSE.
1314 *
1315 * 3) Plugin update, had Freemius in prev version as well:
1316 * 3.1 _version_updates_handler() will be executed 1st, since FS was installed
1317 * before, $this->_storage->plugin_last_version will NOT be empty,
1318 * therefore, $this->_storage->is_plugin_new_install will be set to FALSE.
1319 * 3.2 When _plugins_loaded() will be executed, $this->_storage->is_plugin_new_install is
1320 * already set, therefore, it will not be modified.
1321 *
1322 * Use-case #3 is backward compatible, #3.1 will be executed since 1.0.9.
1323 *
1324 * NOTE:
1325 * The only fallback of this mechanism is if an admin updates a plugin based on use-case #2,
1326 * and then, the next immediate PageView is the plugin's main settings page, it will not
1327 * show the opt-in right away. The reason it will happen is because Freemius execution
1328 * will be turned off till the plugin is fully loaded at least once
1329 * (till $this->_storage->was_plugin_loaded is TRUE).
1330 *
1331 * @author Vova Feldman (@svovaf)
1332 * @since 1.1.9
1333 *
1334 */
1335 function _plugins_loaded() {
1336 // Update flag that plugin was loaded with Freemius at least once.
1337 $this->_storage->was_plugin_loaded = true;
1338
1339 /**
1340 * Bug fix - only set to false when it's a plugin, due to the
1341 * execution sequence of the theme hooks and our methods, if
1342 * this will be set for themes, Freemius will always assume
1343 * it's a theme update.
1344 *
1345 * @author Vova Feldman (@svovaf)
1346 * @since 1.2.2.2
1347 */
1348 if ( $this->is_plugin() &&
1349 ! isset( $this->_storage->is_plugin_new_install )
1350 ) {
1351 $this->_storage->is_plugin_new_install = (
1352 ! is_plugin_active( $this->_plugin_basename ) &&
1353 empty( $this->_storage->plugin_last_version )
1354 );
1355 }
1356 }
1357
1358 function _run_garbage_collector() {
1359 if ( true !== fs_get_optional_constant( 'WP_FS__ENABLE_GARBAGE_COLLECTOR', true ) ) {
1360 return;
1361 }
1362
1363 if ( ! $this->is_user_in_admin() ) {
1364 return;
1365 }
1366
1367 require_once WP_FS__DIR_INCLUDES . '/class-fs-lock.php';
1368
1369 $lock = new FS_Lock( 'garbage_collection' );
1370
1371 if ( $lock->is_locked() ) {
1372 return;
1373 }
1374
1375 // Create a 1-day lock.
1376 $lock->lock( WP_FS__TIME_24_HOURS_IN_SEC );
1377
1378 FS_Garbage_Collector::instance()->clean();
1379 }
1380
1381 /**
1382 * Modifies all external links in the submenu by altering their href, and also opens them in new tab if needed.
1383 *
1384 * @author Vova Feldman (@svovaf)
1385 * @author Swashata Ghosh (@swashata)
1386 * @since 2.1.4
1387 */
1388 static function _handle_submenu_external_link() {
1389 ?>
1390 <script type="text/javascript">
1391 (function ( $ ) {
1392 $( '.fs-submenu-item' ).each( function () {
1393 var $this = $( this ),
1394 $parent = $this.parent(),
1395 externalLink = $this.data( 'fs-external-url' ),
1396 isOpensInNewTab = $this.data( 'fs-new-tab' );
1397
1398 if ( externalLink ) {
1399 $parent.attr( 'href', externalLink );
1400 }
1401
1402 if ( isOpensInNewTab ) {
1403 $parent.attr( { target: '_blank', rel: 'noopener noreferrer' } );
1404 }
1405 } );
1406 } )( jQuery );
1407 </script>
1408 <?php
1409 }
1410
1411 /**
1412 * @author Vova Feldman (@svovaf)
1413 * @since 1.0.9
1414 */
1415 private function register_constructor_hooks() {
1416 $this->_logger->entrance();
1417
1418 if ( is_admin() ) {
1419 add_action( 'admin_init', array( &$this, '_hook_action_links_and_register_account_hooks' ) );
1420
1421 if ( $this->is_plugin() ) {
1422 if ( self::is_plugin_install_page() && true !== fs_request_get_bool( 'fs_allow_updater_and_dialog' ) ) {
1423 /**
1424 * Unless the `fs_allow_updater_and_dialog` URL param exists and its value is `true`, make
1425 * Freemius-related updates unavailable on the "Add Plugins" admin page (/plugin-install.php)
1426 * so that they won't interfere with the .org plugins' functionalities on that page (e.g.
1427 * updating of a .org plugin).
1428 */
1429 add_filter( 'site_transient_update_plugins', array( 'Freemius', '_remove_fs_updates_from_plugin_install_page' ), 10, 2 );
1430 } else if ( self::is_plugins_page() || self::is_updates_page() ) {
1431 /**
1432 * 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.
1433 *
1434 * @author Leo Fajardo (@leorw)
1435 * @since 2.2.3
1436 */
1437 add_action( 'admin_footer', array( 'Freemius', '_prepend_fs_allow_updater_and_dialog_flag_url_param' ) );
1438 }
1439
1440 $plugin_dir = dirname( $this->_plugin_dir_path ) . '/';
1441
1442 /**
1443 * @since 1.2.2
1444 *
1445 * Hook to both free and premium version activations to support
1446 * auto deactivation on the other version activation.
1447 */
1448 register_activation_hook(
1449 $plugin_dir . $this->_free_plugin_basename,
1450 array( &$this, '_activate_plugin_event_hook' )
1451 );
1452
1453 register_activation_hook(
1454 $plugin_dir . $this->premium_plugin_basename(),
1455 array( &$this, '_activate_plugin_event_hook' )
1456 );
1457 } else {
1458 add_action( 'after_switch_theme', array( &$this, '_activate_theme_event_hook' ), 10, 2 );
1459
1460 add_action( 'admin_footer', array( &$this, '_style_premium_theme' ) );
1461 }
1462
1463 /**
1464 * Part of the mechanism to identify new plugin install vs. plugin update.
1465 *
1466 * @author Vova Feldman (@svovaf)
1467 * @since 1.1.9
1468 */
1469 if ( empty( $this->_storage->was_plugin_loaded ) ) {
1470 /**
1471 * During the plugin activation (not theme), 'plugins_loaded' will be already executed
1472 * when the logic gets here since the activation logic first add the activate plugins,
1473 * then triggers 'plugins_loaded', and only then include the code of the plugin that
1474 * is activated. Which means that _plugins_loaded() will NOT be executed during the
1475 * plugin activation, and that IS intentional.
1476 *
1477 * @author Vova Feldman (@svovaf)
1478 */
1479 if ( $this->is_plugin() &&
1480 $this->is_activation_mode( false ) &&
1481 0 == did_action( 'plugins_loaded' )
1482 ) {
1483 add_action( 'plugins_loaded', array( &$this, '_plugins_loaded' ) );
1484 } else {
1485 // If was activated before, then it was already loaded before.
1486 $this->_plugins_loaded();
1487 }
1488 }
1489
1490 add_action( 'plugins_loaded', array( &$this, '_run_garbage_collector' ) );
1491
1492 if ( ! self::is_ajax() ) {
1493 if ( ! $this->is_addon() ) {
1494 add_action( 'init', array( &$this, '_add_default_submenu_items' ), WP_FS__LOWEST_PRIORITY );
1495 }
1496 }
1497
1498 if ( $this->_storage->handle_gdpr_admin_notice ) {
1499 add_action( 'init', array( &$this, '_maybe_show_gdpr_admin_notice' ) );
1500 }
1501
1502 add_action( 'init', array( &$this, '_maybe_add_gdpr_optin_ajax_handler') );
1503 add_action( 'init', array( &$this, '_add_pricing_ajax_handler' ) );
1504 }
1505
1506 if ( $this->is_plugin() ) {
1507 if ( version_compare( $GLOBALS['wp_version'], '5.1', '<' ) ) {
1508 add_action( 'wpmu_new_blog', array( $this, '_after_new_blog_callback' ), 10, 6 );
1509 } else {
1510 add_action( 'wp_initialize_site', array( $this, '_after_wp_initialize_site_callback' ), 11, 2 );
1511 }
1512
1513 register_deactivation_hook( $this->_plugin_main_file_path, array( &$this, '_deactivate_plugin_hook' ) );
1514 }
1515
1516 if ( is_multisite() ) {
1517 add_action( 'deactivate_blog', array( &$this, '_after_site_deactivated_callback' ) );
1518 add_action( 'archive_blog', array( &$this, '_after_site_deactivated_callback' ) );
1519 add_action( 'make_spam_blog', array( &$this, '_after_site_deactivated_callback' ) );
1520
1521 if ( version_compare( $GLOBALS['wp_version'], '5.1', '<' ) ) {
1522 add_action( 'deleted_blog', array( $this, '_after_site_deleted_callback' ), 10, 2 );
1523 } else {
1524 add_action( 'wp_delete_site', array( $this, '_after_wpsite_deleted_callback' ) );
1525 }
1526
1527 add_action( 'activate_blog', array( &$this, '_after_site_reactivated_callback' ) );
1528 add_action( 'unarchive_blog', array( &$this, '_after_site_reactivated_callback' ) );
1529 add_action( 'make_ham_blog', array( &$this, '_after_site_reactivated_callback' ) );
1530 }
1531
1532 if ( $this->is_theme() &&
1533 self::is_customizer() &&
1534 $this->apply_filters( 'show_customizer_upsell', true )
1535 ) {
1536 // Register customizer upsell.
1537 add_action( 'customize_register', array( &$this, '_customizer_register' ) );
1538 }
1539
1540 add_action( 'admin_init', array( &$this, '_redirect_on_clicked_menu_link' ), WP_FS__LOWEST_PRIORITY );
1541
1542 if ( $this->is_theme() && ! $this->is_migration() ) {
1543 add_action( 'admin_init', array( &$this, '_add_tracking_links' ) );
1544 }
1545
1546 add_action( 'admin_init', array( &$this, '_add_license_activation' ) );
1547 add_action( 'admin_init', array( &$this, '_add_premium_version_upgrade_selection' ) );
1548 add_action( 'admin_init', array( &$this, '_add_beta_mode_update_handler' ) );
1549 add_action( 'admin_init', array( &$this, '_add_user_change_option' ) );
1550 add_action( 'admin_init', array( &$this, '_add_email_address_update_option' ) );
1551
1552 $this->add_ajax_action( 'update_billing', array( &$this, '_update_billing_ajax_action' ) );
1553 $this->add_ajax_action( 'start_trial', array( &$this, '_start_trial_ajax_action' ) );
1554 $this->add_ajax_action( 'set_data_debug_mode', array( &$this, '_set_data_debug_mode' ) );
1555 $this->add_ajax_action( 'toggle_whitelabel_mode', array( &$this, '_toggle_whitelabel_mode_ajax_handler' ) );
1556
1557 if ( $this->_is_network_active && fs_is_network_admin() ) {
1558 $this->add_ajax_action( 'network_activate', array( &$this, '_network_activate_ajax_action' ) );
1559 }
1560
1561 $this->add_ajax_action( 'install_premium_version', array(
1562 &$this,
1563 '_install_premium_version_ajax_action'
1564 ) );
1565
1566 $this->add_ajax_action( 'submit_affiliate_application', array( &$this, '_submit_affiliate_application' ) );
1567
1568 $this->add_action( 'after_plans_sync', array( &$this, '_check_for_trial_plans' ) );
1569
1570 $this->add_action( 'sdk_version_update', array( &$this, '_sdk_version_update' ), WP_FS__DEFAULT_PRIORITY, 2 );
1571
1572 $this->add_action(
1573 'plugin_version_update',
1574 array( &$this, '_after_version_update' ),
1575 WP_FS__DEFAULT_PRIORITY,
1576 2
1577 );
1578 $this->add_filter( 'after_code_type_change', array( &$this, '_after_code_type_change' ) );
1579
1580 add_action( 'admin_init', array( &$this, '_add_trial_notice' ) ); // @phpstan-ignore-line
1581 add_action( 'admin_init', array( &$this, '_add_affiliate_program_notice' ) ); // @phpstan-ignore-line
1582 add_action( 'admin_enqueue_scripts', array( &$this, '_enqueue_common_css' ) );
1583
1584 /**
1585 * Handle request to reset anonymous mode for `get_reconnect_url()` or reset the pending activation mode.
1586 *
1587 * @author Vova Feldman (@svovaf)
1588 * @since 1.2.1.5
1589 */
1590 if (
1591 (
1592 fs_request_is_action( 'reset_anonymous_mode' ) ||
1593 fs_request_is_action( 'reset_pending_activation_mode' )
1594 ) &&
1595 $this->get_unique_affix() === fs_request_get_raw( 'fs_unique_affix' )
1596 ) {
1597 add_action( 'admin_init', array( &$this, 'connect_again' ) );
1598 }
1599
1600 FS_DebugManager::register_hooks();
1601 }
1602
1603 /**
1604 * Register the required hooks right after the settings parse is completed.
1605 *
1606 * @author Vova Feldman (@svovaf)
1607 * @since 2.3.1
1608 */
1609 private function register_after_settings_parse_hooks() {
1610 if ( is_admin() &&
1611 $this->is_theme() &&
1612 $this->is_premium() &&
1613 ! $this->has_active_valid_license()
1614 ) {
1615 $this->add_ajax_action(
1616 'delete_theme_update_data',
1617 array( &$this, '_delete_theme_update_data_action' )
1618 );
1619 }
1620
1621 if ( $this->show_settings_with_tabs() ) {
1622 /**
1623 * Include the required hooks to capture the theme settings' page tabs
1624 * and cache them.
1625 *
1626 * @author Vova Feldman (@svovaf)
1627 * @since 1.2.2.7
1628 */
1629 if ( ! $this->_cache->has_valid( 'tabs' ) ) {
1630 add_action( 'admin_footer', array( &$this, '_tabs_capture' ) );
1631 // Add license activation AJAX callback.
1632 $this->add_ajax_action( 'store_tabs', array( &$this, '_store_tabs_ajax_action' ) );
1633
1634 add_action( 'admin_enqueue_scripts', array( &$this, '_store_tabs_styles' ), 9999999 );
1635 }
1636
1637 add_action(
1638 'admin_footer',
1639 array( &$this, '_add_freemius_tabs' ),
1640 /**
1641 * The tabs JS code must be executed after the tabs capture logic (_tabs_capture()).
1642 * That's why the priority is 11 while the tabs capture logic is added
1643 * with priority 10.
1644 *
1645 * @author Vova Feldman (@svovaf)
1646 */
1647 11
1648 );
1649 }
1650
1651 if ( ! self::is_ajax() ) {
1652 if ( ! $this->is_addon() || $this->is_only_premium() ) {
1653 add_action(
1654 ( $this->_is_network_active && fs_is_network_admin() ? 'network_' : '' ) . 'admin_menu',
1655 array( &$this, '_prepare_admin_menu' ),
1656 WP_FS__LOWEST_PRIORITY
1657 );
1658 }
1659 }
1660
1661 if (
1662 $this->is_user_in_admin() &&
1663 $this->is_parallel_activation() &&
1664 $this->_premium_plugin_basename !== $this->_premium_plugin_basename_from_parallel_activation
1665 ) {
1666 $this->_premium_plugin_basename = $this->_premium_plugin_basename_from_parallel_activation;
1667
1668 register_activation_hook(
1669 dirname( $this->_plugin_dir_path ) . '/' . $this->_premium_plugin_basename,
1670 array( &$this, '_activate_plugin_event_hook' )
1671 );
1672 }
1673 }
1674
1675 /**
1676 * Determines if a plugin is running in parallel activation mode.
1677 *
1678 * @author Leo Fajardo (@leorw)
1679 * @since 2.9.1
1680 *
1681 * @return bool
1682 */
1683 private function is_parallel_activation() {
1684 return ! empty( $this->_premium_plugin_basename_from_parallel_activation );
1685 }
1686
1687 /**
1688 * Makes Freemius-related updates unavailable on the "Add Plugins" admin page (/plugin-install.php) so that
1689 * they won't interfere with the .org plugins' functionalities on that page (e.g. updating of a .org plugin).
1690 *
1691 * @author Leo Fajardo (@leorw)
1692 * @since 2.2.3
1693 *
1694 * @param object $updates
1695 * @param string|null $transient
1696 *
1697 * @return object
1698 */
1699 static function _remove_fs_updates_from_plugin_install_page( $updates, $transient = null ) {
1700 if ( is_object( $updates ) && isset( $updates->response ) ) {
1701 foreach ( $updates->response as $file => $plugin ) {
1702 if ( isset( $plugin->package ) && false !== strpos( $plugin->package, 'api.freemius' ) ) {
1703 unset( $updates->response[ $file ] );
1704 }
1705 }
1706 }
1707
1708 return $updates;
1709 }
1710
1711 /**
1712 * Prepends the `fs_allow_updater_and_dialog` param to the plugin information URLs to tell the SDK to handle
1713 * the information that is shown on the plugin details dialog that is shown when the relevant link is clicked.
1714 *
1715 * @author Leo Fajardo (@leorw)
1716 * @since 2.2.3
1717 *
1718 * @return void
1719 */
1720 static function _prepend_fs_allow_updater_and_dialog_flag_url_param() {
1721 $slug_basename_map = array();
1722 foreach ( self::$_instances as $instance ) {
1723 if ( ! $instance->is_plugin() ) {
1724 continue;
1725 }
1726
1727 $slug_basename_map[ $instance->get_slug() ] = $instance->premium_plugin_basename();
1728 }
1729 ?>
1730 <script type="text/javascript">
1731 (function( $ ) {
1732 var slugBasenameMap = <?php echo json_encode( $slug_basename_map ) ?>;
1733 for ( var slug in slugBasenameMap ) {
1734 var basename = slugBasenameMap[ slug ];
1735
1736 // Try to get the plugin rows if on the "Plugins" page.
1737 var $pluginRows = $( '.wp-list-table.plugins tr[data-plugin="' + basename + '"]');
1738
1739 if ( 0 === $pluginRows.length ) {
1740 // Try to get the plugin rows if on the "Updates" page.
1741 var $pluginCheckbox = $( '#update-plugins-table input[type="checkbox"][value="' + basename + '"]' );
1742 if ( 0 !== $pluginCheckbox.length ) {
1743 $pluginRows = $pluginCheckbox.parents( 'tr:first' );
1744 }
1745 }
1746
1747 if ( 0 === $pluginRows.length ) {
1748 // No plugin rows found.
1749 continue;
1750 }
1751
1752 // Find the "View details" links and add the `fs_allow_updater_and_dialog` param to the URL.
1753 $pluginRows.find( 'a[href*="plugin-install.php?tab=plugin-information"]' ).each(function() {
1754 var $this = $( this ),
1755 href = $this.attr( 'href' ).replace( '?tab=', '?fs_allow_updater_and_dialog=true&tab=');
1756
1757 $this.attr( 'href', href );
1758 });
1759 }
1760 })( jQuery );
1761 </script>
1762 <?php
1763 }
1764
1765 /**
1766 * @author Leo Fajardo (@leorw)
1767 * @since 2.3.0
1768 */
1769 static function _maybe_add_beta_label_styles() {
1770 $has_any_beta_version = false;
1771
1772 foreach ( self::$_instances as $instance ) {
1773 if ( $instance->is_beta() ) {
1774 $has_any_beta_version = true;
1775 break;
1776 }
1777 }
1778
1779 if ( $has_any_beta_version ) {
1780 fs_enqueue_local_style( 'fs_plugins', '/admin/plugins.css' );
1781 }
1782 }
1783
1784 /**
1785 * @author Leo Fajardo (@leorw)
1786 * @since 2.3.0
1787 */
1788 static function _maybe_add_beta_label_to_plugins_and_handle_confirmation() {
1789 $beta_data = array();
1790
1791 foreach ( self::$_instances as $instance ) {
1792 if ( ! $instance->is_premium() ) {
1793 continue;
1794 }
1795
1796 /**
1797 * If there's an available beta version update, a confirmation message will be shown when the
1798 * "Update now" link on the "Plugins" or "Themes" page is clicked.
1799 */
1800 $has_beta_update = $instance->has_beta_update();
1801
1802 $is_beta = (
1803 // The "Beta" label is added separately for themes.
1804 $instance->is_plugin() &&
1805 $instance->is_beta()
1806 );
1807
1808 if ( ! $is_beta && ! $has_beta_update ) {
1809 continue;
1810 }
1811
1812 $beta_data[ $instance->get_plugin_basename() ] = array( 'is_installed_version_beta' => $is_beta );
1813
1814 if ( ! $has_beta_update ) {
1815 continue;
1816 }
1817
1818 $beta_data[ $instance->get_plugin_basename() ]['beta_version_update_confirmation_message'] = sprintf(
1819 '%s %s',
1820 sprintf(
1821 fs_esc_attr_inline(
1822 '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.',
1823 'beta-version-update-caution',
1824 $instance->get_slug()
1825 ),
1826 $instance->get_plugin_title()
1827 ),
1828 fs_esc_attr_inline( 'Would you like to proceed with the update?', 'update-confirmation', $instance->get_slug() )
1829 );
1830 }
1831
1832 if ( empty( $beta_data ) ) {
1833 return;
1834 }
1835 ?>
1836 <script type="text/javascript">
1837 ( function( $ ) {
1838 var betaData = <?php echo json_encode( $beta_data ) ?>;
1839
1840 for ( var pluginBasename in betaData ) {
1841 if ( ! betaData.hasOwnProperty( pluginBasename ) ) {
1842 continue;
1843 }
1844
1845 if ( ! betaData[ pluginBasename ].is_installed_version_beta ) {
1846 continue;
1847 }
1848
1849 var $parentContainer = $( '.wp-list-table.plugins tr[data-plugin="' + pluginBasename + '"]' );
1850 if ( 0 === $parentContainer.length ) {
1851 continue;
1852 }
1853
1854 $parentContainer.find( '.plugin-title > strong:first-child').append(
1855 '<span class="fs-tag fs-info"><?php fs_esc_js_echo_inline( 'Beta', 'beta' ) ?></span>'
1856 );
1857 }
1858
1859 setTimeout( function() {
1860 // Wait a little bit before adding the event handler, otherwise, it will be overridden by the core WP logic.
1861 $( '.plugins .update-message .update-link, .themes .theme .update-message' ).on( 'click', function() {
1862 var $parentContainer = $( this ).parents( 'tr:first' );
1863 pluginBasename = ( 0 !== $parentContainer.length ) ?
1864 $parentContainer.data( 'plugin' ) :
1865 $( this ).parents( '.theme:first' ).data( 'slug' );
1866
1867 if (
1868 betaData[ pluginBasename ] &&
1869 betaData[ pluginBasename ].beta_version_update_confirmation_message &&
1870 ! confirm( betaData[ pluginBasename ].beta_version_update_confirmation_message )
1871 ) {
1872 return false;
1873 }
1874 } );
1875 }, 20 );
1876 } )( jQuery );
1877 </script>
1878 <?php
1879 }
1880
1881 /**
1882 * Keeping the uninstall hook registered for free or premium plugin version may result to a fatal error that
1883 * could happen when a user tries to uninstall either version while one of them is still active. Uninstalling a
1884 * plugin will trigger inclusion of the free or premium version and if one of them is active during the
1885 * uninstallation, a fatal error may occur in case the plugin's class or functions are already defined.
1886 *
1887 * @author Leo Fajardo (@leorw)
1888 *
1889 * @since 1.2.0
1890 */
1891 private function unregister_uninstall_hook() {
1892 $uninstallable_plugins = (array) get_option( 'uninstall_plugins' );
1893 unset( $uninstallable_plugins[ $this->_free_plugin_basename ] );
1894 unset( $uninstallable_plugins[ $this->premium_plugin_basename() ] );
1895
1896 update_option( 'uninstall_plugins', $uninstallable_plugins );
1897 }
1898
1899 /**
1900 * @since 1.2.0 Invalidate module's main file cache, otherwise, FS_Plugin_Updater will not fetch updates.
1901 *
1902 * @param bool $store_prev_path
1903 */
1904 private function clear_module_main_file_cache( $store_prev_path = true ) {
1905 if ( ! isset( $this->_storage->plugin_main_file ) ||
1906 empty( $this->_storage->plugin_main_file->path )
1907 ) {
1908 return;
1909 }
1910
1911 if ( ! $store_prev_path ) {
1912 /**
1913 * Storing the previous path is not needed when clearing the cache after an SDK version update since
1914 * the main purpose of the cache clearing in that event is to correct a wrong plugin main file path
1915 * which causes data mix-up between plugins (e.g. titles and versions of an add-on and its parent plugin).
1916 *
1917 * @author Leo Fajardo (@leorw)
1918 * @since 2.2.1
1919 */
1920 unset( $this->_storage->plugin_main_file->path );
1921 } else {
1922 $plugin_main_file = clone $this->_storage->plugin_main_file;
1923
1924 // Store cached path (2nd layer cache).
1925 $plugin_main_file->prev_path = $plugin_main_file->path;
1926
1927 // Clear cached path.
1928 unset( $plugin_main_file->path );
1929
1930 $this->_storage->plugin_main_file = $plugin_main_file;
1931 }
1932
1933 /**
1934 * Clear global cached path.
1935 *
1936 * @author Leo Fajardo (@leorw)
1937 * @since 1.2.2
1938 */
1939 $id_slug_type_path_map = self::$_accounts->get_option( 'id_slug_type_path_map' );
1940 unset( $id_slug_type_path_map[ $this->_module_id ]['path'] );
1941 self::$_accounts->set_option( 'id_slug_type_path_map', $id_slug_type_path_map, true );
1942 }
1943
1944 /**
1945 * @author Leo Fajardo (@leorw)
1946 * @since 2.0.0
1947 */
1948 function _hook_action_links_and_register_account_hooks() {
1949 if ( $this->is_migration() ) {
1950 return;
1951 }
1952
1953 if (
1954 ( self::is_plugins_page() && $this->is_plugin() ) ||
1955 ( self::is_themes_page() && $this->is_theme() ) ||
1956 fs_request_is_action_secure( $this->get_unique_affix() . '_reconnect' )
1957 ) {
1958 $this->_add_tracking_links();
1959 }
1960
1961 if ( self::is_plugins_page() && $this->is_plugin() ) {
1962 $this->hook_plugin_action_links();
1963 }
1964
1965 $this->_register_account_hooks();
1966 }
1967
1968 /**
1969 * @author Vova Feldman (@svovaf)
1970 * @since 1.0.9
1971 */
1972 private function _register_account_hooks() {
1973 if ( ! is_admin() ) {
1974 return;
1975 }
1976
1977 /**
1978 * Always show the deactivation feedback form since we added
1979 * automatic free version deactivation upon premium code activation.
1980 *
1981 * @since 1.2.1.6
1982 */
1983 $this->add_ajax_action(
1984 'submit_uninstall_reason',
1985 array( &$this, '_submit_uninstall_reason_action' )
1986 );
1987
1988 $this->add_ajax_action(
1989 'cancel_subscription_or_trial',
1990 array( &$this, 'cancel_subscription_or_trial_ajax_action' )
1991 );
1992
1993 if ( ! $this->is_addon() || $this->is_parent_plugin_installed() ) {
1994 if ( ( $this->is_plugin() && self::is_plugins_page() ) ||
1995 ( $this->is_theme() && self::is_themes_page() )
1996 ) {
1997 add_action( 'admin_footer', array( &$this, '_add_deactivation_feedback_dialog_box' ) );
1998 }
1999 }
2000 }
2001
2002 /**
2003 * Leverage backtrace to find caller plugin file path.
2004 *
2005 * @param bool $is_init Is initiation sequence.
2006 * @param string $main_file Since 2.5.0 expects the module's main file path to potentially purge the cached path.
2007 *
2008 * @return string
2009 * @since 1.0.6
2010 *
2011 * @author Vova Feldman (@svovaf)
2012 */
2013 private function _find_caller_plugin_file( $is_init = false, $main_file = '' ) {
2014 // Try to load the cached value of the file path.
2015 if ( isset( $this->_storage->plugin_main_file ) ) {
2016 $plugin_main_file = $this->_storage->plugin_main_file;
2017 if ( ! empty( $plugin_main_file->path ) ) {
2018 $absolute_path = $this->get_absolute_path( $plugin_main_file->path );
2019 if ( file_exists( $absolute_path ) ) {
2020 if ( $is_init && $absolute_path !== $this->get_absolute_path( $main_file ) ) {
2021 // Update cached path if not matching the actual path.
2022 $plugin_main_file->path = $main_file;
2023 $this->_storage->plugin_main_file = $plugin_main_file;
2024 }
2025
2026 return $absolute_path;
2027 }
2028 }
2029 }
2030
2031 /**
2032 * @since 1.2.1
2033 *
2034 * `clear_module_main_file_cache()` is clearing the plugin's cached path on
2035 * deactivation. Therefore, if any plugin/theme was initiating `Freemius`
2036 * with that plugin's slug, it was overriding the empty plugin path with a wrong path.
2037 *
2038 * So, we've added a special mechanism with a 2nd layer of cache that uses `prev_path`
2039 * when the class instantiator isn't the module.
2040 */
2041 if ( ! $is_init ) {
2042 // Fetch prev path cache.
2043 if ( isset( $this->_storage->plugin_main_file ) &&
2044 ! empty( $this->_storage->plugin_main_file->prev_path )
2045 ) {
2046 $absolute_path = $this->get_absolute_path( $this->_storage->plugin_main_file->prev_path );
2047 if ( file_exists( $absolute_path ) ) {
2048 return $absolute_path;
2049 }
2050 }
2051
2052 wp_die(
2053 $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' ) .
2054 " Module: {$this->_slug}; SDK: " . WP_FS__SDK_VERSION . ";",
2055 $this->get_text_inline( 'Error', 'error' ),
2056 array( 'back_link' => true )
2057 );
2058 }
2059
2060 /**
2061 * @since 1.2.1
2062 *
2063 * Only the original instantiator that calls dynamic_init can modify the module's path.
2064 */
2065 // Find caller module.
2066 $this->_storage->plugin_main_file = (object) array(
2067 'path' => $main_file,
2068 );
2069
2070 return $this->get_absolute_path( $main_file );
2071 }
2072
2073 /**
2074 * @author Leo Fajardo (@leorw)
2075 * @since 1.2.3
2076 *
2077 * @param string $path
2078 *
2079 * @return string
2080 */
2081 private function get_relative_path( $path ) {
2082 $module_root_dir = $this->get_module_root_dir_path();
2083 if ( 0 === strpos( $path, $module_root_dir ) ) {
2084 $path = substr( $path, strlen( $module_root_dir ) );
2085 }
2086
2087 return $path;
2088 }
2089
2090 /**
2091 * @author Leo Fajardo (@leorw)
2092 * @since 1.2.3
2093 *
2094 * @param string $path
2095 * @param string|bool $module_type
2096 *
2097 * @return string
2098 */
2099 private function get_absolute_path( $path, $module_type = false ) {
2100 $module_root_dir = $this->get_module_root_dir_path( $module_type );
2101 if ( 0 !== strpos( $path, $module_root_dir ) ) {
2102 $path = fs_normalize_path( $module_root_dir . $path );
2103 }
2104
2105 return $path;
2106 }
2107
2108 /**
2109 * @author Leo Fajardo (@leorw)
2110 * @since 1.2.3
2111 *
2112 * @param string|bool $module_type
2113 *
2114 * @return string
2115 */
2116 private function get_module_root_dir_path( $module_type = false ) {
2117 $is_plugin = empty( $module_type ) ?
2118 $this->is_plugin() :
2119 ( WP_FS__MODULE_TYPE_PLUGIN === $module_type );
2120
2121 return fs_normalize_path( trailingslashit( $is_plugin ?
2122 WP_PLUGIN_DIR :
2123 get_theme_root( get_stylesheet() ) ) );
2124 }
2125
2126 /**
2127 * @author Leo Fajardo (@leorw)
2128 *
2129 * @param number $module_id
2130 * @param string $slug
2131 *
2132 * @return string Since 2.5.0 return the module's main file path.
2133 *
2134 * @since 1.2.2
2135 */
2136 private function store_id_slug_type_path_map( $module_id, $slug ) {
2137 $id_slug_type_path_map = self::$_accounts->get_option( 'id_slug_type_path_map', array() );
2138
2139 $store_option = false;
2140
2141 if ( ! isset( $id_slug_type_path_map[ $module_id ] ) ) {
2142 $id_slug_type_path_map[ $module_id ] = array(
2143 'slug' => $slug
2144 );
2145
2146 $store_option = true;
2147 } else if (
2148 isset( $id_slug_type_path_map[ $module_id ]['slug'] ) &&
2149 $slug !== $id_slug_type_path_map[ $module_id ]['slug']
2150 ) {
2151 $id_slug_type_path_map[ $module_id ]['slug'] = $slug;
2152 $store_option = true;
2153 }
2154
2155 $find_caller = empty( $id_slug_type_path_map[ $module_id ]['path'] );
2156
2157 if ( ! $find_caller ) {
2158 /**
2159 * This verification is for cases when suddenly the same module
2160 * is installed but with a different folder name.
2161 *
2162 * @author Vova Feldman (@svovaf)
2163 * @since 1.2.3
2164 */
2165 $find_caller = ! file_exists( $this->get_absolute_path(
2166 $id_slug_type_path_map[ $module_id ]['path'],
2167 $id_slug_type_path_map[ $module_id ]['type']
2168 ) );
2169 }
2170
2171 foreach ( $id_slug_type_path_map as $id => $data ) {
2172 if ( empty( $id ) ) {
2173 // Remove maps with empty module ID.
2174 unset( $id_slug_type_path_map[ $id ] );
2175 $store_option = true;
2176 continue;
2177 }
2178
2179 /**
2180 * 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.
2181 *
2182 * @author Vova Feldman (@svovaf)
2183 * @since 2.5.0
2184 */
2185 if ( ! $find_caller ) {
2186 if ( $id == $module_id ) {
2187 continue;
2188 }
2189
2190 if (
2191 isset( $data['path'] ) &&
2192 $data['path'] === $id_slug_type_path_map[ $module_id ]['path']
2193 ) {
2194 $find_caller = true;
2195 }
2196 }
2197 }
2198
2199 if ( $find_caller ) {
2200 $caller_main_file_and_type = $this->get_caller_main_file_and_type( $module_id );
2201
2202 $id_slug_type_path_map[ $module_id ]['type'] = $caller_main_file_and_type->module_type;
2203 $id_slug_type_path_map[ $module_id ]['path'] = $caller_main_file_and_type->path;
2204
2205 $store_option = true;
2206 }
2207
2208 if ( $store_option ) {
2209 self::$_accounts->set_option( 'id_slug_type_path_map', $id_slug_type_path_map, true );
2210 }
2211
2212 return $id_slug_type_path_map[ $module_id ]['path'];
2213 }
2214
2215 /**
2216 * Identifies the caller type: plugin or theme.
2217 *
2218 * @author Leo Fajardo (@leorw)
2219 * @since 1.2.2
2220 *
2221 * @author Vova Feldman (@svovaf)
2222 * @since 1.2.2.3 Find the earliest module in the call stack that calls to the SDK. This fix is for cases when
2223 * add-ons are relying on loading the SDK from the parent module, and also allows themes including the
2224 * SDK an internal file instead of directly from functions.php.
2225 * @since 1.2.1.7 Knows how to handle cases when an add-on includes the parent module logic.
2226 *
2227 * @param number $module_id @since 2.5.0
2228 */
2229 private function get_caller_main_file_and_type( $module_id ) {
2230 self::require_plugin_essentials();
2231
2232 $all_plugins = fs_get_plugins( true );
2233 $all_plugins_paths = array();
2234
2235 // Get active plugin's main files real full names (might be symlinks).
2236 foreach ( $all_plugins as $relative_path => $data ) {
2237 if ( false === strpos( fs_normalize_path( $relative_path ), '/' ) ) {
2238 /**
2239 * Ignore plugins that don't have a folder (e.g. Hello Dolly) since they
2240 * can't really include the SDK.
2241 *
2242 * @author Vova Feldman
2243 * @since 1.2.1.7
2244 */
2245 continue;
2246 }
2247
2248 $all_plugins_paths[] = fs_normalize_path( realpath( WP_PLUGIN_DIR . '/' . $relative_path ) );
2249 }
2250
2251 $caller_file_candidate = false;
2252 $caller_map = array();
2253 $module_type = WP_FS__MODULE_TYPE_PLUGIN;
2254 $themes_dir = fs_normalize_path( get_theme_root( get_stylesheet() ) );
2255 $plugin_dir_to_skip = false;
2256
2257 for ( $i = 1, $bt = debug_backtrace(), $len = count( $bt ); $i < $len; $i ++ ) {
2258 if ( empty( $bt[ $i ]['file'] ) ) {
2259 continue;
2260 }
2261
2262 if ( $i > 1 && ! empty( $bt[ $i - 1 ]['file'] ) && $bt[ $i ]['file'] === $bt[ $i - 1 ]['file'] ) {
2263 // If file same as the prev file in the stack, skip it.
2264 continue;
2265 }
2266
2267 if ( ! empty( $bt[ $i ]['function'] ) && in_array( $bt[ $i ]['function'], array(
2268 'do_action',
2269 'apply_filter',
2270 // The string split is stupid, but otherwise, theme check
2271 // throws info notices.
2272 'requir' . 'e_once',
2273 'requir' . 'e',
2274 'includ' . 'e_once',
2275 'includ' . 'e',
2276 'install_and_activate_plugin',
2277 'try_activate_plugin',
2278 'activate_plugin'
2279 ) )
2280 ) {
2281 if ( 'activate_plugin' === $bt[ $i ]['function'] ) {
2282 /**
2283 * Store the directory of the activator plugin so that any other file that starts with it
2284 * cannot be mistakenly chosen as a candidate caller file.
2285 *
2286 * @author Leo Fajardo
2287 *
2288 * @since 2.3.0
2289 */
2290 $caller_file_path = fs_normalize_path( $bt[ $i ]['file'] );
2291
2292 foreach ( $all_plugins_paths as $plugin_path ) {
2293 $plugin_dir = fs_normalize_path( dirname( $plugin_path ) . '/' );
2294 if ( false !== strpos( $caller_file_path, $plugin_dir ) ) {
2295 $plugin_dir_to_skip = $plugin_dir;
2296
2297 break;
2298 }
2299 }
2300 }
2301
2302 // Ignore call stack hooks and files inclusion.
2303 continue;
2304 }
2305
2306 $caller_file_path = fs_normalize_path( $bt[ $i ]['file'] );
2307
2308 if ( ! empty( $plugin_dir_to_skip ) ) {
2309 /**
2310 * Skip if it's an activator plugin file to avoid mistakenly choosing it as a candidate caller file.
2311 *
2312 * @author Leo Fajardo
2313 *
2314 * @since 2.3.0
2315 */
2316 if ( 0 === strpos( $caller_file_path, $plugin_dir_to_skip ) ) {
2317 continue;
2318 }
2319 }
2320
2321 if ( 'functions.php' === basename( $caller_file_path ) ) {
2322 /**
2323 * 1. Assumes that theme's starting execution file is functions.php.
2324 * 2. This complex logic fixes symlink issues (e.g. with Vargant).
2325 *
2326 * @author Vova Feldman (@svovaf)
2327 * @since 1.2.2.5
2328 */
2329
2330 if ( $caller_file_path == fs_normalize_path( realpath( trailingslashit( $themes_dir ) . basename( dirname( $caller_file_path ) ) . '/' . basename( $caller_file_path ) ) ) ) {
2331 $module_type = WP_FS__MODULE_TYPE_THEME;
2332
2333 /**
2334 * Relative path of the theme, e.g.:
2335 * `my-theme/functions.php`
2336 *
2337 * @author Leo Fajardo (@leorw)
2338 */
2339 $caller_file_candidate = basename( dirname( $caller_file_path ) ) .
2340 '/' .
2341 basename( $caller_file_path );
2342
2343 continue;
2344 }
2345 }
2346
2347 $caller_file_hash = md5( $caller_file_path );
2348
2349 if ( ! isset( $caller_map[ $caller_file_hash ] ) ) {
2350 foreach ( $all_plugins_paths as $plugin_path ) {
2351 if ( empty( $plugin_path ) ) {
2352 continue;
2353 }
2354
2355 if ( false !== strpos( $caller_file_path, fs_normalize_path( dirname( $plugin_path ) . '/' ) ) ) {
2356 $caller_map[ $caller_file_hash ] = fs_normalize_path( $plugin_path );
2357 break;
2358 }
2359 }
2360 }
2361
2362 if ( isset( $caller_map[ $caller_file_hash ] ) ) {
2363 $module_type = WP_FS__MODULE_TYPE_PLUGIN;
2364 $caller_file_candidate = plugin_basename( $caller_map[ $caller_file_hash ] );
2365 }
2366 }
2367
2368 $caller_main_file_and_type = (object) array(
2369 'module_type' => $module_type,
2370 'path' => $caller_file_candidate
2371 );
2372
2373 return apply_filters( "fs_{$module_id}_caller_main_file_and_type", $caller_main_file_and_type );
2374 }
2375
2376 #----------------------------------------------------------------------------------
2377 #region Deactivation Feedback Form
2378 #----------------------------------------------------------------------------------
2379
2380 /**
2381 * Displays a confirmation and feedback dialog box when the user clicks on the "Deactivate" link on the plugins
2382 * page.
2383 *
2384 * @author Vova Feldman (@svovaf)
2385 * @author Leo Fajardo (@leorw)
2386 *
2387 * @since 1.1.2
2388 */
2389 function _add_deactivation_feedback_dialog_box() {
2390 if (
2391 $this->is_clone() ||
2392 ( is_object( $this->_site ) && ! $this->is_registered() )
2393 ) {
2394 return;
2395 }
2396
2397 $subscription_cancellation_dialog_box_template_params = $this->apply_filters( 'show_deactivation_subscription_cancellation', true ) ?
2398 $this->_get_subscription_cancellation_dialog_box_template_params() :
2399 array();
2400
2401 /**
2402 * @since 2.3.0 Developers can optionally hide the deactivation feedback form using the 'show_deactivation_feedback_form' filter.
2403 */
2404 $show_deactivation_feedback_form = ! self::is_deactivation_snoozed();
2405 if ( $this->has_filter( 'show_deactivation_feedback_form' ) ) {
2406 $show_deactivation_feedback_form = $this->apply_filters( 'show_deactivation_feedback_form', true );
2407 } else if ( $this->is_addon() ) {
2408 /**
2409 * If the add-on's 'show_deactivation_feedback_form' is not set, try to inherit the value from the parent.
2410 */
2411 $show_deactivation_feedback_form = $this->get_parent_instance()->apply_filters( 'show_deactivation_feedback_form', true );
2412 }
2413
2414 $uninstall_confirmation_message = $this->apply_filters( 'uninstall_confirmation_message', '' );
2415
2416 if (
2417 empty( $subscription_cancellation_dialog_box_template_params ) &&
2418 ! $show_deactivation_feedback_form &&
2419 empty( $uninstall_confirmation_message )
2420 ) {
2421 return;
2422 }
2423
2424 $vars = array( 'id' => $this->_module_id );
2425
2426 if ( $show_deactivation_feedback_form ) {
2427 /* Check the type of user:
2428 * 1. Long-term (long-term)
2429 * 2. Non-registered and non-anonymous short-term (non-registered-and-non-anonymous-short-term).
2430 * 3. Short-term (short-term)
2431 */
2432 $is_long_term_user = true;
2433
2434 // Check if the site is at least 2 days old.
2435 $time_installed = $this->_storage->install_timestamp;
2436
2437 // Difference in seconds.
2438 $date_diff = time() - $time_installed;
2439
2440 // Convert seconds to days.
2441 $date_diff_days = floor( $date_diff / ( 60 * 60 * 24 ) );
2442
2443 if ( $date_diff_days < 2 ) {
2444 $is_long_term_user = false;
2445 }
2446
2447 $is_long_term_user = $this->apply_filters( 'is_long_term_user', $is_long_term_user );
2448
2449 if ( $is_long_term_user ) {
2450 $user_type = 'long-term';
2451 } else {
2452 if ( ! $this->is_registered() && ! $this->is_anonymous() ) {
2453 $user_type = 'non-registered-and-non-anonymous-short-term';
2454 } else {
2455 $user_type = 'short-term';
2456 }
2457 }
2458
2459 $uninstall_reasons = $this->_get_uninstall_reasons( $user_type );
2460
2461 $vars['reasons'] = $uninstall_reasons;
2462 }
2463
2464 $vars['subscription_cancellation_dialog_box_template_params'] = &$subscription_cancellation_dialog_box_template_params;
2465 $vars['show_deactivation_feedback_form'] = $show_deactivation_feedback_form;
2466 $vars['uninstall_confirmation_message'] = $uninstall_confirmation_message;
2467
2468 /**
2469 * Load the HTML template for the deactivation feedback dialog box.
2470 *
2471 * @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.
2472 */
2473 fs_require_template( 'forms/deactivation/form.php', $vars );
2474 }
2475
2476 /**
2477 * @author Leo Fajardo (@leorw)
2478 * @since 1.1.2
2479 *
2480 * @param string $user_type
2481 *
2482 * @return array The uninstall reasons for the specified user type.
2483 */
2484 function _get_uninstall_reasons( $user_type = 'long-term' ) {
2485 $module_type = $this->_module_type;
2486
2487 $internal_message_template_var = array(
2488 'id' => $this->_module_id
2489 );
2490
2491 $plan = $this->get_plan();
2492
2493 if ( $this->is_registered() && is_object( $plan ) && $plan->has_technical_support() ) {
2494 $contact_support_template = fs_get_template( 'forms/deactivation/contact.php', $internal_message_template_var );
2495 } else {
2496 $contact_support_template = '';
2497 }
2498
2499 $reason_found_better_plugin = array(
2500 'id' => self::REASON_FOUND_A_BETTER_PLUGIN,
2501 'text' => sprintf( $this->get_text_inline( 'I found a better %s', 'reason-found-a-better-plugin' ), $module_type ),
2502 'input_type' => 'textfield',
2503 'input_placeholder' => sprintf( $this->get_text_inline( "What's the %s's name?", 'placeholder-plugin-name' ), $module_type ),
2504 );
2505
2506 $reason_temporary_deactivation = array(
2507 'id' => self::REASON_TEMPORARY_DEACTIVATION,
2508 'text' => sprintf(
2509 $this->get_text_inline( "It's a temporary %s - I'm troubleshooting an issue", 'reason-temporary-x' ),
2510 strtolower( $this->is_plugin() ?
2511 $this->get_text_inline( 'Deactivation', 'deactivation' ) :
2512 $this->get_text_inline( 'Theme Switch', 'theme-switch' )
2513 )
2514 ),
2515 'input_type' => '',
2516 'input_placeholder' => ''
2517 );
2518
2519 $reason_other = array(
2520 'id' => self::REASON_OTHER,
2521 'text' => $this->get_text_inline( 'Other', 'reason-other' ),
2522 'input_type' => 'textfield',
2523 'input_placeholder' => ''
2524 );
2525
2526 $long_term_user_reasons = array(
2527 array(
2528 'id' => self::REASON_NO_LONGER_NEEDED,
2529 'text' => sprintf( $this->get_text_inline( 'I no longer need the %s', 'reason-no-longer-needed' ), $module_type ),
2530 'input_type' => '',
2531 'input_placeholder' => ''
2532 ),
2533 $reason_found_better_plugin,
2534 array(
2535 'id' => self::REASON_NEEDED_FOR_A_SHORT_PERIOD,
2536 'text' => sprintf( $this->get_text_inline( 'I only needed the %s for a short period', 'reason-needed-for-a-short-period' ), $module_type ),
2537 'input_type' => '',
2538 'input_placeholder' => ''
2539 ),
2540 array(
2541 'id' => self::REASON_BROKE_MY_SITE,
2542 'text' => sprintf( $this->get_text_inline( 'The %s broke my site', 'reason-broke-my-site' ), $module_type ),
2543 'input_type' => '',
2544 'input_placeholder' => '',
2545 'internal_message' => $contact_support_template
2546 ),
2547 array(
2548 'id' => self::REASON_SUDDENLY_STOPPED_WORKING,
2549 'text' => sprintf( $this->get_text_inline( 'The %s suddenly stopped working', 'reason-suddenly-stopped-working' ), $module_type ),
2550 'input_type' => '',
2551 'input_placeholder' => '',
2552 'internal_message' => $contact_support_template
2553 )
2554 );
2555
2556 if ( $this->is_paying() ) {
2557 $long_term_user_reasons[] = array(
2558 'id' => self::REASON_CANT_PAY_ANYMORE,
2559 'text' => $this->get_text_inline( "I can't pay for it anymore", 'reason-cant-pay-anymore' ),
2560 'input_type' => 'textfield',
2561 'input_placeholder' => $this->get_text_inline( 'What price would you feel comfortable paying?', 'placeholder-comfortable-price' )
2562 );
2563 }
2564
2565 $reason_dont_share_info = array(
2566 'id' => self::REASON_DONT_LIKE_TO_SHARE_MY_INFORMATION,
2567 'text' => $this->get_text_inline( "I don't like to share my information with you", 'reason-dont-like-to-share-my-information' ),
2568 'input_type' => '',
2569 'input_placeholder' => ''
2570 );
2571
2572 /**
2573 * If the current user has selected the "don't share data" reason in the deactivation feedback modal, inform the
2574 * user by showing additional message that he doesn't have to share data and can just choose to skip the opt-in
2575 * (the Skip button is included in the message to show). This message will only be shown if anonymous mode is
2576 * enabled and the user's account is currently not in pending activation state (similar to the way the Skip
2577 * button in the opt-in form is shown/hidden).
2578 */
2579 if ( $this->is_enable_anonymous() && ! $this->is_pending_activation() ) {
2580 $reason_dont_share_info['internal_message'] = fs_get_template( 'forms/deactivation/retry-skip.php', $internal_message_template_var );
2581 }
2582
2583 $uninstall_reasons = array(
2584 'long-term' => $long_term_user_reasons,
2585 'non-registered-and-non-anonymous-short-term' => array(
2586 array(
2587 'id' => self::REASON_DIDNT_WORK,
2588 'text' => sprintf( $this->get_text_inline( "The %s didn't work", 'reason-didnt-work' ), $module_type ),
2589 'input_type' => '',
2590 'input_placeholder' => ''
2591 ),
2592 $reason_dont_share_info,
2593 $reason_found_better_plugin
2594 ),
2595 'short-term' => array(
2596 array(
2597 'id' => self::REASON_COULDNT_MAKE_IT_WORK,
2598 'text' => $this->get_text_inline( "I couldn't understand how to make it work", 'reason-couldnt-make-it-work' ),
2599 'input_type' => '',
2600 'input_placeholder' => '',
2601 'internal_message' => $contact_support_template
2602 ),
2603 $reason_found_better_plugin,
2604 array(
2605 'id' => self::REASON_GREAT_BUT_NEED_SPECIFIC_FEATURE,
2606 '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 ),
2607 'input_type' => 'textarea',
2608 'input_placeholder' => $this->get_text_inline( 'What feature?', 'placeholder-feature' )
2609 ),
2610 array(
2611 'id' => self::REASON_NOT_WORKING,
2612 'text' => sprintf( $this->get_text_inline( 'The %s is not working', 'reason-not-working' ), $module_type ),
2613 'input_type' => 'textarea',
2614 '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' )
2615 ),
2616 array(
2617 'id' => self::REASON_NOT_WHAT_I_WAS_LOOKING_FOR,
2618 'text' => $this->get_text_inline( "It's not what I was looking for", 'reason-not-what-i-was-looking-for' ),
2619 'input_type' => 'textarea',
2620 'input_placeholder' => $this->get_text_inline( "What you've been looking for?", 'placeholder-what-youve-been-looking-for' )
2621 ),
2622 array(
2623 'id' => self::REASON_DIDNT_WORK_AS_EXPECTED,
2624 'text' => sprintf( $this->get_text_inline( "The %s didn't work as expected", 'reason-didnt-work-as-expected' ), $module_type ),
2625 'input_type' => 'textarea',
2626 'input_placeholder' => $this->get_text_inline( 'What did you expect?', 'placeholder-what-did-you-expect' )
2627 )
2628 )
2629 );
2630
2631 // Randomize the reasons for the current user type.
2632 shuffle( $uninstall_reasons[ $user_type ] );
2633
2634 // Keep the following reasons as the last items in the list.
2635 $uninstall_reasons[ $user_type ][] = $reason_temporary_deactivation;
2636 $uninstall_reasons[ $user_type ][] = $reason_other;
2637
2638 $uninstall_reasons = $this->apply_filters( 'uninstall_reasons', $uninstall_reasons );
2639
2640 return $uninstall_reasons[ $user_type ];
2641 }
2642
2643 /**
2644 * Called after the user has submitted his reason for deactivating the plugin.
2645 *
2646 * @author Leo Fajardo (@leorw)
2647 * @since 1.1.2
2648 */
2649 function _submit_uninstall_reason_action() {
2650 $this->_logger->entrance();
2651
2652 $this->check_ajax_referer( 'submit_uninstall_reason' );
2653
2654 $reason_id = fs_request_get( 'reason_id' );
2655
2656 // Check if the given reason ID is an unsigned integer.
2657 if ( ! ctype_digit( $reason_id ) ) {
2658 exit;
2659 }
2660
2661 $reason_info = trim( fs_request_get( 'reason_info', '' ) );
2662 if ( ! empty( $reason_info ) ) {
2663 $reason_info = substr( $reason_info, 0, 128 );
2664 }
2665
2666 $reason = (object) array(
2667 'id' => $reason_id,
2668 'info' => $reason_info,
2669 'is_anonymous' => fs_request_get_bool( 'is_anonymous' )
2670 );
2671
2672 $this->_storage->store( 'uninstall_reason', $reason );
2673
2674 if ( self::REASON_TEMPORARY_DEACTIVATION == $reason->id ) {
2675 $snooze_period = fs_request_get( 'snooze_period' );
2676
2677 if ( is_numeric( $snooze_period ) && 0 < $snooze_period ) {
2678 self::snooze_deactivation_form( (int) $snooze_period );
2679 }
2680 }
2681
2682 /**
2683 * If the module type is "theme", trigger the uninstall event here (on theme deactivation) since themes do
2684 * not support uninstall hook.
2685 *
2686 * @author Leo Fajardo (@leorw)
2687 * @since 1.2.2
2688 */
2689 if ( $this->is_theme() ) {
2690 if ( $this->is_premium() && ! $this->has_active_valid_license() ) {
2691 FS_Plugin_Updater::instance( $this )->delete_update_data();
2692 }
2693
2694 $this->_uninstall_plugin_event( false );
2695 $this->remove_sdk_reference();
2696 }
2697
2698 // Print '1' for successful operation.
2699 echo 1;
2700 exit;
2701 }
2702
2703 #--------------------------------------------------------------------------------
2704 #region Deactivation Feedback Snoozing
2705 #--------------------------------------------------------------------------------
2706
2707 /**
2708 * @author Vova Feldman (@svovaf)
2709 * @since 2.4.3
2710 *
2711 * @param int $period
2712 *
2713 * @return bool True if the value was set, false otherwise.
2714 */
2715 private static function snooze_deactivation_form( $period ) {
2716 return ( 0 < $period && self::reset_deactivation_snoozing( $period ) );
2717 }
2718
2719 /**
2720 * Check if deactivation feedback form is snoozed.
2721 *
2722 * @author Vova Feldman (@svovaf)
2723 * @since 2.4.3
2724 *
2725 * @return bool
2726 */
2727 static function is_deactivation_snoozed() {
2728 $is_snoozed = ( ! is_multisite() || fs_is_network_admin() ) ?
2729 get_transient( 'fs_snooze_period' ) :
2730 get_site_transient( 'fs_snooze_period' );
2731
2732
2733 return ( 'true' === $is_snoozed );
2734 }
2735
2736 /**
2737 * Reset deactivation snoozing. When `$period` is `0` will stop deactivation snoozing by deleting the transients. Otherwise, will set the transients for the selected period.
2738 *
2739 * @param int $period Period in seconds.
2740 *
2741 * @author Vova Feldman (@svovaf)
2742 * @since 2.4.3
2743 */
2744 public static function reset_deactivation_snoozing( $period = 0 ) {
2745 $value = ( 0 === $period ) ? null : 'true';
2746
2747 if ( ! is_multisite() || fs_is_network_admin() ) {
2748 return set_transient( 'fs_snooze_period', $value, $period );
2749 } else {
2750 return set_site_transient( 'fs_snooze_period', $value, $period );
2751 }
2752 }
2753
2754 /**
2755 * The deactivation snooze expiration UNIX timestamp (in sec).
2756 *
2757 * @author Vova Feldman (@svovaf)
2758 * @since 2.4.3
2759 *
2760 * @return int
2761 */
2762 static function deactivation_snooze_expires_at() {
2763 return ( ! is_multisite() || fs_is_network_admin() ) ?
2764 (int) get_option( '_transient_timeout_fs_snooze_period' ) :
2765 (int) get_site_option( '_site_transient_timeout_fs_snooze_period' );
2766 }
2767
2768 #endregion
2769
2770 /**
2771 * @author Leo Fajardo (@leorw)
2772 * @since 2.1.4
2773 */
2774 function cancel_subscription_or_trial_ajax_action() {
2775 $this->_logger->entrance();
2776
2777 $this->check_ajax_referer( 'cancel_subscription_or_trial' );
2778
2779 $result = $this->cancel_subscription_or_trial( fs_request_get( 'plugin_id', $this->get_id() ), false );
2780
2781 if ( $this->is_api_error( $result ) ) {
2782 $this->shoot_ajax_failure( $result->error->message );
2783 }
2784
2785 $this->shoot_ajax_success();
2786 }
2787
2788 /**
2789 * @author Leo Fajardo (@leorw)
2790 * @since 2.1.4
2791 *
2792 * @param number $plugin_id
2793 *
2794 * @return object
2795 */
2796 private function cancel_subscription_or_trial( $plugin_id ) {
2797 $fs = null;
2798 if ( $plugin_id == $this->get_id() ) {
2799 $fs = $this;
2800 } else if ( $this->is_addon_activated( $plugin_id ) ) {
2801 $fs = self::get_instance_by_id( $plugin_id );
2802 }
2803
2804 $result = null;
2805
2806 if ( ! is_null( $fs ) ) {
2807 $result = $fs->is_paid_trial() ?
2808 $fs->_cancel_trial() :
2809 $fs->_downgrade_site();
2810 }
2811
2812 return $result;
2813 }
2814
2815 /**
2816 * @author Leo Fajardo (@leorw)
2817 * @since 2.0.2
2818 */
2819 function _delete_theme_update_data_action() {
2820 FS_Plugin_Updater::instance( $this )->delete_update_data();
2821 }
2822
2823 #endregion
2824
2825 #----------------------------------------------------------------------------------
2826 #region Instance
2827 #----------------------------------------------------------------------------------
2828
2829 /**
2830 * Main singleton instance.
2831 *
2832 * @author Vova Feldman (@svovaf)
2833 * @since 1.0.0
2834 *
2835 * @param number $module_id
2836 * @param string|bool $slug
2837 * @param bool $is_init Is initiation sequence.
2838 *
2839 * @return Freemius|false
2840 */
2841 static function instance( $module_id, $slug = false, $is_init = false ) {
2842 if ( empty( $module_id ) ) {
2843 return false;
2844 }
2845
2846 /**
2847 * 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.
2848 */
2849 self::_load_required_static();
2850
2851 if ( ! is_numeric( $module_id ) ) {
2852 if ( ! $is_init && true === $slug ) {
2853 $is_init = true;
2854 }
2855
2856 $slug = $module_id;
2857
2858 $module = FS_Plugin_Manager::instance( $slug )->get();
2859
2860 if ( is_object( $module ) ) {
2861 $module_id = $module->id;
2862 }
2863 }
2864
2865 $key = 'm_' . $module_id;
2866
2867 if ( ! isset( self::$_instances[ $key ] ) ) {
2868 self::$_instances[ $key ] = new Freemius( $module_id, $slug, $is_init );
2869 }
2870
2871 return self::$_instances[ $key ];
2872 }
2873
2874 /**
2875 * @author Vova Feldman (@svovaf)
2876 * @since 1.0.6
2877 *
2878 * @param number $addon_id
2879 *
2880 * @return bool
2881 */
2882 private static function has_instance( $addon_id ) {
2883 return isset( self::$_instances[ 'm_' . $addon_id ] );
2884 }
2885
2886 /**
2887 * @author Leo Fajardo (@leorw)
2888 * @since 1.2.2
2889 *
2890 * @param string|number $id_or_slug
2891 * @param string $module_type
2892 *
2893 * @return number|false
2894 */
2895 private static function get_module_id( $id_or_slug, $module_type = WP_FS__MODULE_TYPE_PLUGIN ) {
2896 if ( is_numeric( $id_or_slug ) ) {
2897 return $id_or_slug;
2898 }
2899
2900 foreach ( self::$_instances as $instance ) {
2901 // Also check the module type since there can be a plugin and a theme with the same slug.
2902 if ( ( $module_type === $instance->get_module_type() ) && ( $id_or_slug === $instance->get_slug() ) ) {
2903 return $instance->get_id();
2904 }
2905 }
2906
2907 return false;
2908 }
2909
2910 /**
2911 * @author Vova Feldman (@svovaf)
2912 * @since 1.0.6
2913 *
2914 * @param number $id
2915 *
2916 * @return false|Freemius
2917 */
2918 static function get_instance_by_id( $id ) {
2919 return isset ( self::$_instances[ 'm_' . $id ] ) ?
2920 self::$_instances[ 'm_' . $id ] :
2921 false;
2922 }
2923
2924 /**
2925 *
2926 * @author Vova Feldman (@svovaf)
2927 * @since 1.0.1
2928 *
2929 * @param string $plugin_file
2930 * @param string $module_type
2931 *
2932 * @return false|Freemius
2933 */
2934 static function get_instance_by_file( $plugin_file, $module_type = WP_FS__MODULE_TYPE_PLUGIN ) {
2935 $slug = self::find_slug_by_basename( $plugin_file );
2936
2937 return ( false !== $slug ) ?
2938 self::instance( self::get_module_id( $slug, $module_type ) ) :
2939 false;
2940 }
2941
2942 /**
2943 * @author Vova Feldman (@svovaf)
2944 * @since 1.0.6
2945 *
2946 * @return false|Freemius
2947 */
2948 function get_parent_instance() {
2949 return self::get_instance_by_id( $this->_plugin->parent_plugin_id );
2950 }
2951
2952 /**
2953 * @author Vova Feldman (@svovaf)
2954 * @since 1.0.6
2955 *
2956 * @param string|number $id_or_slug
2957 *
2958 * @return false|Freemius
2959 */
2960 function get_addon_instance( $id_or_slug ) {
2961 $addon_id = self::get_module_id( $id_or_slug );
2962
2963 return self::instance( $addon_id );
2964 }
2965
2966 /**
2967 * @return Freemius[]
2968 */
2969 static function _get_all_instances() {
2970 return self::$_instances;
2971 }
2972
2973 #endregion ------------------------------------------------------------------
2974
2975 /**
2976 * @author Vova Feldman (@svovaf)
2977 * @since 1.0.6
2978 *
2979 * @return bool
2980 */
2981 function is_parent_plugin_installed() {
2982 $is_active = self::has_instance( $this->_plugin->parent_plugin_id );
2983
2984 if ( $is_active ) {
2985 return true;
2986 }
2987
2988 /**
2989 * Parent module might be a theme. If that's the case, the add-on's FS
2990 * instance will be loaded prior to the theme's FS instance, therefore,
2991 * we need to check if it's active with a "look ahead".
2992 *
2993 * @author Vova Feldman
2994 * @since 1.2.2.3
2995 */
2996 global $fs_active_plugins;
2997 if ( is_object( $fs_active_plugins ) && is_array( $fs_active_plugins->plugins ) ) {
2998 $active_theme = wp_get_theme();
2999
3000 foreach ( $fs_active_plugins->plugins as $sdk => $module ) {
3001 if ( WP_FS__MODULE_TYPE_THEME === $module->type ) {
3002 if ( $module->plugin_path == $active_theme->get_stylesheet() ) {
3003 // Parent module is a theme and it's currently active.
3004 return true;
3005 }
3006 }
3007 }
3008 }
3009
3010 return false;
3011 }
3012
3013 /**
3014 * Check if add-on parent plugin in activation mode.
3015 *
3016 * @author Vova Feldman (@svovaf)
3017 * @since 1.0.7
3018 *
3019 * @return bool
3020 */
3021 function is_parent_in_activation() {
3022 $parent_fs = $this->get_parent_instance();
3023 if ( ! is_object( $parent_fs ) ) {
3024 return false;
3025 }
3026
3027 return ( $parent_fs->is_activation_mode() );
3028 }
3029
3030 /**
3031 * Is plugin in activation mode.
3032 *
3033 * @author Vova Feldman (@svovaf)
3034 * @since 1.0.7
3035 *
3036 * @param bool $and_on
3037 *
3038 * @return bool
3039 */
3040 function is_activation_mode( $and_on = true ) {
3041 return fs_is_network_admin() ?
3042 $this->is_network_activation_mode( $and_on ) :
3043 $this->is_site_activation_mode( $and_on );
3044 }
3045
3046 /**
3047 * Is plugin in activation mode.
3048 *
3049 * @author Vova Feldman (@svovaf)
3050 * @since 1.0.7
3051 *
3052 * @param bool $and_on
3053 *
3054 * @return bool
3055 */
3056 function is_site_activation_mode( $and_on = true ) {
3057 return (
3058 ( $this->is_on() || ! $and_on ) &&
3059 (
3060 ( $this->is_premium() && true === $this->_storage->require_license_activation ) ||
3061 (
3062 ( ! $this->is_registered() ||
3063 ( $this->is_only_premium() && ! $this->has_features_enabled_license() ) ) &&
3064 ( ! $this->is_enable_anonymous() ||
3065 ( ! $this->is_anonymous() && ! $this->is_pending_activation() ) )
3066 )
3067 )
3068 );
3069 }
3070
3071 /**
3072 * Checks if the SDK in network activation mode.
3073 *
3074 * @author Leo Fajardo (@leorw)
3075 * @since 2.0.0
3076 *
3077 * @param bool $and_on
3078 *
3079 * @return bool
3080 */
3081 private function is_network_activation_mode( $and_on = true ) {
3082 if ( ! $this->_is_network_active ) {
3083 // Not network activated.
3084 return false;
3085 }
3086
3087 if ( $this->is_network_upgrade_mode() ) {
3088 // Special flag to enforce network activation mode to decide what to do with the sites that are not yet opted-in nor skipped.
3089 return true;
3090 }
3091
3092 if ( ! $this->is_site_activation_mode( $and_on ) ) {
3093 // 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.
3094 return false;
3095 }
3096
3097 if ( $this->is_network_delegated_connection() ) {
3098 // Super-admin delegated the connection to the site admins -> not activation mode.
3099 return false;
3100 }
3101
3102 if ( $this->is_network_anonymous() && true !== $this->_storage->require_license_activation ) {
3103 // Super-admin skipped the connection network wide -> not activation mode.
3104 return false;
3105 }
3106
3107 if ( $this->is_network_registered() ) {
3108 // Super-admin connected at least one site -> not activation mode.
3109 return false;
3110 }
3111
3112 return true;
3113 }
3114
3115 /**
3116 * Check if current page is the opt-in/pending-activation page.
3117 *
3118 * @author Vova Feldman (@svovaf)
3119 * @since 1.2.1.7
3120 *
3121 * @return bool
3122 */
3123 function is_activation_page() {
3124 if ( $this->_menu->is_activation_page( $this->show_opt_in_on_themes_page() ) ) {
3125 return true;
3126 }
3127
3128 if ( ! $this->is_activation_mode() ) {
3129 return false;
3130 }
3131
3132 // Check if current page is matching the activation page.
3133 return $this->is_matching_url( $this->get_activation_url() );
3134 }
3135
3136 /**
3137 * Check if URL path's are matching and that all querystring
3138 * arguments of the $sub_url exist in the $url with the same values.
3139 *
3140 * WARNING:
3141 * 1. This method doesn't check if the sub/domain are matching.
3142 * 2. Ignore case sensitivity.
3143 *
3144 * @author Vova Feldman (@svovaf)
3145 * @since 1.2.1.7
3146 *
3147 * @param string $sub_url
3148 * @param string $url If argument is not set, check if the sub_url matching the current's page URL.
3149 *
3150 * @return bool
3151 */
3152 private function is_matching_url( $sub_url, $url = '' ) {
3153 if ( empty( $url ) ) {
3154 $url = $_SERVER['REQUEST_URI'];
3155 }
3156
3157 $url = strtolower( $url );
3158 $sub_url = strtolower( $sub_url );
3159
3160 if ( parse_url( $sub_url, PHP_URL_PATH ) !== parse_url( $url, PHP_URL_PATH ) ) {
3161 // Different path - DO NOT OVERRIDE PAGE.
3162 return false;
3163 }
3164
3165 $url_params = fs_parse_url_params( $url );
3166 $sub_url_params = fs_parse_url_params( $sub_url );
3167
3168 foreach ( $sub_url_params as $key => $val ) {
3169 if ( ! isset( $url_params[ $key ] ) || $val != $url_params[ $key ] ) {
3170 // Not matching query string - DO NOT OVERRIDE PAGE.
3171 return false;
3172 }
3173 }
3174
3175 return true;
3176 }
3177
3178 /**
3179 * Get the basenames of all active plugins for specific blog. Including network activated plugins.
3180 *
3181 * @author Vova Feldman (@svovaf)
3182 * @since 2.0.0
3183 *
3184 * @param int $blog_id
3185 *
3186 * @return string[]
3187 */
3188 private static function get_active_plugins_basenames( $blog_id = 0 ) {
3189 if ( is_multisite() && $blog_id > 0 ) {
3190 $active_basenames = get_blog_option( $blog_id, 'active_plugins' );
3191 } else {
3192 $active_basenames = get_option( 'active_plugins' );
3193 }
3194
3195 if ( ! is_array( $active_basenames ) ) {
3196 $active_basenames = array();
3197 }
3198
3199 if ( is_multisite() ) {
3200 $network_active_basenames = get_site_option( 'active_sitewide_plugins' );
3201
3202 if ( is_array( $network_active_basenames ) && ! empty( $network_active_basenames ) ) {
3203 $active_basenames = array_merge( $active_basenames, array_keys( $network_active_basenames ) );
3204 }
3205 }
3206
3207 return $active_basenames;
3208 }
3209
3210 /**
3211 * @author Leo Fajardo (@leorw)
3212 * @since 2.3.0
3213 *
3214 * @param int $blog_id
3215 *
3216 * @return array
3217 */
3218 static function get_active_plugins_directories_map( $blog_id = 0 ) {
3219 $active_basenames = self::get_active_plugins_basenames( $blog_id );
3220
3221 $map = array();
3222
3223 foreach ( $active_basenames as $active_basename ) {
3224 $active_basename = fs_normalize_path( $active_basename );
3225
3226 if ( false === strpos( $active_basename, '/' ) ) {
3227 continue;
3228 }
3229
3230 $map[ dirname( $active_basename ) ] = true;
3231 }
3232
3233 return $map;
3234 }
3235
3236 /**
3237 * Get collection of all active plugins. Including network activated plugins.
3238 *
3239 * @author Vova Feldman (@svovaf)
3240 * @since 1.0.9
3241 *
3242 * @param int $blog_id Since 2.0.0
3243 *
3244 * @return array[string]array
3245 */
3246 private static function get_active_plugins( $blog_id = 0 ) {
3247 self::require_plugin_essentials();
3248
3249 $active_plugin = array();
3250 $all_plugins = fs_get_plugins();
3251 $active_plugins_basenames = self::get_active_plugins_basenames( $blog_id );
3252
3253 foreach ( $active_plugins_basenames as $plugin_basename ) {
3254 $active_plugin[ $plugin_basename ] = $all_plugins[ $plugin_basename ];
3255 }
3256
3257 return $active_plugin;
3258 }
3259
3260 /**
3261 * Get collection of all site active plugins for a specified blog.
3262 *
3263 * @author Vova Feldman (@svovaf)
3264 * @since 2.0.0
3265 *
3266 * @param int $blog_id
3267 *
3268 * @return array[string]array
3269 */
3270 private static function get_site_active_plugins( $blog_id = 0 ) {
3271 $active_basenames = ( is_multisite() && $blog_id > 0 ) ?
3272 get_blog_option( $blog_id, 'active_plugins' ) :
3273 get_option( 'active_plugins' );
3274
3275 $active = array();
3276
3277 if ( ! is_array( $active_basenames ) ) {
3278 return $active;
3279 }
3280
3281 foreach ( $active_basenames as $basename ) {
3282 $active[ $basename ] = array(
3283 'is_active' => true,
3284 'Version' => '1.0', // Dummy version.
3285 'slug' => self::get_plugin_slug( $basename ),
3286 );
3287 }
3288
3289 return $active;
3290 }
3291
3292 /**
3293 * Get collection of all plugins with their activation status for a specified blog.
3294 *
3295 * @author Vova Feldman (@svovaf)
3296 * @since 1.1.8
3297 *
3298 * @param int $blog_id Since 2.0.0
3299 *
3300 * @return array Key is the plugin file path and the value is an array of the plugin data.
3301 */
3302 private static function get_all_plugins( $blog_id = 0 ) {
3303 self::require_plugin_essentials();
3304
3305 $all_plugins = fs_get_plugins();
3306
3307 $active_plugins_basenames = self::get_active_plugins_basenames( $blog_id );
3308
3309 foreach ( $all_plugins as $basename => &$data ) {
3310 // By default set to inactive (next foreach update the active plugins).
3311 $data['is_active'] = false;
3312 // Enrich with plugin slug.
3313 $data['slug'] = self::get_plugin_slug( $basename );
3314 }
3315
3316 // Flag active plugins.
3317 foreach ( $active_plugins_basenames as $basename ) {
3318 if ( isset( $all_plugins[ $basename ] ) ) {
3319 $all_plugins[ $basename ]['is_active'] = true;
3320 }
3321 }
3322
3323 return $all_plugins;
3324 }
3325
3326 /**
3327 * Get collection of all plugins and if they are network level activated.
3328 *
3329 * @author Vova Feldman (@svovaf)
3330 * @since 2.0.0
3331 *
3332 * @return array Key is the plugin basename and the value is an array of the plugin data.
3333 */
3334 private static function get_network_plugins() {
3335 self::require_plugin_essentials();
3336
3337 $all_plugins = fs_get_plugins();
3338
3339 $network_active_basenames = is_multisite() ?
3340 get_site_option( 'active_sitewide_plugins' ) :
3341 array();
3342
3343 foreach ( $all_plugins as $basename => &$data ) {
3344 // By default set to inactive (next foreach update the active plugins).
3345 $data['is_active'] = false;
3346 // Enrich with plugin slug.
3347 $data['slug'] = self::get_plugin_slug( $basename );
3348 }
3349
3350 // Flag active plugins.
3351 foreach ( $network_active_basenames as $basename ) {
3352 if ( isset( $all_plugins[ $basename ] ) ) {
3353 $all_plugins[ $basename ]['is_active'] = true;
3354 }
3355 }
3356
3357 return $all_plugins;
3358 }
3359
3360 /**
3361 * Cached result of get_site_transient( 'update_plugins' )
3362 *
3363 * @author Vova Feldman (@svovaf)
3364 * @since 1.1.8
3365 *
3366 * @var object
3367 */
3368 private static $_plugins_info;
3369
3370 /**
3371 * Helper function to get specified plugin's slug.
3372 *
3373 * @author Vova Feldman (@svovaf)
3374 * @since 1.1.8
3375 *
3376 * @param $basename
3377 *
3378 * @return string
3379 */
3380 private static function get_plugin_slug( $basename ) {
3381 if ( ! isset( self::$_plugins_info ) ) {
3382 self::$_plugins_info = get_site_transient( 'update_plugins' );
3383 }
3384
3385 $slug = '';
3386
3387 if ( is_object( self::$_plugins_info ) ) {
3388 if ( isset( self::$_plugins_info->no_update ) &&
3389 isset( self::$_plugins_info->no_update[ $basename ] ) &&
3390 ! empty( self::$_plugins_info->no_update[ $basename ]->slug )
3391 ) {
3392 $slug = self::$_plugins_info->no_update[ $basename ]->slug;
3393 } else if ( isset( self::$_plugins_info->response ) &&
3394 isset( self::$_plugins_info->response[ $basename ] ) &&
3395 ! empty( self::$_plugins_info->response[ $basename ]->slug )
3396 ) {
3397 $slug = self::$_plugins_info->response[ $basename ]->slug;
3398 }
3399 }
3400
3401 if ( empty( $slug ) ) {
3402 // Try to find slug from FS data.
3403 $slug = self::find_slug_by_basename( $basename );
3404 }
3405
3406 if ( empty( $slug ) ) {
3407 // Fallback to plugin's folder name.
3408 $slug = dirname( $basename );
3409 }
3410
3411 return $slug;
3412 }
3413
3414 private static $_statics_loaded = false;
3415
3416 /**
3417 * Load static resources.
3418 *
3419 * @author Vova Feldman (@svovaf)
3420 * @since 1.0.1
3421 */
3422 private static function _load_required_static() {
3423 if ( self::$_statics_loaded ) {
3424 return;
3425 }
3426
3427 self::$_static_logger = FS_Logger::get_logger( WP_FS__SLUG, WP_FS__DEBUG_SDK, WP_FS__ECHO_DEBUG_SDK );
3428
3429 self::$_static_logger->entrance();
3430
3431 self::$_accounts = FS_Options::instance( WP_FS__ACCOUNTS_OPTION_NAME, true );
3432
3433 if ( is_multisite() ) {
3434 $has_skipped_migration = (
3435 // 'id_slug_type_path_map' - was never stored on older versions, therefore, not exists on the site level.
3436 null === self::$_accounts->get_option( 'id_slug_type_path_map', null, false ) &&
3437 // 'file_slug_map' stored on the site level, so it was running an SDK version before it was integrated with MS-network.
3438 null !== self::$_accounts->get_option( 'file_slug_map', null, false )
3439 );
3440
3441 /**
3442 * If the file_slug_map exists on the site level but doesn't exist on the
3443 * network level storage, it means that we need to process the storage with migration.
3444 *
3445 * 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.
3446 *
3447 * @author Vova Feldman (@svovaf)
3448 * @since 2.0.0
3449 */
3450 if (
3451 ( $has_skipped_migration && true !== self::$_accounts->get_option( 'ms_migration_complete', false, true ) ) ||
3452 ( null === self::$_accounts->get_option( 'file_slug_map', null, true ) &&
3453 null !== self::$_accounts->get_option( 'file_slug_map', null, false ) )
3454 ) {
3455 self::migrate_options_to_network();
3456 }
3457 }
3458
3459 self::$_global_admin_notices = FS_Admin_Notices::instance( 'global' );
3460
3461 FS_DebugManager::load_required_static();
3462
3463 if ( 0 == did_action( 'plugins_loaded' ) ) {
3464 add_action( 'plugins_loaded', array( 'Freemius', '_load_textdomain' ), 1 );
3465 }
3466
3467 $clone_manager = FS_Clone_Manager::instance();
3468 add_action( 'init', array( $clone_manager, '_init' ) );
3469
3470 add_action( 'admin_footer', array( 'Freemius', '_handle_submenu_external_link' ) );
3471
3472 if ( self::is_plugins_page() || self::is_themes_page() ) {
3473 add_action( 'admin_print_footer_scripts', array( 'Freemius', '_maybe_add_beta_label_styles' ), 9 );
3474
3475 /**
3476 * Specifically use this hook so that the JS event handlers will work properly on the "Themes"
3477 * page.
3478 *
3479 * @author Leo Fajardo (@leorw)
3480 * @since 2.3.0
3481 */
3482 add_action( 'admin_footer-' . self::get_current_page(), array( 'Freemius', '_maybe_add_beta_label_to_plugins_and_handle_confirmation') );
3483 }
3484
3485 self::$_statics_loaded = true;
3486 }
3487
3488 public static function get_static_logger() {
3489 return self::$_static_logger;
3490 }
3491
3492 public static function get_accounts() {
3493 return self::$_accounts;
3494 }
3495
3496 #--------------------------------------------------------------------------------
3497 #region Clone
3498 #--------------------------------------------------------------------------------
3499
3500 /**
3501 * @author Leo Fajardo (@leorw)
3502 * @since 2.5.0
3503 *
3504 * @param bool $only_if_manual_resolution_is_not_hidden
3505 *
3506 * @return bool
3507 */
3508 private function is_unresolved_clone( $only_if_manual_resolution_is_not_hidden = false ) {
3509 if ( ! $this->is_clone( $only_if_manual_resolution_is_not_hidden ) ) {
3510 return false;
3511 }
3512
3513 return FS_Clone_Manager::instance()->has_temporary_duplicate_mode_expired();
3514 }
3515
3516 /**
3517 * @author Leo Fajardo (@leorw)
3518 * @since 2.5.0
3519 *
3520 * @param bool $only_if_manual_resolution_is_not_hidden
3521 */
3522 function is_clone( $only_if_manual_resolution_is_not_hidden = false ) {
3523 if ( ! is_object( $this->_site ) ) {
3524 return false;
3525 }
3526
3527 $blog_id = null;
3528
3529 if (
3530 fs_is_network_admin() &&
3531 FS_Site::is_valid_id( $this->_storage->network_install_blog_id )
3532 ) {
3533 // Ensure that we're comparing the network install's URL with the relevant subsite's URL.
3534 $blog_id = $this->_storage->network_install_blog_id;
3535 }
3536
3537 $site_url = Freemius::get_unfiltered_site_url( $blog_id, true, true );
3538
3539 if ( ! $this->_site->is_clone( $site_url ) ) {
3540 return false;
3541 }
3542
3543 return (
3544 ! $only_if_manual_resolution_is_not_hidden ||
3545 ! FS_Clone_Manager::instance()->should_hide_manual_resolution()
3546 );
3547 }
3548
3549 /**
3550 * @author Leo Fajardo (@leorw)
3551 * @since 2.5.0
3552 *
3553 * @param int|null $blog_id
3554 * @param bool $strip_protocol
3555 * @param bool $add_trailing_slash
3556 *
3557 * @return string
3558 */
3559 static function get_unfiltered_site_url( $blog_id = null, $strip_protocol = false, $add_trailing_slash = false ) {
3560 $url = ( ! is_multisite() && defined( 'WP_SITEURL' ) ) ? WP_SITEURL : self::get_site_url_from_wp_option( $blog_id );
3561
3562 if ( $strip_protocol ) {
3563 $url = fs_strip_url_protocol( $url );
3564 }
3565
3566 if ( $add_trailing_slash ) {
3567 $url = trailingslashit( $url );
3568 }
3569
3570 return $url;
3571 }
3572
3573 /**
3574 * @author Leo Fajardo (@leorw)
3575 * @since 2.6.0
3576 *
3577 * @param int|null $blog_id
3578 *
3579 * @return string
3580 */
3581 private static function get_site_url_from_wp_option( $blog_id = null ) {
3582 global $wp_filter;
3583
3584 $site_url_filters = array(
3585 'site_url' => null,
3586 'pre_option_siteurl' => null,
3587 'default_option_siteurl' => null,
3588 'option_siteurl' => null,
3589 );
3590
3591 // Detach all URL-related filters to get the actual site's URL (stripped of potential manipulations by multilingual plugins).
3592 foreach ( $site_url_filters as $hook_name => $site_url_filter ) {
3593 if ( ! empty( $wp_filter[ $hook_name ] ) ) {
3594 $site_url_filters[ $hook_name ] = $wp_filter[ $hook_name ];
3595 unset( $wp_filter[ $hook_name ] );
3596 }
3597 }
3598
3599 $url = get_site_url( $blog_id );
3600
3601 // Re-attach the filters back.
3602 foreach ( $site_url_filters as $hook_name => $site_url_filter ) {
3603 if ( ! empty( $site_url_filter ) ) {
3604 $wp_filter[ $hook_name ] = $site_url_filter;
3605 }
3606 }
3607
3608 return $url;
3609 }
3610
3611 /**
3612 * @author Leo Fajardo (@leorw)
3613 * @since 2.5.0
3614 *
3615 * @param number $site_id
3616 */
3617 function fetch_install_by_id( $site_id ) {
3618 return $this->get_current_or_network_user_api_scope()->get( "/installs/{$site_id}.json" );
3619 }
3620
3621 /**
3622 * @author Leo Fajardo (@leorw)
3623 * @since 2.5.0
3624 *
3625 * @return string|object|bool
3626 */
3627 function _handle_long_term_duplicate() {
3628 $this->_logger->entrance();
3629
3630 $this->delete_current_install( false );
3631
3632 $license = null;
3633
3634 if (
3635 is_object( $this->_license ) &&
3636 ! $this->_license->is_utilized(
3637 ( WP_FS__IS_LOCALHOST_FOR_SERVER || FS_Site::is_localhost_by_address( self::get_unfiltered_site_url() ) )
3638 )
3639 ) {
3640 $license = $this->_license;
3641 }
3642
3643 return $this->opt_in(
3644 false,
3645 false,
3646 false,
3647 ( is_object( $license ) ? $license->secret_key : false ),
3648 false,
3649 false,
3650 false,
3651 null,
3652 array(),
3653 false,
3654 ( is_object( $license ) ? $license->user_id : null )
3655 );
3656 }
3657
3658 #endregion
3659
3660 /**
3661 * @author Leo Fajardo (@leorw)
3662 *
3663 * @since 2.1.3
3664 */
3665 public static function migrate_options_to_network() {
3666 self::migrate_accounts_to_network();
3667
3668 // Migrate API options from site level to network level.
3669 $api_network_options = FS_Option_Manager::get_manager( WP_FS__OPTIONS_OPTION_NAME, true, true );
3670 $api_network_options->migrate_to_network();
3671
3672 // Migrate API cache to network level storage.
3673 FS_Cache_Manager::get_manager( WP_FS__API_CACHE_OPTION_NAME )->migrate_to_network();
3674
3675 self::$_accounts->set_option( 'ms_migration_complete', true, true );
3676 }
3677
3678 #----------------------------------------------------------------------------------
3679 #region Localization
3680 #----------------------------------------------------------------------------------
3681
3682 /**
3683 * Load framework's text domain.
3684 *
3685 * @author Vova Feldman (@svovaf)
3686 * @since 1.2.1
3687 */
3688 static function _load_textdomain() {
3689 if ( ! is_admin() ) {
3690 return;
3691 }
3692
3693 global $fs_active_plugins;
3694
3695 // Works both for plugins and themes.
3696 load_plugin_textdomain(
3697 'freemius',
3698 false,
3699 $fs_active_plugins->newest->sdk_path . '/languages/'
3700 );
3701 }
3702
3703 #endregion
3704
3705 #----------------------------------------------------------------------------------
3706 #region Connectivity Issues
3707 #----------------------------------------------------------------------------------
3708
3709 /**
3710 * Check if Freemius should be turned on for the current plugin install.
3711 *
3712 * Note:
3713 * $this->_is_on is updated in has_api_connectivity()
3714 *
3715 * @author Vova Feldman (@svovaf)
3716 * @since 1.0.9
3717 *
3718 * @return bool
3719 */
3720 function is_on() {
3721 self::$_static_logger->entrance();
3722
3723 if ( is_object( $this->_site ) && ! $this->is_registered() ) {
3724 return false;
3725 }
3726
3727 if ( isset( $this->_is_on ) ) {
3728 return $this->_is_on;
3729 }
3730
3731 // If already installed or pending then sure it's on :)
3732 if ( $this->is_registered() || $this->is_pending_activation() ) {
3733 $this->_is_on = true;
3734
3735 return true;
3736 }
3737
3738 return false;
3739 }
3740
3741 /**
3742 * @author Vova Feldman (@svovaf)
3743 * @since 1.1.7.3
3744 *
3745 * @param bool $flush_if_no_connectivity
3746 *
3747 * @return bool
3748 */
3749 private function should_run_connectivity_test( $flush_if_no_connectivity = false ) {
3750 if ( ! isset( $this->_storage->connectivity_test ) ) {
3751 // Connectivity test was never executed, or cache was cleared.
3752 return true;
3753 }
3754
3755 if ( WP_FS__PING_API_ON_IP_OR_HOST_CHANGES ) {
3756 if ( WP_FS__IS_HTTP_REQUEST ) {
3757 if ( $_SERVER['HTTP_HOST'] != $this->_storage->connectivity_test['host'] ) {
3758 // Domain changed.
3759 return true;
3760 }
3761
3762 if ( WP_FS__REMOTE_ADDR != $this->_storage->connectivity_test['server_ip'] ) {
3763 // Server IP changed.
3764 return true;
3765 }
3766 }
3767 }
3768
3769 if ( $this->_storage->connectivity_test['is_connected'] &&
3770 $this->_storage->connectivity_test['is_active']
3771 ) {
3772 // API connected and Freemius is active - no need to run connectivity check.
3773 return false;
3774 }
3775
3776 if ( $flush_if_no_connectivity ) {
3777 /**
3778 * If explicitly asked to flush when no connectivity - do it only
3779 * if at least 10 sec passed from the last API connectivity test.
3780 */
3781 return ( isset( $this->_storage->connectivity_test['timestamp'] ) &&
3782 ( WP_FS__SCRIPT_START_TIME - $this->_storage->connectivity_test['timestamp'] ) > 10 );
3783 }
3784
3785 /**
3786 * @since 1.1.7 Don't check for connectivity on plugin downgrade.
3787 */
3788 $version = $this->get_plugin_version();
3789 if ( version_compare( $version, $this->_storage->connectivity_test['version'], '>' ) ) {
3790 // If it's a plugin version upgrade and Freemius is off or no connectivity, run connectivity test.
3791 return true;
3792 }
3793
3794 return false;
3795 }
3796
3797 /**
3798 * @author Leo Fajardo (@leorw)
3799 * @since 2.5.4
3800 *
3801 * @param bool $is_update
3802 *
3803 * @return bool
3804 */
3805 private function should_turn_fs_on( $is_update = true ) {
3806 if (
3807 empty( $this->_plugin->opt_in_moderation ) ||
3808 ! is_array( $this->_plugin->opt_in_moderation )
3809 ) {
3810 return true;
3811 }
3812
3813 $optin_config = $this->_plugin->opt_in_moderation;
3814
3815 if (
3816 WP_FS__IS_LOCALHOST &&
3817 ( ! isset( $optin_config['localhost'] ) || false !== $optin_config['localhost'] )
3818 ) {
3819 return true;
3820 }
3821
3822 $optin_config_key = $is_update ?
3823 'updates' :
3824 'new';
3825
3826 if ( ! isset( $optin_config[ $optin_config_key ] ) ) {
3827 return true;
3828 }
3829
3830 $visibility_percentage = $optin_config[ $optin_config_key ];
3831
3832 if ( 0 == $visibility_percentage ) {
3833 return false;
3834 }
3835
3836 if ( ! is_numeric( $visibility_percentage ) ) {
3837 return true;
3838 }
3839
3840 $min = 1;
3841 $max = 100;
3842
3843 if ( function_exists( 'random_int' ) ) {
3844 $random = random_int( $min, $max ); // phpcs:ignore PHPCompatibility.FunctionUse.NewFunctions.random_intFound
3845 } else {
3846 $random = rand( $min, $max );
3847 }
3848
3849 return ( $random <= $visibility_percentage );
3850 }
3851
3852 /**
3853 * Check if there's any connectivity issue to Freemius API.
3854 *
3855 * @author Vova Feldman (@svovaf)
3856 * @since 1.0.9
3857 *
3858 * @param bool $flush_if_no_connectivity
3859 *
3860 * @return bool|null
3861 */
3862 function has_api_connectivity( $flush_if_no_connectivity = false ) {
3863 $this->_logger->entrance();
3864
3865 if ( isset( $this->_has_api_connection ) && ( $this->_has_api_connection || ! $flush_if_no_connectivity ) ) {
3866 return $this->_has_api_connection;
3867 }
3868
3869 if ( WP_FS__SIMULATE_NO_API_CONNECTIVITY &&
3870 isset( $this->_storage->connectivity_test ) &&
3871 true === $this->_storage->connectivity_test['is_connected']
3872 ) {
3873 $this->clear_connectivity_info();
3874 }
3875
3876 if ( ! $this->should_run_connectivity_test( $flush_if_no_connectivity ) ) {
3877 $this->_has_api_connection = $this->_storage->connectivity_test['is_connected'];
3878 /**
3879 * @since 1.1.6 During dev mode, if there's connectivity - turn Freemius on regardless the configuration.
3880 *
3881 * @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.
3882 */
3883 $this->_is_on = $this->_storage->connectivity_test['is_active'] ||
3884 $this->is_premium() ||
3885 ( WP_FS__DEV_MODE && $this->_has_api_connection && ! WP_FS__SIMULATE_FREEMIUS_OFF );
3886
3887 return $this->_has_api_connection;
3888 }
3889
3890 if (
3891 ! empty( $this->_storage->connectivity_test ) &&
3892 isset( $this->_storage->connectivity_test['is_active'] )
3893 ) {
3894 $is_connected = isset( $this->_storage->connectivity_test['is_connected'] ) ?
3895 $this->_storage->connectivity_test['is_connected'] :
3896 null;
3897 $is_active = ( $this->_storage->connectivity_test['is_active'] || is_object( $this->_site ) );
3898 } else {
3899 $is_connected = null;
3900 $is_active = $this->should_turn_fs_on( $this->apply_filters( 'is_plugin_update', $this->is_plugin_update() ) );
3901 }
3902
3903 $this->store_connectivity_info( (object) array( 'is_active' => $is_active ), $is_connected );
3904
3905 if ( $is_active ) {
3906 $this->_is_on = true;
3907 }
3908
3909 return $this->_has_api_connection;
3910 }
3911
3912 /**
3913 * @author Leo Fajardo (@leorw)
3914 * @since 2.5.4
3915 */
3916 private function clear_connectivity_info() {
3917 unset( $this->_storage->connectivity_test );
3918
3919 FS_Api::clear_force_http_flag();
3920 }
3921
3922 /**
3923 * @author Vova Feldman (@svovaf)
3924 * @since 1.1.7.4
3925 *
3926 * @param object $pong
3927 * @param bool|null $is_connected
3928 */
3929 private function store_connectivity_info( $pong, $is_connected ) {
3930 $this->_logger->entrance();
3931
3932 $version = $this->get_plugin_version();
3933
3934 if ( false === $is_connected || WP_FS__SIMULATE_FREEMIUS_OFF ) {
3935 $is_active = false;
3936 } else {
3937 $is_active = ( isset( $pong->is_active ) && true == $pong->is_active );
3938 }
3939
3940 $is_active = $this->apply_filters(
3941 'is_on',
3942 $is_active,
3943 $this->is_plugin_update(),
3944 $version
3945 );
3946
3947 $this->_storage->connectivity_test = array(
3948 'is_connected' => $is_connected,
3949 'host' => $_SERVER['HTTP_HOST'],
3950 'server_ip' => WP_FS__REMOTE_ADDR,
3951 'is_active' => $is_active,
3952 'timestamp' => WP_FS__SCRIPT_START_TIME,
3953 // Last version with connectivity attempt.
3954 'version' => $version,
3955 );
3956
3957 $this->_has_api_connection = $is_connected;
3958 $this->_is_on = $is_active || ( WP_FS__DEV_MODE && $is_connected && ! WP_FS__SIMULATE_FREEMIUS_OFF );
3959 }
3960
3961 /**
3962 * @author Leo Fajardo (@leorw)
3963 * @since 2.5.4
3964 *
3965 * @param bool $is_connected
3966 */
3967 private function update_connectivity_info( $is_connected ) {
3968 $this->store_connectivity_info(
3969 // 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.
3970 (object) array( 'is_active' => true ),
3971 $is_connected
3972 );
3973 }
3974
3975 /**
3976 * Force turning Freemius on.
3977 *
3978 * @author Vova Feldman (@svovaf)
3979 * @since 1.1.8.1
3980 *
3981 * @return bool TRUE if successfully turned on.
3982 */
3983 private function turn_on() {
3984 $this->_logger->entrance();
3985
3986 if ( $this->is_on() || ! isset( $this->_storage->connectivity_test['is_active'] ) ) {
3987 return false;
3988 }
3989
3990 $updated_connectivity = $this->_storage->connectivity_test;
3991 $updated_connectivity['is_active'] = true;
3992 $updated_connectivity['timestamp'] = WP_FS__SCRIPT_START_TIME;
3993 $this->_storage->connectivity_test = $updated_connectivity;
3994
3995 $this->_is_on = true;
3996
3997 return true;
3998 }
3999
4000 /**
4001 * Anonymous and unique site identifier (Hash).
4002 *
4003 * @author Vova Feldman (@svovaf)
4004 * @since 1.1.0
4005 *
4006 * @param null|int $blog_id Since 2.0.0
4007 *
4008 * @return string
4009 */
4010 function get_anonymous_id( $blog_id = null ) {
4011 $unique_id = self::$_accounts->get_option( 'unique_id', null, $blog_id );
4012
4013 if ( empty( $unique_id ) || ! is_string( $unique_id ) ) {
4014 $key = self::get_unfiltered_site_url( $blog_id, true );
4015
4016 $secure_auth = defined( 'SECURE_AUTH_KEY' ) ? SECURE_AUTH_KEY : '';
4017 if ( empty( $secure_auth ) ||
4018 false !== strpos( $secure_auth, ' ' ) ||
4019 'put your unique phrase here' === $secure_auth
4020 ) {
4021 // Protect against default auth key.
4022 $secure_auth = md5( microtime() );
4023 }
4024
4025 /**
4026 * Base the unique identifier on the WP secure authentication key. Which
4027 * turns the key into a secret anonymous identifier. This will help us
4028 * to avoid duplicate installs generation on the backend upon opt-in.
4029 *
4030 * @author Vova Feldman (@svovaf)
4031 * @since 1.2.3
4032 */
4033 $unique_id = md5( $key . $secure_auth );
4034
4035 self::$_accounts->set_option( 'unique_id', $unique_id, true, $blog_id );
4036 }
4037
4038 $this->_logger->departure( $unique_id );
4039
4040 return $unique_id;
4041 }
4042
4043 /**
4044 * Returns anonymous network ID.
4045 *
4046 * @since 2.4.3
4047 *
4048 * @return string
4049 */
4050 function get_anonymous_network_id() {
4051 return $this->get_anonymous_id( get_network()->site_id );
4052 }
4053
4054 /**
4055 * @author Vova Feldman (@svovaf)
4056 * @since 1.1.7.4
4057 *
4058 * @return \WP_User
4059 */
4060 static function _get_current_wp_user() {
4061 self::require_pluggable_essentials();
4062 self::wp_cookie_constants();
4063
4064 return wp_get_current_user();
4065 }
4066
4067 /**
4068 * Define cookie constants which are required by Freemius::_get_current_wp_user() since
4069 * it uses wp_get_current_user() which needs the cookie constants set. When a plugin
4070 * is network activated the cookie constants are only configured after the network
4071 * plugins activation, therefore, if we don't define those constants WP will throw
4072 * PHP warnings/notices.
4073 *
4074 * @author Vova Feldman (@svovaf)
4075 * @since 2.1.1
4076 */
4077 private static function wp_cookie_constants() {
4078 if ( defined( 'LOGGED_IN_COOKIE' ) &&
4079 ( defined( 'AUTH_COOKIE' ) || defined( 'SECURE_AUTH_COOKIE' ) )
4080 ) {
4081 return;
4082 }
4083
4084 /**
4085 * Used to guarantee unique hash cookies
4086 *
4087 * @since 1.5.0
4088 */
4089 if ( ! defined( 'COOKIEHASH' ) ) {
4090 $siteurl = get_site_option( 'siteurl' );
4091 if ( $siteurl ) {
4092 define( 'COOKIEHASH', md5( $siteurl ) );
4093 } else {
4094 define( 'COOKIEHASH', '' );
4095 }
4096 }
4097
4098 if ( ! defined( 'LOGGED_IN_COOKIE' ) ) {
4099 define( 'LOGGED_IN_COOKIE', 'wordpress_logged_in_' . COOKIEHASH );
4100 }
4101
4102 /**
4103 * @since 2.5.0
4104 */
4105 if ( ! defined( 'AUTH_COOKIE' ) ) {
4106 define( 'AUTH_COOKIE', 'wordpress_' . COOKIEHASH );
4107 }
4108
4109 /**
4110 * @since 2.6.0
4111 */
4112 if ( ! defined( 'SECURE_AUTH_COOKIE' ) ) {
4113 define( 'SECURE_AUTH_COOKIE', 'wordpress_sec_' . COOKIEHASH );
4114 }
4115 }
4116
4117 /**
4118 * @author Vova Feldman (@svovaf)
4119 * @since 2.1.0
4120 *
4121 * @return int
4122 */
4123 static function get_current_wp_user_id() {
4124 $wp_user = self::_get_current_wp_user();
4125
4126 return $wp_user->ID;
4127 }
4128
4129 /**
4130 * @author Vova Feldman (@svovaf)
4131 * @since 1.2.1.7
4132 *
4133 * @param string $email
4134 *
4135 * @return bool
4136 */
4137 static function is_valid_email( $email ) {
4138 if ( false === filter_var( $email, FILTER_VALIDATE_EMAIL ) ) {
4139 return false;
4140 }
4141
4142 $parts = explode( '@', $email );
4143
4144 if ( 2 !== count( $parts ) || empty( $parts[1] ) ) {
4145 return false;
4146 }
4147
4148 $blacklist = array(
4149 'admin.',
4150 'webmaster.',
4151 'localhost.',
4152 'dev.',
4153 'development.',
4154 'test.',
4155 'stage.',
4156 'staging.',
4157 );
4158
4159 // Make sure domain is not one of the blacklisted.
4160 foreach ( $blacklist as $invalid ) {
4161 if ( 0 === strpos( $parts[1], $invalid ) ) {
4162 return false;
4163 }
4164 }
4165
4166 // Get the UTF encoded domain name.
4167 /**
4168 * @note - The check of `defined('...')` is there to account for PHP servers compiled with some older version of ICU where the constants are not defined.
4169 * @author - @swashata
4170 */
4171 $is_new_idn_available = (
4172 version_compare( PHP_VERSION, '5.6.40') > 0 &&
4173 defined( 'IDNA_DEFAULT' ) &&
4174 defined( 'INTL_IDNA_VARIANT_UTS46' )
4175 );
4176 if ( $is_new_idn_available ) {
4177 $domain = idn_to_ascii( $parts[1], IDNA_DEFAULT, INTL_IDNA_VARIANT_UTS46 );
4178 } else {
4179 $domain = idn_to_ascii( $parts[1] ); // phpcs:ignore PHPCompatibility.ParameterValues.NewIDNVariantDefault.NotSet
4180 }
4181
4182 $domain = $domain . '.';
4183
4184 return ( checkdnsrr( $domain, 'MX' ) || checkdnsrr( $domain, 'A' ) );
4185 }
4186
4187 #endregion
4188
4189 #----------------------------------------------------------------------------------
4190 #region Email
4191 #----------------------------------------------------------------------------------
4192
4193 /**
4194 * Generates and sends an HTML email with customizable sections.
4195 *
4196 * @author Leo Fajardo (@leorw)
4197 * @since 1.1.2
4198 *
4199 * @param string $to_address
4200 * @param string $subject
4201 * @param array $sections
4202 * @param array $headers
4203 *
4204 * @return bool Whether the email contents were sent successfully.
4205 */
4206 private function send_email(
4207 $to_address,
4208 $subject,
4209 $sections = array(),
4210 $headers = array()
4211 ) {
4212 $default_sections = $this->get_email_sections();
4213
4214 // Insert new sections or replace the default email sections.
4215 if ( is_array( $sections ) && ! empty( $sections ) ) {
4216 foreach ( $sections as $section_id => $custom_section ) {
4217 if ( ! isset( $default_sections[ $section_id ] ) ) {
4218 // If the section does not exist, add it.
4219 $default_sections[ $section_id ] = $custom_section;
4220 } else {
4221 // If the section already exists, override it.
4222 $current_section = $default_sections[ $section_id ];
4223
4224 // Replace the current section's title if a custom section title exists.
4225 if ( isset( $custom_section['title'] ) ) {
4226 $current_section['title'] = $custom_section['title'];
4227 }
4228
4229 // Insert new rows under the current section or replace the default rows.
4230 if ( isset( $custom_section['rows'] ) && is_array( $custom_section['rows'] ) && ! empty( $custom_section['rows'] ) ) {
4231 foreach ( $custom_section['rows'] as $row_id => $row ) {
4232 $current_section['rows'][ $row_id ] = $row;
4233 }
4234 }
4235
4236 $default_sections[ $section_id ] = $current_section;
4237 }
4238 }
4239 }
4240
4241 $vars = array( 'sections' => $default_sections );
4242 $message = fs_get_template( 'email.php', $vars );
4243
4244 // Set the type of email to HTML.
4245 $headers[] = 'Content-type: text/html; charset=UTF-8';
4246
4247 $header_string = implode( "\r\n", $headers );
4248
4249 return wp_mail(
4250 $to_address,
4251 $subject,
4252 $message,
4253 $header_string
4254 );
4255 }
4256
4257 /**
4258 * Generates the data for the sections of the email content.
4259 *
4260 * @author Leo Fajardo (@leorw)
4261 * @since 1.1.2
4262 *
4263 * @return array
4264 */
4265 private function get_email_sections() {
4266 // Retrieve the current user's information so that we can get the user's email, first name, and last name below.
4267 $current_user = self::_get_current_wp_user();
4268
4269 // Retrieve the cURL version information so that we can get the version number below.
4270 $curl_version_information = curl_version();
4271
4272 $active_plugin = self::get_active_plugins();
4273
4274 // Generate the list of active plugins separated by new line.
4275 $active_plugin_string = '';
4276 foreach ( $active_plugin as $plugin ) {
4277 $active_plugin_string .= sprintf(
4278 '<a href="%s">%s</a> [v%s]<br>',
4279 $plugin['PluginURI'],
4280 $plugin['Name'],
4281 $plugin['Version']
4282 );
4283 }
4284
4285 $server_ip = WP_FS__REMOTE_ADDR;
4286
4287 // Add PHP info for deeper investigation.
4288 ob_start();
4289 phpinfo();
4290 $php_info = ob_get_clean();
4291
4292 $api_domain = substr( FS_API__ADDRESS, strpos( FS_API__ADDRESS, ':' ) + 3 );
4293
4294 // Generate the default email sections.
4295 $sections = array(
4296 'sdk' => array(
4297 'title' => 'SDK',
4298 'rows' => array(
4299 'fs_version' => array( 'FS Version', $this->version ),
4300 'curl_version' => array( 'cURL Version', $curl_version_information['version'] )
4301 )
4302 ),
4303 'plugin' => array(
4304 'title' => ucfirst( $this->get_module_type() ),
4305 'rows' => array(
4306 'name' => array( 'Name', $this->get_plugin_name() ),
4307 'version' => array( 'Version', $this->get_plugin_version() )
4308 )
4309 ),
4310 'api' => array(
4311 'title' => 'API Subdomain',
4312 'rows' => array(
4313 'dns' => array(
4314 'DNS_CNAME',
4315 function_exists( 'dns_get_record' ) ?
4316 var_export( dns_get_record( $api_domain, DNS_CNAME ), true ) :
4317 'dns_get_record() disabled/blocked'
4318 ),
4319 'ip' => array(
4320 'IP',
4321 function_exists( 'gethostbyname' ) ?
4322 gethostbyname( $api_domain ) :
4323 'gethostbyname() disabled/blocked'
4324 ),
4325 ),
4326 ),
4327 'site' => array(
4328 'title' => 'Site',
4329 'rows' => array(
4330 'unique_id' => array( 'Unique ID', $this->get_anonymous_id() ),
4331 'address' => array( 'Address', site_url() ),
4332 'host' => array(
4333 'HTTP_HOST',
4334 ( ! empty( $_SERVER['HTTP_HOST'] ) ? $_SERVER['HTTP_HOST'] : '' )
4335 ),
4336 'hosting' => array(
4337 'Hosting Company' => fs_request_has( 'hosting_company' ) ?
4338 fs_request_get( 'hosting_company' ) :
4339 'Unknown',
4340 ),
4341 'server_addr' => array(
4342 'SERVER_ADDR',
4343 '<a href="http://www.projecthoneypot.org/ip_' . $server_ip . '">' . $server_ip . '</a>'
4344 )
4345 )
4346 ),
4347 'user' => array(
4348 'title' => 'User',
4349 'rows' => array(
4350 'email' => array( 'Email', $current_user->user_email ),
4351 'first' => array( 'First', $current_user->user_firstname ),
4352 'last' => array( 'Last', $current_user->user_lastname )
4353 )
4354 ),
4355 'plugins' => array(
4356 'title' => 'Plugins',
4357 'rows' => array(
4358 'active_plugins' => array( 'Active Plugins', $active_plugin_string )
4359 )
4360 ),
4361 'php_info' => array(
4362 'title' => 'PHP Info',
4363 'rows' => array(
4364 'info' => array( $php_info )
4365 ),
4366 )
4367 );
4368
4369 // Allow the sections to be modified by other code.
4370 $sections = $this->apply_filters( 'email_template_sections', $sections );
4371
4372 return $sections;
4373 }
4374
4375 #endregion
4376
4377 #----------------------------------------------------------------------------------
4378 #region Initialization
4379 #----------------------------------------------------------------------------------
4380
4381 /**
4382 * Init plugin's Freemius instance.
4383 *
4384 * @author Vova Feldman (@svovaf)
4385 * @since 1.0.1
4386 *
4387 * @param number $id
4388 * @param string $public_key
4389 * @param bool $is_live
4390 * @param bool $is_premium
4391 */
4392 function init( $id, $public_key, $is_live = true, $is_premium = true ) {
4393 $this->_logger->entrance();
4394
4395 $this->dynamic_init( array(
4396 'id' => $id,
4397 'public_key' => $public_key,
4398 'is_live' => $is_live,
4399 'is_premium' => $is_premium,
4400 ) );
4401 }
4402
4403 /**
4404 * Dynamic initiator, originally created to support initiation
4405 * with parent_id for add-ons.
4406 *
4407 * @author Vova Feldman (@svovaf)
4408 * @since 1.0.6
4409 *
4410 * @param array $plugin_info
4411 *
4412 * @throws Freemius_Exception
4413 */
4414 function dynamic_init( array $plugin_info ) {
4415 $this->_logger->entrance();
4416
4417 $this->parse_settings( $plugin_info );
4418
4419 $this->register_after_settings_parse_hooks();
4420
4421 /**
4422 * 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.
4423 *
4424 * @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.
4425 */
4426 if ( $this->is_anonymous() ) {
4427 $is_network_level = ( $this->_is_network_active && fs_is_network_admin() );
4428
4429 if (
4430 ! $is_network_level ||
4431 FS_Site::is_valid_id( $this->_storage->network_install_blog_id )
4432 ) {
4433 if ( $this->is_paying_or_trial() ) {
4434 $this->reset_anonymous_mode( $is_network_level );
4435 }
4436 } else {
4437 $network = get_network();
4438
4439 if ( is_object( $network ) ) {
4440 $main_blog_id = $network->site_id;
4441 $first_install = $this->get_install_by_blog_id( $main_blog_id );
4442
4443 if ( is_object( $first_install ) ) {
4444 $this->_storage->network_install_blog_id = $main_blog_id;
4445 $this->_storage->network_user_id = $first_install->user_id;
4446 }
4447 }
4448 }
4449 }
4450
4451 if ( $this->should_stop_execution() ) {
4452 return;
4453 }
4454
4455 if ( ! $this->is_registered() ) {
4456 if ( $this->is_anonymous() ) {
4457 // If user skipped, no need to test connectivity.
4458 $this->_has_api_connection = true;
4459 $this->_is_on = true;
4460 } else {
4461 if ( false === $this->has_api_connectivity() ) {
4462 return;
4463 } else {
4464 if ( $this->_anonymous_mode ) {
4465 // Simulate anonymous mode.
4466 $this->_is_anonymous = true;
4467 }
4468 }
4469 }
4470 }
4471
4472 /**
4473 * This should be executed even if Freemius is off for the core module,
4474 * otherwise, the add-ons dialog box won't work properly. This is especially
4475 * relevant when the developer decided to turn FS off for existing users.
4476 *
4477 * @author Vova Feldman (@svovaf)
4478 */
4479 if ( $this->is_user_in_admin() &&
4480 'plugin-information' === fs_request_get( 'tab', false ) &&
4481 $this->should_use_freemius_updater_and_dialog() &&
4482 (
4483 ( $this->is_addon() && $this->get_slug() == fs_request_get( 'plugin', false ) ) ||
4484 ( $this->has_addons() && $this->get_id() == fs_request_get( 'parent_plugin_id', false ) )
4485 )
4486 ) {
4487 require_once WP_FS__DIR_INCLUDES . '/fs-plugin-info-dialog.php';
4488
4489 new FS_Plugin_Info_Dialog( $this->is_addon() ? $this->get_parent_instance() : $this );
4490 }
4491
4492 // Check if Freemius is on for the current plugin.
4493 // This MUST be executed after all the plugin variables has been loaded.
4494 if ( ! $this->is_registered() && ! $this->is_on() ) {
4495 return;
4496 }
4497
4498 if ( $this->has_api_connectivity() ) {
4499 if ( self::is_cron() ) {
4500 $this->hook_callback_to_sync_cron();
4501 } else if ( $this->is_user_in_admin() ) {
4502 /**
4503 * Schedule daily data sync cron if:
4504 *
4505 * 1. User opted-in (for tracking).
4506 * 2. If skipped, but later upgraded (opted-in via upgrade).
4507 *
4508 * @author Vova Feldman (@svovaf)
4509 * @since 1.1.7.3
4510 *
4511 */
4512 if ( $this->is_registered() && $this->is_tracking_allowed() ) {
4513 $this->maybe_schedule_sync_cron();
4514 }
4515
4516 /**
4517 * Check if requested for manual blocking background sync.
4518 */
4519 if ( fs_request_has( 'background_sync' ) ) {
4520 self::require_pluggable_essentials();
4521 self::wp_cookie_constants();
4522
4523 $this->run_manual_sync();
4524 }
4525 }
4526 }
4527
4528 if ( $this->is_registered() ) {
4529 FS_Clone_Manager::instance()->maybe_resolve_new_subsite_install_automatically( $this );
4530
4531 $this->hook_callback_to_install_sync();
4532 }
4533
4534 if ( $this->is_addon() ) {
4535 if ( $this->is_parent_plugin_installed() ) {
4536 // Link to parent FS.
4537 $this->_parent = self::get_instance_by_id( $this->_plugin->parent_plugin_id );
4538
4539 // Get parent plugin reference.
4540 $this->_parent_plugin = $this->_parent->get_plugin();
4541 }
4542 }
4543
4544 if ( $this->is_user_in_admin() ) {
4545 if ( $this->is_registered() && fs_request_has( 'purchase_completed' ) ) {
4546 $this->_admin_notices->add_sticky(
4547 sprintf(
4548 /* translators: %s: License type (e.g. you have a professional license) */
4549 $this->get_text_inline( 'You have purchased a %s license.', 'you-have-x-license' ),
4550 fs_request_get( 'purchased_plan' )
4551 ) .
4552 sprintf(
4553 $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' ),
4554 $this->get_module_label( true ),
4555 ( FS_Plugin::is_valid_id( $this->get_bundle_id() ) ? "products' " : '' ),
4556 ( FS_Plugin::is_valid_id( $this->get_bundle_id() ) ? 's' : '' ),
4557 sprintf(
4558 '<strong>%s</strong>',
4559 fs_request_get( 'purchase_email' )
4560 )
4561 ),
4562 'plan_purchased',
4563 $this->get_text_x_inline( 'Yee-haw', 'interjection expressing joy or exuberance', 'yee-haw' ) . '!'
4564 );
4565 }
4566
4567 if ( $this->is_addon() ) {
4568 if ( ! $this->is_parent_plugin_installed() ) {
4569 $parent_name = $this->get_option( $plugin_info, 'parent_name', null );
4570
4571 if ( isset( $plugin_info['parent'] ) ) {
4572 $parent_name = $this->get_option( $plugin_info['parent'], 'name', null );
4573 }
4574
4575 $this->_admin_notices->add(
4576 ( ! empty( $parent_name ) ?
4577 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 ) :
4578 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() )
4579 ),
4580 $this->get_text_x_inline( 'Oops', 'exclamation', 'oops' ) . '...',
4581 'error'
4582 );
4583
4584 return;
4585 } else {
4586 $is_network_admin = fs_is_network_admin();
4587
4588 if ( ! $this->_parent->is_registered() && $this->is_registered() ) {
4589 // If add-on activated and parent not, automatically install parent for the user.
4590 $this->activate_parent_account( $this->_parent );
4591 } else if (
4592 $this->_parent->is_registered() &&
4593 ! $this->is_registered() &&
4594 /**
4595 * If not registered for add-on and the following conditions for the add-on are met, activate add-on account.
4596 * * Network active and in network admin - network activate add-on account.
4597 * * Network active and not in network admin - activate add-on account for the current blog.
4598 * * Not network active and not in network admin - activate add-on account for the current blog.
4599 *
4600 * If not registered for add-on, not network active, and in network admin, do not handle the add-on activation.
4601 *
4602 * @author Leo Fajardo (@leorw)
4603 * @since 2.3.0
4604 */
4605 ( $this->is_network_active() || ! $is_network_admin )
4606 ) {
4607 $premium_license = null;
4608
4609 if (
4610 ! $this->has_free_plan() &&
4611 $this->is_bundle_license_auto_activation_enabled() &&
4612 $this->_parent->is_activated_with_bundle_license()
4613 ) {
4614 /**
4615 * If the add-on has no free plan, try to activate the account only when there's a bundle license.
4616 *
4617 * @author Leo Fajardo (@leorw)
4618 * @since 2.4.0
4619 */
4620 $bundle_license = $this->get_active_parent_license( $this->_parent->_get_license()->secret_key, false );
4621
4622 if (
4623 is_object( $bundle_license ) &&
4624 ! empty( $bundle_license->products ) &&
4625 in_array( $this->get_id(), $bundle_license->products )
4626 ) {
4627 $premium_license = $bundle_license;
4628 }
4629 }
4630
4631 if ( $this->has_free_plan() || is_object( $premium_license) ) {
4632 // If parent plugin activated, automatically install add-on for the user.
4633 $this->_activate_addon_account(
4634 $this->_parent,
4635 ( $this->is_network_active() && $is_network_admin ) ?
4636 true :
4637 get_current_blog_id(),
4638 $premium_license
4639 );
4640 }
4641 }
4642
4643 // @todo This should be only executed on activation. It should be migrated to register_activation_hook() together with other activation related logic.
4644 if ( $this->is_premium() ) {
4645 // Remove add-on download admin-notice.
4646 $this->_parent->_admin_notices->remove_sticky( array(
4647 'addon_plan_upgraded_' . $this->_slug,
4648 'no_addon_license_' . $this->_slug,
4649 ) );
4650 }
4651
4652 // $this->deactivate_premium_only_addon_without_license();
4653 }
4654 }
4655
4656 add_action( 'admin_init', array( &$this, '_admin_init_action' ) );
4657
4658 // if ( $this->is_registered() ||
4659 // $this->is_anonymous() ||
4660 // $this->is_pending_activation()
4661 // ) {
4662 // $this->_init_admin();
4663 // }
4664 }
4665
4666 /**
4667 * Should be called outside `$this->is_user_in_admin()` scope
4668 * because the updater has some logic that needs to be executed
4669 * during AJAX calls.
4670 *
4671 * Currently, we need to hook to the `http_request_host_is_external` filter.
4672 * In the future, there might be additional logic added.
4673 *
4674 * @author Vova Feldman
4675 * @since 1.2.1.6
4676 */
4677 if (
4678 $this->should_use_freemius_updater_and_dialog() &&
4679 (
4680 $this->is_premium() ||
4681 /**
4682 * If not premium but the premium version is installed, also instantiate the updater so that the
4683 * plugin information dialog of the premium version will have the information from the server.
4684 *
4685 * @author Leo Fajardo (@leorw)
4686 * @since 2.2.3
4687 */
4688 ( file_exists( fs_normalize_path( WP_PLUGIN_DIR . '/' . $this->premium_plugin_basename() ) ) )
4689 ) &&
4690 $this->has_release_on_freemius() &&
4691 ( ! $this->is_unresolved_clone( true ) )
4692 ) {
4693 FS_Plugin_Updater::instance( $this );
4694 }
4695
4696 $this->do_action( 'initiated' );
4697
4698 if ( $this->_storage->prev_is_premium !== $this->_plugin->is_premium ) {
4699 if ( isset( $this->_storage->prev_is_premium ) ) {
4700 $this->apply_filters(
4701 'after_code_type_change',
4702 // New code type.
4703 $this->_plugin->is_premium
4704 );
4705 } else {
4706 // Set for code type for the first time.
4707 $this->_storage->prev_is_premium = $this->_plugin->is_premium;
4708 }
4709 }
4710
4711 if ( ! $this->is_addon() ) {
4712 if ( $this->is_registered() ) {
4713 // Fix for upgrade from versions < 1.0.9.
4714 if ( ! isset( $this->_storage->activation_timestamp ) ) {
4715 $this->_storage->activation_timestamp = WP_FS__SCRIPT_START_TIME;
4716 }
4717
4718 $this->do_action( 'after_init_plugin_registered' );
4719 } else if ( $this->is_anonymous() ) {
4720 $this->do_action( 'after_init_plugin_anonymous' );
4721 } else if ( $this->is_pending_activation() ) {
4722 $this->do_action( 'after_init_plugin_pending_activations' );
4723 }
4724 } else {
4725 if ( $this->is_registered() ) {
4726 $this->do_action( 'after_init_addon_registered' );
4727 } else if ( $this->is_anonymous() ) {
4728 $this->do_action( 'after_init_addon_anonymous' );
4729 } else if ( $this->is_pending_activation() ) {
4730 $this->do_action( 'after_init_addon_pending_activations' );
4731 }
4732 }
4733 }
4734
4735 /**
4736 * @author Leo Fajardo (@leorw)
4737 * @since 2.2.3
4738 *
4739 * @return bool
4740 */
4741 private function should_use_freemius_updater_and_dialog() {
4742 return (
4743 /**
4744 * Allow updater and dialog when the `fs_allow_updater_and_dialog` URL query param exists and has `true`
4745 * value, or when the current page is not the "Add Plugins" page (/plugin-install.php) and the `action`
4746 * URL query param doesn't exist or its value is not `install-plugin` so that there will be no conflicts
4747 * with the .org plugins' functionalities (e.g. installation from the "Add Plugins" page and viewing
4748 * plugin details from .org).
4749 */
4750 ( true === fs_request_get_bool( 'fs_allow_updater_and_dialog' ) ) ||
4751 (
4752 ! self::is_plugin_install_page() &&
4753 // Disallow updater and dialog when installing a plugin, otherwise .org "add-on" plugins will be affected.
4754 ( 'install-plugin' !== fs_request_get( 'action' ) )
4755 )
4756 );
4757 }
4758
4759 /**
4760 * @param string[] $permissions
4761 * @param bool $is_enabled
4762 * @param int|null $blog_id
4763 *
4764 * @return true|object `true` on success, API error object on failure.
4765 */
4766 private function update_site_permissions( array $permissions, $is_enabled, $blog_id = null ) {
4767 $this->_logger->entrance();
4768
4769 $params = array(
4770 'permissions' => implode( ',', $permissions ),
4771 'is_enabled' => $is_enabled,
4772 );
4773
4774 $current_blog_id = get_current_blog_id();
4775 $is_blog_switched = false;
4776 if ( is_numeric( $blog_id ) && $current_blog_id != $blog_id ) {
4777 $is_blog_switched = $this->switch_to_blog( $blog_id );
4778 }
4779
4780 $result = $this->api_site_call( '/permissions.json', 'put', $params );
4781
4782 if ( $is_blog_switched ) {
4783 $this->switch_to_blog( $current_blog_id );
4784 }
4785
4786 if (
4787 ! $this->is_api_result_object( $result ) ||
4788 ! isset( $result->install_id )
4789 ) {
4790 $this->_logger->api_error( $result );
4791
4792 return $result;
4793 }
4794
4795 return true;
4796 }
4797
4798 /**
4799 * @param string[] $permissions
4800 * @param bool $is_enabled
4801 * @param bool $has_site_delegated_connection
4802 *
4803 * @return true|object `true` on success, API error object on failure.
4804 */
4805 private function update_network_permissions(
4806 array $permissions,
4807 $is_enabled,
4808 &$has_site_delegated_connection
4809 ) {
4810 $this->_logger->entrance();
4811
4812 $install_id_2_blog_id = array();
4813 $install_by_blog_id = $this->get_blog_install_map();
4814
4815 $has_site_delegated_connection = false;
4816
4817 foreach ( $install_by_blog_id as $blog_id => $install ) {
4818 if ( $this->is_site_delegated_connection( $blog_id ) ) {
4819 // Only update permissions of non-delegated installs.
4820 $has_site_delegated_connection = true;
4821 continue;
4822 }
4823
4824 $install_id_2_blog_id[ $install->id ] = $blog_id;
4825 }
4826
4827 if ( empty( $install_id_2_blog_id ) ) {
4828 return true;
4829 }
4830
4831 $params = array(
4832 'permissions' => implode( ',', $permissions ),
4833 'is_enabled' => $is_enabled,
4834 'install_ids' => implode( ',', array_keys( $install_id_2_blog_id ) ),
4835 );
4836
4837 // Send update to FS.
4838 $result = $this->get_current_or_network_user_api_scope()->call(
4839 "/plugins/{$this->_module_id}/installs/permissions.json",
4840 'put',
4841 $params
4842 );
4843
4844 if ( ! $this->is_api_result_object( $result, 'installs_metadata' ) ) {
4845 $this->_logger->api_error( $result );
4846
4847 return $result;
4848 }
4849
4850 return true;
4851 }
4852
4853 /**
4854 * @param mixed $result
4855 *
4856 * @return string
4857 */
4858 private function get_api_error_message( $result ) {
4859 $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:',
4860 'unexpected-api-error' ), $this->_module_type ) . ' ';
4861
4862 if (
4863 $this->is_api_error( $result ) &&
4864 isset( $result->error )
4865 ) {
4866 $code = empty( $result->error->code ) ? '' : " Code: {$result->error->code}";
4867
4868 $error_message .= "<b>{$result->error->message}{$code}</b>";
4869 } else {
4870 $error_message .= var_export( $result, true );
4871 }
4872
4873 return $error_message;
4874 }
4875
4876 /**
4877 * @author Vova Feldman (@svovaf)
4878 * @since 2.5.1
4879 */
4880 function _toggle_permission_tracking_callback() {
4881 $this->_logger->entrance();
4882
4883 $this->check_ajax_referer( 'toggle_permission_tracking' );
4884
4885 if ( ! $this->is_registered( true ) ) {
4886 self::shoot_ajax_failure( 'User never opted-in.' );
4887 }
4888
4889 $is_enabled = fs_request_get_bool( 'is_enabled' );
4890 $permissions = fs_request_get( 'permissions' );
4891
4892 if ( ! is_string( $permissions ) ) {
4893 self::shoot_ajax_failure( 'The permissions param must be a string.' );
4894 }
4895
4896 $permissions = explode( ',', $permissions );
4897
4898 $result = $this->toggle_permission_tracking( $permissions, $is_enabled );
4899
4900 if ( true !== $result ) {
4901 self::shoot_ajax_failure( $this->get_api_error_message( $result ) );
4902 }
4903
4904 self::shoot_ajax_success();
4905 }
4906
4907 /**
4908 * @param string[] $permissions
4909 * @param bool $is_enabled
4910 * @param int|null $blog_id
4911 *
4912 * @return bool|mixed `true` if updated successfully or no update is needed.
4913 */
4914 private function toggle_permission_tracking( $permissions, $is_enabled, $blog_id = null ) {
4915 if ( ! $this->is_registered( true ) ) {
4916 // User never opted-in.
4917 return false;
4918 }
4919
4920 // Check if permissions are already set as needed.
4921 if ( FS_Permission_Manager::instance( $this )->are_permissions( $permissions, $is_enabled, $blog_id ) ) {
4922 /**
4923 * Note:
4924 * 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.
4925 */
4926 return true;
4927 }
4928
4929 $api_managed_permissions = array_intersect(
4930 $permissions,
4931 FS_Permission_Manager::get_api_managed_permission_ids()
4932 );
4933
4934 if (
4935 in_array( FS_Permission_Manager::PERMISSION_ESSENTIALS, $permissions ) &&
4936 ! in_array( FS_Permission_Manager::PERMISSION_SITE, $permissions )
4937 ) {
4938 $api_managed_permissions[] = FS_Permission_Manager::PERMISSION_SITE;
4939 }
4940
4941 if ( ! empty( $api_managed_permissions ) ) {
4942 $has_site_delegated_connection = false;
4943
4944 if (
4945 ! $is_enabled &&
4946 ! in_array( FS_Permission_Manager::PERMISSION_EXTENSIONS, $api_managed_permissions ) &&
4947 false === FS_Permission_Manager::instance( $this )->is_extensions_tracking_allowed( $blog_id )
4948 ) {
4949 /**
4950 * 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.
4951 *
4952 * @todo Remove this entire `if` after implementing granular opt-in that also sends the permissions to the API when opting in.
4953 */
4954 $api_managed_permissions[] = FS_Permission_Manager::PERMISSION_EXTENSIONS;
4955 }
4956
4957 if ( is_null( $blog_id ) && fs_is_network_admin() ) {
4958 $result = $this->update_network_permissions(
4959 $api_managed_permissions,
4960 $is_enabled,
4961 $has_site_delegated_connection
4962 );
4963 } else {
4964 $result = $this->update_site_permissions(
4965 $api_managed_permissions,
4966 $is_enabled,
4967 $blog_id
4968 );
4969 }
4970
4971 if ( true !== $result ) {
4972 return $result;
4973 }
4974
4975 if ( in_array( FS_Permission_Manager::PERMISSION_SITE, $api_managed_permissions ) ) {
4976 if ( $is_enabled ) {
4977 $this->schedule_sync_cron();
4978 } else {
4979 $this->clear_sync_cron( ! $has_site_delegated_connection );
4980 }
4981 }
4982
4983 if ( in_array( FS_Permission_Manager::PERMISSION_USER, $api_managed_permissions ) ) {
4984 $this->toggle_user_permission( $is_enabled, $blog_id );
4985 }
4986 }
4987
4988 $this->update_tracking_permissions(
4989 $permissions,
4990 $is_enabled,
4991 $blog_id
4992 );
4993
4994 return true;
4995 }
4996
4997 /**
4998 * @param bool $is_enabled
4999 * @param int|null $blog_id
5000 */
5001 private function toggle_user_permission( $is_enabled, $blog_id = null ) {
5002 $network_or_blog_ids = is_numeric( $blog_id ) ?
5003 $blog_id :
5004 fs_is_network_admin();
5005
5006 if ( $is_enabled ) {
5007 $this->reset_anonymous_mode( $network_or_blog_ids );
5008 } else {
5009 $this->skip_connection( $network_or_blog_ids );
5010 }
5011 }
5012
5013 /**
5014 * Opt-in back into usage tracking.
5015 *
5016 * Note: This will only work if the user opted-in previously.
5017 *
5018 * Returns:
5019 * 1. FALSE - If the user never opted-in.
5020 * 2. TRUE - If successfully opted-in back to usage tracking.
5021 * 3. object - API result on failure.
5022 *
5023 * @author Leo Fajardo (@leorw)
5024 * @since 1.2.1.5
5025 *
5026 * @bool $is_enabled
5027 *
5028 * @return bool|object
5029 */
5030 private function toggle_site_tracking( $is_enabled, $blog_id = null ) {
5031 $this->_logger->entrance();
5032
5033 return $this->toggle_permission_tracking(
5034 FS_Permission_Manager::instance( $this )->get_site_tracking_permission_names(),
5035 $is_enabled,
5036 $blog_id
5037 );
5038 }
5039
5040 /**
5041 * If user opted-in and later disabled usage-tracking,
5042 * re-allow tracking for licensing and updates.
5043 *
5044 * @author Leo Fajardo (@leorw)
5045 * @since 1.2.1.5
5046 *
5047 * @param bool $is_context_single_site
5048 */
5049 private function reconnect_locally( $is_context_single_site = false ) {
5050 $this->_logger->entrance();
5051
5052 if ( ! $this->is_registered() ) {
5053 return;
5054 }
5055
5056 if ( ! fs_is_network_admin() || $is_context_single_site ) {
5057 if ( $this->is_tracking_prohibited() ) {
5058 FS_Permission_Manager::instance( $this )->update_site_tracking( true );
5059 }
5060 } else {
5061 $installs_map = $this->get_blog_install_map();
5062 foreach ( $installs_map as $blog_id => $install ) {
5063 /**
5064 * @var FS_Site $install
5065 */
5066 if ( ! $this->is_tracking_allowed( $blog_id, $install ) ) {
5067 FS_Permission_Manager::instance( $this )->update_site_tracking( true, $blog_id );
5068 }
5069 }
5070 }
5071 }
5072
5073 /**
5074 * 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.
5075 *
5076 * @param string[] $permissions
5077 * @param bool $is_enabled
5078 * @param int|null $blog_id
5079 *
5080 * @return array
5081 */
5082 private function update_tracking_permissions( $permissions, $is_enabled, $blog_id = null ) {
5083 // Alias.
5084 $permission_manager = FS_Permission_Manager::instance( $this );
5085
5086 $network_or_blog_ids = is_numeric( $blog_id ) ?
5087 $blog_id :
5088 fs_is_network_admin();
5089
5090 if ( true === $network_or_blog_ids ) {
5091 // Update the permission for all non-delegated sub-sites.
5092 $blog_ids = $this->get_non_delegated_blog_ids();
5093
5094 // Add the network-level to the array, to update the permission on the network-level storage.
5095 array_unshift( $blog_ids, null );
5096 }
5097 else
5098 {
5099 if ( false === $network_or_blog_ids ) {
5100 $network_or_blog_ids = null;
5101 }
5102
5103 $blog_ids = is_array( $network_or_blog_ids ) ?
5104 $network_or_blog_ids :
5105 array( $network_or_blog_ids );
5106 }
5107
5108 $result = array();
5109 foreach ( $permissions as $permission ) {
5110 $permission = trim( $permission );
5111 $is_permission_supported = true;
5112
5113 foreach ( $blog_ids as $id ) {
5114 $is_permission_supported = $permission_manager->update_permission_tracking_flag(
5115 $permission,
5116 $is_enabled,
5117 $id
5118 );
5119 }
5120
5121 if ( ! $is_permission_supported ) {
5122 $permission = 'no_match';
5123 }
5124
5125 $result[ $permission ] = $is_enabled;
5126 }
5127
5128 return $result;
5129 }
5130
5131 /**
5132 * Parse plugin's settings (as defined by the plugin dev).
5133 *
5134 * @author Vova Feldman (@svovaf)
5135 * @since 1.1.7.3
5136 *
5137 * @param array $plugin_info
5138 *
5139 * @throws \Freemius_Exception
5140 */
5141 private function parse_settings( &$plugin_info ) {
5142 $this->_logger->entrance();
5143
5144 $id = $this->get_numeric_option( $plugin_info, 'id', false );
5145 $public_key = $this->get_option( $plugin_info, 'public_key', false );
5146 $secret_key = $this->get_option( $plugin_info, 'secret_key', null );
5147 $parent_id = $this->get_numeric_option( $plugin_info, 'parent_id', null );
5148 $parent_name = $this->get_option( $plugin_info, 'parent_name', null );
5149
5150 /**
5151 * @author Vova Feldman (@svovaf)
5152 * @since 1.1.9 Try to pull secret key from external config.
5153 */
5154 if ( is_null( $secret_key ) && defined( "WP_FS__{$this->_slug}_SECRET_KEY" ) ) {
5155 $secret_key = constant( "WP_FS__{$this->_slug}_SECRET_KEY" );
5156 }
5157
5158 if ( isset( $plugin_info['parent'] ) ) {
5159 $parent_id = $this->get_numeric_option( $plugin_info['parent'], 'id', null );
5160 // $parent_slug = $this->get_option( $plugin_info['parent'], 'slug', null );
5161 // $parent_public_key = $this->get_option( $plugin_info['parent'], 'public_key', null );
5162 // $parent_name = $this->get_option( $plugin_info['parent'], 'name', null );
5163 }
5164
5165 if ( false === $id ) {
5166 throw new Freemius_Exception( array(
5167 'error' => array(
5168 'type' => 'ParameterNotSet',
5169 'message' => 'Plugin id parameter is not set.',
5170 'code' => 'plugin_id_not_set',
5171 'http' => 500,
5172 )
5173 ) );
5174 }
5175 if ( false === $public_key ) {
5176 throw new Freemius_Exception( array(
5177 'error' => array(
5178 'type' => 'ParameterNotSet',
5179 'message' => 'Plugin public_key parameter is not set.',
5180 'code' => 'plugin_public_key_not_set',
5181 'http' => 500,
5182 )
5183 ) );
5184 }
5185
5186 $plugin = ( $this->_plugin instanceof FS_Plugin ) ?
5187 $this->_plugin :
5188 new FS_Plugin();
5189
5190 $is_premium = $this->get_bool_option( $plugin_info, 'is_premium', true );
5191 $premium_suffix = $this->get_option( $plugin_info, 'premium_suffix', '(Premium)' );
5192
5193 $module_type = $this->get_option( $plugin_info, 'type', $this->_module_type );
5194
5195 $parallel_activation = $this->get_option( $plugin_info, 'parallel_activation' );
5196
5197 if (
5198 ! $is_premium &&
5199 is_array( $parallel_activation ) &&
5200 ( WP_FS__MODULE_TYPE_PLUGIN === $module_type ) &&
5201 $this->get_bool_option( $parallel_activation, 'enabled' )
5202 ) {
5203 $premium_basename = $this->get_option( $parallel_activation, 'premium_version_basename' );
5204
5205 if ( empty( $premium_basename ) ) {
5206 throw new Exception('You need to specify the premium version basename to enable parallel version activation.');
5207 }
5208
5209 $this->_premium_plugin_basename_from_parallel_activation = $premium_basename;
5210
5211 if ( is_plugin_active( $premium_basename ) ) {
5212 $is_premium = true;
5213 }
5214 }
5215
5216 $plugin->update( array(
5217 'id' => $id,
5218 'type' => $module_type,
5219 'public_key' => $public_key,
5220 'slug' => $this->_slug,
5221 'premium_slug' => $this->get_option( $plugin_info, 'premium_slug', "{$this->_slug}-premium" ),
5222 'parent_plugin_id' => $parent_id,
5223 'version' => $this->get_plugin_version(),
5224 'title' => $this->get_plugin_name( $premium_suffix ),
5225 'file' => $this->_plugin_basename,
5226 'is_premium' => $is_premium,
5227 'premium_suffix' => $premium_suffix,
5228 'is_live' => $this->get_bool_option( $plugin_info, 'is_live', true ),
5229 'affiliate_moderation' => $this->get_option( $plugin_info, 'has_affiliation' ),
5230 'bundle_id' => $this->get_option( $plugin_info, 'bundle_id', null ),
5231 'bundle_public_key' => $this->get_option( $plugin_info, 'bundle_public_key', null ),
5232 'opt_in_moderation' => $this->get_option(
5233 $plugin_info,
5234 'opt_in',
5235 // For backward compatibility, we support both parameter names: opt_in and opt_in_moderation.
5236 $this->get_option( $plugin_info, 'opt_in_moderation', null )
5237 ),
5238 ) );
5239
5240 if ( $plugin->is_updated() ) {
5241 // Update plugin details.
5242 $this->_plugin = FS_Plugin_Manager::instance( $this->_module_id )->store( $plugin );
5243 }
5244 // Set the secret key after storing the plugin, we don't want to store the key in the storage.
5245 $this->_plugin->secret_key = $secret_key;
5246
5247 /**
5248 * 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).
5249 *
5250 * @author Vova Feldman
5251 * @since 2.4.5
5252 */
5253 if ( $this->is_network_active() && fs_is_network_admin() ) {
5254 if ( isset( $plugin_info['menu_network'] ) &&
5255 is_array( $plugin_info['menu_network'] ) &&
5256 ! empty( $plugin_info['menu_network'] )
5257 ) {
5258 $plugin_info['menu'] = $plugin_info['menu_network'];
5259 }
5260 }
5261
5262 if ( ! isset( $plugin_info['menu'] ) ) {
5263 $plugin_info['menu'] = array();
5264
5265 if ( ! empty( $this->_storage->sdk_last_version ) &&
5266 version_compare( $this->_storage->sdk_last_version, '1.1.2', '<=' )
5267 ) {
5268 // Backward compatibility to 1.1.2
5269 $plugin_info['menu']['slug'] = isset( $plugin_info['menu_slug'] ) ?
5270 $plugin_info['menu_slug'] :
5271 $this->_slug;
5272 }
5273 }
5274
5275 $this->_menu = FS_Admin_Menu_Manager::instance(
5276 $this->_module_id,
5277 $this->_module_type,
5278 $this->get_unique_affix()
5279 );
5280
5281 $this->_menu->init( $plugin_info['menu'], $this->is_addon() );
5282
5283 $this->_has_addons = $this->get_bool_option( $plugin_info, 'has_addons', false );
5284 $this->_has_paid_plans = $this->get_bool_option( $plugin_info, 'has_paid_plans', true );
5285 $this->_has_premium_version = $this->get_bool_option( $plugin_info, 'has_premium_version', $this->_has_paid_plans );
5286 $this->_ignore_pending_mode = $this->get_bool_option( $plugin_info, 'ignore_pending_mode', false );
5287 $this->_is_org_compliant = $this->get_bool_option( $plugin_info, 'is_org_compliant', true );
5288 $this->_is_premium_only = $this->get_bool_option( $plugin_info, 'is_premium_only', false );
5289 if ( $this->_is_premium_only ) {
5290 // If premium only plugin, disable anonymous mode.
5291 $this->_enable_anonymous = false;
5292 $this->_anonymous_mode = false;
5293 } else {
5294 $this->_enable_anonymous = $this->get_bool_option( $plugin_info, 'enable_anonymous', true );
5295 $this->_anonymous_mode = (
5296 $this->get_bool_option( $plugin_info, 'anonymous_mode', false ) ||
5297 (
5298 $this->apply_filters( 'playground_anonymous_mode', true ) &&
5299 ! empty( $_SERVER['HTTP_HOST'] ) &&
5300 FS_Site::is_playground_wp_environment_by_host( $_SERVER['HTTP_HOST'] )
5301 )
5302 );
5303 }
5304 $this->_permissions = $this->get_option( $plugin_info, 'permissions', array() );
5305 $this->_is_bundle_license_auto_activation_enabled = $this->get_option( $plugin_info, 'bundle_license_auto_activation', false );
5306
5307 if ( ! empty( $plugin_info['trial'] ) ) {
5308 $this->_trial_days = $this->get_numeric_option(
5309 $plugin_info['trial'],
5310 'days',
5311 // Default to 0 - trial without days specification.
5312 0
5313 );
5314
5315 $this->_is_trial_require_payment = $this->get_bool_option( $plugin_info['trial'], 'is_require_payment', false );
5316 }
5317
5318 $this->_navigation = $this->get_option(
5319 $plugin_info,
5320 'navigation',
5321 $this->is_free_wp_org_theme() ?
5322 self::NAVIGATION_TABS :
5323 self::NAVIGATION_MENU
5324 );
5325 }
5326
5327 /**
5328 * @param string[] $options
5329 * @param string $key
5330 * @param mixed $default
5331 *
5332 * @return bool
5333 */
5334 private function get_option( &$options, $key, $default = false ) {
5335 return ! empty( $options[ $key ] ) ? $options[ $key ] : $default;
5336 }
5337
5338 private function get_bool_option( &$options, $key, $default = false ) {
5339 return isset( $options[ $key ] ) && is_bool( $options[ $key ] ) ? $options[ $key ] : $default;
5340 }
5341
5342 private function get_numeric_option( &$options, $key, $default = false ) {
5343 return isset( $options[ $key ] ) && is_numeric( $options[ $key ] ) ? $options[ $key ] : $default;
5344 }
5345
5346 /**
5347 * Gate keeper.
5348 *
5349 * @author Vova Feldman (@svovaf)
5350 * @since 1.1.7.3
5351 *
5352 * @return bool
5353 */
5354 private function should_stop_execution() {
5355 if ( empty( $this->_storage->was_plugin_loaded ) ) {
5356 /**
5357 * Don't execute Freemius until plugin was fully loaded at least once,
5358 * to give the opportunity for the activation hook to run before pinging
5359 * the API for connectivity test. This logic is relevant for the
5360 * identification of new plugin install vs. plugin update.
5361 *
5362 * @author Vova Feldman (@svovaf)
5363 * @since 1.1.9
5364 */
5365 return true;
5366 }
5367
5368 if ( $this->is_activation_mode() ) {
5369 if ( ! is_admin() ) {
5370 /**
5371 * If in activation mode, don't execute Freemius outside the admin dashboard.
5372 *
5373 * @author Vova Feldman (@svovaf)
5374 * @since 1.1.7.3
5375 */
5376 return true;
5377 }
5378
5379 if ( ! WP_FS__IS_HTTP_REQUEST ) {
5380 /**
5381 * If in activation and executed without HTTP context (e.g. CLI, Cronjob),
5382 * then don't start Freemius.
5383 *
5384 * @author Vova Feldman (@svovaf)
5385 * @since 1.1.6.3
5386 *
5387 * @link https://wordpress.org/support/topic/errors-in-the-freemius-class-when-running-in-wordpress-in-cli
5388 */
5389 return true;
5390 }
5391
5392 if ( self::is_cron() ) {
5393 /**
5394 * If in activation mode, don't execute Freemius during wp crons
5395 * (wp crons have HTTP context - called as HTTP request).
5396 *
5397 * @author Vova Feldman (@svovaf)
5398 * @since 1.1.7.3
5399 */
5400 return true;
5401 }
5402
5403 if ( self::is_ajax() ) {
5404 /**
5405 * During activation, if running in AJAX mode, unless there's a sticky
5406 * connectivity issue notice, don't run Freemius.
5407 *
5408 * @author Vova Feldman (@svovaf)
5409 * @since 1.1.7.3
5410 */
5411 return true;
5412 }
5413 }
5414
5415 return false;
5416 }
5417
5418 /**
5419 * Triggered after code type has changed.
5420 *
5421 * @author Vova Feldman (@svovaf)
5422 * @since 1.1.9.1
5423 */
5424 function _after_code_type_change() {
5425 $this->_logger->entrance();
5426
5427 if ( $this->is_theme() ) {
5428 // Expire the cache of the previous tabs since the theme may
5429 // have setting updates after code type has changed.
5430 $this->_cache->expire( 'tabs' );
5431 $this->_cache->expire( 'tabs_stylesheets' );
5432 }
5433
5434 if ( ! $this->is_addon() ) {
5435 add_action(
5436 is_admin() ? 'admin_init' : 'init',
5437 array( &$this, '_plugin_code_type_changed' )
5438 );
5439 }
5440
5441 if ( $this->is_registered() && $this->is_premium() ) {
5442 // Purge cached payments after switching to the premium version.
5443 // @todo This logic doesn't handle purging the cache for serviceware module upgrade.
5444 $this->get_api_user_scope()->purge_cache( "/plugins/{$this->_module_id}/payments.json?include_addons=true" );
5445 }
5446 }
5447
5448 /**
5449 * Handles plugin's code type change (free <--> premium).
5450 *
5451 * @author Vova Feldman (@svovaf)
5452 * @since 1.0.9
5453 */
5454 function _plugin_code_type_changed() {
5455 $this->_logger->entrance();
5456
5457 if ( $this->is_premium() ) {
5458 $this->reconnect_locally();
5459
5460 // Activated premium code.
5461 $this->do_action( 'after_premium_version_activation' );
5462
5463 // Remove all sticky messages related to download of the premium version.
5464 $this->_admin_notices->remove_sticky( array(
5465 'trial_started',
5466 'plan_upgraded',
5467 'plan_changed',
5468 'license_activated',
5469 ) );
5470
5471 $notice = '';
5472 if ( ! $this->is_only_premium() ) {
5473 $notice = sprintf( $this->get_text_inline( 'Premium %s version was successfully activated.', 'premium-activated-message' ), $this->_module_type );
5474 }
5475
5476 $license_notice = $this->get_license_network_activation_notice();
5477 if ( ! empty( $license_notice ) ) {
5478 $notice .= ' ' . $license_notice;
5479 }
5480
5481 if ( ! empty( $notice ) ) {
5482 $this->_admin_notices->add_sticky(
5483 trim( $notice ),
5484 'premium_activated',
5485 $this->get_text_x_inline( 'W00t',
5486 'Used to express elation, enthusiasm, or triumph (especially in electronic communication).', 'woot' ) . '!'
5487 );
5488 }
5489 } else {
5490 // Remove sticky message related to premium code activation.
5491 $this->_admin_notices->remove_sticky( 'premium_activated' );
5492
5493 // Activated free code (after had the premium before).
5494 $this->do_action( 'after_free_version_reactivation' );
5495
5496 if ( $this->is_paying() && ! $this->is_premium() ) {
5497 $this->add_complete_upgrade_instructions_notice(
5498 sprintf(
5499 /* translators: %s: License type (e.g. you have a professional license) */
5500 $this->get_text_inline( 'You have a %s license.', 'you-have-x-license' ),
5501 $this->get_plan_title()
5502 ),
5503 'plan_upgraded'
5504 );
5505 }
5506 }
5507
5508 if ( $this->is_registered() ) {
5509 // Schedule code type changes event.
5510 $this->maybe_schedule_install_sync_cron();
5511 }
5512
5513 /**
5514 * Unregister the uninstall hook for the other version of the plugin (with different code type) to avoid
5515 * triggering a fatal error when uninstalling that plugin. For example, after deactivating the "free" version
5516 * of a specific plugin, its uninstall hook should be unregistered after the "premium" version has been
5517 * activated. If we don't do that, a fatal error will occur when we try to uninstall the "free" version since
5518 * the main file of the "free" version will be loaded first before calling the hooked callback. Since the
5519 * free and premium versions are almost identical (same class or have same functions), a fatal error like
5520 * "Cannot redeclare class MyClass" or "Cannot redeclare my_function()" will occur.
5521 */
5522 $this->unregister_uninstall_hook();
5523
5524 $this->clear_module_main_file_cache();
5525
5526 // Update is_premium of latest version.
5527 $this->_storage->prev_is_premium = $this->_plugin->is_premium;
5528 }
5529
5530 #endregion
5531
5532 #----------------------------------------------------------------------------------
5533 #region Add-ons
5534 #----------------------------------------------------------------------------------
5535
5536 /**
5537 * Check if add-on installed and activated on site.
5538 *
5539 * @author Vova Feldman (@svovaf)
5540 * @since 1.0.6
5541 *
5542 * @param string|number $id_or_slug
5543 * @param bool|null $is_premium Since 1.2.1.7 can check for specified add-on version.
5544 *
5545 * @return bool
5546 */
5547 function is_addon_activated( $id_or_slug, $is_premium = null ) {
5548 $this->_logger->entrance();
5549
5550 $addon_id = self::get_module_id( $id_or_slug );
5551 $is_activated = self::has_instance( $addon_id );
5552
5553 if ( ! $is_activated ) {
5554 return false;
5555 }
5556
5557 if ( is_bool( $is_premium ) ) {
5558 // Check if the specified code version is activate.
5559 $addon = $this->get_addon_instance( $addon_id );
5560 $is_activated = ( $is_premium === $addon->is_premium() );
5561 }
5562
5563 return $is_activated;
5564 }
5565
5566 /**
5567 * Check if add-on was connected to install
5568 *
5569 * @author Vova Feldman (@svovaf)
5570 * @since 1.1.7
5571 *
5572 * @param string|number $id_or_slug
5573 *
5574 * @return bool
5575 */
5576 function is_addon_connected( $id_or_slug ) {
5577 $this->_logger->entrance();
5578
5579 $sites = self::get_all_sites( WP_FS__MODULE_TYPE_PLUGIN );
5580
5581 $addon_id = self::get_module_id( $id_or_slug );
5582 $addon = $this->get_addon( $addon_id );
5583 $slug = $addon->slug;
5584 if ( ! isset( $sites[ $slug ] ) ) {
5585 return false;
5586 }
5587
5588 $site = $sites[ $slug ];
5589
5590 $plugin = FS_Plugin_Manager::instance( $addon_id )->get();
5591
5592 if ( $plugin->parent_plugin_id != $this->_plugin->id ) {
5593 // The given slug do NOT belong to any of the plugin's add-ons.
5594 return false;
5595 }
5596
5597 return ( is_object( $site ) &&
5598 is_numeric( $site->id ) &&
5599 is_numeric( $site->user_id ) &&
5600 FS_Plugin_Plan::is_valid_id( $site->plan_id )
5601 );
5602 }
5603
5604 /**
5605 * Determines if add-on installed.
5606 *
5607 * NOTE: This is a heuristic and only works if the folder/file named as the slug.
5608 *
5609 * @author Vova Feldman (@svovaf)
5610 * @since 1.0.6
5611 *
5612 * @param string|number $id_or_slug
5613 *
5614 * @return bool
5615 */
5616 function is_addon_installed( $id_or_slug ) {
5617 $this->_logger->entrance();
5618
5619 $addon_id = self::get_module_id( $id_or_slug );
5620
5621 return file_exists( fs_normalize_path( WP_PLUGIN_DIR . '/' . $this->get_addon_basename( $addon_id ) ) );
5622 }
5623
5624 /**
5625 * Get add-on basename.
5626 *
5627 * @author Vova Feldman (@svovaf)
5628 * @since 1.0.6
5629 *
5630 * @param string|number $id_or_slug
5631 *
5632 * @return string
5633 */
5634 function get_addon_basename( $id_or_slug ) {
5635 $addon_id = self::get_module_id( $id_or_slug );
5636
5637 if ( $this->is_addon_activated( $addon_id ) ) {
5638 return self::instance( $addon_id )->get_plugin_basename();
5639 }
5640
5641 $addon = $this->get_addon( $addon_id );
5642 $premium_basename = "{$addon->premium_slug}/{$addon->slug}.php";
5643
5644 if ( file_exists( fs_normalize_path( WP_PLUGIN_DIR . '/' . $premium_basename ) ) ) {
5645 return $premium_basename;
5646 }
5647
5648 $all_plugins = $this->get_all_plugins();
5649
5650 foreach ( $all_plugins as $basename => $data ) {
5651 if ( $addon->slug === $data['slug'] ||
5652 $addon->premium_slug === $data['slug']
5653 ) {
5654 return $basename;
5655 }
5656 }
5657
5658 $free_basename = "{$addon->slug}/{$addon->slug}.php";
5659
5660 return $free_basename;
5661 }
5662
5663 /**
5664 * Get installed add-ons instances.
5665 *
5666 * @author Vova Feldman (@svovaf)
5667 * @since 1.0.6
5668 *
5669 * @return Freemius[]
5670 */
5671 function get_installed_addons() {
5672 if ( $this->is_addon() ) {
5673 // Add-on cannot have add-ons.
5674 return array();
5675 }
5676
5677 $installed_addons = array();
5678
5679 foreach ( self::$_instances as $instance ) {
5680 if ( $instance->is_addon_of( $this->_plugin->id ) ) {
5681 $installed_addons[] = $instance;
5682 }
5683 }
5684
5685 return $installed_addons;
5686 }
5687
5688 /**
5689 * Check if any add-ons of the plugin are installed.
5690 *
5691 * @author Leo Fajardo (@leorw)
5692 * @since 1.1.1
5693 *
5694 * @return bool
5695 */
5696 function has_installed_addons() {
5697 if ( ! $this->has_addons() ) {
5698 return false;
5699 }
5700
5701 foreach ( self::$_instances as $instance ) {
5702 if ( $instance->is_addon() && is_object( $instance->_parent_plugin ) ) {
5703 if ( $this->_plugin->id == $instance->_parent_plugin->id ) {
5704 return true;
5705 }
5706 }
5707 }
5708
5709 return false;
5710 }
5711
5712 /**
5713 * Tell Freemius that the current plugin is an add-on.
5714 *
5715 * @author Vova Feldman (@svovaf)
5716 * @since 1.0.6
5717 *
5718 * @param number $parent_plugin_id The parent plugin ID
5719 */
5720 function init_addon( $parent_plugin_id ) {
5721 $this->_plugin->parent_plugin_id = $parent_plugin_id;
5722 }
5723
5724 /**
5725 * @author Vova Feldman (@svovaf)
5726 * @since 1.0.6
5727 *
5728 * @return bool
5729 */
5730 function is_addon() {
5731 return (
5732 isset( $this->_plugin->parent_plugin_id ) &&
5733 is_numeric( $this->_plugin->parent_plugin_id )
5734 );
5735 }
5736
5737 /**
5738 * @author Vova Feldman (@svovaf)
5739 * @since 2.3.2
5740 *
5741 * @param number $parent_product_id
5742 *
5743 * @return bool
5744 */
5745 function is_addon_of( $parent_product_id ) {
5746 return (
5747 $this->is_addon() &&
5748 $parent_product_id == $this->_plugin->parent_plugin_id
5749 );
5750 }
5751
5752 /**
5753 * Deactivate add-on if it's premium only and the user does't have a valid license.
5754 *
5755 * @param bool $is_after_trial_cancel
5756 *
5757 * @return bool If add-on was deactivated.
5758 */
5759 private function deactivate_premium_only_addon_without_license( $is_after_trial_cancel = false ) {
5760 if ( ! $this->has_free_plan() &&
5761 ! $this->has_features_enabled_license() &&
5762 ! $this->_has_premium_license()
5763 ) {
5764 if ( $this->is_registered() ) {
5765 // IF wrapper is turned off because activation_timestamp is currently only stored for plugins (not addons).
5766 // if (empty($this->_storage->activation_timestamp) ||
5767 // (WP_FS__SCRIPT_START_TIME - $this->_storage->activation_timestamp) > 30
5768 // ) {
5769 /**
5770 * @todo When it's first fail, there's no reason to try and re-sync because the licenses were just synced after initial activation.
5771 *
5772 * Retry syncing the user add-on licenses.
5773 */
5774 // Sync licenses.
5775 $this->_sync_licenses();
5776 // }
5777
5778 // Try to activate premium license.
5779 $this->_activate_license( true );
5780 }
5781
5782 if ( ! $this->has_free_plan() &&
5783 ! $this->has_features_enabled_license() &&
5784 ! $this->_has_premium_license()
5785 ) {
5786 // @todo Check if deactivate plugins also call the deactivation hook.
5787
5788 $this->_parent->_admin_notices->add_sticky(
5789 sprintf(
5790 ( $is_after_trial_cancel ?
5791 $this->_parent->get_text_inline(
5792 '%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.',
5793 'addon-trial-cancelled-message'
5794 ) :
5795 $this->_parent->get_text_inline(
5796 '%s is a premium only add-on. You have to purchase a license first before activating the plugin.',
5797 'addon-no-license-message'
5798 )
5799 ),
5800 '<b>' . $this->_plugin->title . '</b>'
5801 ) . ' ' . sprintf(
5802 '<a href="%s" aria-label="%s" class="button button-primary" style="margin-left: 10px; vertical-align: middle;">%s &nbsp;&#10140;</a>',
5803 $this->_parent->addon_url( $this->_slug ),
5804 esc_attr( sprintf( $this->_parent->get_text_inline( 'More information about %s', 'more-information-about-x' ), $this->_plugin->title ) ),
5805 $this->_parent->get_text_inline( 'Purchase License', 'purchase-license' )
5806 ),
5807 'no_addon_license_' . $this->_slug,
5808 ( $is_after_trial_cancel ? '' : $this->_parent->get_text_x_inline( 'Oops', 'exclamation', 'oops' ) . '...' ),
5809 ( $is_after_trial_cancel ? 'success' : 'error' )
5810 );
5811
5812 deactivate_plugins( array( $this->_plugin_basename ), true );
5813
5814 return true;
5815 }
5816 }
5817
5818 return false;
5819 }
5820
5821 #endregion
5822
5823 #----------------------------------------------------------------------------------
5824 #region Sandbox
5825 #----------------------------------------------------------------------------------
5826
5827 /**
5828 * Set Freemius into sandbox mode for debugging.
5829 *
5830 * @author Vova Feldman (@svovaf)
5831 * @since 1.0.4
5832 *
5833 * @param string $secret_key
5834 */
5835 function init_sandbox( $secret_key ) {
5836 $this->_plugin->secret_key = $secret_key;
5837
5838 // Update plugin details.
5839 FS_Plugin_Manager::instance( $this->_module_id )->update( $this->_plugin, true );
5840 }
5841
5842 /**
5843 * Check if running payments in sandbox mode.
5844 *
5845 * @author Vova Feldman (@svovaf)
5846 * @since 1.0.4
5847 *
5848 * @return bool
5849 */
5850 function is_payments_sandbox() {
5851 return ( ! $this->is_live() ) || isset( $this->_plugin->secret_key );
5852 }
5853
5854 #endregion
5855
5856 /**
5857 * Check if running test vs. live plugin.
5858 *
5859 * @author Vova Feldman (@svovaf)
5860 * @since 1.0.5
5861 *
5862 * @return bool
5863 */
5864 function is_live() {
5865 return $this->_plugin->is_live;
5866 }
5867
5868 /**
5869 * Check if super-admin skipped connection for all sites in the network.
5870 *
5871 * @author Vova Feldman (@svovaf)
5872 * @since 2.0.0
5873 */
5874 function is_network_anonymous() {
5875 if ( ! $this->_is_network_active ) {
5876 return false;
5877 }
5878
5879 $is_anonymous_ms = $this->_storage->get( 'is_anonymous_ms' );
5880
5881 if ( empty( $is_anonymous_ms ) ) {
5882 return false;
5883 }
5884
5885 return $is_anonymous_ms['is'];
5886 }
5887
5888 /**
5889 * Check if super-admin opted-in for all sites in the network.
5890 *
5891 * @author Vova Feldman (@svovaf)
5892 * @since 2.0.0
5893 */
5894 function is_network_connected() {
5895 if ( ! $this->_is_network_active ) {
5896 return false;
5897 }
5898
5899 return $this->_storage->get( 'is_network_connected' );
5900 }
5901
5902 /**
5903 * Check if the user skipped connecting the account with Freemius.
5904 *
5905 * @author Vova Feldman (@svovaf)
5906 * @since 1.0.7
5907 *
5908 * @return bool
5909 */
5910 function is_anonymous() {
5911 if ( ! isset( $this->_is_anonymous ) ) {
5912 if ( $this->is_network_anonymous() ) {
5913 $this->_is_anonymous = true;
5914 } else if ( fs_is_network_admin() ) {
5915 /**
5916 * When not-network-anonymous, yet, running in the network admin, consider as anonymous only when ALL non-delegated sites are set to anonymous.
5917 */
5918 $non_delegated_sites = $this->get_non_delegated_blog_ids();
5919
5920 foreach ( $non_delegated_sites as $blog_id ) {
5921 $is_anonymous = $this->_storage->get( 'is_anonymous', false, $blog_id );
5922
5923 if ( empty( $is_anonymous ) || false === $is_anonymous[ 'is' ] ) {
5924 $this->_is_anonymous = false;
5925 break;
5926 }
5927 }
5928
5929 if ( false !== $this->_is_anonymous ) {
5930 $this->_is_anonymous = true;
5931 }
5932 } else {
5933 if ( ! isset( $this->_storage->is_anonymous ) ) {
5934 // Not skipped.
5935 $this->_is_anonymous = false;
5936 } else if ( is_bool( $this->_storage->is_anonymous ) ) {
5937 // For back compatibility, since the variable was boolean before.
5938 $this->_is_anonymous = $this->_storage->is_anonymous;
5939
5940 // Upgrade stored data format to 1.1.3 format.
5941 $this->set_anonymous_mode( $this->_storage->is_anonymous );
5942 } else {
5943 // Version 1.1.3 and later.
5944 $this->_is_anonymous = $this->_storage->is_anonymous['is'];
5945 }
5946 }
5947 }
5948
5949 return $this->_is_anonymous;
5950 }
5951
5952 /**
5953 * Check if the user skipped the connection of a specified site.
5954 *
5955 * @author Vova Feldman (@svovaf)
5956 * @since 2.0.0
5957 *
5958 * @param int $blog_id
5959 *
5960 * @return bool
5961 */
5962 function is_anonymous_site( $blog_id = 0 ) {
5963 if ( $this->is_network_anonymous() ) {
5964 return true;
5965 }
5966
5967 $is_anonymous = $this->_storage->get( 'is_anonymous', false, $blog_id );
5968
5969 if ( empty( $is_anonymous ) ) {
5970 return false;
5971 }
5972
5973 return $is_anonymous['is'];
5974 }
5975
5976 /**
5977 * Check if user connected his account and install pending email activation.
5978 *
5979 * @author Vova Feldman (@svovaf)
5980 * @since 1.0.7
5981 *
5982 * @return bool
5983 */
5984 function is_pending_activation() {
5985 return $this->_storage->get( 'is_pending_activation', false );
5986 }
5987
5988 /**
5989 * @author Leo Fajardo (@leorw)
5990 * @since 2.5.0
5991 */
5992 private function clear_pending_activation_mode() {
5993 // Remove the pending activation sticky notice (if it still exists).
5994 $this->_admin_notices->remove_sticky( 'activation_pending' );
5995
5996 // Clear the plugin's pending activation mode.
5997 unset( $this->_storage->is_pending_activation );
5998 }
5999
6000 /**
6001 * Check if plugin must be WordPress.org compliant.
6002 *
6003 * @since 1.0.7
6004 *
6005 * @return bool
6006 */
6007 function is_org_repo_compliant() {
6008 return $this->_is_org_compliant;
6009 }
6010
6011 #--------------------------------------------------------------------------------
6012 #region WP Cron Common
6013 #--------------------------------------------------------------------------------
6014
6015 /**
6016 * @author Vova Feldman (@svovaf)
6017 * @since 2.0.0
6018 *
6019 * @param string $name Cron name.
6020 *
6021 * @return object
6022 */
6023 private function get_cron_data( $name ) {
6024 $this->_logger->entrance( $name );
6025
6026 /**
6027 * @var object $cron_data
6028 */
6029 return $this->_storage->get( "{$name}_cron", null );
6030 }
6031
6032 /**
6033 * @author Vova Feldman (@svovaf)
6034 * @since 2.0.0
6035 *
6036 * @param string $name Cron name.
6037 */
6038 private function clear_cron_data( $name ) {
6039 $this->_logger->entrance( $name );
6040
6041 $this->_storage->remove( "{$name}_cron" );
6042 }
6043
6044 /**
6045 * @author Vova Feldman (@svovaf)
6046 * @since 2.0.0
6047 *
6048 * @param string $name Cron name.
6049 * @param int $cron_blog_id The cron executing blog ID.
6050 */
6051 private function set_cron_data( $name, $cron_blog_id = 0 ) {
6052 $this->_logger->entrance( $name );
6053
6054 $this->_storage->store( "{$name}_cron", (object) array(
6055 'version' => $this->get_plugin_version(),
6056 'blog_id' => $cron_blog_id,
6057 'sdk_version' => $this->version,
6058 'timestamp' => WP_FS__SCRIPT_START_TIME,
6059 'on' => true,
6060 ) );
6061 }
6062
6063 /**
6064 * Get the cron's executing blog ID.
6065 *
6066 * @author Vova Feldman (@svovaf)
6067 * @since 2.0.0
6068 *
6069 * @param string $name Cron name.
6070 *
6071 * @return int
6072 */
6073 private function get_cron_blog_id( $name ) {
6074 $this->_logger->entrance( $name );
6075
6076 if ( ! is_multisite() ) {
6077 // Not a multisite.
6078 return 0;
6079 }
6080
6081 $cron_data = $this->get_cron_data( $name );
6082
6083 return ( is_object( $cron_data ) && is_numeric( $cron_data->blog_id ) ) ?
6084 $cron_data->blog_id :
6085 0;
6086 }
6087
6088 /**
6089 * @author Vova Feldman (@svovaf)
6090 * @since 2.0.0
6091 *
6092 * @param string $name Cron name.
6093 *
6094 * @return bool
6095 */
6096 private function is_cron_on( $name ) {
6097 $this->_logger->entrance( $name );
6098
6099 /**
6100 * @var object $cron_data
6101 */
6102 $cron_data = $this->get_cron_data( $name );
6103
6104 return ( ! is_null( $cron_data ) && true === $cron_data->on );
6105 }
6106
6107 /**
6108 * Unix timestamp for previous cron execution or false if never executed.
6109 *
6110 * @author Vova Feldman (@svovaf)
6111 * @since 2.0.0
6112 *
6113 * @param string $name Cron name.
6114 *
6115 * @return int|false
6116 */
6117 private function cron_last_execution( $name ) {
6118 $this->_logger->entrance( $name );
6119
6120 return $this->_storage->get( "{$name}_timestamp" );
6121 }
6122
6123 /**
6124 * Set cron execution time to now.
6125 *
6126 * @author Vova Feldman (@svovaf)
6127 * @since 2.0.0
6128 *
6129 * @param string $name Cron name.
6130 */
6131 private function set_cron_execution_timestamp( $name ) {
6132 $this->_logger->entrance( $name );
6133
6134 $this->_storage->store( "{$name}_timestamp", time() );
6135 }
6136
6137 /**
6138 * Sets the keepalive time to now.
6139 *
6140 * @author Leo Fajardo (@leorw)
6141 * @since 2.2.3
6142 *
6143 * @param bool|null $use_network_level_storage
6144 */
6145 private function set_keepalive_timestamp( $use_network_level_storage = null ) {
6146 $this->_logger->entrance();
6147
6148 $this->_storage->store( 'keepalive_timestamp', time(), $use_network_level_storage );
6149 }
6150
6151 /**
6152 * Check if cron was executed in the last $period of seconds.
6153 *
6154 * @author Vova Feldman (@svovaf)
6155 * @since 2.0.0
6156 *
6157 * @param string $name Cron name.
6158 * @param int $period In seconds
6159 *
6160 * @return bool
6161 */
6162 private function is_cron_executed( $name, $period = WP_FS__TIME_24_HOURS_IN_SEC ) {
6163 $this->_logger->entrance( $name );
6164
6165 $last_execution = $this->cron_last_execution( $name );
6166
6167 if ( ! is_numeric( $last_execution ) ) {
6168 return false;
6169 }
6170
6171 return ( $last_execution > ( WP_FS__SCRIPT_START_TIME - $period ) );
6172 }
6173
6174 /**
6175 * WP Cron is executed on a site level. When running in a multisite network environment
6176 * with the network integration activated, for optimization reasons, we are consolidating
6177 * the installs data sync cron to be executed only from a single site.
6178 *
6179 * @author Vova Feldman (@svovaf)
6180 * @since 2.0.0
6181 *
6182 * @param int $except_blog_id Target any except the excluded blog ID.
6183 *
6184 * @return int
6185 */
6186 private function get_cron_target_blog_id( $except_blog_id = 0 ) {
6187 if ( ! is_multisite() ) {
6188 return 0;
6189 }
6190
6191 if ( $this->_is_network_active ) {
6192 $network_install_blog_id = $this->_storage->network_install_blog_id;
6193
6194 if (
6195 is_numeric( $network_install_blog_id ) &&
6196 $except_blog_id != $network_install_blog_id &&
6197 self::is_site_active( $network_install_blog_id )
6198 ) {
6199 // Try to run cron from the main network blog.
6200 $install = $this->get_install_by_blog_id( $network_install_blog_id );
6201
6202 if (
6203 is_object( $install ) &&
6204 $this->is_tracking_allowed( $network_install_blog_id, $install )
6205 ) {
6206 return $network_install_blog_id;
6207 }
6208 }
6209 }
6210
6211 // Get first opted-in blog ID with active tracking.
6212 $installs = $this->get_blog_install_map();
6213 foreach ( $installs as $blog_id => $install ) {
6214 if ( $except_blog_id != $blog_id &&
6215 self::is_site_active( $blog_id ) &&
6216 $this->is_tracking_allowed( $blog_id, $install )
6217 ) {
6218 return $blog_id;
6219 }
6220 }
6221
6222 return 0;
6223 }
6224
6225 /**
6226 * @author Vova Feldman (@svovaf)
6227 * @since 2.0.0
6228 *
6229 * @param string $name Cron name.
6230 * @param string $action_tag Callback action tag.
6231 * @param bool $is_network_clear If set to TRUE, clear sync cron even if there are installs that are still connected.
6232 */
6233 private function clear_cron( $name, $action_tag = '', $is_network_clear = false ) {
6234 $this->_logger->entrance( $name );
6235
6236 if ( ! $this->is_cron_on( $name ) ) {
6237 return;
6238 }
6239
6240 $clear_cron = true;
6241 if ( ! $is_network_clear && $this->_is_network_active ) {
6242 $installs = $this->get_blog_install_map();
6243
6244 foreach ( $installs as $blog_id => $install ) {
6245 /**
6246 * @var FS_Site $install
6247 */
6248 if ( $this->is_tracking_allowed( $blog_id, $install ) ) {
6249 $clear_cron = false;
6250 break;
6251 }
6252 }
6253 }
6254
6255 if ( ! $clear_cron ) {
6256 return;
6257 }
6258
6259 $cron_blog_id = $this->get_cron_blog_id( $name );
6260
6261 $this->clear_cron_data( $name );
6262
6263 if ( 0 < $cron_blog_id ) {
6264 switch_to_blog( $cron_blog_id );
6265 }
6266
6267 if ( empty( $action_tag ) ) {
6268 $action_tag = $name;
6269 }
6270
6271 wp_clear_scheduled_hook( $this->get_action_tag( $action_tag ) );
6272
6273 if ( 0 < $cron_blog_id ) {
6274 restore_current_blog();
6275 }
6276 }
6277
6278 /**
6279 * Unix timestamp for next cron execution or false if not scheduled.
6280 *
6281 * @author Vova Feldman (@svovaf)
6282 * @since 2.0.0
6283 *
6284 * @param string $name Cron name.
6285 * @param string $action_tag Callback action tag.
6286 *
6287 * @return int|false
6288 */
6289 private function get_next_scheduled_cron( $name, $action_tag = '' ) {
6290 $this->_logger->entrance( $name );
6291
6292 if ( ! $this->is_cron_on( $name ) ) {
6293 return false;
6294 }
6295
6296 $cron_blog_id = $this->get_cron_blog_id( $name );
6297
6298 if ( 0 < $cron_blog_id ) {
6299 switch_to_blog( $cron_blog_id );
6300 }
6301
6302 if ( empty( $action_tag ) ) {
6303 $action_tag = $name;
6304 }
6305
6306 $next_scheduled = wp_next_scheduled( $this->get_action_tag( $action_tag ) );
6307
6308 if ( 0 < $cron_blog_id ) {
6309 restore_current_blog();
6310 }
6311
6312 return $next_scheduled;
6313 }
6314
6315 /**
6316 * @author Vova Feldman (@svovaf)
6317 * @since 2.0.0
6318 *
6319 * @param string $name Cron name.
6320 * @param string $action_tag Callback action tag.
6321 * @param string $recurrence 'single' or 'daily'.
6322 * @param int $start_at Defaults to now.
6323 * @param bool $randomize_start If true, schedule first job randomly during the next 12 hours. Otherwise, schedule job to start right away.
6324 * @param int $except_blog_id Target any except the excluded blog ID.
6325 */
6326 private function schedule_cron(
6327 $name,
6328 $action_tag = '',
6329 $recurrence = 'single',
6330 $start_at = WP_FS__SCRIPT_START_TIME,
6331 $randomize_start = true,
6332 $except_blog_id = 0
6333 ) {
6334 $this->_logger->entrance( $name );
6335
6336 $this->clear_cron( $name, $action_tag, true );
6337
6338 $cron_blog_id = $this->get_cron_target_blog_id( $except_blog_id );
6339
6340 if ( is_multisite() && 0 == $cron_blog_id ) {
6341 // Don't schedule cron since couldn't find a target blog.
6342 return;
6343 }
6344
6345 if ( 0 < $cron_blog_id ) {
6346 switch_to_blog( $cron_blog_id );
6347 }
6348
6349 if ( 'daily' === $recurrence ) {
6350 if ( $randomize_start ) {
6351 // Schedule first sync with a random 12 hour time range from now.
6352 $start_at += rand( 0, ( WP_FS__TIME_24_HOURS_IN_SEC / 2 ) );
6353 }
6354
6355 // Schedule daily WP cron.
6356 wp_schedule_event(
6357 $start_at,
6358 'daily',
6359 $this->get_action_tag( $action_tag )
6360 );
6361 } else if ( 'single' === $recurrence ) {
6362 // Schedule single cron.
6363 wp_schedule_single_event(
6364 $start_at,
6365 $this->get_action_tag( $action_tag )
6366 );
6367 }
6368
6369 $this->set_cron_data( $name, $cron_blog_id );
6370
6371 if ( 0 < $cron_blog_id ) {
6372 restore_current_blog();
6373 }
6374 }
6375
6376 /**
6377 * Consolidated cron execution for performance optimization. The max number of API requests is based on the number of unique opted-in users.
6378 * that doesn't halt page loading.
6379 *
6380 * @author Vova Feldman (@svovaf)
6381 * @since 2.0.0
6382 *
6383 * @param string $name Cron name.
6384 * @param callable $callable The function that should be executed.
6385 */
6386 private function execute_cron( $name, $callable ) {
6387 $this->_logger->entrance( $name );
6388
6389 // Store the last time data sync was executed.
6390 $this->set_cron_execution_timestamp( $name );
6391
6392 // Check if API is temporary down.
6393 if ( FS_Api::is_temporary_down() ) {
6394 return;
6395 }
6396
6397 // @todo Add logic that identifies API latency, and reschedule the next background sync randomly between 8-16 hours.
6398
6399 $users_2_blog_ids = array();
6400
6401 if ( ! is_multisite() ) {
6402 // Add dummy blog.
6403 $users_2_blog_ids[0] = array( 0 );
6404 } else {
6405 $installs = $this->get_blog_install_map();
6406 foreach ( $installs as $blog_id => $install ) {
6407 if ( $this->is_tracking_allowed( $blog_id, $install ) ) {
6408 if ( ! isset( $users_2_blog_ids[ $install->user_id ] ) ) {
6409 $users_2_blog_ids[ $install->user_id ] = array();
6410 }
6411
6412 $users_2_blog_ids[ $install->user_id ][] = $blog_id;
6413 }
6414 }
6415 }
6416
6417 $current_blog_id = get_current_blog_id();
6418
6419 foreach ( $users_2_blog_ids as $user_id => $blog_ids ) {
6420 if ( 0 < $blog_ids[0] ) {
6421 $this->switch_to_blog( $blog_ids[0] );
6422 }
6423
6424 call_user_func_array( $callable, array( $blog_ids, ( is_multisite() ? $current_blog_id : null ) ) );
6425
6426 foreach ( $blog_ids as $blog_id ) {
6427 $this->do_action( "after_{$name}_cron", $blog_id );
6428 }
6429 }
6430
6431 if ( is_multisite() ) {
6432 $this->switch_to_blog( $current_blog_id, fs_is_network_admin() ? $this->get_network_install() : null );
6433
6434 $this->do_action( "after_{$name}_cron_multisite" );
6435 }
6436 }
6437
6438 #endregion
6439
6440 #----------------------------------------------------------------------------------
6441 #region Daily Sync Cron
6442 #----------------------------------------------------------------------------------
6443
6444
6445 /**
6446 * @author Vova Feldman (@svovaf)
6447 * @since 2.0.0
6448 *
6449 * @return bool
6450 */
6451 private function is_sync_cron_scheduled() {
6452 return $this->is_cron_on( 'sync' );
6453 }
6454
6455 /**
6456 * Get the sync cron's executing blog ID.
6457 *
6458 * @author Vova Feldman (@svovaf)
6459 * @since 2.0.0
6460 *
6461 * @return int
6462 */
6463 private function get_sync_cron_blog_id() {
6464 return $this->get_cron_blog_id( 'sync' );
6465 }
6466
6467 /**
6468 * @author Vova Feldman (@svovaf)
6469 * @since 1.1.7.3
6470 */
6471 private function run_manual_sync() {
6472 if ( ! $this->is_user_admin() ) {
6473 return;
6474 }
6475
6476 // Run manual sync.
6477 $this->_sync_cron();
6478
6479 // Reschedule next cron to run 24 hours from now (performance optimization).
6480 $this->schedule_sync_cron( time() + WP_FS__TIME_24_HOURS_IN_SEC, false );
6481 }
6482
6483 /**
6484 * Data sync cron job. Replaces the background sync non blocking HTTP request
6485 * that doesn't halt page loading.
6486 *
6487 * @author Vova Feldman (@svovaf)
6488 * @since 1.1.7.3
6489 * @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.
6490 */
6491 function _sync_cron() {
6492 $this->_logger->entrance();
6493
6494 $this->execute_cron( 'sync', array( &$this, '_sync_cron_method' ) );
6495 }
6496
6497 /**
6498 * The actual data sync cron logic.
6499 *
6500 * @author Vova Feldman (@svovaf)
6501 * @since 2.0.0
6502 *
6503 * @param int[] $blog_ids
6504 * @param int|null $current_blog_id @since 2.2.3. This is passed from the `execute_cron` method and used by the
6505 * `_sync_plugin_license` method in order to switch to the previous blog when sending
6506 * updates for a single site in case `execute_cron` has switched to a different blog.
6507 */
6508 function _sync_cron_method( array $blog_ids, $current_blog_id = null ) {
6509 if ( $this->is_registered() ) {
6510 if ( $this->has_paid_plan() ) {
6511 // Initiate background plan sync.
6512 $this->_sync_license( true, false, $current_blog_id );
6513
6514 if ( $this->is_paying() ) {
6515 // Check for premium plugin updates.
6516 $this->check_updates( true );
6517 }
6518 } else {
6519 // Sync install(s) (only if something changed locally).
6520 if ( 1 < count( $blog_ids ) ) {
6521 $this->sync_installs();
6522 } else {
6523 $this->sync_install();
6524 }
6525
6526 $this->maybe_sync_install_user();
6527 }
6528 }
6529 }
6530
6531 /**
6532 * Check if sync was executed in the last $period of seconds.
6533 *
6534 * @author Vova Feldman (@svovaf)
6535 * @since 1.1.7.3
6536 *
6537 * @param int $period In seconds
6538 *
6539 * @return bool
6540 */
6541 private function is_sync_executed( $period = WP_FS__TIME_24_HOURS_IN_SEC ) {
6542 return $this->is_cron_executed( 'sync', $period );
6543 }
6544
6545 /**
6546 * @author Vova Feldman (@svovaf)
6547 * @since 1.1.7.3
6548 *
6549 * @return bool
6550 */
6551 private function is_sync_cron_on() {
6552 return $this->is_cron_on( 'sync' );
6553 }
6554
6555 /**
6556 * @author Leo Fajardo (@leorw)
6557 * @since 2.5.0
6558 */
6559 private function maybe_schedule_sync_cron() {
6560 $next_schedule = $this->next_sync_cron();
6561
6562 // The event is properly scheduled, so no need to reschedule it.
6563 if (
6564 is_numeric( $next_schedule ) &&
6565 $next_schedule > time()
6566 ) {
6567 return;
6568 }
6569
6570 $this->schedule_sync_cron();
6571 }
6572
6573 /**
6574 * Instead of running blocking install sync event, execute non blocking scheduled cron job.
6575 *
6576 * @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 specified blog ID from being the cron job executor.
6577 *
6578 * @author Leo Fajardo (@leorw)
6579 * @since 2.9.1
6580 */
6581 private function maybe_schedule_install_sync_cron( $except_blog_id = 0 ) {
6582 if ( ! $this->is_user_in_admin() ) {
6583 return;
6584 }
6585
6586 if ( $this->is_clone() ) {
6587 return;
6588 }
6589
6590 if (
6591 // The event has been properly scheduled, so no need to reschedule it.
6592 is_numeric( $this->next_install_sync() )
6593 ) {
6594 return;
6595 }
6596
6597 $this->schedule_cron( 'install_sync', 'install_sync', 'single', WP_FS__SCRIPT_START_TIME, false, $except_blog_id );
6598 }
6599
6600 /**
6601 * @author Vova Feldman (@svovaf)
6602 * @since 1.1.7.3
6603 *
6604 * @param int $start_at Defaults to now.
6605 * @param bool $randomize_start If true, schedule first job randomly during the next 12 hours. Otherwise, schedule job to start right away.
6606 * @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.
6607 */
6608 private function schedule_sync_cron(
6609 $start_at = WP_FS__SCRIPT_START_TIME,
6610 $randomize_start = true,
6611 $except_blog_id = 0
6612 ) {
6613 $this->schedule_cron(
6614 'sync',
6615 'data_sync',
6616 'daily',
6617 $start_at,
6618 $randomize_start,
6619 $except_blog_id
6620 );
6621 }
6622
6623 /**
6624 * Add the actual sync function to the cron job hook.
6625 *
6626 * @author Vova Feldman (@svovaf)
6627 * @since 1.1.7.3
6628 */
6629 private function hook_callback_to_sync_cron() {
6630 $this->add_action( 'data_sync', array( &$this, '_sync_cron' ) );
6631 }
6632
6633 /**
6634 * @author Vova Feldman (@svovaf)
6635 * @since 1.1.7.3
6636 *
6637 * @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.
6638 */
6639 private function clear_sync_cron( $is_network_clear = false ) {
6640 $this->_logger->entrance();
6641
6642 $this->clear_cron( 'sync', 'data_sync', $is_network_clear );
6643 }
6644
6645 /**
6646 * Unix timestamp for next sync cron execution or false if not scheduled.
6647 *
6648 * @author Vova Feldman (@svovaf)
6649 * @since 1.1.7.3
6650 *
6651 * @return int|false
6652 */
6653 function next_sync_cron() {
6654 return $this->get_next_scheduled_cron( 'sync', 'data_sync' );
6655 }
6656
6657 /**
6658 * Unix timestamp for previous sync cron execution or false if never executed.
6659 *
6660 * @author Vova Feldman (@svovaf)
6661 * @since 1.1.7.3
6662 *
6663 * @return int|false
6664 */
6665 function last_sync_cron() {
6666 return $this->cron_last_execution( 'sync' );
6667 }
6668
6669 #endregion Daily Sync Cron ------------------------------------------------------------------
6670
6671 #----------------------------------------------------------------------------------
6672 #region Async Install Sync
6673 #----------------------------------------------------------------------------------
6674
6675 /**
6676 * @author Vova Feldman (@svovaf)
6677 * @since 1.1.7.3
6678 *
6679 * @return bool
6680 */
6681 private function is_install_sync_scheduled() {
6682 return $this->is_cron_on( 'install_sync' );
6683 }
6684
6685 /**
6686 * Get the sync cron's executing blog ID.
6687 *
6688 * @author Vova Feldman (@svovaf)
6689 * @since 2.0.0
6690 *
6691 * @return int
6692 */
6693 private function get_install_sync_cron_blog_id() {
6694 return $this->get_cron_blog_id( 'install_sync' );
6695 }
6696
6697 /**
6698 * Unix timestamp for previous install sync cron execution or false if never executed.
6699 *
6700 * @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.
6701 *
6702 * @author Vova Feldman (@svovaf)
6703 * @since 1.1.7.3
6704 *
6705 * @return int|false
6706 */
6707 function last_install_sync() {
6708 return $this->cron_last_execution( 'install_sync' );
6709 }
6710
6711 /**
6712 * Unix timestamp for next install sync cron execution or false if not scheduled.
6713 *
6714 * @author Vova Feldman (@svovaf)
6715 * @since 1.1.7.3
6716 *
6717 * @return int|false
6718 */
6719 function next_install_sync() {
6720 return $this->get_next_scheduled_cron( 'install_sync', 'install_sync' );
6721 }
6722
6723 /**
6724 * Add the actual install sync function to the cron job hook.
6725 *
6726 * @author Vova Feldman (@svovaf)
6727 * @since 1.1.7.3
6728 */
6729 private function hook_callback_to_install_sync() {
6730 $this->add_action( 'install_sync', array( &$this, '_run_sync_install' ) );
6731 }
6732
6733 /**
6734 * @author Vova Feldman (@svovaf)
6735 * @since 1.1.7.3
6736 *
6737 * @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.
6738 */
6739 private function clear_install_sync_cron( $is_network_clear = false ) {
6740 $this->_logger->entrance();
6741
6742 $this->clear_cron( 'install_sync', 'install_sync', $is_network_clear );
6743 }
6744
6745 /**
6746 * @author Vova Feldman (@svovaf)
6747 * @since 1.1.7.3
6748 * @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.
6749 */
6750 public function _run_sync_install() {
6751 $this->_logger->entrance();
6752
6753 $this->execute_cron( 'sync', array( &$this, '_sync_install_cron_method' ) );
6754 }
6755
6756 /**
6757 * The actual install(s) sync cron logic.
6758 *
6759 * @author Vova Feldman (@svovaf)
6760 * @since 2.0.0
6761 *
6762 * @param int[] $blog_ids
6763 * @param int|null $current_blog_id
6764 */
6765 function _sync_install_cron_method( array $blog_ids, $current_blog_id = null ) {
6766 if ( $this->is_registered() ) {
6767 if ( 1 < count( $blog_ids ) ) {
6768 $this->sync_installs( array(), true );
6769 } else {
6770 $this->sync_install( array(), true );
6771 }
6772
6773 $this->maybe_sync_install_user();
6774 }
6775 }
6776
6777 #endregion Async Install Sync ------------------------------------------------------------------
6778
6779 /**
6780 * Show a notice that activation is currently pending.
6781 *
6782 * @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.
6783 *
6784 * @author Vova Feldman (@svovaf)
6785 * @since 1.0.7
6786 *
6787 * @param bool|string $email_address
6788 * @param bool $is_pending_trial Since 1.2.1.5
6789 * @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.
6790 * @param bool $has_upgrade_context Since 2.5.3
6791 * @param bool $support_email_address Since 2.5.3
6792 */
6793 function _add_pending_activation_notice(
6794 $email_address = false,
6795 $is_pending_trial = false,
6796 $is_suspicious_email = false,
6797 $has_upgrade_context = false,
6798 $support_email_address = false
6799 ) {
6800 if ( ! is_string( $email_address ) ) {
6801 $current_user = self::_get_current_wp_user();
6802 $email_address = $current_user->user_email;
6803 }
6804
6805 $formatted_message_args = array(
6806 "<b>{$this->get_plugin_name()}</b>",
6807 "<b>{$email_address}</b>",
6808 );
6809
6810 if ( ! $has_upgrade_context || ! fs_is_network_admin() ) {
6811 /* translators: %3$s: action (e.g.: "start the trial" or "complete the opt-in") */
6812 $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' );
6813
6814 $formatted_message_args[] = $is_pending_trial ?
6815 $this->get_text_inline( 'start the trial', 'start-the-trial' ) :
6816 $this->get_text_inline( 'complete the opt-in', 'complete-the-opt-in' );
6817
6818 $notice_title = $this->get_text_inline( 'Thanks!', 'thanks' );
6819 } else {
6820 /* translators: %3$s: What the user is expected to receive via email (e.g.: "the installation instructions" or "a license key") */
6821 $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.' );
6822
6823 if ( $this->has_release_on_freemius() ) {
6824 $formatted_message_args[] = $this->get_text_x_inline(
6825 'the installation instructions',
6826 'Part of the message telling the user what they should receive via email.',
6827 'the-installation-instructions-phrase'
6828 );
6829 } else {
6830 $formatted_message_args[] = $this->get_text_x_inline(
6831 'a license key',
6832 'Part of the message telling the user what they should receive via email.',
6833 'a-license-key-phrase'
6834 );
6835
6836 $formatted_message .= ( ' ' . sprintf(
6837 /* translators: %s: activation link (e.g.: <a>Click here</a>) */
6838 $this->get_text_inline( '%s to activate the license once you get it.', 'license-activation-link-message' ),
6839 sprintf(
6840 '<b><a href="%s">%s</a></b>',
6841 $this->get_activation_url( array(
6842 'fs_action' => 'reset_pending_activation_mode',
6843 'require_license' => 'true',
6844 'fs_unique_affix' => $this->get_unique_affix(),
6845 ) ),
6846 $this->get_text_x_inline( 'Click here', 'Part of an activation link message.', 'click-here' )
6847 )
6848 ) );
6849 }
6850
6851 $formatted_message_args[] = ( ! empty( $support_email_address ) ) ?
6852 ( "<b>{$support_email_address}</b>" ) :
6853 $this->get_text_x_inline(
6854 "the product's support email address",
6855 'Part of the message that tells the user to check their spam folder for a specific email.',
6856 'product-support-email-address-phrase'
6857 );
6858
6859 $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' ) );
6860
6861 $notice_title = $this->get_text_inline( 'Thanks for upgrading.', 'after-upgrade-thank-you-message' );
6862 }
6863
6864 $this->_admin_notices->add_sticky(
6865 vsprintf( $formatted_message, $formatted_message_args ),
6866 'activation_pending',
6867 $notice_title
6868 );
6869 }
6870
6871 /**
6872 * Check if currently in plugin activation.
6873 *
6874 * @author Vova Feldman (@svovaf)
6875 * @since 1.1.4
6876 *
6877 * @return bool
6878 */
6879 function is_plugin_activation() {
6880 $result = get_transient( "fs_{$this->_module_type}_{$this->_slug}_activated" );
6881
6882 return !empty($result);
6883 }
6884
6885 /**
6886 *
6887 * NOTE: admin_menu action executed before admin_init.
6888 *
6889 * @author Vova Feldman (@svovaf)
6890 * @since 1.0.7
6891 */
6892 function _admin_init_action() {
6893 $is_migration = $this->is_migration();
6894
6895 /**
6896 * Automatically redirect to connect/activation page after plugin activation.
6897 *
6898 * @since 1.1.7 Do NOT redirect to opt-in when running in network admin mode.
6899 */
6900 if ( $this->is_plugin_activation() ) {
6901 delete_transient( "fs_{$this->_module_type}_{$this->_slug}_activated" );
6902
6903 if ( isset( $_GET['activate-multi'] ) ) {
6904 /**
6905 * Don't redirect if activating multiple plugins at once (bulk activation).
6906 */
6907 } else if (
6908 self::is_deactivation_snoozed() &&
6909 (
6910 // Either running the free code base.
6911 ! $this->is_premium() ||
6912 // Or if has a free version.
6913 ! $this->is_only_premium() ||
6914 // If premium only, don't redirect if license is activated.
6915 ( $this->is_registered() && ! $this->can_use_premium_code() )
6916 )
6917 ) {
6918 /**
6919 * 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.
6920 */
6921 } else if ( ! $is_migration ) {
6922 $this->_redirect_on_activation_hook();
6923 return;
6924 }
6925 }
6926
6927 if ( $is_migration ) {
6928 return;
6929 }
6930
6931 if ( fs_request_is_action( $this->get_unique_affix() . '_skip_activation' ) ) {
6932 check_admin_referer( $this->get_unique_affix() . '_skip_activation' );
6933
6934 $this->skip_connection( fs_is_network_admin() );
6935
6936 fs_redirect( $this->get_after_activation_url( 'after_skip_url' ) );
6937 }
6938
6939 if ( $this->is_network_activation_mode() &&
6940 fs_request_is_action( $this->get_unique_affix() . '_delegate_activation' )
6941 ) {
6942 check_admin_referer( $this->get_unique_affix() . '_delegate_activation' );
6943
6944 $this->delegate_connection();
6945
6946 fs_redirect( $this->get_after_activation_url( 'after_delegation_url' ) );
6947 }
6948
6949 $this->_add_upgrade_action_link();
6950
6951 if ( ! ( ! $this->_is_network_active && fs_is_network_admin() ) &&
6952 (
6953 ( true === $this->_storage->require_license_activation ) ||
6954 // Not registered nor anonymous.
6955 ( ! $this->is_registered() && ! $this->is_anonymous() ) ||
6956 // OR, network level and in network upgrade mode.
6957 ( fs_is_network_admin() && $this->_is_network_active && $this->is_network_upgrade_mode() )
6958 )
6959 ) {
6960 if ( ! $this->is_pending_activation() ) {
6961 if ( ! $this->is_activation_page() ) {
6962 /**
6963 * If a user visits any other admin page before activating the premium-only theme with a valid
6964 * license, reactivate the previous theme.
6965 *
6966 * @author Leo Fajardo (@leorw)
6967 * @since 1.2.2
6968 */
6969 if ( $this->is_theme() &&
6970 ! $this->has_settings_menu() &&
6971 ! isset( $_REQUEST['fs_action'] ) &&
6972 $this->can_activate_previous_theme()
6973 ) {
6974 if ( $this->is_only_premium() ) {
6975 $this->activate_previous_theme();
6976 return;
6977 }
6978
6979 if ( true === $this->_storage->require_license_activation ) {
6980 $this->_storage->require_license_activation = false;
6981 }
6982 }
6983
6984 if ( ! fs_is_network_admin() &&
6985 $this->is_network_activation_mode() &&
6986 ! $this->is_delegated_connection()
6987 ) {
6988 return;
6989 }
6990
6991 if ( $this->is_plugin_new_install() || $this->is_only_premium() ) {
6992 if ( ! $this->_anonymous_mode &&
6993 ( ! $this->is_addon() || ! $this->_parent->is_anonymous() ) ) {
6994 // Show notice for new plugin installations.
6995 $this->_admin_notices->add(
6996 sprintf(
6997 $this->get_text_inline( 'You are just one step away - %s', 'you-are-step-away' ),
6998 sprintf( '<b><a href="%s">%s</a></b>',
6999 $this->get_activation_url( array(), ! $this->is_delegated_connection() ),
7000 sprintf( $this->get_text_x_inline( 'Complete "%s" Activation Now',
7001 '%s - plugin name. As complete "PluginX" activation now', 'activate-x-now' ), $this->get_plugin_name() )
7002 )
7003 ),
7004 '',
7005 'update-nag'
7006 );
7007 }
7008 } else {
7009 if ( $this->should_add_sticky_optin_notice() ) {
7010 $this->add_sticky_optin_admin_notice();
7011 }
7012
7013 if ( $this->has_filter( 'optin_pointer_element' ) ) {
7014 // Don't show admin nag if plugin update.
7015 wp_enqueue_script( 'wp-pointer' );
7016 wp_enqueue_style( 'wp-pointer' );
7017
7018 $this->_enqueue_connect_essentials();
7019
7020 add_action( 'admin_print_footer_scripts', array(
7021 $this,
7022 '_add_connect_pointer_script'
7023 ) );
7024 }
7025 }
7026 }
7027 }
7028
7029 if ( $this->show_opt_in_on_themes_page() &&
7030 $this->is_activation_page()
7031 ) {
7032 $this->_show_theme_activation_optin_dialog();
7033 }
7034 }
7035 }
7036
7037 /**
7038 * @author Vova Feldman (@svovaf)
7039 * @since 2.0.0
7040 *
7041 * @return bool
7042 */
7043 private function should_add_sticky_optin_notice() {
7044 if ( $this->is_addon() && $this->_parent->is_anonymous() ) {
7045 return false;
7046 }
7047
7048 if ( fs_is_network_admin() ) {
7049 if ( ! $this->_is_network_active ) {
7050 return false;
7051 }
7052
7053 if ( ! $this->is_network_activation_mode() ) {
7054 return false;
7055 }
7056
7057 return ! isset( $this->_storage->sticky_optin_added_ms );
7058 }
7059
7060 if ( ! $this->is_activation_mode() ) {
7061 return false;
7062 }
7063
7064 // If running from a blog admin and delegated the connection.
7065 return ! isset( $this->_storage->sticky_optin_added );
7066 }
7067
7068 /**
7069 * @author Leo Fajardo (@leorw)
7070 * @since 2.0.0
7071 */
7072 private function add_sticky_optin_admin_notice() {
7073 if ( ! $this->_is_network_active || ! fs_is_network_admin() ) {
7074 $this->_storage->sticky_optin_added = true;
7075 } else {
7076 $this->_storage->sticky_optin_added_ms = true;
7077 }
7078
7079 // Show notice for new plugin installations.
7080 $this->_admin_notices->add_sticky(
7081 sprintf(
7082 $this->get_text_inline( 'We made a few tweaks to the %s, %s', 'few-plugin-tweaks' ),
7083 $this->_module_type,
7084 sprintf( '<b><a href="%s">%s</a></b>',
7085 $this->get_activation_url(),
7086 sprintf( $this->get_text_inline( 'Opt in to make "%s" better!', 'optin-x-now' ), $this->get_plugin_name() )
7087 )
7088 ),
7089 'connect_account',
7090 '',
7091 'update-nag'
7092 );
7093 }
7094
7095 /**
7096 * Enqueue connect requires scripts and styles.
7097 *
7098 * @author Vova Feldman (@svovaf)
7099 * @since 1.1.4
7100 */
7101 function _enqueue_connect_essentials() {
7102 wp_enqueue_script( 'jquery' );
7103 wp_enqueue_script( 'json2' );
7104
7105 fs_enqueue_local_script( 'postmessage', 'nojquery.ba-postmessage.js' );
7106 fs_enqueue_local_script( 'fs-postmessage', 'postmessage.js' );
7107 }
7108
7109 /**
7110 * Add connect / opt-in pointer.
7111 *
7112 * @author Vova Feldman (@svovaf)
7113 * @since 1.1.4
7114 */
7115 function _add_connect_pointer_script() {
7116 $vars = array( 'id' => $this->_module_id );
7117 $pointer_content = fs_get_template( 'connect.php', $vars );
7118 ?>
7119 <script type="text/javascript">// <![CDATA[
7120 jQuery(document).ready(function ($) {
7121 if ('undefined' !== typeof(jQuery().pointer)) {
7122
7123 var element = <?php echo $this->apply_filters( 'optin_pointer_element', '$("#non_existing_element");' ) ?>;
7124
7125 if (element.length > 0) {
7126 var optin = $(element).pointer($.extend(true, {}, {
7127 content : <?php echo json_encode( $pointer_content ) ?>,
7128 position : {
7129 edge : 'left',
7130 align: 'center'
7131 },
7132 buttons : function () {
7133 // Don't show pointer buttons.
7134 return '';
7135 },
7136 pointerWidth: 482
7137 }, <?php echo $this->apply_filters( 'optin_pointer_options_json', '{}' ) ?>));
7138
7139 <?php
7140 echo $this->apply_filters( 'optin_pointer_execute', "
7141
7142 optin.pointer('open');
7143
7144 // Tag the opt-in pointer with custom class.
7145 $('.wp-pointer #fs_connect')
7146 .parents('.wp-pointer.wp-pointer-top')
7147 .addClass('fs-opt-in-pointer');
7148
7149 ", 'element', 'optin' ) ?>
7150 }
7151 }
7152 });
7153 // ]]></script>
7154 <?php
7155 }
7156
7157 /**
7158 * Return current page's URL.
7159 *
7160 * @author Vova Feldman (@svovaf)
7161 * @since 1.0.7
7162 *
7163 * @return string
7164 */
7165 static function current_page_url() {
7166 $url = 'http';
7167
7168 if ( isset( $_SERVER["HTTPS"] ) ) {
7169 if ( $_SERVER["HTTPS"] == "on" ) {
7170 $url .= "s";
7171 }
7172 }
7173 $url .= "://";
7174 if ( $_SERVER["SERVER_PORT"] != "80" ) {
7175 $url .= $_SERVER["SERVER_NAME"] . ":" . $_SERVER["SERVER_PORT"] . $_SERVER["REQUEST_URI"];
7176 } else {
7177 $url .= $_SERVER["SERVER_NAME"] . $_SERVER["REQUEST_URI"];
7178 }
7179
7180 return esc_url( $url );
7181 }
7182
7183 /**
7184 * Check if the current page is the plugin's main admin settings page.
7185 *
7186 * @author Vova Feldman (@svovaf)
7187 * @since 1.0.7
7188 *
7189 * @return bool
7190 */
7191 function _is_plugin_page() {
7192 return fs_is_plugin_page( $this->_menu->get_raw_slug() ) ||
7193 fs_is_plugin_page( $this->_slug );
7194 }
7195
7196 /* Events
7197 ------------------------------------------------------------------------------------------------------------------*/
7198 /**
7199 * Delete site install from Database.
7200 *
7201 * @author Vova Feldman (@svovaf)
7202 * @since 1.0.1
7203 *
7204 * @param bool $store
7205 * @param int|null $blog_id Since 2.0.0
7206 *
7207 * @return false|int The install ID if deleted. Otherwise, FALSE (when install not exist).
7208 */
7209 function _delete_site( $store = true, $blog_id = null ) {
7210 return self::_delete_site_by_slug( $this->_slug, $this->_module_type, $store, $blog_id );
7211 }
7212
7213 /**
7214 * Delete site install from Database.
7215 *
7216 * @author Vova Feldman (@svovaf)
7217 * @since 1.2.2.7
7218 *
7219 * @param string $slug
7220 * @param string $module_type
7221 * @param bool $store
7222 * @param int|null $blog_id Since 2.0.0
7223 *
7224 * @return false|int The install ID if deleted. Otherwise, FALSE (when install not exist).
7225 */
7226 static function _delete_site_by_slug( $slug, $module_type, $store = true, $blog_id = null ) {
7227 $sites = self::get_all_sites( $module_type, $blog_id );
7228
7229 $install_id = false;
7230
7231 if ( isset( $sites[ $slug ] ) ) {
7232 if ( is_object( $sites[ $slug ] ) ) {
7233 $install_id = $sites[ $slug ]->id;
7234 }
7235
7236 unset( $sites[ $slug ] );
7237
7238 self::set_account_option_by_module( $module_type, 'sites', $sites, $store, $blog_id );
7239 }
7240
7241 return $install_id;
7242 }
7243
7244 /**
7245 * Delete plugin's plans information.
7246 *
7247 * @param bool $store Flush to Database if true.
7248 * @param bool $keep_associated_plans If set to false, delete all plans, even if a plan is associated with an install.
7249 *
7250 * @author Vova Feldman (@svovaf)
7251 * @since 1.0.9
7252 */
7253 private function _delete_plans( $store = true, $keep_associated_plans = true ) {
7254 $this->_logger->entrance();
7255
7256 $plans = self::get_all_plans( $this->_module_type );
7257
7258 $plans_to_keep = array();
7259
7260 if ( $keep_associated_plans ) {
7261 $plans_ids_to_keep = $this->get_plans_ids_associated_with_installs();
7262 foreach ( $plans_ids_to_keep as $plan_id ) {
7263 $plan = self::_get_plan_by_id( $plan_id );
7264 if ( is_object( $plan ) ) {
7265 $plans_to_keep[] = self::_encrypt_entity( $plan );
7266 }
7267 }
7268 }
7269
7270 if ( ! empty( $plans_to_keep ) ) {
7271 $plans[ $this->_slug ] = $plans_to_keep;
7272 } else {
7273 unset( $plans[ $this->_slug ] );
7274 }
7275
7276 $this->set_account_option( 'plans', $plans, $store );
7277 }
7278
7279 /**
7280 * Delete all plugin licenses.
7281 *
7282 * @author Vova Feldman (@svovaf)
7283 * @since 1.0.9
7284 *
7285 * @param bool $store
7286 */
7287 private function _delete_licenses( $store = true ) {
7288 $this->_logger->entrance();
7289
7290 $all_licenses = self::get_all_licenses();
7291
7292 unset( $all_licenses[ $this->_module_id ] );
7293
7294 self::$_accounts->set_option( 'all_licenses', $all_licenses, $store );
7295 }
7296
7297 /**
7298 * Check if Freemius was added on new plugin installation.
7299 *
7300 * @author Vova Feldman (@svovaf)
7301 * @since 1.1.5
7302 *
7303 * @return bool
7304 */
7305 function is_plugin_new_install() {
7306 return isset( $this->_storage->is_plugin_new_install ) &&
7307 $this->_storage->is_plugin_new_install;
7308 }
7309
7310 /**
7311 * Check if it's the first plugin release that is running Freemius.
7312 *
7313 * @author Vova Feldman (@svovaf)
7314 * @since 1.2.1.5
7315 *
7316 * @return bool
7317 */
7318 function is_first_freemius_powered_version() {
7319 return empty( $this->_storage->plugin_last_version );
7320 }
7321
7322 /**
7323 * @author Leo Fajardo (@leorw)
7324 * @since 1.2.2
7325 *
7326 * @return bool|string
7327 */
7328 private function get_previous_theme_slug() {
7329 return isset( $this->_storage->previous_theme ) ?
7330 $this->_storage->previous_theme :
7331 false;
7332 }
7333
7334 /**
7335 * @author Leo Fajardo (@leorw)
7336 * @since 1.2.2
7337 *
7338 * @return bool
7339 */
7340 private function can_activate_previous_theme() {
7341 return $this->can_activate_theme( $this->get_previous_theme_slug() );
7342 }
7343
7344 /**
7345 * @author Leo Fajardo (@leorw)
7346 * @since 2.5.0
7347 *
7348 * @return bool
7349 */
7350 private function can_activate_theme( $slug ) {
7351 if ( false !== $slug && current_user_can( 'switch_themes' ) ) {
7352 $theme_instance = wp_get_theme( $slug );
7353
7354 return $theme_instance->exists();
7355 }
7356
7357 return false;
7358 }
7359
7360 /**
7361 * @author Leo Fajardo (@leorw)
7362 * @since 1.2.2
7363 */
7364 private function activate_previous_theme() {
7365 switch_theme( $this->get_previous_theme_slug() );
7366 unset( $this->_storage->previous_theme );
7367
7368 global $pagenow;
7369 if ( 'themes.php' === $pagenow ) {
7370 /**
7371 * Refresh the active theme information.
7372 *
7373 * @author Leo Fajardo (@leorw)
7374 * @since 1.2.2
7375 */
7376 fs_redirect( $this->admin_url( $pagenow ) );
7377 }
7378 }
7379
7380 /**
7381 * @author Leo Fajardo (@leorw)
7382 * @since 1.2.2
7383 *
7384 * @return string
7385 */
7386 function get_previous_theme_activation_url() {
7387 if ( ! $this->can_activate_previous_theme() ) {
7388 return '';
7389 }
7390
7391 /**
7392 * Activation URL
7393 *
7394 * @author Leo Fajardo (@leorw)
7395 * @since 1.2.2
7396 */
7397 return wp_nonce_url(
7398 $this->admin_url( 'themes.php?action=activate&stylesheet=' . urlencode( $this->get_previous_theme_slug() ) ),
7399 'switch-theme_' . $this->get_previous_theme_slug()
7400 );
7401 }
7402
7403 /**
7404 * Saves the slug of the previous theme if it still exists so that it can be used by the logic in the opt-in
7405 * form that decides whether to add a close button to the opt-in dialog or not. So after a premium-only theme is
7406 * activated, the close button will appear and will reactivate the previous theme if clicked. If the previous
7407 * theme doesn't exist, then there will be no close button.
7408 *
7409 * @author Leo Fajardo (@leorw)
7410 * @since 1.2.2
7411 *
7412 * @param string $slug_or_name Old theme's slug or name.
7413 * @param bool|WP_Theme $old_theme WP_Theme instance of the old theme if it still exists.
7414 */
7415 function _activate_theme_event_hook( $slug_or_name, $old_theme = false ) {
7416 $this->_storage->previous_theme = ( false !== $old_theme ) ?
7417 $old_theme->get_stylesheet() :
7418 $slug_or_name;
7419
7420 $this->_activate_plugin_event_hook();
7421 }
7422
7423 /**
7424 * Plugin activated hook.
7425 *
7426 * @author Vova Feldman (@svovaf)
7427 * @since 1.0.1
7428 *
7429 * @uses FS_Api
7430 */
7431 function _activate_plugin_event_hook() {
7432 $this->_logger->entrance( 'slug = ' . $this->_slug );
7433
7434 if ( ! $this->is_user_admin() ) {
7435 return;
7436 }
7437
7438 $this->unregister_uninstall_hook();
7439
7440 // Clear API cache on activation.
7441 FS_Api::clear_cache();
7442
7443 $is_premium_version_activation = $this->is_plugin() ?
7444 ( current_filter() !== ( 'activate_' . $this->_free_plugin_basename ) ) :
7445 $this->is_premium();
7446
7447 if ( $is_premium_version_activation && $this->is_pending_activation() ) {
7448 $this->clear_pending_activation_mode();
7449 }
7450
7451 $this->_logger->info( 'Activating ' . ( $is_premium_version_activation ? 'premium' : 'free' ) . ' plugin version.' );
7452
7453 if ( $this->is_plugin() ) {
7454 // This logic is relevant only to plugins since both the free and premium versions of a plugin can be active at the same time.
7455 // 1. If running in the activation of the FREE module, get the basename of the PREMIUM.
7456 // 2. If running in the activation of the PREMIUM module, get the basename of the FREE.
7457 $other_version_basename = $is_premium_version_activation ?
7458 $this->_free_plugin_basename :
7459 $this->premium_plugin_basename();
7460
7461 if ( ! $this->_is_network_active ) {
7462 /**
7463 * Themes are always network activated, but the ACTUAL activation is per site.
7464 *
7465 * During the activation, the plugin isn't yet active, therefore,
7466 * _is_network_active will be set to false even if it's a network level
7467 * activation. So we need to fix that by looking at the is_network_admin() value.
7468 *
7469 * @author Vova Feldman
7470 */
7471 $this->_is_network_active = (
7472 $this->_is_multisite_integrated &&
7473 fs_is_network_admin()
7474 );
7475 }
7476
7477 /**
7478 * If the other module version is active, deactivate it.
7479 *
7480 * is_plugin_active() checks if the plugin is active on the site or the network level and
7481 * deactivate_plugins() deactivates the plugin whether it's activated on the site or network level.
7482 *
7483 * @author Leo Fajardo (@leorw)
7484 * @since 1.2.2
7485 */
7486 if (
7487 is_plugin_active( $other_version_basename ) &&
7488 $this->apply_filters( 'deactivate_on_activation', ! $this->is_parallel_activation() )
7489 ) {
7490 deactivate_plugins( $other_version_basename );
7491 }
7492 }
7493
7494 if ( $this->is_registered() ) {
7495 if ( $is_premium_version_activation ) {
7496 $this->reconnect_locally();
7497 }
7498
7499
7500 // Schedule re-activation event and sync.
7501 // $this->sync_install( array(), true );
7502 $this->maybe_schedule_install_sync_cron();
7503
7504 // If activating the premium module version, add an admin notice to congratulate for an upgrade completion.
7505 if ( $is_premium_version_activation ) {
7506 $this->_admin_notices->add(
7507 sprintf( $this->get_text_inline( 'The upgrade of %s was successfully completed.', 'successful-version-upgrade-message' ), sprintf( '<b>%s</b>', $this->_plugin->title ) ),
7508 $this->get_text_x_inline( 'W00t',
7509 'Used to express elation, enthusiasm, or triumph (especially in electronic communication).', 'woot' ) . '!'
7510 );
7511 }
7512 } else if ( $this->is_anonymous() ) {
7513 if ( isset( $this->_storage->is_anonymous_ms ) && $this->_storage->is_anonymous_ms['is'] ) {
7514 $plugin_version = $this->_storage->is_anonymous_ms['version'];
7515 $network = true;
7516 } else {
7517 $plugin_version = isset( $this->_storage->is_anonymous ) ?
7518 $this->_storage->is_anonymous['version'] :
7519 null;
7520 $network = false;
7521 }
7522
7523 /**
7524 * Reset "skipped" click cache on the following:
7525 * 1. Freemius DEV mode.
7526 * 2. WordPress DEBUG mode.
7527 * 3. If a plugin and the user skipped the exact same version before.
7528 *
7529 * @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).
7530 *
7531 * @todo 4. If explicitly asked to retry after every activation.
7532 */
7533 if ( WP_FS__DEV_MODE ||
7534 (
7535 ( $this->is_plugin() || ( defined( 'WP_DEBUG' ) && WP_DEBUG ) ) &&
7536 $this->get_plugin_version() == $plugin_version
7537 )
7538 ) {
7539 $this->reset_anonymous_mode( $network );
7540 }
7541 }
7542
7543 $is_trial_or_has_features_enabled_license = ( $this->is_trial() || $this->has_features_enabled_license() );
7544
7545 if ( $this->is_addon() && ! $is_trial_or_has_features_enabled_license ) {
7546 /**
7547 * When activating an add-on, try to also activate a license.
7548 *
7549 * @author Leo Fajardo (@leorw)
7550 * @since 2.3.0
7551 */
7552 if ( ! $this->_is_network_active ) {
7553 $this->maybe_activate_addon_license();
7554 } else {
7555 $this->maybe_network_activate_addon_license();
7556 }
7557
7558 /**
7559 * Avoid redirecting to the license activation screen after automatically activating an add-on license.
7560 *
7561 * @author Leo Fajardo (@leorw)
7562 * @since 2.3.0
7563 */
7564 $is_trial_or_has_features_enabled_license = ( $this->is_trial() || $this->has_features_enabled_license() );
7565
7566 if ( $is_trial_or_has_features_enabled_license && true === $this->_storage->require_license_activation ) {
7567 $this->_storage->require_license_activation = false;
7568 }
7569 }
7570
7571 if (
7572 $is_premium_version_activation &&
7573 (
7574 ( ! $this->is_registered() && $this->is_anonymous() ) ||
7575 (
7576 $this->is_registered() &&
7577 ! $is_trial_or_has_features_enabled_license
7578 )
7579 )
7580 ) {
7581 $this->_storage->require_license_activation = true;
7582 }
7583
7584 if ( ! isset( $this->_storage->is_plugin_new_install ) ) {
7585 /**
7586 * If no previous version of plugin's version exist, it means that it's either
7587 * the first time that the plugin installed on the site, or the plugin was installed
7588 * before but didn't have Freemius integrated.
7589 *
7590 * Since register_activation_hook() do NOT fires on updates since 3.1, and only fires
7591 * on manual activation via the dashboard, is_plugin_activation() is TRUE
7592 * only after immediate activation.
7593 *
7594 * @since 1.1.4
7595 * @link https://make.wordpress.org/core/2010/10/27/plugin-activation-hooks-no-longer-fire-for-updates/
7596 */
7597 $this->_storage->is_plugin_new_install = empty( $this->_storage->plugin_last_version );
7598 }
7599
7600 /**
7601 * Also flush when activating the premium version so that even if Freemius was off before, the API
7602 * connectivity test can be run again.
7603 *
7604 * @author Leo Fajardo (@leorw)
7605 * @since 2.2.3.1
7606 */
7607 $has_api_connectivity = $this->has_api_connectivity( WP_FS__DEV_MODE || $is_premium_version_activation );
7608
7609 if ( ! $this->_anonymous_mode &&
7610 ( false !== $has_api_connectivity ) &&
7611 ! $this->_isAutoInstall
7612 ) {
7613 // Store hint that the plugin was just activated to enable auto-redirection to settings.
7614 set_transient( "fs_{$this->_module_type}_{$this->_slug}_activated", true, 60 );
7615 }
7616
7617 /**
7618 * Activation hook is executed after the plugin's main file is loaded, therefore,
7619 * after the plugin was loaded. The logic is located at activate_plugin()
7620 * ./wp-admin/includes/plugin.php.
7621 *
7622 * @author Vova Feldman (@svovaf)
7623 * @since 1.1.9
7624 */
7625 $this->_storage->was_plugin_loaded = true;
7626 }
7627
7628 /**
7629 * @author Leo Fajardo (@leorw)
7630 * @since 2.3.0
7631 */
7632 private function maybe_activate_addon_license() {
7633 $parent_fs = $this->get_parent_instance();
7634
7635 if (
7636 ! is_object( $parent_fs ) ||
7637 ( ! $parent_fs->is_registered() && ! $parent_fs->is_network_registered() )
7638 ) {
7639 // Try to activate a license only if the parent plugin is active and has a valid `install`.
7640 return;
7641 }
7642
7643 $license = $this->get_active_parent_license();
7644 if ( ! is_object( $license ) ) {
7645 return;
7646 }
7647
7648 if (
7649 $this->is_bundle_license_auto_activation_enabled() &&
7650 ! empty( $license->products )
7651 ) {
7652 $this->activate_bundle_license( $license );
7653
7654 return;
7655 }
7656
7657 if ( ! $this->is_registered() ) {
7658 // Opt in with a license key.
7659 $this->opt_in(
7660 $parent_fs->get_current_or_network_user()->email,
7661 false,
7662 false,
7663 $license->secret_key,
7664 false,
7665 false,
7666 false,
7667 null,
7668 array(),
7669 true,
7670 $license->user_id
7671 );
7672 } else {
7673 // Activate the license.
7674 $install = $this->api_site_call(
7675 '/',
7676 'put',
7677 array( 'license_key' => $this->apply_filters( 'license_key', $license->secret_key ) )
7678 );
7679
7680 if ( ! FS_Api::is_api_error( $install ) ) {
7681 $this->_sync_addon_license( $this->get_id(), true );
7682 }
7683 }
7684 }
7685
7686 /**
7687 * @author Leo Fajardo (@leorw)
7688 * @since 2.3.0
7689 *
7690 * @param FS_Plugin_License $license
7691 */
7692 private function maybe_network_activate_addon_license( $license = null ) {
7693 $parent_fs = $this->get_parent_instance();
7694 if ( ! is_object( $parent_fs ) || ( ! $parent_fs->is_registered() && ! $parent_fs->is_network_registered() ) ) {
7695 // Try to activate a license only if the parent plugin is active and has a valid `install`.
7696 return;
7697 }
7698
7699 $license = ( ! is_null( $license ) ) ?
7700 $license :
7701 $this->get_active_parent_license();
7702
7703 if ( ! is_object( $license ) ) {
7704 return;
7705 }
7706
7707 if (
7708 $this->is_bundle_license_auto_activation_enabled() &&
7709 ! empty( $license->products )
7710 ) {
7711 $this->activate_bundle_license( $license );
7712
7713 return;
7714 }
7715
7716 if ( ! $this->is_network_registered() ) {
7717 $sites = $this->get_sites_for_network_level_optin();
7718
7719 if ( count( $sites ) > $license->left() ) {
7720 // If the add-on is network active, try to activate the license only if it can be activated on all sites.
7721 return;
7722 }
7723
7724 // Opt in with a license key.
7725 $this->opt_in(
7726 $parent_fs->get_user()->email,
7727 false,
7728 false,
7729 $license->secret_key,
7730 false,
7731 false,
7732 false,
7733 null,
7734 $sites,
7735 true,
7736 $license->user_id
7737 );
7738 } else {
7739 $blog_2_install_map = array();
7740 $site_ids = array();
7741
7742 $all_sites = Freemius::get_sites();
7743
7744 foreach ( $all_sites as $site ) {
7745 $blog_id = Freemius::get_site_blog_id( $site );
7746 $install = $this->get_install_by_blog_id( $blog_id );
7747
7748 if ( is_object( $install ) && FS_Plugin_License::is_valid_id( $install->license_id ) ) {
7749 // Skip license activation for installs that are already associated with a license.
7750 continue;
7751 }
7752
7753 if ( is_object( $install ) ) {
7754 $blog_2_install_map[ $blog_id ] = $install;
7755 } else {
7756 $site_ids[] = $blog_id;
7757 }
7758 }
7759
7760 if ( ( count( $blog_2_install_map ) + count( $site_ids ) ) > $license->left() ) {
7761 return;
7762 }
7763
7764 $user = $this->get_current_or_network_user();
7765
7766 if ( ! empty( $blog_2_install_map ) ) {
7767 $result = $this->activate_license_on_many_installs( $user, $license->secret_key, $blog_2_install_map );
7768
7769 if ( true !== $result ) {
7770 return;
7771 }
7772 }
7773
7774 if ( ! empty( $site_ids ) ) {
7775 $this->activate_license_on_many_sites( $user, $license->secret_key, $site_ids );
7776 }
7777 }
7778 }
7779
7780 /**
7781 * 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.
7782 *
7783 * @author Leo Fajardo (@leorw)
7784 * @since 2.4.0
7785 *
7786 * @param FS_Plugin_License $license
7787 * @param array $sites
7788 * @param int $blog_id
7789 */
7790 private function maybe_activate_bundle_license( $license = null, $sites = array(), $blog_id = 0 ) {
7791 if ( ! is_object( $license ) && $this->has_active_valid_license() ) {
7792 $license = $this->_license;
7793 }
7794
7795 if ( ! is_object( $license ) ) {
7796 return;
7797 }
7798
7799 $parent_license = ( ! empty( $license->products ) ) ?
7800 $license :
7801 $this->get_active_parent_license( $license->secret_key );
7802
7803 if ( is_object( $parent_license ) ) {
7804 $this->activate_bundle_license( $parent_license, $sites, $blog_id );
7805 }
7806 }
7807
7808 /**
7809 * Try to activate a bundle license for all the bundle products installed on the site.
7810 * (1) If a child product install already has a license, the bundle license won't be activated.
7811 * (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.
7812 * (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.
7813 *
7814 * @author Leo Fajardo (@leorw)
7815 * @since 2.4.0
7816 *
7817 * @param FS_Plugin_License $license
7818 * @param array $sites
7819 * @param int $current_blog_id
7820 */
7821 private function activate_bundle_license( $license, $sites = array(), $current_blog_id = 0 ) {
7822 $is_network_admin = fs_is_network_admin();
7823
7824 $installs_by_blog_map = array();
7825 $site_info_by_blog_map = array();
7826
7827 /**
7828 * Try to activate the license for all supported products.
7829 *
7830 * @author Leo Fajardo
7831 */
7832 foreach ( $license->products as $product_id ) {
7833 $fs = self::get_instance_by_id( $product_id );
7834
7835 if ( ! is_object( $fs ) ) {
7836 continue;
7837 }
7838
7839 if ( ! $fs->has_paid_plan() ) {
7840 continue;
7841 }
7842
7843 if (
7844 ! $fs->is_addon() &&
7845 ! FS_Plan_Manager::instance()->has_paid_plan( $fs->_plans )
7846 ) {
7847 /**
7848 * The parent product can be free-only but can have its `has_paid_plan` flag set to `true` when
7849 * there is a context bundle.
7850 */
7851 continue;
7852 }
7853
7854 if ( $current_blog_id > 0 ) {
7855 $fs->switch_to_blog( $current_blog_id );
7856 }
7857
7858 if ( $fs->has_active_valid_license() ) {
7859 continue;
7860 }
7861
7862 if ( ! $is_network_admin || $current_blog_id > 0 ) {
7863 if ( $fs->is_network_active() && ! $fs->is_delegated_connection( $current_blog_id ) ) {
7864 // Do not try to activate the license in the site level if the product is network active and the connection was not delegated.
7865 continue;
7866 }
7867 } else {
7868 if ( ! $fs->is_network_active() ) {
7869 // Do not try to activate the license in the network level if the product is not network active.
7870 continue;
7871 }
7872
7873 if ( $fs->is_network_delegated_connection() ) {
7874 // Do not try to activate the license in the network level if the activation has been delegated to site admins.
7875 continue;
7876 }
7877
7878 $has_install_with_license = false;
7879
7880 // 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.
7881 $filtered_sites = array();
7882
7883 if ( empty( $sites ) ) {
7884 $all_sites = self::get_sites();
7885
7886 foreach ( $all_sites as $site ) {
7887 $sites[] = array( 'blog_id' => self::get_site_blog_id( $site ) );
7888 }
7889 } else {
7890 // Populate the map here to avoid calling `$fs->get_site_info( $site );` in the other `for` loop below.
7891 foreach ( $sites as $site ) {
7892 if ( ! isset( $site['blog_id'] ) || ! is_numeric( $site['blog_id'] ) ) {
7893 continue;
7894 }
7895
7896 $site_info_by_blog_map[ $site['blog_id'] ] = $site;
7897 }
7898 }
7899
7900 foreach ( $sites as $site ) {
7901 if ( ! isset( $site['blog_id'] ) || ! is_numeric( $site['blog_id'] ) ) {
7902 continue;
7903 }
7904
7905 $blog_id = $site['blog_id'];
7906
7907 if ( ! isset( $installs_by_blog_map[ $blog_id ] ) ) {
7908 $installs_by_blog_map[ $blog_id ] = self::get_all_sites( $fs->get_module_type(), $blog_id );
7909 }
7910
7911 $installs = $installs_by_blog_map[ $blog_id ];
7912 $install = null;
7913
7914 if ( isset( $installs[ $fs->get_slug() ] ) ) {
7915 $install = $installs[ $fs->get_slug() ];
7916
7917 if (
7918 is_object( $install ) &&
7919 (
7920 ! FS_Site::is_valid_id( $install->id ) ||
7921 ! FS_User::is_valid_id( $install->user_id ) ||
7922 ! FS_Plugin_Plan::is_valid_id( $install->plan_id )
7923 )
7924 ) {
7925 $install = null;
7926 }
7927 }
7928
7929 if (
7930 is_object( $install ) &&
7931 FS_Plugin_License::is_valid_id( $install->license_id )
7932 ) {
7933 $has_install_with_license = true;
7934 break;
7935 }
7936
7937 if ( $fs->is_site_delegated_connection( $blog_id ) ) {
7938 // Site activation delegated, don't activate bundle license on the site in the network admin.
7939 continue;
7940 }
7941
7942 if ( ! isset( $site_info_by_blog_map[ $blog_id ] ) ) {
7943 $site_info_by_blog_map[ $blog_id ] = $fs->get_site_info( $site );
7944 }
7945
7946 $filtered_sites[] = $site_info_by_blog_map[ $blog_id ];
7947 }
7948
7949 if ( $has_install_with_license || empty( $filtered_sites ) ) {
7950 // 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.
7951 continue;
7952 }
7953
7954 $sites = $filtered_sites;
7955 }
7956
7957 $fs->activate_migrated_license(
7958 $license->secret_key,
7959 null,
7960 null,
7961 $sites,
7962 ( $current_blog_id > 0 ? $current_blog_id : null ),
7963 $license->user_id
7964 );
7965 }
7966 }
7967
7968 /**
7969 * Returns a parent license that can be activated for the context product.
7970 *
7971 * @author Leo Fajardo (@leorw)
7972 * @since 2.3.0
7973 *
7974 * @param string|null $license_key
7975 * @param bool $flush
7976 *
7977 * @return FS_Plugin_License
7978 */
7979 function get_active_parent_license( $license_key = null, $flush = true ) {
7980 $parent_licenses_endpoint = "/plugins/{$this->get_id()}/parent_licenses.json?filter=activatable";
7981
7982 $fs = $this;
7983
7984 if ( $this->is_addon() ) {
7985 $parent_instance = $this->get_parent_instance();
7986
7987 if ( is_object( $parent_instance ) && $parent_instance->is_registered() ) {
7988 $fs = $parent_instance;
7989 }
7990 }
7991
7992 $foreign_licenses = $fs->get_foreign_licenses_info(
7993 self::get_all_licenses( $this->get_parent_id() )
7994 );
7995
7996 if ( ! empty ( $foreign_licenses ) ) {
7997 $foreign_licenses = array(
7998 // Prefix with `+` to tell the server to include foreign licenses in the licenses collection.
7999 'ids' => ( urlencode( '+' ) . implode( ',', $foreign_licenses['ids'] ) ),
8000 'license_keys' => implode( ',', array_map( 'urlencode', $foreign_licenses['license_keys'] ) )
8001 );
8002
8003 $parent_licenses_endpoint = add_query_arg( $foreign_licenses, $parent_licenses_endpoint );
8004 }
8005
8006 $result = $fs->get_current_or_network_user_api_scope()->get( $parent_licenses_endpoint, $flush );
8007
8008 if (
8009 ! $this->is_api_result_object( $result, 'licenses' ) ||
8010 ! is_array( $result->licenses ) ||
8011 empty( $result->licenses )
8012 ) {
8013 return null;
8014 }
8015
8016 $parent_license = null;
8017
8018 if ( empty( $license_key ) ) {
8019 $parent_license = $result->licenses[0];
8020 } else {
8021 foreach ( $result->licenses as $license ) {
8022 if ( $license_key === $license->secret_key ) {
8023 $parent_license = $license;
8024 break;
8025 }
8026 }
8027 }
8028
8029 if ( ! is_null( $parent_license ) ) {
8030 $parent_license = new FS_Plugin_License( $parent_license );
8031 }
8032
8033 return $parent_license;
8034 }
8035
8036 /**
8037 * @author Leo Fajardo (@leorw)
8038 * @since 2.3.0
8039 *
8040 * @return array
8041 */
8042 function get_sites_for_network_level_optin() {
8043 $sites = array();
8044 $all_sites = self::get_sites();
8045
8046 foreach ( $all_sites as $site ) {
8047 $blog_id = self::get_site_blog_id( $site );
8048
8049 if ( ! $this->is_site_delegated_connection( $blog_id ) &&
8050 ! $this->is_installed_on_site( $blog_id )
8051 ) {
8052 $sites[] = $this->get_site_info( $site );
8053 }
8054 }
8055
8056 return $sites;
8057 }
8058
8059 /**
8060 * Delete account.
8061 *
8062 * @author Vova Feldman (@svovaf)
8063 * @since 1.0.3
8064 *
8065 * @param bool $check_user Enforce checking if user have plugins activation privileges.
8066 */
8067 function delete_account_event( $check_user = true ) {
8068 $this->_logger->entrance( 'slug = ' . $this->_slug );
8069
8070 if ( $check_user && ! $this->is_user_admin() ) {
8071 return;
8072 }
8073
8074 $this->do_action( 'before_account_delete' );
8075
8076 // Clear all admin notices.
8077 $this->_admin_notices->clear_all_sticky( false );
8078
8079 $this->_delete_site( false );
8080
8081 $delete_network_common_data = true;
8082
8083 if ( $this->_is_network_active ) {
8084 $installs = $this->get_blog_install_map();
8085
8086 // Don't delete common network data unless no other installs left.
8087 $delete_network_common_data = empty( $installs );
8088 }
8089
8090 if ( $delete_network_common_data ) {
8091 $this->_delete_plans( false );
8092
8093 $this->_delete_licenses( false );
8094
8095 // Delete add-ons related to plugin's account.
8096 $this->_delete_account_addons( false );
8097 }
8098
8099 // @todo Delete plans and licenses of add-ons.
8100
8101 self::$_accounts->store();
8102
8103 /**
8104 * IMPORTANT:
8105 * Clear crons must be executed before clearing all storage.
8106 * Otherwise, the cron will not be cleared.
8107 */
8108 if ( $delete_network_common_data ) {
8109 $this->clear_sync_cron();
8110 }
8111
8112 $this->clear_install_sync_cron();
8113
8114 // Clear all storage data.
8115 $this->_storage->clear_all( true, array(
8116 'is_delegated_connection',
8117 'connectivity_test',
8118 'is_on',
8119 ), false );
8120
8121 // Send delete event.
8122 $this->get_api_site_scope()->call( '/', 'delete' );
8123
8124 $this->do_action( 'after_account_delete' );
8125 }
8126
8127 /**
8128 * Delete network level account.
8129 *
8130 * @author Vova Feldman (@svovaf)
8131 * @since 2.0.0
8132 *
8133 * @param bool $check_user Enforce checking if user have plugins activation privileges.
8134 */
8135 function delete_network_account_event( $check_user = true ) {
8136 $this->_logger->entrance( 'slug = ' . $this->_slug );
8137
8138 if ( $check_user && ! $this->is_user_admin() ) {
8139 return;
8140 }
8141
8142 $this->do_action( 'before_network_account_delete' );
8143
8144 // Clear all admin notices.
8145 $this->_admin_notices->clear_all_sticky();
8146
8147 $this->_delete_plans( false, false );
8148
8149 $this->_delete_licenses( false );
8150
8151 // Delete add-ons related to plugin's account.
8152 $this->_delete_account_addons( false );
8153
8154 // @todo Delete plans and licenses of add-ons.
8155
8156 self::$_accounts->store( true );
8157
8158 /**
8159 * IMPORTANT:
8160 * Clear crons must be executed before clearing all storage.
8161 * Otherwise, the cron will not be cleared.
8162 */
8163 $this->clear_sync_cron( true );
8164 $this->clear_install_sync_cron( true );
8165
8166 $sites = self::get_sites();
8167
8168 $install_ids = array();
8169 foreach ( $sites as $site ) {
8170 $blog_id = self::get_site_blog_id( $site );
8171
8172 if ( $this->is_site_delegated_connection( $blog_id ) ) {
8173 continue;
8174 }
8175
8176 $install_id = $this->_delete_site( true, $blog_id );
8177
8178 // Clear all storage data.
8179 $this->_storage->clear_all( true, array( 'connectivity_test' ), $blog_id );
8180
8181 if ( FS_Site::is_valid_id( $install_id ) ) {
8182 $install_ids[] = $install_id;
8183 }
8184
8185 switch_to_blog( $blog_id );
8186
8187 $this->do_action( 'after_account_delete' );
8188
8189 restore_current_blog();
8190 }
8191
8192 $this->_storage->clear_all( true, array(
8193 'connectivity_test',
8194 'is_on',
8195 ), true );
8196
8197 // Send delete event.
8198 if ( ! empty( $install_ids ) ) {
8199 $result = $this->get_current_or_network_user_api_scope()->call( "/plugins/{$this->_module_id}/installs.json?ids=" . implode( ',', $install_ids ), 'delete' );
8200 }
8201
8202 $this->do_action( 'after_network_account_delete' );
8203 }
8204
8205 /**
8206 * Plugin deactivation hook.
8207 *
8208 * @author Vova Feldman (@svovaf)
8209 * @since 1.0.1
8210 */
8211 function _deactivate_plugin_hook() {
8212 $this->_logger->entrance( 'slug = ' . $this->_slug );
8213
8214 if ( ! $this->is_user_admin() ) {
8215 return;
8216 }
8217
8218 $is_network_deactivation = fs_is_network_admin();
8219 $storage_keys_for_removal = array();
8220
8221 $this->_admin_notices->clear_all_sticky();
8222
8223 $storage_keys_for_removal[] = 'sticky_optin_added';
8224 if ( isset( $this->_storage->sticky_optin_added ) ) {
8225 unset( $this->_storage->sticky_optin_added );
8226 }
8227
8228 if ( ! isset( $this->_storage->is_plugin_new_install ) ) {
8229 // Remember that plugin was already installed.
8230 $this->_storage->is_plugin_new_install = false;
8231 }
8232
8233 // Hook to plugin uninstall.
8234 register_uninstall_hook( $this->_plugin_main_file_path, array( 'Freemius', '_uninstall_plugin_hook' ) );
8235
8236 $this->clear_module_main_file_cache();
8237 $this->clear_sync_cron( $this->_is_network_active );
8238 $this->clear_install_sync_cron();
8239
8240 if ( $this->is_registered() ) {
8241 if ( $this->is_premium() && ! $this->has_active_valid_license() ) {
8242 FS_Plugin_Updater::instance( $this )->delete_update_data();
8243 }
8244
8245 if ( $is_network_deactivation ) {
8246 // Send deactivation event.
8247 $this->sync_installs( array(
8248 'is_active' => false,
8249 ) );
8250 } else {
8251 // Send deactivation event.
8252 $this->sync_install( array(
8253 'is_active' => false,
8254 ) );
8255 }
8256 } else {
8257 if ( false === $this->has_api_connectivity() && ! $this->is_premium() ) {
8258 // Reset connectivity test cache.
8259 $this->clear_connectivity_info();
8260
8261 $storage_keys_for_removal[] = 'connectivity_test';
8262 }
8263 }
8264
8265 if ( $is_network_deactivation ) {
8266 if ( isset( $this->_storage->sticky_optin_added_ms ) ) {
8267 unset( $this->_storage->sticky_optin_added_ms );
8268 }
8269
8270 if ( ! empty( $storage_keys_for_removal ) ) {
8271 $sites = self::get_sites();
8272
8273 foreach ( $sites as $site ) {
8274 $blog_id = self::get_site_blog_id( $site );
8275
8276 foreach ( $storage_keys_for_removal as $key ) {
8277 $this->_storage->remove( $key, false, $blog_id );
8278 }
8279
8280 $this->_storage->save( $blog_id );
8281 }
8282 }
8283 }
8284
8285 // Clear API cache on deactivation.
8286 FS_Api::clear_cache();
8287
8288 $this->remove_sdk_reference();
8289 }
8290
8291 /**
8292 * @author Vova Feldman (@svovaf)
8293 * @since 1.1.6
8294 */
8295 private function remove_sdk_reference() {
8296 global $fs_active_plugins;
8297
8298 foreach ( $fs_active_plugins->plugins as $sdk_path => $data ) {
8299 if ( $this->_plugin_basename == $data->plugin_path ) {
8300 unset( $fs_active_plugins->plugins[ $sdk_path ] );
8301 break;
8302 }
8303 }
8304
8305 fs_fallback_to_newest_active_sdk();
8306 }
8307
8308 /**
8309 * @author Vova Feldman (@svovaf)
8310 * @since 1.1.3
8311 *
8312 * @param bool $is_anonymous
8313 * @param bool|int $network_or_blog_id Since 2.0.0
8314 */
8315 private function set_anonymous_mode( $is_anonymous = true, $network_or_blog_id = 0 ) {
8316 // Store information regarding skip to try and opt-in the user
8317 // again in the future.
8318 $skip_info = array(
8319 'is' => $is_anonymous,
8320 'timestamp' => WP_FS__SCRIPT_START_TIME,
8321 'version' => $this->get_plugin_version(),
8322 );
8323
8324 if ( true === $network_or_blog_id ) {
8325 $this->_storage->is_anonymous_ms = $skip_info;
8326 } else {
8327 $this->_storage->store( 'is_anonymous', $skip_info, $network_or_blog_id );
8328 }
8329
8330 $this->network_upgrade_mode_completed();
8331
8332 // Update anonymous mode cache.
8333 $this->_is_anonymous = $is_anonymous;
8334 }
8335
8336 /**
8337 * @author Vova Feldman (@svovaf)
8338 * @since 2.5.1
8339 *
8340 * @param bool|int $network_or_blog_id
8341 */
8342 private function unset_anonymous_mode( $network_or_blog_id = 0 ) {
8343 if ( true === $network_or_blog_id ) {
8344 unset( $this->_storage->is_anonymous_ms );
8345 } else {
8346 $this->_storage->remove( 'is_anonymous', true, $network_or_blog_id );
8347 }
8348 }
8349
8350 /**
8351 * @author Vova Feldman (@svovaf)
8352 * @since 2.0.0
8353 *
8354 * @param int $blog_id Site ID.
8355 * @param int $user_id User ID.
8356 * @param string $domain Site domain.
8357 * @param string $path Site path.
8358 * @param int $network_id Network ID. Only relevant on multi-network installations.
8359 * @param array $meta Metadata. Used to set initial site options.
8360 *
8361 * @uses Freemius::is_license_network_active() to check if the context license was network activated by the super-admin.
8362 * @uses Freemius::is_network_connected() to check if the super-admin network opted-in.
8363 * @uses Freemius::is_network_anonymous() to check if the super-admin network skipped.
8364 * @uses Freemius::is_network_delegated_connection() to check if the super-admin network delegated the connection to the site admins.
8365 */
8366 public function _after_new_blog_callback( $blog_id, $user_id, $domain, $path, $network_id, $meta ) {
8367 $this->_logger->entrance();
8368
8369 if ( ! $this->_is_network_active ) {
8370 FS_Clone_Manager::instance()->store_blog_install_info( $blog_id );
8371 return;
8372 }
8373
8374 $site = null;
8375 $new_blog_id = $blog_id;
8376
8377 if ( $this->is_premium() &&
8378 $this->is_network_connected() &&
8379 is_object( $this->_license ) &&
8380 $this->_license->can_activate( FS_Site::is_localhost_by_address( $domain ) ) &&
8381 $this->is_license_network_active( $blog_id )
8382 ) {
8383 /**
8384 * 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.
8385 */
8386 $current_blog_id = get_current_blog_id();
8387 $license = clone $this->_license;
8388
8389 $this->switch_to_blog( $blog_id );
8390
8391 // Opt-in with network user.
8392 $this->install_with_user(
8393 $this->get_network_user(),
8394 $license->secret_key,
8395 false,
8396 false,
8397 false
8398 );
8399
8400 if ( is_object( $this->_site ) ) {
8401 if ( $this->_site->license_id == $license->id ) {
8402 /**
8403 * If the license was activated successfully, sync the license data from the remote server.
8404 */
8405 $this->_license = $license;
8406 $this->sync_site_license();
8407 }
8408 }
8409
8410 $site = $this->_site;
8411
8412 $this->switch_to_blog( $current_blog_id );
8413
8414 if ( is_object( $site ) ) {
8415 FS_Clone_Manager::instance()->store_blog_install_info( $blog_id, $site );
8416
8417 // Already connected (with or without a license), so no need to continue.
8418 return;
8419 }
8420 }
8421
8422 if ( $this->is_network_anonymous() ) {
8423 /**
8424 * Opt-in was network skipped so automatically skip the opt-in for the new site.
8425 */
8426 $this->skip_site_connection( $blog_id );
8427 } else if ( $this->is_network_delegated_connection() ) {
8428 /**
8429 * Opt-in was network delegated so automatically delegate the opt-in for the new site's admin.
8430 */
8431 $this->delegate_site_connection( $blog_id );
8432 } else if ( $this->is_network_connected() ) {
8433 /**
8434 * Opt-in was network activated so automatically opt-in with the network user and new site admin.
8435 */
8436 $current_blog_id = get_current_blog_id();
8437
8438 $this->switch_to_blog( $blog_id );
8439
8440 // Opt-in with network user.
8441 $this->install_with_user(
8442 $this->get_network_user(),
8443 false,
8444 false,
8445 false,
8446 false
8447 );
8448
8449 $site = $this->_site;
8450
8451 $this->switch_to_blog( $current_blog_id );
8452 } else {
8453 /**
8454 * If the super-admin mixed different options (connect, skip, delegated):
8455 * a) If at least one site connection was delegated, then automatically delegate connection.
8456 * 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.
8457 */
8458 $has_delegated_site = false;
8459
8460 $sites = self::get_sites();
8461 foreach ( $sites as $wp_site ) {
8462 $blog_id = self::get_site_blog_id( $wp_site );
8463
8464 if ( $this->is_site_delegated_connection( $blog_id ) ) {
8465 $has_delegated_site = true;
8466 break;
8467 }
8468 }
8469
8470 if ( $has_delegated_site ) {
8471 $this->delegate_site_connection( $blog_id );
8472 } else {
8473 $this->skip_site_connection( $blog_id );
8474 }
8475 }
8476
8477 /**
8478 * 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.
8479 *
8480 * @author Leo Fajardo (@leorw)
8481 * @since 2.5.0
8482 */
8483 FS_Clone_Manager::instance()->store_blog_install_info( $new_blog_id, $site );
8484 }
8485
8486 /**
8487 * @author Vova Feldman (@svovaf)
8488 * @since 2.5.0
8489 *
8490 * @param \WP_Site $new_site
8491 * @param array $args
8492 */
8493 public function _after_wp_initialize_site_callback( WP_Site $new_site, $args ) {
8494 $this->_logger->entrance();
8495
8496 $this->_after_new_blog_callback(
8497 $new_site->id,
8498 // Dummy user ID (not in use).
8499 0,
8500 $new_site->domain,
8501 $new_site->path,
8502 $new_site->network_id,
8503 // Dummy meta, not in use.
8504 array()
8505 );
8506 }
8507
8508 /**
8509 * @author Vova Feldman (@svovaf)
8510 * @since 1.1.3
8511 *
8512 * @param bool|int|int[] $network_or_blog_ids Since 2.0.0.
8513 */
8514 private function reset_anonymous_mode( $network_or_blog_ids = false ) {
8515 if ( true === $network_or_blog_ids ) {
8516 $this->unset_anonymous_mode( true );
8517
8518 if ( fs_is_network_admin() ) {
8519 $this->_is_anonymous = null;
8520 }
8521
8522 // Rest anonymous mode for all non-delegated sub-sites.
8523 $blog_ids = $this->get_non_delegated_blog_ids();
8524 }
8525 else
8526 {
8527 if ( false === $network_or_blog_ids ) {
8528 $network_or_blog_ids = 0;
8529 }
8530
8531 $blog_ids = is_array( $network_or_blog_ids ) ?
8532 $network_or_blog_ids :
8533 array( $network_or_blog_ids );
8534
8535 foreach ( $blog_ids as $blog_id ) {
8536 if ( 0 === $blog_id || get_current_blog_id() == $blog_id ) {
8537 $this->_is_anonymous = null;
8538 }
8539 }
8540 }
8541
8542 foreach ( $blog_ids as $blog_id ) {
8543 $this->unset_anonymous_mode( $blog_id );
8544 }
8545
8546 /**
8547 * Ensure that this field is also "false", otherwise, if the current module's type is "theme" and the module
8548 * has no menus, the opt-in popup will not be shown immediately (in this case, the user will have to click
8549 * on the admin notice that contains the opt-in link in order to trigger the opt-in popup).
8550 *
8551 * @author Leo Fajardo (@leorw)
8552 * @since 1.2.2
8553 */
8554 if ( ! $this->_is_network_active ) {
8555 $this->_is_anonymous = null;
8556 }
8557 }
8558
8559 /**
8560 * @author Leo Fajardo (@leorw)
8561 * @since 2.5.3
8562 */
8563 private function update_license_required_permissions_if_anonymous() {
8564 if ( ! $this->is_anonymous() ) {
8565 return;
8566 }
8567
8568 $this->reset_anonymous_mode( fs_is_network_admin() );
8569
8570 FS_Permission_Manager::instance( $this )->update_permissions_tracking_flag( array(
8571 'essentials' => true,
8572 'events' => true,
8573 'diagnostic' => false,
8574 'extensions' => false,
8575 'site' => false,
8576 ) );
8577 }
8578
8579 /**
8580 * This is used to ensure that before redirecting to the opt-in page after resetting the anonymous mode or
8581 * deleting the account in the network level, the URL of the page to redirect to is correct.
8582 *
8583 * @author Leo Fajardo (@leorw)
8584 *
8585 * @since 2.1.3
8586 */
8587 private function maybe_set_slug_and_network_menu_exists_flag() {
8588 if ( ! empty( $this->_dynamically_added_top_level_page_hook_name ) ) {
8589 $this->_menu->set_slug_and_network_menu_exists_flag( $this->_menu->has_menu() ?
8590 $this->_menu->get_slug() :
8591 $this->_slug
8592 );
8593 }
8594 }
8595
8596 /**
8597 * Clears the anonymous mode and redirects to the opt-in screen.
8598 *
8599 * @author Vova Feldman (@svovaf)
8600 * @since 1.1.7
8601 */
8602 function connect_again() {
8603 if ( ! $this->is_anonymous() && ! $this->is_pending_activation() ) {
8604 return;
8605 }
8606
8607 if ( $this->is_anonymous() ) {
8608 $this->reset_anonymous_mode( fs_is_network_admin() );
8609 }
8610
8611 $activation_url_params = array();
8612
8613 if ( $this->is_pending_activation() ) {
8614 $this->clear_pending_activation_mode();
8615
8616 if ( fs_request_get_bool( 'require_license' ) ) {
8617 $activation_url_params['require_license'] = true;
8618 }
8619 }
8620
8621 $this->maybe_set_slug_and_network_menu_exists_flag();
8622
8623 fs_redirect( $this->get_activation_url( $activation_url_params ) );
8624 }
8625
8626 /**
8627 * Skip account connect, and set anonymous mode.
8628 *
8629 * @author Vova Feldman (@svovaf)
8630 * @since 1.1.1
8631 *
8632 * @param bool|int|int[] $network_or_blog_ids Since 2.5.1
8633 */
8634 function skip_connection( $network_or_blog_ids = false ) {
8635 $this->_logger->entrance();
8636
8637 $this->_admin_notices->remove_sticky( 'connect_account' );
8638
8639 if ( true === $network_or_blog_ids ) {
8640 $this->set_anonymous_mode( true, true );
8641
8642 if ( fs_is_network_admin() ) {
8643 $this->_is_anonymous = null;
8644 }
8645
8646 // Rest anonymous mode for all non-delegated sub-sites.
8647 $blog_ids = $this->get_non_delegated_blog_ids();
8648 }
8649 else
8650 {
8651 if ( false === $network_or_blog_ids ) {
8652 $network_or_blog_ids = 0;
8653 }
8654
8655 $blog_ids = is_array( $network_or_blog_ids ) ?
8656 $network_or_blog_ids :
8657 array( $network_or_blog_ids );
8658
8659 foreach ( $blog_ids as $blog_id ) {
8660 if ( 0 === $blog_id || get_current_blog_id() == $blog_id ) {
8661 $this->_is_anonymous = null;
8662 }
8663 }
8664 }
8665
8666 foreach ( $blog_ids as $blog_id ) {
8667 $this->skip_site_connection( $blog_id );
8668 }
8669
8670 $this->network_upgrade_mode_completed();
8671 }
8672
8673 /**
8674 * Skip connection for specific site in the network.
8675 *
8676 * @author Vova Feldman (@svovaf)
8677 * @since 2.0.0
8678 *
8679 * @param int|null $blog_id
8680 * @param bool $send_skip
8681 */
8682 private function skip_site_connection( $blog_id = null ) {
8683 $this->_logger->entrance();
8684
8685 $this->_admin_notices->remove_sticky( 'connect_account', $blog_id );
8686
8687 $this->set_anonymous_mode( true, $blog_id );
8688 }
8689
8690 /**
8691 * Plugin version update hook.
8692 *
8693 * @author Vova Feldman (@svovaf)
8694 * @since 1.0.4
8695 */
8696 private function update_plugin_version_event() {
8697 $this->_logger->entrance();
8698
8699 if ( ! $this->is_registered() ) {
8700 return;
8701 }
8702
8703 $this->maybe_schedule_install_sync_cron();
8704 // $this->sync_install( array(), true );
8705 }
8706
8707 /**
8708 * Generate an MD5 signature of a plugins collection.
8709 * This helper methods used to identify changes in a plugins collection.
8710 *
8711 * @author Vova Feldman (@svovaf)
8712 * @since 2.0.0
8713 *
8714 * @param array [string]array $plugins
8715 *
8716 * @return string
8717 */
8718 private function get_plugins_thumbprint( $plugins ) {
8719 ksort( $plugins );
8720
8721 $thumbprint = '';
8722 foreach ( $plugins as $basename => $data ) {
8723 $thumbprint .= $data['slug'] . ',' .
8724 $data['Version'] . ',' .
8725 ( $data['is_active'] ? '1' : '0' ) . ';';
8726 }
8727
8728 return md5( $thumbprint );
8729 }
8730
8731 /**
8732 * Return a list of modified plugins since the last sync.
8733 *
8734 * Note:
8735 * There's no point to store a plugins counter since even if the number of
8736 * plugins didn't change, we still need to check if the versions are all the
8737 * same and the activity state is similar.
8738 *
8739 * @author Vova Feldman (@svovaf)
8740 * @since 1.1.8
8741 *
8742 * @return array|false
8743 */
8744 private function get_plugins_data_for_api() {
8745 // Alias.
8746 $site_active_plugins_option_name = 'active_plugins';
8747 $network_plugins_option_name = 'all_plugins';
8748
8749 /**
8750 * Collection of all site level active plugins.
8751 */
8752 $site_active_plugins_cache = self::$_accounts->get_option( $site_active_plugins_option_name );
8753
8754 if ( ! is_object( $site_active_plugins_cache ) ) {
8755 $site_active_plugins_cache = (object) array(
8756 'timestamp' => '',
8757 'md5' => '',
8758 'plugins' => array(),
8759 );
8760 }
8761
8762 $time = time();
8763
8764 if ( ! empty( $site_active_plugins_cache->timestamp ) &&
8765 ( $time - $site_active_plugins_cache->timestamp ) < WP_FS__TIME_5_MIN_IN_SEC
8766 ) {
8767 // Don't send plugin updates if last update was in the past 5 min.
8768 return false;
8769 }
8770
8771 // Write timestamp to lock the logic.
8772 $site_active_plugins_cache->timestamp = $time;
8773 self::$_accounts->set_option( $site_active_plugins_option_name, $site_active_plugins_cache, true );
8774
8775 // Reload options from DB.
8776 self::$_accounts->load( true );
8777 $site_active_plugins_cache = self::$_accounts->get_option( $site_active_plugins_option_name );
8778
8779 if ( $time != $site_active_plugins_cache->timestamp ) {
8780 // If timestamp is different, then another thread captured the lock.
8781 return false;
8782 }
8783
8784 /**
8785 * Collection of all plugins (network level).
8786 */
8787 $network_plugins_cache = self::$_accounts->get_option( $network_plugins_option_name );
8788
8789 if ( ! is_object( $network_plugins_cache ) ) {
8790 $network_plugins_cache = (object) array(
8791 'timestamp' => '',
8792 'md5' => '',
8793 'plugins' => array(),
8794 );
8795 }
8796
8797 // Check if there's a change in plugins.
8798 $network_plugins = self::get_network_plugins();
8799 $site_active_plugins = self::get_site_active_plugins();
8800
8801 $network_plugins_thumbprint = $this->get_plugins_thumbprint( $network_plugins );
8802 $site_active_plugins_thumbprint = $this->get_plugins_thumbprint( $site_active_plugins );
8803
8804 // Check if plugins status changed (version or active/inactive).
8805 $network_plugins_changed = ( $network_plugins_cache->md5 !== $network_plugins_thumbprint );
8806 $site_active_plugins_changed = ( $site_active_plugins_cache->md5 !== $site_active_plugins_thumbprint );
8807
8808 if ( ! $network_plugins_changed &&
8809 ! $site_active_plugins_changed
8810 ) {
8811 // No changes.
8812 return array();
8813 }
8814
8815 $plugins_update_data = array();
8816
8817 foreach ( $network_plugins_cache->plugins as $basename => $data ) {
8818 if ( ! isset( $network_plugins[ $basename ] ) ) {
8819 // Plugin uninstalled.
8820 $uninstalled_plugin_data = $data;
8821 $uninstalled_plugin_data['is_active'] = false;
8822 $uninstalled_plugin_data['is_uninstalled'] = true;
8823 $plugins_update_data[] = $uninstalled_plugin_data;
8824
8825 unset( $network_plugins[ $basename ] );
8826
8827 unset( $network_plugins_cache->plugins[ $basename ] );
8828 unset( $site_active_plugins_cache->plugins[ $basename ] );
8829
8830 continue;
8831 }
8832
8833 $was_active = $data['is_active'] ||
8834 ( isset( $site_active_plugins_cache->plugins[ $basename ] ) &&
8835 true === $site_active_plugins_cache->plugins[ $basename ]['is_active'] );
8836 $is_active = $network_plugins[ $basename ]['is_active'] ||
8837 ( isset( $site_active_plugins[ $basename ] ) &&
8838 $site_active_plugins[ $basename ]['is_active'] );
8839
8840 if ( ! isset( $site_active_plugins_cache->plugins[ $basename ] ) &&
8841 isset( $site_active_plugins[ $basename ] )
8842 ) {
8843 // Plugin was site level activated.
8844 $site_active_plugins_cache->plugins[ $basename ] = $network_plugins[ $basename ];
8845 $site_active_plugins_cache->plugins[ $basename ]['is_active'] = true;
8846 } else if ( isset( $site_active_plugins_cache->plugins[ $basename ] ) &&
8847 ! isset( $site_active_plugins[ $basename ] )
8848 ) {
8849 // Plugin was site level deactivated.
8850 unset( $site_active_plugins_cache->plugins[ $basename ] );
8851 }
8852
8853 $prev_version = $data['version'];
8854 $current_version = $network_plugins[ $basename ]['Version'];
8855
8856 if ( $was_active !== $is_active || $prev_version !== $current_version ) {
8857 // Plugin activated or deactivated, or version changed.
8858
8859 if ( $was_active !== $is_active ) {
8860 if ( $data['is_active'] != $network_plugins[ $basename ]['is_active'] ) {
8861 $network_plugins_cache->plugins[ $basename ]['is_active'] = $data['is_active'];
8862 }
8863 }
8864
8865 if ( $prev_version !== $current_version ) {
8866 $network_plugins_cache->plugins[ $basename ]['Version'] = $current_version;
8867 }
8868
8869 $updated_plugin_data = $data;
8870 $updated_plugin_data['is_active'] = $is_active;
8871 $updated_plugin_data['version'] = $current_version;
8872 $updated_plugin_data['title'] = $network_plugins[ $basename ]['Name'];
8873 $plugins_update_data[] = $updated_plugin_data;
8874 }
8875 }
8876
8877 // Find new plugins that weren't yet seen before.
8878 foreach ( $network_plugins as $basename => $data ) {
8879 if ( ! isset( $network_plugins_cache->plugins[ $basename ] ) ) {
8880 // New plugin.
8881 $new_plugin = array(
8882 'slug' => $data['slug'],
8883 'version' => $data['Version'],
8884 'title' => $data['Name'],
8885 'is_active' => $data['is_active'],
8886 'is_uninstalled' => false,
8887 );
8888
8889 $network_plugins_cache->plugins[ $basename ] = $new_plugin;
8890
8891 $is_site_level_active = (
8892 isset( $site_active_plugins[ $basename ] ) &&
8893 $site_active_plugins[ $basename ]['is_active']
8894 );
8895
8896 /**
8897 * If not network active, set the activity status based on the site-level plugin status.
8898 */
8899 if ( ! $new_plugin['is_active'] ) {
8900 $new_plugin['is_active'] = $is_site_level_active;
8901 }
8902
8903 $plugins_update_data[] = $new_plugin;
8904
8905 if ( isset( $site_active_plugins[ $basename ] ) ) {
8906 $site_active_plugins_cache->plugins[ $basename ] = $new_plugin;
8907 $site_active_plugins_cache->plugins[ $basename ]['is_active'] = $is_site_level_active;
8908 }
8909 }
8910 }
8911
8912 $site_active_plugins_cache->md5 = $site_active_plugins_thumbprint;
8913 $site_active_plugins_cache->timestamp = $time;
8914 self::$_accounts->set_option( $site_active_plugins_option_name, $site_active_plugins_cache, true );
8915
8916 $network_plugins_cache->md5 = $network_plugins_thumbprint;
8917 $network_plugins_cache->timestamp = $time;
8918 self::$_accounts->set_option( $network_plugins_option_name, $network_plugins_cache, true );
8919
8920 return $plugins_update_data;
8921 }
8922
8923 /**
8924 * Return a list of modified themes since the last sync.
8925 *
8926 * Note:
8927 * There's no point to store a themes counter since even if the number of
8928 * themes didn't change, we still need to check if the versions are all the
8929 * same and the activity state is similar.
8930 *
8931 * @author Vova Feldman (@svovaf)
8932 * @since 1.1.8
8933 *
8934 * @return array|false
8935 */
8936 private function get_themes_data_for_api() {
8937 // Alias.
8938 $option_name = 'all_themes';
8939
8940 $all_cached_themes = self::$_accounts->get_option( $option_name );
8941
8942 if ( ! is_object( $all_cached_themes ) ) {
8943 $all_cached_themes = (object) array(
8944 'timestamp' => '',
8945 'md5' => '',
8946 'themes' => array(),
8947 );
8948 }
8949
8950 $time = time();
8951
8952 if ( ! empty( $all_cached_themes->timestamp ) &&
8953 ( $time - $all_cached_themes->timestamp ) < WP_FS__TIME_5_MIN_IN_SEC
8954 ) {
8955 // Don't send theme updates if last update was in the past 5 min.
8956 return false;
8957 }
8958
8959 // Write timestamp to lock the logic.
8960 $all_cached_themes->timestamp = $time;
8961 self::$_accounts->set_option( $option_name, $all_cached_themes, true );
8962
8963 // Reload options from DB.
8964 self::$_accounts->load( true );
8965 $all_cached_themes = self::$_accounts->get_option( $option_name );
8966
8967 if ( $time != $all_cached_themes->timestamp ) {
8968 // If timestamp is different, then another thread captured the lock.
8969 return false;
8970 }
8971
8972 // Get active theme.
8973 $active_theme = wp_get_theme();
8974 $active_theme_stylesheet = $active_theme->get_stylesheet();
8975
8976 // Check if there's a change in themes.
8977 $all_themes = wp_get_themes();
8978
8979 // Check if themes changed.
8980 ksort( $all_themes );
8981
8982 $themes_signature = '';
8983 foreach ( $all_themes as $slug => $data ) {
8984 $is_active = ( $slug === $active_theme_stylesheet );
8985 $themes_signature .= $slug . ',' .
8986 $data->version . ',' .
8987 ( $is_active ? '1' : '0' ) . ';';
8988 }
8989
8990 // Check if themes status changed (version or active/inactive).
8991 $themes_changed = ( $all_cached_themes->md5 !== md5( $themes_signature ) );
8992
8993 $themes_update_data = array();
8994
8995 if ( $themes_changed ) {
8996 // Change in themes, report changes.
8997
8998 // Update existing themes info.
8999 foreach ( $all_cached_themes->themes as $slug => $data ) {
9000 $is_active = ( $slug === $active_theme_stylesheet );
9001
9002 if ( ! isset( $all_themes[ $slug ] ) ) {
9003 // Plugin uninstalled.
9004 $uninstalled_theme_data = $data;
9005 $uninstalled_theme_data['is_active'] = false;
9006 $uninstalled_theme_data['is_uninstalled'] = true;
9007 $themes_update_data[] = $uninstalled_theme_data;
9008
9009 unset( $all_themes[ $slug ] );
9010 unset( $all_cached_themes->themes[ $slug ] );
9011 } else if ( $data['is_active'] !== $is_active ||
9012 $data['version'] !== $all_themes[ $slug ]->version
9013 ) {
9014 // Plugin activated or deactivated, or version changed.
9015
9016 $all_cached_themes->themes[ $slug ]['is_active'] = $is_active;
9017 $all_cached_themes->themes[ $slug ]['version'] = $all_themes[ $slug ]->version;
9018
9019 $themes_update_data[] = $all_cached_themes->themes[ $slug ];
9020 }
9021 }
9022
9023 // Find new themes that weren't yet seen before.
9024 foreach ( $all_themes as $slug => $data ) {
9025 if ( ! isset( $all_cached_themes->themes[ $slug ] ) ) {
9026 $is_active = ( $slug === $active_theme_stylesheet );
9027
9028 // New plugin.
9029 $new_plugin = array(
9030 'slug' => $slug,
9031 'version' => $data->version,
9032 'title' => $data->name,
9033 'is_active' => $is_active,
9034 'is_uninstalled' => false,
9035 );
9036
9037 $themes_update_data[] = $new_plugin;
9038 $all_cached_themes->themes[ $slug ] = $new_plugin;
9039 }
9040 }
9041
9042 $all_cached_themes->md5 = md5( $themes_signature );
9043 $all_cached_themes->timestamp = time();
9044 self::$_accounts->set_option( $option_name, $all_cached_themes, true );
9045 }
9046
9047 return $themes_update_data;
9048 }
9049
9050 /**
9051 * Get site data for API install request.
9052 *
9053 * @author Vova Feldman (@svovaf)
9054 * @since 1.1.2
9055 *
9056 * @param string[] $override
9057 * @param bool $include_plugins Since 1.1.8 by default include plugin changes.
9058 * @param bool $include_themes Since 1.1.8 by default include plugin changes.
9059 * @param bool $include_blog_data Since 2.3.0 by default include the current blog's data (language, title, and URL).
9060 *
9061 * @return array
9062 */
9063 private function get_install_data_for_api(
9064 array $override,
9065 $include_plugins = true,
9066 $include_themes = true,
9067 $include_blog_data = true
9068 ) {
9069 // Alias.
9070 $permissions = FS_Permission_Manager::instance( $this );
9071
9072 if ( $permissions->is_extensions_tracking_allowed() ) {
9073 if ( ! defined( 'WP_FS__TRACK_PLUGINS' ) || false !== WP_FS__TRACK_PLUGINS ) {
9074 /**
9075 * @since 1.1.8 Also send plugin updates.
9076 */
9077 if ( $include_plugins && ! isset( $override['plugins'] ) ) {
9078 $plugins = $this->get_plugins_data_for_api();
9079 if ( ! empty( $plugins ) ) {
9080 $override['plugins'] = $plugins;
9081 }
9082 }
9083 }
9084
9085 if ( ! defined( 'WP_FS__TRACK_THEMES' ) || false !== WP_FS__TRACK_THEMES ) {
9086 /**
9087 * @since 1.1.8 Also send themes updates.
9088 */
9089 if ( $include_themes && ! isset( $override['themes'] ) ) {
9090 $themes = $this->get_themes_data_for_api();
9091 if ( ! empty( $themes ) ) {
9092 $override['themes'] = $themes;
9093 }
9094 }
9095 }
9096 }
9097
9098 $versions = $this->get_versions();
9099
9100 $blog_data = array();
9101 if ( $include_blog_data ) {
9102 $blog_data['url'] = self::get_unfiltered_site_url();
9103
9104 if ( $permissions->is_diagnostic_tracking_allowed() ) {
9105 $blog_data = array_merge( $blog_data, array(
9106 'language' => self::get_sanitized_language(),
9107 'title' => get_bloginfo( 'name' ),
9108 ) );
9109 }
9110 }
9111
9112 return array_merge( $versions, $blog_data, array(
9113 'version' => $this->get_plugin_version(),
9114 'is_premium' => $this->is_premium(),
9115 // Special params.
9116 'is_active' => true,
9117 'is_uninstalled' => false,
9118 ), $override );
9119 }
9120
9121 /**
9122 * Update installs details.
9123 *
9124 * @todo V1 of multiste network support doesn't support plugin and theme data sending.
9125 *
9126 * @author Vova Feldman (@svovaf)
9127 * @since 2.0.0
9128 *
9129 * @param string[] string $override
9130 * @param bool $only_diff
9131 * @param bool $is_keepalive
9132 * @param bool $include_plugins Since 1.1.8 by default include plugin changes.
9133 * @param bool $include_themes Since 1.1.8 by default include plugin changes.
9134 *
9135 * @return array
9136 */
9137 private function get_installs_data_for_api(
9138 array $override,
9139 $only_diff = false,
9140 $is_keepalive = false,
9141 $include_plugins = true,
9142 $include_themes = true
9143 ) {
9144 /**
9145 * @since 1.1.8 Also send plugin updates.
9146 */
9147 // if ( $include_plugins && ! isset( $override['plugins'] ) ) {
9148 // $plugins = $this->get_plugins_data_for_api();
9149 // if ( ! empty( $plugins ) ) {
9150 // $override['plugins'] = $plugins;
9151 // }
9152 // }
9153 /**
9154 * @since 1.1.8 Also send themes updates.
9155 */
9156 // if ( $include_themes && ! isset( $override['themes'] ) ) {
9157 // $themes = $this->get_themes_data_for_api();
9158 // if ( ! empty( $themes ) ) {
9159 // $override['themes'] = $themes;
9160 // }
9161 // }
9162
9163 // Common properties.
9164 $versions = $this->get_versions();
9165 $common = array_merge( $versions, array(
9166 'version' => $this->get_plugin_version(),
9167 'is_premium' => $this->is_premium(),
9168 ), $override );
9169
9170
9171 $is_common_diff_for_any_site = false;
9172 $common_diff_union = array();
9173
9174 $installs_data = array();
9175
9176 $sites = self::get_sites();
9177
9178 $subsite_data_for_api_by_install_id = array();
9179 $install_url_by_install_id = array();
9180 $subsite_registration_date_by_install_id = array();
9181
9182 foreach ( $sites as $site ) {
9183 $blog_id = self::get_site_blog_id( $site );
9184
9185 $install = $this->get_install_by_blog_id( $blog_id );
9186
9187 if ( is_object( $install ) ) {
9188 if ( $install->user_id != $this->_user->id ) {
9189 // Install belongs to a different owner.
9190 continue;
9191 }
9192
9193 if ( ! $this->is_tracking_allowed( $blog_id, $install ) ) {
9194 // Don't send updates regarding opted-out installs.
9195 continue;
9196 }
9197
9198 $install_data = $this->get_site_info( $site, true );
9199
9200 if ( FS_Clone_Manager::instance()->is_temporary_duplicate_by_blog_id( $install_data['blog_id'] ) ) {
9201 continue;
9202 }
9203
9204 $uid = $install_data['uid'];
9205 $url = $install_data['url'];
9206 $registration_date = $install_data['registration_date'];
9207
9208 if ( isset( $subsite_data_for_api_by_install_id[ $install->id ] ) ) {
9209 $clone_subsite_data = $subsite_data_for_api_by_install_id[ $install->id ];
9210 $clone_install_url = $install_url_by_install_id[ $install->id ];
9211 $clone_subsite_registration_date = $subsite_registration_date_by_install_id[ $install->id ];
9212
9213 $skip = false;
9214
9215 if (
9216 ! empty( $install_data['registration_date'] ) &&
9217 ! empty( $clone_subsite_registration_date )
9218 ) {
9219 /**
9220 * 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.
9221 *
9222 * @author Leo Fajardo (@leorw)
9223 * @since 2.5.1
9224 */
9225 $skip = ( strtotime( $install_data['registration_date'] ) > strtotime( $clone_subsite_registration_date ) );
9226 } else if (
9227 /**
9228 * 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.
9229 *
9230 * @author Leo Fajardo (@leorw)
9231 * @since 2.5.0
9232 */
9233 fs_strip_url_protocol( untrailingslashit( $clone_install_url ) ) === fs_strip_url_protocol( untrailingslashit( $clone_subsite_data['url'] ) ) ||
9234 fs_strip_url_protocol( untrailingslashit( $install->url ) ) !== fs_strip_url_protocol( untrailingslashit( $url ) )
9235 ) {
9236 $skip = true;
9237 }
9238
9239 if ( $skip ) {
9240 // 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.
9241 FS_Clone_Manager::instance()->store_blog_install_info( $blog_id );
9242 continue;
9243 }
9244 }
9245
9246 unset( $install_data['blog_id'] );
9247 unset( $install_data['uid'] );
9248 unset( $install_data['url'] );
9249 unset( $install_data['registration_date'] );
9250
9251 $install_data['is_active'] = $this->is_active_for_site( $blog_id );
9252 $install_data['is_uninstalled'] = $install->is_uninstalled;
9253
9254 $common_diff = null;
9255 $is_common_diff = false;
9256 if ( $only_diff ) {
9257 $install_data = $this->get_install_diff_for_api( $install_data, $install, $override );
9258 $common_diff = $this->get_install_diff_for_api( $common, $install, $override );
9259
9260 $is_common_diff = ! empty( $common_diff );
9261
9262 if ( $is_common_diff ) {
9263 foreach ( $common_diff as $k => $v ) {
9264 if ( ! isset( $common_diff_union[ $k ] ) ) {
9265 $common_diff_union[ $k ] = $v;
9266 }
9267 }
9268 }
9269
9270 $is_common_diff_for_any_site = $is_common_diff_for_any_site || $is_common_diff;
9271 }
9272
9273 if ( ! empty( $install_data ) || $is_common_diff || $is_keepalive ) {
9274 // Add install ID and site unique ID.
9275 $install_data['id'] = $install->id;
9276 $install_data['uid'] = $uid;
9277 $install_data['url'] = $url;
9278
9279 $subsite_data_for_api_by_install_id[ $install->id ] = $install_data;
9280 $install_url_by_install_id[ $install->id ] = $install->url;
9281 $subsite_registration_date_by_install_id[ $install->id ] = $registration_date;
9282 }
9283 }
9284 }
9285
9286 restore_current_blog();
9287
9288 $installs_data = array_merge(
9289 $installs_data,
9290 array_values( $subsite_data_for_api_by_install_id )
9291 );
9292
9293 if ( 0 < count( $installs_data ) && ( $is_common_diff_for_any_site || ! $only_diff ) ) {
9294 if ( ! $only_diff ) {
9295 $installs_data[] = $common;
9296 } else if ( ! empty( $common_diff_union ) ) {
9297 $installs_data[] = $common_diff_union;
9298 }
9299 }
9300
9301 foreach ( $installs_data as &$data ) {
9302 $data = (object) $data;
9303 }
9304
9305 return $installs_data;
9306 }
9307
9308 /**
9309 * Compare site actual data to the stored install data and return the differences for an API data sync.
9310 *
9311 * @author Vova Feldman (@svovaf)
9312 * @since 2.0.0
9313 *
9314 * @param array $site
9315 * @param FS_Site $install
9316 * @param string[] string $override
9317 *
9318 * @return array
9319 */
9320 private function get_install_diff_for_api( $site, $install, $override = array() ) {
9321 $diff = array();
9322 $special = array();
9323 $special_override = false;
9324
9325 foreach ( $site as $p => $v ) {
9326 if ( property_exists( $install, $p ) ) {
9327 if ( ( is_bool( $install->{$p} ) || ! empty( $install->{$p} ) ) &&
9328 $install->{$p} != $v
9329 ) {
9330 $val = self::get_api_sanitized_property( $p, $v );
9331
9332 if ( $install->{$p} != $val ) {
9333 $install->{$p} = $val;
9334 $diff[ $p ] = $val;
9335 }
9336 }
9337 } else {
9338 $special[ $p ] = $v;
9339
9340 if ( isset( $override[ $p ] ) ||
9341 'plugins' === $p ||
9342 'themes' === $p
9343 ) {
9344 $special_override = true;
9345 }
9346 }
9347 }
9348
9349 if ( $special_override || 0 < count( $diff ) ) {
9350 // Add special params only if has at least one
9351 // standard param, or if explicitly requested to
9352 // override a special param or a param which is not exist
9353 // in the install object.
9354 $diff = array_merge( $diff, $special );
9355 }
9356
9357 return $diff;
9358 }
9359
9360 /**
9361 * @author Leo Fajardo (@leorw)
9362 * @since 2.5.1
9363 */
9364 private function send_pending_clone_update_once() {
9365 $this->_logger->entrance();
9366
9367 if ( ! empty( $this->_storage->clone_id ) ) {
9368 return;
9369 }
9370
9371 $install_clone = $this->get_api_site_scope()->call(
9372 '/clones',
9373 'post',
9374 array( 'site_url' => self::get_unfiltered_site_url() )
9375 );
9376
9377 if ( $this->is_api_result_entity( $install_clone ) ) {
9378 $this->_storage->clone_id = $install_clone->id;
9379 }
9380 }
9381
9382 /**
9383 * @author Leo Fajardo (@leorw)
9384 * @since 2.5.1
9385 *
9386 * @param string $resolution_type
9387 * @param FS_Site $clone_context_install
9388 */
9389 function send_clone_resolution_update( $resolution_type, $clone_context_install ) {
9390 $this->_logger->entrance();
9391
9392 if ( empty( $this->_storage->clone_id ) ) {
9393 return;
9394 }
9395
9396 $new_install_id = null;
9397 $current_site = null;
9398
9399 $flush = false;
9400
9401 /**
9402 * 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.
9403 */
9404 if ( $clone_context_install->id != $this->_site->id ) {
9405 $new_install_id = $this->_site->id;
9406 $current_site = $this->_site;
9407 $this->_site = $clone_context_install;
9408
9409 $flush = true;
9410 }
9411
9412 $this->get_api_site_scope( $flush )->call(
9413 "/clones/{$this->_storage->clone_id}",
9414 'put',
9415 array(
9416 'resolution' => $resolution_type,
9417 'new_install_id' => $new_install_id,
9418 )
9419 );
9420
9421 if ( is_object( $current_site ) ) {
9422 /**
9423 * Ensure that the install scope entity is updated back to the previous install entity.
9424 */
9425 $this->_site = $current_site;
9426
9427 // Restore the previous install scope entity of the API.
9428 $this->get_api_site_scope( true );
9429 }
9430 }
9431
9432 /**
9433 * Update install only if changed.
9434 *
9435 * @author Vova Feldman (@svovaf)
9436 * @since 1.0.9
9437 *
9438 * @param string[] string $override
9439 * @param bool $flush
9440 * @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.
9441 *
9442 * @return false|object|string
9443 */
9444 private function send_install_update( $override = array(), $flush = false, $is_two_way_sync = false ) {
9445 $this->_logger->entrance();
9446
9447 $check_properties = $this->get_install_data_for_api( $override );
9448
9449 if ( $flush ) {
9450 $params = $check_properties;
9451 } else {
9452 $params = $this->get_install_diff_for_api( $check_properties, $this->_site, $override );
9453 }
9454
9455 if ( empty( $params ) ) {
9456 $keepalive_only_update = $this->should_send_keepalive_update();
9457
9458 if ( ! $keepalive_only_update ) {
9459 /**
9460 * There are no updates to send including keepalive.
9461 *
9462 * @author Leo Fajardo (@leorw)
9463 * @since 2.2.3
9464 */
9465 return false;
9466 }
9467 }
9468
9469 if ( $is_two_way_sync ) {
9470 /**
9471 * Update last install sync timestamp during a two-way sync call as we expect that updates are sent during this call.
9472 *
9473 * @author Leo Fajardo (@leorw)
9474 * @since 2.2.3
9475 */
9476 if ( ! is_multisite() ) {
9477 // Update last install sync timestamp.
9478 $this->set_cron_execution_timestamp( 'install_sync' );
9479 }
9480
9481 $params['uid'] = $this->get_anonymous_id();
9482 }
9483
9484 $this->set_keepalive_timestamp();
9485
9486 // Send updated values to FS.
9487 $site = $this->api_site_call( '/', 'put', $params, true );
9488
9489 if ( $is_two_way_sync && $this->is_api_result_entity( $site ) ) {
9490 /**
9491 * Clear scheduled install sync after a two-way sync call.
9492 *
9493 * @author Leo Fajardo (@leorw)
9494 * @since 2.2.3
9495 */
9496 if ( ! is_multisite() ) {
9497 // I successfully sent install update, clear scheduled sync if exist.
9498 $this->clear_install_sync_cron();
9499 }
9500 }
9501
9502 return $site;
9503 }
9504
9505 /**
9506 * Update installs only if changed.
9507 *
9508 * @author Vova Feldman (@svovaf)
9509 * @since 2.0.0
9510 *
9511 * @param string[] string $override
9512 * @param bool $flush
9513 * @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.
9514 *
9515 * @return false|object|string
9516 */
9517 private function send_installs_update( $override = array(), $flush = false, $is_two_way_sync = false ) {
9518 $this->_logger->entrance();
9519
9520 /**
9521 * Pass `true` to use the network level storage since the update is for many installs.
9522 *
9523 * @author Leo Fajardo (@leorw)
9524 * @since 2.2.3
9525 */
9526 $should_send_keepalive = $this->should_send_keepalive_update( true );
9527
9528 $installs_data = $this->get_installs_data_for_api( $override, ! $flush, $should_send_keepalive );
9529
9530 if ( empty( $installs_data ) ) {
9531 return false;
9532 }
9533
9534 if ( $is_two_way_sync ) {
9535 // Update last install sync timestamp during a two-way sync call as we expect that updates are sent during this call.
9536 $this->set_cron_execution_timestamp( 'install_sync' );
9537 }
9538
9539 /**
9540 * Pass `true` to use the network level storage since the update is for many installs.
9541 *
9542 * @author Leo Fajardo (@leorw)
9543 * @since 2.2.3
9544 */
9545 $this->set_keepalive_timestamp( true );
9546
9547 // Send updated values to FS.
9548 $result = $this->get_api_user_scope()->call( "/plugins/{$this->_plugin->id}/installs.json", 'put', $installs_data );
9549
9550 if ( $is_two_way_sync && $this->is_api_result_object( $result, 'installs' ) ) {
9551 // I successfully sent a two-way installs update, clear the scheduled install sync if it exists.
9552 $this->clear_install_sync_cron();
9553 }
9554
9555 return $result;
9556 }
9557
9558 /**
9559 * @author Leo Fajardo (@leorw)
9560 *
9561 * @param bool|null $use_network_level_storage
9562 *
9563 * @return bool
9564 */
9565 private function should_send_keepalive_update( $use_network_level_storage = null ) {
9566 $keepalive_timestamp = $this->_storage->get( 'keepalive_timestamp', 0, $use_network_level_storage );
9567
9568 if ( $keepalive_timestamp < ( time() - WP_FS__TIME_WEEK_IN_SEC ) ) {
9569 // If updated more than 7 days ago, trigger a keepalive and update the time it was triggered.
9570 return true;
9571 } else {
9572 // 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.
9573 return ( 7 == rand( 1, 7 ) );
9574 }
9575 }
9576
9577 /**
9578 * Syncs the install owner's data if needed (i.e., if the install owner is different from the loaded user).
9579 *
9580 * @author Leo Fajardo (@leorw)
9581 * @since 2.3.2
9582 */
9583 private function maybe_sync_install_user() {
9584 if ( $this->_user->id == $this->_site->user_id ) {
9585 return;
9586 }
9587
9588 // Fetch user data and store if found.
9589 $this->sync_user_by_current_install();
9590 }
9591
9592 /**
9593 * Update install only if changed.
9594 *
9595 * @author Vova Feldman (@svovaf)
9596 * @since 1.0.9
9597 *
9598 * @param string[] string $override
9599 * @param bool $flush
9600 */
9601 function sync_install( $override = array(), $flush = false ) {
9602 $this->_logger->entrance();
9603
9604 $site = $this->send_install_update( $override, $flush, true );
9605
9606 if ( false === $site ) {
9607 // No sync required.
9608 return;
9609 }
9610
9611 if ( ! $this->is_api_result_entity( $site ) ) {
9612 // Failed to sync, don't update locally.
9613 return;
9614 }
9615
9616 $this->_site = new FS_Site( $site );
9617
9618 $this->_store_site( true );
9619 }
9620
9621 /**
9622 * Update install only if changed.
9623 *
9624 * @author Vova Feldman (@svovaf)
9625 * @since 1.0.9
9626 *
9627 * @param string[] string $override
9628 * @param bool $flush
9629 */
9630 private function sync_installs( $override = array(), $flush = false ) {
9631 $this->_logger->entrance();
9632
9633 $result = $this->send_installs_update( $override, $flush, true );
9634
9635 if ( false === $result ) {
9636 // No sync required.
9637 return;
9638 }
9639
9640 if ( ! $this->is_api_result_object( $result, 'installs' ) ) {
9641 // Failed to sync, don't update locally.
9642 return;
9643 }
9644
9645 $address_to_blog_map = $this->get_address_to_blog_map();
9646
9647 foreach ( $result->installs as $install ) {
9648 $this->_site = new FS_Site( $install );
9649
9650 $address = trailingslashit( fs_strip_url_protocol( $install->url ) );
9651 $blog_id = $address_to_blog_map[ $address ];
9652
9653 $this->_store_site( true, $blog_id );
9654 }
9655 }
9656
9657 /**
9658 * Track install's custom event.
9659 *
9660 * IMPORTANT:
9661 * Custom event tracking is currently only supported for specific clients.
9662 * If you are not one of them, please don't use this method. If you will,
9663 * the API will simply ignore your request based on the plugin ID.
9664 *
9665 * Need custom tracking for your plugin or theme?
9666 * If you are interested in custom event tracking please contact yo@freemius.com
9667 * for further details.
9668 *
9669 * @author Vova Feldman (@svovaf)
9670 * @since 1.2.1
9671 *
9672 * @param string $name Event name.
9673 * @param array $properties Associative key/value array with primitive values only
9674 * @param bool $process_at A valid future date-time in the following format Y-m-d H:i:s.
9675 * @param bool $once If true, event will be tracked only once. IMPORTANT: Still trigger the API call.
9676 *
9677 * @return object|false Event data or FALSE on failure.
9678 *
9679 * @throws \Freemius_InvalidArgumentException
9680 */
9681 public function track_event( $name, $properties = array(), $process_at = false, $once = false ) {
9682 $this->_logger->entrance( http_build_query( array( 'name' => $name, 'once' => $once ) ) );
9683
9684 if ( ! $this->is_registered() ) {
9685 return false;
9686 }
9687
9688 $event = array( 'type' => $name );
9689
9690 if ( is_numeric( $process_at ) && $process_at > time() ) {
9691 $event['process_at'] = $process_at;
9692 }
9693
9694 if ( $once ) {
9695 $event['once'] = true;
9696 }
9697
9698 if ( ! empty( $properties ) ) {
9699 // Verify associative array values are primitive.
9700 foreach ( $properties as $k => $v ) {
9701 if ( ! is_scalar( $v ) ) {
9702 throw new Freemius_InvalidArgumentException( 'The $properties argument must be an associative key/value array with primitive values only.' );
9703 }
9704 }
9705
9706 $event['properties'] = $properties;
9707 }
9708
9709 $result = $this->get_api_site_scope()->call( 'events.json', 'post', $event );
9710
9711 return $this->is_api_error( $result ) ?
9712 false :
9713 $result;
9714 }
9715
9716 /**
9717 * Track install's custom event only once, but it still triggers the API call.
9718 *
9719 * IMPORTANT:
9720 * Custom event tracking is currently only supported for specific clients.
9721 * If you are not one of them, please don't use this method. If you will,
9722 * the API will simply ignore your request based on the plugin ID.
9723 *
9724 * Need custom tracking for your plugin or theme?
9725 * If you are interested in custom event tracking please contact yo@freemius.com
9726 * for further details.
9727 *
9728 * @author Vova Feldman (@svovaf)
9729 * @since 1.2.1
9730 *
9731 * @param string $name Event name.
9732 * @param array $properties Associative key/value array with primitive values only
9733 * @param bool $process_at A valid future date-time in the following format Y-m-d H:i:s.
9734 *
9735 * @return object|false Event data or FALSE on failure.
9736 *
9737 * @throws \Freemius_InvalidArgumentException
9738 *
9739 * @user Freemius::track_event()
9740 */
9741 public function track_event_once( $name, $properties = array(), $process_at = false ) {
9742 return $this->track_event( $name, $properties, $process_at, true );
9743 }
9744
9745 /**
9746 * Plugin uninstall hook.
9747 *
9748 * @author Vova Feldman (@svovaf)
9749 * @since 1.0.1
9750 *
9751 * @param bool $check_user Enforce checking if user have plugins activation privileges.
9752 */
9753 function _uninstall_plugin_event( $check_user = true ) {
9754 $this->_logger->entrance( 'slug = ' . $this->_slug );
9755
9756 if ( $check_user && ! current_user_can( 'activate_plugins' ) ) {
9757 return;
9758 }
9759
9760 $params = array();
9761 $uninstall_reason = null;
9762 if ( isset( $this->_storage->uninstall_reason ) ) {
9763 $uninstall_reason = $this->_storage->uninstall_reason;
9764 $params['reason_id'] = $uninstall_reason->id;
9765 $params['reason_info'] = $uninstall_reason->info;
9766 }
9767
9768 if ( ! $this->is_registered() ) {
9769 // Send anonymous uninstall event only if user submitted a feedback.
9770 if ( isset( $uninstall_reason ) ) {
9771 if ( isset( $uninstall_reason->is_anonymous ) && ! $uninstall_reason->is_anonymous ) {
9772 $this->opt_in( false, false, false, false, true );
9773 } else {
9774 $params['uid'] = $this->get_anonymous_id();
9775 $this->get_api_plugin_scope()->call( 'uninstall.json', 'put', $params );
9776 }
9777 }
9778 } else {
9779 $params = array_merge( $params, array(
9780 'is_active' => false,
9781 'is_uninstalled' => true,
9782 ) );
9783
9784 if ( $this->_is_network_active ) {
9785 // Send uninstall event.
9786 $this->send_installs_update( $params );
9787 } else {
9788 // Send uninstall event and handle the result.
9789 $this->sync_install( $params );
9790 }
9791 }
9792
9793 // @todo Decide if we want to delete plugin information from db.
9794 }
9795
9796 /**
9797 * Set the basename of the current product and hook _activate_plugin_event_hook() to the activation action.
9798 *
9799 * @author Vova Feldman (@svovaf)
9800 * @since 2.2.1
9801 *
9802 * @param string $is_premium
9803 * @param string $caller
9804 *
9805 * @return void
9806 */
9807 function set_basename( $is_premium, $caller ) {
9808 $basename = plugin_basename( $caller );
9809
9810 $current_basename = $is_premium ?
9811 $this->_premium_plugin_basename :
9812 $this->_free_plugin_basename;
9813
9814 if ( $current_basename == $basename ) {
9815 // Basename value set correctly.
9816 return;
9817 }
9818
9819 if ( $is_premium ) {
9820 $this->_premium_plugin_basename = $basename;
9821 } else {
9822 $this->_free_plugin_basename = $basename;
9823 }
9824
9825 $plugin_dir = dirname( $this->_plugin_dir_path ) . '/';
9826
9827 register_activation_hook(
9828 $plugin_dir . $basename,
9829 array( &$this, '_activate_plugin_event_hook' )
9830 );
9831 }
9832
9833 /**
9834 * @author Vova Feldman (@svovaf)
9835 * @since 1.1.1
9836 * @since 2.2.1 If the context product is in its premium version, use the current module's basename, even if it was renamed.
9837 *
9838 * @return string
9839 */
9840 function premium_plugin_basename() {
9841 if ( ! isset( $this->_premium_plugin_basename ) ) {
9842 $this->_premium_plugin_basename = $this->is_premium() ?
9843 // The product is premium, so use the current basename.
9844 $this->_plugin_basename :
9845 $this->get_premium_slug() . '/' . basename( $this->_free_plugin_basename );
9846 }
9847
9848 return $this->_premium_plugin_basename;
9849 }
9850
9851 /**
9852 * Uninstall plugin hook. Called only when connected his account with Freemius for active sites tracking.
9853 *
9854 * @author Vova Feldman (@svovaf)
9855 * @since 1.0.2
9856 */
9857 public static function _uninstall_plugin_hook() {
9858 self::_load_required_static();
9859
9860 self::$_static_logger->entrance();
9861
9862 if ( ! current_user_can( 'activate_plugins' ) ) {
9863 return;
9864 }
9865
9866 $plugin_file = substr( current_filter(), strlen( 'uninstall_' ) );
9867
9868 self::$_static_logger->info( 'plugin = ' . $plugin_file );
9869
9870 define( 'WP_FS__UNINSTALL_MODE', true );
9871
9872 $fs = self::get_instance_by_file( $plugin_file );
9873
9874 if ( is_object( $fs ) ) {
9875 $fs->remove_sdk_reference();
9876
9877 self::require_plugin_essentials();
9878
9879 if ( is_plugin_active( $fs->_free_plugin_basename ) ||
9880 is_plugin_active( $fs->premium_plugin_basename() )
9881 ) {
9882 // Deleting Free or Premium plugin version while the other version still installed.
9883 return;
9884 }
9885
9886 if (
9887 ! $fs->is_clone() &&
9888 /**
9889 * 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).
9890 *
9891 * @author Leo Fajardo
9892 */
9893 ( ! is_object( $fs->_site ) || $fs->is_registered() )
9894 ) {
9895 $fs->_uninstall_plugin_event();
9896 }
9897
9898 $fs->do_action( 'after_uninstall' );
9899 }
9900 }
9901
9902 #----------------------------------------------------------------------------------
9903 #region Plugin Information
9904 #----------------------------------------------------------------------------------
9905
9906 /**
9907 * Load WordPress core plugin.php essential module.
9908 *
9909 * @author Vova Feldman (@svovaf)
9910 * @since 1.1.1
9911 */
9912 private static function require_plugin_essentials() {
9913 if ( ! function_exists( 'get_plugins' ) ) {
9914 self::$_static_logger->log( 'Including wp-admin/includes/plugin.php...' );
9915
9916 require_once ABSPATH . 'wp-admin/includes/plugin.php';
9917 }
9918 }
9919
9920 /**
9921 * Load WordPress core pluggable.php module.
9922 *
9923 * @author Vova Feldman (@svovaf)
9924 * @since 1.1.2
9925 */
9926 private static function require_pluggable_essentials() {
9927 if ( ! function_exists( 'wp_get_current_user' ) ) {
9928 require_once ABSPATH . 'wp-includes/pluggable.php';
9929 }
9930 }
9931
9932 /**
9933 * Return plugin data.
9934 *
9935 * @author Vova Feldman (@svovaf)
9936 * @since 1.0.1
9937 *
9938 * @param bool $reparse_plugin_metadata
9939 *
9940 * @return array
9941 */
9942 function get_plugin_data( $reparse_plugin_metadata = false ) {
9943 if ( ! isset( $this->_plugin_data ) || $reparse_plugin_metadata ) {
9944 self::require_plugin_essentials();
9945
9946 if ( $this->is_plugin() ) {
9947 /**
9948 * @author Vova Feldman (@svovaf)
9949 * @since 1.2.0 When using get_plugin_data() do NOT translate plugin data.
9950 *
9951 * @link https://github.com/Freemius/wordpress-sdk/issues/77
9952 */
9953 $plugin_data = get_plugin_data(
9954 $this->_plugin_main_file_path,
9955 false,
9956 false
9957 );
9958 } else {
9959 $theme_data = wp_get_theme();
9960
9961 if ( $this->_plugin_basename !== $theme_data->get_stylesheet() && is_child_theme() ) {
9962 $parent_theme = $theme_data->parent();
9963
9964 if ( ( $parent_theme instanceof WP_Theme ) && $this->_plugin_basename === $parent_theme->get_stylesheet() ) {
9965 $theme_data = $parent_theme;
9966 }
9967 }
9968
9969 $plugin_data = array(
9970 'Name' => $theme_data->get( 'Name' ),
9971 'Version' => $theme_data->get( 'Version' ),
9972 'Author' => $theme_data->get( 'Author' ),
9973 'Description' => $theme_data->get( 'Description' ),
9974 'PluginURI' => $theme_data->get( 'ThemeURI' ),
9975 );
9976 }
9977
9978 $this->_plugin_data = $plugin_data;
9979 }
9980
9981 return $this->_plugin_data;
9982 }
9983
9984 /**
9985 * @author Vova Feldman (@svovaf)
9986 * @since 1.0.1
9987 * @since 1.2.2.5 If slug not set load slug by module ID.
9988 *
9989 * @return string Plugin slug.
9990 */
9991 function get_slug() {
9992 if ( ! isset( $this->_slug ) ) {
9993 $id_slug_type_path_map = self::$_accounts->get_option( 'id_slug_type_path_map', array() );
9994 $this->_slug = $id_slug_type_path_map[ $this->_module_id ]['slug'];
9995 }
9996
9997 return $this->_slug;
9998 }
9999
10000 /**
10001 * @author Leo Fajardo (@leorw)
10002 * @since 2.2.1
10003 *
10004 * @return string
10005 */
10006 function get_premium_slug() {
10007 return ( is_object( $this->_plugin ) && ! empty( $this->_plugin->premium_slug ) ) ?
10008 $this->_plugin->premium_slug :
10009 "{$this->_slug}-premium";
10010 }
10011
10012 /**
10013 * Retrieve the desired folder name for the product.
10014 *
10015 * @author Vova Feldman (@svovaf)
10016 * @since 1.2.1.7
10017 *
10018 * @return string Plugin slug.
10019 */
10020 function get_target_folder_name() {
10021 return $this->can_use_premium_code() ?
10022 $this->_plugin->premium_slug :
10023 $this->_slug;
10024 }
10025
10026 /**
10027 * @author Vova Feldman (@svovaf)
10028 * @since 1.0.1
10029 *
10030 * @return number Plugin ID.
10031 */
10032 function get_id() {
10033 return $this->_plugin->id;
10034 }
10035
10036 /**
10037 * @author Leo Fajardo (@leorw)
10038 * @since 2.2.4
10039 *
10040 * @return number|null Bundle ID.
10041 */
10042 function get_bundle_id() {
10043 return ( isset( $this->_plugin->bundle_id ) && FS_Plugin::is_valid_id( $this->_plugin->bundle_id ) ) ?
10044 $this->_plugin->bundle_id :
10045 null;
10046 }
10047
10048 /**
10049 * @author Vova Feldman (@svovaf)
10050 * @since 2.3.1
10051 *
10052 * @return string|null Bundle public key.
10053 */
10054 function get_bundle_public_key() {
10055 return isset( $this->_plugin->bundle_public_key ) ?
10056 $this->_plugin->bundle_public_key :
10057 null;
10058 }
10059
10060 /**
10061 * Get whether the SDK has been initiated in the context of a Bundle.
10062 *
10063 * This will return true, if `bundle_id` is present in the SDK init parameters.
10064 *
10065 * ```php
10066 * $my_fs = fs_dynamic_init( array(
10067 * // ...
10068 * 'bundle_id' => 'XXXX', // Will return true since we have bundle id.
10069 * 'bundle_public_key' => 'pk_XXXX',
10070 * ) );
10071 * ```
10072 *
10073 * @author Swashata Ghosh (@swashata)
10074 * @since 2.5.0
10075 *
10076 * @return bool True if we are running in bundle context, false otherwise.
10077 */
10078 private function has_bundle_context() {
10079 return ! is_null( $this->get_bundle_id() );
10080 }
10081
10082 /**
10083 * @author Vova Feldman (@svovaf)
10084 * @since 1.2.1.5
10085 *
10086 * @return string Freemius SDK version
10087 */
10088 function get_sdk_version() {
10089 return $this->version;
10090 }
10091
10092 /**
10093 * @author Vova Feldman (@svovaf)
10094 * @since 1.2.1.5
10095 *
10096 * @return number Parent plugin ID (if parent exist).
10097 */
10098 function get_parent_id() {
10099 return $this->is_addon() ?
10100 $this->get_parent_instance()->get_id() :
10101 $this->_plugin->id;
10102 }
10103
10104 /**
10105 * @author Vova Feldman (@svovaf)
10106 * @since 2.3.1
10107 *
10108 * @return string
10109 */
10110 function get_usage_tracking_terms_url() {
10111 return $this->apply_filters(
10112 'usage_tracking_terms_url',
10113 "https://freemius.com/product/opt-in/{$this->_plugin->id}/{$this->_slug}/"
10114 );
10115 }
10116
10117 /**
10118 * @todo (For LiteSDK) We can refactor this and other related functions giving links to several landing pages on freemius.com to come from a separate class like `FS_Terms_Pages`. This would get a `FS_WP_Hook` (hypothetical) instance as a dependency and use it to hook into the `license_activation_terms_url` or related filters. The entry level instance from `ms_fs()` would hold a public read-only variable `my_fs()->terms_pages` which would be an instance of `FS_Terms_Pages` and would hold all the links to the terms pages.
10119 * @since 2.5.8
10120 *
10121 * @return string
10122 */
10123 function get_license_activation_terms_url() {
10124 return $this->apply_filters(
10125 'license_activation_terms_url',
10126 "https://freemius.com/product/license-activation/{$this->_plugin->id}/{$this->_slug}/"
10127 );
10128 }
10129
10130 /**
10131 * @author Vova Feldman (@svovaf)
10132 * @since 2.3.1
10133 *
10134 * @return string
10135 */
10136 function get_eula_url() {
10137 return $this->apply_filters(
10138 'eula_url',
10139 "https://freemius.com/product/{$this->_plugin->id}/{$this->_slug}/legal/eula/"
10140 );
10141 }
10142
10143 /**
10144 * @author Vova Feldman (@svovaf)
10145 * @since 1.0.1
10146 *
10147 * @return string Plugin public key.
10148 */
10149 function get_public_key() {
10150 return $this->_plugin->public_key;
10151 }
10152
10153 /**
10154 * Will be available only on sandbox mode.
10155 *
10156 * @author Vova Feldman (@svovaf)
10157 * @since 1.0.4
10158 *
10159 * @return mixed Plugin secret key.
10160 */
10161 function get_secret_key() {
10162 return $this->_plugin->secret_key;
10163 }
10164
10165 /**
10166 * @author Vova Feldman (@svovaf)
10167 * @since 1.1.1
10168 *
10169 * @return bool
10170 */
10171 function has_secret_key() {
10172 return ! empty( $this->_plugin->secret_key );
10173 }
10174
10175 /**
10176 * @author Vova Feldman (@svovaf)
10177 * @since 1.0.9
10178 *
10179 * @param string|bool $premium_suffix
10180 *
10181 * @return string
10182 */
10183 function get_plugin_name( $premium_suffix = false ) {
10184 $this->_logger->entrance();
10185
10186 /**
10187 * This `if-else` can be squeezed into a single `if` but I intentionally split it for code readability.
10188 *
10189 * @author Vova Feldman
10190 */
10191 if ( ! isset( $this->_plugin_name ) ) {
10192 // Name is not yet set.
10193 $this->set_name( $premium_suffix );
10194 } else if (
10195 ! empty( $premium_suffix ) &&
10196 ( ! is_object( $this->_plugin ) || $this->_plugin->premium_suffix !== $premium_suffix )
10197 ) {
10198 // Name is already set, but there's a change in the premium suffix.
10199 $this->set_name( $premium_suffix );
10200 }
10201
10202 return $this->_plugin_name;
10203 }
10204
10205 /**
10206 * Calculates and stores the product's name. This helper function was created specifically for get_plugin_name() just to make the code clearer.
10207 *
10208 * @author Vova Feldman (@svovaf)
10209 * @since 2.2.1
10210 *
10211 * @param string $premium_suffix
10212 */
10213 private function set_name( $premium_suffix = '' ) {
10214 $plugin_data = $this->get_plugin_data();
10215
10216 // Get name.
10217 $this->_plugin_name = $plugin_data['Name'];
10218
10219 if ( is_string( $premium_suffix ) ) {
10220 $premium_suffix = trim( $premium_suffix );
10221
10222 if ( ! empty( $premium_suffix ) ) {
10223 // Check if plugin name contains " (premium)" or a custom suffix and remove it.
10224 $suffix = ( ' ' . strtolower( $premium_suffix ) );
10225 $suffix_len = strlen( $suffix );
10226
10227 if ( strlen( $plugin_data['Name'] ) > $suffix_len &&
10228 $suffix === substr( strtolower( $plugin_data['Name'] ), - $suffix_len )
10229 ) {
10230 $this->_plugin_name = substr( $plugin_data['Name'], 0, - $suffix_len );
10231 }
10232 }
10233 }
10234
10235 $this->_logger->departure( 'Name = ' . $this->_plugin_name );
10236 }
10237
10238 /**
10239 * @author Vova Feldman (@svovaf)
10240 * @since 1.0.0
10241 *
10242 * @param bool $reparse_plugin_metadata
10243 *
10244 * @return string
10245 */
10246 function get_plugin_version( $reparse_plugin_metadata = false ) {
10247 $this->_logger->entrance();
10248
10249 $plugin_data = $this->get_plugin_data( $reparse_plugin_metadata );
10250
10251 $this->_logger->departure( 'Version = ' . $plugin_data['Version'] );
10252
10253 return $this->apply_filters( 'plugin_version', $plugin_data['Version'] );
10254 }
10255
10256 /**
10257 * @author Vova Feldman (@svovaf)
10258 * @since 1.2.1.7
10259 *
10260 * @return string
10261 */
10262 function get_plugin_title() {
10263 $this->_logger->entrance();
10264
10265 $title = $this->_plugin->title;
10266
10267 return $this->apply_filters( 'plugin_title', $title );
10268 }
10269
10270 /**
10271 * @author Vova Feldman (@svovaf)
10272 * @since 1.2.2.7
10273 *
10274 * @param bool $lowercase
10275 *
10276 * @return string
10277 */
10278 function get_module_label( $lowercase = false ) {
10279 $label = $this->is_addon() ?
10280 $this->get_text_inline( 'Add-On', 'addon' ) :
10281 ( $this->is_plugin() ?
10282 $this->get_text_inline( 'Plugin', 'plugin' ) :
10283 $this->get_text_inline( 'Theme', 'theme' ) );
10284
10285 if ( $lowercase ) {
10286 $label = strtolower( $label );
10287 }
10288
10289 return $label;
10290 }
10291
10292 /**
10293 * @author Vova Feldman (@svovaf)
10294 * @since 1.0.4
10295 *
10296 * @return string
10297 */
10298 function get_plugin_basename() {
10299 if ( ! isset( $this->_plugin_basename ) ) {
10300 if ( $this->is_plugin() ) {
10301 $this->_plugin_basename = plugin_basename( $this->_plugin_main_file_path );
10302 } else {
10303 $this->_plugin_basename = basename( dirname( $this->_plugin_main_file_path ) );
10304 }
10305 }
10306
10307 return $this->_plugin_basename;
10308 }
10309
10310 function get_plugin_folder_name() {
10311 $this->_logger->entrance();
10312
10313 $plugin_folder = $this->_plugin_basename;
10314
10315 while ( '.' !== dirname( $plugin_folder ) ) {
10316 $plugin_folder = dirname( $plugin_folder );
10317 }
10318
10319 $this->_logger->departure( 'Folder Name = ' . $plugin_folder );
10320
10321 return $plugin_folder;
10322 }
10323
10324 #endregion ------------------------------------------------------------------
10325
10326 /* Account
10327 ------------------------------------------------------------------------------------------------------------------*/
10328
10329 /**
10330 * Find plugin's slug by plugin's basename.
10331 *
10332 * @author Vova Feldman (@svovaf)
10333 * @since 1.0.9
10334 *
10335 * @param string $plugin_base_name
10336 *
10337 * @return false|string
10338 */
10339 private static function find_slug_by_basename( $plugin_base_name ) {
10340 $file_slug_map = self::$_accounts->get_option( 'file_slug_map', array() );
10341
10342 if ( ! array( $file_slug_map ) || ! isset( $file_slug_map[ $plugin_base_name ] ) ) {
10343 return false;
10344 }
10345
10346 return $file_slug_map[ $plugin_base_name ];
10347 }
10348
10349 /**
10350 * Store the map between the plugin's basename to the slug.
10351 *
10352 * @author Vova Feldman (@svovaf)
10353 * @since 1.0.9
10354 */
10355 private function store_file_slug_map() {
10356 $file_slug_map = self::$_accounts->get_option( 'file_slug_map', array() );
10357
10358 if ( ! array( $file_slug_map ) ) {
10359 $file_slug_map = array();
10360 }
10361
10362 if ( ! isset( $file_slug_map[ $this->_plugin_basename ] ) ||
10363 $file_slug_map[ $this->_plugin_basename ] !== $this->_slug
10364 ) {
10365 $file_slug_map[ $this->_plugin_basename ] = $this->_slug;
10366 self::$_accounts->set_option( 'file_slug_map', $file_slug_map, true );
10367 }
10368 }
10369
10370 /**
10371 * @return array[number]FS_User
10372 */
10373 static function get_all_users() {
10374 $users = self::maybe_get_entities_account_option( 'users', array() );
10375
10376 if ( ! is_array( $users ) ) {
10377 $users = array();
10378 }
10379
10380 return $users;
10381 }
10382
10383 /**
10384 * @param string $module_type
10385 * @param null|int $blog_id Since 2.0.0
10386 *
10387 * @return array[string]FS_Site
10388 */
10389 public static function get_all_sites(
10390 $module_type = WP_FS__MODULE_TYPE_PLUGIN,
10391 $blog_id = null,
10392 $is_backup = false
10393 ) {
10394 $sites = self::get_account_option(
10395 ( $is_backup ? 'prev_' : '' ) . 'sites',
10396 $module_type,
10397 $blog_id
10398 );
10399
10400 if ( ! is_array( $sites ) ) {
10401 $sites = array();
10402 }
10403
10404 return $sites;
10405 }
10406
10407 /**
10408 * @author Leo Fajardo (@leorw)
10409 *
10410 * @since 1.2.2
10411 *
10412 * @param string $option_name
10413 * @param string $module_type
10414 * @param null|int $network_level_or_blog_id Since 2.0.0
10415 *
10416 * @return mixed
10417 */
10418 public static function get_account_option( $option_name, $module_type = null, $network_level_or_blog_id = null ) {
10419 if ( ! is_null( $module_type ) && WP_FS__MODULE_TYPE_PLUGIN !== $module_type ) {
10420 $option_name = $module_type . '_' . $option_name;
10421 }
10422
10423 return self::maybe_get_entities_account_option( $option_name, array(), $network_level_or_blog_id );
10424 }
10425
10426 /**
10427 * @author Leo Fajardo (@leorw)
10428 *
10429 * @since 1.2.2
10430 *
10431 * @param string $option_name
10432 * @param mixed $option_value
10433 * @param bool $store
10434 * @param null|int $network_level_or_blog_id Since 2.0.0
10435 */
10436 private function set_account_option( $option_name, $option_value, $store, $network_level_or_blog_id = null ) {
10437 self::set_account_option_by_module(
10438 $this->_module_type,
10439 $option_name,
10440 $option_value,
10441 $store,
10442 $network_level_or_blog_id
10443 );
10444 }
10445
10446 /**
10447 * @author Vova Feldman (@svovaf)
10448 *
10449 * @since 1.2.2.7
10450 *
10451 * @param string $module_type
10452 * @param string $option_name
10453 * @param mixed $option_value
10454 * @param bool $store
10455 * @param null|int $network_level_or_blog_id Since 2.0.0
10456 */
10457 private static function set_account_option_by_module(
10458 $module_type,
10459 $option_name,
10460 $option_value,
10461 $store,
10462 $network_level_or_blog_id = null
10463 ) {
10464 if ( WP_FS__MODULE_TYPE_PLUGIN != $module_type ) {
10465 $option_name = $module_type . '_' . $option_name;
10466 }
10467
10468 self::$_accounts->set_option( $option_name, $option_value, $store, $network_level_or_blog_id );
10469 }
10470
10471 /**
10472 * This method can also return non-entity or non-entities collection option like the `user_id_license_ids_map` option.
10473 *
10474 * @author Leo Fajardo (@leorw)
10475 * @since 2.3.1
10476 *
10477 * @param string $option_name
10478 * @param mixed $default
10479 * @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).
10480 *
10481 * @return mixed|FS_Plugin[]|FS_User[]|FS_Site[]|FS_Plugin_License[]|FS_Plugin_Plan[]|FS_Plugin_Tag[]
10482 */
10483 private static function maybe_get_entities_account_option( $option_name, $default = null, $network_level_or_blog_id = null ) {
10484 $option = self::$_accounts->get_option( $option_name, $default, $network_level_or_blog_id );
10485
10486 $class_name = '';
10487
10488 if ( fs_starts_with( $option_name, WP_FS__MODULE_TYPE_THEME . '_' ) ) {
10489 $option_name = str_replace( WP_FS__MODULE_TYPE_THEME . '_', '', $option_name );
10490 }
10491
10492 switch ( $option_name ) {
10493 case 'plugins':
10494 case 'themes':
10495 case 'addons':
10496 $class_name = FS_Plugin::get_class_name();
10497 break;
10498 case 'users':
10499 $class_name = FS_User::get_class_name();
10500 break;
10501 case 'sites':
10502 $class_name = FS_Site::get_class_name();
10503 break;
10504 case 'licenses':
10505 case 'all_licenses':
10506 $class_name = FS_Plugin_License::get_class_name();
10507 break;
10508 case 'plans':
10509 $class_name = FS_Plugin_Plan::get_class_name();
10510 break;
10511 case 'updates':
10512 $class_name = FS_Plugin_Tag::get_class_name();
10513 break;
10514 }
10515
10516 if ( empty( $class_name ) ) {
10517 return $option;
10518 }
10519
10520 return fs_get_entities( $option, $class_name );
10521 }
10522
10523 /**
10524 * @author Vova Feldman (@svovaf)
10525 * @since 1.0.6
10526 *
10527 * @param number|null $module_id
10528 *
10529 * @return FS_Plugin_License[]
10530 */
10531 private static function get_all_licenses( $module_id = null ) {
10532 $licenses = self::get_account_option( 'all_licenses' );
10533
10534 if ( ! is_array( $licenses ) ) {
10535 $licenses = array();
10536 }
10537
10538 if ( is_null( $module_id ) ) {
10539 return $licenses;
10540 }
10541
10542 $licenses = isset( $licenses[ $module_id ] ) ?
10543 $licenses[ $module_id ] :
10544 array();
10545
10546 return $licenses;
10547 }
10548
10549 /**
10550 * @author Leo Fajardo (@leorw)
10551 * @since 2.0.0
10552 *
10553 * @param number $module_id
10554 * @param number|null $user_id
10555 *
10556 * @return array
10557 */
10558 private static function get_user_id_license_ids_map( $module_id, $user_id = null ) {
10559 $all_modules_user_id_license_ids_map = self::get_account_option( 'user_id_license_ids_map' );
10560
10561 if ( ! is_array( $all_modules_user_id_license_ids_map ) ) {
10562 $all_modules_user_id_license_ids_map = array();
10563 }
10564
10565 $user_id_license_ids_map = isset( $all_modules_user_id_license_ids_map[ $module_id ] ) ?
10566 $all_modules_user_id_license_ids_map[ $module_id ] :
10567 array();
10568
10569 if ( FS_User::is_valid_id( $user_id ) ) {
10570 $user_id_license_ids_map = isset( $user_id_license_ids_map[ $user_id ] ) ?
10571 $user_id_license_ids_map[ $user_id ] :
10572 array();
10573 }
10574
10575 return $user_id_license_ids_map;
10576 }
10577
10578 /**
10579 * @author Leo Fajardo (@leorw)
10580 * @since 2.0.0
10581 *
10582 * @param array $new_user_id_license_ids_map
10583 * @param number $module_id
10584 * @param number|null $user_id
10585 */
10586 private static function store_user_id_license_ids_map( $new_user_id_license_ids_map, $module_id, $user_id = null ) {
10587 $all_modules_user_id_license_ids_map = self::get_account_option( 'user_id_license_ids_map' );
10588 if ( ! is_array( $all_modules_user_id_license_ids_map ) ) {
10589 $all_modules_user_id_license_ids_map = array();
10590 }
10591
10592 if ( ! isset( $all_modules_user_id_license_ids_map[ $module_id ] ) ) {
10593 $all_modules_user_id_license_ids_map[ $module_id ] = array();
10594 }
10595
10596 if ( FS_User::is_valid_id( $user_id ) ) {
10597 $all_modules_user_id_license_ids_map[ $module_id ][ $user_id ] = $new_user_id_license_ids_map;
10598 } else {
10599 $all_modules_user_id_license_ids_map[ $module_id ] = $new_user_id_license_ids_map;
10600 }
10601
10602 self::$_accounts->set_option( 'user_id_license_ids_map', $all_modules_user_id_license_ids_map, true );
10603 }
10604
10605 /**
10606 * Get a collection of the user's linked license IDs.
10607 *
10608 * @author Vova Feldman (@svovaf)
10609 * @since 2.0.0
10610 *
10611 * @param number $user_id
10612 *
10613 * @return number[]
10614 */
10615 private function get_user_linked_license_ids( $user_id ) {
10616 return self::get_user_id_license_ids_map( $this->_module_id, $user_id );
10617 }
10618
10619 /**
10620 * Override the user's linked license IDs with a new IDs collection.
10621 *
10622 * @author Vova Feldman (@svovaf)
10623 * @since 2.0.0
10624 *
10625 * @param number $user_id
10626 * @param number[] $license_ids
10627 */
10628 private function set_user_linked_license_ids( $user_id, array $license_ids ) {
10629 self::store_user_id_license_ids_map( $license_ids, $this->_module_id, $user_id );
10630 }
10631
10632 /**
10633 * Link a specified license ID to a given user.
10634 *
10635 * @author Vova Feldman (@svovaf)
10636 * @since 2.0.0
10637 *
10638 * @param number $license_id
10639 * @param number $user_id
10640 */
10641 private function link_license_2_user( $license_id, $user_id ) {
10642 $license_ids = $this->get_user_linked_license_ids( $user_id );
10643
10644 if ( in_array( $license_id, $license_ids ) ) {
10645 // License already linked.
10646 return;
10647 }
10648
10649 $license_ids[] = $license_id;
10650
10651 $this->set_user_linked_license_ids( $user_id, $license_ids );
10652 }
10653
10654 /**
10655 * @param string|bool $module_type
10656 *
10657 * @return FS_Plugin_Plan[]
10658 */
10659 private static function get_all_plans( $module_type = false ) {
10660 $plans = self::get_account_option( 'plans', $module_type );
10661
10662 if ( ! is_array( $plans ) ) {
10663 $plans = array();
10664 }
10665
10666 return $plans;
10667 }
10668
10669 /**
10670 * @author Vova Feldman (@svovaf)
10671 * @since 1.0.4
10672 *
10673 * @return FS_Plugin_Tag[]
10674 */
10675 private static function get_all_updates() {
10676 $updates = self::maybe_get_entities_account_option( 'updates', array() );
10677
10678 if ( ! is_array( $updates ) ) {
10679 $updates = array();
10680 }
10681
10682 return $updates;
10683 }
10684
10685 /**
10686 * @author Vova Feldman (@svovaf)
10687 * @since 1.0.6
10688 *
10689 * @return array<number,FS_Plugin[]>|false
10690 */
10691 public static function get_all_addons() {
10692 $addons = self::maybe_get_entities_account_option( 'addons', array() );
10693
10694 if ( ! is_array( $addons ) ) {
10695 $addons = array();
10696 }
10697
10698 return $addons;
10699 }
10700
10701 /**
10702 * @author Vova Feldman (@svovaf)
10703 * @since 1.0.6
10704 *
10705 * @return number[]|false
10706 */
10707 public static function get_all_account_addons() {
10708 $addons = self::$_accounts->get_option( 'account_addons', array() );
10709
10710 if ( ! is_array( $addons ) ) {
10711 $addons = array();
10712 }
10713
10714 return $addons;
10715 }
10716
10717 /**
10718 * Check if user has connected his account (opted-in).
10719 *
10720 * Note:
10721 * If the user opted-in and opted-out on a later stage,
10722 * this will still return true. If you want to check if the
10723 * user is currently opted-in, use:
10724 * `$fs->is_registered() && $fs->is_tracking_allowed()`
10725 *
10726 * @author Vova Feldman (@svovaf)
10727 * @since 1.0.1
10728 *
10729 * @param bool $ignore_anonymous_state Since 2.5.1
10730 *
10731 * @return bool
10732 */
10733 function is_registered( $ignore_anonymous_state = false ) {
10734 return (
10735 is_object( $this->_user ) &&
10736 (
10737 $this->is_premium() ||
10738 $ignore_anonymous_state ||
10739 ! $this->is_anonymous()
10740 )
10741 );
10742 }
10743
10744 /**
10745 * Returns TRUE if the user opted-in and didn't disconnect (opt-out).
10746 *
10747 * @author Leo Fajardo (@leorw)
10748 * @since 1.2.1.5
10749 *
10750 * @return bool
10751 */
10752 function is_tracking_allowed( $blog_id = null, $install = null ) {
10753 if ( is_null( $install ) ) {
10754 $install = is_null( $blog_id ) ?
10755 $this->_site :
10756 $this->get_install_by_blog_id( $blog_id );
10757 }
10758
10759 return (
10760 is_object( $install ) &&
10761 FS_Permission_Manager::instance( $this )->is_homepage_url_tracking_allowed( $blog_id )
10762 );
10763 }
10764
10765 /**
10766 * Returns TRUE if the user never opted-in or manually opted-out.
10767 *
10768 * @author Vova Feldman (@svovaf)
10769 * @since 1.2.1.5
10770 *
10771 * @param int|null $blog_id
10772 *
10773 * @return bool
10774 */
10775 function is_tracking_prohibited( $blog_id = null ) {
10776 return (
10777 ! $this->is_registered( true ) ||
10778 ! $this->is_tracking_allowed( $blog_id )
10779 );
10780 }
10781
10782 /**
10783 * @author Leo Fajardo (@leorw)
10784 * @since 2.4.0
10785 *
10786 * @return bool
10787 */
10788 function is_bundle_license_auto_activation_enabled() {
10789 return $this->is_addon() ?
10790 ( is_object( $this->_parent ) && $this->_parent->is_bundle_license_auto_activation_enabled() ) :
10791 $this->_is_bundle_license_auto_activation_enabled;
10792 }
10793
10794 /**
10795 * @author Vova Feldman (@svovaf)
10796 * @since 1.0.4
10797 *
10798 * @return FS_Plugin
10799 */
10800 function get_plugin() {
10801 return $this->_plugin;
10802 }
10803
10804 /**
10805 * @author Vova Feldman (@svovaf)
10806 * @since 1.0.3
10807 *
10808 * @return FS_User
10809 */
10810 function get_user() {
10811 return $this->_user;
10812 }
10813
10814 /**
10815 * @author Vova Feldman (@svovaf)
10816 * @since 1.0.3
10817 *
10818 * @return FS_Site
10819 */
10820 function get_site() {
10821 return $this->_site;
10822 }
10823
10824 /**
10825 * @author Daniele Alessandra (@danielealessandra)
10826 * @return FS_Storage
10827 * @since 2.6.2
10828 *
10829 */
10830 public function get_storage() {
10831 return $this->_storage;
10832 }
10833
10834 /**
10835 * @author Leo Fajardo (@leorw)
10836 * @since 2.5.0
10837 */
10838 function store_site( $site ) {
10839 $this->_site = $site;
10840 $this->_store_site( true );
10841 }
10842
10843 /**
10844 * 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).
10845 *
10846 * @author Leo Fajardo (@leorw)
10847 * @since 2.5.0
10848 */
10849 function delete_current_install( $back_up ) {
10850 // Back up and delete the unique ID.
10851 if ( $back_up ) {
10852 self::$_accounts->set_option( 'prev_unique_id', $this->get_anonymous_id() );
10853 }
10854
10855 self::$_accounts->set_option( 'unique_id', null );
10856
10857 if ( $back_up ) {
10858 // 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).
10859 $this->back_up_site();
10860 }
10861
10862 $this->_delete_site();
10863 $this->_site = null;
10864 }
10865
10866 /**
10867 * @author Leo Fajardo (@leorw)
10868 * @since 2.5.0
10869 */
10870 function restore_backup_site() {
10871 self::$_accounts->set_option(
10872 'unique_id',
10873 self::$_accounts->get_option( 'prev_unique_id' )
10874 );
10875
10876 $sites = self::get_all_sites( $this->_module_type, null, true );
10877 $this->store_site( clone $sites[ $this->_slug ] );
10878 }
10879
10880 /**
10881 * Get plugin add-ons.
10882 *
10883 * @author Vova Feldman (@svovaf)
10884 * @since 1.0.6
10885 *
10886 * @since 1.1.7.3 If not yet loaded, fetch data from the API.
10887 *
10888 * @param bool $flush
10889 *
10890 * @return FS_Plugin[]|false
10891 */
10892 function get_addons( $flush = false ) {
10893 $this->_logger->entrance();
10894
10895 if ( ! $this->_has_addons ) {
10896 return false;
10897 }
10898
10899 $addons = $this->sync_addons( $flush );
10900
10901 return ( ! is_array( $addons ) || empty( $addons ) ) ?
10902 false :
10903 $addons;
10904 }
10905
10906 /**
10907 * @author Vova Feldman (@svovaf)
10908 * @since 1.0.6
10909 *
10910 * @return number[]|false
10911 */
10912 function get_account_addons() {
10913 $this->_logger->entrance();
10914
10915 $addons = self::get_all_account_addons();
10916
10917 if ( ! is_array( $addons ) ||
10918 ! isset( $addons[ $this->_plugin->id ] ) ||
10919 ! is_array( $addons[ $this->_plugin->id ] ) ||
10920 0 === count( $addons[ $this->_plugin->id ] )
10921 ) {
10922 return false;
10923 }
10924
10925 return $addons[ $this->_plugin->id ];
10926 }
10927
10928 /**
10929 * Check if user has any
10930 *
10931 * @author Vova Feldman (@svovaf)
10932 * @since 1.1.6
10933 *
10934 * @return bool
10935 */
10936 function has_account_addons() {
10937 $addons = $this->get_account_addons();
10938
10939 return is_array( $addons ) && ( 0 < count( $addons ) );
10940 }
10941
10942
10943 /**
10944 * Get add-on by ID (from local data).
10945 *
10946 * @author Vova Feldman (@svovaf)
10947 * @since 1.0.6
10948 *
10949 * @param number $id
10950 *
10951 * @return FS_Plugin|false
10952 */
10953 function get_addon( $id ) {
10954 $this->_logger->entrance();
10955
10956 $addons = $this->get_addons();
10957
10958 if ( is_array( $addons ) ) {
10959 foreach ( $addons as $addon ) {
10960 if ( $id == $addon->id ) {
10961 return $addon;
10962 }
10963 }
10964 }
10965
10966 return false;
10967 }
10968
10969 /**
10970 * Get add-on by slug (from local data).
10971 *
10972 * @author Vova Feldman (@svovaf)
10973 * @since 1.0.6
10974 *
10975 * @param string $slug
10976 *
10977 * @param bool $flush
10978 *
10979 * @return FS_Plugin|false
10980 */
10981 function get_addon_by_slug( $slug, $flush = false ) {
10982 $this->_logger->entrance();
10983
10984 $addons = $this->get_addons( $flush );
10985
10986 if ( is_array( $addons ) ) {
10987 foreach ( $addons as $addon ) {
10988 if ( $slug === $addon->slug ) {
10989 return $addon;
10990 }
10991 }
10992 }
10993
10994 return false;
10995 }
10996
10997 /**
10998 * @var array<number,object[]> {
10999 * @key number Add-on ID.
11000 * @val object[] The add-on's plans and prices object.
11001 * }
11002 */
11003 private $plans_and_pricing_by_addon_id;
11004
11005 /**
11006 * @author Leo Fajardo (@leorw)
11007 * @since 2.3.0
11008 *
11009 * @return array<number,object[]> {
11010 * @key number Add-on ID.
11011 * @val object[] The add-on's plans and prices object.
11012 * }
11013 */
11014 function _get_addons_plans_and_pricing_map_by_id() {
11015 if ( ! isset( $this->plans_and_pricing_by_addon_id ) ) {
11016 $result = $this->get_api_plugin_scope()->get( $this->add_show_pending( "/addons/pricing.json?type=visible" ) );
11017
11018 $plans_and_pricing_by_addon_id = array();
11019 if ( $this->is_api_result_object( $result, 'addons' ) ) {
11020 foreach ( $result->addons as $addon ) {
11021 $plans_and_pricing_by_addon_id[ $addon->id ] = $addon->plans;
11022 }
11023 }
11024
11025 $this->plans_and_pricing_by_addon_id = $plans_and_pricing_by_addon_id;
11026 }
11027
11028 return $this->plans_and_pricing_by_addon_id;
11029 }
11030
11031 /**
11032 * @author Leo Fajardo (@leorw)
11033 * @since 2.3.0
11034 *
11035 * @param number $addon_id
11036 * @param bool $is_installed
11037 *
11038 * @return array
11039 */
11040 function _get_addon_info( $addon_id, $is_installed ) {
11041 $addon = $this->get_addon( $addon_id );
11042
11043 if ( ! is_object( $addon ) ) {
11044 // Unexpected call.
11045 return array();
11046 }
11047
11048 $slug = $addon->slug;
11049
11050 $addon_storage = FS_Storage::instance( WP_FS__MODULE_TYPE_PLUGIN, $slug );
11051
11052 if ( ! fs_is_network_admin() ) {
11053 // Get blog-level activated installations.
11054 $sites = self::maybe_get_entities_account_option( 'sites', array() );
11055 } else {
11056 $sites = null;
11057
11058 if ( $this->is_addon_activated( $addon_id ) &&
11059 $this->get_addon_instance( $addon_id )->is_network_active()
11060 ) {
11061 if ( FS_Site::is_valid_id( $addon_storage->network_install_blog_id ) ) {
11062 // Get network-level activated installations.
11063 $sites = self::maybe_get_entities_account_option(
11064 'sites',
11065 array(),
11066 $addon_storage->network_install_blog_id
11067 );
11068 }
11069 }
11070 }
11071
11072 $addon_info = array(
11073 'is_connected' => false,
11074 'slug' => $slug,
11075 'title' => $addon->title,
11076 'is_whitelabeled' => $addon_storage->is_whitelabeled
11077 );
11078
11079 if ( ! $is_installed ) {
11080 $plans_and_pricing_by_addon_id = $this->_get_addons_plans_and_pricing_map_by_id();
11081
11082 if ( isset( $plans_and_pricing_by_addon_id[ $addon_id ] ) ) {
11083 $has_paid_plan = false;
11084 $plans = $plans_and_pricing_by_addon_id[ $addon_id ];
11085
11086 if ( is_array( $plans ) && count( $plans ) > 0 ) {
11087 foreach ( $plans as $plan ) {
11088 if ( isset( $plan->pricing ) &&
11089 is_array( $plan->pricing ) &&
11090 count( $plan->pricing ) > 0
11091 ) {
11092 $has_paid_plan = true;
11093 break;
11094 }
11095 }
11096 }
11097
11098 $addon_info['has_paid_plan'] = $has_paid_plan;
11099 }
11100 }
11101
11102 if ( ! is_array( $sites ) || ! isset( $sites[ $slug ] ) ) {
11103 return $addon_info;
11104 }
11105
11106 $site = $sites[ $slug ];
11107
11108 $addon_info['is_connected'] = (
11109 ( $addon->parent_plugin_id == $this->get_id() ) &&
11110 is_object( $site ) &&
11111 FS_Site::is_valid_id( $site->id ) &&
11112 FS_User::is_valid_id( $site->user_id ) &&
11113 FS_Plugin_Plan::is_valid_id( $site->plan_id )
11114 );
11115
11116 if ( $addon_info['is_connected'] && $is_installed ) {
11117 return $addon_info;
11118 }
11119
11120 $addon_info['site'] = $site;
11121
11122 $plugins_data = self::maybe_get_entities_account_option( WP_FS__MODULE_TYPE_PLUGIN . 's', array() );
11123 if ( isset( $plugins_data[ $slug ] ) ) {
11124 $plugin_data = $plugins_data[ $slug ];
11125
11126 $addon_info['version'] = $plugin_data->version;
11127 }
11128
11129 $all_plans = self::maybe_get_entities_account_option( 'plans', array() );
11130 if ( isset( $all_plans[ $slug ] ) ) {
11131 $plans = $all_plans[ $slug ];
11132
11133 foreach ( $plans as $plan ) {
11134 if ( $site->plan_id == Freemius::_decrypt( $plan->id ) ) {
11135 $addon_info['plan_name'] = Freemius::_decrypt( $plan->name );
11136 $addon_info['plan_title'] = Freemius::_decrypt( $plan->title );
11137 break;
11138 }
11139 }
11140 }
11141
11142 $licenses = self::maybe_get_entities_account_option( 'all_licenses', array() );
11143 if ( is_array( $licenses ) && isset( $licenses[ $addon_id ] ) ) {
11144 foreach ( $licenses[ $addon_id ] as $license ) {
11145 if ( $license->id == $site->license_id ) {
11146 $addon_info['license'] = $license;
11147 break;
11148 }
11149 }
11150 }
11151
11152 if ( isset( $addon_info['license'] ) ) {
11153 if ( isset( $addon_storage->subscriptions ) &&
11154 ! empty( $addon_storage->subscriptions )
11155 ) {
11156 $addon_subscriptions = fs_get_entities( $addon_storage->subscriptions, FS_Subscription::get_class_name() );
11157
11158 foreach ( $addon_subscriptions as $subscription ) {
11159 if ( $subscription->license_id == $site->license_id ) {
11160 $addon_info['subscription'] = $subscription;
11161 break;
11162 }
11163 }
11164 }
11165 }
11166
11167 return $addon_info;
11168 }
11169
11170 /**
11171 * @author Vova Feldman (@svovaf)
11172 * @since 2.0.0
11173 *
11174 * @param number $user_id
11175 *
11176 * @return FS_User
11177 */
11178 static function _get_user_by_id( $user_id ) {
11179 self::$_static_logger->entrance( "user_id = {$user_id}" );
11180
11181 $users = self::get_all_users();
11182
11183 if ( is_array( $users ) ) {
11184 if ( isset( $users[ $user_id ] ) &&
11185 $users[ $user_id ] instanceof FS_User &&
11186 $user_id == $users[ $user_id ]->id
11187 ) {
11188 return $users[ $user_id ];
11189 }
11190
11191 // If user wasn't found by the key, iterate over all the users collection.
11192 foreach ( $users as $user ) {
11193 /**
11194 * @var FS_User $user
11195 */
11196 if ( $user_id == $user->id ) {
11197 return $user;
11198 }
11199 }
11200 }
11201
11202 return null;
11203 }
11204
11205 /**
11206 * Checks if a Freemius user_id is associated with a super-admin.
11207 *
11208 * @author Vova Feldman (@svovaf)
11209 * @since 2.0.0
11210 *
11211 * @param number $user_id
11212 *
11213 * @return bool
11214 */
11215 private static function is_super_admin( $user_id ) {
11216 $is_super_admin = false;
11217
11218 $user = self::_get_user_by_id( $user_id );
11219
11220 if ( $user instanceof FS_User && ! empty( $user->email ) ) {
11221 self::require_pluggable_essentials();
11222
11223 $wp_user = get_user_by( 'email', $user->email );
11224
11225 if ( $wp_user instanceof WP_User ) {
11226 $super_admins = get_super_admins();
11227 $is_super_admin = ( is_array( $super_admins ) && in_array( $wp_user->user_login, $super_admins ) );
11228 }
11229 }
11230
11231 return $is_super_admin;
11232 }
11233
11234 #----------------------------------------------------------------------------------
11235 #region Plans & Licensing
11236 #----------------------------------------------------------------------------------
11237
11238 /**
11239 * Check if running premium plugin code.
11240 *
11241 * @author Vova Feldman (@svovaf)
11242 * @since 1.0.5
11243 *
11244 * @return bool
11245 */
11246 function is_premium() {
11247 /**
11248 * `$this->_plugin` will be `false` when `is_activation_mode` calls this method directly from the
11249 * `register_constructor_hooks` method.
11250 *
11251 * @author Leo Fajardo (@leorw)
11252 * @since 2.2.3
11253 */
11254 return is_object( $this->_plugin ) ?
11255 $this->_plugin->is_premium :
11256 false;
11257 }
11258
11259 /**
11260 * Get site's plan ID.
11261 *
11262 * @author Vova Feldman (@svovaf)
11263 * @since 1.0.2
11264 *
11265 * @return number
11266 */
11267 function get_plan_id() {
11268 return $this->_site->plan_id;
11269 }
11270
11271 /**
11272 * Get site's plan title.
11273 *
11274 * @author Vova Feldman (@svovaf)
11275 * @since 1.0.2
11276 *
11277 * @return string
11278 */
11279 function get_plan_title() {
11280 $plan = $this->get_plan();
11281
11282 return is_object( $plan ) ? $plan->title : 'PLAN_TITLE';
11283 }
11284
11285 /**
11286 * Get site's plan name.
11287 *
11288 * @author Vova Feldman (@svovaf)
11289 * @since 2.0.0
11290 *
11291 * @return string
11292 */
11293 function get_plan_name() {
11294 $plan = $this->get_plan();
11295
11296 return is_object( $plan ) ? $plan->name : 'PLAN_NAME';
11297 }
11298
11299 /**
11300 * @author Vova Feldman (@svovaf)
11301 * @since 1.0.9
11302 *
11303 * @return FS_Plugin_Plan|false
11304 */
11305 function get_plan() {
11306 if ( ! is_object( $this->_site ) ) {
11307 return false;
11308 }
11309
11310 return FS_Plugin_Plan::is_valid_id( $this->_site->plan_id ) ?
11311 $this->_get_plan_by_id( $this->_site->plan_id ) :
11312 false;
11313 }
11314
11315 /**
11316 * @author Vova Feldman (@svovaf)
11317 * @since 1.0.3
11318 *
11319 * @return bool
11320 */
11321 function is_trial() {
11322 $this->_logger->entrance();
11323
11324 if ( ! $this->is_registered( true ) || ! is_object( $this->_site ) ) {
11325 return false;
11326 }
11327
11328 return $this->_site->is_trial();
11329 }
11330
11331 /**
11332 * Check if currently in a trial with payment method (credit card or paypal).
11333 *
11334 * @author Vova Feldman (@svovaf)
11335 * @since 1.1.7
11336 *
11337 * @return bool
11338 */
11339 function is_paid_trial() {
11340 $this->_logger->entrance();
11341
11342 if ( ! $this->is_trial() ) {
11343 return false;
11344 }
11345
11346 if ( ! $this->has_active_valid_license() ) {
11347 return false;
11348 }
11349
11350 if ( $this->_site->trial_plan_id != $this->_license->plan_id ) {
11351 return false;
11352 }
11353
11354 /**
11355 * @var FS_Subscription $subscription
11356 */
11357 $subscription = $this->_get_subscription( $this->_license->id );
11358
11359 return ( is_object( $subscription ) && $subscription->is_active() );
11360 }
11361
11362 /**
11363 * Check if trial already utilized.
11364 *
11365 * @since 1.0.9
11366 *
11367 * @return bool
11368 */
11369 function is_trial_utilized() {
11370 $this->_logger->entrance();
11371
11372 if ( ! $this->is_registered() ) {
11373 return false;
11374 }
11375
11376 return $this->_site->is_trial_utilized();
11377 }
11378
11379 /**
11380 * Get trial plan information (if in trial).
11381 *
11382 * @author Vova Feldman (@svovaf)
11383 * @since 1.0.9
11384 *
11385 * @return bool|FS_Plugin_Plan
11386 */
11387 function get_trial_plan() {
11388 $this->_logger->entrance();
11389
11390 if ( ! $this->is_trial() ) {
11391 return false;
11392 }
11393
11394 // Try to load plan from local cache.
11395 $trial_plan = $this->_get_plan_by_id( $this->_site->trial_plan_id );
11396
11397 if ( ! is_object( $trial_plan ) ) {
11398 $trial_plan = $this->_fetch_site_plan( $this->_site->trial_plan_id );
11399
11400 /**
11401 * If managed to fetch the plan, add it to the plans collection.
11402 */
11403 if ( $trial_plan instanceof FS_Plugin_Plan ) {
11404 if ( ! is_array( $this->_plans ) ) {
11405 $this->_plans = array();
11406 }
11407
11408 $this->_plans[] = $trial_plan;
11409 $this->_store_plans();
11410 }
11411 }
11412
11413 if ( $trial_plan instanceof FS_Plugin_Plan ) {
11414 return $trial_plan;
11415 }
11416
11417 /**
11418 * If for some reason failed to get the trial plan, fallback to a dummy name and title.
11419 */
11420 $trial_plan = new FS_Plugin_Plan();
11421 $trial_plan->id = $this->_site->trial_plan_id;
11422 $trial_plan->name = 'pro';
11423 $trial_plan->title = 'Pro';
11424
11425 return $trial_plan;
11426 }
11427
11428 /**
11429 * Check if the user has an activate, non-expired license on current plugin's install.
11430 *
11431 * @since 1.0.9
11432 *
11433 * @return bool
11434 */
11435 function is_paying() {
11436 $this->_logger->entrance();
11437
11438 if ( ! $this->is_registered( true ) ) {
11439 return false;
11440 }
11441
11442 if ( ! $this->has_paid_plan() ) {
11443 return false;
11444 }
11445
11446 return (
11447 ! $this->is_trial() &&
11448 'free' !== $this->get_plan_name() &&
11449 $this->has_active_valid_license()
11450 );
11451 }
11452
11453 /**
11454 * @author Vova Feldman (@svovaf)
11455 * @since 1.0.4
11456 *
11457 * @return bool
11458 */
11459 function is_free_plan() {
11460 if ( ! $this->is_registered() ) {
11461 return true;
11462 }
11463
11464 if ( ! $this->has_paid_plan() ) {
11465 return true;
11466 }
11467
11468 return (
11469 'free' === $this->get_plan_name() ||
11470 ! $this->has_features_enabled_license()
11471 );
11472 }
11473
11474 /**
11475 * @author Vova Feldman (@svovaf)
11476 * @since 1.0.5
11477 *
11478 * @return bool
11479 */
11480 function _has_premium_license() {
11481 $this->_logger->entrance();
11482
11483 $premium_license = $this->_get_available_premium_license();
11484
11485 return ( false !== $premium_license );
11486 }
11487
11488 /**
11489 * Check if user has any licenses associated with the plugin (including expired or blocking).
11490 *
11491 * @author Vova Feldman (@svovaf)
11492 * @since 1.1.7.3
11493 *
11494 * @param bool $including_foreign
11495 *
11496 * @return bool
11497 */
11498 function has_any_license( $including_foreign = true ) {
11499 if ( ! is_array( $this->_licenses ) || 0 === count( $this->_licenses ) ) {
11500 return false;
11501 }
11502
11503 if ( $including_foreign ) {
11504 return true;
11505 }
11506
11507 foreach ( $this->_licenses as $license ) {
11508 if ( $this->_user->id == $license->user_id ) {
11509 return true;
11510 }
11511 }
11512
11513 return false;
11514 }
11515
11516 /**
11517 * @author Vova Feldman (@svovaf)
11518 * @since 1.0.5
11519 *
11520 * @param bool|null $is_localhost
11521 *
11522 * @return FS_Plugin_License|false
11523 */
11524 function _get_available_premium_license( $is_localhost = null ) {
11525 $this->_logger->entrance();
11526
11527 $licenses = $this->get_available_premium_licenses( $is_localhost );
11528 if ( ! empty( $licenses ) ) {
11529 return $licenses[0];
11530 }
11531
11532 return false;
11533 }
11534
11535 /**
11536 * @author Vova Feldman (@svovaf)
11537 * @since 1.0.5
11538 *
11539 * @param bool|null $is_localhost
11540 *
11541 * @return FS_Plugin_License[]
11542 */
11543 function get_available_premium_licenses( $is_localhost = null ) {
11544 $this->_logger->entrance();
11545
11546 $licenses = array();
11547 if ( ! $this->has_paid_plan() ) {
11548 return $licenses;
11549 }
11550
11551 if ( is_array( $this->_licenses ) ) {
11552 foreach ( $this->_licenses as $license ) {
11553 if ( ! $license->can_activate( $is_localhost ) ) {
11554 continue;
11555 }
11556
11557 $licenses[] = $license;
11558 }
11559 }
11560
11561 return $licenses;
11562 }
11563
11564 /**
11565 * Sync local plugin plans with remote server.
11566 *
11567 * 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).
11568 *
11569 * @author Vova Feldman (@svovaf)
11570 * @since 1.0.5
11571 *
11572 * @return FS_Plugin_Plan[]|object
11573 */
11574 function _sync_plans() {
11575 $plans = $this->_fetch_plugin_plans();
11576
11577 if ( $this->is_array_instanceof( $plans, 'FS_Plugin_Plan' ) ) {
11578 $plans_map = array();
11579 foreach ( $plans as $plan ) {
11580 $plans_map[ $plan->id ] = true;
11581 }
11582
11583 $plans_ids_to_keep = $this->get_plans_ids_associated_with_installs();
11584
11585 foreach ( $plans_ids_to_keep as $plan_id ) {
11586 if ( isset( $plans_map[ $plan_id ] ) ) {
11587 continue;
11588 }
11589
11590 $missing_plan = self::_get_plan_by_id( $plan_id, false );
11591
11592 if ( is_object( $missing_plan ) ) {
11593 $plans[] = $missing_plan;
11594 }
11595 }
11596
11597 $this->_plans = $plans;
11598 $this->_store_plans();
11599 }
11600
11601 $this->do_action( 'after_plans_sync', $plans );
11602
11603 return $this->_plans;
11604 }
11605
11606 /**
11607 * Check if specified plan exists locally. If not, fetch it and store it.
11608 *
11609 * @author Vova Feldman (@svovaf)
11610 * @since 2.0.0
11611 *
11612 * @param number $plan_id
11613 *
11614 * @return \FS_Plugin_Plan|object The plan entity or the API error object on failure.
11615 */
11616 private function sync_plan_if_not_exist( $plan_id ) {
11617 $plan = self::_get_plan_by_id( $plan_id );
11618
11619 if ( is_object( $plan ) ) {
11620 // Plan already exists.
11621 return $plan;
11622 }
11623
11624 $plan = $this->fetch_plan_by_id( $plan_id );
11625
11626 if ( $plan instanceof FS_Plugin_Plan ) {
11627 $this->_plans[] = $plan;
11628 $this->_store_plans();
11629
11630 return $plan;
11631 }
11632
11633 return $plan;
11634 }
11635
11636 /**
11637 * Check if specified license exists locally. If not, fetch it and store it.
11638 *
11639 * @author Vova Feldman (@svovaf)
11640 * @since 2.0.0
11641 *
11642 * @param number $license_id
11643 * @param string $license_key
11644 *
11645 * @return \FS_Plugin_Plan|object The plan entity or the API error object on failure.
11646 */
11647 private function sync_license_if_not_exist( $license_id, $license_key ) {
11648 $license = $this->_get_license_by_id( $license_id );
11649
11650 if ( is_object( $license ) ) {
11651 // License already exists.
11652 return $license;
11653 }
11654
11655 $license = $this->fetch_license_by_key( $license_id, $license_key );
11656
11657 if ( $license instanceof FS_Plugin_License ) {
11658 $this->_licenses[] = $license;
11659
11660 $this->set_license( $license );
11661
11662 $this->_store_licenses();
11663
11664 return $license;
11665 }
11666
11667 return $license;
11668 }
11669
11670 /**
11671 * Get a collection of unique plan IDs that are associated with any installs in the network.
11672 *
11673 * @author Leo Fajardo (@leorw)
11674 * @since 2.0.0
11675 *
11676 * @return number[]
11677 */
11678 private function get_plans_ids_associated_with_installs() {
11679 if ( ! is_multisite() ) {
11680 if ( ! is_object( $this->_site ) ||
11681 ! FS_Plugin_Plan::is_valid_id( $this->_site->plan_id )
11682 ) {
11683 return array();
11684 }
11685
11686 return array( $this->_site->plan_id );
11687 }
11688
11689 $plan_ids = array();
11690 $sites = self::get_sites();
11691 foreach ( $sites as $site ) {
11692 $blog_id = self::get_site_blog_id( $site );
11693 $install = $this->get_install_by_blog_id( $blog_id );
11694
11695 if ( ! is_object( $install ) ||
11696 ! FS_Plugin_Plan::is_valid_id( $install->plan_id )
11697 ) {
11698 continue;
11699 }
11700
11701 $plan_ids[ $install->plan_id ] = true;
11702 }
11703
11704 return array_keys( $plan_ids );
11705 }
11706
11707 /**
11708 * Get a collection of unique license IDs that are associated with any installs in the network.
11709 *
11710 * @author Leo Fajardo (@leorw)
11711 * @since 2.0.0
11712 *
11713 * @return number[]
11714 */
11715 private function get_license_ids_associated_with_installs() {
11716 if ( ! $this->_is_network_active ) {
11717 if ( ! is_object( $this->_site ) ||
11718 ! FS_Plugin_License::is_valid_id( $this->_site->license_id )
11719 ) {
11720 return array();
11721 }
11722
11723 return array( $this->_site->license_id );
11724 }
11725
11726 $license_ids = array();
11727 $sites = self::get_sites();
11728 foreach ( $sites as $site ) {
11729 $blog_id = self::get_site_blog_id( $site );
11730 $install = $this->get_install_by_blog_id( $blog_id );
11731
11732 if ( ! is_object( $install ) ||
11733 ! FS_Plugin_License::is_valid_id( $install->license_id )
11734 ) {
11735 continue;
11736 }
11737
11738 $license_ids[ $install->license_id ] = true;
11739 }
11740
11741 return array_keys( $license_ids );
11742 }
11743
11744 /**
11745 * @author Vova Feldman (@svovaf)
11746 * @since 1.0.5
11747 *
11748 * @param number $id
11749 *
11750 * @return FS_Plugin_Plan|false
11751 */
11752 function _get_plan_by_id( $id, $allow_sync = true ) {
11753 $this->_logger->entrance();
11754
11755 if ( $allow_sync && ( ! is_array( $this->_plans ) || 0 === count( $this->_plans ) ) ) {
11756 $this->_sync_plans();
11757 }
11758
11759 foreach ( $this->_plans as $plan ) {
11760 if ( $id == $plan->id ) {
11761 return $plan;
11762 }
11763 }
11764
11765 return false;
11766 }
11767
11768 /**
11769 * @author Vova Feldman (@svovaf)
11770 * @since 1.1.8.1
11771 *
11772 * @param string $name
11773 *
11774 * @return FS_Plugin_Plan|false
11775 */
11776 private function get_plan_by_name( $name ) {
11777 $this->_logger->entrance();
11778
11779 if ( ! is_array( $this->_plans ) || 0 === count( $this->_plans ) ) {
11780 $this->_sync_plans();
11781 }
11782
11783 foreach ( $this->_plans as $plan ) {
11784 if ( $name == $plan->name ) {
11785 return $plan;
11786 }
11787 }
11788
11789 return false;
11790 }
11791
11792 /**
11793 * Sync local licenses with remote server.
11794 *
11795 * @author Vova Feldman (@svovaf)
11796 * @since 1.0.6
11797 *
11798 * @param number|bool $site_license_id
11799 * @param number|null $blog_id
11800 *
11801 * @return FS_Plugin_License[]|object
11802 */
11803 function _sync_licenses( $site_license_id = false, $blog_id = null ) {
11804 $this->_logger->entrance();
11805
11806 $is_network_admin = fs_is_network_admin();
11807
11808 if ( $is_network_admin && is_null( $blog_id ) ) {
11809 $all_licenses = self::get_all_licenses( $this->_module_id );
11810 } else {
11811 $all_licenses = $this->get_user_licenses( $this->_user->id );
11812 }
11813
11814 $foreign_licenses = $this->get_foreign_licenses_info( $all_licenses, $site_license_id );
11815
11816 $all_licenses_map = array();
11817 foreach ( $all_licenses as $license ) {
11818 $all_licenses_map[ $license->id ] = true;
11819 }
11820
11821 $licenses = $this->_fetch_licenses( false, $site_license_id, $foreign_licenses, $blog_id );
11822
11823 if ( $this->is_array_instanceof( $licenses, 'FS_Plugin_License' ) ) {
11824 $licenses_map = array();
11825 foreach ( $licenses as $license ) {
11826 $licenses_map[ $license->id ] = true;
11827 }
11828
11829 // $license_ids_to_keep = $this->get_license_ids_associated_with_installs();
11830 // foreach ( $license_ids_to_keep as $license_id ) {
11831 // if ( isset( $licenses_map[ $license_id ] ) ) {
11832 // continue;
11833 // }
11834 //
11835 // $missing_license = self::_get_license_by_id( $license_id, false );
11836 // if ( is_object( $missing_license ) ) {
11837 // $licenses[] = $missing_license;
11838 // $licenses_map[ $missing_license->id ] = true;
11839 // }
11840 // }
11841
11842 $user_license_ids = $this->get_user_linked_license_ids( $this->_user->id );
11843
11844 foreach ( $user_license_ids as $key => $license_id ) {
11845 if ( ! isset( $licenses_map[ $license_id ] ) ) {
11846 // Remove access to licenses that no longer exist.
11847 unset( $user_license_ids[ $key ] );
11848 }
11849 }
11850
11851 if ( ! empty( $user_license_ids ) ) {
11852 foreach ( $licenses_map as $license_id => $value ) {
11853 if ( ! isset( $all_licenses_map[ $license_id ] ) ) {
11854 // Associate new licenses with the user who triggered the license syncing.
11855 $user_license_ids[] = $license_id;
11856 }
11857 }
11858
11859 $user_license_ids = array_unique( $user_license_ids );
11860 } else {
11861 $user_license_ids = array_keys( $licenses_map );
11862 }
11863
11864 if ( ! $is_network_admin || ! is_null( $blog_id ) ) {
11865 $user_licenses = array();
11866 foreach ( $licenses as $license ) {
11867 if ( ! in_array( $license->id, $user_license_ids ) ) {
11868 continue;
11869 }
11870
11871 $user_licenses[] = $license;
11872 }
11873
11874 $this->_licenses = $user_licenses;
11875 } else {
11876 $this->_licenses = $licenses;
11877 }
11878
11879 $this->set_user_linked_license_ids( $this->_user->id, $user_license_ids );
11880
11881 $this->_store_licenses( true, $this->_module_id, $licenses );
11882 }
11883
11884 // Update current license.
11885 if ( is_object( $this->_license ) ) {
11886 $license = $this->_get_license_by_id( $this->_license->id );
11887
11888 if ( is_object( $license ) ) {
11889 /**
11890 * `$license` can be `false` in case a user change action has just been completed and this method
11891 * has synced the `$this->_licenses` collection for the new user. In this case, the
11892 * `$this->_licenses` collection may have only the newly activated license that is associated with
11893 * the new user. `set_license` will eventually be called in the same request by the logic that
11894 * follows outside this method which will detect that the install's license has been updated, and
11895 * then `_update_site_license` will be called which in turn will call `set_license`.
11896 *
11897 * @author Leo Fajardo (@leorw)
11898 * @since 2.3.2
11899 */
11900 $this->set_license( $license );
11901 }
11902 }
11903
11904 return $this->_licenses;
11905 }
11906
11907 /**
11908 * @author Vova Feldman (@svovaf)
11909 * @since 1.0.5
11910 *
11911 * @param number $id
11912 * @param bool $sync_licenses
11913 *
11914 * @return FS_Plugin_License|false
11915 */
11916 function _get_license_by_id( $id, $sync_licenses = true ) {
11917 $this->_logger->entrance();
11918
11919 if ( ! FS_Plugin_License::is_valid_id( $id ) ) {
11920 return false;
11921 }
11922
11923 /**
11924 * When running from the network level admin and opted-in from the network,
11925 * check if the license exists in the network user licenses collection.
11926 *
11927 * @author Vova Feldman (@svovaf)
11928 * @since 2.0.0
11929 */
11930 if ( fs_is_network_admin() &&
11931 $this->is_network_registered() &&
11932 ( ! is_object( $this->_user ) || $this->_storage->network_user_id != $this->_user->id )
11933 ) {
11934 $licenses = $this->get_user_licenses( $this->_storage->network_user_id );
11935
11936 foreach ( $licenses as $license ) {
11937 if ( $id == $license->id ) {
11938 return $license;
11939 }
11940 }
11941 }
11942
11943 if ( ! $this->has_any_license() && $sync_licenses ) {
11944 $this->_sync_licenses( $id );
11945 }
11946
11947 if ( is_array( $this->_licenses ) ) {
11948 foreach ( $this->_licenses as $license ) {
11949 if ( $id == $license->id ) {
11950 return $license;
11951 }
11952 }
11953 }
11954
11955 return false;
11956 }
11957
11958 /**
11959 * 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.
11960 *
11961 * @author Vova Feldman (@svovaf)
11962 * @since 2.0.0
11963 *
11964 * @param number $id
11965 *
11966 * @return FS_Plugin_License
11967 */
11968 private function get_license_by_id( $id ) {
11969 $licenses = self::get_all_licenses( $this->_module_id );
11970
11971 if ( is_array( $licenses ) && ! empty( $licenses ) ) {
11972 foreach ( $licenses as $license ) {
11973 if ( $id == $license->id ) {
11974 return $license;
11975 }
11976 }
11977 }
11978
11979 return null;
11980 }
11981
11982 /**
11983 * Synchronize the site's context license by fetching the license form the API and updating the local data with it.
11984 *
11985 * @author Vova Feldman (@svovaf)
11986 * @since 2.0.0
11987 *
11988 * @return \FS_Plugin_License|mixed
11989 */
11990 private function sync_site_license() {
11991 $api = $this->get_api_user_scope();
11992
11993 $result = $api->get( "/licenses/{$this->_license->id}.json?license_key=" . urlencode( $this->_license->secret_key ), true );
11994
11995 if ( ! $this->is_api_result_entity( $result ) ) {
11996 return $result;
11997 }
11998
11999 $license = $this->_update_site_license( new FS_Plugin_License( $result ) );
12000 $this->_store_licenses();
12001
12002 return $license;
12003 }
12004
12005 /**
12006 * Get all user's available licenses for the current module.
12007 *
12008 * @author Vova Feldman (@svovaf)
12009 * @since 2.0.0
12010 *
12011 * @param number $user_id
12012 *
12013 * @return FS_Plugin_License[]
12014 */
12015 private function get_user_licenses( $user_id ) {
12016 $all_licenses = self::get_all_licenses( $this->_module_id );
12017 if ( empty( $all_licenses ) ) {
12018 return array();
12019 }
12020
12021 $user_license_ids = $this->get_user_linked_license_ids( $user_id );
12022 if ( empty( $user_license_ids ) ) {
12023 return array();
12024 }
12025
12026 $licenses = array();
12027 foreach ( $all_licenses as $license ) {
12028 if ( in_array( $license->id, $user_license_ids ) ) {
12029 $licenses[] = $license;
12030 }
12031 }
12032
12033 return $licenses;
12034 }
12035
12036 /**
12037 * Checks if the context license is network activated except on the given blog ID.
12038 *
12039 * @author Vova Feldman (@svovaf)
12040 * @since 2.0.0
12041 *
12042 * @param int $except_blog_id
12043 *
12044 * @return bool
12045 */
12046 private function is_license_network_active( $except_blog_id = 0 ) {
12047 $this->_logger->entrance();
12048
12049 if ( ! is_object( $this->_license ) ) {
12050 return false;
12051 }
12052
12053 $sites = self::get_sites();
12054
12055 if ( $this->_license->total_activations() < ( count( $sites ) - 1 ) ) {
12056 // There are more sites than the number of activations, so license cannot be network activated.
12057 return false;
12058 }
12059
12060 foreach ( $sites as $site ) {
12061 $blog_id = self::get_site_blog_id( $site );
12062
12063 if ( $except_blog_id == $blog_id ) {
12064 // Skip excluded blog.
12065 continue;
12066 }
12067
12068 $install = $this->get_install_by_blog_id( $blog_id );
12069
12070 if ( is_object( $install ) && $install->license_id != $this->_license->id ) {
12071 return false;
12072 }
12073 }
12074
12075 return true;
12076 }
12077
12078 /**
12079 * 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.
12080 *
12081 * Notice: On success, this method will also update the license activations counters (without updating the license in the storage).
12082 *
12083 * @author Vova Feldman (@svovaf)
12084 * @since 2.0.0
12085 *
12086 * @param \FS_User $user
12087 * @param \FS_Plugin_License $license
12088 *
12089 * @return bool
12090 */
12091 private function try_activate_license_on_network( FS_User $user, FS_Plugin_License $license ) {
12092 $this->_logger->entrance();
12093
12094 $result = $this->can_activate_license_on_network( $license );
12095
12096 if ( false === $result ) {
12097 return false;
12098 }
12099
12100 $installs_without_license = $result['installs'];
12101 if ( ! empty( $installs_without_license ) ) {
12102 $this->activate_license_on_many_installs( $user, $license->secret_key, $installs_without_license );
12103 }
12104
12105 $disconnected_site_ids = $result['sites'];
12106 if ( ! empty( $disconnected_site_ids ) ) {
12107 $this->activate_license_on_many_sites( $user, $license->secret_key, $disconnected_site_ids );
12108 }
12109
12110 $this->link_license_2_user( $license->id, $user->id );
12111
12112 // Sync license after activations.
12113 $license->activated += $result['production_count'];
12114 $license->activated_local += $result['localhost_count'];
12115
12116 // $this->_store_licenses()
12117
12118 return true;
12119 }
12120
12121 /**
12122 * Checks if the given license can be activated on the whole network.
12123 *
12124 * @author Vova Feldman (@svovaf)
12125 * @since 2.0.0
12126 *
12127 * @param \FS_Plugin_License $license
12128 *
12129 * @return false|array {
12130 * @type array[int]FS_Site $installs Blog ID to install map.
12131 * @type int[] $sites Non-connected blog IDs.
12132 * @type int $production_count Production sites count.
12133 * @type int $localhost_count Production sites count.
12134 * }
12135 */
12136 private function can_activate_license_on_network( FS_Plugin_License $license ) {
12137 $sites = self::get_sites();
12138
12139 $production_count = 0;
12140 $localhost_count = 0;
12141
12142 $installs_without_license = array();
12143 $disconnected_site_ids = array();
12144
12145 foreach ( $sites as $site ) {
12146 $blog_id = self::get_site_blog_id( $site );
12147 $install = $this->get_install_by_blog_id( $blog_id );
12148
12149 if ( is_object( $install ) ) {
12150 if ( FS_Plugin_License::is_valid_id( $install->license_id ) ) {
12151 // License already activated on the install.
12152 continue;
12153 }
12154
12155 $url = $install->url;
12156
12157 $installs_without_license[ $blog_id ] = $install;
12158 } else {
12159 $url = is_object( $site ) ?
12160 $site->siteurl :
12161 self::get_unfiltered_site_url( $blog_id );
12162
12163 $disconnected_site_ids[] = $blog_id;
12164 }
12165
12166 if ( FS_Site::is_localhost_by_address( $url ) ) {
12167 $localhost_count ++;
12168 } else {
12169 $production_count ++;
12170 }
12171 }
12172
12173 if ( ! $license->can_activate_bulk( $production_count, $localhost_count ) ) {
12174 return false;
12175 }
12176
12177 return array(
12178 'installs' => $installs_without_license,
12179 'sites' => $disconnected_site_ids,
12180 'production_count' => $production_count,
12181 'localhost_count' => $localhost_count,
12182 );
12183 }
12184
12185 /**
12186 * Activate a given license on a collection of installs.
12187 *
12188 * @author Vova Feldman (@svovaf)
12189 * @since 2.0.0
12190 *
12191 * @param \FS_User $user
12192 * @param string $license_key
12193 * @param array $blog_2_install_map {
12194 * @key int Blog ID.
12195 * @value FS_Site Blog's associated install.
12196 * }
12197 *
12198 * @return mixed|true
12199 */
12200 private function activate_license_on_many_installs(
12201 FS_User $user,
12202 $license_key,
12203 array $blog_2_install_map
12204 ) {
12205 $params = array(
12206 array( 'license_key' => $this->apply_filters( 'license_key', $license_key ) )
12207 );
12208
12209 $install_2_blog_map = array();
12210 foreach ( $blog_2_install_map as $blog_id => $install ) {
12211 $params[] = array( 'id' => $install->id, 'url' => $install->url );
12212
12213 $install_2_blog_map[ $install->id ] = $blog_id;
12214 }
12215
12216 $result = $this->get_api_user_scope_by_user( $user )->call(
12217 "plugins/{$this->_plugin->id}/installs.json",
12218 'PUT',
12219 $params
12220 );
12221
12222 if ( ! $this->is_api_result_object( $result, 'installs' ) ) {
12223 return $result;
12224 }
12225
12226 foreach ( $result->installs as $r_install ) {
12227 $install = new FS_Site( $r_install );
12228 $install->is_disconnected = false;
12229
12230 // Update install.
12231 $this->_store_site(
12232 true,
12233 $install_2_blog_map[ $r_install->id ],
12234 $install
12235 );
12236 }
12237
12238 return true;
12239 }
12240
12241 /**
12242 * Activate a given license on a collection of blogs/sites that are not yet opted-in.
12243 *
12244 * @author Vova Feldman (@svovaf)
12245 * @since 2.3.1
12246 *
12247 * @param \FS_User $user
12248 * @param string $license_key
12249 *
12250 * @return true|mixed True if successful, otherwise, the API result.
12251 */
12252 private function activate_license_on_site( FS_User $user, $license_key ) {
12253 return $this->activate_license_on_many_sites( $user, $license_key );
12254 }
12255
12256 /**
12257 * Activate a given license on a collection of blogs/sites that are not yet opted-in.
12258 *
12259 * @author Vova Feldman (@svovaf)
12260 * @since 2.0.0
12261 *
12262 * @param \FS_User $user
12263 * @param string $license_key
12264 * @param int[] $site_ids
12265 *
12266 * @return true|mixed True if successful, otherwise, the API result.
12267 */
12268 private function activate_license_on_many_sites(
12269 FS_User $user,
12270 $license_key,
12271 array $site_ids = array()
12272 ) {
12273 $sites = array();
12274 foreach ( $site_ids as $site_id ) {
12275 $sites[] = $this->get_site_info( array( 'blog_id' => $site_id ) );
12276 }
12277
12278 // Install the plugin.
12279 $result = $this->create_installs_with_user(
12280 $user,
12281 $license_key,
12282 false,
12283 $sites,
12284 false,
12285 true
12286 );
12287
12288 if ( ! $this->is_api_result_entity( $result ) &&
12289 ! $this->is_api_result_object( $result, 'installs' )
12290 ) {
12291 return $result;
12292 }
12293
12294 $installs = array();
12295
12296 if ( $this->is_api_result_entity( $result ) ) {
12297 $install = new FS_Site( $result );
12298
12299 $this->_user = $user;
12300
12301 $this->_store_site( true, null, $install );
12302
12303 $this->_site = $install;
12304
12305 $this->reset_anonymous_mode();
12306 } else {
12307 foreach ( $result->installs as $install ) {
12308 $installs[] = new FS_Site( $install );
12309 }
12310
12311 // Map site addresses to their blog IDs.
12312 $address_to_blog_map = $this->get_address_to_blog_map();
12313
12314 $first_blog_id = null;
12315
12316 foreach ( $installs as $install ) {
12317 $address = trailingslashit( fs_strip_url_protocol( $install->url ) );
12318 $blog_id = $address_to_blog_map[ $address ];
12319
12320 $this->_store_site( true, $blog_id, $install );
12321
12322 $this->reset_anonymous_mode( $blog_id );
12323
12324 if ( is_null( $first_blog_id ) ) {
12325 $first_blog_id = $blog_id;
12326 }
12327 }
12328
12329 if ( ! FS_Site::is_valid_id( $this->_storage->network_install_blog_id ) ) {
12330 $this->_storage->network_install_blog_id = $first_blog_id;
12331 }
12332 }
12333
12334 return true;
12335 }
12336
12337 /**
12338 * Sync site's license with user licenses.
12339 *
12340 * @author Vova Feldman (@svovaf)
12341 * @since 1.0.6
12342 *
12343 * @param FS_Plugin_License|null $new_license
12344 *
12345 * @return FS_Plugin_License|null
12346 */
12347 function _update_site_license( $new_license ) {
12348 $this->_logger->entrance();
12349
12350 /**
12351 * In case this call will be removed in the future, the `_sync_licenses()` method needs to be updated
12352 * accordingly so that it will also handle the case when an ownership change is done via license
12353 * activation.
12354 *
12355 * @author Leo Fajardo (@leorw)
12356 * @since 2.3.2
12357 */
12358 $this->set_license( $new_license );
12359
12360 if ( ! is_object( $new_license ) ) {
12361 $this->_site->license_id = null;
12362 $this->_sync_site_subscription( null );
12363
12364 return $this->_license;
12365 }
12366
12367 $this->_site->license_id = $this->_license->id;
12368
12369 if ( ! is_array( $this->_licenses ) ) {
12370 $this->_licenses = array();
12371 }
12372
12373 $is_license_found = false;
12374 for ( $i = 0, $len = count( $this->_licenses ); $i < $len; $i ++ ) {
12375 if ( $new_license->id == $this->_licenses[ $i ]->id ) {
12376 $this->_licenses[ $i ] = $new_license;
12377
12378 $is_license_found = true;
12379 break;
12380 }
12381 }
12382
12383 // If new license just append.
12384 if ( ! $is_license_found ) {
12385 $this->_licenses[] = $new_license;
12386 }
12387
12388 $this->_sync_site_subscription( $new_license );
12389
12390 return $this->_license;
12391 }
12392
12393 /**
12394 * @author Vova Feldman (@svovaf)
12395 * @since 2.3.1
12396 *
12397 * @param \FS_Plugin_License $license
12398 */
12399 private function set_license( $license = null ) {
12400 $this->_license = $license;
12401
12402 $this->maybe_update_whitelabel_flag( $license );
12403 }
12404
12405 /**
12406 * @author Leo Fajardo (@leorw)
12407 * @since 2.3.1
12408 *
12409 * @param FS_Plugin_License $license
12410 */
12411 private function maybe_update_whitelabel_flag( $license ) {
12412 $is_whitelabeled = isset( $this->_storage->is_whitelabeled ) ?
12413 $this->_storage->is_whitelabeled :
12414 false;
12415
12416 if ( is_object( $license ) ) {
12417 $license_user = self::_get_user_by_id( $license->user_id );
12418
12419 if ( ! is_object( $license_user ) ) {
12420 // If foreign license, do not update the `is_whitelabeled` flag.
12421 return;
12422 }
12423
12424 if ( $this->is_addon() ) {
12425 /**
12426 * Store the last license data to the parent's storage since it's needed only when showing the
12427 * "Start Debug" dialog which is triggered from the "Account" page. This way, there's no need to
12428 * iterate over the add-ons just to get the last license data.
12429 */
12430 $this->get_parent_instance()->store_last_activated_license_data( $license, $license_user );
12431 } else {
12432 $this->store_last_activated_license_data( $license );
12433 }
12434
12435 if ( $license->is_whitelabeled ) {
12436 // Activated a developer license, data should be hidden.
12437 $is_whitelabeled = true;
12438 } else if ( $this->is_registered() && $this->_user->id == $license->user_id ) {
12439 // The account owner activated a regular license key, no need to hide the data.
12440 $is_whitelabeled = false;
12441 }
12442 }
12443
12444 $this->_storage->is_whitelabeled = $is_whitelabeled;
12445
12446 // Reset the whitelabeled status after update.
12447 $this->is_whitelabeled = null;
12448 if ( $this->is_addon() ) {
12449 $parent_fs = $this->get_parent_instance();
12450
12451 if ( is_object( $parent_fs ) ) {
12452 $parent_fs->is_whitelabeled = null;
12453 }
12454 }
12455 }
12456
12457 /**
12458 * @author Leo Fajardo (@leorw)
12459 * @since 2.3.1
12460 *
12461 * @param FS_Plugin_License $license
12462 * @param FS_User $license_user
12463 */
12464 private function store_last_activated_license_data( FS_Plugin_License $license, $license_user = null ) {
12465 if ( ! is_object( $license_user ) ) {
12466 $this->_storage->last_license_key = md5( $license->secret_key );
12467 $this->_storage->last_license_user_id = null;
12468 } else {
12469 $this->_storage->last_license_user_key = md5( $license_user->secret_key );
12470 $this->_storage->last_license_user_id = $license_user->id;
12471 }
12472 }
12473
12474 /**
12475 * @author Leo Fajardo (@leorw)
12476 * @since 2.3.1
12477 *
12478 * @param bool $ignore_data_debug_mode
12479 *
12480 * @return bool
12481 */
12482 function is_whitelabeled_by_flag( $ignore_data_debug_mode = false ) {
12483 if ( true !== $this->_storage->is_whitelabeled ) {
12484 return false;
12485 } else if ( $ignore_data_debug_mode ) {
12486 return true;
12487 }
12488
12489 $fs = $this->is_addon() ?
12490 $this->get_parent_instance() :
12491 $this;
12492
12493 return ! $fs->is_data_debug_mode();
12494 }
12495
12496 /**
12497 * @author Leo Fajardo (@leorw)
12498 * @since 2.3.1
12499 *
12500 * @return number
12501 */
12502 function get_last_license_user_id() {
12503 return ( FS_User::is_valid_id( $this->_storage->last_license_user_id ) ) ?
12504 $this->_storage->last_license_user_id :
12505 null;
12506 }
12507
12508 /**
12509 * @author Leo Fajardo (@leorw)
12510 * @since 2.3.1
12511 *
12512 * @param int $blog_id
12513 * @param bool $ignore_data_debug_mode
12514 *
12515 * @return bool
12516 */
12517 function is_whitelabeled( $ignore_data_debug_mode = false, $blog_id = null ) {
12518 if ( ! is_null( $blog_id ) ) {
12519 $this->switch_to_blog( $blog_id );
12520 }
12521
12522 if ( ! is_null( $this->is_whitelabeled ) ) {
12523 $is_whitelabeled = $this->is_whitelabeled;
12524 } else {
12525 $is_whitelabeled = false;
12526
12527 $is_whitelabeled_flag = $this->is_whitelabeled_by_flag( true );
12528
12529 if ( ! $this->has_addons() ) {
12530 $is_whitelabeled = $is_whitelabeled_flag;
12531 } else if ( $is_whitelabeled_flag ) {
12532 $is_whitelabeled = true;
12533 } else {
12534 if ( $this->is_registered() || $this->is_premium() ) {
12535 $addon_ids = $this->get_updated_account_addons();
12536 } else {
12537 $addons = self::get_all_addons();
12538
12539 $plugin_addons = isset( $addons[ $this->_plugin->id ] ) ?
12540 $addons[ $this->_plugin->id ] :
12541 array();
12542
12543 $addon_ids = array();
12544 foreach ( $plugin_addons as $addon ) {
12545 $addon_ids[] = $addon->id;
12546 }
12547 }
12548
12549 $installed_addons = $this->get_installed_addons();
12550 foreach ( $installed_addons as $fs_addon ) {
12551 $addon_ids[] = $fs_addon->get_id();
12552 }
12553
12554 if ( ! empty( $addon_ids ) ) {
12555 $addon_ids = array_unique( $addon_ids );
12556
12557 $is_network_level = (
12558 fs_is_network_admin() &&
12559 $this->is_network_active()
12560 );
12561
12562 foreach ( $addon_ids as $addon_id ) {
12563 $addon = $this->get_addon( $addon_id );
12564
12565 if ( ! is_object( $addon ) ) {
12566 continue;
12567 }
12568
12569 $addon_storage = FS_Storage::instance( WP_FS__MODULE_TYPE_PLUGIN, $addon->slug );
12570 $fs_addon = $this->is_addon_activated( $addon_id ) ?
12571 self::get_addon_instance( $addon_id ) :
12572 null;
12573
12574 $was_addon_network_activated = false;
12575
12576 if ( is_object( $fs_addon ) ) {
12577 $was_addon_network_activated = $fs_addon->is_network_active();
12578 } else if ( $is_network_level ) {
12579 $was_addon_network_activated = $addon_storage->get( 'was_plugin_loaded', false, true );
12580 }
12581
12582 $network_delegated_connection = (
12583 $was_addon_network_activated &&
12584 $addon_storage->get( 'is_delegated_connection', false, true )
12585 );
12586
12587 if (
12588 $is_network_level &&
12589 ( ! $was_addon_network_activated || $network_delegated_connection )
12590 ) {
12591 $sites = self::get_sites();
12592
12593 /**
12594 * If in network admin area and the add-on was not network-activated or network-activated
12595 * and network-delegated, find any add-on whose is_whitelabeled flag is true.
12596 */
12597 foreach ( $sites as $site ) {
12598 $site_info = $this->get_site_info( $site );
12599
12600 if ( $addon_storage->get( 'is_whitelabeled', false, $site_info['blog_id'] ) ) {
12601 $is_whitelabeled = true;
12602 break;
12603 }
12604 }
12605
12606 if ( $is_whitelabeled ) {
12607 break;
12608 }
12609 } else {
12610 /**
12611 * This will be executed when any of the following is met:
12612 * 1. Add-on was network-activated, not network-delegated, and in network admin area.
12613 * 2. Add-on was network-activated, network-delegated, and in site admin area.
12614 * 3. Add-on was not network-activated and in site admin area.
12615 */
12616 if ( true === $addon_storage->is_whitelabeled ) {
12617 $is_whitelabeled = true;
12618 break;
12619 }
12620 }
12621 }
12622 }
12623 }
12624
12625 $this->is_whitelabeled = $is_whitelabeled;
12626
12627 if ( ! $is_whitelabeled || ! $this->is_data_debug_mode() ) {
12628 $this->_admin_notices->remove_sticky( 'data_debug_mode_enabled' );
12629 }
12630
12631 if ( ! is_null( $blog_id ) ) {
12632 $this->restore_current_blog();
12633 }
12634 }
12635
12636 return (
12637 $is_whitelabeled &&
12638 ( $ignore_data_debug_mode || ! $this->is_data_debug_mode() )
12639 );
12640 }
12641
12642 /**
12643 * Sync site's subscription.
12644 *
12645 * @author Vova Feldman (@svovaf)
12646 * @since 1.0.9
12647 *
12648 * @param FS_Plugin_License|null $license
12649 *
12650 * @return bool|\FS_Subscription
12651 */
12652 private function _sync_site_subscription( $license ) {
12653 if ( ! is_object( $license ) ) {
12654 $this->delete_unused_subscriptions();
12655
12656 return false;
12657 }
12658
12659 // Load subscription details if not lifetime.
12660 $subscription = $license->is_lifetime() ?
12661 false :
12662 $this->_fetch_site_license_subscription();
12663
12664 if ( is_object( $subscription ) && ! isset( $subscription->error ) ) {
12665 $this->store_subscription( $subscription );
12666 } else {
12667 $this->delete_unused_subscriptions();
12668 }
12669
12670 return $subscription;
12671 }
12672
12673 /**
12674 * @author Vova Feldman (@svovaf)
12675 * @since 1.0.6
12676 *
12677 * @return bool|\FS_Plugin_License
12678 */
12679 function _get_license() {
12680 if ( ! fs_is_network_admin() || is_object( $this->_license ) ) {
12681 return $this->_license;
12682 }
12683
12684 return $this->_get_available_premium_license();
12685 }
12686
12687 /**
12688 * @param number $license_id
12689 *
12690 * @return null|\FS_Subscription
12691 */
12692 function _get_subscription( $license_id ) {
12693 if ( ! isset( $this->_storage->subscriptions ) ||
12694 empty( $this->_storage->subscriptions )
12695 ) {
12696 return null;
12697 }
12698
12699 foreach ( fs_get_entities( $this->_storage->subscriptions, FS_Subscription::get_class_name() ) as $subscription ) {
12700 if ( $subscription->license_id == $license_id ) {
12701 return $subscription;
12702 }
12703 }
12704
12705 return null;
12706 }
12707
12708 /**
12709 * @author Leo Fajardo (@leorw)
12710 * @since 2.0.0
12711 *
12712 * @param FS_Subscription $subscription
12713 */
12714 function store_subscription( FS_Subscription $subscription ) {
12715 if ( ! isset( $this->_storage->subscriptions ) ) {
12716 $this->_storage->subscriptions = array();
12717 }
12718
12719 if ( empty( $this->_storage->subscriptions ) || ! is_multisite() ) {
12720 $this->_storage->subscriptions = array( $subscription );
12721
12722 return;
12723 }
12724
12725 $subscriptions = fs_get_entities( $this->_storage->subscriptions, FS_Subscription::get_class_name() );
12726
12727 $updated_subscription = false;
12728 foreach ( $subscriptions as $key => $existing_subscription ) {
12729 if ( $existing_subscription->id == $subscription->id ) {
12730 $subscriptions[ $key ] = $subscription;
12731 $updated_subscription = true;
12732 break;
12733 }
12734 }
12735
12736 if ( ! $updated_subscription ) {
12737 $subscriptions[] = $subscription;
12738 }
12739
12740 $this->_storage->subscriptions = $subscriptions;
12741 }
12742
12743 /**
12744 * @author Leo Fajardo (@leorw)
12745 * @since 2.0.0
12746 */
12747 function delete_unused_subscriptions() {
12748 if ( ! isset( $this->_storage->subscriptions ) ||
12749 empty( $this->_storage->subscriptions ) ||
12750 // Clean up only if there are already at least 3 subscriptions.
12751 ( count( $this->_storage->subscriptions ) < 3 )
12752 ) {
12753 return;
12754 }
12755
12756 if ( ! is_multisite() ) {
12757 // If not multisite, there should only be 1 subscription, so just clear the array.
12758 $this->_storage->subscriptions = array();
12759
12760 return;
12761 }
12762
12763 $subscriptions_to_keep_by_license_id_map = array();
12764 $sites = self::get_sites();
12765 foreach ( $sites as $site ) {
12766 $blog_id = self::get_site_blog_id( $site );
12767 $install = $this->get_install_by_blog_id( $blog_id );
12768
12769 if ( ! is_object( $install ) ||
12770 ! FS_Plugin_License::is_valid_id( $install->license_id )
12771 ) {
12772 continue;
12773 }
12774
12775 $subscriptions_to_keep_by_license_id_map[ $install->license_id ] = true;
12776 }
12777
12778 if ( empty( $subscriptions_to_keep_by_license_id_map ) ) {
12779 $this->_storage->subscriptions = array();
12780
12781 return;
12782 }
12783
12784 foreach ( $this->_storage->subscriptions as $key => $subscription ) {
12785 if ( ! isset( $subscriptions_to_keep_by_license_id_map[ $subscription->license_id ] ) ) {
12786 unset( $this->_storage->subscriptions[ $key ] );
12787 }
12788 }
12789 }
12790
12791 /**
12792 * @author Vova Feldman (@svovaf)
12793 * @since 1.0.2
12794 *
12795 * @param string $plan Plan name
12796 * @param bool $exact If true, looks for exact plan. If false, also check "higher" plans.
12797 *
12798 * @return bool
12799 */
12800 function is_plan( $plan, $exact = false ) {
12801 $this->_logger->entrance();
12802
12803 if ( ! $this->is_registered() ) {
12804 return false;
12805 }
12806
12807 $plan = strtolower( $plan );
12808
12809 $current_plan_name = $this->get_plan_name();
12810
12811 if ( $current_plan_name === $plan ) {
12812 // Exact plan.
12813 return true;
12814 } else if ( $exact ) {
12815 // Required exact, but plans are different.
12816 return false;
12817 }
12818
12819 $current_plan_order = - 1;
12820 $required_plan_order = PHP_INT_MAX;
12821 for ( $i = 0, $len = count( $this->_plans ); $i < $len; $i ++ ) {
12822 if ( $plan === $this->_plans[ $i ]->name ) {
12823 $required_plan_order = $i;
12824 } else if ( $current_plan_name === $this->_plans[ $i ]->name ) {
12825 $current_plan_order = $i;
12826 }
12827 }
12828
12829 return ( $current_plan_order > $required_plan_order );
12830 }
12831
12832 /**
12833 * Check if module has only one plan.
12834 *
12835 * @author Vova Feldman (@svovaf)
12836 * @since 1.2.1.7
12837 *
12838 * @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.
12839 *
12840 * @return bool
12841 */
12842 function is_single_plan( $double_check = false ) {
12843 $this->_logger->entrance();
12844
12845 if ( ! $this->is_registered() ||
12846 ! is_array( $this->_plans ) ||
12847 0 === count( $this->_plans )
12848 ) {
12849 return true;
12850 }
12851
12852 $has_free_plan = $this->has_free_plan();
12853
12854 if ( ! $has_free_plan && $double_check ) {
12855 foreach ( $this->_plans as $plan ) {
12856 if ( $plan->is_free() ) {
12857 $has_free_plan = true;
12858 break;
12859 }
12860 }
12861 }
12862
12863 return ( 1 === ( count( $this->_plans ) - ( $has_free_plan ? 1 : 0 ) ) );
12864 }
12865
12866 /**
12867 * Check if plan based on trial. If not in trial mode, should return false.
12868 *
12869 * @since 1.0.9
12870 *
12871 * @param string $plan Plan name
12872 * @param bool $exact If true, looks for exact plan. If false, also check "higher" plans.
12873 *
12874 * @return bool
12875 */
12876 function is_trial_plan( $plan, $exact = false ) {
12877 $this->_logger->entrance();
12878
12879 if ( ! $this->is_registered() ) {
12880 return false;
12881 }
12882
12883 if ( ! $this->is_trial() ) {
12884 return false;
12885 }
12886
12887 $trial_plan = $this->get_trial_plan();
12888
12889 if ( $trial_plan->name === $plan ) {
12890 // Exact plan.
12891 return true;
12892 } else if ( $exact ) {
12893 // Required exact, but plans are different.
12894 return false;
12895 }
12896
12897 $current_plan_order = - 1;
12898 $required_plan_order = - 1;
12899 for ( $i = 0, $len = count( $this->_plans ); $i < $len; $i ++ ) {
12900 if ( $plan === $this->_plans[ $i ]->name ) {
12901 $required_plan_order = $i;
12902 } else if ( $trial_plan->name === $this->_plans[ $i ]->name ) {
12903 $current_plan_order = $i;
12904 }
12905 }
12906
12907 return ( $current_plan_order > $required_plan_order );
12908 }
12909
12910 /**
12911 * Check if plugin has any paid plans.
12912 *
12913 * @author Vova Feldman (@svovaf)
12914 * @since 1.0.7
12915 *
12916 * @return bool
12917 */
12918 function has_paid_plan() {
12919 return $this->_has_paid_plans ||
12920 FS_Plan_Manager::instance()->has_paid_plan( $this->_plans );
12921 }
12922
12923 /**
12924 * Check if plugin has any plan with a trail.
12925 *
12926 * @author Vova Feldman (@svovaf)
12927 * @since 1.0.9
12928 *
12929 * @return bool
12930 */
12931 function has_trial_plan() {
12932 /**
12933 * @author Vova Feldman(@svovaf)
12934 * @since 1.2.1.5
12935 *
12936 * Allow setting a trial from the SDK without calling the API.
12937 * But, if the user did opt-in, continue using the real data from the API.
12938 */
12939 if ( $this->_trial_days >= 0 ) {
12940 return true;
12941 }
12942
12943 return $this->_storage->get( 'has_trial_plan', false );
12944 }
12945
12946 /**
12947 * Check if plugin has any free plan, or is it premium only.
12948 *
12949 * Note: If no plans configured, assume plugin is free.
12950 *
12951 * @author Vova Feldman (@svovaf)
12952 * @since 1.0.7
12953 *
12954 * @return bool
12955 */
12956 function has_free_plan() {
12957 return ! $this->is_only_premium();
12958 }
12959
12960 /**
12961 * Displays a license activation dialog box when the user clicks on the "Activate License"
12962 * or "Change License" link on the plugins
12963 * page.
12964 *
12965 * @author Leo Fajardo (@leorw)
12966 * @since 1.1.9
12967 */
12968 function _add_license_activation_dialog_box() {
12969 $vars = array(
12970 'id' => $this->_module_id,
12971 );
12972
12973 fs_require_template( 'forms/license-activation.php', $vars );
12974 fs_require_template( 'forms/resend-key.php', $vars );
12975 }
12976
12977 /**
12978 * Displays an email address update dialog box when the user clicks on the email address "Edit" button on the "Account" page.
12979 *
12980 * @author Leo Fajardo (@leorw)
12981 * @since 2.5.0
12982 */
12983 function _add_email_address_update_dialog_box() {
12984 $vars = array( 'id' => $this->_module_id );
12985
12986 fs_require_template( 'forms/email-address-update.php', $vars );
12987 }
12988
12989 /**
12990 * @author Leo Fajardo (@leorw)
12991 * @since 2.5.0
12992 */
12993 function _add_email_address_update_option() {
12994 if ( ! $this->should_handle_user_change() ) {
12995 return;
12996 }
12997
12998 // Add email address update AJAX handler.
12999 $this->add_ajax_action( 'update_email_address', array( &$this, '_email_address_update_ajax_handler' ) );
13000 }
13001
13002 /**
13003 * @author Leo Fajardo (@leorw)
13004 * @since 2.5.0
13005 */
13006 function _email_address_update_ajax_handler() {
13007 $this->check_ajax_referer( 'update_email_address' );
13008
13009 $new_email_address = fs_request_get( 'email_address' );
13010 $transfer_type = fs_request_get( 'transfer_type' );
13011
13012 $result = $this->update_email( $new_email_address );
13013
13014 if ( ! FS_Api::is_api_error( $result ) ) {
13015 self::shoot_ajax_success();
13016 }
13017
13018 $error = '';
13019
13020 if ( FS_Api::is_api_error_object( $result ) ) {
13021 switch ( $result->error->code ) {
13022 case 'user_exist':
13023 case 'account_verification_required':
13024 $error = array(
13025 'code' => 'change_ownership',
13026 'url' => $this->get_account_url( 'change_owner', array(
13027 'state' => 'init',
13028 'candidate_email' => $new_email_address,
13029 'transfer_type' => $transfer_type,
13030 ) ),
13031 );
13032
13033 break;
13034 }
13035 }
13036
13037 if ( empty( $error ) ) {
13038 $error = is_object( $result ) ?
13039 var_export( $result->error, true ) :
13040 $result;
13041 }
13042
13043 self::shoot_ajax_failure( $error );
13044 }
13045
13046 /**
13047 * Returns a collection of IDs of installs that are associated with the context product and its add-ons, and activated with foreign licenses.
13048 *
13049 * @author Leo Fajardo (@leorw)
13050 * @since 2.3.2
13051 *
13052 * @return number[]
13053 */
13054 function get_installs_ids_with_foreign_licenses() {
13055 $installs = array();
13056
13057 if (
13058 is_object( $this->_license ) &&
13059 $this->_site->user_id != $this->_license->user_id
13060 ) {
13061 $installs[] = $this->_site->id;
13062 }
13063
13064 /**
13065 * Also try to get foreign licenses for the context product's add-ons.
13066 */
13067 $installs_by_slug_map = $this->get_parent_and_addons_installs_info();
13068
13069 foreach ( $installs_by_slug_map as $slug => $install_info ) {
13070 if ( $slug == $this->get_slug() ) {
13071 continue;
13072 }
13073
13074 $install = $install_info['install'];
13075 $license = $install_info['license'];
13076
13077 if (
13078 is_object( $license ) &&
13079 $install->user_id != $license->user_id
13080 ) {
13081 $installs[] = $install->id;
13082 }
13083 }
13084
13085 return $installs;
13086 }
13087
13088 /**
13089 * Displays the "Change User" dialog box when the user clicks on the "Change User" button on the "Account" page.
13090 *
13091 * @author Leo Fajardo (@leorw)
13092 * @since 2.3.2
13093 *
13094 * @param number[] $install_ids
13095 */
13096 function _add_user_change_dialog_box( $install_ids ) {
13097 $vars = array(
13098 'id' => $this->_module_id,
13099 'license_owners' => $this->fetch_installs_licenses_owners_data( $install_ids )
13100 );
13101
13102 fs_require_template( 'forms/user-change.php', $vars );
13103 }
13104
13105 /**
13106 * @author Leo Fajardo (@leorw)
13107 * @since 2.3.1
13108 */
13109 function _add_data_debug_mode_dialog_box() {
13110 $vars = array(
13111 'id' => $this->_module_id,
13112 );
13113
13114 fs_require_template( 'forms/data-debug-mode.php', $vars );
13115 }
13116
13117 /**
13118 * Displays a subscription cancellation dialog box when the user clicks on the "Deactivate License"
13119 * link on the "Account" page or deactivates a plugin and there's an active subscription that is
13120 * either associated with a non-lifetime single-site license or non-lifetime multisite license that
13121 * is only activated on a single production site.
13122 *
13123 * @author Leo Fajardo (@leorw)
13124 * @since 2.2.1
13125 *
13126 * @param bool $is_license_deactivation
13127 *
13128 * @return array
13129 */
13130 function _get_subscription_cancellation_dialog_box_template_params( $is_license_deactivation = false ) {
13131 if ( fs_is_network_admin() ) {
13132 // Subscription cancellation dialog box is currently not supported for multisite networks.
13133 return array();
13134 }
13135
13136 if ( $this->is_whitelabeled() ) {
13137 return array();
13138 }
13139
13140 $license = $this->_get_license();
13141
13142 /**
13143 * 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.
13144 *
13145 * @author Leo Fajardo (@leorw) (Comment added by Vova Feldman @svovaf)
13146 * @since 2.2.1
13147 */
13148 if ( ! is_object( $license ) ||
13149 $license->is_lifetime() ||
13150 ( ! $license->is_single_site() && $license->activated > 1 )
13151 ) {
13152 return array();
13153 }
13154
13155 /**
13156 * @var FS_Subscription $subscription
13157 */
13158 $subscription = $this->_get_subscription( $license->id );
13159 if ( ! is_object( $subscription ) || ! $subscription->is_active() ) {
13160 return array();
13161 }
13162
13163 return array(
13164 'id' => $this->_module_id,
13165 'license' => $license,
13166 'has_trial' => $this->is_paid_trial(),
13167 'is_license_deactivation' => $is_license_deactivation,
13168 );
13169 }
13170
13171 /**
13172 * @author Leo Fajardo (@leorw)
13173 * @since 2.0.2
13174 */
13175 function _add_premium_version_upgrade_selection_dialog_box() {
13176 $modules_update = get_site_transient( $this->is_theme() ? 'update_themes' : 'update_plugins' );
13177 if ( ! isset( $modules_update->response[ $this->_plugin_basename ] ) ) {
13178 return;
13179 }
13180
13181 $vars = array(
13182 'id' => $this->_module_id,
13183 'new_version' => is_object( $modules_update->response[ $this->_plugin_basename ] ) ?
13184 $modules_update->response[ $this->_plugin_basename ]->new_version :
13185 $modules_update->response[ $this->_plugin_basename ]['new_version']
13186 );
13187
13188 fs_require_template( 'forms/premium-versions-upgrade-metadata.php', $vars );
13189 fs_require_once_template( 'forms/premium-versions-upgrade-handler.php', $vars );
13190 }
13191
13192 /**
13193 * Displays the opt-out dialog box when the user clicks on the "Opt Out" link on the "Plugins"
13194 * page.
13195 *
13196 * @author Leo Fajardo (@leorw)
13197 * @since 1.2.1.5
13198 */
13199 function _add_optout_dialog() {
13200 if ( $this->is_theme() ) {
13201 $vars = null;
13202 fs_require_once_template( '/js/jquery.content-change.php', $vars );
13203 }
13204
13205 $vars = array( 'id' => $this->_module_id );
13206 fs_require_template( 'forms/optout.php', $vars );
13207 }
13208
13209 /**
13210 * Prepare page to include all required UI and logic for the license activation dialog.
13211 *
13212 * @author Vova Feldman (@svovaf)
13213 * @since 1.2.0
13214 */
13215 function _add_license_activation() {
13216 if ( $this->is_migration() ) {
13217 return;
13218 }
13219
13220 if ( ! $this->is_user_admin() ) {
13221 // Only admins can activate a license.
13222 return;
13223 }
13224
13225 if ( ! $this->has_paid_plan() ) {
13226 // Module doesn't have any paid plans.
13227 return;
13228 }
13229
13230 if (
13231 $this->has_premium_version() &&
13232 ! $this->is_premium() &&
13233 /**
13234 * Also handle the case when an upgrade was made using the free version.
13235 *
13236 * @author Leo Fajardo (@leorw)
13237 * @since 2.3.2
13238 */
13239 ! is_object( $this->_get_license() )
13240 ) {
13241 // Only add license activation logic to the premium version, or in case of a serviceware plugin, also in the free version.
13242 return;
13243 }
13244
13245 // Add license activation link and AJAX request handler.
13246 if ( self::is_plugins_page() ) {
13247 $is_network_admin = fs_is_network_admin();
13248
13249 if (
13250 ( $is_network_admin && $this->is_network_active() && ! $this->is_network_delegated_connection() ) ||
13251 ( ! $is_network_admin && ( ! $this->is_network_active() || $this->is_delegated_connection() ) )
13252 ) {
13253 if (
13254 $this->is_premium() ||
13255 ( $this->has_paid_plan() && ! $this->has_premium_version() )
13256 ) {
13257 /**
13258 * @since 1.2.0 Add license action link only on plugins page.
13259 */
13260 $this->_add_license_action_link();
13261 }
13262 }
13263 }
13264
13265 // Add license activation AJAX callback.
13266 $this->add_ajax_action( 'activate_license', array( &$this, '_activate_license_ajax_action' ) );
13267
13268 // Add resend license AJAX callback.
13269 $this->add_ajax_action( 'resend_license_key', array( &$this, '_resend_license_key_ajax_action' ) );
13270 }
13271
13272 /**
13273 * Prepares page to include all required UI and logic for the "Change User" dialog.
13274 *
13275 * @author Leo Fajardo (@leorw)
13276 * @since 2.3.2
13277 */
13278 function _add_user_change_option() {
13279 if ( ! $this->should_handle_user_change() ) {
13280 return;
13281 }
13282
13283 $installs_ids_with_foreign_licenses = $this->get_installs_ids_with_foreign_licenses();
13284
13285 if ( empty( $installs_ids_with_foreign_licenses ) ) {
13286 // Handle user change only when the parent product or one of its add-ons is activated with a foreign license.
13287 return;
13288 }
13289
13290 // Add user change AJAX handler.
13291 $this->add_ajax_action( 'change_user', array( &$this, '_user_change_ajax_action' ) );
13292 }
13293
13294 /**
13295 * @author Leo Fajardo (@leorw)
13296 * @since 2.3.2
13297 */
13298 function should_handle_user_change() {
13299 if ( ! $this->is_user_admin() ) {
13300 // Only admins can change user.
13301 return false;
13302 }
13303
13304 if ( $this->is_addon() ) {
13305 return false;
13306 }
13307
13308 if ( ! $this->is_registered() ) {
13309 return false;
13310 }
13311
13312 if (
13313 $this->is_network_active() &&
13314 ( fs_is_network_admin() || ! $this->is_site_delegated_connection() )
13315 ) {
13316 // Handle only on site-level "Account" section for now.
13317 return false;
13318 }
13319
13320 return true;
13321 }
13322
13323 /**
13324 * @author Leo Fajardo (@leorw)
13325 * @since 2.0.2
13326 */
13327 function _add_premium_version_upgrade_selection() {
13328 if ( ! $this->is_user_admin() ) {
13329 return;
13330 }
13331
13332 if ( ! $this->is_premium() || $this->has_any_active_valid_license() ) {
13333 // This is relevant only to the free versions and premium versions without an active license.
13334 return;
13335 }
13336
13337 if ( self::is_updates_page() || ( $this->is_plugin() && self::is_plugins_page() ) ) {
13338 $this->_add_premium_version_upgrade_selection_action();
13339 }
13340 }
13341
13342 /**
13343 * @author Edgar Melkonyan
13344 * @since 2.4.1
13345 *
13346 * @throws Freemius_Exception
13347 */
13348 function _toggle_whitelabel_mode_ajax_handler() {
13349 $this->_logger->entrance();
13350
13351 $this->check_ajax_referer( 'toggle_whitelabel_mode' );
13352
13353 if ( ! $this->is_user_admin() ) {
13354 // Only for admins.
13355 self::shoot_ajax_failure();
13356 }
13357
13358 $license = $this->get_api_user_scope()->call(
13359 "/licenses/{$this->_site->license_id}.json",
13360 'put',
13361 array( 'is_whitelabeled' => ! $this->_license->is_whitelabeled )
13362 );
13363
13364 if ( ! $this->is_api_result_entity( $license ) ) {
13365 self::shoot_ajax_failure(
13366 FS_Api::is_api_error_object( $license ) ?
13367 $license->error->message :
13368 fs_text_inline( "An unknown error has occurred while trying to toggle the license's white-label mode.", 'unknown-error-occurred', $this->get_slug() )
13369 );
13370 }
13371
13372 $this->_license->is_whitelabeled = $license->is_whitelabeled;
13373 $this->_store_licenses();
13374
13375 $this->_sync_license();
13376
13377 if ( ! $license->is_whitelabeled ) {
13378 $this->_admin_notices->remove_sticky( 'license_whitelabeled' );
13379 } else {
13380 $this->_admin_notices->add_sticky(
13381 sprintf(
13382 $this->get_text_inline(
13383 '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.',
13384 'license_whitelabeled'
13385 ),
13386 "<strong>{$this->get_plugin_title()}</strong>",
13387 sprintf( '<a href="https://users.freemius.com" target="_blank">%s</a>', $this->get_text_inline( 'User Dashboard', 'user-dashboard' ) ),
13388 sprintf( '<a href="#" class="fs-toggle-whitelabel-mode">%s</a>', $this->get_text_inline( 'revert it now', 'revert-it-now' ) )
13389 ),
13390 'license_whitelabeled'
13391 );
13392 }
13393
13394 self::shoot_ajax_response( array( 'success' => true ) );
13395 }
13396
13397 /**
13398 * @author Leo Fajardo (@leorw)
13399 * @since 2.3.0
13400 */
13401 function _add_beta_mode_update_handler() {
13402 if ( ! $this->is_user_admin() ) {
13403 return;
13404 }
13405
13406 if ( ! $this->is_premium() ) {
13407 return;
13408 }
13409
13410 $this->add_ajax_action( 'set_beta_mode', array( &$this, '_set_beta_mode_ajax_handler' ) );
13411 }
13412
13413 /**
13414 * @author Leo Fajardo (@leorw)
13415 * @since 2.3.0
13416 */
13417 function _set_beta_mode_ajax_handler() {
13418 $this->_logger->entrance();
13419
13420 $this->check_ajax_referer( 'set_beta_mode' );
13421
13422 if ( ! $this->is_user_admin() ) {
13423 // Only for admins.
13424 self::shoot_ajax_failure();
13425 }
13426
13427 $is_beta = trim( fs_request_get( 'is_beta', '', 'post' ) );
13428
13429 if ( empty( $is_beta ) || ! in_array( $is_beta, array( 'true', 'false' ) ) ) {
13430 self::shoot_ajax_failure();
13431 }
13432
13433 $site = $this->api_site_call(
13434 '',
13435 'put',
13436 array(
13437 'is_beta' => ( 'true' == $is_beta ),
13438 'fields' => 'is_beta'
13439 )
13440 );
13441
13442 if ( ! $this->is_api_result_entity( $site ) ) {
13443 self::shoot_ajax_failure(
13444 FS_Api::is_api_error_object( $site ) ?
13445 $site->error->message :
13446 fs_text_inline( "An unknown error has occurred while trying to set the user's beta mode.", 'unknown-error-occurred', $this->get_slug() )
13447 );
13448 }
13449
13450 $this->_site->is_beta = $site->is_beta;
13451 $this->_store_site();
13452
13453 self::shoot_ajax_response( array( 'success' => true ) );
13454 }
13455
13456 /**
13457 * License activation WP AJAX handler.
13458 *
13459 * @author Leo Fajardo (@leorw)
13460 * @since 1.1.9
13461 *
13462 * @uses Freemius::activate_license()
13463 */
13464 function _activate_license_ajax_action() {
13465 $this->_logger->entrance();
13466
13467 $this->check_ajax_referer( 'activate_license' );
13468
13469 $license_key = trim( fs_request_get_raw( 'license_key' ) );
13470
13471 if ( empty( $license_key ) ) {
13472 $license_id = trim( fs_request_get_raw( 'license_id' ) );
13473
13474 if ( FS_Plugin_License::is_valid_id( $license_id ) ) {
13475 $license = $this->_get_license_by_id( $license_id, false );
13476
13477 if ( is_object( $license ) ) {
13478 $license_key = $license->secret_key;
13479 }
13480 }
13481 }
13482
13483 if ( empty( $license_key ) ) {
13484 exit;
13485 }
13486
13487 $sites = fs_is_network_admin() ?
13488 fs_request_get( 'sites', array(), 'post' ) :
13489 array();
13490
13491 $result = $this->activate_license(
13492 $license_key,
13493 $sites,
13494 fs_request_get_bool( 'is_marketing_allowed', null ),
13495 fs_request_get( 'blog_id', null ),
13496 fs_request_get( 'module_id', null, 'post' ),
13497 fs_request_get( 'user_id', null ),
13498 fs_request_get_bool( 'is_extensions_tracking_allowed', null ),
13499 fs_request_get_bool( 'is_diagnostic_tracking_allowed', null ),
13500 fs_request_get( 'license_owner_id', null )
13501 );
13502
13503 if (
13504 $result['success'] &&
13505 $this->is_bundle_license_auto_activation_enabled()
13506 ) {
13507 $license = new FS_Plugin_License();
13508 $license->secret_key = $license_key;
13509
13510 $this->maybe_activate_bundle_license( $license, $sites );
13511 }
13512
13513 echo json_encode( $result );
13514
13515 exit;
13516 }
13517
13518 /**
13519 * User change WP AJAX handler.
13520 *
13521 * @author Leo Fajardo (@leorw)
13522 * @since 2.3.2
13523 */
13524 function _user_change_ajax_action() {
13525 $this->_logger->entrance();
13526
13527 $this->check_ajax_referer( 'change_user' );
13528
13529 $new_email_address = trim( fs_request_get( 'email_address', '' ) );
13530 $new_user_id = fs_request_get( 'user_id' );
13531
13532 if ( empty( $new_email_address ) && ! FS_User::is_valid_id( $new_user_id ) ) {
13533 self::shoot_ajax_failure( fs_text_inline( 'Invalid new user ID or email address.', 'invalid-new-user-id-or-email', $this->get_slug() ) );
13534 }
13535
13536 $params = array();
13537
13538 if ( ! empty( $new_email_address ) ) {
13539 $params['user_email'] = $new_email_address;
13540 } else {
13541 $params['user_id'] = $new_user_id;
13542 }
13543
13544 $installs_info_by_slug_map = $this->get_parent_and_addons_installs_info();
13545 $install_ids = array();
13546
13547 foreach ( $installs_info_by_slug_map as $slug => $install_info ) {
13548 $install_ids[ $slug ] = $install_info['install']->id;
13549 }
13550
13551 $params['install_ids'] = implode( ',', array_values( $install_ids ) );
13552
13553 $install = $this->get_api_site_scope()->call( $this->add_show_pending( '/' ), 'put', $params );
13554
13555 if ( FS_Api::is_api_error( $install ) ) {
13556 $error = '';
13557
13558 if ( is_object( $install ) ) {
13559 switch ( $install->error->code ) {
13560 case 'user_exist':
13561 $error = (
13562 $this->get_text_x_inline( 'Oops', 'exclamation', 'oops' ) . '...' .
13563 $this->get_text_inline( 'Sorry, we could not complete the email update. Another user with the same email is already registered.', 'user-exist-message' ) . ' ' .
13564 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>' ) .
13565 sprintf(
13566 '<a style="line-height: 40px;" href="%s"><button class="button button-primary">%s &nbsp;&#10140;</button></a>',
13567 $this->get_account_url( 'change_owner', array(
13568 'state' => 'init',
13569 'candidate_email' => $new_email_address
13570 ) ),
13571 $this->get_text_inline( 'Change Ownership', 'change-ownership' )
13572 )
13573 );
13574 break;
13575 }
13576 }
13577
13578 if ( empty( $error ) ) {
13579 $error = FS_Api::is_api_error_object( $install ) ?
13580 $install->error->message :
13581 var_export( $install->error, true );
13582 }
13583
13584 self::shoot_ajax_failure( $error );
13585 } else {
13586 if (
13587 // If successful ownership change.
13588 $this->get_user()->id != $install->user_id ||
13589 ! empty( $new_email_address )
13590 ) {
13591 $this->complete_ownership_change_by_license( $install->user_id, $install_ids );
13592 }
13593 }
13594
13595 self::shoot_ajax_success();
13596 }
13597
13598 /**
13599 * @author Leo Fajardo (@leorw)
13600 * @since 2.3.2.14
13601 */
13602 function starting_migration() {
13603 if ( ! empty( $this->_storage->license_migration ) ) {
13604 // Do not overwrite the data if already set.
13605 return;
13606 }
13607
13608 $this->_storage->license_migration = array(
13609 'is_migrating' => true,
13610 'start_timestamp' => time()
13611 );
13612 }
13613
13614 /**
13615 * @author Leo Fajardo (@leorw)
13616 * @since 2.3.2.14
13617 */
13618 function is_migration() {
13619 if ( $this->is_addon() ) {
13620 return $this->get_parent_instance()->is_migration();
13621 }
13622
13623 if ( empty( $this->_storage->license_migration ) ) {
13624 return false;
13625 }
13626
13627 if ( ! $this->_storage->license_migration['is_migrating'] ) {
13628 return false;
13629 }
13630
13631 return (
13632 // Return `true` if the migration is within 5 minutes from the starting time.
13633 ( time() - $this->_storage->license_migration['start_timestamp'] ) <= WP_FS__TIME_5_MIN_IN_SEC
13634 );
13635 }
13636
13637 /**
13638 *
13639 * A helper method to activate migrated licenses. If the product is network activated and integrated, the method will network activate the license.
13640 *
13641 * @author Vova Feldman (@svovaf)
13642 * @since 2.3.0
13643 *
13644 * @param string $license_key
13645 * @param null|bool $is_marketing_allowed
13646 * @param null|number $plugin_id
13647 * @param array $sites
13648 * @param int $blog_id
13649 * @param null|number $license_owner_id
13650 *
13651 * @return array {
13652 * @var bool $success
13653 * @var string $error
13654 * @var string $next_page
13655 * }
13656 *
13657 * @uses Freemius::activate_license()
13658 */
13659 function activate_migrated_license(
13660 $license_key,
13661 $is_marketing_allowed = null,
13662 $plugin_id = null,
13663 $sites = array(),
13664 $blog_id = null,
13665 $license_owner_id = null
13666 ) {
13667 $this->_logger->entrance();
13668
13669 $result = $this->activate_license(
13670 $license_key,
13671 ( empty( $sites ) && is_null( $blog_id ) && $this->is_network_active() ) ?
13672 $this->get_sites_for_network_level_optin() :
13673 $sites,
13674 $is_marketing_allowed,
13675 $blog_id,
13676 $plugin_id,
13677 null,
13678 null,
13679 null,
13680 $license_owner_id
13681 );
13682
13683 // No need to show the sticky after license activation notice after migrating a license.
13684 $this->_admin_notices->remove_sticky( 'plan_upgraded' );
13685
13686 return $result;
13687 }
13688
13689 /**
13690 * @author Leo Fajardo (@leorw)
13691 * @since 2.3.1
13692 *
13693 * @return string
13694 */
13695 function get_pricing_js_path() {
13696 if ( ! isset( $this->_pricing_js_path ) ) {
13697 $default_path = WP_FS__DIR_JS . '/pricing/freemius-pricing.js';
13698
13699 $pricing_js_path = $this->apply_filters( 'freemius_pricing_js_path', $default_path );
13700
13701 // Backward compatibility for people who placed the freemius-pricing inside `includes` directory. Let it take more preference than the default path.
13702 if ( empty( $pricing_js_path ) ) {
13703 global $fs_active_plugins;
13704
13705 foreach ( $fs_active_plugins->plugins as $sdk_path => $data ) {
13706 if ( $data->plugin_path == $this->get_plugin_basename() ) {
13707 $plugin_or_theme_root_dir = ( $this->is_plugin() ? WP_PLUGIN_DIR : get_theme_root( get_stylesheet() ) );
13708
13709 $pricing_js_path = $plugin_or_theme_root_dir
13710 . '/'
13711 // The basename will be `plugins`, `themes`, or the basename of a custom plugins or themes directory.
13712 . str_replace( '../' . basename( $plugin_or_theme_root_dir ) . '/', '', $sdk_path )
13713 . '/includes/freemius-pricing/freemius-pricing.js';
13714
13715 break;
13716 }
13717 }
13718 }
13719
13720 // If it is still empty, load the default pricing JS.
13721 if ( ! file_exists( $pricing_js_path ) ) {
13722 $pricing_js_path = $default_path;
13723 }
13724
13725 $this->_pricing_js_path = $pricing_js_path;
13726 }
13727
13728 return $this->_pricing_js_path;
13729 }
13730
13731 /**
13732 * @author Leo Fajardo (@leorw)
13733 * @since 2.3.1
13734 *
13735 * @deprecated Since v2.9.0 we have removed the iFrame based pricing. This will always return `false`.
13736 *
13737 * @return bool
13738 */
13739 function should_use_external_pricing() {
13740 return false;
13741 }
13742
13743 /**
13744 * The implementation of this method was previously in `_activate_license_ajax_action()`.
13745 *
13746 * @author Vova Feldman (@svovaf)
13747 * @since 2.2.4
13748 * @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).
13749 * @param string $license_key
13750 * @param array $sites
13751 * @param null|bool $is_marketing_allowed
13752 * @param null|int $blog_id
13753 * @param null|number $plugin_id
13754 * @param null|number $user_id
13755 * @param bool|null $is_extensions_tracking_allowed
13756 * @param bool|null $is_diagnostic_tracking_allowed Since 2.5.0.2 to allow license activation with minimal data footprint.
13757 * @param null|number $license_owner_id
13758 *
13759 *
13760 * @return array {
13761 * @var bool $success
13762 * @var string $error
13763 * @var string $next_page
13764 * }
13765 */
13766 private function activate_license(
13767 $license_key,
13768 $sites = array(),
13769 $is_marketing_allowed = null,
13770 $blog_id = null,
13771 $plugin_id = null,
13772 $user_id = null,
13773 $is_extensions_tracking_allowed = null,
13774 $is_diagnostic_tracking_allowed = null,
13775 $license_owner_id = null
13776 ) {
13777 $this->_logger->entrance();
13778
13779 $license_key = trim( $license_key );
13780
13781 $is_network_activation_or_migration = (
13782 fs_is_network_admin() ||
13783 ( ! empty( $sites ) && $this->is_migration() )
13784 );
13785
13786 if ( ! $is_network_activation_or_migration ) {
13787 // If the license activation is executed outside the context of a network admin, ignore the sites collection.
13788 $sites = array();
13789 }
13790
13791 $fs = ( empty($plugin_id) || $plugin_id == $this->_module_id ) ?
13792 $this :
13793 $this->get_addon_instance( $plugin_id );
13794
13795 FS_Permission_Manager::instance( $this )->update_permissions_tracking_flag( array(
13796 FS_Permission_Manager::PERMISSION_DIAGNOSTIC => $is_diagnostic_tracking_allowed,
13797 FS_Permission_Manager::PERMISSION_EXTENSIONS => $is_extensions_tracking_allowed,
13798 ) );
13799
13800 $error = false;
13801 $next_page = false;
13802
13803 $has_valid_blog_id = is_numeric( $blog_id );
13804
13805 $user = null;
13806
13807 if ( $fs->is_addon() && $fs->get_parent_instance()->is_registered() ) {
13808 /**
13809 * When activating an add-on's license and the parent is opted-in, activate the license with the parent's opted-in user context.
13810 *
13811 * @author Vova Feldman (@svovaf)
13812 */
13813 $user = $fs->get_parent_instance()->get_current_or_network_user();
13814 } else if ( $fs->is_registered() ) {
13815 $user = $fs->get_current_or_network_user();
13816 }
13817
13818 if ( $has_valid_blog_id ) {
13819 /**
13820 * If a specific blog ID was provided, activate the license only on the specific blog that is associated with the given blog ID.
13821 *
13822 * @author Leo Fajardo (@leorw)
13823 */
13824 $fs->switch_to_blog( $blog_id );
13825 }
13826
13827 if ( is_object( $user ) ) {
13828 $result = true;
13829
13830 if ( $is_network_activation_or_migration && ! $has_valid_blog_id ) {
13831 // If no specific blog ID was provided, activate the license for all sites in the network.
13832 $blog_2_install_map = array();
13833 $site_ids = array();
13834
13835 foreach ( $sites as $site ) {
13836 if ( ! isset( $site['blog_id'] ) || ! is_numeric( $site['blog_id'] ) ) {
13837 continue;
13838 }
13839
13840 $install = $fs->get_install_by_blog_id( $site['blog_id'] );
13841
13842 if ( is_object( $install ) ) {
13843 $blog_2_install_map[ $site['blog_id'] ] = $install;
13844 } else {
13845 $site_ids[] = $site['blog_id'];
13846 }
13847 }
13848
13849 if ( ! empty( $blog_2_install_map ) ) {
13850 $result = $fs->activate_license_on_many_installs( $user, $license_key, $blog_2_install_map );
13851 }
13852
13853 if ( true === $result && ! empty( $site_ids ) ) {
13854 $result = $fs->activate_license_on_many_sites( $user, $license_key, $site_ids );
13855 }
13856 } else {
13857 if ( $fs->is_registered() ) {
13858 $params = array(
13859 'license_key' => $fs->apply_filters( 'license_key', $license_key )
13860 );
13861
13862 $install_ids = array();
13863
13864 $change_owner = FS_User::is_valid_id( $user_id );
13865
13866 if ( $change_owner ) {
13867 $params['user_id'] = $user_id;
13868
13869 $installs_info_by_slug_map = $fs->get_parent_and_addons_installs_info();
13870
13871 foreach ( $installs_info_by_slug_map as $slug => $install_info ) {
13872 $install_ids[ $slug ] = $install_info['install']->id;
13873 }
13874
13875 $params['install_ids'] = implode( ',', array_values( $install_ids ) );
13876 }
13877
13878 $api = $fs->get_api_site_scope();
13879
13880 $result = $api->call( $fs->add_show_pending( '/' ), 'put', $params );
13881
13882 if ( ! FS_Api::is_api_error( $result ) ) {
13883 $install = $result;
13884
13885 $fs->reconnect_locally( $has_valid_blog_id );
13886
13887 if (
13888 $change_owner &&
13889 // If successful ownership change.
13890 $fs->get_user()->id != $install->user_id
13891 ) {
13892 $fs->complete_ownership_change_by_license( $install->user_id, $install_ids );
13893 }
13894 }
13895 } else /* ( $fs->is_addon() && $fs->get_parent_instance()->is_registered() ) */ {
13896 $result = $fs->activate_license_on_site( $user, $license_key );
13897 }
13898 }
13899
13900 $is_connected = null;
13901
13902 if ( true !== $result && ! FS_Api::is_api_result_entity( $result ) ) {
13903 if ( FS_Api::is_blocked( $result ) ) {
13904 $result->error->message = $this->generate_api_blocked_notice_message_from_result( $result );
13905
13906 $is_connected = false;
13907 }
13908
13909 $error = FS_Api::is_api_error_object( $result ) ?
13910 $result->error->message :
13911 var_export( $result, true );
13912 } else {
13913 $is_connected = true;
13914
13915 $fs->network_upgrade_mode_completed();
13916
13917 $fs->_user = $user;
13918
13919 if ( fs_is_network_admin() && ! $has_valid_blog_id ) {
13920 $fs->_site = $fs->get_network_install();
13921 }
13922
13923 $fs->_sync_license( true, $has_valid_blog_id );
13924
13925 $this->maybe_sync_install_user();
13926
13927 $next_page = $fs->is_addon() ?
13928 $fs->get_parent_instance()->get_account_url() :
13929 $fs->get_after_activation_url( 'after_connect_url' );
13930 }
13931
13932 $fs->update_connectivity_info( $is_connected );
13933 } else {
13934 $next_page = $fs->opt_in(
13935 false,
13936 false,
13937 false,
13938 $license_key,
13939 false,
13940 false,
13941 false,
13942 $is_marketing_allowed,
13943 $sites,
13944 true,
13945 $license_owner_id
13946 );
13947
13948 if ( isset( $next_page->error ) ) {
13949 $error = $next_page->error;
13950 } else {
13951 if ( $is_network_activation_or_migration ) {
13952 /**
13953 * Get the list of sites that were just opted-in (and license activated).
13954 * This is an optimization for the next part below saving some DB queries.
13955 */
13956 $connected_sites = array();
13957 foreach ( $sites as $site ) {
13958 if ( isset( $site['blog_id'] ) && is_numeric( $site['blog_id'] ) ) {
13959 $connected_sites[ $site['blog_id'] ] = true;
13960 }
13961 }
13962
13963 $all_sites = self::get_sites();
13964 $pending_blog_ids = array();
13965
13966 /**
13967 * 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.
13968 *
13969 * @author Vova Feldman (@svovaf)
13970 */
13971 foreach ( $all_sites as $site ) {
13972 $blog_id = self::get_site_blog_id( $site );
13973
13974 if ( isset( $connected_sites[ $blog_id ] ) ) {
13975 // Site was just connected.
13976 continue;
13977 }
13978
13979 if ( $fs->is_installed_on_site( $blog_id ) ) {
13980 // Site was already connected before.
13981 continue;
13982 }
13983
13984 if ( $fs->is_site_delegated_connection( $blog_id ) ) {
13985 // Site's connection was delegated.
13986 continue;
13987 }
13988
13989 if ( $fs->is_anonymous_site( $blog_id ) ) {
13990 // Site connection was already skipped.
13991 continue;
13992 }
13993
13994 $pending_blog_ids[] = $blog_id;
13995 }
13996
13997 if ( ! empty( $pending_blog_ids ) ) {
13998 if ( $fs->is_freemium() && $fs->is_enable_anonymous() ) {
13999 $fs->skip_connection( $pending_blog_ids );
14000 } else {
14001 $fs->delegate_connection( $pending_blog_ids );
14002 }
14003 }
14004 }
14005 }
14006 }
14007
14008 if ( false === $error && true === $fs->_storage->require_license_activation ) {
14009 $fs->_storage->require_license_activation = false;
14010 }
14011
14012 $result = array(
14013 'success' => ( false === $error )
14014 );
14015
14016 if ( false !== $error ) {
14017 $result['error'] = $fs->apply_filters( 'opt_in_error_message', $error );
14018 } else {
14019 if ( $fs->is_addon() || $fs->has_addons() ) {
14020 /**
14021 * Purge the valid user licenses cache so that when the "Account" or the "Add-Ons" page is loaded,
14022 * an updated valid user licenses collection will be fetched from the server which is used to also
14023 * update the account add-ons (add-ons the user has licenses for).
14024 *
14025 * @author Leo Fajardo (@leorw)
14026 * @since 2.2.4
14027 */
14028 $fs->purge_valid_user_licenses_cache();
14029 }
14030
14031 $result['next_page'] = $next_page;
14032 }
14033
14034 return $result;
14035 }
14036
14037 /**
14038 * @author Leo Fajardo (@leorw)
14039 * @since 2.3.2
14040 *
14041 * @return array {
14042 * @key string Product slug.
14043 * @value array {
14044 * @property FS_Site $site
14045 * @property FS_Plugin_License $license
14046 * }
14047 * }
14048 */
14049 private function get_parent_and_addons_installs_info() {
14050 $fs = $this->is_addon() ?
14051 $this->get_parent_instance() :
14052 $this;
14053
14054 $installed_addons_ids = array();
14055
14056 $installed_addons_instances = $fs->get_installed_addons();
14057 foreach ( $installed_addons_instances as $instance ) {
14058 $installed_addons_ids[] = $instance->get_id();
14059 }
14060
14061 $addons_ids = array_unique( array_merge(
14062 $installed_addons_ids,
14063 $fs->get_updated_account_addons()
14064 ) );
14065
14066 // Add parent product info.
14067 $installs_info_by_slug_map = array(
14068 $fs->get_slug() => array(
14069 'install' => $fs->get_site(),
14070 'license' => $fs->_get_license()
14071 )
14072 );
14073
14074 foreach ( $addons_ids as $addon_id ) {
14075 $is_installed = isset( $installed_addons_ids_map[ $addon_id ] );
14076
14077 $addon_info = $fs->_get_addon_info( $addon_id, $is_installed );
14078
14079 if ( ! isset( $addon_info['is_connected'] ) || ! $addon_info['is_connected'] ) {
14080 // Add-on is not associated with an install entity.
14081 continue;
14082 }
14083
14084 $installs_info_by_slug_map[ $addon_info['slug'] ] = array(
14085 'install' => $addon_info['site'],
14086 'license' => isset( $addon_info['license'] ) ?
14087 $addon_info['license'] :
14088 null
14089 );
14090 }
14091
14092 return $installs_info_by_slug_map;
14093 }
14094
14095 /**
14096 * @author Leo Fajardo (@leorw)
14097 * @since 1.2.3.1
14098 */
14099 function _network_activate_ajax_action() {
14100 $this->_logger->entrance();
14101
14102 $this->check_ajax_referer( 'network_activate' );
14103
14104 $plugin_id = fs_request_get( 'module_id', '', 'post' );
14105 $fs = ( $plugin_id == $this->_module_id ) ?
14106 $this :
14107 $this->get_addon_instance( $plugin_id );
14108
14109 $error = false;
14110
14111 $sites = fs_request_get( 'sites', array(), 'post' );
14112 if ( is_array( $sites ) && ! empty( $sites ) ) {
14113 $sites_by_action = array(
14114 'allow' => array(),
14115 'delegate' => array(),
14116 'skip' => array()
14117 );
14118
14119 foreach ( $sites as $site ) {
14120 $sites_by_action[ $site['action'] ][] = $site;
14121 }
14122
14123 $total_sites = count( $sites );
14124 $total_sites_to_delegate = count( $sites_by_action['delegate'] );
14125
14126 $next_page = '';
14127
14128 $has_any_install = fs_request_get_bool( 'has_any_install' );
14129
14130 if ( $total_sites === $total_sites_to_delegate &&
14131 ! $this->is_network_upgrade_mode() &&
14132 ! $has_any_install
14133 ) {
14134 $this->delegate_connection();
14135 } else {
14136 if ( ! empty( $sites_by_action['delegate'] ) ) {
14137 $this->delegate_connection( self::get_sites_blog_ids( $sites_by_action['delegate'] ) );
14138 }
14139
14140 if ( ! empty( $sites_by_action['skip'] ) ) {
14141 $this->skip_connection( self::get_sites_blog_ids( $sites_by_action['skip'] ) );
14142 }
14143
14144 if ( empty( $sites_by_action['allow'] ) ) {
14145 if ( $has_any_install ) {
14146 $first_install = $fs->find_first_install();
14147
14148 if ( ! is_null( $first_install ) ) {
14149 $fs->_site = $first_install['install'];
14150 $fs->_storage->network_install_blog_id = $first_install['blog_id'];
14151
14152 $fs->_user = self::_get_user_by_id( $fs->_site->user_id );
14153 $fs->_storage->network_user_id = $fs->_user->id;
14154 }
14155 }
14156 } else {
14157 if ( ! $fs->is_registered() || ! $this->_is_network_active ) {
14158 $next_page = $fs->opt_in(
14159 false,
14160 false,
14161 false,
14162 false,
14163 false,
14164 false,
14165 false,
14166 fs_request_get_bool( 'is_marketing_allowed', null ),
14167 $sites_by_action['allow']
14168 );
14169 } else {
14170 $next_page = $fs->install_with_user(
14171 $this->get_network_user(),
14172 false,
14173 false,
14174 false,
14175 true,
14176 $sites_by_action['allow']
14177 );
14178 }
14179
14180 if ( is_object( $next_page ) && isset( $next_page->error ) ) {
14181 $error = $next_page->error;
14182 }
14183 }
14184 }
14185
14186 if ( empty( $next_page ) ) {
14187 $next_page = $this->get_after_activation_url( 'after_network_activation_url' );
14188 }
14189 } else {
14190 $error = $this->get_text_inline( 'Invalid site details collection.', 'invalid_site_details_collection' );
14191 }
14192
14193 $result = array(
14194 'success' => ( false === $error )
14195 );
14196
14197 if ( false !== $error ) {
14198 $result['error'] = $error;
14199 } else {
14200 $result['next_page'] = $next_page;
14201 }
14202
14203 echo json_encode( $result );
14204
14205 exit;
14206 }
14207
14208 /**
14209 * Billing update AJAX callback.
14210 *
14211 * @author Vova Feldman (@svovaf)
14212 * @since 1.2.1.5
14213 */
14214 function _update_billing_ajax_action() {
14215 $this->_logger->entrance();
14216
14217 $this->check_ajax_referer( 'update_billing' );
14218
14219 if ( ! $this->is_user_admin() ) {
14220 // Only for admins.
14221 self::shoot_ajax_failure();
14222 }
14223
14224 $billing = fs_request_get( 'billing' );
14225
14226 $api = $this->get_api_user_scope();
14227 $result = $api->call( '/billing.json', 'put', array_merge( $billing, array(
14228 'plugin_id' => $this->get_parent_id(),
14229 ) ) );
14230
14231 if ( ! $this->is_api_result_entity( $result ) ) {
14232 self::shoot_ajax_failure();
14233 }
14234
14235 // Purge cached billing.
14236 $this->get_api_user_scope()->purge_cache( 'billing.json' );
14237
14238 self::shoot_ajax_success();
14239 }
14240
14241 /**
14242 * Trial start for anonymous users (AJAX callback).
14243 *
14244 * @author Vova Feldman (@svovaf)
14245 * @since 1.2.1.5
14246 */
14247 function _start_trial_ajax_action() {
14248 $this->_logger->entrance();
14249
14250 $this->check_ajax_referer( 'start_trial' );
14251
14252 if ( ! $this->is_user_admin() ) {
14253 // Only for admins.
14254 self::shoot_ajax_failure();
14255 }
14256
14257 $trial_data = fs_request_get( 'trial' );
14258
14259 $next_page = $this->opt_in(
14260 false,
14261 false,
14262 false,
14263 false,
14264 false,
14265 $trial_data['plan_id']
14266 );
14267
14268 if ( is_object( $next_page ) && $this->is_api_error( $next_page ) ) {
14269 self::shoot_ajax_failure(
14270 isset( $next_page->error ) ?
14271 $next_page->error->message :
14272 var_export( $next_page, true )
14273 );
14274 }
14275
14276 $this->shoot_ajax_success( array(
14277 'next_page' => $next_page,
14278 ) );
14279 }
14280
14281 /**
14282 * @author Leo Fajardo (@leorw)
14283 * @since 1.2.0
14284 */
14285 function _resend_license_key_ajax_action() {
14286 $this->_logger->entrance();
14287
14288 $this->check_ajax_referer( 'resend_license_key' );
14289
14290 $email_address = sanitize_email( trim( fs_request_get( 'email', '', 'post' ) ) );
14291
14292 if ( empty( $email_address ) ) {
14293 exit;
14294 }
14295
14296 $error = false;
14297
14298 $api = $this->get_api_plugin_scope();
14299 $result = $api->call( '/licenses/resend.json', 'post',
14300 array(
14301 'email' => $email_address,
14302 'url' => home_url(),
14303 )
14304 );
14305
14306 if ( is_object( $result ) && isset( $result->error ) ) {
14307 $error = $result->error;
14308
14309 if ( in_array( $error->code, array( 'invalid_email', 'no_user' ) ) ) {
14310 $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' );
14311 } else if ( 'no_license' === $error->code ) {
14312 $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' );
14313 } else {
14314 $error = $error->message;
14315 }
14316 }
14317
14318 $licenses = array(
14319 'success' => ( false === $error )
14320 );
14321
14322 if ( false !== $error ) {
14323 $licenses['error'] = sprintf( '%s... %s', $this->get_text_x_inline( 'Oops', 'exclamation', 'oops' ), strtolower( $error ) );
14324 }
14325
14326 echo json_encode( $licenses );
14327
14328 exit;
14329 }
14330
14331 /**
14332 * @author Vova Feldman (@svovaf)
14333 * @since 1.2.1.8
14334 *
14335 * @var string
14336 */
14337 private static $_pagenow;
14338
14339 /**
14340 * Get current page or the referer if executing a WP AJAX request.
14341 *
14342 * @author Vova Feldman (@svovaf)
14343 * @since 1.2.1.8
14344 *
14345 * @return string
14346 */
14347 static function get_current_page() {
14348 if ( ! isset( self::$_pagenow ) ) {
14349 global $pagenow;
14350 if ( empty( $pagenow ) && is_admin() && is_multisite() ) {
14351 /**
14352 * It appears that `$pagenow` is not yet initialized in some network admin pages when this method
14353 * is called, so initialize it here using some pieces of code from `wp-includes/vars.php`.
14354 *
14355 * @author Leo Fajardo (@leorw)
14356 * @since 2.2.3
14357 */
14358 if ( is_network_admin() ) {
14359 preg_match( '#/wp-admin/network/?(.*?)$#i', $_SERVER['PHP_SELF'], $self_matches );
14360 } else if ( is_user_admin() ) {
14361 preg_match( '#/wp-admin/user/?(.*?)$#i', $_SERVER['PHP_SELF'], $self_matches );
14362 } else {
14363 preg_match( '#/wp-admin/?(.*?)$#i', $_SERVER['PHP_SELF'], $self_matches );
14364 }
14365
14366 $pagenow = $self_matches[1];
14367 $pagenow = trim( $pagenow, '/' );
14368 $pagenow = preg_replace( '#\?.*?$#', '', $pagenow );
14369 if ( '' === $pagenow || 'index' === $pagenow || 'index.php' === $pagenow ) {
14370 $pagenow = 'index.php';
14371 } else {
14372 preg_match( '#(.*?)(/|$)#', $pagenow, $self_matches );
14373 $pagenow = strtolower( $self_matches[1] );
14374 if ( '.php' !== substr($pagenow, -4, 4) )
14375 $pagenow .= '.php'; // for Options +Multiviews: /wp-admin/themes/index.php (themes.php is queried)
14376 }
14377 }
14378
14379 self::$_pagenow = $pagenow;
14380
14381 if ( self::is_ajax() &&
14382 'admin-ajax.php' === $pagenow
14383 ) {
14384 $referer = fs_get_raw_referer();
14385
14386 if ( is_string( $referer ) ) {
14387 $parts = explode( '?', $referer );
14388
14389 self::$_pagenow = basename( $parts[0] );
14390 }
14391 }
14392 }
14393
14394 return self::$_pagenow;
14395 }
14396
14397 /**
14398 * Helper method to check if user in the plugins page.
14399 *
14400 * @author Vova Feldman (@svovaf)
14401 * @since 1.2.1.5
14402 *
14403 * @return bool
14404 */
14405 static function is_plugins_page() {
14406 return ( 'plugins.php' === self::get_current_page() );
14407 }
14408
14409 /**
14410 * @author Leo Fajardo (@leorw)
14411 * @since 2.2.3
14412 *
14413 * @return bool
14414 */
14415 static function is_plugin_install_page() {
14416 return ( 'plugin-install.php' === self::get_current_page() );
14417 }
14418
14419 /**
14420 * @author Leo Fajardo (@leorw)
14421 * @since 2.0.2
14422 *
14423 * @return bool
14424 */
14425 static function is_updates_page() {
14426 return ( 'update-core.php' === self::get_current_page() );
14427 }
14428
14429 /**
14430 * Helper method to check if user in the themes page.
14431 *
14432 * @author Vova Feldman (@svovaf)
14433 * @since 1.2.2.6
14434 *
14435 * @return bool
14436 */
14437 static function is_themes_page() {
14438 return ( 'themes.php' === self::get_current_page() );
14439 }
14440
14441 #----------------------------------------------------------------------------------
14442 #region Affiliation
14443 #----------------------------------------------------------------------------------
14444
14445 /**
14446 * @author Leo Fajardo (@leorw)
14447 * @since 1.2.3
14448 *
14449 * @return bool
14450 */
14451 function has_affiliate_program() {
14452 if ( ! is_object( $this->_plugin ) ) {
14453 return false;
14454 }
14455
14456 return $this->_plugin->has_affiliate_program();
14457 }
14458
14459 /**
14460 * Get Plugin ID under which we will track affiliate application.
14461 *
14462 * This could either be the Bundle ID or the main plugin ID.
14463 *
14464 * @return number Bundle ID if developer has provided one, else the main plugin ID.
14465 */
14466 private function get_plugin_id_for_affiliate_terms() {
14467 return $this->has_bundle_context() ?
14468 $this->get_bundle_id() :
14469 $this->_plugin->id;
14470 }
14471
14472 /**
14473 * @author Leo Fajardo (@leorw)
14474 * @since 1.2.4
14475 */
14476 private function fetch_affiliate_terms() {
14477 if ( ! is_object( $this->plugin_affiliate_terms ) ) {
14478 /**
14479 * In case we have a bundle set in SDK configuration, we would like to use that for affiliates, not the main plugin.
14480 */
14481 $plugins_api = $this->has_bundle_context() ?
14482 $this->get_api_bundle_scope() :
14483 $this->get_api_plugin_scope();
14484
14485 $affiliate_terms = $plugins_api->get( '/aff.json?type=affiliation', false );
14486
14487 /**
14488 * 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.
14489 */
14490 if ( ! $this->is_api_result_entity( $affiliate_terms ) ) {
14491 return;
14492 }
14493
14494 $this->plugin_affiliate_terms = new FS_AffiliateTerms( $affiliate_terms );
14495 }
14496 }
14497
14498 /**
14499 * @author Leo Fajardo (@leorw)
14500 * @since 1.2.4
14501 */
14502 private function fetch_affiliate_and_custom_terms() {
14503 if ( ! empty( $this->_storage->affiliate_application_data ) ) {
14504 $application_data = $this->_storage->affiliate_application_data;
14505 $flush = ( ! isset( $application_data['status'] ) || 'pending' === $application_data['status'] );
14506
14507 $plugin_id_for_affiliate = $this->get_plugin_id_for_affiliate_terms();
14508
14509 $users_api = $this->get_api_user_scope();
14510 $result = $users_api->get( "/plugins/{$plugin_id_for_affiliate}/aff/{$this->plugin_affiliate_terms->id}/affiliates.json", $flush );
14511 if ( $this->is_api_result_object( $result, 'affiliates' ) ) {
14512 if ( ! empty( $result->affiliates ) ) {
14513 $affiliate = new FS_Affiliate( $result->affiliates[0] );
14514
14515 if ( ! isset( $application_data['status'] ) || $application_data['status'] !== $affiliate->status ) {
14516 $application_data['status'] = $affiliate->status;
14517 $this->_storage->affiliate_application_data = $application_data;
14518 }
14519
14520 if ( $affiliate->is_using_custom_terms ) {
14521 $affiliate_terms = $users_api->get( "/plugins/{$this->_plugin->id}/affiliates/{$affiliate->id}/aff/{$affiliate->custom_affiliate_terms_id}.json", $flush );
14522 if ( $this->is_api_result_entity( $affiliate_terms ) ) {
14523 $this->custom_affiliate_terms = new FS_AffiliateTerms( $affiliate_terms );
14524 }
14525 }
14526
14527 $this->affiliate = $affiliate;
14528 }
14529 }
14530 }
14531 }
14532
14533 /**
14534 * @author Leo Fajardo (@leorw)
14535 * @since 1.2.3
14536 */
14537 private function fetch_affiliate_and_terms() {
14538 $this->_logger->entrance();
14539
14540 $this->fetch_affiliate_terms();
14541 $this->fetch_affiliate_and_custom_terms();
14542 }
14543
14544 /**
14545 * @author Leo Fajardo (@leorw)
14546 * @since 1.2.3
14547 *
14548 * @return FS_Affiliate
14549 */
14550 function get_affiliate() {
14551 return $this->affiliate;
14552 }
14553
14554
14555 /**
14556 * @author Leo Fajardo (@leorw)
14557 * @since 1.2.3
14558 *
14559 * @return FS_AffiliateTerms
14560 */
14561 function get_affiliate_terms() {
14562 return is_object( $this->custom_affiliate_terms ) ?
14563 $this->custom_affiliate_terms :
14564 $this->plugin_affiliate_terms;
14565 }
14566
14567 /**
14568 * @author Leo Fajardo (@leorw)
14569 * @since 1.2.3
14570 */
14571 function _submit_affiliate_application() {
14572 $this->_logger->entrance();
14573
14574 $this->check_ajax_referer( 'submit_affiliate_application' );
14575
14576 if ( ! $this->is_user_admin() ) {
14577 // Only for admins.
14578 self::shoot_ajax_failure();
14579 }
14580
14581 $affiliate = fs_request_get( 'affiliate' );
14582
14583 if ( empty( $affiliate['promotion_methods'] ) ) {
14584 unset( $affiliate['promotion_methods'] );
14585 }
14586
14587 if ( ! empty( $affiliate['additional_domains'] ) ) {
14588 $affiliate['additional_domains'] = array_unique( $affiliate['additional_domains'] );
14589 }
14590
14591 if ( ! $this->is_registered() ) {
14592 $email_address = isset( $affiliate['email'] ) ? $affiliate['email'] : '';
14593
14594 if ( ! is_email( $email_address ) ) {
14595 self::shoot_ajax_failure('Invalid email address.');
14596 }
14597
14598 // Opt in but don't track usage.
14599 $next_page = $this->opt_in(
14600 $email_address,
14601 false,
14602 false,
14603 false,
14604 false,
14605 false,
14606 true
14607 );
14608
14609 if ( is_object( $next_page ) && $this->is_api_error( $next_page ) ) {
14610 self::shoot_ajax_failure(
14611 isset( $next_page->error ) ?
14612 $next_page->error->message :
14613 var_export( $next_page, true )
14614 );
14615 } else if ( $this->is_pending_activation() ) {
14616 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' ) );
14617 }
14618 }
14619
14620 $this->fetch_affiliate_terms();
14621
14622 $plugin_id_for_affiliate = $this->get_plugin_id_for_affiliate_terms();
14623
14624 $api = $this->get_api_user_scope();
14625 $result = $api->call(
14626 ( "/plugins/{$plugin_id_for_affiliate}/aff/{$this->plugin_affiliate_terms->id}/affiliates.json" ),
14627 'post',
14628 $affiliate
14629 );
14630
14631 if ( $this->is_api_error( $result ) ) {
14632 self::shoot_ajax_failure(
14633 isset( $result->error ) ?
14634 $result->error->message :
14635 var_export( $result, true )
14636 );
14637 } else {
14638 if ( $this->_admin_notices->has_sticky( 'affiliate_program' ) ) {
14639 $this->_admin_notices->remove_sticky( 'affiliate_program' );
14640 }
14641
14642 $affiliate_application_data = array(
14643 'status' => 'pending',
14644 'stats_description' => $affiliate['stats_description'],
14645 'promotion_method_description' => $affiliate['promotion_method_description'],
14646 );
14647
14648 if ( ! empty( $affiliate['promotion_methods'] ) ) {
14649 $affiliate_application_data['promotion_methods'] = $affiliate['promotion_methods'];
14650 }
14651
14652 if ( ! empty( $affiliate['domain'] ) ) {
14653 $affiliate_application_data['domain'] = $affiliate['domain'];
14654 }
14655
14656 if ( ! empty( $affiliate['additional_domains'] ) ) {
14657 $affiliate_application_data['additional_domains'] = $affiliate['additional_domains'];
14658 }
14659
14660 $this->_storage->affiliate_application_data = $affiliate_application_data;
14661 }
14662
14663 // Purge cached affiliate.
14664 $api->purge_cache( 'affiliate.json' );
14665
14666 self::shoot_ajax_success( $result );
14667 }
14668
14669 /**
14670 * @author Leo Fajardo (@leorw)
14671 * @since 1.2.3
14672 *
14673 * @return array|null
14674 */
14675 function get_affiliate_application_data() {
14676 if ( empty( $this->_storage->affiliate_application_data ) ) {
14677 return null;
14678 }
14679
14680 return $this->_storage->affiliate_application_data;
14681 }
14682
14683 #endregion Affiliation ------------------------------------------------------------
14684
14685 #----------------------------------------------------------------------------------
14686 #region URL Generators
14687 #----------------------------------------------------------------------------------
14688
14689 /**
14690 * Alias to pricing_url().
14691 *
14692 * @author Vova Feldman (@svovaf)
14693 * @since 1.0.2
14694 *
14695 * @uses pricing_url()
14696 *
14697 * @param string $period Billing cycle
14698 * @param bool $is_trial
14699 *
14700 * @return string
14701 */
14702 function get_upgrade_url( $period = WP_FS__PERIOD_ANNUALLY, $is_trial = false ) {
14703 return $this->pricing_url( $period, $is_trial );
14704 }
14705
14706 /**
14707 * @author Vova Feldman (@svovaf)
14708 * @since 1.0.9
14709 *
14710 * @uses get_upgrade_url()
14711 *
14712 * @return string
14713 */
14714 function get_trial_url() {
14715 return $this->get_upgrade_url( WP_FS__PERIOD_ANNUALLY, true );
14716 }
14717
14718 /**
14719 * @author Leo Fajardo (@leorw)
14720 * @since 2.1.4
14721 *
14722 * @param string $new_version
14723 *
14724 * @return string
14725 */
14726 function version_upgrade_checkout_link( $new_version ) {
14727 if ( ! is_object( $this->_license ) ) {
14728 $url = $this->pricing_url();
14729
14730 $purchase_license_text = $this->get_text_inline( 'Buy a license now', 'buy-license-now' );
14731 } else {
14732 $subscription = $this->_get_subscription( $this->_license->id );
14733
14734 $url = $this->checkout_url(
14735 is_object( $subscription ) ?
14736 ( 1 == $subscription->billing_cycle ? WP_FS__PERIOD_MONTHLY : WP_FS__PERIOD_ANNUALLY ) :
14737 WP_FS__PERIOD_LIFETIME,
14738 false,
14739 array( 'licenses' => $this->_license->quota )
14740 );
14741
14742 $purchase_license_text = $this->get_text_inline( 'Renew your license now', 'renew-license-now' );
14743 }
14744
14745 return sprintf(
14746 $this->get_text_inline( '%s to access version %s security & feature updates, and support.', 'x-for-updates-and-support' ),
14747 sprintf(
14748 '<a href="%s">%s</a>',
14749 $this->apply_filters( 'update_notice_checkout_url', $url ),
14750 $purchase_license_text
14751 ),
14752 $new_version
14753 );
14754 }
14755
14756 /**
14757 * Plugin's pricing URL.
14758 *
14759 * @author Vova Feldman (@svovaf)
14760 * @since 1.0.4
14761 *
14762 * @param string $billing_cycle Billing cycle
14763 *
14764 * @param bool $is_trial
14765 *
14766 * @return string
14767 */
14768 function pricing_url( $billing_cycle = WP_FS__PERIOD_ANNUALLY, $is_trial = false ) {
14769 $this->_logger->entrance();
14770
14771 $params = array(
14772 'billing_cycle' => $billing_cycle
14773 );
14774
14775 if ( $is_trial ) {
14776 $params['trial'] = 'true';
14777 }
14778
14779 $url = $this->is_addon() ?
14780 $this->_parent->addon_url( $this->_slug ) :
14781 $this->_get_admin_page_url( 'pricing', $params );
14782
14783 return $this->get_pricing_url_with_filter( $url );
14784 }
14785
14786 /**
14787 * Retrieves the filtered pricing URL.
14788 *
14789 * @author Leo Fajardo (@leorw)
14790 * @since 2.7.4
14791 *
14792 * @param string $url
14793 *
14794 * @return string
14795 */
14796 private function get_pricing_url_with_filter( $url ) {
14797 return $this->apply_filters( 'pricing_url', $url );
14798 }
14799
14800 /**
14801 * Checkout page URL.
14802 *
14803 * @author Vova Feldman (@svovaf)
14804 * @since 1.0.6
14805 *
14806 * @param string $billing_cycle Billing cycle
14807 * @param bool $is_trial
14808 * @param array $extra (optional) Extra parameters, override other query params.
14809 * @param bool|null $network
14810 *
14811 * @return string
14812 */
14813 function checkout_url(
14814 $billing_cycle = WP_FS__PERIOD_ANNUALLY,
14815 $is_trial = false,
14816 $extra = array(),
14817 $network = null
14818 ) {
14819 $this->_logger->entrance();
14820
14821 $params = array(
14822 'checkout' => 'true',
14823 'billing_cycle' => $billing_cycle,
14824 );
14825
14826 if ( $is_trial ) {
14827 $params['trial'] = 'true';
14828 }
14829
14830 /**
14831 * Params in extra override other params.
14832 */
14833 $params = array_merge( $params, $extra );
14834
14835 return $this->apply_filters( 'checkout_url', $this->_get_admin_page_url( 'pricing', $params, $network ) );
14836 }
14837
14838 /**
14839 * Add-on checkout URL.
14840 *
14841 * @author Vova Feldman (@svovaf)
14842 * @since 1.1.7
14843 *
14844 * @param number $addon_id
14845 * @param number $pricing_id
14846 * @param string $billing_cycle
14847 * @param bool $is_trial
14848 * @param bool|null $network
14849 *
14850 * @return string
14851 */
14852 function addon_checkout_url(
14853 $addon_id,
14854 $pricing_id,
14855 $billing_cycle = WP_FS__PERIOD_ANNUALLY,
14856 $is_trial = false,
14857 $network = null
14858 ) {
14859 return $this->checkout_url( $billing_cycle, $is_trial, array(
14860 'plugin_id' => $addon_id,
14861 'pricing_id' => $pricing_id,
14862 ), $network );
14863 }
14864
14865 #endregion
14866
14867 #endregion ------------------------------------------------------------------
14868
14869 /**
14870 * Check if plugin has any add-ons.
14871 *
14872 * @author Vova Feldman (@svovaf)
14873 * @since 1.0.5
14874 *
14875 * @since 1.1.7.3 Base logic only on the parameter provided by the developer in the init function.
14876 *
14877 * @return bool
14878 */
14879 function has_addons() {
14880 $this->_logger->entrance();
14881
14882 return $this->_has_addons;
14883 }
14884
14885 /**
14886 * Check if plugin can work in anonymous mode.
14887 *
14888 * @author Vova Feldman (@svovaf)
14889 * @since 1.0.9
14890 *
14891 * @return bool
14892 *
14893 * @deprecated Please use is_enable_anonymous() instead.
14894 */
14895 function enable_anonymous() {
14896 return $this->_enable_anonymous;
14897 }
14898
14899 /**
14900 * Check if plugin can work in anonymous mode.
14901 *
14902 * @author Vova Feldman (@svovaf)
14903 * @since 1.1.9
14904 *
14905 * @return bool
14906 */
14907 function is_enable_anonymous() {
14908 return $this->_enable_anonymous;
14909 }
14910
14911 /**
14912 * Check if plugin is premium only (no free plans).
14913 *
14914 * @author Vova Feldman (@svovaf)
14915 * @since 1.1.9
14916 *
14917 * @return bool
14918 */
14919 function is_only_premium() {
14920 return $this->_is_premium_only;
14921 }
14922
14923 /**
14924 * Checks if the plugin's type is "plugin". The other type is "theme".
14925 *
14926 * @author Leo Fajardo (@leorw)
14927 * @since 1.2.2
14928 *
14929 * @return bool
14930 */
14931 function is_plugin() {
14932 return ( WP_FS__MODULE_TYPE_PLUGIN === $this->_module_type );
14933 }
14934
14935 /**
14936 * @author Leo Fajardo (@leorw)
14937 * @since 1.2.2
14938 *
14939 * @return string
14940 */
14941 function get_module_type() {
14942 if ( ! isset( $this->_module_type ) ) {
14943 $id_slug_type_path_map = self::$_accounts->get_option( 'id_slug_type_path_map', array() );
14944 $this->_module_type = $id_slug_type_path_map[ $this->_module_id ]['type'];
14945 }
14946
14947 return $this->_module_type;
14948 }
14949
14950 /**
14951 * @author Leo Fajardo (@leorw)
14952 * @since 1.2.2
14953 *
14954 * @return string
14955 */
14956 function get_plugin_main_file_path() {
14957 return $this->_plugin_main_file_path;
14958 }
14959
14960 /**
14961 * Check if module has a premium code version.
14962 *
14963 * Serviceware module might be freemium without any
14964 * premium code version, where the paid features
14965 * are all part of the service.
14966 *
14967 * @author Vova Feldman (@svovaf)
14968 * @since 1.2.1.6
14969 *
14970 * @return bool
14971 */
14972 function has_premium_version() {
14973 return $this->_has_premium_version;
14974 }
14975
14976 /**
14977 * Check if feature supported with current site's plan.
14978 *
14979 * @author Vova Feldman (@svovaf)
14980 * @since 1.0.1
14981 *
14982 * @todo IMPLEMENT
14983 *
14984 * @param number $feature_id
14985 *
14986 * @throws Exception
14987 */
14988 function is_feature_supported( $feature_id ) {
14989 throw new Exception( 'not implemented' );
14990 }
14991
14992 /**
14993 * @author Vova Feldman (@svovaf)
14994 * @since 1.0.1
14995 *
14996 * @return bool Is running in SSL/HTTPS
14997 */
14998 function is_ssl() {
14999 return WP_FS__IS_HTTPS;
15000 }
15001
15002 /**
15003 * @author Vova Feldman (@svovaf)
15004 * @since 1.0.9
15005 *
15006 * @return bool Is running in AJAX call.
15007 *
15008 * @link http://wordpress.stackexchange.com/questions/70676/how-to-check-if-i-am-in-admin-ajax
15009 */
15010 static function is_ajax() {
15011 return ( defined( 'DOING_AJAX' ) && DOING_AJAX );
15012 }
15013
15014 /**
15015 * Check if it's an AJAX call targeted for the current module.
15016 *
15017 * @author Vova Feldman (@svovaf)
15018 * @since 1.2.0
15019 *
15020 * @param array|string $actions Collection of AJAX actions.
15021 *
15022 * @return bool
15023 */
15024 function is_ajax_action( $actions ) {
15025 // Verify it's an ajax call.
15026 if ( ! self::is_ajax() ) {
15027 return false;
15028 }
15029
15030 // Verify the call is relevant for the plugin.
15031 if ( $this->_module_id != fs_request_get( 'module_id' ) ) {
15032 return false;
15033 }
15034
15035 // Verify it's one of the specified actions.
15036 if ( is_string( $actions ) ) {
15037 $actions = explode( ',', $actions );
15038 }
15039
15040 if ( is_array( $actions ) && 0 < count( $actions ) ) {
15041 $ajax_action = fs_request_get( 'action' );
15042
15043 foreach ( $actions as $action ) {
15044 if ( $ajax_action === $this->get_action_tag( $action ) ) {
15045 return true;
15046 }
15047 }
15048 }
15049
15050 return false;
15051 }
15052
15053 /**
15054 * Check if it's an AJAX call targeted for current request.
15055 *
15056 * @author Vova Feldman (@svovaf)
15057 * @since 1.2.0
15058 *
15059 * @param array|string $actions Collection of AJAX actions.
15060 * @param number|null $module_id
15061 *
15062 * @return bool
15063 */
15064 static function is_ajax_action_static( $actions, $module_id = null ) {
15065 // Verify it's an ajax call.
15066 if ( ! self::is_ajax() ) {
15067 return false;
15068 }
15069
15070
15071 if ( ! empty( $module_id ) ) {
15072 // Verify the call is relevant for the plugin.
15073 if ( $module_id != fs_request_get( 'module_id' ) ) {
15074 return false;
15075 }
15076 }
15077
15078 // Verify it's one of the specified actions.
15079 if ( is_string( $actions ) ) {
15080 $actions = explode( ',', $actions );
15081 }
15082
15083 if ( is_array( $actions ) && 0 < count( $actions ) ) {
15084 $ajax_action = fs_request_get( 'action' );
15085
15086 foreach ( $actions as $action ) {
15087 if ( $ajax_action === self::get_ajax_action_static( $action, $module_id ) ) {
15088 return true;
15089 }
15090 }
15091 }
15092
15093 return false;
15094 }
15095
15096 /**
15097 * @author Vova Feldman (@svovaf)
15098 * @since 1.1.7
15099 *
15100 * @return bool
15101 */
15102 static function is_cron() {
15103 return ( defined( 'DOING_CRON' ) && DOING_CRON );
15104 }
15105
15106 /**
15107 * @author Leo Fajardo (@leorw)
15108 * @since 2.5.0
15109 *
15110 * @return bool
15111 */
15112 static function is_admin_post() {
15113 return ( 'admin-post.php' === self::get_current_page() );
15114 }
15115
15116 /**
15117 * Check if a real user is visiting the admin dashboard.
15118 *
15119 * @author Vova Feldman (@svovaf)
15120 * @since 1.1.7
15121 *
15122 * @return bool
15123 */
15124 function is_user_in_admin() {
15125 return (
15126 is_admin() &&
15127 ! self::is_ajax() &&
15128 ! self::is_cron() &&
15129 ! self::is_admin_post()
15130 );
15131 }
15132
15133 /**
15134 * Check if a real user is in the customizer view.
15135 *
15136 * @author Vova Feldman (@svovaf)
15137 * @since 1.2.2.7
15138 *
15139 * @return bool
15140 */
15141 static function is_customizer() {
15142 return is_customize_preview();
15143 }
15144
15145 /**
15146 * Check if running in HTTPS and if site's plan matching the specified plan.
15147 *
15148 * @param string $plan
15149 * @param bool $exact
15150 *
15151 * @return bool
15152 */
15153 function is_ssl_and_plan( $plan, $exact = false ) {
15154 return ( $this->is_ssl() && $this->is_plan( $plan, $exact ) );
15155 }
15156
15157 /**
15158 * Construct plugin's settings page URL.
15159 *
15160 * @author Vova Feldman (@svovaf)
15161 * @since 1.0.4
15162 *
15163 * @param string $page
15164 * @param array $params
15165 * @param bool|null $network
15166 *
15167 * @return string
15168 */
15169 function _get_admin_page_url( $page = '', $params = array(), $network = null ) {
15170 if ( is_null( $network ) ) {
15171 $network = (
15172 $this->_is_network_active &&
15173 ( fs_is_network_admin() || ! $this->is_delegated_connection() )
15174 );
15175 }
15176
15177 if ( 0 < count( $params ) ) {
15178 foreach ( $params as $k => $v ) {
15179 $params[ $k ] = urlencode( $v );
15180 }
15181 }
15182
15183 $page_param = $this->_menu->get_slug( $page );
15184
15185 if ( empty( $page ) &&
15186 // Show the opt-in as an overlay for free wp.org themes or themes without any settings page.
15187 $this->show_opt_in_on_themes_page()
15188 ) {
15189 $params[ $this->get_unique_affix() . '_show_optin' ] = 'true';
15190
15191 return add_query_arg(
15192 $params,
15193 $this->admin_url( 'themes.php', 'admin', $network )
15194 );
15195 }
15196
15197 if ( ! $this->has_settings_menu() ) {
15198 if ( ! empty( $page ) ) {
15199 // Module doesn't have a setting page, but since the request is for
15200 // a specific Freemius page, use the admin.php path.
15201 return add_query_arg( array_merge( $params, array(
15202 'page' => $page_param,
15203 ) ), $this->admin_url( 'admin.php', 'admin', $network ) );
15204 } else {
15205 if ( $this->is_activation_mode() ) {
15206 /**
15207 * @author Vova Feldman
15208 * @since 1.2.1.6
15209 *
15210 * If plugin doesn't have a settings page, create one for the opt-in screen.
15211 */
15212 return add_query_arg( array_merge( $params, array(
15213 'page' => $this->_slug,
15214 ) ), $this->admin_url( 'admin.php', 'admin', $network ) );
15215 } else {
15216 // Plugin without a settings page.
15217 return add_query_arg(
15218 $params,
15219 $this->admin_url( 'plugins.php', 'admin', $network )
15220 );
15221 }
15222 }
15223 }
15224
15225 // Module has a submenu settings page.
15226 if ( ! $this->_menu->is_top_level() ) {
15227 $parent_slug = $this->_menu->get_parent_slug();
15228 $menu_file = ( false !== strpos( $parent_slug, '.php' ) ) ?
15229 $parent_slug :
15230 'admin.php';
15231
15232 return add_query_arg( array_merge( $params, array(
15233 'page' => $page_param,
15234 ) ), $this->admin_url( $menu_file, 'admin', $network ) );
15235 }
15236
15237 // Module has a top level CPT settings page.
15238 if ( $this->_menu->is_cpt() ) {
15239 if ( empty( $page ) && $this->is_activation_mode() ) {
15240 return add_query_arg( array_merge( $params, array(
15241 'page' => $page_param
15242 ) ), $this->admin_url( 'admin.php', 'admin', $network ) );
15243 } else {
15244 if ( ! empty( $page ) ) {
15245 $params['page'] = $page_param;
15246 }
15247
15248 return add_query_arg(
15249 $params,
15250 $this->admin_url( $this->_menu->get_raw_slug(), 'admin', $network )
15251 );
15252 }
15253 }
15254
15255 // Module has a custom top level settings page.
15256 return add_query_arg( array_merge( $params, array(
15257 'page' => $page_param,
15258 ) ), $this->admin_url( 'admin.php', 'admin', $network ) );
15259 }
15260
15261 #--------------------------------------------------------------------------------
15262 #region Multisite
15263 #--------------------------------------------------------------------------------
15264
15265 /**
15266 * @author Leo Fajardo (@leorw)
15267 * @since 2.0.0
15268 *
15269 * @return bool
15270 */
15271 function is_network_active() {
15272 return $this->_is_network_active;
15273 }
15274
15275 /**
15276 * Delegate activation for the given sites in the network (or all sites if `null`) to site admins.
15277 *
15278 * @author Leo Fajardo (@leorw)
15279 * @since 2.0.0
15280 *
15281 * @param bool|int[] $all_or_blog_ids
15282 */
15283 private function delegate_connection( $all_or_blog_ids = true ) {
15284 $this->_logger->entrance();
15285
15286 $this->_admin_notices->remove_sticky( 'connect_account' );
15287
15288 if ( true === $all_or_blog_ids ) {
15289 // All sites delegation.
15290 $this->_storage->store( 'is_delegated_connection', true, true );
15291 } else {
15292 // Specified sites delegation.
15293 foreach ( $all_or_blog_ids as $blog_id ) {
15294 $this->delegate_site_connection( $blog_id );
15295 }
15296 }
15297
15298 $this->network_upgrade_mode_completed();
15299 }
15300
15301 /**
15302 * Delegate specific network site conncetion to the site admin.
15303 *
15304 * @author Vova Feldman (@svovaf)
15305 * @since 2.0.0
15306 *
15307 * @param int $blog_id
15308 */
15309 private function delegate_site_connection( $blog_id ) {
15310 $this->_storage->store( 'is_delegated_connection', true, $blog_id );
15311 }
15312
15313 /**
15314 * Check if super-admin delegated the connection of ALL sites to the site admins.
15315 *
15316 * @author Vova Feldman (@svovaf)
15317 * @since 2.0.0
15318 *
15319 * @return bool
15320 */
15321 function is_network_delegated_connection() {
15322 if ( ! $this->_is_network_active ) {
15323 return false;
15324 }
15325
15326 return $this->_storage->get( 'is_delegated_connection', false, true );
15327 }
15328
15329 /**
15330 * @author Leo Fajardo (@leorw)
15331 * @since 2.0.0
15332 *
15333 * @param int $blog_id
15334 *
15335 * @return bool
15336 */
15337 function is_site_delegated_connection( $blog_id = 0 ) {
15338 if ( ! $this->_is_network_active ) {
15339 return false;
15340 }
15341
15342 if ( 0 == $blog_id ) {
15343 $blog_id = get_current_blog_id();
15344 }
15345
15346 return $this->_storage->get( 'is_delegated_connection', false, $blog_id );
15347 }
15348
15349 /**
15350 * Check if delegated the connection. When running within the network admin,
15351 * and haven't specified the blog ID, checks if network level delegated. If running
15352 * within a site admin or specified a blog ID, check if delegated the connection for
15353 * the current context site.
15354 *
15355 * If executed outside the the admin, check if delegated the connection
15356 * for the current context site OR the whole network.
15357 *
15358 * @author Vova Feldman (@svovaf)
15359 * @since 2.0.0
15360 *
15361 * @param int $blog_id If set, checks if network delegated or blog specific delegated.
15362 *
15363 * @return bool
15364 */
15365 function is_delegated_connection( $blog_id = 0 ) {
15366 if ( ! $this->_is_network_active ) {
15367 return false;
15368 }
15369
15370 if ( fs_is_network_admin() && 0 == $blog_id ) {
15371 return $this->is_network_delegated_connection();
15372 }
15373
15374 return (
15375 $this->is_network_delegated_connection() ||
15376 $this->is_site_delegated_connection( $blog_id )
15377 );
15378 }
15379
15380 /**
15381 * Check if the current module is active for the site.
15382 *
15383 * @author Vova Feldman (@svovaf)
15384 * @since 2.0.0
15385 *
15386 * @param int $blog_id
15387 *
15388 * @return bool
15389 */
15390 function is_active_for_site( $blog_id ) {
15391 if ( ! is_multisite() ) {
15392 // Not a multisite and this code is executed, means that the plugin is active.
15393 return true;
15394 }
15395
15396 if ( $this->is_theme() ) {
15397 // All themes are site level activated.
15398 return true;
15399 }
15400
15401 if ( $this->_is_network_active ) {
15402 // Plugin was network activated so it's active.
15403 return true;
15404 }
15405
15406 return in_array( $this->_plugin_basename, (array) get_blog_option( $blog_id, 'active_plugins', array() ) );
15407 }
15408
15409 /**
15410 * @todo Implement pagination when accessing the subsites collection.
15411 *
15412 * @author Leo Fajardo (@leorw)
15413 * @since 2.0.0
15414 *
15415 * @param int $limit Default to 1,000
15416 * @param int $offset Default to 0
15417 *
15418 * @return array Active & public sites collection.
15419 */
15420 static function get_sites( $limit = 1000, $offset = 0 ) {
15421 if ( ! is_multisite() ) {
15422 return array();
15423 }
15424
15425 /**
15426 * For consistency with get_blog_list() which only return active public sites.
15427 *
15428 * @author Vova Feldman (@svovaf)
15429 */
15430 $args = array(
15431 /**
15432 * Commented out in order to handle the migration of site options whether the site is public or not.
15433 *
15434 * @author Leo Fajardo (@leorw)
15435 * @since 2.2.1
15436 */
15437 // 'public' => 1,
15438 'archived' => 0,
15439 'mature' => 0,
15440 'spam' => 0,
15441 'deleted' => 0,
15442 'number' => $limit,
15443 'offset' => $offset,
15444 );
15445
15446 return get_sites( $args );
15447 }
15448
15449 /**
15450 * Checks if a given blog is active.
15451 *
15452 * @author Vova Feldman (@svovaf)
15453 * @since 2.0.0
15454 *
15455 * @param $blog_id
15456 *
15457 * @return bool
15458 */
15459 private static function is_site_active( $blog_id ) {
15460 global $wpdb;
15461
15462 $blog_info = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM {$wpdb->blogs} WHERE blog_id = %d", $blog_id ) );
15463
15464 if ( ! is_object( $blog_info ) ) {
15465 return false;
15466 }
15467
15468 return (
15469 true == $blog_info->public &&
15470 false == $blog_info->archived &&
15471 false == $blog_info->mature &&
15472 false == $blog_info->spam &&
15473 false == $blog_info->deleted
15474 );
15475 }
15476
15477 /**
15478 * Get a mapping between the site addresses to their blog IDs.
15479 *
15480 * @author Vova Feldman (@svovaf)
15481 * @since 2.0.0
15482 *
15483 * @return array {
15484 * @key string Site address without protocol with a trailing slash.
15485 * @value int Site's blog ID.
15486 * }
15487 */
15488 private function get_address_to_blog_map() {
15489 $sites = self::get_sites();
15490
15491 // Map site addresses to their blog IDs.
15492 $address_to_blog_map = array();
15493 foreach ( $sites as $site ) {
15494 $blog_id = self::get_site_blog_id( $site );
15495 $address = self::get_unfiltered_site_url( $blog_id, true, true );
15496 $address_to_blog_map[ $address ] = $blog_id;
15497 }
15498
15499 return $address_to_blog_map;
15500 }
15501
15502 /**
15503 * Get a mapping between the site addresses to their blog IDs.
15504 *
15505 * @author Vova Feldman (@svovaf)
15506 * @since 2.0.0
15507 *
15508 * @return array {
15509 * @key int Site's blog ID.
15510 * @value FS_Site Associated install.
15511 * }
15512 */
15513 function get_blog_install_map() {
15514 $sites = self::get_sites();
15515
15516 // Map site blog ID to its install.
15517 $install_map = array();
15518
15519 foreach ( $sites as $site ) {
15520 $blog_id = self::get_site_blog_id( $site );
15521 $install = $this->get_install_by_blog_id( $blog_id );
15522
15523 if ( is_object( $install ) ) {
15524 $install_map[ $blog_id ] = $install;
15525 }
15526 }
15527
15528 return $install_map;
15529 }
15530
15531 /**
15532 * @author Vova Feldman (@svovaf)
15533 * @since 2.5.1
15534 *
15535 * @param bool|null $is_delegated When `true`, returns only connection delegated blog IDs. When `false`, only non-delegated blog IDs.
15536 *
15537 * @return int[]
15538 */
15539 private function get_blog_ids( $is_delegated = null ) {
15540 $blog_ids = array();
15541
15542 $sites = self::get_sites();
15543 foreach ( $sites as $site ) {
15544 $blog_id = self::get_site_blog_id( $site );
15545
15546 if (
15547 is_null( $is_delegated ) ||
15548 $is_delegated === $this->is_site_delegated_connection( $blog_id )
15549 ) {
15550 $blog_ids[] = $blog_id;
15551 }
15552 }
15553
15554 return $blog_ids;
15555 }
15556
15557 /**
15558 * @author Vova Feldman (@svovaf)
15559 * @since 2.5.1
15560 *
15561 * @return int[]
15562 */
15563 private function get_non_delegated_blog_ids() {
15564 return $this->get_blog_ids( false );
15565 }
15566
15567 /**
15568 * Gets a map of module IDs that the given user has opted-in to.
15569 *
15570 * @author Leo Fajardo (@leorw)
15571 * @since 2.1.0
15572 *
15573 * @param number $fs_user_id
15574 *
15575 * @return array {
15576 * @key number $plugin_id
15577 * @value bool Always true.
15578 * }
15579 */
15580 private static function get_user_opted_in_module_ids_map( $fs_user_id ) {
15581 self::$_static_logger->entrance();
15582
15583 if ( ! is_multisite() ) {
15584 $installs = array_merge(
15585 self::get_all_sites( WP_FS__MODULE_TYPE_PLUGIN ),
15586 self::get_all_sites( WP_FS__MODULE_TYPE_THEME )
15587 );
15588 } else {
15589 $sites = self::get_sites();
15590
15591 $installs = array();
15592 foreach ( $sites as $site ) {
15593 $blog_id = self::get_site_blog_id( $site );
15594
15595 $installs = array_merge(
15596 $installs,
15597 self::get_all_sites( WP_FS__MODULE_TYPE_PLUGIN, $blog_id ),
15598 self::get_all_sites( WP_FS__MODULE_TYPE_THEME, $blog_id )
15599 );
15600 }
15601 }
15602
15603 $module_ids_map = array();
15604 foreach ( $installs as $install ) {
15605 if ( is_object( $install ) &&
15606 FS_Site::is_valid_id( $install->id ) &&
15607 FS_User::is_valid_id( $install->user_id ) &&
15608 ( $install->user_id == $fs_user_id )
15609 ) {
15610 $module_ids_map[ $install->plugin_id ] = true;
15611 }
15612 }
15613
15614 return $module_ids_map;
15615 }
15616
15617 /**
15618 * @author Leo Fajardo (@leorw)
15619 *
15620 * @return null|array {
15621 * 'install' => FS_Site Module's install,
15622 * 'blog_id' => string The associated blog ID.
15623 * }
15624 */
15625 function find_first_install() {
15626 $sites = self::get_sites();
15627
15628 foreach ( $sites as $site ) {
15629 $blog_id = self::get_site_blog_id( $site );
15630 $install = $this->get_install_by_blog_id( $blog_id );
15631
15632 if ( is_object( $install ) ) {
15633 return array(
15634 'install' => $install,
15635 'blog_id' => $blog_id
15636 );
15637 }
15638 }
15639
15640 return null;
15641 }
15642
15643 /**
15644 * Switches the Freemius site level context to a specified blog.
15645 *
15646 * @author Vova Feldman (@svovaf)
15647 * @since 2.0.0
15648 *
15649 * @param int $blog_id
15650 * @param FS_Site $install
15651 * @param bool $flush
15652 *
15653 * @return bool Since 2.3.1 returns if a switch was made.
15654 */
15655 function switch_to_blog( $blog_id, $install = null, $flush = false ) {
15656 if ( ! is_numeric( $blog_id ) ) {
15657 return false;
15658 }
15659
15660 if ( ! $flush && $blog_id == $this->_context_is_network_or_blog_id ) {
15661 return false;
15662 }
15663
15664 switch_to_blog( $blog_id );
15665 $this->_context_is_network_or_blog_id = $blog_id;
15666
15667 self::$_accounts->set_site_blog_context( $blog_id );
15668 $this->_storage->set_site_blog_context( $blog_id );
15669 $this->_storage->set_network_active( $this->_is_network_active, $this->is_delegated_connection( $blog_id ) );
15670
15671 $this->_site = is_object( $install ) ?
15672 $install :
15673 $this->get_install_by_blog_id( $blog_id );
15674
15675 $this->_user = false;
15676 $this->_licenses = false;
15677 $this->_license = null;
15678 $this->is_whitelabeled = null;
15679
15680 if ( is_object( $this->_site ) ) {
15681 // Try to fetch user from install.
15682 $this->_user = self::_get_user_by_id( $this->_site->user_id );
15683
15684 if ( ! is_object( $this->_user ) &&
15685 FS_User::is_valid_id( $this->_storage->prev_user_id )
15686 ) {
15687 // Try to fetch previously saved user.
15688 $this->_user = self::_get_user_by_id( $this->_storage->prev_user_id );
15689
15690 if ( ! is_object( $this->_user ) ) {
15691 // Fallback to network's user.
15692 $this->_user = $this->get_network_user();
15693 }
15694 }
15695
15696 $all_plugin_licenses = self::get_all_licenses( $this->_module_id );
15697
15698 if ( ! empty( $all_plugin_licenses ) ) {
15699 if ( ! FS_Plugin_License::is_valid_id( $this->_site->license_id ) ) {
15700 $this->_license = null;
15701 } else {
15702 $license_found = false;
15703 foreach ( $all_plugin_licenses as $license ) {
15704 if ( $license->id == $this->_site->license_id ) {
15705 // License found.
15706 $this->_license = $license;
15707 $license_found = true;
15708 break;
15709 }
15710 }
15711
15712 if ( $license_found ) {
15713 $this->link_license_2_user( $this->_license->id, $this->_user->id );
15714 }
15715 }
15716
15717 $this->_licenses = $this->get_user_licenses( $this->_user->id );
15718 }
15719 }
15720
15721 unset( $this->_site_api );
15722 unset( $this->_user_api );
15723
15724 return true;
15725 }
15726
15727 /**
15728 * Restore the blog context to the blog that originally loaded the module.
15729 *
15730 * @author Vova Feldman (@svovaf)
15731 * @since 2.0.0
15732 */
15733 function restore_current_blog() {
15734 $this->switch_to_blog( $this->_blog_id );
15735 }
15736
15737 /**
15738 * @author Vova Feldman (@svovaf)
15739 * @since 2.0.0
15740 *
15741 * @param array|WP_Site $site
15742 *
15743 * @return int
15744 */
15745 static function get_site_blog_id( &$site ) {
15746 return ( $site instanceof WP_Site ) ?
15747 $site->blog_id :
15748 ( is_object( $site ) && isset( $site->userblog_id ) ?
15749 $site->userblog_id :
15750 $site['blog_id'] );
15751 }
15752
15753 /**
15754 * @author Vova Feldman (@svovaf)
15755 * @since 2.5.1
15756 *
15757 * @param WP_Site[]|array[] $sites
15758 *
15759 * @return int[]
15760 */
15761 static function get_sites_blog_ids( $sites ) {
15762 $blog_ids = array();
15763 foreach ( $sites as $site ) {
15764 $blog_ids[] = self::get_site_blog_id( $site );
15765 }
15766
15767 return $blog_ids;
15768 }
15769
15770 /**
15771 * @author Leo Fajardo (@leorw)
15772 * @since 2.0.0
15773 *
15774 * @param array|WP_Site|null $site
15775 * @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.
15776 *
15777 * @return array
15778 */
15779 function get_site_info( $site = null, $load_registration = false ) {
15780 $this->_logger->entrance();
15781
15782 $switched = false;
15783
15784 $registration_date = null;
15785
15786 if ( is_null( $site ) ) {
15787 $url = self::get_unfiltered_site_url();
15788 $name = get_bloginfo( 'name' );
15789 $blog_id = null;
15790 } else {
15791 $blog_id = self::get_site_blog_id( $site );
15792
15793 if ( get_current_blog_id() != $blog_id ) {
15794 switch_to_blog( $blog_id );
15795 $switched = true;
15796 }
15797
15798 if ( $site instanceof WP_Site ) {
15799 $url = $site->siteurl;
15800 $name = $site->blogname;
15801 $registration_date = $site->registered;
15802 } else {
15803 $url = self::get_unfiltered_site_url( $blog_id );
15804 $name = get_bloginfo( 'name' );
15805 }
15806 }
15807
15808 if ( empty( $registration_date ) && $load_registration ) {
15809 $blog_details = get_blog_details( $blog_id, false );
15810
15811 if ( is_object( $blog_details ) && isset( $blog_details->registered ) ) {
15812 $registration_date = $blog_details->registered;
15813 }
15814 }
15815
15816 $info = array(
15817 'uid' => $this->get_anonymous_id( $blog_id ),
15818 'url' => $url,
15819 );
15820
15821 // Add these diagnostic information only if user allowed to track.
15822 if ( FS_Permission_Manager::instance( $this )->is_diagnostic_tracking_allowed() ) {
15823 $info = array_merge( $info, array(
15824 'title' => $name,
15825 'language' => self::get_sanitized_language(),
15826 ) );
15827 }
15828
15829 if ( is_numeric( $blog_id ) ) {
15830 $info['blog_id'] = $blog_id;
15831 }
15832
15833 if ( ! empty( $registration_date ) ) {
15834 $info[ 'registration_date' ] = $registration_date;
15835 }
15836
15837 if ( $switched ) {
15838 restore_current_blog();
15839 }
15840
15841 return $info;
15842 }
15843
15844 /**
15845 * Load the module's install based on the blog ID.
15846 *
15847 * @author Vova Feldman (@svovaf)
15848 * @since 2.0.0
15849 *
15850 * @param int|null $blog_id
15851 *
15852 * @return FS_Site
15853 */
15854 function get_install_by_blog_id( $blog_id = null ) {
15855 $installs = self::get_all_sites( $this->_module_type, $blog_id );
15856 $install = isset( $installs[ $this->_slug ] ) ? $installs[ $this->_slug ] : null;
15857
15858 if ( is_object( $install ) &&
15859 is_numeric( $install->id ) &&
15860 is_numeric( $install->user_id ) &&
15861 FS_Plugin_Plan::is_valid_id( $install->plan_id )
15862 ) {
15863 // Load site.
15864 $install = clone $install;
15865 }
15866
15867 return $install;
15868 }
15869
15870 /**
15871 * Check if module is installed on a specified site.
15872 *
15873 * @author Vova Feldman (@svovaf)
15874 * @since 2.0.0
15875 *
15876 * @param int|null $blog_id
15877 *
15878 * @return bool
15879 */
15880 function is_installed_on_site( $blog_id = null ) {
15881 $installs = self::get_all_sites( $this->_module_type, $blog_id );
15882 $install = isset( $installs[ $this->_slug ] ) ? $installs[ $this->_slug ] : null;
15883
15884 return (
15885 is_object( $install ) &&
15886 is_numeric( $install->id ) &&
15887 is_numeric( $install->user_id ) &&
15888 FS_Plugin_Plan::is_valid_id( $install->plan_id )
15889 );
15890 }
15891
15892 /**
15893 * Check if super-admin connected at least one site via the network opt-in.
15894 *
15895 * @author Vova Feldman (@svovaf)
15896 * @since 2.0.0
15897 *
15898 * @return bool
15899 */
15900 function is_network_registered() {
15901 if ( ! $this->_is_network_active ) {
15902 return false;
15903 }
15904
15905 return FS_User::is_valid_id( $this->_storage->network_user_id );
15906 }
15907
15908 /**
15909 * Returns the main user associated with the network.
15910 *
15911 * @author Vova Feldman (@svovaf)
15912 * @since 2.0.0
15913 *
15914 * @return FS_User
15915 */
15916 function get_network_user() {
15917 if ( ! $this->_is_network_active ) {
15918 return null;
15919 }
15920
15921 return FS_User::is_valid_id( $this->_storage->network_user_id ) ?
15922 self::_get_user_by_id( $this->_storage->network_user_id ) :
15923 null;
15924 }
15925
15926 /**
15927 * Returns the current context user or the network's main user.
15928 *
15929 * @author Vova Feldman (@svovaf)
15930 * @since 2.0.0
15931 *
15932 * @return FS_User
15933 */
15934 function get_current_or_network_user() {
15935 return ( $this->_user instanceof FS_User ) ?
15936 $this->_user :
15937 $this->get_network_user();
15938 }
15939
15940 /**
15941 * Returns the main install associated with the network.
15942 *
15943 * @author Vova Feldman (@svovaf)
15944 * @since 2.0.0
15945 *
15946 * @return FS_Site
15947 */
15948 function get_network_install() {
15949 if ( ! $this->_is_network_active ) {
15950 return null;
15951 }
15952
15953 return FS_Site::is_valid_id( $this->_storage->network_install_blog_id ) ?
15954 $this->get_install_by_blog_id( $this->_storage->network_install_blog_id ) :
15955 null;
15956 }
15957
15958 /**
15959 * Returns the blog ID that is associated with the main install.
15960 *
15961 * @author Leo Fajardo (@leorw)
15962 * @since 2.0.0
15963 *
15964 * @return int|null
15965 */
15966 function get_network_install_blog_id() {
15967 if ( ! $this->_is_network_active ) {
15968 return null;
15969 }
15970
15971 return FS_Site::is_valid_id( $this->_storage->network_install_blog_id ) ?
15972 $this->_storage->network_install_blog_id :
15973 null;
15974 }
15975
15976 /**
15977 * Returns the current context install or the network's main install.
15978 *
15979 * @author Vova Feldman (@svovaf)
15980 * @since 2.0.0
15981 *
15982 * @return FS_Site
15983 */
15984 function get_current_or_network_install() {
15985 return ( $this->_site instanceof FS_Site ) ?
15986 $this->_site :
15987 $this->get_network_install();
15988 }
15989
15990 /**
15991 * Check if executing a site level action from the network level admin.
15992 *
15993 * @author Vova Feldman (@svovaf)
15994 * @since 2.0.0
15995 *
15996 * @return false|int If yes, return the requested blog ID.
15997 */
15998 private function is_network_level_site_specific_action() {
15999 if ( ! $this->_is_network_active ) {
16000 return false;
16001 }
16002
16003 if ( ! fs_is_network_admin() ) {
16004 return false;
16005 }
16006
16007 $blog_id = fs_request_get( 'blog_id', '' );
16008
16009 return is_numeric( $blog_id ) ? $blog_id : false;
16010 }
16011
16012 /**
16013 * Check if executing an action from the network level admin.
16014 *
16015 * @author Vova Feldman (@svovaf)
16016 * @since 2.0.0
16017 *
16018 * @return bool
16019 */
16020 private function is_network_level_action() {
16021 return ( $this->_is_network_active && fs_is_network_admin() );
16022 }
16023
16024 /**
16025 * Needs to be executed after site deactivation, archive, deletion, or flag as spam.
16026 * 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.
16027 *
16028 * @author Vova Feldman (@svovaf)
16029 * @since 2.0.0
16030 *
16031 * @param int $context_blog_id
16032 */
16033 private function update_multisite_data_after_site_deactivation( $context_blog_id = 0 ) {
16034 $this->_logger->entrance();
16035
16036 if ( $this->_is_network_active ) {
16037 if ( $context_blog_id == $this->_storage->network_install_blog_id ) {
16038 $installs_map = $this->get_blog_install_map();
16039
16040 foreach ( $installs_map as $blog_id => $install ) {
16041 /**
16042 * @var FS_Site $install
16043 */
16044 if ( $context_blog_id == $blog_id ) {
16045 continue;
16046 }
16047
16048 if ( $install->user_id != $this->_storage->network_user_id ) {
16049 continue;
16050 }
16051
16052 // Switch reference to a blog that is opted-in and belong to the same super-admin.
16053 $this->_storage->network_install_blog_id = $blog_id;
16054 break;
16055 }
16056 }
16057 }
16058
16059 if ( ! $this->is_registered() ) {
16060 return;
16061 }
16062
16063 if ( $this->is_sync_cron_scheduled() &&
16064 $context_blog_id == $this->get_sync_cron_blog_id()
16065 ) {
16066 $this->schedule_sync_cron( WP_FS__SCRIPT_START_TIME, true, $context_blog_id );
16067 }
16068
16069 if ( $this->is_install_sync_scheduled() &&
16070 $context_blog_id == $this->get_install_sync_cron_blog_id()
16071 ) {
16072 $this->maybe_schedule_install_sync_cron( $context_blog_id );
16073 }
16074 }
16075
16076 /**
16077 * Executed after site deactivation, archive, or flag as spam.
16078 *
16079 * @author Vova Feldman (@svovaf)
16080 * @since 2.0.0
16081 *
16082 * @param int $context_blog_id
16083 */
16084 public function _after_site_deactivated_callback( $context_blog_id = 0 ) {
16085 $this->_logger->entrance();
16086
16087 $install = $this->get_install_by_blog_id( $context_blog_id );
16088
16089 if ( ! is_object( $install ) ) {
16090 // Site not connected.
16091 return;
16092 }
16093
16094 $this->update_multisite_data_after_site_deactivation( $context_blog_id );
16095
16096 if ( ! $this->is_registered() ) {
16097 return;
16098 }
16099
16100 $current_blog_id = get_current_blog_id();
16101
16102 $this->switch_to_blog( $context_blog_id );
16103
16104 // Send deactivation event.
16105 $this->sync_install( array(
16106 'is_active' => false,
16107 ) );
16108
16109 $this->switch_to_blog( $current_blog_id );
16110 }
16111
16112 /**
16113 * Executed after site deletion.
16114 *
16115 * @author Vova Feldman (@svovaf)
16116 * @since 2.0.0
16117 *
16118 * @param int $context_blog_id
16119 * @param bool $drop True if site's database tables should be dropped. Default is false.
16120 */
16121 public function _after_site_deleted_callback( $context_blog_id = 0, $drop = false ) {
16122 $this->_logger->entrance();
16123
16124 $install = $this->get_install_by_blog_id( $context_blog_id );
16125
16126 if ( ! is_object( $install ) ) {
16127 // Site not connected.
16128 return;
16129 }
16130
16131 $this->update_multisite_data_after_site_deactivation( $context_blog_id );
16132
16133 if ( ! $this->is_registered() ) {
16134 return;
16135 }
16136
16137 $current_blog_id = get_current_blog_id();
16138
16139 $this->switch_to_blog( $context_blog_id );
16140
16141 if ( $drop ) {
16142 // Delete install if dropping site DB.
16143 $this->delete_account_event();
16144 } else {
16145 // Send deactivation event.
16146 $this->sync_install( array(
16147 'is_active' => false,
16148 ) );
16149 }
16150
16151 $this->switch_to_blog( $current_blog_id );
16152 }
16153
16154 /**
16155 * Executed after site deletion, called from wp_delete_site
16156 *
16157 * @author Dario Curvino (@dudo)
16158 * @since 2.5.0
16159 *
16160 * @param WP_Site $old_site
16161 */
16162 public function _after_wpsite_deleted_callback( WP_Site $old_site ) {
16163 $this->_logger->entrance();
16164
16165 $this->_after_site_deleted_callback( $old_site->blog_id, true );
16166 }
16167
16168 /**
16169 * Executed after site re-activation.
16170 *
16171 * @author Vova Feldman (@svovaf)
16172 * @since 2.0.0
16173 *
16174 * @param int $context_blog_id
16175 */
16176 public function _after_site_reactivated_callback( $context_blog_id = 0 ) {
16177 $this->_logger->entrance();
16178
16179 $install = $this->get_install_by_blog_id( $context_blog_id );
16180
16181 if ( ! is_object( $install ) ) {
16182 // Site not connected.
16183 return;
16184 }
16185
16186 if ( ! self::is_site_active( $context_blog_id ) ) {
16187 // Site not yet active (can be in spam mode, archived, deleted...).
16188 return;
16189 }
16190
16191 $current_blog_id = get_current_blog_id();
16192
16193 $this->switch_to_blog( $context_blog_id );
16194
16195 // Send re-activation event.
16196 $this->sync_install( array(
16197 'is_active' => true,
16198 ) );
16199
16200 $this->switch_to_blog( $current_blog_id );
16201 }
16202
16203 #endregion Multisite
16204
16205 /**
16206 * @author Leo Fajardo (@leorw)
16207 *
16208 * @param string $path
16209 * @param string $scheme
16210 * @param bool $network
16211 *
16212 * @return string
16213 */
16214 private function admin_url( $path = '', $scheme = 'admin', $network = true ) {
16215 return ( $this->_is_network_active && $network ) ?
16216 network_admin_url( $path, $scheme ) :
16217 admin_url( $path, $scheme );
16218 }
16219
16220 /**
16221 * Check if currently in a specified admin page.
16222 *
16223 * @author Vova Feldman (@svovaf)
16224 * @since 1.2.2.7
16225 *
16226 * @param string $page
16227 *
16228 * @return bool
16229 */
16230 function is_admin_page( $page ) {
16231 return ( $this->_menu->get_slug( $page ) === fs_request_get( 'page', '', 'get' ) );
16232 }
16233
16234 /**
16235 * Check if currently in the product's main admin page.
16236 *
16237 * @author Vova Feldman (@svovaf)
16238 * @since 2.3.1
16239 *
16240 * @return bool
16241 */
16242 function is_main_admin_page() {
16243 return $this->is_admin_page( '' );
16244 }
16245
16246 /**
16247 * Get module's main admin setting page URL.
16248 *
16249 * @author Vova Feldman (@svovaf)
16250 * @since 1.2.2.7
16251 *
16252 * @return string
16253 */
16254 function main_menu_url() {
16255 return $this->_menu->main_menu_url();
16256 }
16257
16258 /**
16259 * Check if currently on the theme's setting page or
16260 * on any of the Freemius added pages (via tabs).
16261 *
16262 * @author Vova Feldman (@svovaf)
16263 * @since 1.2.2.7
16264 *
16265 * @return bool
16266 *
16267 * @deprecated Please use is_product_settings_page() instead;
16268 */
16269 function is_theme_settings_page() {
16270 return $this->is_product_settings_page();
16271 }
16272
16273 /**
16274 * Check if currently on the product's main setting page or on any of the Freemius added pages (via tabs).
16275 *
16276 * @author Vova Feldman (@svovaf)
16277 * @since 1.2.2.7
16278 *
16279 * @return bool
16280 */
16281 function is_product_settings_page() {
16282 $page = fs_request_get( 'page', '', 'get' );
16283 $menu_slug = $this->_menu->get_slug();
16284
16285 if ( $page === $menu_slug ) {
16286 return true;
16287 }
16288
16289 return fs_starts_with(
16290 // e.g., {$menu_slug}-account, {$menu_slug}-affiliation, etc.
16291 $page,
16292 ( $menu_slug . '-' )
16293 );
16294 }
16295
16296 /**
16297 * Plugin's account page + sync license URL.
16298 *
16299 * @author Vova Feldman (@svovaf)
16300 * @since 1.1.9.1
16301 *
16302 * @param bool|number $plugin_id
16303 * @param bool $add_action_nonce
16304 * @param array $params
16305 *
16306 * @return string
16307 */
16308 function _get_sync_license_url( $plugin_id = false, $add_action_nonce = true, $params = array() ) {
16309 if ( is_numeric( $plugin_id ) ) {
16310 $params['plugin_id'] = $plugin_id;
16311 }
16312
16313 return $this->get_account_url(
16314 $this->get_unique_affix() . '_sync_license',
16315 $params,
16316 $add_action_nonce
16317 );
16318 }
16319
16320 /**
16321 * Plugin's account URL.
16322 *
16323 * @author Vova Feldman (@svovaf)
16324 * @since 1.0.4
16325 *
16326 * @param bool|string $action
16327 * @param array $params
16328 *
16329 * @param bool $add_action_nonce
16330 *
16331 * @return string
16332 */
16333 function get_account_url( $action = false, $params = array(), $add_action_nonce = true ) {
16334 if ( is_string( $action ) ) {
16335 $params['fs_action'] = $action;
16336 }
16337
16338 self::require_pluggable_essentials();
16339
16340 return ( $add_action_nonce && is_string( $action ) ) ?
16341 fs_nonce_url( $this->_get_admin_page_url( 'account', $params ), $action ) :
16342 $this->_get_admin_page_url( 'account', $params );
16343 }
16344
16345 /**
16346 * @author Vova Feldman (@svovaf)
16347 * @since 1.2.0
16348 *
16349 * @param string $tab
16350 * @param bool $action
16351 * @param array $params
16352 * @param bool $add_action_nonce
16353 *
16354 * @return string
16355 *
16356 * @uses get_account_url()
16357 */
16358 function get_account_tab_url( $tab, $action = false, $params = array(), $add_action_nonce = true ) {
16359 $params['tab'] = $tab;
16360
16361 return $this->get_account_url( $action, $params, $add_action_nonce );
16362 }
16363
16364 /**
16365 * Plugin's account URL.
16366 *
16367 * @author Vova Feldman (@svovaf)
16368 * @since 1.0.4
16369 *
16370 * @param bool|string $topic
16371 * @param bool|string $message
16372 * @param bool|string $summary Since 2.5.1.
16373 *
16374 * @return string
16375 */
16376 function contact_url( $topic = false, $message = false, $summary = false ) {
16377 $params = array();
16378 if ( is_string( $topic ) ) {
16379 $params['topic'] = $topic;
16380 }
16381 if ( is_string( $message ) ) {
16382 $params['message'] = $message;
16383 }
16384
16385 if ( is_string( $summary ) ) {
16386 $params['summary'] = $summary;
16387 }
16388
16389 if ( $this->is_addon() ) {
16390 $params['addon_id'] = $this->get_id();
16391
16392 return $this->get_parent_instance()->_get_admin_page_url( 'contact', $params );
16393 } else {
16394 return $this->_get_admin_page_url( 'contact', $params );
16395 }
16396 }
16397
16398 /**
16399 * Add-on direct info URL.
16400 *
16401 * @author Vova Feldman (@svovaf)
16402 * @since 1.1.0
16403 *
16404 * @param string $slug
16405 *
16406 * @return string
16407 */
16408 function addon_url( $slug ) {
16409 return $this->_get_admin_page_url( 'addons', array(
16410 'slug' => $slug
16411 ) );
16412 }
16413
16414 /**
16415 * Add-ons URL.
16416 *
16417 * @author Vova Feldman (@svovaf)
16418 * @since 2.4.5
16419 *
16420 * @return string
16421 */
16422 function get_addons_url() {
16423 return $this->_get_admin_page_url( 'addons' );
16424 }
16425
16426 /* Logger
16427 ------------------------------------------------------------------------------------------------------------------*/
16428 /**
16429 * @param string $id
16430 * @param bool $prefix_slug
16431 *
16432 * @return FS_Logger
16433 */
16434 function get_logger( $id = '', $prefix_slug = true ) {
16435 return FS_Logger::get_logger( ( $prefix_slug ? $this->_slug : '' ) . ( ( ! $prefix_slug || empty( $id ) ) ? '' : '_' ) . $id );
16436 }
16437
16438 /**
16439 * Note: This method is used externally so don't delete it.
16440 *
16441 * @param $id
16442 * @param bool $load_options
16443 * @param bool $prefix_slug
16444 *
16445 * @return FS_Option_Manager
16446 */
16447 function get_options_manager( $id, $load_options = false, $prefix_slug = true ) {
16448 return FS_Option_Manager::get_manager( ( $prefix_slug ? $this->_slug : '' ) . ( ( ! $prefix_slug || empty( $id ) ) ? '' : '_' ) . $id, $load_options );
16449 }
16450
16451 /* Security
16452 ------------------------------------------------------------------------------------------------------------------*/
16453 private static function _encrypt( $str ) {
16454 if ( is_null( $str ) ) {
16455 return null;
16456 }
16457
16458 /**
16459 * The encrypt/decrypt functions are used to protect
16460 * the user from messing up with some of the sensitive
16461 * data stored for the module as a JSON in the database.
16462 *
16463 * I used the same suggested hack by the theme review team.
16464 * For more details, look at the function `Base64UrlDecode()`
16465 * in `./sdk/FreemiusBase.php`.
16466 *
16467 * @todo Remove this hack once the base64 error is removed from the Theme Check.
16468 *
16469 * @author Vova Feldman (@svovaf)
16470 * @since 1.2.2
16471 */
16472 $fn = 'base64' . '_encode';
16473
16474 return $fn( $str );
16475 }
16476
16477 static function _decrypt( $str ) {
16478 if ( is_null( $str ) ) {
16479 return null;
16480 }
16481
16482 /**
16483 * The encrypt/decrypt functions are used to protect
16484 * the user from messing up with some of the sensitive
16485 * data stored for the module as a JSON in the database.
16486 *
16487 * I used the same suggested hack by the theme review team.
16488 * For more details, look at the function `Base64UrlDecode()`
16489 * in `./sdk/FreemiusBase.php`.
16490 *
16491 * @todo Remove this hack once the base64 error is removed from the Theme Check.
16492 *
16493 * @author Vova Feldman (@svovaf)
16494 * @since 1.2.2
16495 */
16496 $fn = 'base64' . '_decode';
16497
16498 return $fn( $str );
16499 }
16500
16501 /**
16502 * @author Vova Feldman (@svovaf)
16503 * @since 1.0.5
16504 *
16505 * @param FS_Entity $entity
16506 *
16507 * @return FS_Entity Return an encrypted clone entity.
16508 */
16509 private static function _encrypt_entity( FS_Entity $entity ) {
16510 $clone = clone $entity;
16511 $props = get_object_vars( $entity );
16512
16513 foreach ( $props as $key => $val ) {
16514 $clone->{$key} = self::_encrypt( $val );
16515 }
16516
16517 return $clone;
16518 }
16519
16520 /**
16521 * @author Vova Feldman (@svovaf)
16522 * @since 1.0.5
16523 *
16524 * @param FS_Entity $entity
16525 *
16526 * @return FS_Entity Return an decrypted clone entity.
16527 */
16528 private static function decrypt_entity( FS_Entity $entity ) {
16529 $clone = clone $entity;
16530 $props = get_object_vars( $entity );
16531
16532 foreach ( $props as $key => $val ) {
16533 $clone->{$key} = self::_decrypt( $val );
16534 }
16535
16536 return $clone;
16537 }
16538
16539 /**
16540 * @author Vova Feldman (@svovaf)
16541 * @since 1.0.7
16542 *
16543 * @param string $email
16544 *
16545 * @return FS_User|false
16546 */
16547 public static function _get_user_by_email( $email ) {
16548 self::$_static_logger->entrance();
16549
16550 $email = trim( strtolower( $email ) );
16551
16552 $users = self::get_all_users();
16553
16554 if ( is_array( $users ) ) {
16555 foreach ( $users as $user ) {
16556 if ( $email === trim( strtolower( $user->email ) ) ) {
16557 return $user;
16558 }
16559 }
16560 }
16561
16562 return false;
16563 }
16564
16565 #----------------------------------------------------------------------------------
16566 #region Account (Loading, Updates & Activation)
16567 #----------------------------------------------------------------------------------
16568
16569 /***
16570 * Load account information (user + site).
16571 *
16572 * @author Vova Feldman (@svovaf)
16573 * @since 1.0.1
16574 */
16575 private function _load_account() {
16576 $this->_logger->entrance();
16577
16578 $this->do_action( 'before_account_load' );
16579
16580 $users = self::get_all_users();
16581 $plans = self::get_all_plans( $this->_module_type );
16582
16583 if ( $this->_logger->is_on() && is_admin() ) {
16584 $this->_logger->log( 'users = ' . var_export( $users, true ) );
16585 $this->_logger->log( 'plans = ' . var_export( $plans, true ) );
16586 }
16587
16588 $site = fs_is_network_admin() ?
16589 $this->get_network_install() :
16590 $this->get_install_by_blog_id();
16591
16592 if ( fs_is_network_admin() &&
16593 $this->is_network_active() &&
16594 ! is_object( $site ) &&
16595 FS_Site::is_valid_id( $this->_storage->network_install_blog_id )
16596 ) {
16597 $first_install = $this->find_first_install();
16598
16599 if ( is_null( $first_install ) ) {
16600 unset( $this->_storage->network_install_blog_id );
16601 } else {
16602 $site = $first_install['install'];
16603 $this->_storage->network_install_blog_id = $first_install['blog_id'];
16604 }
16605 }
16606
16607 if ( is_object( $site ) &&
16608 is_numeric( $site->id ) &&
16609 is_numeric( $site->user_id ) &&
16610 FS_Plugin_Plan::is_valid_id( $site->plan_id )
16611 ) {
16612 // Load site.
16613 $this->_site = $site;
16614 }
16615
16616 $user = null;
16617 if ( fs_is_network_admin() && $this->_is_network_active ) {
16618 $user = $this->get_network_user();
16619 }
16620
16621 if ( is_object( $user ) ) {
16622 $this->_user = clone $user;
16623 } else if ( $this->_site ) {
16624 $user = self::_get_user_by_id( $this->_site->user_id );
16625
16626 if ( ! is_object( $user ) && FS_User::is_valid_id( $this->_storage->prev_user_id ) ) {
16627 /**
16628 * Try to load the previous owner. This recovery is used for the following use-case:
16629 * 1. Opt-in
16630 * 2. Cloning site1 to site2
16631 * 3. Ownership switch in site1 (same applies for site2)
16632 * 4. Install data sync on site2
16633 * 5. Now site2's install is associated with the new owner which does not exists locally.
16634 */
16635 $user = self::_get_user_by_id( $this->_storage->prev_user_id );
16636 }
16637
16638 if ( ! is_object( $user ) ) {
16639 /**
16640 * This is a special fault tolerance mechanism to handle a scenario that the user data is missing.
16641 */
16642 if (
16643 ! isset( $this->_storage->user_recovery_from_install_last_attempt_timestamp ) ||
16644 time() > ( $this->_storage->user_recovery_from_install_last_attempt_timestamp + FS_Clone_Manager::CLONE_RESOLUTION_MAX_EXECUTION_TIME )
16645 ) {
16646 $user = $this->sync_user_by_current_install();
16647 } else {
16648 return;
16649 }
16650
16651 if ( is_object( $user ) ) {
16652 $this->_storage->user_was_recovered_from_install = true;
16653 } else {
16654 $this->_storage->user_recovery_from_install_attempts = isset( $this->_storage->user_recovery_from_install_attempts ) ?
16655 ( $this->_storage->user_recovery_from_install_attempts + 1 ) :
16656 1;
16657
16658 if ( $this->_storage->user_recovery_from_install_attempts >= 3 ) {
16659 $this->delete_current_install( false );
16660 } else {
16661 $this->_storage->user_recovery_from_install_last_attempt_timestamp = time();
16662
16663 return;
16664 }
16665 }
16666 }
16667
16668 $this->_user = ( $user instanceof FS_User ) ?
16669 clone $user :
16670 null;
16671 }
16672
16673 if ( is_object( $this->_user ) ) {
16674 // Load licenses.
16675 $this->_licenses = $this->get_user_licenses( $this->_user->id );
16676 }
16677
16678 if ( is_object( $this->_site ) ) {
16679 // Load plans.
16680 $this->_plans = isset( $plans[ $this->_slug ] ) ?
16681 $plans[ $this->_slug ] :
16682 array();
16683
16684 if ( ! is_array( $this->_plans ) || empty( $this->_plans ) ) {
16685 $this->_sync_plans();
16686 } else {
16687 for ( $i = 0, $len = count( $this->_plans ); $i < $len; $i ++ ) {
16688 if ( $this->_plans[ $i ] instanceof FS_Plugin_Plan ) {
16689 $this->_plans[ $i ] = self::decrypt_entity( $this->_plans[ $i ] );
16690 } else {
16691 unset( $this->_plans[ $i ] );
16692 }
16693 }
16694 }
16695
16696 $this->_license = $this->_get_license_by_id( $this->_site->license_id );
16697
16698 if ( $this->_site->version != $this->get_plugin_version() ) {
16699 // If stored install version is different than current installed plugin version,
16700 // then update plugin version event.
16701 $this->update_plugin_version_event();
16702 }
16703 }
16704
16705 if ( true === $this->_storage->require_license_activation &&
16706 ! fs_request_get_bool( 'require_license', true )
16707 ) {
16708 $this->_storage->require_license_activation = false;
16709 }
16710
16711 if ( $this->is_theme() ) {
16712 $this->_register_account_hooks();
16713 }
16714
16715 if ( $this->is_user_in_admin() && $this->is_clone() ) {
16716 if ( empty( FS_Clone_Manager::instance()->get_clone_identification_timestamp() ) ) {
16717 FS_Clone_Manager::instance()->store_clone_identification_timestamp();
16718 }
16719
16720 FS_Clone_Manager::instance()->maybe_update_clone_resolution_support_flag( $this->_storage->sdk_last_version );
16721 $this->send_pending_clone_update_once();
16722 }
16723 }
16724
16725 /**
16726 * Special user recovery mechanism.
16727 *
16728 * @author Vova Feldman (@svovaf)
16729 * @since 2.0.0
16730 *
16731 * @param number|null $site_user_id
16732 *
16733 * @return \FS_User|mixed
16734 */
16735 private function sync_user_by_current_install( $site_user_id = null ) {
16736 $site_user_id = FS_Site::is_valid_id( $site_user_id ) ?
16737 $site_user_id :
16738 $this->_site->user_id;
16739
16740 $api = $this->get_api_site_scope();
16741
16742 $uid = $this->get_anonymous_id();
16743 $request_path = "/users/{$site_user_id}.json?uid={$uid}";
16744
16745 $result = $api->get( $request_path, false, WP_FS__TIME_10_MIN_IN_SEC );
16746
16747 if ( $this->is_api_result_entity( $result ) ) {
16748 $user = new FS_User( $result );
16749 $this->_user = $user;
16750 $this->_store_user();
16751
16752 return $user;
16753 }
16754
16755 $error_code = FS_Api::get_error_code( $result );
16756
16757 if ( in_array( $error_code, array( 'invalid_unique_id', 'user_cannot_be_recovered' ) ) ) {
16758 /**
16759 * Those API errors will continue coming and are not recoverable with the
16760 * current site's data. Therefore, extend the API call's cached result to 7 days.
16761 */
16762 $api->update_cache_expiration( $request_path, WP_FS__TIME_WEEK_IN_SEC );
16763 }
16764
16765 return $result;
16766 }
16767
16768 /**
16769 * @author Vova Feldman (@svovaf)
16770 * @since 1.0.1
16771 *
16772 * @param FS_User $user
16773 * @param FS_Site $site
16774 * @param bool|array $plans
16775 */
16776 private function _set_account( FS_User $user, FS_Site $site, $plans = false ) {
16777 $site->user_id = $user->id;
16778
16779 $this->_site = $site;
16780 $this->_user = $user;
16781 if ( false !== $plans ) {
16782 $this->_plans = $plans;
16783 }
16784
16785 $this->send_install_update();
16786
16787 $this->_store_account();
16788
16789 }
16790
16791 /**
16792 * Get a sanitized array with the WordPress version, SDK version, and PHP version.
16793 * Each version is trimmed after the 16th char.
16794 *
16795 * @author Vova Feldman (@svovaf)
16796 * @since 2.2.1
16797 *
16798 * @return array
16799 */
16800 private function get_versions() {
16801 $versions = array();
16802 $versions['sdk_version'] = $this->version;
16803
16804 // Collect these diagnostic information only if it's allowed.
16805 if ( FS_Permission_Manager::instance( $this )->is_diagnostic_tracking_allowed() ) {
16806 $versions['platform_version'] = get_bloginfo( 'version' );
16807 $versions['programming_language_version'] = phpversion();
16808 }
16809
16810 foreach ( $versions as $k => $version ) {
16811 $versions[ $k ] = self::get_api_sanitized_property( $k, $version );
16812 }
16813
16814 return $versions;
16815 }
16816
16817 /**
16818 * Get sanitized site language.
16819 *
16820 * @param string $language
16821 * @param int $max_len
16822 *
16823 * @since 2.5.1
16824 * @author Vova Feldman (@svovaf)
16825 *
16826 * @return string
16827 */
16828 private static function get_sanitized_language( $language = '', $max_len = self::LANGUAGE_MAX_CHARS ) {
16829 if ( empty( $language ) ) {
16830 $language = get_bloginfo( 'language' );
16831 }
16832
16833 return substr( $language, 0, $max_len );
16834 }
16835
16836 /**
16837 * Get core version stripped from pre-release and build.
16838 *
16839 * @since 2.5.1
16840 * @author Vova Feldman (@svovaf)
16841 *
16842 * @param string $version
16843 * @param int $parts
16844 * @param int $max_len
16845 * @param bool $include_pre_release
16846 *
16847 * @return string
16848 */
16849 private static function get_core_version(
16850 $version,
16851 $parts = 3,
16852 $max_len = self::VERSION_MAX_CHARS,
16853 $include_pre_release = false
16854 ) {
16855 if ( empty( $version ) ) {
16856 // Version is empty.
16857 return '';
16858 }
16859
16860 if ( is_numeric( $version ) ) {
16861 $is_float_version = is_float( $version );
16862
16863 $version = (string) $version;
16864
16865 /**
16866 * 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.
16867 */
16868 if ( $is_float_version && false === strpos( $version, '.' ) ) {
16869 $version .= '.0';
16870 }
16871 }
16872
16873 if ( ! is_string( $version ) ) {
16874 return '';
16875 }
16876
16877 if ( $parts < 1 ) {
16878 return '';
16879 }
16880
16881 $pre_release_regex = $include_pre_release ?
16882 '(\-(alpha|beta|RC)([0-9]+)?)?' :
16883 '';
16884
16885 if ( 0 === preg_match( '/^([0-9]+(\.[0-9]+){0,' . ( $parts - 1 ) . '}' . $pre_release_regex . ')/i', $version, $matches ) ) {
16886 // Version is not starting with a digit.
16887 return '';
16888 }
16889
16890 return substr( $matches[1], 0, $max_len );
16891 }
16892
16893 /**
16894 * @param string $prop
16895 * @param mixed $val
16896 *
16897 * @return mixed
16898 *@author Vova Feldman (@svovaf)
16899 *
16900 * @since 2.5.1
16901 */
16902 private static function get_api_sanitized_property( $prop, $val ) {
16903 if ( ! is_string( $val ) || empty( $val ) ) {
16904 return $val;
16905 }
16906
16907 switch ( $prop ) {
16908 case 'programming_language_version':
16909 // Get core PHP version, which can have up to 3 parts (ignore pre-releases).
16910 return self::get_core_version( $val );
16911 case 'platform_version':
16912 // Get the exact WordPress version, which can have up to 3 parts (including pre-releases).
16913 return self::get_core_version( $val, 3, self::VERSION_MAX_CHARS, true );
16914 case 'sdk_version':
16915 // Get the exact SDK version, which can have up to 4 parts.
16916 return self::get_core_version( $val, 4 );
16917 case 'version':
16918 // Get the entire version but just limited in length.
16919 return substr( $val, 0, self::VERSION_MAX_CHARS );
16920 case 'language':
16921 return self::get_sanitized_language( $val );
16922 default:
16923 return $val;
16924 }
16925 }
16926
16927 /**
16928 * @author Leo Fajardo (@leorw)
16929 * @since 2.3.0
16930 *
16931 * @return bool
16932 */
16933 function has_beta_update() {
16934 return (
16935 ! empty( $this->_storage->beta_data ) &&
16936 ( true === $this->_storage->beta_data['is_beta'] ) &&
16937 version_compare( $this->_storage->beta_data['version'], $this->get_plugin_version(), '>' )
16938 );
16939 }
16940
16941 /**
16942 * @author Leo Fajardo (@leorw)
16943 * @since 2.3.0
16944 *
16945 * @return bool
16946 */
16947 function is_beta() {
16948 return (
16949 ! empty( $this->_storage->beta_data ) &&
16950 ( true === $this->_storage->beta_data['is_beta'] ) &&
16951 ( $this->get_plugin_version() === $this->_storage->beta_data['version'] )
16952 );
16953 }
16954
16955 /**
16956 * @author Vova Feldman (@svovaf)
16957 * @since 1.1.7.4
16958 *
16959 * @param array $override_with
16960 * @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.
16961 * @param bool $skip_user_info
16962 *
16963 * @return array
16964 */
16965 function get_opt_in_params( $override_with = array(), $network_level_or_blog_id = null, $skip_user_info = false ) {
16966 $this->_logger->entrance();
16967
16968 $activation_action = $this->get_unique_affix() . '_activate_new';
16969 $return_url = $this->is_anonymous() ?
16970 // If skipped already, then return to the account page.
16971 $this->get_account_url( $activation_action, array(), false ) :
16972 // Return to the module's main page.
16973 $this->get_after_activation_url( 'after_connect_url', array( 'fs_action' => $activation_action ) );
16974
16975 $versions = $this->get_versions();
16976
16977 $params = array_merge( $versions, array(
16978 'plugin_slug' => $this->_slug,
16979 'plugin_id' => $this->get_id(),
16980 'plugin_public_key' => $this->get_public_key(),
16981 'plugin_version' => $this->get_plugin_version(),
16982 'return_url' => fs_nonce_url( $return_url, $activation_action ),
16983 'account_url' => fs_nonce_url( $this->_get_admin_page_url(
16984 'account',
16985 array( 'fs_action' => 'sync_user' )
16986 ), 'sync_user' ),
16987 'is_premium' => $this->is_premium(),
16988 'is_active' => true,
16989 'is_uninstalled' => false,
16990 'is_localhost' => WP_FS__IS_LOCALHOST,
16991 ) );
16992
16993 if (
16994 ! $skip_user_info &&
16995 (
16996 empty( $override_with['user_firstname'] ) ||
16997 empty( $override_with['user_lastname'] ) ||
16998 empty( $override_with['user_email'] )
16999 )
17000 ) {
17001 $current_user = self::_get_current_wp_user();
17002
17003 $params['user_firstname'] = $current_user->user_firstname;
17004 $params['user_lastname'] = $current_user->user_lastname;
17005 $params['user_email'] = $current_user->user_email;
17006 }
17007
17008 if ( $this->is_addon() ) {
17009 $parent_fs = $this->get_parent_instance();
17010
17011 $params['parent_plugin_slug'] = $parent_fs->_slug;
17012 $params['parent_plugin_id'] = $parent_fs->get_id();
17013 }
17014
17015 if ( true === $network_level_or_blog_id ) {
17016 if ( ! isset( $override_with['sites'] ) ) {
17017 $params['sites'] = $this->get_sites_for_network_level_optin();
17018 }
17019 } else {
17020 $site = is_numeric( $network_level_or_blog_id ) ?
17021 array( 'blog_id' => $network_level_or_blog_id ) :
17022 null;
17023
17024 $site = $this->get_site_info( $site );
17025
17026 $diagnostic_info = array();
17027 if ( FS_Permission_Manager::instance( $this )->is_diagnostic_tracking_allowed() ) {
17028 $diagnostic_info = array(
17029 'site_name' => $site['title'],
17030 'language' => self::get_sanitized_language( $site['language'] ),
17031 );
17032 }
17033
17034 $params = array_merge( $params, $diagnostic_info, array(
17035 'site_uid' => $site['uid'],
17036 'site_url' => $site['url'],
17037 ) );
17038 }
17039
17040 if ( $this->is_pending_activation() &&
17041 ! empty( $this->_storage->pending_license_key )
17042 ) {
17043 $params['license_key'] = $this->_storage->pending_license_key;
17044 }
17045
17046 if ( WP_FS__SKIP_EMAIL_ACTIVATION && $this->has_secret_key() ) {
17047 // Even though rand() is known for its security issues,
17048 // the timestamp adds another layer of protection.
17049 // It would be very hard for an attacker to get the secret key form here.
17050 // Plus, this should never run in production since the secret should never
17051 // be included in the production version.
17052 $params['ts'] = WP_FS__SCRIPT_START_TIME;
17053 $params['salt'] = md5( uniqid( rand() ) );
17054 $params['secure'] = md5(
17055 $params['ts'] .
17056 $params['salt'] .
17057 $this->get_secret_key()
17058 );
17059 }
17060
17061 if ( is_multisite() && function_exists( 'get_network' ) ) {
17062 $params['network_uid'] = $this->get_anonymous_network_id();
17063 }
17064
17065 return array_merge( $params, $override_with );
17066 }
17067
17068 /**
17069 * 1. If successful opt-in or pending activation returns the next page that the user should be redirected to.
17070 * 2. If there was an API error, return the API result.
17071 *
17072 * @author Vova Feldman (@svovaf)
17073 * @since 1.1.7.4
17074 *
17075 * @param string|bool $email
17076 * @param string|bool $first
17077 * @param string|bool $last
17078 * @param string|bool $license_key
17079 * @param bool $is_uninstall If "true", this means that the module is currently being uninstalled.
17080 * In this case, the user and site info will be sent to the server but no
17081 * data will be saved to the WP installation's database.
17082 * @param number|bool $trial_plan_id
17083 * @param bool $is_disconnected Whether to opt in without tracking.
17084 * @param null|bool $is_marketing_allowed
17085 * @param array $sites If network-level opt-in, an array of containing details of sites.
17086 * @param bool $redirect
17087 * @param null|number $license_owner_id
17088 *
17089 * @return string|object
17090 * @use WP_Error
17091 */
17092 function opt_in(
17093 $email = false,
17094 $first = false,
17095 $last = false,
17096 $license_key = false,
17097 $is_uninstall = false,
17098 $trial_plan_id = false,
17099 $is_disconnected = false,
17100 $is_marketing_allowed = null,
17101 $sites = array(),
17102 $redirect = true,
17103 $license_owner_id = null
17104 ) {
17105 $this->_logger->entrance();
17106
17107 /**
17108 * @since 1.2.1 If activating with license key, ignore the context-user
17109 * since the user will be automatically loaded from the license.
17110 */
17111 if ( empty( $license_key ) ) {
17112 // Clean up pending license if opt-ing in again.
17113 $this->_storage->remove( 'pending_license_key' );
17114
17115 if ( ! $is_uninstall ) {
17116 if ( false === $email ) {
17117 $current_user = self::_get_current_wp_user();
17118 $email = $current_user->user_email;
17119 }
17120
17121 $fs_user = Freemius::_get_user_by_email( $email );
17122 if ( is_object( $fs_user ) && ! $this->is_pending_activation() ) {
17123 return $this->install_with_user(
17124 $fs_user,
17125 false,
17126 $trial_plan_id,
17127 $redirect,
17128 true,
17129 $sites
17130 );
17131 }
17132 }
17133 }
17134
17135 $skip_user_info = ( ! empty( $license_key ) && FS_User::is_valid_id( $license_owner_id ) );
17136
17137 $user_info = array();
17138
17139 if ( ! $skip_user_info ) {
17140 if ( ! empty( $email ) ) {
17141 $user_info['user_email'] = $email;
17142 }
17143
17144 if ( ! empty( $first ) ) {
17145 $user_info['user_firstname'] = $first;
17146 }
17147
17148 if ( ! empty( $last ) ) {
17149 $user_info['user_lastname'] = $last;
17150 }
17151 }
17152
17153 if ( ! empty( $sites ) ) {
17154 $is_network = true;
17155
17156 $user_info['sites'] = $sites;
17157 } else {
17158 $is_network = false;
17159 }
17160
17161 $params = $this->get_opt_in_params( $user_info, $is_network, $skip_user_info );
17162
17163 $filtered_license_key = false;
17164 if ( is_string( $license_key ) ) {
17165 $filtered_license_key = $this->apply_filters( 'license_key', $license_key );
17166 $params['license_key'] = $filtered_license_key;
17167 } else if ( FS_Plugin_Plan::is_valid_id( $trial_plan_id ) ) {
17168 $params['trial_plan_id'] = $trial_plan_id;
17169 }
17170
17171 if ( $is_uninstall ) {
17172 $params['uninstall_params'] = array(
17173 'reason_id' => $this->_storage->uninstall_reason->id,
17174 'reason_info' => $this->_storage->uninstall_reason->info
17175 );
17176 }
17177
17178 if ( isset( $params['license_key'] ) ) {
17179 $fs_user = Freemius::_get_user_by_email( $email );
17180
17181 if ( is_object( $fs_user ) ) {
17182 /**
17183 * If opting in with a context license and the context WP Admin user already opted in
17184 * before from the current site, add the user context security params to avoid the
17185 * unnecessary email activation when the context license is owned by the same context user.
17186 *
17187 * @author Leo Fajardo (@leorw)
17188 * @since 1.2.3
17189 */
17190 $params = array_merge( $params, FS_Security::instance()->get_context_params(
17191 $fs_user,
17192 false,
17193 'install_with_existing_user'
17194 ) );
17195 }
17196 }
17197
17198 if ( is_bool( $is_marketing_allowed ) ) {
17199 $params['is_marketing_allowed'] = $is_marketing_allowed;
17200 }
17201
17202 $params['is_disconnected'] = $is_disconnected;
17203 $params['format'] = 'json';
17204 $params['is_extensions_tracking_allowed'] = FS_Permission_Manager::instance( $this )->is_extensions_tracking_allowed();
17205 $params['is_diagnostic_tracking_allowed'] = FS_Permission_Manager::instance( $this )->is_diagnostic_tracking_allowed();
17206
17207 $request = array(
17208 'method' => 'POST',
17209 'body' => $params,
17210 'timeout' => 60,
17211 );
17212
17213 $url = $this->add_show_pending( WP_FS__ADDRESS . '/action/service/user/install/' );
17214 $response = self::safe_remote_post( $url, $request );
17215
17216 if ( is_wp_error( $response ) ) {
17217 /**
17218 * @var WP_Error $response
17219 */
17220 $result = new stdClass();
17221
17222 $error_code = $response->get_error_code();
17223 $error_type = str_replace( ' ', '', ucwords( str_replace( '_', ' ', $error_code ) ) );
17224
17225 $result->error = (object) array(
17226 'type' => $error_type,
17227 'message' => $response->get_error_message(),
17228 'code' => $error_code,
17229 'http' => 402
17230 );
17231
17232 $this->maybe_modify_api_curl_error_message( $result );
17233
17234 if ( FS_Api::is_blocked( $result ) ) {
17235 $result->error->message = $this->generate_api_blocked_notice_message_from_result( $result );
17236 }
17237
17238 $is_connected = null;
17239
17240 if ( empty( $license_key ) && $this->is_enable_anonymous() ) {
17241 $this->skip_connection( fs_is_network_admin() );
17242
17243 $is_connected = ( ! FS_Api::is_blocked( $result ) );
17244 }
17245
17246 $this->update_connectivity_info( $is_connected );
17247
17248 return $result;
17249 }
17250
17251 $this->update_connectivity_info( true );
17252
17253 // Module is being uninstalled, don't handle the returned data.
17254 if ( $is_uninstall ) {
17255 return true;
17256 }
17257
17258 /**
17259 * 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.
17260 *
17261 * @author Vova Feldman (@svovaf)
17262 * @since 1.2.3
17263 * @link https://themes.trac.wordpress.org/ticket/46134#comment:5
17264 * @link https://themes.trac.wordpress.org/ticket/46134#comment:9
17265 * @link https://themes.trac.wordpress.org/ticket/46134#comment:12
17266 * @link https://themes.trac.wordpress.org/ticket/46134#comment:14
17267 */
17268 $decoded = is_string( $response['body'] ) ?
17269 json_decode( $response['body'] ) :
17270 null;
17271
17272 if ( empty( $decoded ) ) {
17273 return false;
17274 }
17275
17276 if ( ! $this->is_api_result_object( $decoded ) ) {
17277 if ( ! empty( $params['license_key'] ) ) {
17278 // Pass the fully entered license key to the failure handler.
17279 $params['license_key'] = $license_key;
17280 }
17281
17282 return $is_uninstall ?
17283 $decoded :
17284 $this->apply_filters( 'after_install_failure', $decoded, $params );
17285 } else if ( isset( $decoded->pending_activation ) && $decoded->pending_activation ) {
17286 if ( $is_network ) {
17287 $site_ids = array();
17288 foreach ( $sites as $site ) {
17289 $site_ids[] = $site['blog_id'];
17290 }
17291
17292 /**
17293 * Store the sites so that they can be installed once the user has clicked on the activation link
17294 * in the email.
17295 *
17296 * @author Leo Fajardo (@leorw)
17297 */
17298 $this->_storage->pending_sites_info = array(
17299 'blog_ids' => $site_ids,
17300 'license_key' => $license_key,
17301 'trial_plan_id' => $trial_plan_id
17302 );
17303 }
17304
17305 // Pending activation, add message.
17306 return $this->set_pending_confirmation(
17307 ( isset( $decoded->email ) ?
17308 $decoded->email :
17309 true ),
17310 false,
17311 $filtered_license_key,
17312 ! empty( $params['trial_plan_id'] ),
17313 isset( $decoded->is_suspicious_email ) && $decoded->is_suspicious_email
17314 );
17315 } else if ( isset( $decoded->install_secret_key ) ) {
17316 return $this->install_with_new_user(
17317 $decoded->user_id,
17318 $decoded->user_public_key,
17319 $decoded->user_secret_key,
17320 ( isset( $decoded->is_marketing_allowed ) && ! is_null( $decoded->is_marketing_allowed ) ?
17321 $decoded->is_marketing_allowed :
17322 null ),
17323 ( isset( $decoded->is_extensions_tracking_allowed ) && ! is_null( $decoded->is_extensions_tracking_allowed ) ?
17324 $decoded->is_extensions_tracking_allowed :
17325 null ),
17326 ( isset( $decoded->is_diagnostic_tracking_allowed ) && ! is_null( $decoded->is_diagnostic_tracking_allowed ) ?
17327 $decoded->is_diagnostic_tracking_allowed :
17328 null ),
17329 $decoded->install_id,
17330 $decoded->install_public_key,
17331 $decoded->install_secret_key,
17332 false
17333 );
17334 } else if ( is_array( $decoded->installs ) ) {
17335 return $this->install_many_with_new_user(
17336 $decoded->user_id,
17337 $decoded->user_public_key,
17338 $decoded->user_secret_key,
17339 ( isset( $decoded->is_marketing_allowed ) && ! is_null( $decoded->is_marketing_allowed ) ?
17340 $decoded->is_marketing_allowed :
17341 null ),
17342 ( isset( $decoded->is_extensions_tracking_allowed ) && ! is_null( $decoded->is_extensions_tracking_allowed ) ?
17343 $decoded->is_extensions_tracking_allowed :
17344 null ),
17345 ( isset( $decoded->is_diagnostic_tracking_allowed ) && ! is_null( $decoded->is_diagnostic_tracking_allowed ) ?
17346 $decoded->is_diagnostic_tracking_allowed :
17347 null ),
17348 $decoded->installs,
17349 false
17350 );
17351 }
17352
17353 return $decoded;
17354 }
17355
17356 /**
17357 * Set user and site identities.
17358 *
17359 * @author Vova Feldman (@svovaf)
17360 * @since 1.0.9
17361 *
17362 * @param FS_User $user
17363 * @param FS_Site $site
17364 * @param bool $redirect
17365 * @param bool $auto_install Since 1.2.1.7 If `true` and setting up an account with a valid license, will
17366 * redirect (or return a URL) to the account page with a special parameter to
17367 * trigger the auto installation processes.
17368 *
17369 * @return string If redirect is `false`, returns the next page the user should be redirected to.
17370 */
17371 function setup_account(
17372 FS_User $user,
17373 FS_Site $site,
17374 $redirect = true,
17375 $auto_install = false
17376 ) {
17377 return $this->setup_network_account(
17378 $user,
17379 array( $site ),
17380 $redirect,
17381 $auto_install,
17382 false
17383 );
17384 }
17385
17386 /**
17387 * Set user and site identities.
17388 *
17389 * @author Vova Feldman (@svovaf)
17390 * @since 2.0.0
17391 *
17392 * @param FS_User $user
17393 * @param FS_Site[] $installs
17394 * @param bool $redirect
17395 * @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.
17396 * @param bool $is_network_level_opt_in
17397 *
17398 * @return string If redirect is `false`, returns the next page the user should be redirected to.
17399 */
17400 function setup_network_account(
17401 FS_User $user,
17402 array $installs,
17403 $redirect = true,
17404 $auto_install = false,
17405 $is_network_level_opt_in = true
17406 ) {
17407 $first_install = $installs[0];
17408
17409 $this->_user = $user;
17410 $this->_site = $first_install;
17411
17412 $this->_sync_plans();
17413
17414 if ( $this->_storage->handle_gdpr_admin_notice &&
17415 $this->should_handle_gdpr_admin_notice() &&
17416 FS_GDPR_Manager::instance()->should_show_opt_in_notice()
17417 ) {
17418 /**
17419 * Clear user lock after an opt-in.
17420 */
17421 require_once WP_FS__DIR_INCLUDES . '/class-fs-user-lock.php';
17422 FS_User_Lock::instance()->unlock();
17423 }
17424
17425 if ( 1 < count( $installs ) ) {
17426 // Only network level opt-in can have more than one install.
17427 $is_network_level_opt_in = true;
17428 }
17429
17430 $this->update_connectivity_info( true );
17431
17432 // $is_network_level_opt_in = self::is_ajax_action_static( 'network_activate', $this->_module_id );
17433 // If Freemius was OFF before, turn it on.
17434 $this->turn_on();
17435
17436 $this->handle_account_connection(
17437 $installs,
17438 ( ! $this->_is_network_active || ! $is_network_level_opt_in )
17439 );
17440
17441 if ( is_numeric( $first_install->license_id ) ) {
17442 $this->set_license( $this->_get_license_by_id( $first_install->license_id ) );
17443 }
17444
17445 $this->_admin_notices->remove_sticky( 'connect_account' );
17446
17447 if ( $this->is_pending_activation() || ! $this->has_settings_menu() ) {
17448 $this->clear_pending_activation_mode();
17449
17450 if ( ! $this->is_paying_or_trial() ) {
17451 $this->_admin_notices->add_sticky(
17452 sprintf( $this->get_text_inline( '%s opt-in was successfully completed.', 'plugin-x-activation-message' ), '<b>' . $this->get_plugin_name() . '</b>' ),
17453 'activation_complete'
17454 );
17455 }
17456 }
17457
17458 if ( $this->is_paying_or_trial() ) {
17459 if ( ! $this->is_premium() ||
17460 ! $this->has_premium_version() ||
17461 ! $this->has_settings_menu()
17462 ) {
17463 if ( $this->is_paying() ) {
17464 $this->add_complete_upgrade_instructions_notice(
17465 sprintf(
17466 $this->get_text_inline( 'Your account was successfully activated with the %s plan.', 'activation-with-plan-x-message' ),
17467 $this->get_plan_title()
17468 ),
17469 'plan_upgraded'
17470 );
17471 } else {
17472 $trial_plan = $this->get_trial_plan();
17473
17474 $this->add_complete_upgrade_instructions_notice(
17475 sprintf(
17476 $this->get_text_inline( 'Your trial has been successfully started.', 'trial-started-message' ),
17477 '<i>' . $this->get_plugin_name() . '</i>'
17478 ),
17479 'trial_started',
17480 $trial_plan->title
17481 );
17482 }
17483 }
17484
17485 $this->_admin_notices->remove_sticky( array(
17486 'trial_promotion',
17487 ) );
17488 }
17489
17490 $plugin_id = fs_request_get( 'plugin_id', false );
17491
17492 // Store activation time ONLY for plugins & themes (not add-ons).
17493 if ( ! is_numeric( $plugin_id ) || ( $plugin_id == $this->_plugin->id ) ) {
17494 if ( empty( $this->_storage->activation_timestamp ) ) {
17495 $this->_storage->activation_timestamp = WP_FS__SCRIPT_START_TIME;
17496 }
17497 }
17498
17499 $next_page = '';
17500
17501 $extra = array();
17502 if ( $auto_install ) {
17503 $extra['auto_install'] = 'true';
17504 }
17505
17506 if ( is_numeric( $plugin_id ) ) {
17507 /**
17508 * @author Leo Fajardo (@leorw)
17509 * @since 1.2.1.6
17510 *
17511 * Also sync the license after an anonymous user subscribes.
17512 */
17513 if ( $this->is_anonymous() || $plugin_id != $this->_plugin->id ) {
17514 // Add-on was installed - sync license right after install.
17515 $next_page = $this->_get_sync_license_url( $plugin_id, true, $extra );
17516 }
17517 } else {
17518 /**
17519 * @author Vova Feldman (@svovaf)
17520 * @since 1.1.9 If site installed with a valid license, sync license.
17521 */
17522 if ( $this->is_paying() ) {
17523 $this->_sync_plugin_license(
17524 true,
17525 // Installs data is already synced in the beginning of this method directly or via _set_account().
17526 false
17527 );
17528 }
17529
17530 // Reload the page with the keys.
17531 $next_page = $this->is_anonymous() ?
17532 // If user previously skipped, redirect to account page.
17533 $this->get_account_url( false, $extra ) :
17534 $this->get_after_activation_url( 'after_connect_url', array(), $is_network_level_opt_in );
17535 }
17536
17537 if ( ! empty( $next_page ) && $redirect ) {
17538 fs_redirect( $next_page );
17539 }
17540
17541 return $next_page;
17542 }
17543
17544 /**
17545 * Install plugin with new user information after approval.
17546 *
17547 * @author Vova Feldman (@svovaf)
17548 * @since 1.0.7
17549 */
17550 function _install_with_new_user() {
17551 $this->_logger->entrance();
17552
17553 if ( $this->is_registered() ) {
17554 return;
17555 }
17556
17557 $has_pending_activation_confirmation_param = fs_request_has( 'pending_activation' );
17558
17559 $this->update_license_required_permissions_if_anonymous();
17560
17561 if ( ( $this->is_plugin() && fs_request_is_action( $this->get_unique_affix() . '_activate_new' ) ) ||
17562 // @todo This logic should be improved because it's executed on every load of a theme.
17563 $this->is_theme()
17564 ) {
17565 // check_admin_referer( $this->_slug . '_activate_new' );
17566
17567 if ( fs_request_has( 'user_secret_key' ) ) {
17568 if ( fs_is_network_admin() && isset( $this->_storage->pending_sites_info ) ) {
17569 $pending_sites_info = $this->_storage->pending_sites_info;
17570
17571 $this->install_many_pending_with_user(
17572 fs_request_get( 'user_id' ),
17573 fs_request_get_raw( 'user_public_key' ),
17574 fs_request_get_raw( 'user_secret_key' ),
17575 fs_request_get_bool( 'is_marketing_allowed', null ),
17576 fs_request_get_bool( 'is_extensions_tracking_allowed', null ),
17577 fs_request_get_bool( 'is_diagnostic_tracking_allowed', null ),
17578 $pending_sites_info['blog_ids'],
17579 $pending_sites_info['license_key'],
17580 $pending_sites_info['trial_plan_id']
17581 );
17582 } else {
17583 $this->install_with_new_user(
17584 fs_request_get( 'user_id' ),
17585 fs_request_get_raw( 'user_public_key' ),
17586 fs_request_get_raw( 'user_secret_key' ),
17587 fs_request_get_bool( 'is_marketing_allowed', null ),
17588 fs_request_get_bool( 'is_extensions_tracking_allowed', null ),
17589 fs_request_get_bool( 'is_diagnostic_tracking_allowed', null ),
17590 fs_request_get( 'install_id' ),
17591 fs_request_get_raw( 'install_public_key' ),
17592 fs_request_get_raw( 'install_secret_key' ),
17593 true,
17594 fs_request_get_bool( 'auto_install' )
17595 );
17596 }
17597 } else if ( $has_pending_activation_confirmation_param ) {
17598 $this->set_pending_confirmation(
17599 fs_request_get( 'user_email' ),
17600 true,
17601 false,
17602 false,
17603 fs_request_get_bool( 'is_suspicious_email' ),
17604 fs_request_get_bool( 'has_upgrade_context' ),
17605 fs_request_get( 'support_email_address' )
17606 );
17607 }
17608 }
17609 }
17610
17611 /**
17612 * @author Vova Feldman (@svovaf)
17613 * @since 2.0.0
17614 *
17615 * @param number $id
17616 * @param string $public_key
17617 * @param string $secret_key
17618 *
17619 * @return \FS_User
17620 */
17621 private function setup_user( $id, $public_key, $secret_key ) {
17622 $user = self::_get_user_by_id( $id );
17623
17624 if ( is_object( $user ) ) {
17625 $this->_user = $user;
17626 } else {
17627 $user = new FS_User();
17628 $user->id = $id;
17629 $user->public_key = $public_key;
17630 $user->secret_key = $secret_key;
17631
17632 $this->_user = $user;
17633 $user_result = $this->get_api_user_scope()->get();
17634 $user = new FS_User( $user_result );
17635
17636 $this->_user = $user;
17637 $this->_store_user();
17638 }
17639
17640 return $user;
17641 }
17642
17643 /**
17644 * Install plugin with new user.
17645 *
17646 * @author Vova Feldman (@svovaf)
17647 * @since 1.1.7.4
17648 *
17649 * @param number $user_id
17650 * @param string $user_public_key
17651 * @param string $user_secret_key
17652 * @param bool|null $is_marketing_allowed
17653 * @param bool|null $is_extensions_tracking_allowed Since 2.3.2
17654 * @param bool|null $is_diagnostic_tracking_allowed Since 2.5.0.2
17655 * @param number $install_id
17656 * @param string $install_public_key
17657 * @param string $install_secret_key
17658 * @param bool $redirect
17659 * @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.
17660 *
17661 * @return string If redirect is `false`, returns the next page the user should be redirected to.
17662 */
17663 private function install_with_new_user(
17664 $user_id,
17665 $user_public_key,
17666 $user_secret_key,
17667 $is_marketing_allowed,
17668 $is_extensions_tracking_allowed,
17669 $is_diagnostic_tracking_allowed,
17670 $install_id,
17671 $install_public_key,
17672 $install_secret_key,
17673 $redirect = true,
17674 $auto_install = false
17675 ) {
17676 /**
17677 * This method is also executed after opting in with a license key since the
17678 * license can be potentially associated with a different owner.
17679 *
17680 * @since 2.0.0
17681 */
17682 $user = self::_get_user_by_id( $user_id );
17683
17684 if ( ! is_object( $user ) ) {
17685 $user = new FS_User();
17686 $user->id = $user_id;
17687 $user->public_key = $user_public_key;
17688 $user->secret_key = $user_secret_key;
17689
17690 $this->_user = $user;
17691 $user_result = $this->get_api_user_scope()->get();
17692 $user = new FS_User( $user_result );
17693 }
17694
17695 $this->_user = $user;
17696
17697 $site = new FS_Site();
17698 $site->id = $install_id;
17699 $site->public_key = $install_public_key;
17700 $site->secret_key = $install_secret_key;
17701
17702 $this->_site = $site;
17703 $site_result = $this->get_api_site_scope( true )->get();
17704 $site = new FS_Site( $site_result );
17705 $this->_site = $site;
17706
17707 if ( ! is_null( $is_marketing_allowed ) ) {
17708 $this->disable_opt_in_notice_and_lock_user();
17709 }
17710
17711 FS_Permission_Manager::instance( $this )->update_permissions_tracking_flag( array(
17712 FS_Permission_Manager::PERMISSION_DIAGNOSTIC => $is_diagnostic_tracking_allowed,
17713 FS_Permission_Manager::PERMISSION_EXTENSIONS => $is_extensions_tracking_allowed,
17714 ) );
17715
17716 return $this->setup_account(
17717 $this->_user,
17718 $this->_site,
17719 $redirect,
17720 $auto_install
17721 );
17722 }
17723
17724 /**
17725 * Install plugin with user.
17726 *
17727 * @author Leo Fajardo (@leorw)
17728 * @since 2.0.0
17729 *
17730 * @param number $user_id
17731 * @param string $user_public_key
17732 * @param string $user_secret_key
17733 * @param bool|null $is_marketing_allowed
17734 * @param bool|null $is_extensions_tracking_allowed Since 2.3.2
17735 * @param bool|null $is_diagnostic_tracking_allowed Since 2.5.0.2
17736 * @param array $site_ids
17737 * @param bool $license_key
17738 * @param bool $trial_plan_id
17739 * @param bool $redirect
17740 *
17741 * @return void
17742 */
17743 private function install_many_pending_with_user(
17744 $user_id,
17745 $user_public_key,
17746 $user_secret_key,
17747 $is_marketing_allowed,
17748 $is_extensions_tracking_allowed,
17749 $is_diagnostic_tracking_allowed,
17750 $site_ids,
17751 $license_key = false,
17752 $trial_plan_id = false,
17753 $redirect = true
17754 ) {
17755 $user = $this->setup_user( $user_id, $user_public_key, $user_secret_key );
17756
17757 if ( ! is_null( $is_marketing_allowed ) ) {
17758 $this->disable_opt_in_notice_and_lock_user();
17759 }
17760
17761 FS_Permission_Manager::instance( $this )->update_permissions_tracking_flag( array(
17762 FS_Permission_Manager::PERMISSION_DIAGNOSTIC => $is_diagnostic_tracking_allowed,
17763 FS_Permission_Manager::PERMISSION_EXTENSIONS => $is_extensions_tracking_allowed,
17764 ) );
17765
17766 $sites = array();
17767 foreach ( $site_ids as $site_id ) {
17768 $sites[] = $this->get_site_info( array( 'blog_id' => $site_id ) );
17769 }
17770
17771 $this->install_with_user( $user, $license_key, $trial_plan_id, $redirect, true, $sites );
17772 }
17773
17774 /**
17775 * Multi-site install with a new user.
17776 *
17777 * @author Vova Feldman (@svovaf)
17778 * @since 2.0.0
17779 *
17780 * @param number $user_id
17781 * @param string $user_public_key
17782 * @param string $user_secret_key
17783 * @param bool|null $is_marketing_allowed
17784 * @param bool|null $is_extensions_tracking_allowed Since 2.3.2
17785 * @param bool|null $is_diagnostic_tracking_allowed Since 2.5.0.2
17786 * @param object[] $installs
17787 * @param bool $redirect
17788 * @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.
17789 *
17790 * @return string If redirect is `false`, returns the next page the user should be redirected to.
17791 */
17792 private function install_many_with_new_user(
17793 $user_id,
17794 $user_public_key,
17795 $user_secret_key,
17796 $is_marketing_allowed,
17797 $is_extensions_tracking_allowed,
17798 $is_diagnostic_tracking_allowed,
17799 array $installs,
17800 $redirect = true,
17801 $auto_install = false
17802 ) {
17803 $this->setup_user( $user_id, $user_public_key, $user_secret_key );
17804
17805 if ( ! is_null( $is_marketing_allowed ) ) {
17806 $this->disable_opt_in_notice_and_lock_user();
17807 }
17808
17809 FS_Permission_Manager::instance( $this )->update_permissions_tracking_flag( array(
17810 FS_Permission_Manager::PERMISSION_DIAGNOSTIC => $is_diagnostic_tracking_allowed,
17811 FS_Permission_Manager::PERMISSION_EXTENSIONS => $is_extensions_tracking_allowed,
17812 ) );
17813
17814 $install_ids = array();
17815
17816 foreach ( $installs as $install ) {
17817 $install_ids[] = $install->id;
17818 }
17819
17820 $items_per_request = 25;
17821 $left = count( $install_ids );
17822 $offset = 0;
17823
17824 $installs = array();
17825 while ( $left > 0 ) {
17826 $result = $this->get_api_user_scope()->get( "/plugins/{$this->_module_id}/installs.json?ids=" . implode( ',', array_slice( $install_ids, $offset, $items_per_request ) ) );
17827
17828 if ( ! $this->is_api_result_object( $result, 'installs' ) ) {
17829 // @todo Handle API error.
17830 }
17831
17832 $installs = array_merge( $installs, $result->installs );
17833
17834 $left -= $items_per_request;
17835 $offset += $items_per_request;
17836 }
17837
17838 foreach ( $installs as &$install ) {
17839 $install = new FS_Site( $install );
17840 }
17841
17842 return $this->setup_network_account(
17843 $this->_user,
17844 $installs,
17845 $redirect,
17846 $auto_install
17847 );
17848 }
17849
17850 /**
17851 * @author Vova Feldman (@svovaf)
17852 * @since 1.1.7.4
17853 *
17854 * @param string|bool $email
17855 * @param bool $redirect
17856 * @param string|bool $license_key Since 1.2.1.5
17857 * @param bool $is_pending_trial Since 1.2.1.5
17858 * @param bool $is_suspicious_email Since 2.5.0
17859 * @param bool $has_upgrade_context Since 2.5.3
17860 * @param bool|string $support_email_address Since 2.5.3
17861 *
17862 * @return string Since 1.2.1.5 if $redirect is `false`, return the pending activation page.
17863 */
17864 private function set_pending_confirmation(
17865 $email = false,
17866 $redirect = true,
17867 $license_key = false,
17868 $is_pending_trial = false,
17869 $is_suspicious_email = false,
17870 $has_upgrade_context = false,
17871 $support_email_address = false
17872 ) {
17873 $is_network_admin = fs_is_network_admin();
17874
17875 if ( $this->_ignore_pending_mode && ! $has_upgrade_context ) {
17876 /**
17877 * If explicitly asked to ignore pending mode, set to anonymous mode
17878 * 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).
17879 *
17880 * @author Vova Feldman
17881 * @since 1.2.1.6
17882 */
17883 $this->skip_connection( $is_network_admin );
17884 } else {
17885 // Install must be activated via email since
17886 // user with the same email already exist.
17887 $this->_storage->is_pending_activation = true;
17888 $this->_add_pending_activation_notice(
17889 $email,
17890 $is_pending_trial,
17891 $is_suspicious_email,
17892 $has_upgrade_context,
17893 $support_email_address
17894 );
17895 }
17896
17897 if ( ! empty( $license_key ) ) {
17898 $this->_storage->pending_license_key = $license_key;
17899 }
17900
17901 // Remove the opt-in sticky notice.
17902 $this->_admin_notices->remove_sticky( array(
17903 'connect_account',
17904 'trial_promotion',
17905 ) );
17906
17907 $next_page = $this->get_after_activation_url( 'after_pending_connect_url' );
17908
17909 if ( $redirect ) {
17910 // Reload the page with a pending activation message.
17911 fs_redirect( $next_page );
17912 }
17913
17914 return $next_page;
17915 }
17916
17917 /**
17918 * Install plugin with current logged WP user info.
17919 *
17920 * @author Vova Feldman (@svovaf)
17921 * @since 1.0.7
17922 */
17923 function _install_with_current_user() {
17924 $this->_logger->entrance();
17925
17926 if ( $this->is_registered() ) {
17927 return;
17928 }
17929
17930 if ( fs_request_is_action( $this->get_unique_affix() . '_activate_existing' ) && fs_request_is_post() ) {
17931 check_admin_referer( $this->get_unique_affix() . '_activate_existing' );
17932
17933 /**
17934 * @author Vova Feldman (@svovaf)
17935 * @since 1.1.9 Add license key if given.
17936 */
17937 $license_key = fs_request_get_raw( 'license_secret_key' );
17938
17939 FS_Permission_Manager::instance( $this )->update_permissions_tracking_flag( array(
17940 FS_Permission_Manager::PERMISSION_DIAGNOSTIC => fs_request_get_bool( 'is_diagnostic_tracking_allowed', null ),
17941 FS_Permission_Manager::PERMISSION_EXTENSIONS => fs_request_get_bool( 'is_extensions_tracking_allowed', null ),
17942 ) );
17943
17944 $this->install_with_current_user( $license_key );
17945 }
17946 }
17947
17948
17949 /**
17950 * @author Vova Feldman (@svovaf)
17951 * @since 1.1.7.4
17952 *
17953 * @param string|bool $license_key
17954 * @param number|bool $trial_plan_id
17955 * @param array $sites Since 2.0.0
17956 * @param bool $redirect
17957 *
17958 * @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.
17959 */
17960 function install_with_current_user(
17961 $license_key = false,
17962 $trial_plan_id = false,
17963 $sites = array(),
17964 $redirect = true
17965 ) {
17966 // Get current logged WP user.
17967 $current_user = self::_get_current_wp_user();
17968
17969 // Find the relevant FS user by the email.
17970 $user = self::_get_user_by_email( $current_user->user_email );
17971
17972 return $this->install_with_user( $user, $license_key, $trial_plan_id, $redirect, true, $sites );
17973 }
17974
17975 /**
17976 * @author Vova Feldman (@svovaf)
17977 * @since 2.0.0
17978 *
17979 * @param \FS_User $user
17980 * @param string|bool $license_key
17981 * @param number|bool $trial_plan_id
17982 * @param bool $redirect
17983 * @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.
17984 * @param array $sites Since 2.0.0. If not empty, should be a collection of site details for the bulk install API request.
17985 *
17986 * @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.
17987 */
17988 function install_with_user(
17989 FS_User $user,
17990 $license_key = false,
17991 $trial_plan_id = false,
17992 $redirect = true,
17993 $setup_account = true,
17994 $sites = array()
17995 ) {
17996 // We have to set the user before getting user scope API handler.
17997 $this->_user = $user;
17998
17999 // Install the plugin.
18000 $result = $this->create_installs_with_user(
18001 $user,
18002 $license_key,
18003 $trial_plan_id,
18004 $sites,
18005 $redirect
18006 );
18007
18008 if ( ! $this->is_api_result_entity( $result ) &&
18009 ! $this->is_api_result_object( $result, 'installs' )
18010 ) {
18011 // @todo Handler potential API error of the $result
18012 }
18013
18014 if ( empty( $sites ) ) {
18015 $site = new FS_Site( $result );
18016 $this->_site = $site;
18017
18018 if ( ! $setup_account ) {
18019 $this->_store_site();
18020
18021 $this->sync_plan_if_not_exist( $site->plan_id );
18022
18023 if ( ! empty( $license_key ) && FS_Plugin_License::is_valid_id( $site->license_id ) ) {
18024 $this->sync_license_if_not_exist( $site->license_id, $license_key );
18025 }
18026
18027 $this->_admin_notices->remove_sticky( 'connect_account', false );
18028
18029 return $site;
18030 }
18031
18032 return $this->setup_account( $this->_user, $this->_site, $redirect );
18033 } else {
18034 $installs = array();
18035 foreach ( $result->installs as $install ) {
18036 $installs[] = new FS_Site( $install );
18037 }
18038
18039 return $this->setup_network_account(
18040 $user,
18041 $installs,
18042 $redirect
18043 );
18044 }
18045 }
18046
18047 /**
18048 * Initiate an API request to create a collection of installs.
18049 *
18050 * @author Vova Feldman (@svovaf)
18051 * @since 2.0.0
18052 *
18053 * @param \FS_User $user
18054 * @param bool $license_key
18055 * @param bool $trial_plan_id
18056 * @param array $sites
18057 * @param bool $redirect
18058 * @param bool $silent
18059 *
18060 * @return object|mixed
18061 */
18062 private function create_installs_with_user(
18063 FS_User $user,
18064 $license_key = false,
18065 $trial_plan_id = false,
18066 $sites = array(),
18067 $redirect = false,
18068 $silent = false
18069 ) {
18070 $extra_install_params = array(
18071 'uid' => $this->get_anonymous_id(),
18072 'is_disconnected' => false,
18073 );
18074
18075 if ( ! empty( $license_key ) ) {
18076 $extra_install_params['license_key'] = $this->apply_filters( 'license_key', $license_key );
18077
18078 if ( $silent ) {
18079 $extra_install_params['ignore_license_owner'] = true;
18080 }
18081 } else if ( FS_Plugin_Plan::is_valid_id( $trial_plan_id ) ) {
18082 $extra_install_params['trial_plan_id'] = $trial_plan_id;
18083 }
18084
18085 if ( ! empty( $sites ) ) {
18086 $extra_install_params['sites'] = $sites;
18087 }
18088
18089 $args = $this->get_install_data_for_api( $extra_install_params, false, false );
18090
18091 // Install the plugin.
18092 $result = $this->get_api_user_scope_by_user( $user )->call(
18093 "/plugins/{$this->get_id()}/installs.json",
18094 'post',
18095 $args
18096 );
18097
18098 if ( ! $this->is_api_result_entity( $result ) &&
18099 ! $this->is_api_result_object( $result, 'installs' )
18100 ) {
18101 if ( ! empty( $args['license_key'] ) ) {
18102 // Pass the fully entered license key to the failure handler.
18103 $args['license_key'] = $license_key;
18104 }
18105
18106 $result = $this->apply_filters( 'after_install_failure', $result, $args );
18107
18108 if ( ! $silent ) {
18109 $this->_admin_notices->add(
18110 sprintf( $this->get_text_inline( 'Couldn\'t activate %s.', 'could-not-activate-x' ), $this->get_plugin_name() ) . ' ' .
18111 $this->get_text_inline( 'Please contact us with the following message:', 'contact-us-with-error-message' ) . ' ' . '<b>' . $result->error->message . '</b>',
18112 $this->get_text_x_inline( 'Oops', 'exclamation', 'oops' ) . '...',
18113 'error'
18114 );
18115 }
18116
18117 if ( $redirect ) {
18118 /**
18119 * We set the user before getting the user scope API handler, so the user became temporarily
18120 * registered (`is_registered() = true`). Since the API returned an error and we will redirect,
18121 * we have to set the user to `null`, otherwise, the user will be redirected to the wrong
18122 * activation page based on the return value of `is_registered()`. In addition, in case the
18123 * context plugin doesn't have a settings menu and the default page is the `Plugins` page,
18124 * misleading plugin activation errors will be shown on the `Plugins` page.
18125 *
18126 * @author Leo Fajardo (@leorw)
18127 */
18128 $user = $this->_user;
18129
18130 $this->_user = null;
18131
18132 fs_redirect( $this->get_activation_url( array( 'error' => $result->error->message ) ) );
18133
18134 /**
18135 * Restore the user after the redirect, this is relevant when there are cases where the redirect will choose not to do anything.
18136 */
18137 $this->_user = $user;
18138 }
18139 }
18140
18141 return $result;
18142 }
18143
18144 /**
18145 * Tries to activate add-on account based on parent plugin info.
18146 *
18147 * @author Vova Feldman (@svovaf)
18148 * @since 1.0.6
18149 *
18150 * @param Freemius $parent_fs
18151 * @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.
18152 * @param FS_Plugin_License $bundle_license Since 2.4.0. If provided, this license will be activated for the add-on.
18153 */
18154 private function _activate_addon_account(
18155 Freemius $parent_fs,
18156 $network_level_or_blog_id = null,
18157 $bundle_license = null
18158 ) {
18159 if ( $this->is_registered() ) {
18160 // Already activated.
18161 return;
18162 }
18163
18164 $permission_ids = FS_Permission_Manager::get_all_permission_ids();
18165 $permissions = array();
18166 foreach ( $permission_ids as $permission_id ) {
18167 $permissions[ $permission_id ] = FS_Permission_Manager::instance( $parent_fs )->is_permission( $permission_id, true );
18168 }
18169
18170 FS_Permission_Manager::instance( $this )->update_permissions_tracking_flag( $permissions );
18171
18172 /**
18173 * Do not override the `uid` if network-level opt-in since the call to `get_sites_for_network_level_optin()`
18174 * already returns the data for the current blog.
18175 *
18176 * @author Leo Fajardo (@leorw)
18177 * @since 2.3.0
18178 */
18179 $uid_param_to_override = ( true === $network_level_or_blog_id ) ?
18180 array() :
18181 array( 'uid' => $this->get_anonymous_id() );
18182
18183 $params = $this->get_install_data_for_api(
18184 $uid_param_to_override,
18185 false,
18186 false,
18187 /**
18188 * Do not include the data for the current blog if network-level opt-in since the call to `get_sites_for_network_level_optin`
18189 * already includes the data for it.
18190 *
18191 * @author Leo Fajardo (@leorw)
18192 * @since 2.3.0
18193 */
18194 ( true !== $network_level_or_blog_id )
18195 );
18196
18197 if ( true === $network_level_or_blog_id ) {
18198 $params['sites'] = $this->get_sites_for_network_level_optin();
18199
18200 if ( empty( $params['sites'] ) ) {
18201 return;
18202 }
18203 }
18204
18205 if ( is_object( $bundle_license ) ) {
18206 $params['license_key'] = $bundle_license->secret_key;
18207 }
18208
18209 // Activate add-on with parent plugin credentials.
18210 $result = $parent_fs->get_api_site_scope()->call(
18211 "/addons/{$this->_plugin->id}/installs.json",
18212 'post',
18213 $params
18214 );
18215
18216 if ( ! $this->is_api_result_object( $result, 'installs' ) ) {
18217 if ( is_object( $bundle_license ) ) {
18218 /**
18219 * 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.
18220 *
18221 * @author Leo Fajardo (@leorw)
18222 * @since 2.4.0
18223 */
18224 } else {
18225 $error_message = FS_Api::is_api_error_object( $result ) ?
18226 $result->error->message :
18227 $this->get_text_inline( 'An unknown error has occurred.', 'unknown-error' );
18228
18229 $this->_admin_notices->add(
18230 sprintf( $this->get_text_inline( 'Couldn\'t activate %s.', 'could-not-activate-x' ), $this->get_plugin_name() ) . ' ' .
18231 $this->get_text_inline( 'Please contact us with the following message:', 'contact-us-with-error-message' ) . ' ' . '<b>' . $error_message . '</b>',
18232 $this->get_text_x_inline( 'Oops', 'exclamation', 'oops' ) . '...',
18233 'error'
18234 );
18235 }
18236
18237 return;
18238 }
18239
18240 $addon_installs = $result->installs;
18241 foreach ( $addon_installs as $key => $addon_install ) {
18242 $addon_installs[ $key ] = new FS_Site( $addon_install );
18243 }
18244
18245 $first_install = $addon_installs[0];
18246
18247 // Get user information based on parent's plugin.
18248 $user = $parent_fs->get_user();
18249
18250 // First of all, set site and user info - otherwise we won't
18251 // be able to invoke API calls.
18252 $this->_site = $first_install;
18253 $this->_user = $user;
18254
18255 // Sync add-on plans.
18256 $this->_sync_plans();
18257
18258 $this->handle_account_connection( $addon_installs, ! fs_is_network_admin() );
18259
18260 // Get site's current plan.
18261 //$this->_site->plan = $this->_get_plan_by_id( $this->_site->plan->id );
18262
18263 // Sync licenses.
18264 $this->_sync_licenses();
18265
18266 if ( ! fs_is_network_admin() ) {
18267 // Try to activate premium license.
18268 $this->_activate_license( true, $bundle_license );
18269
18270 if ( is_object( $bundle_license ) ) {
18271 $this->maybe_activate_bundle_license( $bundle_license );
18272 }
18273 } else {
18274 if ( is_object( $bundle_license ) ) {
18275 $premium_license = $bundle_license;
18276 } else {
18277 $license_id = fs_request_get( 'license_id' );
18278
18279 if ( is_object( $this->_site ) &&
18280 FS_Plugin_License::is_valid_id( $license_id ) &&
18281 $license_id == $this->_site->license_id
18282 ) {
18283 // License is already activated.
18284 return;
18285 }
18286
18287 $premium_license = FS_Plugin_License::is_valid_id( $license_id ) ?
18288 $this->_get_license_by_id( $license_id ) :
18289 $this->_get_available_premium_license();
18290 }
18291
18292 if ( is_object( $premium_license ) ) {
18293 $this->maybe_network_activate_addon_license( $premium_license );
18294 }
18295 }
18296 }
18297
18298 /**
18299 * @author Leo Fajardo (@leorw)
18300 * @since 2.3.0
18301 *
18302 * @param FS_Site[] $installs
18303 * @param bool $is_site_level
18304 */
18305 private function handle_account_connection( $installs, $is_site_level ) {
18306 $first_install = $installs[0];
18307
18308 if ( $is_site_level ) {
18309 $this->_set_account( $this->_user, $first_install );
18310
18311 $this->do_action( 'after_account_connection', $this->_user, $first_install );
18312 } else {
18313 $this->_store_user();
18314
18315 // Map site addresses to their blog IDs.
18316 $address_to_blog_map = $this->get_address_to_blog_map();
18317
18318 $first_blog_id = null;
18319 $blog_2_install_map = array();
18320 foreach ( $installs as $install ) {
18321 $address = trailingslashit( fs_strip_url_protocol( $install->url ) );
18322 $blog_id = $address_to_blog_map[ $address ];
18323
18324 $this->_store_site( true, $blog_id, $install );
18325
18326 if ( is_null( $first_blog_id ) ) {
18327 $first_blog_id = $blog_id;
18328 }
18329
18330 $blog_2_install_map[ $blog_id ] = $install;
18331 }
18332
18333 if ( ! FS_User::is_valid_id( $this->_storage->network_user_id ) ||
18334 ! is_object( self::_get_user_by_id( $this->_storage->network_user_id ) )
18335 ) {
18336 // Store network user.
18337 $this->_storage->network_user_id = $this->_user->id;
18338 }
18339
18340 if ( ! FS_Site::is_valid_id( $this->_storage->network_install_blog_id ) ) {
18341 $this->_storage->network_install_blog_id = $first_blog_id;
18342 }
18343
18344 if ( count( $installs ) === count( $address_to_blog_map ) ) {
18345 // Super admin opted in for all sites in the network.
18346 $this->_storage->is_network_connected = true;
18347 }
18348
18349 $this->_store_licenses( false );
18350
18351 self::$_accounts->store();
18352
18353 // Don't sync the installs data on network upgrade
18354 if ( ! $this->network_upgrade_mode_completed() ) {
18355 $this->send_installs_update();
18356 }
18357
18358 $current_blog = get_current_blog_id();
18359
18360 foreach ( $blog_2_install_map as $blog_id => $install ) {
18361 $this->switch_to_blog( $blog_id );
18362
18363 $this->do_action( 'after_account_connection', $this->_user, $install );
18364 }
18365
18366 // Switch install context back to the first install.
18367 $this->switch_to_blog(
18368 $current_blog,
18369 $first_install,
18370 ( $this->_site->id != $first_install->id )
18371 );
18372
18373 $this->do_action( 'after_network_account_connection', $this->_user, $blog_2_install_map );
18374 }
18375 }
18376
18377 /**
18378 * Tries to activate parent account based on add-on's info.
18379 *
18380 * @author Vova Feldman (@svovaf)
18381 * @since 1.2.2.7
18382 *
18383 * @param Freemius $parent_fs
18384 */
18385 private function activate_parent_account( Freemius $parent_fs ) {
18386 if ( ! $this->is_addon() ) {
18387 // This is not an add-on.
18388 return;
18389 }
18390
18391 if ( $parent_fs->is_registered() ) {
18392 // Already activated.
18393 return;
18394 }
18395
18396 // Activate parent with add-on's user credentials.
18397 $parent_install = $this->get_api_user_scope()->call(
18398 "/plugins/{$parent_fs->_plugin->id}/installs.json",
18399 'post',
18400 $parent_fs->get_install_data_for_api( array(
18401 'uid' => $parent_fs->get_anonymous_id(),
18402 ), false, false )
18403 );
18404
18405 if ( isset( $parent_install->error ) ) {
18406 $this->_admin_notices->add(
18407 sprintf( $this->get_text_inline( 'Couldn\'t activate %s.', 'could-not-activate-x' ), $this->get_plugin_name() ) . ' ' .
18408 $this->get_text_inline( 'Please contact us with the following message:', 'contact-us-with-error-message' ) . ' ' . '<b>' . $parent_install->error->message . '</b>',
18409 $this->get_text_x_inline( 'Oops', 'exclamation', 'oops' ) . '...',
18410 'error'
18411 );
18412
18413 return;
18414 }
18415
18416 $parent_fs->_admin_notices->remove_sticky( 'connect_account' );
18417
18418 if ( $parent_fs->is_pending_activation() ) {
18419 $parent_fs->clear_pending_activation_mode();
18420 }
18421
18422 // Get user information based on parent's plugin.
18423 $user = $this->get_user();
18424
18425 // First of all, set site info - otherwise we won't
18426 // be able to invoke API calls.
18427 $parent_fs->_site = new FS_Site( $parent_install );
18428 $parent_fs->_user = $user;
18429
18430 // Sync add-on plans.
18431 $parent_fs->_sync_plans();
18432
18433 $parent_fs->update_license_required_permissions_if_anonymous();
18434
18435 $parent_fs->_set_account( $user, $parent_fs->_site );
18436 }
18437
18438 #endregion
18439
18440 #----------------------------------------------------------------------------------
18441 #region Admin Menu Items
18442 #----------------------------------------------------------------------------------
18443
18444 private $_menu_items = array();
18445
18446 /**
18447 * @author Vova Feldman (@svovaf)
18448 * @since 1.2.1.8
18449 *
18450 * @return array
18451 */
18452 function get_menu_items() {
18453 return $this->_menu_items;
18454 }
18455
18456 /**
18457 * @author Vova Feldman (@svovaf)
18458 * @since 1.0.7
18459 *
18460 * @return string
18461 */
18462 function get_menu_slug() {
18463 return $this->_menu->get_slug();
18464 }
18465
18466 /**
18467 * @author Vova Feldman (@svovaf)
18468 * @since 1.0.9
18469 */
18470 function _prepare_admin_menu() {
18471 // if ( ! $this->is_on() ) {
18472 // return;
18473 // }
18474
18475 if ( is_object( $this->_site ) && ! $this->is_registered() ) {
18476 return;
18477 }
18478
18479 /**
18480 * When running from a site admin with a network activated module and the connection
18481 * was NOT delegated and the user still haven't skipped or opted-in, then hide the
18482 * site level settings.
18483 *
18484 * @author Vova Feldman (@svovaf)
18485 * @since 2.0.0
18486 */
18487 $should_hide_site_admin_settings = (
18488 $this->_is_network_active &&
18489 ! fs_is_network_admin() &&
18490 ! $this->is_delegated_connection() &&
18491 ! $this->is_anonymous() &&
18492 ! $this->is_registered()
18493 );
18494
18495 $should_hide_site_admin_settings = $this->apply_filters( 'should_hide_site_admin_settings_on_network_activation_mode', $should_hide_site_admin_settings );
18496
18497 if ( ( false === $this->has_api_connectivity() && ! $this->is_enable_anonymous() ) ||
18498 $should_hide_site_admin_settings
18499 ) {
18500 $this->_menu->remove_menu_item( $should_hide_site_admin_settings );
18501 } else {
18502 $this->do_action( fs_is_network_admin() ?
18503 'before_network_admin_menu_init' :
18504 'before_admin_menu_init'
18505 );
18506
18507 $this->add_menu_action();
18508
18509 $this->add_network_menu_when_missing();
18510
18511 $this->add_submenu_items();
18512 }
18513 }
18514
18515 /**
18516 * Admin dashboard menu items modifications.
18517 *
18518 * NOTE: admin_menu action executed before admin_init.
18519 *
18520 * @author Vova Feldman (@svovaf)
18521 * @since 1.0.7
18522 *
18523 */
18524 private function add_menu_action() {
18525 if ( $this->is_activation_mode() ) {
18526 if ( $this->show_opt_in_on_setting_page() ) {
18527 $this->override_plugin_menu_with_activation();
18528 } else {
18529 /**
18530 * Handle theme opt-in when the opt-in form shows as a dialog box in the themes page.
18531 */
18532 if ( fs_request_is_action( $this->get_unique_affix() . '_activate_existing' ) ) {
18533 add_action( 'load-themes.php', array( &$this, '_install_with_current_user' ) );
18534 } else if ( fs_request_is_action( $this->get_unique_affix() . '_activate_new' ) ||
18535 fs_request_get_bool( 'pending_activation' )
18536 ) {
18537 add_action( 'load-themes.php', array( &$this, '_install_with_new_user' ) );
18538 }
18539 }
18540 } else {
18541 if ( ! $this->is_registered() ) {
18542 // If not registered try to install user.
18543 if ( fs_request_is_action( $this->get_unique_affix() . '_activate_new' ) ) {
18544 $this->_install_with_new_user();
18545 }
18546 } else if (
18547 fs_request_is_action( 'sync_user' ) &&
18548 ( ! $this->has_settings_menu() || $this->show_opt_in_on_themes_page() )
18549 ) {
18550 $this->_handle_account_user_sync();
18551 }
18552 }
18553 }
18554
18555 /**
18556 * @author Vova Feldman (@svovaf)
18557 * @since 1.0.1
18558 */
18559 function _redirect_on_clicked_menu_link() {
18560 $this->_logger->entrance();
18561
18562 $page = fs_request_get('page');
18563 $page = is_string($page) ? strtolower($page) : '';
18564
18565 $this->_logger->log( 'page = ' . $page );
18566
18567 foreach ( $this->_menu_items as $priority => $items ) {
18568 foreach ( $items as $item ) {
18569 if ( isset( $item['url'] ) ) {
18570 if ( $page === $this->_menu->get_slug( strtolower( $item['menu_slug'] ) ) ) {
18571 $this->_logger->log( 'Redirecting to ' . $item['url'] );
18572
18573 fs_redirect( $item['url'] );
18574 }
18575 }
18576 }
18577 }
18578 }
18579
18580 /**
18581 * Remove plugin's all admin menu items & pages, and replace with activation page.
18582 *
18583 * @author Vova Feldman (@svovaf)
18584 * @since 1.0.1
18585 */
18586 private function override_plugin_menu_with_activation() {
18587 $this->_logger->entrance();
18588
18589 $hook = false;
18590
18591 if ( ! $this->has_settings_menu() ) {
18592 // Add the opt-in page without a menu item.
18593 $hook = FS_Admin_Menu_Manager::add_subpage(
18594 '',
18595 $this->get_plugin_name(),
18596 $this->get_plugin_name(),
18597 'manage_options',
18598 $this->_slug,
18599 array( &$this, '_connect_page_render' )
18600 );
18601 } else if ( $this->_menu->is_top_level() ) {
18602 if ( $this->_menu->is_override_exact() ) {
18603 // Make sure the current page is matching the activation page.
18604 if ( ! $this->is_matching_url( $this->get_activation_url() ) ) {
18605 return;
18606 }
18607 }
18608
18609 $hook = $this->_menu->override_menu_item( array( &$this, '_connect_page_render' ) );
18610
18611 if ( false === $hook ) {
18612 // Create new menu item just for the opt-in.
18613 $hook = FS_Admin_Menu_Manager::add_page(
18614 $this->get_plugin_name(),
18615 $this->get_plugin_name(),
18616 'manage_options',
18617 $this->_menu->get_slug(),
18618 array( &$this, '_connect_page_render' )
18619 );
18620 }
18621 } else {
18622 $menus = array( $this->_menu->get_parent_slug() );
18623
18624 if ( $this->_menu->is_override_exact() ) {
18625 // Make sure the current page is matching the activation page.
18626 if ( ! $this->is_matching_url( $this->get_activation_url() ) ) {
18627 return;
18628 }
18629 }
18630
18631 foreach ( $menus as $parent_slug ) {
18632 $hook = $this->_menu->override_submenu_action(
18633 $parent_slug,
18634 $this->_menu->get_raw_slug(),
18635 array( &$this, '_connect_page_render' )
18636 );
18637
18638 if ( false !== $hook ) {
18639 // Found plugin's submenu item.
18640 break;
18641 }
18642 }
18643 }
18644
18645 if ( $this->is_activation_page() ) {
18646 // Clean admin page from distracting content.
18647 self::_clean_admin_content_section();
18648 }
18649
18650 if ( false !== $hook ) {
18651 if ( fs_request_is_action( $this->get_unique_affix() . '_activate_existing' ) ) {
18652 $this->_install_with_current_user();
18653 } else if ( fs_request_is_action( $this->get_unique_affix() . '_activate_new' ) ) {
18654 $this->_install_with_new_user();
18655 }
18656 }
18657 }
18658
18659 /**
18660 * If a plugin was network activated and connected but don't have a network
18661 * level settings, then add an artificial menu item for the Account and other
18662 * Freemius settings.
18663 *
18664 * @author Vova Feldman (@svovaf)
18665 * @since 2.0.0
18666 */
18667 private function add_network_menu_when_missing() {
18668 $this->_logger->entrance();
18669
18670 if ( ! $this->_is_network_active ) {
18671 // Plugin wasn't activated on the network level.
18672 return;
18673 }
18674
18675 if ( ! fs_is_network_admin() ) {
18676 // The context is not the network admin.
18677 return;
18678 }
18679
18680 if ( $this->_menu->has_network_menu() ) {
18681 // Plugin already has a network level menu.
18682 return;
18683 }
18684
18685 if ( $this->is_network_activation_mode() ) {
18686 /**
18687 * Do not add during activation mode, otherwise, there will be duplicate menus while the opt-in
18688 * screen is being shown.
18689 *
18690 * @author Leo Fajardo (@leorw)
18691 */
18692 return;
18693 }
18694
18695 if ( ! WP_FS__SHOW_NETWORK_EVEN_WHEN_DELEGATED ) {
18696 if ( $this->is_network_delegated_connection() ) {
18697 // Super-admin delegated the connection to the site admins.
18698 return;
18699 }
18700 }
18701
18702 if ( ! $this->_menu->has_menu() || $this->_menu->is_top_level() ) {
18703
18704 if ( $this->_menu->has_menu() ||
18705 ! $this->is_addon() ||
18706 $this->is_activation_mode()
18707 ) {
18708 $this->_dynamically_added_top_level_page_hook_name = $this->_menu->add_page_and_update(
18709 $this->get_plugin_name(),
18710 $this->get_plugin_name(),
18711 'manage_options',
18712 $this->_menu->has_menu() ? $this->_menu->get_slug() : $this->_slug
18713 );
18714 }
18715 } else {
18716 $this->_menu->add_subpage_and_update(
18717 $this->_menu->get_parent_slug(),
18718 $this->get_plugin_name(),
18719 $this->get_plugin_name(),
18720 'manage_options',
18721 $this->_menu->get_slug()
18722 );
18723 }
18724 }
18725
18726 /**
18727 * @author Leo Fajardo (@leorw)
18728 * @since 1.2.1
18729 *
18730 * return string
18731 */
18732 function get_top_level_menu_capability() {
18733 global $menu;
18734
18735 $top_level_menu_slug = $this->get_top_level_menu_slug();
18736
18737 foreach ( $menu as $menu_info ) {
18738 /**
18739 * The second element in the menu info array is the capability/role that has access to the menu and the
18740 * third element is the menu slug.
18741 */
18742 if ( $menu_info[2] === $top_level_menu_slug ) {
18743 return $menu_info[1];
18744 }
18745 }
18746
18747 return 'read';
18748 }
18749
18750 /**
18751 * @author Vova Feldman (@svovaf)
18752 * @since 1.0.0
18753 *
18754 * @return string
18755 */
18756 private function get_top_level_menu_slug() {
18757 return ( $this->is_addon() ?
18758 $this->get_parent_instance()->_menu->get_top_level_menu_slug() :
18759 $this->_menu->get_top_level_menu_slug() );
18760 }
18761
18762 /**
18763 * @author Vova Feldman (@svovaf)
18764 * @since 1.2.2.7
18765 *
18766 * @return string
18767 */
18768 function get_pricing_cta_label() {
18769 $label = $this->get_text_inline( 'Upgrade', 'upgrade' );
18770
18771 if ( $this->is_in_trial_promotion() &&
18772 ! $this->is_paying_or_trial()
18773 ) {
18774 // If running a trial promotion, modify the pricing to load the trial.
18775 $label = $this->get_text_inline( 'Start Trial', 'start-trial' );
18776 } else if ( $this->is_paying() ) {
18777 $label = $this->get_text_inline( 'Pricing', 'pricing' );
18778 }
18779
18780 return $label;
18781 }
18782
18783 /**
18784 * @author Vova Feldman (@svovaf)
18785 * @since 1.2.2.7
18786 *
18787 * @return bool
18788 */
18789 function is_pricing_page_visible() {
18790 $visible = (
18791 // Has at least one paid plan.
18792 $this->has_paid_plan() &&
18793 // Didn't ask to hide the pricing page.
18794 $this->is_page_visible( 'pricing' ) &&
18795 // Don't have a valid active license or has more than one plan.
18796 ( ! $this->is_paying() || ! $this->is_single_plan( true ) )
18797 );
18798
18799 return $this->apply_filters( 'is_pricing_page_visible', $visible );
18800 }
18801
18802 /**
18803 * @author Leo Fajardo (@leorw)
18804 * @since 2.3.0
18805 *
18806 * @param bool $is_activation_mode
18807 *
18808 * @return bool
18809 */
18810 private function should_add_submenu_or_action_links( $is_activation_mode ) {
18811 if ( $this->is_addon() ) {
18812 // No submenu items or action links for add-ons.
18813 return false;
18814 }
18815
18816 if ( $this->show_opt_in_on_themes_page() ) {
18817 if ( ! fs_is_network_admin() ) {
18818 // Also add action links or submenu items when running in a free .org theme so the tabs will be visible.
18819 return true;
18820 }
18821 } else if ( $is_activation_mode ) {
18822 // Don't show submenu-items/tabs in activation mode, unless it's a wp.org theme.
18823 return false;
18824 }
18825
18826 if ( fs_is_network_admin() ) {
18827 /**
18828 * Add submenu items or action links to network level when plugin was network activated and the super
18829 * admin did NOT delegate the connection of all sites to site admins.
18830 */
18831 return (
18832 $this->_is_network_active &&
18833 ( WP_FS__SHOW_NETWORK_EVEN_WHEN_DELEGATED ||
18834 ! $this->is_network_delegated_connection() )
18835 );
18836 }
18837
18838 return ( ! $this->_is_network_active || $this->is_delegated_connection() );
18839 }
18840
18841 /**
18842 * Add default Freemius menu items.
18843 *
18844 * @author Vova Feldman (@svovaf)
18845 * @since 1.0.0
18846 * @since 1.2.2.7 Also add submenu items when running in a free .org theme so the tabs will be visible.
18847 */
18848 private function add_submenu_items() {
18849 $this->_logger->entrance();
18850
18851 $is_activation_mode = $this->is_activation_mode();
18852
18853 $add_submenu_items = $this->should_add_submenu_or_action_links( $is_activation_mode );
18854
18855 if ( $add_submenu_items ) {
18856 if ( $this->has_affiliate_program() ) {
18857 // Add affiliation page.
18858 $this->add_submenu_item(
18859 $this->get_text_inline( 'Affiliation', 'affiliation' ),
18860 array( &$this, '_affiliation_page_render' ),
18861 $this->get_plugin_name() . ' &ndash; ' . $this->get_text_inline( 'Affiliation', 'affiliation' ),
18862 'manage_options',
18863 'affiliation',
18864 'Freemius::_clean_admin_content_section',
18865 WP_FS__DEFAULT_PRIORITY,
18866 $this->is_submenu_item_visible( 'affiliation' )
18867 );
18868 }
18869 }
18870
18871 if ( $add_submenu_items ||
18872 ( $is_activation_mode &&
18873 $this->is_only_premium() &&
18874 $this->is_admin_page( 'account' ) &&
18875 fs_request_is_action( $this->get_unique_affix() . '_sync_license' )
18876 )
18877 ) {
18878 if ( ! WP_FS__DEMO_MODE && $this->is_registered() ) {
18879 $show_account = (
18880 $this->is_submenu_item_visible( 'account' ) &&
18881 /**
18882 * @since 1.2.2.7 Don't show the Account for free WP.org themes without any paid plans.
18883 */
18884 ( ! $this->is_free_wp_org_theme() || $this->has_paid_plan() )
18885 );
18886
18887 // Add user account page.
18888 $this->add_submenu_item(
18889 $this->get_text_inline( 'Account', 'account' ),
18890 array( &$this, '_account_page_render' ),
18891 $this->get_plugin_name() . ' &ndash; ' . $this->get_text_inline( 'Account', 'account' ),
18892 'manage_options',
18893 'account',
18894 array( &$this, '_account_page_load' ),
18895 WP_FS__DEFAULT_PRIORITY,
18896 ( $add_submenu_items && $show_account )
18897 );
18898 }
18899 }
18900
18901 if ( $add_submenu_items ) {
18902 if (! WP_FS__DEMO_MODE && ! $this->is_whitelabeled() ) {
18903 // Add contact page.
18904 if ( $this->is_premium() ) {
18905 $this->add_submenu_item(
18906 $this->get_text_inline( 'Contact Us', 'contact-us' ),
18907 array( &$this, '_contact_page_render' ),
18908 $this->get_plugin_name() . ' &ndash; ' . $this->get_text_inline( 'Contact Us', 'contact-us' ),
18909 'manage_options',
18910 'contact',
18911 'Freemius::_clean_admin_content_section',
18912 WP_FS__DEFAULT_PRIORITY,
18913 $this->is_submenu_item_visible( 'contact' )
18914 );
18915 } else {
18916 $this->add_submenu_link_item(
18917 $this->get_text_inline( 'Contact Us', 'contact-us' ),
18918 FS_Contact_Form_Manager::instance()->get_standalone_link( $this ),
18919 'contact',
18920 'manage_options',
18921 WP_FS__DEFAULT_PRIORITY,
18922 $this->is_submenu_item_visible( 'contact' ),
18923 'fs_external_contact',
18924 true
18925 );
18926 }
18927 }
18928
18929 if ( $this->has_addons() ) {
18930 $this->add_submenu_item(
18931 $this->get_text_inline( 'Add-Ons', 'add-ons' ),
18932 array( &$this, '_addons_page_render' ),
18933 $this->get_plugin_name() . ' &ndash; ' . $this->get_text_inline( 'Add-Ons', 'add-ons' ),
18934 'manage_options',
18935 'addons',
18936 array( &$this, '_addons_page_load' ),
18937 WP_FS__LOWEST_PRIORITY - 1,
18938 $this->is_submenu_item_visible( 'addons' )
18939 );
18940 }
18941 }
18942
18943 if ( $add_submenu_items ||
18944 ( $is_activation_mode && $this->is_only_premium() && $this->is_admin_page( 'pricing' ) )
18945 ) {
18946 if (! WP_FS__DEMO_MODE && ! $this->is_whitelabeled() ) {
18947 $show_pricing = (
18948 $this->is_submenu_item_visible( 'pricing' ) &&
18949 $this->is_pricing_page_visible()
18950 );
18951
18952 $pricing_cta_text = $this->get_pricing_cta_label();
18953 $pricing_class = 'upgrade-mode';
18954 if ( $show_pricing ) {
18955 if ( $this->is_in_trial_promotion() &&
18956 ! $this->is_paying_or_trial()
18957 ) {
18958 // If running a trial promotion, modify the pricing to load the trial.
18959 $pricing_class = 'trial-mode';
18960 } else if ( $this->is_paying() ) {
18961 $pricing_class = '';
18962 }
18963 }
18964
18965 $custom_pricing_url = $this->get_pricing_url_with_filter( null );
18966 $pricing_menu_title = $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' ) );
18967 $show_pricing_submenu_item = ( $add_submenu_items && $show_pricing );
18968
18969 // Add upgrade/pricing submenu item.
18970 if ( ! is_null( $custom_pricing_url ) ) {
18971 $this->add_submenu_link_item(
18972 $pricing_menu_title,
18973 $custom_pricing_url,
18974 'pricing',
18975 'manage_options',
18976 WP_FS__LOWEST_PRIORITY,
18977 $show_pricing_submenu_item,
18978 $pricing_class
18979 );
18980 } else {
18981 $this->add_submenu_item(
18982 $pricing_menu_title,
18983 array( &$this, '_pricing_page_render' ),
18984 $this->get_plugin_name() . ' &ndash; ' . $this->get_text_x_inline( 'Pricing', 'noun', 'pricing' ),
18985 'manage_options',
18986 'pricing',
18987 'Freemius::_clean_admin_content_section',
18988 WP_FS__LOWEST_PRIORITY,
18989 $show_pricing_submenu_item,
18990 $pricing_class
18991 );
18992 }
18993 }
18994 }
18995
18996 if ( ! $is_activation_mode || ( true !== $this->_storage->require_license_activation ) ) {
18997 /**
18998 * Add the other menu items if there are any when not in activation mode or license activation is not
18999 * required (license activation is required for registered or anonymous users after activating the
19000 * premium version when the site is not in trial mode or there's no active valid license).
19001 *
19002 * @author Leo Fajardo (@leorw)
19003 * @since 2.2.1
19004 */
19005 if ( 0 < count( $this->_menu_items ) ) {
19006 if ( ! $this->_menu->is_top_level() ) {
19007 fs_enqueue_local_style( 'fs_common', '/admin/common.css' );
19008
19009 // Append submenu items right after the plugin's submenu item.
19010 $this->order_sub_submenu_items();
19011 } else {
19012 // Append submenu items.
19013 $this->embed_submenu_items();
19014 }
19015 }
19016 }
19017 }
19018
19019 /**
19020 * Moved the actual submenu item additions to a separated function,
19021 * in order to support sub-submenu items when the plugin's settings
19022 * only have a submenu and not top-level menu item.
19023 *
19024 * @author Vova Feldman (@svovaf)
19025 * @since 1.1.4
19026 */
19027 private function embed_submenu_items() {
19028 $item_classes = $this->_menu->is_top_level() ? 'fs-submenu-item' : 'fs-submenu-item fs-sub';
19029
19030 $item_template = '<span class="' . $item_classes . ' %1$s %2$s %3$s" data-fs-external-url="%5$s" data-fs-new-tab="%6$s">%4$s</span>';
19031
19032 $top_level_menu_capability = $this->get_top_level_menu_capability();
19033
19034 ksort( $this->_menu_items );
19035
19036 $is_first_submenu_item = true;
19037
19038 foreach ( $this->_menu_items as $priority => $items ) {
19039 foreach ( $items as $item ) {
19040 $capability = ( ! empty( $item['capability'] ) ? $item['capability'] : $top_level_menu_capability );
19041
19042 $menu_item = sprintf(
19043 $item_template,
19044 $this->get_unique_affix(),
19045 $item['menu_slug'],
19046 ! empty( $item['class'] ) ? $item['class'] : '',
19047 $item['menu_title'],
19048 esc_attr( isset( $item['url'] ) ? $item['url'] : '' ),
19049 esc_attr( isset( $item['new_tab'] ) ? 'true' : 'false' )
19050 );
19051
19052 $top_level_menu_slug = $this->get_top_level_menu_slug();
19053 $menu_slug = $this->_menu->get_slug( $item['menu_slug'] );
19054
19055 if ( ! isset( $item['url'] ) ) {
19056 $hook = FS_Admin_Menu_Manager::add_subpage(
19057 $item['show_submenu'] ?
19058 $top_level_menu_slug :
19059 '',
19060 $item['page_title'],
19061 $menu_item,
19062 $capability,
19063 $menu_slug,
19064 $item['render_function']
19065 );
19066
19067 if ( false !== $item['before_render_function'] ) {
19068 add_action( "load-$hook", $item['before_render_function'] );
19069 }
19070 } else {
19071 FS_Admin_Menu_Manager::add_subpage(
19072 $item['show_submenu'] ?
19073 $top_level_menu_slug :
19074 '',
19075 $item['page_title'],
19076 $menu_item,
19077 $capability,
19078 $menu_slug,
19079 array( $this, '' )
19080 );
19081 }
19082
19083 if ( $item['show_submenu'] && $is_first_submenu_item ) {
19084 if ( $this->_is_network_active && ! empty( $this->_dynamically_added_top_level_page_hook_name ) ) {
19085 /**
19086 * If the top-level menu has been dynamically created, remove the first submenu item that
19087 * WordPress automatically creates when there's no submenu item whose slug matches the
19088 * parent's. In the following example, the `Awesome Plugin` submenu item will be removed.
19089 *
19090 * Awesome Plugin
19091 * - Awesome Plugin <-- we want to remove this since there's no real setting page for the top-level
19092 *
19093 * @author Leo Fajardo (@leorw)
19094 */
19095 remove_submenu_page( $top_level_menu_slug, $top_level_menu_slug );
19096 }
19097
19098 $is_first_submenu_item = false;
19099 }
19100 }
19101 }
19102 }
19103
19104 /**
19105 * Re-order the submenu items so all Freemius added new submenu items
19106 * are added right after the plugin's settings submenu item.
19107 *
19108 * @author Vova Feldman (@svovaf)
19109 * @since 1.1.4
19110 */
19111 private function order_sub_submenu_items() {
19112 global $submenu;
19113
19114 $menu_slug = $this->_menu->get_top_level_menu_slug();
19115
19116 /**
19117 * Before "admin_menu" fires, WordPress will loop over the default submenus and remove pages for which the user
19118 * does not have permissions. So in case a plugin does not have top-level menu but does have submenus under any
19119 * of the default menus, only users that have the right role can access its sub-submenus (Account, Contact Us,
19120 * Support Forum, etc.) since $submenu[ $menu_slug ] will be empty if the user doesn't have permission.
19121 *
19122 * In case a plugin does not have submenus under any of the default menus but does have submenus under the menu
19123 * of another plugin, only users that have the right role can access its sub-submenus since we will use the
19124 * capability needed to access the parent menu as the capability for the submenus that we will add.
19125 */
19126 if ( empty( $submenu[ $menu_slug ] ) ) {
19127 return;
19128 }
19129
19130 $top_level_menu = &$submenu[ $menu_slug ];
19131
19132 $all_submenu_items_after = array();
19133
19134 $found_submenu_item = false;
19135
19136 foreach ( $top_level_menu as $submenu_id => $meta ) {
19137 if ( $found_submenu_item ) {
19138 // Remove all submenu items after the plugin's submenu item.
19139 $all_submenu_items_after[] = $meta;
19140 unset( $top_level_menu[ $submenu_id ] );
19141 }
19142
19143 if ( $this->_menu->get_raw_slug() === $meta[2] ) {
19144 // Found the submenu item, put all below.
19145 $found_submenu_item = true;
19146 continue;
19147 }
19148 }
19149
19150 // Embed all plugin's new submenu items.
19151 $this->embed_submenu_items();
19152
19153 // Start with specially high number to make sure it's appended.
19154 $i = max( 10000, max( array_keys( $top_level_menu ) ) + 1 );
19155 foreach ( $all_submenu_items_after as $meta ) {
19156 $top_level_menu[ $i ] = $meta;
19157 $i ++;
19158 }
19159
19160 // Sort submenu items.
19161 ksort( $top_level_menu );
19162 }
19163
19164 /**
19165 * Helper method to return the module's support forum URL.
19166 *
19167 * @author Vova Feldman (@svovaf)
19168 * @since 1.2.2.7
19169 *
19170 * @return string
19171 */
19172 function get_support_forum_url() {
19173 return $this->apply_filters( 'support_forum_url', "https://wordpress.org/support/{$this->_module_type}/{$this->_slug}" );
19174 }
19175
19176 /**
19177 * Displays the Support Forum link when enabled.
19178 *
19179 * Can be filtered like so:
19180 *
19181 * function _fs_show_support_menu( $is_visible, $menu_id ) {
19182 * if ( 'support' === $menu_id ) {
19183 * return _fs->is_registered();
19184 * }
19185 * return $is_visible;
19186 * }
19187 * _fs()->add_filter('is_submenu_visible', '_fs_show_support_menu', 10, 2);
19188 *
19189 */
19190 function _add_default_submenu_items() {
19191 if ( ! $this->is_on() ) {
19192 return;
19193 }
19194
19195 if ( ! $this->is_activation_mode() &&
19196 ( ( $this->_is_network_active && fs_is_network_admin() ) ||
19197 ( ! $this->_is_network_active && is_admin() ) )
19198 ) {
19199 $this->add_submenu_link_item(
19200 $this->apply_filters( 'support_forum_submenu', $this->get_text_inline( 'Support Forum', 'support-forum' ) ),
19201 $this->get_support_forum_url(),
19202 'wp-support-forum',
19203 null,
19204 50,
19205 $this->is_submenu_item_visible( 'support' ),
19206 '',
19207 true
19208 );
19209 }
19210 }
19211
19212 /**
19213 * @author Vova Feldman (@svovaf)
19214 * @since 1.0.1
19215 *
19216 * @param string $menu_title
19217 * @param callable $render_function
19218 * @param bool|string $page_title
19219 * @param string $capability
19220 * @param bool|string $menu_slug
19221 * @param bool|callable $before_render_function
19222 * @param int $priority
19223 * @param bool $show_submenu
19224 * @param string $class Since 1.2.1.5 can add custom classes to menu items.
19225 */
19226 function add_submenu_item(
19227 $menu_title,
19228 $render_function,
19229 $page_title = false,
19230 $capability = 'manage_options',
19231 $menu_slug = false,
19232 $before_render_function = false,
19233 $priority = WP_FS__DEFAULT_PRIORITY,
19234 $show_submenu = true,
19235 $class = ''
19236 ) {
19237 $this->_logger->entrance( 'Title = ' . $menu_title );
19238
19239 if ( $this->is_addon() ) {
19240 $parent_fs = $this->get_parent_instance();
19241
19242 if ( is_object( $parent_fs ) ) {
19243 $parent_fs->add_submenu_item(
19244 $menu_title,
19245 $render_function,
19246 $page_title,
19247 $capability,
19248 $menu_slug,
19249 $before_render_function,
19250 $priority,
19251 $show_submenu,
19252 $class
19253 );
19254
19255 return;
19256 }
19257 }
19258
19259 if ( ! isset( $this->_menu_items[ $priority ] ) ) {
19260 $this->_menu_items[ $priority ] = array();
19261 }
19262
19263 $this->_menu_items[ $priority ][] = array(
19264 'page_title' => is_string( $page_title ) ? $page_title : $menu_title,
19265 'menu_title' => $menu_title,
19266 'capability' => $capability,
19267 'menu_slug' => is_string( $menu_slug ) ? $menu_slug : strtolower( $menu_title ),
19268 'render_function' => $render_function,
19269 'before_render_function' => $before_render_function,
19270 'show_submenu' => $show_submenu,
19271 'class' => $class,
19272 );
19273 }
19274
19275 /**
19276 * @author Vova Feldman (@svovaf)
19277 * @since 1.0.1
19278 *
19279 * @param string $menu_title
19280 * @param string $url
19281 * @param bool $menu_slug
19282 * @param string $capability
19283 * @param int $priority
19284 * @param bool $show_submenu
19285 * @param string $class
19286 * @param bool $new_tab
19287 */
19288 function add_submenu_link_item(
19289 $menu_title,
19290 $url,
19291 $menu_slug = false,
19292 $capability = 'read',
19293 $priority = WP_FS__DEFAULT_PRIORITY,
19294 $show_submenu = true,
19295 $class = '',
19296 $new_tab = false
19297 ) {
19298 $this->_logger->entrance( 'Title = ' . $menu_title . '; Url = ' . $url );
19299
19300 if ( $this->is_addon() ) {
19301 $parent_fs = $this->get_parent_instance();
19302
19303 if ( is_object( $parent_fs ) ) {
19304 $parent_fs->add_submenu_link_item(
19305 $menu_title,
19306 $url,
19307 $menu_slug,
19308 $capability,
19309 $priority,
19310 $show_submenu,
19311 $class,
19312 $new_tab
19313 );
19314
19315 return;
19316 }
19317 }
19318
19319 if ( ! isset( $this->_menu_items[ $priority ] ) ) {
19320 $this->_menu_items[ $priority ] = array();
19321 }
19322
19323 $this->_menu_items[ $priority ][] = array(
19324 'menu_title' => $menu_title,
19325 'capability' => $capability,
19326 'menu_slug' => is_string( $menu_slug ) ? $menu_slug : strtolower( $menu_title ),
19327 'url' => $url,
19328 'page_title' => $menu_title,
19329 'render_function' => 'fs_dummy',
19330 'before_render_function' => '',
19331 'show_submenu' => $show_submenu,
19332 'class' => $class,
19333 'new_tab' => $new_tab,
19334 );
19335 }
19336
19337 #endregion ------------------------------------------------------------------
19338
19339 #--------------------------------------------------------------------------------
19340 #region Admin Notices
19341 #--------------------------------------------------------------------------------
19342
19343 /**
19344 * @author Vova Feldman (@svovaf)
19345 * @since 2.3.1
19346 *
19347 * @param string|string[] $ids
19348 * @param int|null $network_level_or_blog_id
19349 *
19350 * @uses FS_Admin_Notices::remove_sticky()
19351 */
19352 function remove_sticky( $ids, $network_level_or_blog_id = null ) {
19353 $this->_admin_notices->remove_sticky( $ids, $network_level_or_blog_id );
19354 }
19355
19356 #endregion
19357
19358 #--------------------------------------------------------------------------------
19359 #region Actions / Hooks / Filters
19360 #--------------------------------------------------------------------------------
19361
19362 /**
19363 * @author Vova Feldman (@svovaf)
19364 * @since 1.1.7
19365 *
19366 * @param string $tag
19367 *
19368 * @return string
19369 */
19370 public function get_action_tag( $tag ) {
19371 return self::get_action_tag_static( $tag, $this->_slug, $this->is_plugin() );
19372 }
19373
19374 /**
19375 * @author Vova Feldman (@svovaf)
19376 * @since 1.2.1.6
19377 *
19378 * @param string $tag
19379 * @param string $slug
19380 * @param bool $is_plugin
19381 *
19382 * @return string
19383 */
19384 static function get_action_tag_static( $tag, $slug = '', $is_plugin = true ) {
19385 $action = "fs_{$tag}";
19386
19387 if ( ! empty( $slug ) ) {
19388 $action .= '_' . self::get_module_unique_affix( $slug, $is_plugin );
19389 }
19390
19391 return $action;
19392 }
19393
19394 /**
19395 * Returns a string that can be used to generate a unique action name,
19396 * option name, HTML element ID, or HTML element class.
19397 *
19398 * @author Leo Fajardo (@leorw)
19399 * @since 1.2.2
19400 *
19401 * @return string
19402 */
19403 public function get_unique_affix() {
19404 return self::get_module_unique_affix( $this->_slug, $this->is_plugin() );
19405 }
19406
19407 /**
19408 * Returns a string that can be used to generate a unique action name,
19409 * option name, HTML element ID, or HTML element class.
19410 *
19411 * @author Vova Feldman (@svovaf)
19412 * @since 1.2.2.5
19413 *
19414 * @param string $slug
19415 * @param bool $is_plugin
19416 *
19417 * @return string
19418 */
19419 static function get_module_unique_affix( $slug, $is_plugin = true ) {
19420 $affix = $slug;
19421
19422 if ( ! $is_plugin ) {
19423 $affix .= '-' . WP_FS__MODULE_TYPE_THEME;
19424 }
19425
19426 return $affix;
19427 }
19428
19429 /**
19430 * @author Vova Feldman (@svovaf)
19431 * @since 1.2.1
19432 * @since 1.2.2.5 The AJAX action names are based on the module ID, not like the non-AJAX actions that are
19433 * based on the slug for backward compatibility.
19434 *
19435 * @param string $tag
19436 *
19437 * @return string
19438 */
19439 function get_ajax_action( $tag ) {
19440 return self::get_ajax_action_static( $tag, $this->_module_id );
19441 }
19442
19443 /**
19444 * @author Vova Feldman (@svovaf)
19445 * @since 1.2.1.7
19446 *
19447 * @param string $tag
19448 *
19449 * @return string
19450 */
19451 function get_ajax_security( $tag ) {
19452 return wp_create_nonce( $this->get_ajax_action( $tag ) );
19453 }
19454
19455 /**
19456 * @author Vova Feldman (@svovaf)
19457 * @since 1.2.1.7
19458 *
19459 * @param string $tag
19460 */
19461 function check_ajax_referer( $tag ) {
19462 check_ajax_referer( $this->get_ajax_action( $tag ), 'security' );
19463 }
19464
19465 /**
19466 * @author Vova Feldman (@svovaf)
19467 * @since 1.2.1.6
19468 * @since 1.2.2.5 The AJAX action names are based on the module ID, not like the non-AJAX actions that are
19469 * based on the slug for backward compatibility.
19470 *
19471 * @param string $tag
19472 * @param number|null $module_id
19473 *
19474 * @return string
19475 */
19476 static function get_ajax_action_static( $tag, $module_id = null ) {
19477 $action = "fs_{$tag}";
19478
19479 if ( ! empty( $module_id ) ) {
19480 $action .= "_{$module_id}";
19481 }
19482
19483 return $action;
19484 }
19485
19486 /**
19487 * Do action, specific for the current context plugin.
19488 *
19489 * @author Vova Feldman (@svovaf)
19490 * @since 1.0.1
19491 *
19492 * @param string $tag The name of the action to be executed.
19493 * @param mixed $arg,... Optional. Additional arguments which are passed on to the
19494 * functions hooked to the action. Default empty.
19495 *
19496 * @uses do_action()
19497 */
19498 function do_action( $tag, $arg = '' ) {
19499 $args = func_get_args();
19500
19501 $this->_logger->entrance( $tag );
19502
19503 call_user_func_array( 'do_action', array_merge(
19504 array( $this->get_action_tag( $tag ) ),
19505 array_slice( $args, 1 ) )
19506 );
19507 }
19508
19509 /**
19510 * Add action, specific for the current context plugin.
19511 *
19512 * @author Vova Feldman (@svovaf)
19513 * @since 1.0.1
19514 *
19515 * @param string $tag
19516 * @param callable $function_to_add
19517 * @param int $priority
19518 * @param int $accepted_args
19519 *
19520 * @uses add_action()
19521 */
19522 function add_action(
19523 $tag,
19524 $function_to_add,
19525 $priority = WP_FS__DEFAULT_PRIORITY,
19526 $accepted_args = 1
19527 ) {
19528 $this->_logger->entrance( $tag );
19529
19530 add_action( $this->get_action_tag( $tag ), $function_to_add, $priority, $accepted_args );
19531 }
19532
19533 /**
19534 * Add AJAX action, specific for the current context plugin.
19535 *
19536 * @author Vova Feldman (@svovaf)
19537 * @since 1.2.1
19538 *
19539 * @param string $tag
19540 * @param callable $function_to_add
19541 * @param int $priority
19542 *
19543 * @uses add_action()
19544 *
19545 * @return bool True if action added, false if no need to add the action since the AJAX call isn't matching.
19546 */
19547 function add_ajax_action(
19548 $tag,
19549 $function_to_add,
19550 $priority = WP_FS__DEFAULT_PRIORITY
19551 ) {
19552 $this->_logger->entrance( $tag );
19553
19554 return self::add_ajax_action_static(
19555 $tag,
19556 $function_to_add,
19557 $priority,
19558 $this->_module_id
19559 );
19560 }
19561
19562 /**
19563 * Add AJAX action.
19564 *
19565 * @author Vova Feldman (@svovaf)
19566 * @since 1.2.1.6
19567 *
19568 * @param string $tag
19569 * @param callable $function_to_add
19570 * @param int $priority
19571 * @param number|null $module_id
19572 *
19573 * @return bool True if action added, false if no need to add the action since the AJAX call isn't matching.
19574 * @uses add_action()
19575 *
19576 */
19577 static function add_ajax_action_static(
19578 $tag,
19579 $function_to_add,
19580 $priority = WP_FS__DEFAULT_PRIORITY,
19581 $module_id = null
19582 ) {
19583 self::$_static_logger->entrance( $tag );
19584
19585 if ( ! self::is_ajax_action_static( $tag, $module_id ) ) {
19586 return false;
19587 }
19588
19589 add_action(
19590 'wp_ajax_' . self::get_ajax_action_static( $tag, $module_id ),
19591 $function_to_add,
19592 $priority,
19593 0
19594 );
19595
19596 self::$_static_logger->info( "$tag AJAX callback action added." );
19597
19598 return true;
19599 }
19600
19601 /**
19602 * Send a JSON response back to an Ajax request.
19603 *
19604 * @author Vova Feldman (@svovaf)
19605 * @since 1.2.1.5
19606 *
19607 * @param mixed $response
19608 */
19609 static function shoot_ajax_response( $response ) {
19610 wp_send_json( $response );
19611 }
19612
19613 /**
19614 * Send a JSON response back to an Ajax request, indicating success.
19615 *
19616 * @author Vova Feldman (@svovaf)
19617 * @since 1.2.1.5
19618 *
19619 * @param mixed $data Data to encode as JSON, then print and exit.
19620 */
19621 static function shoot_ajax_success( $data = null ) {
19622 wp_send_json_success( $data );
19623 }
19624
19625 /**
19626 * Send a JSON response back to an Ajax request, indicating failure.
19627 *
19628 * @author Vova Feldman (@svovaf)
19629 * @since 1.2.1.5
19630 *
19631 * @param mixed $error Optional error message.
19632 */
19633 static function shoot_ajax_failure( $error = '' ) {
19634 $result = array( 'success' => false );
19635 if ( ! empty( $error ) ) {
19636 $result['error'] = $error;
19637 }
19638
19639 wp_send_json( $result );
19640 }
19641
19642 /**
19643 * Returns an AJAX URL with a special extra param to indicate whether the request was triggered from the network admin or blog admin.
19644 *
19645 * @author Vova Feldman (@svovaf)
19646 * @since 2.5.1
19647 *
19648 * @param string $wrap_with By default, returns the AJAX URL wrapped with single quotes.
19649 *
19650 * @return string
19651 */
19652 static function ajax_url( $wrap_with = "'") {
19653 if ( fs_is_network_admin() ) {
19654 $param_name = '_fs_network_admin';
19655 } else {
19656 $param_name = '_fs_blog_admin';
19657 }
19658
19659 $url = admin_url( 'admin-ajax.php', 'relative' );
19660 $url .= ( false === strpos( $url, '?' ) ) ? '?' : '&';
19661 $url .= "{$param_name}=true";
19662
19663 return "{$wrap_with}{$url}{$wrap_with}";
19664 }
19665
19666 /**
19667 * Apply filter, specific for the current context plugin.
19668 *
19669 * @author Vova Feldman (@svovaf)
19670 * @since 1.0.9
19671 *
19672 * @param string $tag The name of the filter hook.
19673 * @param mixed $value The value on which the filters hooked to `$tag` are applied on.
19674 *
19675 * @return mixed The filtered value after all hooked functions are applied to it.
19676 *
19677 * @uses apply_filters()
19678 */
19679 function apply_filters( $tag, $value ) {
19680 $args = func_get_args();
19681
19682 $this->_logger->entrance( $tag );
19683
19684 array_unshift( $args, $this->get_unique_affix() );
19685
19686 return call_user_func_array( 'fs_apply_filter', $args );
19687 }
19688
19689 /**
19690 * Add filter, specific for the current context plugin.
19691 *
19692 * @author Vova Feldman (@svovaf)
19693 * @since 1.0.9
19694 *
19695 * @param string $tag
19696 * @param callable $function_to_add
19697 * @param int $priority
19698 * @param int $accepted_args
19699 *
19700 * @uses add_filter()
19701 */
19702 function add_filter( $tag, $function_to_add, $priority = WP_FS__DEFAULT_PRIORITY, $accepted_args = 1 ) {
19703 $this->_logger->entrance( $tag );
19704
19705 add_filter( $this->get_action_tag( $tag ), $function_to_add, $priority, $accepted_args );
19706 }
19707
19708 /**
19709 * Check if has filter.
19710 *
19711 * @author Vova Feldman (@svovaf)
19712 * @since 1.1.4
19713 *
19714 * @param string $tag
19715 * @param callable|bool $function_to_check Optional. The callback to check for. Default false.
19716 *
19717 * @return false|int
19718 *
19719 * @uses has_filter()
19720 */
19721 function has_filter( $tag, $function_to_check = false ) {
19722 $this->_logger->entrance( $tag );
19723
19724 return has_filter( $this->get_action_tag( $tag ), $function_to_check );
19725 }
19726
19727 #endregion
19728
19729 /**
19730 * Override default i18n text phrases.
19731 *
19732 * @author Vova Feldman (@svovaf)
19733 * @since 1.1.6
19734 *
19735 * @param string[] string $key_value
19736 *
19737 * @uses fs_override_i18n()
19738 */
19739 function override_i18n( $key_value ) {
19740 fs_override_i18n( $key_value, $this->_slug );
19741 }
19742
19743 /* Account Page
19744 ------------------------------------------------------------------------------------------------------------------*/
19745 /**
19746 * Update site information.
19747 *
19748 * @author Vova Feldman (@svovaf)
19749 * @since 1.0.1
19750 *
19751 * @param bool $store Flush to Database if true.
19752 * @param null|int $network_level_or_blog_id Since 2.0.0
19753 * @param \FS_Site $site Since 2.0.0
19754 */
19755 private function _store_site( $store = true, $network_level_or_blog_id = null, $site = null, $is_backup = false ) {
19756 $this->_logger->entrance();
19757
19758 if ( is_null( $site ) ) {
19759 $site = $this->_site;
19760 }
19761
19762 if ( !isset( $site ) || !is_object($site) || empty( $site->id ) ) {
19763 $this->_logger->error( "Empty install ID, can't store site." );
19764
19765 return;
19766 }
19767
19768 $site_clone = clone $site;
19769
19770 $sites = self::get_all_sites( $this->_module_type, $network_level_or_blog_id, $is_backup );
19771
19772 if (
19773 ! $is_backup &&
19774 is_object( $this->_user ) && $this->_user->id != $site->user_id
19775 ) {
19776 $this->sync_user_by_current_install( $site->user_id );
19777
19778 $prev_stored_user_id = $this->_storage->get( 'prev_user_id', false, $network_level_or_blog_id );
19779
19780 if ( empty( $prev_stored_user_id ) &&
19781 is_object($this->_user) && $this->_user->id != $site->user_id
19782 ) {
19783 /**
19784 * Store the current user ID as the previous user ID so that the previous user can be used
19785 * as the install's owner while the new owner's details are not yet available.
19786 *
19787 * This will be executed only in the `replica` site. For example, there are 2 sites, namely `original`
19788 * and `replica`, then an ownership change was initiated and completed in the `original`, the `replica`
19789 * will be using the previous user until it is updated again (e.g.: until the next clone of `original`
19790 * into `replica`.
19791 *
19792 * @author Leo Fajardo (@leorw)
19793 */
19794 $this->_storage->store( 'prev_user_id', $sites[ $this->_slug ]->user_id, $network_level_or_blog_id );
19795 }
19796 }
19797
19798 $sites[ $this->_slug ] = $site_clone;
19799
19800 $this->set_account_option(
19801 ( $is_backup ? 'prev_' : '' ) . 'sites',
19802 $sites,
19803 $store,
19804 $network_level_or_blog_id
19805 );
19806 }
19807
19808 /**
19809 * 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).
19810 *
19811 * @author Leo Fajardo (@leorw)
19812 * @since 2.5.0
19813 */
19814 private function back_up_site() {
19815 $this->_logger->entrance();
19816
19817 $site_clone = clone $this->_site;
19818
19819 $this->_store_site( true, null, $site_clone, true );
19820 }
19821
19822 /**
19823 * Update plugin's plans information.
19824 *
19825 * @author Vova Feldman (@svovaf)
19826 * @since 1.0.2
19827 *
19828 * @param bool $store Flush to Database if true.
19829 */
19830 private function _store_plans( $store = true ) {
19831 $this->_logger->entrance();
19832
19833 $plans = self::get_all_plans( $this->_module_type );
19834
19835 // Copy plans.
19836 $encrypted_plans = array();
19837 for ( $i = 0, $len = count( $this->_plans ); $i < $len; $i ++ ) {
19838 $encrypted_plans[] = self::_encrypt_entity( $this->_plans[ $i ] );
19839 }
19840
19841 $plans[ $this->_slug ] = $encrypted_plans;
19842
19843 $this->set_account_option( 'plans', $plans, $store );
19844 }
19845
19846 /**
19847 * Update user's plugin licenses.
19848 *
19849 * @author Vova Feldman (@svovaf)
19850 * @since 1.0.5
19851 *
19852 * @param bool $store
19853 * @param number|bool $module_id
19854 * @param FS_Plugin_License[] $licenses
19855 */
19856 private function _store_licenses( $store = true, $module_id = false, $licenses = array() ) {
19857 $this->_logger->entrance();
19858
19859 $all_licenses = self::get_all_licenses();
19860
19861 if ( ! FS_Plugin::is_valid_id( $module_id ) ) {
19862 $module_id = $this->_module_id;
19863
19864 $user_licenses = is_array( $this->_licenses ) ?
19865 $this->_licenses :
19866 array();
19867
19868 if ( empty( $user_licenses ) ) {
19869 // If the context user doesn't have any license, don't update the licenses collection.
19870 return;
19871 }
19872
19873 $new_user_licenses_map = array();
19874 foreach ( $user_licenses as $user_license ) {
19875 $new_user_licenses_map[ $user_license->id ] = $user_license;
19876 }
19877
19878 self::store_user_id_license_ids_map( array_keys( $new_user_licenses_map ), $this->_module_id, $this->_user->id );
19879
19880 // Update user licenses.
19881 $licenses_to_update_count = count( $new_user_licenses_map );
19882 foreach ( $all_licenses[ $module_id ] as $key => $license ) {
19883 if ( 0 === $licenses_to_update_count ) {
19884 break;
19885 }
19886
19887 if ( isset( $new_user_licenses_map[ $license->id ] ) ) {
19888 // Update license.
19889 $all_licenses[ $module_id ][ $key ] = $new_user_licenses_map[ $license->id ];
19890 unset( $new_user_licenses_map[ $license->id ] );
19891
19892 $licenses_to_update_count --;
19893 }
19894 }
19895
19896 if ( ! empty( $new_user_licenses_map ) ) {
19897 // Add new licenses.
19898 $all_licenses[ $module_id ] = array_merge( array_values( $new_user_licenses_map ), $all_licenses[ $module_id ] );
19899 }
19900
19901 $licenses = $all_licenses[ $module_id ];
19902 }
19903
19904 if ( ! isset( $all_licenses[ $module_id ] ) ) {
19905 $all_licenses[ $module_id ] = array();
19906 }
19907
19908 $all_licenses[ $module_id ] = $licenses;
19909
19910 self::$_accounts->set_option( 'all_licenses', $all_licenses, $store );
19911 }
19912
19913 /**
19914 * Update user information.
19915 *
19916 * @author Vova Feldman (@svovaf)
19917 * @since 1.0.1
19918 *
19919 * @param bool $store Flush to Database if true.
19920 */
19921 private function _store_user( $store = true ) {
19922 $this->_logger->entrance();
19923
19924 if ( empty( $this->_user->id ) ) {
19925 $this->_logger->error( "Empty user ID, can't store user." );
19926
19927 return;
19928 }
19929
19930 $users = self::get_all_users();
19931 $users[ $this->_user->id ] = $this->_user;
19932 self::$_accounts->set_option( 'users', $users, $store );
19933 }
19934
19935 /**
19936 * Update new updates information.
19937 *
19938 * @author Vova Feldman (@svovaf)
19939 * @since 1.0.4
19940 *
19941 * @param FS_Plugin_Tag|null $update
19942 * @param bool $store Flush to Database if true.
19943 * @param bool|number $plugin_id
19944 */
19945 private function _store_update( $update, $store = true, $plugin_id = false ) {
19946 $this->_logger->entrance();
19947
19948 if ( $update instanceof FS_Plugin_Tag ) {
19949 $update->updated = time();
19950 }
19951
19952 if ( ! is_numeric( $plugin_id ) ) {
19953 $plugin_id = $this->_plugin->id;
19954 }
19955
19956 $updates = self::get_all_updates();
19957 $updates[ $plugin_id ] = $update;
19958 self::$_accounts->set_option( 'updates', $updates, $store );
19959 }
19960
19961 /**
19962 * Update new updates information.
19963 *
19964 * @author Vova Feldman (@svovaf)
19965 * @since 1.0.6
19966 *
19967 * @param FS_Plugin[] $plugin_addons
19968 * @param bool $store Flush to Database if true.
19969 */
19970 private function _store_addons( $plugin_addons, $store = true ) {
19971 $this->_logger->entrance();
19972
19973 $addons = self::get_all_addons();
19974 $addons[ $this->_plugin->id ] = $plugin_addons;
19975 self::$_accounts->set_option( 'addons', $addons, $store );
19976 }
19977
19978 /**
19979 * Delete plugin's associated add-ons.
19980 *
19981 * @author Vova Feldman (@svovaf)
19982 * @since 1.0.8
19983 *
19984 * @param bool $store
19985 *
19986 * @return bool
19987 */
19988 private function _delete_account_addons( $store = true ) {
19989 $all_addons = self::get_all_account_addons();
19990
19991 if ( ! isset( $all_addons[ $this->_plugin->id ] ) ) {
19992 return false;
19993 }
19994
19995 unset( $all_addons[ $this->_plugin->id ] );
19996
19997 self::$_accounts->set_option( 'account_addons', $all_addons, $store );
19998
19999 return true;
20000 }
20001
20002 /**
20003 * Update account add-ons list.
20004 *
20005 * @author Vova Feldman (@svovaf)
20006 * @since 1.0.6
20007 *
20008 * @param FS_Plugin[] $addons
20009 * @param bool $store Flush to Database if true.
20010 */
20011 private function _store_account_addons( $addons, $store = true ) {
20012 $this->_logger->entrance();
20013
20014 $all_addons = self::get_all_account_addons();
20015 $all_addons[ $this->_plugin->id ] = $addons;
20016 self::$_accounts->set_option( 'account_addons', $all_addons, $store );
20017 }
20018
20019 /**
20020 * Purges the cache for the valid user licenses API call so that when the `Account` or `Add-Ons` page is loaded,
20021 * the valid user licenses will be fetched again and the account add-ons may be updated.
20022 *
20023 * @author Leo Fajardo (@leorw)
20024 * @since 2.2.4
20025 */
20026 private function purge_valid_user_licenses_cache() {
20027 if ( ! $this->is_registered() ) {
20028 return;
20029 }
20030
20031 $this->get_api_user_scope()->purge_cache( $this->get_valid_user_licenses_endpoint() );
20032 }
20033
20034 /**
20035 * @author Leo Fajardo (@leorw)
20036 * @since 2.3.0
20037 *
20038 * @param array $all_licenses
20039 * @param number|null $site_license_id
20040 * @param bool $include_parent_licenses
20041 *
20042 * @return array
20043 */
20044 private function get_foreign_licenses_info( $all_licenses, $site_license_id = null, $include_parent_licenses = false ) {
20045 $foreign_licenses = array(
20046 'ids' => array(),
20047 'license_keys' => array()
20048 );
20049
20050 $parent_license_ids_map = array();
20051
20052 foreach ( $all_licenses as $license ) {
20053 if ( $license->user_id == $this->_user->id || $license->id == $site_license_id ) {
20054 continue;
20055 }
20056
20057 $foreign_licenses['ids'][] = $license->id;
20058 $foreign_licenses['license_keys'][] = $license->secret_key;
20059
20060 if (
20061 $include_parent_licenses &&
20062 is_object( $this->_license ) &&
20063 FS_Plugin_License::is_valid_id( $this->_license->parent_license_id ) &&
20064 ! isset( $parent_license_ids_map[ $this->_license->parent_license_id ] )
20065 ) {
20066 /**
20067 * Include the parent license's info only if it has not been included before since child licenses
20068 * can have the same parent license.
20069 */
20070 $foreign_licenses['ids'][] = $this->_license->parent_license_id;
20071 $foreign_licenses['license_keys'][] = $license->secret_key;
20072
20073 $parent_license_ids_map[ $this->_license->parent_license_id ] = true;
20074 }
20075 }
20076
20077 if ( empty( $foreign_licenses['ids'] ) ) {
20078 $foreign_licenses = array();
20079 }
20080
20081 return $foreign_licenses;
20082 }
20083
20084 /**
20085 * @author Leo Fajardo (@leorw)
20086 * @since 2.3.0
20087 *
20088 * @return string
20089 */
20090 private function get_valid_user_licenses_endpoint() {
20091 $user_licenses_endpoint = '/licenses.json?type=active' .
20092 ( FS_Plugin::is_valid_id( $this->get_bundle_id() ) ? '&is_enriched=true' : '' );
20093
20094 $foreign_licenses = $this->get_foreign_licenses_info( self::get_all_licenses( $this->_module_id ), null, true );
20095
20096 if ( ! empty ( $foreign_licenses ) ) {
20097 $foreign_licenses = array(
20098 // Prefix with `+` to tell the server to include foreign licenses in the licenses collection.
20099 'ids' => ( urlencode( '+' ) . implode( ',', $foreign_licenses['ids'] ) ),
20100 'license_keys' => implode( ',', array_map( 'urlencode', $foreign_licenses['license_keys'] ) )
20101 );
20102
20103 $user_licenses_endpoint = add_query_arg( $foreign_licenses, $user_licenses_endpoint );
20104 }
20105
20106 return $user_licenses_endpoint;
20107 }
20108
20109 /**
20110 * Fetches active licenses that are enriched with product type if there's a context `bundle_id` and bundle
20111 * licenses enriched with product IDs if there are any. From the licenses, the `get_updated_account_addons`
20112 * method filters out non–add-on product IDs and stores the add-on IDs.
20113 *
20114 * @author Leo Fajardo (@leorw)
20115 * @since 2.2.4
20116 *
20117 * @return stdClass[] array
20118 */
20119 private function fetch_valid_user_licenses() {
20120 $this->_logger->entrance();
20121
20122 $result = $this->get_api_user_scope()->get( $this->get_valid_user_licenses_endpoint() );
20123
20124 if ( ! $this->is_api_result_object( $result, 'licenses' ) ||
20125 ! is_array( $result->licenses )
20126 ) {
20127 return array();
20128 }
20129
20130 return $result->licenses;
20131 }
20132
20133 /**
20134 * @author Leo Fajardo (@leorw)
20135 * @since 2.2.4
20136 *
20137 * @return number[] Account add-on IDs.
20138 */
20139 function get_updated_account_addons() {
20140 $addons = $this->get_addons();
20141 if ( empty( $addons ) ) {
20142 return array();
20143 }
20144
20145 $account_addons = $this->get_account_addons();
20146 if ( ! is_array( $account_addons ) ) {
20147 $account_addons = array();
20148 }
20149
20150 $user_licenses = $this->is_registered() ?
20151 $this->fetch_valid_user_licenses() :
20152 array();
20153
20154 if ( empty( $user_licenses ) ) {
20155 return $account_addons;
20156 }
20157
20158 $addon_ids = array();
20159 foreach ( $addons as $addon ) {
20160 $addon_ids[] = $addon->id;
20161 }
20162
20163 $license_product_ids = array();
20164
20165 foreach ( $user_licenses as $license ) {
20166 if ( isset( $license->plugin_type ) && 'bundle' === $license->plugin_type ) {
20167 $license_product_ids = array_merge( $license_product_ids, $license->products );
20168 } else {
20169 $license_product_ids[] = $license->plugin_id;
20170 }
20171 }
20172
20173 // Filter out non–add-on IDs.
20174 $new_account_addons = array_intersect( $addon_ids, $license_product_ids );
20175 if ( count( $new_account_addons ) !== count( $account_addons ) ) {
20176 $this->_store_account_addons( array_unique( $new_account_addons ) );
20177 }
20178
20179 return $new_account_addons;
20180 }
20181
20182 /**
20183 * Store account params in the Database.
20184 *
20185 * @author Vova Feldman (@svovaf)
20186 * @since 1.0.1
20187 *
20188 * @param null|int $blog_id Since 2.0.0
20189 */
20190 private function _store_account( $blog_id = null ) {
20191 $this->_logger->entrance();
20192
20193 $this->_store_site( false, $blog_id );
20194 $this->_store_user( false );
20195 $this->_store_plans( false );
20196 $this->_store_licenses( false );
20197
20198 self::$_accounts->store( $blog_id );
20199 }
20200
20201 /**
20202 * Sync user's information.
20203 *
20204 * @author Vova Feldman (@svovaf)
20205 * @since 1.0.3
20206 * @uses FS_Api
20207 */
20208 private function _handle_account_user_sync() {
20209 $this->_logger->entrance();
20210
20211 $api = $this->get_api_user_scope();
20212
20213 // Get user's information.
20214 $user = $api->get( '/', true );
20215
20216 if ( isset( $user->id ) ) {
20217 $this->_user->first = $user->first;
20218 $this->_user->last = $user->last;
20219 $this->_user->email = $user->email;
20220
20221 $is_menu_item_account_visible = $this->is_submenu_item_visible( 'account' );
20222
20223 if ( $user->is_verified &&
20224 ( ! isset( $this->_user->is_verified ) || false === $this->_user->is_verified )
20225 ) {
20226 $this->_user->is_verified = true;
20227
20228 $this->do_action( 'account_email_verified', $user->email );
20229
20230 $this->_admin_notices->add(
20231 $this->get_text_inline( 'Your email has been successfully verified - you are AWESOME!', 'email-verified-message' ),
20232 $this->get_text_x_inline( 'Right on', 'a positive response', 'right-on' ) . '!',
20233 'success',
20234 // Make admin sticky if account menu item is invisible,
20235 // since the page will be auto redirected to the plugin's
20236 // main settings page, and the non-sticky message
20237 // will disappear.
20238 ! $is_menu_item_account_visible,
20239 'email_verified'
20240 );
20241 }
20242
20243 // Flush user details to DB.
20244 $this->_store_user();
20245
20246 $this->do_action( 'after_account_user_sync', $user );
20247
20248 /**
20249 * If account menu item is hidden, redirect to plugin's main settings page.
20250 *
20251 * @author Vova Feldman (@svovaf)
20252 * @since 1.1.6
20253 *
20254 * @link https://github.com/Freemius/wordpress-sdk/issues/6
20255 */
20256 if ( ! $is_menu_item_account_visible ) {
20257 fs_redirect( $this->_get_admin_page_url() );
20258 }
20259 }
20260 }
20261
20262 /**
20263 * @author Vova Feldman (@svovaf)
20264 * @since 1.0.9
20265 * @uses FS_Api
20266 *
20267 * @param number|bool $license_id
20268 *
20269 * @return FS_Subscription|object|bool
20270 */
20271 private function _fetch_site_license_subscription( $license_id = false ) {
20272 $this->_logger->entrance();
20273 $api = $this->get_api_site_scope();
20274
20275 if ( ! is_numeric( $license_id ) ) {
20276 $license_id = FS_Plugin_License::is_valid_id( $this->_license->parent_license_id ) ?
20277 $this->_license->parent_license_id :
20278 $this->_license->id;
20279 }
20280
20281 $result = $api->get( "/licenses/{$license_id}/subscriptions.json", true );
20282
20283 return ! isset( $result->error ) ?
20284 ( ( is_array( $result->subscriptions ) && 0 < count( $result->subscriptions ) ) ?
20285 new FS_Subscription( $result->subscriptions[0] ) :
20286 false
20287 ) :
20288 $result;
20289 }
20290
20291 /**
20292 * @author Vova Feldman (@svovaf)
20293 * @since 1.0.4
20294 * @uses FS_Api
20295 *
20296 * @param number|bool $plan_id
20297 *
20298 * @return FS_Plugin_Plan|object
20299 */
20300 private function _fetch_site_plan( $plan_id = false ) {
20301 $this->_logger->entrance();
20302 $api = $this->get_api_site_scope();
20303
20304 if ( ! is_numeric( $plan_id ) ) {
20305 $plan_id = $this->_site->plan_id;
20306 }
20307
20308 $plan = $api->get( "/plans/{$plan_id}.json", true );
20309
20310 return ! isset( $plan->error ) ? new FS_Plugin_Plan( $plan ) : $plan;
20311 }
20312
20313 /**
20314 * @author Vova Feldman (@svovaf)
20315 * @since 1.0.5
20316 * @uses FS_Api
20317 *
20318 * @return FS_Plugin_Plan[]|object
20319 */
20320 private function _fetch_plugin_plans() {
20321 $this->_logger->entrance();
20322 $api = $this->get_current_or_network_user_api_scope();
20323
20324 /**
20325 * @since 1.2.3 When running in DEV mode, retrieve pending plans as well.
20326 */
20327 $result = $api->get( $this->add_show_pending( "/plugins/{$this->_module_id}/plans.json" ), true );
20328
20329 if ( $this->is_api_result_object( $result, 'plans' ) && is_array( $result->plans ) ) {
20330 for ( $i = 0, $len = count( $result->plans ); $i < $len; $i ++ ) {
20331 $result->plans[ $i ] = new FS_Plugin_Plan( $result->plans[ $i ] );
20332 }
20333
20334 $result = $result->plans;
20335 }
20336
20337 return $result;
20338 }
20339
20340 /**
20341 * @author Vova Feldman (@svovaf)
20342 * @since 2.0.0
20343 *
20344 * @param number $plan_id
20345 *
20346 * @return \FS_Plugin_Plan|object
20347 */
20348 private function fetch_plan_by_id( $plan_id ) {
20349 $this->_logger->entrance();
20350 $api = $this->get_current_or_network_user_api_scope();
20351
20352 $result = $api->get( "/plugins/{$this->_module_id}/plans/{$plan_id}.json", true );
20353
20354 return $this->is_api_result_entity( $result ) ?
20355 new FS_Plugin_Plan( $result ) :
20356 $result;
20357 }
20358
20359 /**
20360 * @author Vova Feldman (@svovaf)
20361 * @since 1.0.5
20362 * @uses FS_Api
20363 *
20364 * @param number|bool $plugin_id
20365 * @param number|bool $site_license_id
20366 * @param array $foreign_licenses @since 2.0.0. This is used by network-activated plugins.
20367 * @param number|null $blog_id
20368 *
20369 * @return FS_Plugin_License[]|object
20370 */
20371 private function _fetch_licenses(
20372 $plugin_id = false,
20373 $site_license_id = false,
20374 $foreign_licenses = array(),
20375 $blog_id = null
20376 ) {
20377 $this->_logger->entrance();
20378
20379 $api = $this->get_api_user_scope();
20380
20381 if ( ! is_numeric( $plugin_id ) ) {
20382 $plugin_id = $this->_plugin->id;
20383 }
20384
20385 $user_licenses_endpoint = "/plugins/{$plugin_id}/licenses.json?is_enriched=true";
20386 if ( ! empty ( $foreign_licenses ) ) {
20387 $foreign_licenses = array(
20388 // Prefix with `+` to tell the server to include foreign licenses in the licenses collection.
20389 'ids' => ( urlencode( '+' ) . implode( ',', $foreign_licenses['ids'] ) ),
20390 'license_keys' => implode( ',', array_map( 'urlencode', $foreign_licenses['license_keys'] ) )
20391 );
20392
20393 $user_licenses_endpoint = add_query_arg( $foreign_licenses, $user_licenses_endpoint );
20394 }
20395
20396 $result = $api->get( $user_licenses_endpoint, true );
20397
20398 $is_site_license_synced = false;
20399
20400 $api_errors = array();
20401
20402 if ( $this->is_api_result_object( $result, 'licenses' ) &&
20403 is_array( $result->licenses )
20404 ) {
20405 for ( $i = 0, $len = count( $result->licenses ); $i < $len; $i ++ ) {
20406 $result->licenses[ $i ] = new FS_Plugin_License( $result->licenses[ $i ] );
20407
20408 if ( ( ! $is_site_license_synced ) && is_numeric( $site_license_id ) ) {
20409 $is_site_license_synced = ( $site_license_id == $result->licenses[ $i ]->id );
20410 }
20411 }
20412
20413 $result = $result->licenses;
20414 } else {
20415 $api_errors[] = $result;
20416 $result = array();
20417 }
20418
20419 if ( ! $is_site_license_synced ) {
20420 if ( ! is_null( $blog_id ) ) {
20421 /**
20422 * If blog ID is not null, the request is for syncing of the license of a single site via the
20423 * network-level "Account" page.
20424 *
20425 * @author Leo Fajardo (@leorw)
20426 */
20427 $this->switch_to_blog( $blog_id );
20428 }
20429
20430 $api = $this->get_api_site_scope();
20431
20432 if ( is_numeric( $site_license_id ) ) {
20433 // Try to retrieve a foreign license that is linked to the install.
20434 $api_result = $api->call( '/licenses.json?is_enriched=true' );
20435
20436 if ( $this->is_api_result_object( $api_result, 'licenses' ) &&
20437 is_array( $api_result->licenses )
20438 ) {
20439 $licenses = $api_result->licenses;
20440
20441 if ( ! empty( $licenses ) ) {
20442 $result[] = new FS_Plugin_License( $licenses[0] );
20443 }
20444 } else {
20445 $api_errors[] = $api_result;
20446 }
20447 } else if (
20448 is_object( $this->_license ) &&
20449 /**
20450 * Sync only if the license belongs to the context plugin. `$plugin_id` can be an add-on ID while
20451 * the FS instance that does the syncing is the parent FS instance.
20452 *
20453 * @author Leo Fajardo (@leorw)
20454 * @since 2.3.0
20455 */
20456 $this->_license->plugin_id == $plugin_id
20457 ) {
20458 $is_license_in_result = false;
20459 if ( ! empty( $result ) ) {
20460 foreach ( $result as $license ) {
20461 if ( $license->id == $this->_license->id ) {
20462 $is_license_in_result = true;
20463 break;
20464 }
20465 }
20466 }
20467
20468 if ( ! $is_license_in_result ) {
20469 // Fetch foreign license by ID and license key.
20470 $license = $api->get( "/licenses/{$this->_license->id}.json?license_key=" .
20471 urlencode( $this->_license->secret_key ) . '&is_enriched=true' );
20472
20473 if ( $this->is_api_result_entity( $license ) ) {
20474 $result[] = new FS_Plugin_License( $license );
20475 } else {
20476 $api_errors[] = $license;
20477 }
20478 }
20479 }
20480
20481 if ( ! is_null( $blog_id ) ) {
20482 $this->switch_to_blog( $this->_storage->network_install_blog_id );
20483 }
20484 }
20485
20486 if ( is_array( $result ) && 0 < count( $result ) ) {
20487 // If found at least one license, return license collection even if there are errors.
20488 return $result;
20489 }
20490
20491 if ( ! empty( $api_errors ) ) {
20492 // If found any errors and no licenses, return first error.
20493 return $api_errors[0];
20494 }
20495
20496 // Fallback to empty licenses list.
20497 return $result;
20498 }
20499
20500 /**
20501 * @author Vova Feldman (@svovaf)
20502 * @since 2.0.0
20503 *
20504 * @param number $license_id
20505 * @param string $license_key
20506 *
20507 * @return \FS_Plugin_License|object
20508 */
20509 private function fetch_license_by_key( $license_id, $license_key ) {
20510 $this->_logger->entrance();
20511
20512 $api = $this->get_current_or_network_user_api_scope();
20513
20514 $result = $api->get( "/licenses/{$license_id}.json?license_key=" . urlencode( $license_key ) );
20515
20516 return $this->is_api_result_entity( $result ) ?
20517 new FS_Plugin_License( $result ) :
20518 $result;
20519 }
20520
20521 /**
20522 * @author Vova Feldman (@svovaf)
20523 * @since 1.2.0
20524 * @uses FS_Api
20525 *
20526 * @param number|bool $plugin_id
20527 * @param bool $flush
20528 *
20529 * @return FS_Payment[]|object
20530 */
20531 function _fetch_payments( $plugin_id = false, $flush = false ) {
20532 $this->_logger->entrance();
20533
20534 $api = $this->get_api_user_scope();
20535
20536 if ( ! is_numeric( $plugin_id ) ) {
20537 $plugin_id = $this->_plugin->id;
20538 }
20539
20540 $include_bundles = (
20541 is_object( $this->_plugin ) &&
20542 FS_Plugin::is_valid_id( $this->_plugin->bundle_id )
20543 );
20544
20545 $result = $api->get(
20546 "/plugins/{$plugin_id}/payments.json?include_addons=true" . ($include_bundles ? '&include_bundles=true' : ''),
20547 $flush
20548 );
20549
20550 if ( ! isset( $result->error ) ) {
20551 for ( $i = 0, $len = count( $result->payments ); $i < $len; $i ++ ) {
20552 $result->payments[ $i ] = new FS_Payment( $result->payments[ $i ] );
20553 }
20554 $result = $result->payments;
20555 }
20556
20557 return $result;
20558 }
20559
20560 /**
20561 * @author Vova Feldman (@svovaf)
20562 * @since 1.2.1.5
20563 * @uses FS_Api
20564 *
20565 * @param bool $flush
20566 *
20567 * @return \FS_Billing|mixed
20568 */
20569 function _fetch_billing( $flush = false ) {
20570 require_once WP_FS__DIR_INCLUDES . '/entities/class-fs-billing.php';
20571
20572 $billing = $this->get_api_user_scope()->get( 'billing.json', $flush );
20573
20574 if ( $this->is_api_result_entity( $billing ) ) {
20575 $billing = new FS_Billing( $billing );
20576 }
20577
20578 return $billing;
20579 }
20580
20581 /**
20582 * @author Vova Feldman (@svovaf)
20583 * @since 1.0.5
20584 *
20585 * @param FS_Plugin_License[] $licenses
20586 * @param number $module_id
20587 */
20588 private function _update_licenses( $licenses, $module_id ) {
20589 $this->_logger->entrance();
20590
20591 if ( is_array( $licenses ) ) {
20592 for ( $i = 0, $len = count( $licenses ); $i < $len; $i ++ ) {
20593 $licenses[ $i ]->updated = time();
20594 }
20595 }
20596
20597 $this->_store_licenses( true, $module_id, $licenses );
20598 }
20599
20600 /**
20601 * @author Vova Feldman (@svovaf)
20602 * @since 1.0.4
20603 *
20604 * @param bool|number $plugin_id
20605 * @param bool $flush Since 1.1.7.3
20606 * @param int $expiration Since 1.2.2.7
20607 * @param bool|string $newer_than Since 2.2.1
20608 *
20609 * @return object|false New plugin tag info if exist.
20610 */
20611 private function _fetch_newer_version( $plugin_id = false, $flush = true, $expiration = WP_FS__TIME_24_HOURS_IN_SEC, $newer_than = false ) {
20612 $latest_tag = $this->_fetch_latest_version( $plugin_id, $flush, $expiration, $newer_than );
20613
20614 if ( ! is_object( $latest_tag ) ) {
20615 return false;
20616 }
20617
20618 $plugin_version = $this->get_plugin_version();
20619
20620 // Check if version is actually newer.
20621 $has_new_version =
20622 // If it's an non-installed add-on then always return latest.
20623 ( $this->_is_addon_id( $plugin_id ) && ! $this->is_addon_activated( $plugin_id ) ) ||
20624 // Compare versions.
20625 version_compare( $plugin_version, $latest_tag->version, '<' );
20626
20627 $this->_logger->departure( $has_new_version ? 'Found newer plugin version ' . $latest_tag->version : 'No new version' );
20628
20629 $is_latest_version_beta = ( 'beta' === $latest_tag->release_mode );
20630
20631 $this->_storage->beta_data = array(
20632 'is_beta' => $is_latest_version_beta,
20633 'version' => $latest_tag->version
20634 );
20635
20636 return $has_new_version ? $latest_tag : false;
20637 }
20638
20639 /**
20640 * @author Vova Feldman (@svovaf)
20641 * @since 1.0.5
20642 *
20643 * @param bool|number $plugin_id
20644 * @param bool $flush Since 1.1.7.3
20645 * @param int $expiration Since 1.2.2.7
20646 * @param bool|string $newer_than Since 2.2.1
20647 *
20648 * @return bool|FS_Plugin_Tag
20649 */
20650 function get_update( $plugin_id = false, $flush = true, $expiration = FS_Plugin_Updater::UPDATES_CHECK_CACHE_EXPIRATION, $newer_than = false ) {
20651 $this->_logger->entrance();
20652
20653 if ( ! is_numeric( $plugin_id ) ) {
20654 $plugin_id = $this->_plugin->id;
20655 }
20656
20657 $this->check_updates( true, $plugin_id, $flush, $expiration, $newer_than );
20658 $updates = $this->get_all_updates();
20659
20660 return isset( $updates[ $plugin_id ] ) && is_object( $updates[ $plugin_id ] ) ? $updates[ $plugin_id ] : false;
20661 }
20662
20663 /**
20664 * Check if site assigned with active license.
20665 *
20666 * @author Vova Feldman (@svovaf)
20667 * @since 1.0.6
20668 *
20669 * @deprecated Please use has_active_valid_license() instead because license can be cancelled.
20670 */
20671 function has_active_license() {
20672 return (
20673 is_object( $this->_license ) &&
20674 is_numeric( $this->_license->id ) &&
20675 ! $this->_license->is_expired()
20676 );
20677 }
20678
20679 /**
20680 * Check if site assigned with active & valid (not expired) license.
20681 *
20682 * @author Vova Feldman (@svovaf)
20683 * @since 1.2.1
20684 *
20685 * @param bool $check_expiration
20686 */
20687 function has_active_valid_license( $check_expiration = true ) {
20688 return self::is_active_valid_license( $this->_license, $check_expiration );
20689 }
20690
20691 /**
20692 * @author Leo Fajardo (@leorw)
20693 * @since 2.3.1
20694 */
20695 function is_data_debug_mode() {
20696 if ( is_null( $this->is_whitelabeled ) || ! $this->is_whitelabeled ) {
20697 return false;
20698 }
20699
20700 $fs = $this->is_addon() ?
20701 $this->get_parent_instance() :
20702 $this;
20703
20704 if ( $fs->is_network_active() && fs_is_network_admin() ) {
20705 $is_developer_license_debug_mode = get_site_transient( "fs_{$this->get_id()}_data_debug_mode" );
20706 } else {
20707 $is_developer_license_debug_mode = get_transient( "fs_{$this->get_id()}_data_debug_mode" );
20708 }
20709
20710 return ( 'true' === $is_developer_license_debug_mode );
20711 }
20712
20713 /**
20714 * @author Leo Fajardo (@leorw)
20715 * @since 2.3.1
20716 */
20717 function _set_data_debug_mode() {
20718 if ( ! $this->is_whitelabeled( true ) ) {
20719 return;
20720 }
20721
20722 $license_or_user_key = fs_request_get_raw( 'license_or_user_key' );
20723
20724 $transient_value = ( ! empty( $license_or_user_key ) ) ?
20725 'true' :
20726 'false';
20727
20728 if ( 'true' === $transient_value ) {
20729 $stored_key = $this->_storage->get( ! FS_User::is_valid_id( $this->_storage->last_license_user_id ) ?
20730 'last_license_key' :
20731 'last_license_user_key'
20732 );
20733
20734 if ( md5( $license_or_user_key ) !== $stored_key ) {
20735 $this->shoot_ajax_failure( sprintf(
20736 '%s... %s',
20737 $this->get_text_x_inline( 'Oops', 'exclamation', 'oops' ),
20738 $this->get_text_inline(
20739 'seems like the key you entered doesn\'t match our records.',
20740 'developer-or-license-not-found'
20741 )
20742 ) );
20743 }
20744 }
20745
20746 if ( $this->is_network_active() && fs_is_network_admin() ) {
20747 set_site_transient(
20748 "fs_{$this->get_id()}_data_debug_mode",
20749 $transient_value,
20750 WP_FS__TIME_24_HOURS_IN_SEC / 24
20751 );
20752 } else {
20753 set_transient(
20754 "fs_{$this->get_id()}_data_debug_mode",
20755 $transient_value,
20756 WP_FS__TIME_24_HOURS_IN_SEC / 24
20757 );
20758 }
20759
20760 if ( 'true' === $transient_value ) {
20761 $this->_admin_notices->add_sticky(
20762 $this->get_text_inline(
20763 '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.',
20764 'data_debug_mode_enabled'
20765 ),
20766 'data_debug_mode_enabled'
20767 );
20768 }
20769
20770 $this->shoot_ajax_success();
20771 }
20772
20773 /**
20774 * Check if a given license is active & valid (not expired).
20775 *
20776 * @author Vova Feldman (@svovaf)
20777 * @since 2.1.3
20778 *
20779 * @param FS_Plugin_License $license
20780 * @param bool $check_expiration
20781 *
20782 * @return bool
20783 */
20784 private static function is_active_valid_license( $license, $check_expiration = true ) {
20785 return (
20786 is_object( $license ) &&
20787 FS_Plugin_License::is_valid_id( $license->id ) &&
20788 $license->is_active() &&
20789 ( ! $check_expiration || $license->is_valid() )
20790 );
20791 }
20792
20793 /**
20794 * Checks if there's any site that is associated with an active & valid license.
20795 * This logic is used to determine if the admin can download the premium code base from a network level admin.
20796 *
20797 * @author Vova Feldman (@svovaf)
20798 * @since 2.1.3
20799 *
20800 * @return bool
20801 */
20802 function has_any_active_valid_license() {
20803 if ( ! fs_is_network_admin() ) {
20804 return $this->has_active_valid_license();
20805 }
20806
20807 $installs = $this->get_blog_install_map();
20808 $all_plugin_licenses = self::get_all_licenses( $this->_module_id );
20809
20810 foreach ( $installs as $blog_id => $install ) {
20811 if ( ! FS_Plugin_License::is_valid_id( $install->license_id ) ) {
20812 continue;
20813 }
20814
20815 foreach ( $all_plugin_licenses as $license ) {
20816 if ( $license->id == $install->license_id ) {
20817 if ( self::is_active_valid_license( $license ) ) {
20818 return true;
20819 }
20820 }
20821 }
20822 }
20823
20824 return false;
20825 }
20826
20827 /**
20828 * Check if site assigned with license with enabled features.
20829 *
20830 * @author Vova Feldman (@svovaf)
20831 * @since 1.0.6
20832 *
20833 * @return bool
20834 */
20835 function has_features_enabled_license() {
20836 return (
20837 is_object( $this->_license ) &&
20838 is_numeric( $this->_license->id ) &&
20839 $this->_license->is_features_enabled()
20840 );
20841 }
20842
20843 /**
20844 * Checks if the product is activated with a bundle license.
20845 *
20846 * @author Leo Fajardo (@leorw)
20847 * @since 2.4.0
20848 *
20849 * @return bool
20850 */
20851 function is_activated_with_bundle_license() {
20852 if ( ! $this->has_features_enabled_license() ) {
20853 return false;
20854 }
20855
20856 return FS_Plugin_License::is_valid_id( $this->_license->parent_license_id );
20857 }
20858
20859 /**
20860 * Check if user is a trial or have feature enabled license.
20861 *
20862 * @author Vova Feldman (@svovaf)
20863 * @since 1.1.7
20864 *
20865 * @return bool
20866 */
20867 function can_use_premium_code() {
20868 return $this->is_trial() || $this->has_features_enabled_license();
20869 }
20870
20871 /**
20872 * Checks if the current user can activate plugins or switch themes. Note that this method should only be used
20873 * after the `init` action is triggered because it is using `current_user_can()` which is only functional after
20874 * the context user is authenticated.
20875 *
20876 * @author Leo Fajardo (@leorw)
20877 * @since 1.2.2
20878 *
20879 * @return bool
20880 */
20881 function is_user_admin() {
20882 /**
20883 * Require a super-admin when network activated, running from the network level OR if
20884 * running from the site level but not delegated the opt-in.
20885 *
20886 * @author Vova Feldman (@svovaf)
20887 * @since 2.0.0
20888 */
20889 if ( $this->_is_network_active &&
20890 ( fs_is_network_admin() || ! $this->is_delegated_connection() )
20891 ) {
20892 return is_super_admin();
20893 }
20894
20895 return ( $this->is_plugin() && current_user_can( is_multisite() ? 'manage_options' : 'activate_plugins' ) )
20896 || ( $this->is_theme() && current_user_can( 'switch_themes' ) );
20897 }
20898
20899 /**
20900 * Sync site's plan.
20901 *
20902 * @author Vova Feldman (@svovaf)
20903 * @since 1.0.3
20904 *
20905 * @uses FS_Api
20906 *
20907 * @param bool $background Hints the method if it's a background sync. If false, it means that was initiated by
20908 * the admin.
20909 * @param bool $is_context_single_site @since 2.0.0. This is used when syncing a license for a single install from the
20910 * network-level "Account" page.
20911 * @param int|null $current_blog_id @since 2.2.3. This is passed from the `execute_cron` method and used by the
20912 * `_sync_plugin_license` method in order to switch to the previous blog when sending
20913 * updates for a single site in case `execute_cron` has switched to a different blog.
20914 */
20915 private function _sync_license( $background = false, $is_context_single_site = false, $current_blog_id = null ) {
20916 $this->_logger->entrance();
20917
20918 $plugin_id = fs_request_get( 'plugin_id', $this->get_id() );
20919
20920 $is_addon_sync = ( ! $this->_plugin->is_addon() && $plugin_id != $this->get_id() );
20921
20922 if ( $is_addon_sync ) {
20923 $this->_sync_addon_license( $plugin_id, $background );
20924 } else {
20925 $this->_sync_plugin_license( $background, true, $is_context_single_site, $current_blog_id );
20926 }
20927
20928 $this->do_action( 'after_account_plan_sync', $this->get_plan_name() );
20929 }
20930
20931 /**
20932 * Sync plugin's add-on license.
20933 *
20934 * @author Vova Feldman (@svovaf)
20935 * @since 1.0.6
20936 * @uses FS_Api
20937 *
20938 * @param number $addon_id
20939 * @param bool $background
20940 */
20941 private function _sync_addon_license( $addon_id, $background ) {
20942 $this->_logger->entrance();
20943
20944 if ( $this->is_addon_activated( $addon_id ) ) {
20945 // If already installed, use add-on sync.
20946 $fs_addon = self::get_instance_by_id( $addon_id );
20947
20948 if (
20949 // Add-on is network activated and network integrated.
20950 $fs_addon->is_network_active() ||
20951 // Background sync cron.
20952 self::is_cron() ||
20953 // Add-on is not network activated or not network integrated.
20954 ! fs_is_network_admin()
20955 ) {
20956 $fs_addon->_sync_license( $background );
20957
20958 return;
20959 }
20960 }
20961
20962 // Validate add-on exists.
20963 $addon = $this->get_addon( $addon_id );
20964
20965 if ( ! is_object( $addon ) ) {
20966 return;
20967 }
20968
20969 // Add add-on into account add-ons.
20970 $account_addons = $this->get_account_addons();
20971 if ( ! is_array( $account_addons ) ) {
20972 $account_addons = array();
20973 }
20974 $account_addons[] = $addon->id;
20975 $account_addons = array_unique( $account_addons );
20976 $this->_store_account_addons( $account_addons );
20977
20978 // Load add-on licenses.
20979 $licenses = $this->_fetch_licenses( $addon->id );
20980
20981 // Sync add-on licenses.
20982 if ( $this->is_array_instanceof( $licenses, 'FS_Plugin_License' ) ) {
20983 $this->_update_licenses( $licenses, $addon->id );
20984
20985 if ( ! $this->is_addon_installed( $addon->id ) && FS_License_Manager::has_premium_license( $licenses ) ) {
20986 $plans_result = $this->get_api_site_or_plugin_scope()->get( $this->add_show_pending( "/addons/{$addon_id}/plans.json" ) );
20987
20988 if ( ! isset( $plans_result->error ) ) {
20989 $plans = array();
20990 foreach ( $plans_result->plans as $plan ) {
20991 $plans[] = new FS_Plugin_Plan( $plan );
20992 }
20993
20994 $this->_admin_notices->add_sticky(
20995 sprintf(
20996 ( FS_Plan_Manager::instance()->has_free_plan( $plans ) ?
20997 $this->get_text_inline( 'Your %s Add-on plan was successfully upgraded.', 'addon-successfully-upgraded-message' ) :
20998 /* translators: %s:product name, e.g. Facebook add-on was successfully... */
20999 $this->get_text_inline( '%s Add-on was successfully purchased.', 'addon-successfully-purchased-message' ) ),
21000 $addon->title
21001 ) . ' ' . $this->get_latest_download_link(
21002 $this->get_text_inline( 'Download the latest version', 'download-latest-version' ),
21003 $addon_id
21004 ),
21005 'addon_plan_upgraded_' . $addon->slug,
21006 $this->get_text_x_inline( 'Yee-haw', 'interjection expressing joy or exuberance', 'yee-haw' ) . '!'
21007 );
21008 }
21009 }
21010 }
21011 }
21012
21013 /**
21014 * Sync site's plugin plan.
21015 *
21016 * @author Vova Feldman (@svovaf)
21017 * @since 1.0.6
21018 * @uses FS_Api
21019 *
21020 * @param bool $background Hints the method if it's a background sync. If false, it means that was initiated by the admin.
21021 * @param bool $send_installs_update Since 2.0.0
21022 * @param bool $is_context_single_site Since 2.0.0. This is used when sending an update for a single install and
21023 * syncing its license from the network-level "Account" page (e.g.: after
21024 * activating a license only for the single install).
21025 * @param int|null $current_blog_id Since 2.2.3. This is passed from the `execute_cron` method so that it
21026 * can be used here to switch to the previous blog in case `execute_cron`
21027 * has switched to a different blog.
21028 */
21029 private function _sync_plugin_license(
21030 $background = false,
21031 $send_installs_update = true,
21032 $is_context_single_site = false,
21033 $current_blog_id = null
21034 ) {
21035 $this->_logger->entrance();
21036
21037 $plan_change = 'none';
21038
21039 $is_site_level_sync = ( $is_context_single_site || fs_is_blog_admin() || ! $this->_is_network_active );
21040
21041 if ( ! $send_installs_update ) {
21042 $site = $this->_site;
21043 } else {
21044 /**
21045 * Sync site info.
21046 *
21047 * @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.
21048 */
21049 if ( $is_site_level_sync ) {
21050 /**
21051 * Switch to the previous blog since `execute_cron` may have switched to a different blog.
21052 *
21053 * @author Leo Fajardo (@leorw)
21054 * @since 2.2.3
21055 */
21056 if ( is_numeric( $current_blog_id ) ) {
21057 $this->switch_to_blog( $current_blog_id );
21058 }
21059
21060 $result = $this->send_install_update( array(), true, true );
21061 $is_valid = $this->is_api_result_entity( $result );
21062 } else {
21063 $result = $this->send_installs_update( array(), true, true );
21064 $is_valid = $this->is_api_result_object( $result, 'installs' );
21065 }
21066
21067 if ( ! $is_valid ) {
21068 if ( $is_context_single_site ) {
21069 // Switch back to the main blog so that the following logic will have the right entities.
21070 $this->switch_to_blog( $this->_storage->network_install_blog_id );
21071 }
21072
21073 // Show API message only if not background sync or if paying customer.
21074 if ( ! $background || $this->is_paying() ) {
21075 // Try to ping API to see if not blocked.
21076 if ( FS_Api::is_blocked( $result ) ) {
21077 /**
21078 * @author Vova Feldman (@svovaf)
21079 * @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.
21080 */
21081 if ( ! self::$_global_admin_notices->has_sticky( 'api_blocked' ) ) {
21082 // Add notice immediately if not a background sync.
21083 $add_notice = ( ! $background );
21084
21085 if ( ! $add_notice ) {
21086 $counter = (int) get_transient( '_fs_api_connection_retry_counter' );
21087
21088 // We only want to add the notice after 3 consecutive failures.
21089 $add_notice = ( 3 <= $counter );
21090
21091 if ( ! $add_notice ) {
21092 /**
21093 * 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.
21094 *
21095 * 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.
21096 */
21097 set_transient( '_fs_api_connection_retry_counter', $counter + 1, WP_FS__TIME_WEEK_IN_SEC );
21098 }
21099 }
21100
21101 // Add notice instantly for not-background sync and only after 3 failed attempts for background sync.
21102 if ( $add_notice ) {
21103 self::$_global_admin_notices->add(
21104 $this->generate_api_blocked_notice_message_from_result( $result ),
21105 '',
21106 'error',
21107 $background,
21108 'api_blocked'
21109 );
21110
21111 add_action( 'admin_footer', array( 'Freemius', '_add_api_connectivity_notice_handler_js' ) );
21112
21113 // Notice was just shown, reset connectivity counter.
21114 delete_transient( '_fs_api_connection_retry_counter' );
21115 }
21116 }
21117 } else if ( is_object( $result ) ) {
21118 // Authentication params are broken.
21119 $this->_admin_notices->add(
21120 $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 ),
21121 '',
21122 'error'
21123 );
21124 }
21125 }
21126
21127 // No reason to continue with license sync while there are API issues.
21128 return;
21129 }
21130
21131 // API is working now. Delete the transient and start afresh.
21132 delete_transient('_fs_api_connection_retry_counter');
21133
21134 if ( $is_site_level_sync ) {
21135 $site = new FS_Site( $result );
21136 } else {
21137 // Map site addresses to their blog IDs.
21138 $address_to_blog_map = $this->get_address_to_blog_map();
21139
21140 // Find the current context install.
21141 $site = null;
21142 foreach ( $result->installs as $install ) {
21143 if ( $install->id == $this->_site->id ) {
21144 $site = new FS_Site( $install );
21145 } else {
21146 $address = trailingslashit( fs_strip_url_protocol( $install->url ) );
21147 $blog_id = $address_to_blog_map[ $address ];
21148
21149 $this->_store_site( true, $blog_id, new FS_Site( $install ) );
21150 }
21151 }
21152 }
21153
21154 // Sync plans.
21155 $this->_sync_plans();
21156 }
21157
21158 // Remove sticky API connectivity message.
21159 self::$_global_admin_notices->remove_sticky( 'api_blocked' );
21160
21161 if ( ! $this->has_paid_plan() ) {
21162 $this->_site = $site;
21163 $this->_store_site(
21164 true,
21165 $is_site_level_sync ?
21166 null :
21167 $this->get_network_install_blog_id()
21168 );
21169 } else {
21170 $context_blog_id = 0;
21171
21172 if ( $is_context_single_site ) {
21173 $context_blog_id = get_current_blog_id();
21174
21175 // Switch back to the main blog in order to properly sync the license.
21176 $this->switch_to_blog( $this->_storage->network_install_blog_id );
21177 }
21178
21179 /**
21180 * Sync licenses. Pass the site's license ID so that the foreign licenses will be fetched if the license
21181 * associated with that ID is not included in the user's licenses collection.
21182 * Save previous value to manage remote license renewals.
21183 */
21184 $was_license_expired_before_sync = is_object( $this->_license ) && $this->_license->is_expired();
21185 $this->_sync_licenses(
21186 $site->license_id,
21187 ( $is_context_single_site ?
21188 $context_blog_id :
21189 null
21190 )
21191 );
21192
21193 if ( $is_context_single_site ) {
21194 $this->switch_to_blog( $context_blog_id );
21195 }
21196
21197 // Check if plan / license changed.
21198 if ( $site->plan_id != $this->_site->plan_id ||
21199 // Check if trial started.
21200 $site->trial_plan_id != $this->_site->trial_plan_id ||
21201 $site->trial_ends != $this->_site->trial_ends ||
21202 // Check if license changed.
21203 $site->license_id != $this->_site->license_id
21204 ) {
21205 if ( $site->is_trial() && ( ! $this->_site->is_trial() || $site->trial_ends != $this->_site->trial_ends ) ) {
21206 // New trial started.
21207 $this->_site = $site;
21208 $plan_change = 'trial_started';
21209
21210 // For trial with subscription use-case.
21211 $new_license = is_null( $site->license_id ) ? null : $this->_get_license_by_id( $site->license_id );
21212
21213 if ( is_object( $new_license ) && $new_license->is_valid() ) {
21214 $this->_site = $site;
21215 $this->_update_site_license( $new_license );
21216 $this->_store_licenses();
21217
21218 $this->_sync_site_subscription( $this->_license );
21219 }
21220 } else if ( $this->_site->is_trial() && ! $site->is_trial() && ! is_numeric( $site->license_id ) ) {
21221 // Was in trial, but now trial expired and no license ID.
21222 // New trial started.
21223 $this->_site = $site;
21224 $plan_change = 'trial_expired';
21225 } else {
21226 $is_free = $this->is_free_plan();
21227
21228 // Make sure license exist and not expired.
21229 $new_license = is_null( $site->license_id ) ?
21230 null :
21231 $this->_get_license_by_id( $site->license_id );
21232
21233 if ( $is_free && is_null( $new_license ) && $this->has_any_license() && $this->_license->is_cancelled ) {
21234 // License cancelled.
21235 $this->_site = $site;
21236 $this->_update_site_license( $new_license );
21237 $this->_store_licenses();
21238
21239 $plan_change = 'cancelled';
21240 } else if ( $is_free && ( ( ! is_object( $new_license ) || $new_license->is_expired() ) ) ) {
21241 // The license is expired, so ignore upgrade method.
21242 $this->_site = $site;
21243 } else {
21244 // License changed.
21245 $this->_site = $site;
21246
21247 /**
21248 * IMPORTANT:
21249 * 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.
21250 *
21251 * @author Vova Feldman (@svovaf)
21252 * @since 2.0.0
21253 */
21254 $this->_update_site_license( $new_license );
21255
21256 if ( ! $is_context_single_site &&
21257 fs_is_network_admin() &&
21258 $this->_is_network_active &&
21259 $new_license->quota > 1 &&
21260 get_blog_count() > 1
21261 ) {
21262 // See if license can activated on all sites.
21263 if ( ! $this->try_activate_license_on_network( $this->_user, $new_license ) ) {
21264 if ( ! fs_request_get_bool( 'auto_install' ) ) {
21265 // Open the license activation dialog box on the account page.
21266 add_action( 'admin_footer', array(
21267 &$this,
21268 '_open_license_activation_dialog_box'
21269 ) );
21270 }
21271 }
21272 }
21273
21274 $this->_store_licenses();
21275
21276 $plan_change = $is_free ?
21277 ( $this->is_only_premium() ? 'activated' : 'upgraded' ) :
21278 ( is_object( $new_license ) ?
21279 'changed' :
21280 'downgraded' );
21281 }
21282 }
21283
21284 // Store updated site info.
21285 $this->_store_site(
21286 true,
21287 $is_site_level_sync ?
21288 null :
21289 $this->get_network_install_blog_id()
21290 );
21291 } else {
21292 if ( ! is_object( $this->_license ) ) {
21293 $this->maybe_update_whitelabel_flag(
21294 FS_Plugin_License::is_valid_id( $site->license_id ) ?
21295 $this->get_license_by_id( $site->license_id ) :
21296 null
21297 );
21298 } else {
21299 $this->maybe_update_whitelabel_flag( $this->_license );
21300
21301 if ( $this->_license->is_expired() ) {
21302 if ( ! $this->has_features_enabled_license() ) {
21303 $this->_deactivate_license();
21304 $plan_change = 'downgraded';
21305 } else {
21306 $last_time_expired_license_notice_was_shown = $this->_storage->get( 'expired_license_notice_shown', 0 );
21307
21308 if ( time() - ( 14 * WP_FS__TIME_24_HOURS_IN_SEC ) >= $last_time_expired_license_notice_was_shown ) {
21309 /**
21310 * Show the expired license notice every 14 days.
21311 *
21312 * @author Leo Fajardo (@leorw)
21313 * @since 2.3.1
21314 */
21315 $plan_change = 'expired';
21316 }
21317 }
21318 } else if ( $was_license_expired_before_sync ) {
21319 /**
21320 * If license was expired but it is not anymore.
21321 *
21322 *
21323 * @author Daniele Alessandra (@danielealessandra)
21324 */
21325 $plan_change = 'extended';
21326 }
21327 }
21328
21329 if ( is_numeric( $site->license_id ) && is_object( $this->_license ) ) {
21330 $this->_sync_site_subscription( $this->_license );
21331 }
21332 }
21333
21334 if ( ! $this->is_addon() &&
21335 $this->_site->is_beta() !== $site->is_beta()
21336 ) {
21337 // Beta flag updated.
21338 $this->_site = $site;
21339
21340 $this->_store_site(
21341 true,
21342 $is_site_level_sync ?
21343 null :
21344 $this->get_network_install_blog_id()
21345 );
21346 }
21347
21348 if ( $this->is_addon() || $this->has_addons() ) {
21349 /**
21350 * Purge the valid user licenses cache so that when the "Account" or the "Add-Ons" page is loaded,
21351 * an updated valid user licenses collection will be fetched from the server which is used to also
21352 * update the account add-ons (add-ons the user has licenses for).
21353 *
21354 * @author Leo Fajardo (@leorw)
21355 * @since 2.2.4
21356 */
21357 $this->purge_valid_user_licenses_cache();
21358 }
21359 }
21360
21361 $hmm_text = $this->get_text_x_inline( 'Hmm', 'something somebody says when they are thinking about what you have just said.', 'hmm' ) . '...';
21362
21363 if ( $this->apply_filters( 'has_paid_plan_account', $this->has_paid_plan() ) ) {
21364 switch ( $plan_change ) {
21365 case 'none':
21366 if ( ! $background && is_admin() ) {
21367 $plan = $this->is_trial() ?
21368 $this->get_trial_plan() :
21369 $this->get_plan();
21370
21371 if ( $plan->is_free() ) {
21372 $this->_admin_notices->add(
21373 sprintf(
21374 $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' ),
21375 '<i><b>' . $plan->title . ( $this->is_trial() ? ' ' . $this->get_text_x_inline( 'Trial', 'trial period', 'trial' ) : '' ) . '</b></i>'
21376 ) . ' ' . sprintf(
21377 '<a href="%s">%s</a>',
21378 $this->contact_url(
21379 'bug',
21380 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' ),
21381 strtoupper( $plan->name )
21382 )
21383 ),
21384 $this->get_text_inline( 'Please contact us here', 'contact-us-here' )
21385 ),
21386 $hmm_text
21387 );
21388 }
21389 }
21390 break;
21391 case 'upgraded':
21392 case 'activated':
21393 $this->add_after_plan_activation_or_upgrade_instructions_notice( 'upgraded' === $plan_change );
21394
21395 $this->_admin_notices->remove_sticky( array(
21396 'trial_started',
21397 'trial_promotion',
21398 'trial_expired',
21399 'activation_complete',
21400 'license_expired',
21401 ) );
21402 break;
21403 case 'extended':
21404 $this->_admin_notices->remove_sticky( array(
21405 'trial_expired',
21406 'license_expired',
21407 ) );
21408 break;
21409 case 'changed':
21410 $this->_admin_notices->add_sticky(
21411 sprintf(
21412 $this->get_text_inline( 'Your plan was successfully changed to %s.', 'plan-changed-to-x-message' ),
21413 $this->get_plan_title()
21414 ),
21415 'plan_changed'
21416 );
21417
21418 $this->_admin_notices->remove_sticky( array(
21419 'trial_started',
21420 'trial_promotion',
21421 'trial_expired',
21422 'activation_complete',
21423 ) );
21424 break;
21425 case 'downgraded':
21426 $this->_admin_notices->add_sticky(
21427 ($this->has_free_plan() ?
21428 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 ) :
21429 /* translators: %1$s: product title; %2$s, %3$s: wrapping HTML anchor element; %4$s: 'plugin', 'theme', or 'add-on'. */
21430 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) ) ),
21431 'license_expired',
21432 $hmm_text
21433 );
21434 $this->_admin_notices->remove_sticky( 'plan_upgraded' );
21435 break;
21436 case 'cancelled':
21437 $this->_admin_notices->add(
21438 $this->get_text_inline( 'Your license has been cancelled. If you think it\'s a mistake, please contact support.', 'license-cancelled' ) . ' ' .
21439 sprintf(
21440 '<a href="%s">%s</a>',
21441 $this->contact_url( 'bug' ),
21442 $this->get_text_inline( 'Please contact us here', 'contact-us-here' )
21443 ),
21444 $hmm_text,
21445 'error'
21446 );
21447 $this->_admin_notices->remove_sticky( 'plan_upgraded' );
21448 break;
21449 case 'expired':
21450 $this->_admin_notices->add_sticky(
21451 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 ),
21452 'license_expired',
21453 $hmm_text
21454 );
21455
21456 $this->_storage->expired_license_notice_shown = WP_FS__SCRIPT_START_TIME;
21457
21458 $this->_admin_notices->remove_sticky( 'plan_upgraded' );
21459 break;
21460 case 'trial_started':
21461 $this->add_complete_upgrade_instructions_notice(
21462 sprintf(
21463 $this->get_text_inline( 'Your trial has been successfully started.', 'trial-started-message' ),
21464 '<i>' . $this->get_plugin_name() . '</i>'
21465 ),
21466 'trial_started',
21467 $this->get_trial_plan()->title
21468 );
21469
21470 $this->_admin_notices->remove_sticky( array(
21471 'trial_promotion',
21472 ) );
21473 break;
21474 case 'trial_expired':
21475 $this->_admin_notices->add_sticky(
21476 ($this->has_free_plan() ?
21477 $this->get_text_inline( 'Your free trial has expired. You can still continue using all our free features.', 'trial-expired-message' ) :
21478 /* translators: %1$s: product title; %2$s, %3$s: wrapping HTML anchor element; %4$s: 'plugin', 'theme', or 'add-on'. */
21479 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))),
21480 'trial_expired',
21481 $hmm_text
21482 );
21483 $this->_admin_notices->remove_sticky( array(
21484 'trial_started',
21485 'trial_promotion',
21486 'plan_upgraded',
21487 ) );
21488 break;
21489 }
21490 }
21491
21492 if ( 'none' !== $plan_change ) {
21493 if (
21494 ! is_object( $this->_license ) ||
21495 ! $this->_license->is_whitelabeled
21496 ) {
21497 $this->_admin_notices->remove_sticky( 'license_whitelabeled' );
21498 }
21499
21500 $this->do_action( 'after_license_change', $plan_change, $this->get_plan() );
21501 }
21502 }
21503
21504 /**
21505 * @author Leo Fajardo (@leorw)
21506 * @since 2.5.4
21507 *
21508 * @param mixed $result
21509 *
21510 * @return string
21511 */
21512 private function generate_api_blocked_notice_message_from_result( $result ) {
21513 $api_domains = $this->apply_filters( 'api_domains', array(
21514 'api.freemius.com',
21515 'wp.freemius.com',
21516 ) );
21517
21518 $api_domains_list_items = '';
21519
21520 foreach( $api_domains as $api_domain ) {
21521 $api_domains_list_items .= "<li>{$api_domain}</li>";
21522 }
21523
21524 $error_message = sprintf(
21525 $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' ),
21526 $this->get_plugin_name(),
21527 "<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>"
21528 );
21529
21530 $error_message =
21531 "<div>{$error_message}</div>" .
21532 '<div class="fs-api-request-error-details" style="display: none">' .
21533 '<strong>' . $this->get_text_inline( 'Error received from the server:', 'server-error-message' ) . '</strong><br>' .
21534 $result->error->message .
21535 '</div>';
21536
21537 return $error_message;
21538 }
21539
21540 /**
21541 * Include the required JS at the footer of the admin to trigger the license activation dialog box.
21542 *
21543 * @author Vova Feldman (@svovaf)
21544 * @since 2.0.0
21545 */
21546 public function _open_license_activation_dialog_box() {
21547 $vars = array( 'license_id' => $this->_site->license_id );
21548 fs_require_once_template( 'js/open-license-activation.php', $vars );
21549 }
21550
21551 /**
21552 * @author Vova Feldman (@svovaf)
21553 * @since 1.0.5
21554 *
21555 * @param bool $background
21556 * @param FS_Plugin_License|null $premium_license
21557 */
21558 protected function _activate_license( $background = false, $premium_license = null ) {
21559 $this->_logger->entrance();
21560
21561 if ( is_null( $premium_license ) ) {
21562 $license_id = fs_request_get( 'license_id' );
21563
21564 if ( is_object( $this->_site ) &&
21565 FS_Plugin_License::is_valid_id( $license_id ) &&
21566 $license_id == $this->_site->license_id
21567 ) {
21568 // License is already activated.
21569 return;
21570 }
21571
21572 $premium_license = FS_Plugin_License::is_valid_id( $license_id ) ?
21573 $this->_get_license_by_id( $license_id ) :
21574 $this->_get_available_premium_license();
21575 }
21576
21577 if ( ! is_object( $premium_license ) ) {
21578 return;
21579 }
21580
21581 if ( ! is_object( $this->_site ) ) {
21582 // Not yet opted-in.
21583 $user = $this->get_current_or_network_user();
21584 if ( ! is_object( $user ) ) {
21585 $user = self::_get_user_by_id( $premium_license->user_id );
21586 }
21587
21588 if ( is_object( $user ) ) {
21589 $this->install_with_user( $user, $premium_license->secret_key, false, false, false );
21590 } else {
21591 $this->opt_in(
21592 false,
21593 false,
21594 false,
21595 $premium_license->secret_key,
21596 false,
21597 false,
21598 false,
21599 null,
21600 array(),
21601 true,
21602 $premium_license->user_id
21603 );
21604
21605 return;
21606 }
21607 }
21608
21609
21610 /**
21611 * If the premium license is already associated with the install, just
21612 * update the license reference (activation is not required).
21613 *
21614 * @since 1.1.9
21615 */
21616 if ( $premium_license->id == $this->_site->license_id ) {
21617 // License is already activated.
21618 $this->_update_site_license( $premium_license );
21619 $this->_store_account();
21620
21621 return;
21622 }
21623
21624 if ( $this->_site->user_id != $premium_license->user_id ) {
21625 $api_request_params = array( 'license_key' => $premium_license->secret_key );
21626 } else {
21627 $api_request_params = array();
21628 }
21629
21630 $api = $this->get_api_site_scope();
21631 $license = $api->call( "/licenses/{$premium_license->id}.json?is_enriched=true", 'put', $api_request_params );
21632
21633 if ( ! $this->is_api_result_entity( $license ) ) {
21634 if ( ! $background ) {
21635 $this->_admin_notices->add( sprintf(
21636 '%s %s',
21637 $this->get_text_inline( 'It looks like the license could not be activated.', 'license-activation-failed-message' ),
21638 ( is_object( $license ) && isset( $license->error ) ?
21639 $license->error->message :
21640 sprintf( '%s<br><code>%s</code>',
21641 $this->get_text_inline( 'Error received from the server:', 'server-error-message' ),
21642 var_export( $license, true )
21643 )
21644 )
21645 ),
21646 $this->get_text_x_inline( 'Hmm', 'something somebody says when they are thinking about what you have just said.', 'hmm' ) . '...',
21647 'error'
21648 );
21649 }
21650
21651 return;
21652 }
21653
21654 $premium_license = new FS_Plugin_License( $license );
21655
21656 // Updated site plan.
21657 $site = $this->get_api_site_scope()->get( '/', true );
21658 if ( $this->is_api_result_entity( $site ) ) {
21659 $this->_site = new FS_Site( $site );
21660 }
21661 $this->_update_site_license( $premium_license );
21662
21663 $this->_store_account();
21664
21665 if ( $this->is_addon() || $this->has_addons() ) {
21666 /**
21667 * Purge the valid user licenses cache so that when the "Account" or the "Add-Ons" page is loaded,
21668 * an updated valid user licenses collection will be fetched from the server which is used to also
21669 * update the account add-ons (add-ons the user has licenses for).
21670 *
21671 * @author Leo Fajardo (@leorw)
21672 * @since 2.2.4
21673 */
21674 $this->purge_valid_user_licenses_cache();
21675 }
21676
21677 if ( ! $background ) {
21678 $this->add_complete_upgrade_instructions_notice(
21679 $this->get_text_inline( 'Your license was successfully activated.', 'license-activated-message' ),
21680 'license_activated'
21681 );
21682 }
21683
21684 $this->_admin_notices->remove_sticky( array(
21685 'trial_promotion',
21686 'license_expired',
21687 ) );
21688 }
21689
21690 /**
21691 * @author Vova Feldman (@svovaf)
21692 * @since 1.0.5
21693 *
21694 * @param bool $show_notice
21695 */
21696 protected function _deactivate_license( $show_notice = true ) {
21697 $this->_logger->entrance();
21698
21699 $hmm_text = $this->get_text_x_inline( 'Hmm', 'something somebody says when they are thinking about what you have just said.', 'hmm' ) . '...';
21700
21701 if ( ! FS_Plugin_License::is_valid_id( $this->_site->license_id ) ) {
21702 $this->_admin_notices->add(
21703 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() ),
21704 $hmm_text
21705 );
21706
21707 return;
21708 }
21709
21710 $api = $this->get_api_site_scope();
21711 $license = $api->call( "/licenses/{$this->_site->license_id}.json", 'delete' );
21712
21713 $this->handle_license_deactivation_result( $license, $hmm_text, $show_notice );
21714 }
21715
21716 /**
21717 * @author Leo Fajardo (@leorw)
21718 * @since 2.2.1
21719 *
21720 * @param FS_Plugin_License $license
21721 * @param bool|string $hmm_text
21722 * @param bool $show_notice
21723 */
21724 private function handle_license_deactivation_result( $license, $hmm_text = false, $show_notice = true ) {
21725 if ( isset( $license->error ) ) {
21726 $this->_admin_notices->add(
21727 $this->get_text_inline( 'It looks like the license deactivation failed.', 'license-deactivation-failed-message' ) . '<br> ' .
21728 $this->get_text_inline( 'Error received from the server:', 'server-error-message' ) . ' ' . var_export( $license->error, true ),
21729 $hmm_text,
21730 'error'
21731 );
21732
21733 return;
21734 }
21735
21736 // Update license cache.
21737 if ( is_array( $this->_licenses ) ) {
21738 for ( $i = 0, $len = count( $this->_licenses ); $i < $len; $i ++ ) {
21739 if ( $license->id == $this->_licenses[ $i ]->id ) {
21740 $this->_licenses[ $i ] = new FS_Plugin_License( $license );
21741 }
21742 }
21743 }
21744
21745 // Update site plan to default.
21746 $this->_sync_plans();
21747 $this->_site->plan_id = $this->_plans[0]->id;
21748 // Unlink license from site.
21749 $this->_update_site_license( null );
21750
21751 $this->_store_account();
21752
21753 if ( $show_notice ) {
21754 $this->_admin_notices->add(
21755 sprintf( $this->is_only_premium() ?
21756 $this->get_text_inline( 'Your %s license was successfully deactivated.', 'license-deactivation-message_premium-only' ) :
21757 $this->get_text_inline( 'Your license was successfully deactivated, you are back to the %s plan.', 'license-deactivation-message' ),
21758 $this->get_plan_title()
21759 ),
21760 $this->get_text_inline( 'O.K', 'ok' )
21761 );
21762 }
21763
21764 $this->_admin_notices->remove_sticky( array(
21765 'plan_upgraded',
21766 'license_activated',
21767 ) );
21768 }
21769
21770 /**
21771 * Site plan downgrade.
21772 *
21773 * @author Vova Feldman (@svovaf)
21774 * @since 1.0.4
21775 *
21776 * @return object
21777 *
21778 * @uses FS_Api
21779 */
21780 private function _downgrade_site() {
21781 $this->_logger->entrance();
21782
21783 $deactivate_license = fs_request_get_bool( 'deactivate_license' );
21784
21785 $api = $this->get_api_site_scope();
21786 $site = $api->call( 'downgrade.json', 'put', array( 'deactivate_license' => $deactivate_license ) );
21787
21788 $plan_downgraded = false;
21789 $plan = false;
21790 if ( $this->is_api_result_entity( $site ) ) {
21791 $prev_plan_id = $this->_site->plan_id;
21792
21793 // Update new site plan id.
21794 $this->_site->plan_id = $site->plan_id;
21795
21796 $plan = $this->get_plan();
21797 $subscription = $this->_sync_site_subscription( $this->_license );
21798
21799 // Plan downgraded if plan was changed or subscription was cancelled.
21800 $plan_downgraded = ( $plan instanceof FS_Plugin_Plan && $prev_plan_id != $plan->id ) ||
21801 ( is_object( $subscription ) && ! isset( $subscription->error ) && ! $subscription->is_active() );
21802 } else {
21803 // handle different error cases.
21804 $this->handle_license_deactivation_result(
21805 $site,
21806 $this->get_text_x_inline( 'Hmm', 'something somebody says when they are thinking about what you have just said.', 'hmm' ) . '...'
21807 );
21808 }
21809
21810 if ( ! $plan_downgraded ) {
21811 return (object) array(
21812 'error' => (object) array(
21813 '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' )
21814 )
21815 );
21816 }
21817
21818 // Remove previous sticky message about upgrade (if exist).
21819 $this->_admin_notices->remove_sticky( 'plan_upgraded' );
21820
21821 $this->_admin_notices->add(
21822 sprintf( $this->get_text_inline( 'Your subscription was successfully cancelled. Your %s plan license will expire in %s.', 'plan-x-downgraded-message' ),
21823 $plan->title,
21824 human_time_diff( time(), strtotime( $this->_license->expiration ) )
21825 )
21826 );
21827
21828 // Store site updates.
21829 $this->_store_site();
21830
21831 if ( $deactivate_license &&
21832 ! FS_Plugin_License::is_valid_id( $site->license_id )
21833 ) {
21834 if ( $this->_site->is_localhost() ) {
21835 $this->_license->activated_local = max( 0, $this->_license->activated_local - 1 );
21836 } else {
21837 $this->_license->activated = max( 0, $this->_license->activated - 1 );
21838 }
21839
21840 // Handle successful license deactivation result.
21841 $this->handle_license_deactivation_result( $this->_license );
21842 }
21843
21844 return $site;
21845 }
21846
21847 /**
21848 * @author Vova Feldman (@svovaf)
21849 * @since 1.1.8.1
21850 *
21851 * @param bool|string $plan_name
21852 * @param bool $add_sticky_notice
21853 *
21854 * @return bool If trial was successfully started.
21855 */
21856 function start_trial( $plan_name = false, $add_sticky_notice = false ) {
21857 $this->_logger->entrance();
21858
21859 // Alias.
21860 $oops_text = $this->get_text_x_inline( 'Oops', 'exclamation', 'oops' ) . '...';
21861
21862 if ( $this->is_trial() ) {
21863 // Already in trial mode.
21864 $this->_admin_notices->add(
21865 sprintf( $this->get_text_inline( 'You are already running the %s in a trial mode.', 'in-trial-mode' ), $this->_module_type ),
21866 $oops_text,
21867 'error',
21868 $add_sticky_notice
21869 );
21870
21871 return false;
21872 }
21873
21874 if ( $this->_site->is_trial_utilized() && ! $this->is_payments_sandbox() ) {
21875 // Trial was already utilized.
21876 $this->_admin_notices->add(
21877 $this->get_text_inline( 'You already utilized a trial before.', 'trial-utilized' ),
21878 $oops_text,
21879 'error',
21880 $add_sticky_notice
21881 );
21882
21883 return false;
21884 }
21885
21886 if ( false !== $plan_name ) {
21887 $plan = $this->get_plan_by_name( $plan_name );
21888
21889 if ( false === $plan ) {
21890 // Plan doesn't exist.
21891 $this->_admin_notices->add(
21892 sprintf( $this->get_text_inline( 'Plan %s do not exist, therefore, can\'t start a trial.', 'trial-plan-x-not-exist' ), $plan_name ),
21893 $oops_text,
21894 'error',
21895 $add_sticky_notice
21896 );
21897
21898 return false;
21899 }
21900
21901 if ( ! $plan->has_trial() ) {
21902 // Plan doesn't exist.
21903 $this->_admin_notices->add(
21904 sprintf( $this->get_text_inline( 'Plan %s does not support a trial period.', 'plan-x-no-trial' ), $plan_name ),
21905 $oops_text,
21906 'error',
21907 $add_sticky_notice
21908 );
21909
21910 return false;
21911 }
21912 } else {
21913 if ( ! $this->has_trial_plan() ) {
21914 // None of the plans have a trial.
21915 $this->_admin_notices->add(
21916 sprintf( $this->get_text_inline( 'None of the %s\'s plans supports a trial period.', 'no-trials' ), $this->_module_type ),
21917 $oops_text,
21918 'error',
21919 $add_sticky_notice
21920 );
21921
21922 return false;
21923 }
21924
21925 $plans_with_trial = FS_Plan_Manager::instance()->get_trial_plans( $this->_plans );
21926
21927 $plan = $plans_with_trial[0];
21928 }
21929
21930 $trial_params = array();
21931
21932 if ( $this->is_payments_sandbox() ) {
21933 $trial_params['trial_timestamp'] = time();
21934 $trial_params['trial_token'] = FS_Security::instance()->get_trial_token(
21935 $this->get_plugin(),
21936 $plan,
21937 $trial_params['trial_timestamp']
21938 );
21939 }
21940
21941 $api = $this->get_api_site_scope();
21942 $trial = $api->call( "plans/{$plan->id}/trials.json", 'post', $trial_params );
21943
21944 if ( ! $this->is_api_result_entity( $trial ) ) {
21945 // Some API error while trying to start the trial.
21946 $this->_admin_notices->add(
21947 $this->get_api_error_message( $trial ),
21948 $oops_text,
21949 'error',
21950 $add_sticky_notice
21951 );
21952
21953 return false;
21954 }
21955
21956 // Sync license.
21957 $this->_sync_license();
21958
21959 return $this->is_trial();
21960 }
21961
21962 /**
21963 * Cancel site trial.
21964 *
21965 * @author Vova Feldman (@svovaf)
21966 * @since 1.0.9
21967 *
21968 * @return object
21969 *
21970 * @uses FS_Api
21971 */
21972 private function _cancel_trial() {
21973 $this->_logger->entrance();
21974
21975 if ( ! $this->is_trial() ) {
21976 return (object) array(
21977 'error' => (object) array(
21978 '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' )
21979 )
21980 );
21981 }
21982
21983 $trial_plan = $this->get_trial_plan();
21984
21985 $api = $this->get_api_site_scope();
21986 $site = $api->call( 'trials.json', 'delete' );
21987
21988 $trial_cancelled = false;
21989
21990 if ( $this->is_api_result_entity( $site ) ) {
21991 $prev_trial_ends = $this->_site->trial_ends;
21992
21993 if ( $this->is_paid_trial() ) {
21994 $this->_license->expiration = $site->trial_ends;
21995 $this->_license->is_cancelled = true;
21996 $this->_update_site_license( $this->_license );
21997 $this->_store_licenses();
21998
21999 // Clear subscription reference.
22000 $this->_sync_site_subscription( null );
22001 }
22002
22003 // Update site info.
22004 $this->_site = new FS_Site( $site );
22005
22006 $trial_cancelled = ( $prev_trial_ends != $site->trial_ends );
22007 } else {
22008 // @todo handle different error cases.
22009 }
22010
22011 if ( ! $trial_cancelled ) {
22012 return (object) array(
22013 'error' => (object) array(
22014 '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' )
22015 )
22016 );
22017 }
22018
22019 // Remove previous sticky messages about upgrade or trial (if exist).
22020 $this->_admin_notices->remove_sticky( array(
22021 'trial_started',
22022 'trial_promotion',
22023 'plan_upgraded',
22024 ) );
22025
22026 // Store site updates.
22027 $this->_store_site();
22028
22029 if ( ! $this->is_addon() ||
22030 ! $this->deactivate_premium_only_addon_without_license( true )
22031 ) {
22032 $this->_admin_notices->add(
22033 sprintf( $this->get_text_inline( 'Your %s free trial was successfully cancelled.', 'trial-cancel-message' ), $trial_plan->title )
22034 );
22035 }
22036
22037 return $site;
22038 }
22039
22040 /**
22041 * @author Vova Feldman (@svovaf)
22042 * @since 1.0.6
22043 *
22044 * @param bool|number $plugin_id
22045 *
22046 * @return bool
22047 */
22048 private function _is_addon_id( $plugin_id ) {
22049 return is_numeric( $plugin_id ) && ( $this->get_id() != $plugin_id );
22050 }
22051
22052 /**
22053 * Check if user eligible to download premium version updates.
22054 *
22055 * @author Vova Feldman (@svovaf)
22056 * @since 1.0.6
22057 *
22058 * @return bool
22059 */
22060 private function _can_download_premium() {
22061 return $this->has_any_active_valid_license() ||
22062 ( $this->is_trial() && ! $this->get_trial_plan()->is_free() );
22063 }
22064
22065 /**
22066 *
22067 * @author Vova Feldman (@svovaf)
22068 * @since 1.0.6
22069 *
22070 * @param bool|number $addon_id
22071 * @param string $type "json" or "zip"
22072 *
22073 * @return string
22074 */
22075 private function _get_latest_version_endpoint( $addon_id = false, $type = 'json' ) {
22076
22077 $is_addon = $this->_is_addon_id( $addon_id );
22078
22079 $is_premium = null;
22080 if ( ! $is_addon ) {
22081 $is_premium = ( $this->is_premium() || $this->_can_download_premium() );
22082 } else if ( $this->is_addon_activated( $addon_id ) ) {
22083 $fs_addon = self::get_instance_by_id( $addon_id );
22084 $is_premium = ( $fs_addon->is_premium() || $fs_addon->_can_download_premium() );
22085 }
22086
22087 // If add-on, then append add-on ID.
22088 $endpoint = ( $is_addon ? "/addons/$addon_id" : '' ) .
22089 '/updates/latest.' . $type;
22090
22091 // If add-on and not yet activated, try to fetch based on server licensing.
22092 if ( is_bool( $is_premium ) ) {
22093 $endpoint = add_query_arg( 'is_premium', json_encode( $is_premium ), $endpoint );
22094 }
22095
22096 if ( $this->has_secret_key() ) {
22097 $endpoint = add_query_arg( 'type', 'all', $endpoint );
22098 } else if ( is_object( $this->_site ) && $this->_site->is_beta() ) {
22099 $endpoint = add_query_arg( 'type', 'beta', $endpoint );
22100 }
22101
22102 return $endpoint;
22103 }
22104
22105 /**
22106 * @author Vova Feldman (@svovaf)
22107 * @since 1.0.4
22108 *
22109 * @param bool|number $addon_id
22110 * @param bool $flush Since 1.1.7.3
22111 * @param int $expiration Since 1.2.2.7
22112 * @param bool|string $newer_than Since 2.2.1
22113 * @param bool|string $fetch_readme Since 2.2.1
22114 *
22115 * @return object|false Plugin latest tag info.
22116 */
22117 function _fetch_latest_version(
22118 $addon_id = false,
22119 $flush = true,
22120 $expiration = WP_FS__TIME_24_HOURS_IN_SEC,
22121 $newer_than = false,
22122 $fetch_readme = true
22123 ) {
22124 $this->_logger->entrance();
22125
22126 if ( $this->is_unresolved_clone( true ) ) {
22127 return false;
22128 }
22129
22130 $switch_to_blog_id = null;
22131
22132 /**
22133 * @since 1.1.7.3 Check for plugin updates from Freemius only if opted-in.
22134 * @since 1.1.7.4 Also check updates for add-ons.
22135 */
22136 if (
22137 ( ! $this->is_registered() || ! FS_Permission_Manager::instance( $this )->is_essentials_tracking_allowed() ) &&
22138 ! $this->_is_addon_id( $addon_id )
22139 ) {
22140 if ( ! is_multisite() ) {
22141 return false;
22142 }
22143
22144 $installs_map = $this->get_blog_install_map();
22145
22146 foreach ( $installs_map as $blog_id => $install ) {
22147 if ( ! FS_Permission_Manager::instance( $this )->is_essentials_tracking_allowed( $blog_id ) ) {
22148 continue;
22149 }
22150
22151 /**
22152 * @var FS_Site $install
22153 */
22154 if ( $install->is_trial() ) {
22155 $switch_to_blog_id = $blog_id;
22156 break;
22157 }
22158
22159 if ( FS_Plugin_License::is_valid_id( $install->license_id ) ) {
22160 $license = $this->get_license_by_id( $install->license_id );
22161
22162 if ( is_object( $license ) && $license->is_features_enabled() ) {
22163 $switch_to_blog_id = $blog_id;
22164 break;
22165 }
22166 }
22167 }
22168
22169 if ( is_null( $switch_to_blog_id ) ) {
22170 return false;
22171 }
22172 }
22173
22174 $current_blog_id = is_numeric( $switch_to_blog_id ) ?
22175 get_current_blog_id() :
22176 0;
22177
22178 if ( is_numeric( $switch_to_blog_id ) ) {
22179 $this->switch_to_blog( $switch_to_blog_id );
22180 }
22181
22182 $latest_version_endpoint = $this->_get_latest_version_endpoint( $addon_id, 'json' );
22183
22184 if ( ! empty( $newer_than ) ) {
22185 $latest_version_endpoint = add_query_arg( 'newer_than', $newer_than, $latest_version_endpoint );
22186 }
22187
22188 if ( true === $fetch_readme ) {
22189 $latest_version_endpoint = add_query_arg( 'readme', 'true', $latest_version_endpoint );
22190
22191 // Don't cache the API response when fetching readme information.
22192 $expiration = null;
22193 }
22194
22195 $tag = $this->get_api_site_or_plugin_scope()->get(
22196 $latest_version_endpoint,
22197 $flush,
22198 $expiration
22199 );
22200
22201 if ( is_numeric( $switch_to_blog_id ) ) {
22202 $this->switch_to_blog( $current_blog_id );
22203 }
22204
22205 $latest_version = ( is_object( $tag ) && isset( $tag->version ) ) ? $tag->version : 'couldn\'t get';
22206
22207 $this->_logger->departure( 'Latest version ' . $latest_version );
22208
22209 return ( is_object( $tag ) && isset( $tag->version ) ) ? $tag : false;
22210 }
22211
22212 #----------------------------------------------------------------------------------
22213 #region Download Plugin
22214 #----------------------------------------------------------------------------------
22215
22216 /**
22217 * Download latest plugin version, based on plan.
22218 *
22219 * Not like _download_latest(), this will redirect the page
22220 * to secure download url to prevent dual download (from FS to WP server,
22221 * and then from WP server to the client / browser).
22222 *
22223 * @author Vova Feldman (@svovaf)
22224 * @since 1.0.9
22225 *
22226 * @param bool|number $plugin_id
22227 *
22228 * @uses FS_Api
22229 * @uses wp_redirect()
22230 */
22231 private function download_latest_directly( $plugin_id = false ) {
22232 $this->_logger->entrance();
22233
22234 wp_redirect( $this->get_latest_download_api_url( $plugin_id ) );
22235 }
22236
22237 /**
22238 * Get latest plugin FS API download URL.
22239 *
22240 * @author Vova Feldman (@svovaf)
22241 * @since 1.0.9
22242 *
22243 * @param bool|number $plugin_id
22244 *
22245 * @return string
22246 */
22247 private function get_latest_download_api_url( $plugin_id = false ) {
22248 $this->_logger->entrance();
22249
22250 $download_api_url = $this->get_api_site_scope()->get_signed_url(
22251 $this->_get_latest_version_endpoint( $plugin_id, 'zip' )
22252 );
22253
22254 return str_replace( 'http:', 'https:', $download_api_url );
22255 }
22256
22257 /**
22258 * Get payment invoice URL.
22259 *
22260 * @author Vova Feldman (@svovaf)
22261 * @since 1.2.0
22262 *
22263 * @param bool|number $payment_id
22264 *
22265 * @return string
22266 */
22267 function _get_invoice_api_url( $payment_id = false ) {
22268 $this->_logger->entrance();
22269
22270 $url = $this->get_api_user_scope()->get_signed_url(
22271 "/payments/{$payment_id}/invoice.pdf"
22272 );
22273
22274 if ( ! fs_starts_with( $url, 'https://' ) ) {
22275 // Always use HTTPS for invoices.
22276 $url = 'https' . substr( $url, 4 );
22277 }
22278
22279 return $url;
22280 }
22281
22282 /**
22283 * Get latest plugin download link.
22284 *
22285 * @author Vova Feldman (@svovaf)
22286 * @since 1.0.9
22287 *
22288 * @param string $label
22289 * @param bool|number $plugin_id
22290 *
22291 * @return string
22292 */
22293 private function get_latest_download_link( $label, $plugin_id = false ) {
22294 return sprintf(
22295 '<a target="_blank" rel="noopener" href="%s">%s</a>',
22296 $this->_get_latest_download_local_url( $plugin_id ),
22297 $label
22298 );
22299 }
22300
22301 /**
22302 * Get latest plugin download local URL.
22303 *
22304 * @author Vova Feldman (@svovaf)
22305 * @since 1.0.9
22306 *
22307 * @param bool|number $plugin_id
22308 *
22309 * @return string
22310 */
22311 function _get_latest_download_local_url( $plugin_id = false ) {
22312 // Add timestamp to protect from caching.
22313 $params = array( 'ts' => WP_FS__SCRIPT_START_TIME );
22314
22315 if ( ! empty( $plugin_id ) ) {
22316 $params['plugin_id'] = $plugin_id;
22317 } else if ( $this->is_addon() ) {
22318 $params['plugin_id'] = $this->get_id();
22319 }
22320
22321 $fs = $this->is_addon() ?
22322 $this->get_parent_instance() :
22323 $this;
22324
22325 return $this->apply_filters( 'download_latest_url', $fs->get_account_url( 'download_latest', $params ) );
22326 }
22327
22328 #endregion Download Plugin ------------------------------------------------------------------
22329
22330 /**
22331 * @author Vova Feldman (@svovaf)
22332 * @since 1.0.4
22333 *
22334 * @uses FS_Api
22335 *
22336 * @param bool $background Hints the method if it's a background updates check. If false, it means that
22337 * was initiated by the admin.
22338 * @param bool|number $plugin_id
22339 * @param bool $flush Since 1.1.7.3
22340 * @param int $expiration Since 1.2.2.7
22341 * @param bool|string $newer_than Since 2.2.1
22342 */
22343 private function check_updates(
22344 $background = false,
22345 $plugin_id = false,
22346 $flush = true,
22347 $expiration = FS_Plugin_Updater::UPDATES_CHECK_CACHE_EXPIRATION,
22348 $newer_than = false
22349 ) {
22350 $this->_logger->entrance();
22351
22352 // Check if there's a newer version for download.
22353 $new_version = $this->_fetch_newer_version( $plugin_id, $flush, $expiration, $newer_than );
22354
22355 $update = null;
22356 if ( is_object( $new_version ) ) {
22357 $update = new FS_Plugin_Tag( $new_version );
22358
22359 if ( ! $background ) {
22360 $this->_admin_notices->add(
22361 sprintf(
22362 /* translators: %s: Numeric version number (e.g. '2.1.9' */
22363 $this->get_text_inline( 'Version %s was released.', 'version-x-released' ) . ' ' . $this->get_text_inline( 'Please download %s.', 'please-download-x' ),
22364 $update->version,
22365 sprintf(
22366 '<a href="%s" target="_blank" rel="noopener">%s</a>',
22367 $this->get_account_url( 'download_latest' ),
22368 sprintf(
22369 /* translators: %s: plan name (e.g. latest "Professional" version) */
22370 $this->get_text_inline( 'the latest %s version here', 'latest-x-version' ),
22371 $this->get_plan_title()
22372 )
22373 )
22374 ),
22375 $this->get_text_inline( 'New', 'new' ) . '!'
22376 );
22377 }
22378 } else if ( false === $new_version && ! $background ) {
22379 $this->_admin_notices->add(
22380 $this->get_text_inline( 'Seems like you got the latest release.', 'you-have-latest' ),
22381 $this->get_text_inline( 'You are all good!', 'you-are-good' )
22382 );
22383 }
22384
22385 $this->_store_update( $update, true, $plugin_id );
22386 }
22387
22388 /**
22389 * @author Vova Feldman (@svovaf)
22390 * @since 1.0.4
22391 *
22392 * @param bool $flush Since 1.1.7.3 add 24 hour cache by default.
22393 *
22394 * @return FS_Plugin[]
22395 *
22396 * @uses FS_Api
22397 */
22398 private function sync_addons( $flush = false ) {
22399 $this->_logger->entrance();
22400
22401 $api = $this->get_api_site_or_plugin_scope();
22402
22403 $path = $this->add_show_pending( '/addons.json?enriched=true&count=50' );
22404
22405 /**
22406 * @since 1.2.1
22407 *
22408 * If there's a cached version of the add-ons and not asking
22409 * for a flush, just use the currently stored add-ons.
22410 */
22411 if ( ! $flush && $api->is_cached( $path ) ) {
22412 $addons = self::get_all_addons();
22413
22414 return isset( $addons[ $this->_plugin->id ] ) ?
22415 $addons[ $this->_plugin->id ] :
22416 array();
22417 }
22418
22419 $result = $api->get( $path, $flush );
22420
22421 $addons = array();
22422 if ( $this->is_api_result_object( $result, 'plugins' ) &&
22423 is_array( $result->plugins )
22424 ) {
22425 for ( $i = 0, $len = count( $result->plugins ); $i < $len; $i ++ ) {
22426 $addons[ $i ] = new FS_Plugin( $result->plugins[ $i ] );
22427 }
22428
22429 $this->_store_addons( $addons, true );
22430 }
22431
22432 return $addons;
22433 }
22434
22435 /**
22436 * Handle user email update.
22437 *
22438 * @author Vova Feldman (@svovaf)
22439 * @since 1.0.3
22440 * @uses FS_Api
22441 *
22442 * @param string $new_email
22443 *
22444 * @return object
22445 */
22446 private function update_email( $new_email ) {
22447 $this->_logger->entrance();
22448
22449 $api = $this->get_api_user_scope();
22450 $user = $api->call( "?plugin_id={$this->_plugin->id}&fields=id,email,is_verified", 'put', array(
22451 'email' => $new_email,
22452 'after_email_confirm_url' => $this->_get_admin_page_url(
22453 'account',
22454 array( 'fs_action' => 'sync_user' )
22455 ),
22456 ) );
22457
22458 if ( ! isset( $user->error ) ) {
22459 $this->_user->email = $user->email;
22460 $this->_user->is_verified = $user->is_verified;
22461 $this->_store_user();
22462 } else {
22463 // handle different error cases.
22464 }
22465
22466 return $user;
22467 }
22468
22469 #----------------------------------------------------------------------------------
22470 #region API Error Handling
22471 #----------------------------------------------------------------------------------
22472
22473 /**
22474 * @author Vova Feldman (@svovaf)
22475 * @since 1.1.1
22476 *
22477 * @param mixed $result
22478 *
22479 * @return bool Is API result contains an error.
22480 */
22481 private function is_api_error( $result ) {
22482 return FS_Api::is_api_error( $result );
22483 }
22484
22485 /**
22486 * Checks if given API result is a non-empty and not an error object.
22487 *
22488 * @author Vova Feldman (@svovaf)
22489 * @since 1.2.1.5
22490 *
22491 * @param mixed $result
22492 * @param string|null $required_property Optional property we want to verify that is set.
22493 *
22494 * @return bool
22495 */
22496 function is_api_result_object( $result, $required_property = null ) {
22497 return FS_Api::is_api_result_object( $result, $required_property );
22498 }
22499
22500 /**
22501 * Checks if given API result is a non-empty entity object with non-empty ID.
22502 *
22503 * @author Vova Feldman (@svovaf)
22504 * @since 1.2.1.5
22505 *
22506 * @param mixed $result
22507 *
22508 * @return bool
22509 */
22510 private function is_api_result_entity( $result ) {
22511 return FS_Api::is_api_result_entity( $result );
22512 }
22513
22514 #endregion
22515
22516 /**
22517 * Make sure a given argument is an array of a specific type.
22518 *
22519 * @author Vova Feldman (@svovaf)
22520 * @since 1.2.1.5
22521 *
22522 * @param mixed $array
22523 * @param string $class
22524 *
22525 * @return bool
22526 */
22527 private function is_array_instanceof( $array, $class ) {
22528 return ( is_array( $array ) && ( empty( $array ) || $array[0] instanceof $class ) );
22529 }
22530
22531 /**
22532 * Start install ownership change.
22533 *
22534 * @author Vova Feldman (@svovaf)
22535 * @since 1.1.1
22536 * @uses FS_Api
22537 *
22538 * @param string $candidate_email
22539 * @param string $transfer_type
22540 *
22541 * @return bool Is ownership change successfully initiated.
22542 */
22543 private function init_change_owner( $candidate_email, $transfer_type ) {
22544 $this->_logger->entrance();
22545
22546 $installs_info_by_slug_map = $this->get_parent_and_addons_installs_info();
22547 $install_ids = array();
22548
22549 foreach ( $installs_info_by_slug_map as $slug => $install_info ) {
22550 $install = $install_info['install'];
22551
22552 if ( $this->_user->id != $install->user_id ) {
22553 // Skip add-on installs that are not owned by the parent product's install's owner.
22554 continue;
22555 }
22556
22557 $install_ids[ $slug ] = $install->id;
22558 }
22559
22560 $api = $this->get_api_site_scope();
22561 $result = $api->call( "/users/{$this->_user->id}.json", 'put', array(
22562 'email' => $candidate_email,
22563 'transfer_type' => $transfer_type,
22564 'install_ids' => implode( ',', array_values( $install_ids ) ),
22565 'after_confirm_url' => $this->_get_admin_page_url(
22566 'account',
22567 array( 'fs_action' => 'change_owner' )
22568 ),
22569 ) );
22570
22571 return ! $this->is_api_error( $result );
22572 }
22573
22574 /**
22575 * Handle install ownership change.
22576 *
22577 * @author Vova Feldman (@svovaf)
22578 * @since 1.1.1
22579 * @uses FS_Api
22580 *
22581 * @return bool Was ownership change successfully complete.
22582 */
22583 private function complete_change_owner() {
22584 $this->_logger->entrance();
22585
22586 $install_ids = fs_request_get( 'install_ids' );
22587
22588 if ( ! empty( $install_ids ) ) {
22589 $install_ids = explode( ',', $install_ids );
22590
22591 foreach ( $install_ids as $key => $install_id ) {
22592 if ( ! FS_Site::is_valid_id( $install_id ) ) {
22593 unset( $install_ids[ $key ] );
22594 }
22595 }
22596 }
22597
22598 if ( ! is_array( $install_ids ) ) {
22599 $install_ids = array();
22600 }
22601
22602 $user = new FS_User();
22603 $user->id = fs_request_get( 'user_id' );
22604 $user->public_key = fs_request_get_raw( 'user_public_key' );
22605 $user->secret_key = fs_request_get_raw( 'user_secret_key' );
22606
22607 $prev_user = $this->_user;
22608 $this->_user = $user;
22609
22610 $result = $this->get_api_user_scope( true )->get(
22611 "/installs.json?install_ids=" . implode( ',', $install_ids )
22612 );
22613
22614 $current_blog_sites = self::get_all_sites( $this->get_module_type() );
22615
22616 if ( $this->is_api_result_object( $result, 'installs' ) ) {
22617 $site_id_slug_map = array();
22618
22619 foreach ( $current_blog_sites as $slug => $site ) {
22620 $site_id_slug_map[ $site->id ] = $slug;
22621 }
22622
22623 foreach ( $result->installs as $install ) {
22624 $site = new FS_Site( $install );
22625
22626 if ( ! isset( $site_id_slug_map[ $install->id ] ) ) {
22627 continue;
22628 }
22629
22630 $current_blog_sites[ $site_id_slug_map[ $install->id ] ] = clone $site;
22631
22632 if ( $this->_site->id == $site->id ) {
22633 $this->_site = $site;
22634 }
22635 }
22636 }
22637
22638 // Validate install's user and given user.
22639 if ( $user->id != $this->_site->user_id ) {
22640 $this->_user = $prev_user;
22641
22642 return false;
22643 }
22644
22645 $this->set_account_option( 'sites', $current_blog_sites, true );
22646
22647 // Fetch new user information.
22648 $user_result = $this->get_api_user_scope( true )->get();
22649 $user = new FS_User( $user_result );
22650 $this->_user = $user;
22651
22652 $this->_set_account( $user, $this->_site );
22653
22654 $remove_user = true;
22655 $all_modules_sites = FS_DebugManager::get_all_modules_sites();
22656
22657 foreach ( $all_modules_sites as $sites_by_module_type ) {
22658 foreach ( $sites_by_module_type as $sites_by_slug ) {
22659 foreach ( $sites_by_slug as $site ) {
22660 if ( $prev_user->id == $site->user_id ) {
22661 $remove_user = false;
22662 break;
22663 }
22664 }
22665
22666 if ( ! $remove_user ) {
22667 break;
22668 }
22669 }
22670
22671 if ( ! $remove_user ) {
22672 break;
22673 }
22674 }
22675
22676 if ( $remove_user ) {
22677 $users = self::get_all_users();
22678
22679 if ( isset( $users[ $prev_user->id ] ) ) {
22680 unset( $users[ $prev_user->id ] );
22681 } else {
22682 // If the prev user wasn't found by the key, iterate over the users collection.
22683 foreach ( $users as $key => $user ) {
22684 if ( $user->id == $prev_user->id ) {
22685 unset( $users[ $key ] );
22686 break;
22687 }
22688 }
22689 }
22690
22691 $this->set_account_option( 'users', $users, true );
22692 }
22693
22694 return true;
22695 }
22696
22697 /**
22698 * Completes ownership change by license.
22699 *
22700 * @author Leo Fajardo (@leorw)
22701 * @since 2.3.2
22702 *
22703 * @param number $user_id
22704 * @param array[string]number $install_ids_by_slug_map
22705 *
22706 */
22707 private function complete_ownership_change_by_license( $user_id, $install_ids_by_slug_map ) {
22708 $this->_logger->entrance();
22709
22710 $this->sync_user_by_current_install( $user_id );
22711
22712 $result = $this->get_api_user_scope( true )->get(
22713 "/installs.json?install_ids=" . implode( ',', $install_ids_by_slug_map )
22714 );
22715
22716 if ( $this->is_api_result_object( $result, 'installs' ) ) {
22717 $sites = self::get_all_sites( $this->get_module_type() );
22718 $install_ids_by_slug_map = array_flip( $install_ids_by_slug_map );
22719
22720 foreach ( $result->installs as $install ) {
22721 $site = new FS_Site( $install );
22722
22723 $sites[ $install_ids_by_slug_map[ $site->id ] ] = clone $site;
22724 }
22725
22726 $this->set_account_option( 'sites', $sites, true );
22727 }
22728 }
22729
22730 /**
22731 * Handle user name update.
22732 *
22733 * @author Vova Feldman (@svovaf)
22734 * @since 1.0.9
22735 * @uses FS_Api
22736 *
22737 * @return object
22738 */
22739 private function update_user_name() {
22740 $this->_logger->entrance();
22741 $name = fs_request_get( 'fs_user_name_' . $this->get_unique_affix(), '' );
22742
22743 $api = $this->get_api_user_scope();
22744 $user = $api->call( "?plugin_id={$this->_plugin->id}&fields=id,first,last", 'put', array(
22745 'name' => $name,
22746 ) );
22747
22748 if ( ! isset( $user->error ) ) {
22749 $this->_user->first = $user->first;
22750 $this->_user->last = $user->last;
22751 $this->_store_user();
22752 } else {
22753 // handle different error cases.
22754
22755 }
22756
22757 return $user;
22758 }
22759
22760 /**
22761 * Verify user email.
22762 *
22763 * @author Vova Feldman (@svovaf)
22764 * @since 1.0.3
22765 * @uses FS_Api
22766 */
22767 private function verify_email() {
22768 $this->_handle_account_user_sync();
22769
22770 if ( $this->_user->is_verified() ) {
22771 return;
22772 }
22773
22774 $api = $this->get_api_site_scope();
22775 $result = $api->call( "/users/{$this->_user->id}/verify.json", 'put', array(
22776 'after_email_confirm_url' => $this->_get_admin_page_url(
22777 'account',
22778 array( 'fs_action' => 'sync_user' )
22779 )
22780 ) );
22781
22782 if ( ! isset( $result->error ) ) {
22783 $this->_admin_notices->add( sprintf(
22784 $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' ),
22785 sprintf( '<a href="mailto:%1$s">%2$s</a>', esc_url( $this->_user->email ), $this->_user->email )
22786 ) );
22787 } else {
22788 // handle different error cases.
22789
22790 }
22791 }
22792
22793 /**
22794 * @author Vova Feldman (@svovaf)
22795 * @since 1.1.2
22796 *
22797 * @param array $params
22798 * @param bool|null $network
22799 *
22800 * @return string
22801 */
22802 function get_activation_url( $params = array(), $network = null ) {
22803 if ( $this->is_addon() && $this->has_free_plan() ) {
22804 /**
22805 * @author Vova Feldman (@svovaf)
22806 * @since 1.2.1.7 Add-on's activation is the parent's module activation.
22807 */
22808 return $this->get_parent_instance()->get_activation_url( $params );
22809 }
22810
22811 return $this->apply_filters( 'connect_url', $this->_get_admin_page_url( '', $params, $network ) );
22812 }
22813
22814 /**
22815 * @author Vova Feldman (@svovaf)
22816 * @since 1.2.1.5
22817 *
22818 * @param array $params
22819 *
22820 * @return string
22821 */
22822 function get_reconnect_url( $params = array() ) {
22823 $params['fs_action'] = 'reset_anonymous_mode';
22824 $params['fs_unique_affix'] = $this->get_unique_affix();
22825
22826 return $this->get_activation_url( $params );
22827 }
22828
22829 /**
22830 * Get the URL of the page that should be loaded after the user connect
22831 * or skip in the opt-in screen.
22832 *
22833 * @author Vova Feldman (@svovaf)
22834 * @since 1.1.3
22835 *
22836 * @param string $filter Filter name.
22837 * @param array $params Since 1.2.2.7
22838 * @param bool|null $network
22839 *
22840 * @return string
22841 */
22842 function get_after_activation_url( $filter, $params = array(), $network = null ) {
22843 if ( $this->show_opt_in_on_themes_page() &&
22844 ( fs_request_has( 'pending_activation' ) ||
22845 // For cases when the first time path is set, even though it's a WP.org theme.
22846 fs_request_get_bool( $this->get_unique_affix() . '_show_optin' ) )
22847 ) {
22848 $first_time_path = '';
22849 } else {
22850 $first_time_path = $this->_menu->get_first_time_path(
22851 fs_is_network_admin() && $this->_is_network_active
22852 );
22853 }
22854
22855 if ( $this->_is_network_active &&
22856 fs_is_network_admin() &&
22857 ! $this->_menu->has_network_menu() &&
22858 $this->is_network_registered()
22859 ) {
22860 $target_url = $this->get_account_url();
22861 } else {
22862 // Default plugin's page.
22863 $target_url = $this->_get_admin_page_url( '', array(), $network );
22864 }
22865
22866 return add_query_arg( $params, $this->apply_filters(
22867 $filter,
22868 empty( $first_time_path ) ?
22869 $target_url :
22870 $first_time_path
22871 ) );
22872 }
22873
22874 /**
22875 * Handle account page updates / edits / actions.
22876 *
22877 * @author Vova Feldman (@svovaf)
22878 * @since 1.0.2
22879 *
22880 */
22881 private function _handle_account_edits() {
22882 if ( ! $this->is_user_admin() ) {
22883 return;
22884 }
22885
22886 $action = fs_get_action();
22887
22888 if ( empty( $action ) ) {
22889 return;
22890 }
22891
22892 $plugin_id = fs_request_get( 'plugin_id', $this->get_id() );
22893 $install_id = fs_request_get( 'install_id', '' );
22894
22895 // Alias.
22896 $oops_text = $this->get_text_x_inline( 'Oops', 'exclamation', 'oops' ) . '...';
22897
22898 $is_network_action = $this->is_network_level_action();
22899 $blog_id = $this->is_network_level_site_specific_action();
22900 $is_parent_plugin_action = ( $plugin_id == $this->get_id() );
22901
22902 if ( is_numeric( $blog_id ) ) {
22903 $this->switch_to_blog( $blog_id );
22904 } else {
22905 $blog_id = '';
22906 }
22907
22908 switch ( $action ) {
22909 case 'opt_in':
22910 check_admin_referer( trim( "{$action}:{$blog_id}:{$install_id}", ':' ) );
22911
22912 if ( $is_parent_plugin_action ) {
22913 if ( $is_network_action && ! empty( $blog_id ) ) {
22914 if ( ! $this->is_registered() ) {
22915 $this->install_with_user(
22916 $this->get_network_user(),
22917 false,
22918 false,
22919 false,
22920 false
22921 );
22922
22923 $this->_admin_notices->add(
22924 $this->get_text_inline( 'Site successfully opted in.', 'successful-opt-in' ),
22925 $this->get_text_inline( 'Awesome', 'awesome' )
22926 );
22927 }
22928 }
22929 }
22930 break;
22931
22932 case 'toggle_tracking':
22933 check_admin_referer( trim( "{$action}:{$blog_id}:{$install_id}", ':' ) );
22934
22935 if ( $is_parent_plugin_action ) {
22936 if ( $is_network_action && ! empty( $blog_id ) ) {
22937 if ( $this->is_registered( true ) ) {
22938 if ( $this->is_tracking_prohibited( $blog_id ) ) {
22939 if ( $this->toggle_site_tracking( true, $blog_id ) ) {
22940 $this->_admin_notices->add(
22941 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>" ),
22942 $this->get_text_inline( 'Thank you!', 'thank-you' )
22943 );
22944 }
22945 } else {
22946 if ( $this->toggle_site_tracking( false, $blog_id ) ) {
22947 $install = $this->get_install_by_blog_id( $blog_id );
22948
22949 $this->_admin_notices->add(
22950 sprintf(
22951 $this->get_text_inline( 'Diagnostic data will no longer be sent from %s to %s.', 'opted-out-successfully' ),
22952 self::get_unfiltered_site_url( $blog_id, true ),
22953 "<b>{$this->get_plugin_title()}</b>"
22954 )
22955 );
22956 }
22957 }
22958 }
22959 }
22960 }
22961
22962 break;
22963
22964 case 'delete_account':
22965 check_admin_referer( trim( "{$action}:{$blog_id}:{$install_id}", ':' ) );
22966
22967 $is_network_deletion = $is_network_action && empty( $blog_id );
22968
22969 if ( $is_parent_plugin_action ) {
22970 // Delete add-on installs if have any.
22971 $installed_addons = $this->get_installed_addons();
22972 foreach ( $installed_addons as $fs_addon ) {
22973 if ( $is_network_deletion ) {
22974 $fs_addon->delete_network_account_event();
22975 } else {
22976 $fs_addon->delete_account_event();
22977 }
22978 }
22979
22980 if ( $is_network_deletion ) {
22981 $this->delete_network_account_event();
22982 } else {
22983 $this->delete_account_event();
22984 }
22985
22986 // Clear user and site.
22987 $this->_site = null;
22988 $this->_user = null;
22989
22990 $this->maybe_set_slug_and_network_menu_exists_flag();
22991
22992 fs_redirect( $this->get_activation_url() );
22993 } else {
22994 if ( $this->is_addon_activated( $plugin_id ) ) {
22995 $fs_addon = self::get_instance_by_id( $plugin_id );
22996
22997 if ( $is_network_deletion ) {
22998 $fs_addon->delete_network_account_event();
22999 } else {
23000 $fs_addon->delete_account_event();
23001 }
23002
23003 fs_redirect( $this->_get_admin_page_url( 'account' ) );
23004 }
23005 }
23006
23007 return;
23008
23009 case 'downgrade_account':
23010 if ( is_numeric( $blog_id ) ) {
23011 check_admin_referer( trim( "{$action}:{$blog_id}:{$install_id}", ':' ) );
23012 } else {
23013 check_admin_referer( $action );
23014 }
23015
23016 $switch_to_network_install_blog_after_cancellation = (
23017 is_numeric( $blog_id ) &&
23018 $plugin_id == $this->get_id() &&
23019 ! $this->is_trial()
23020 );
23021
23022 $result = $this->cancel_subscription_or_trial( $plugin_id );
23023 if ( $this->is_api_error( $result ) ) {
23024 $this->_admin_notices->add(
23025 $result->error->message,
23026 $this->get_text_x_inline( 'Oops', 'exclamation', 'oops' ) . '...',
23027 'error'
23028 );
23029 }
23030
23031 if ( $switch_to_network_install_blog_after_cancellation ) {
23032 $this->switch_to_blog( $this->_storage->network_install_blog_id );
23033 }
23034
23035 return;
23036
23037 case 'activate_license':
23038 check_admin_referer( trim( "{$action}:{$blog_id}:{$install_id}", ':' ) );
23039
23040 $fs = $this;
23041 if ( $plugin_id != $this->get_id() ) {
23042 $fs = $this->is_addon_activated( $plugin_id ) ?
23043 self::get_instance_by_id( $plugin_id ) :
23044 null;
23045 }
23046
23047 if ( is_object( $fs ) ) {
23048 $fs->_activate_license();
23049
23050 /**
23051 * Remove the product ID from `$_REQUEST` so that the syncing of the license for the other products will work properly.
23052 *
23053 * @author Leo Fajardo (@leorw)
23054 * @since 2.4.0
23055 */
23056 unset( $_REQUEST['plugin_id'] );
23057
23058 if ( $this->is_bundle_license_auto_activation_enabled() ) {
23059 $fs->maybe_activate_bundle_license( null, array(), is_numeric( $blog_id ) ? $blog_id : 0 );
23060 }
23061 }
23062
23063 return;
23064
23065 case 'deactivate_license':
23066 check_admin_referer( trim( "{$action}:{$blog_id}:{$install_id}", ':' ) );
23067
23068 if ( $plugin_id == $this->get_id() ) {
23069 $this->_deactivate_license();
23070
23071 if ( $this->is_only_premium() ) {
23072 // Clear user and site.
23073 $this->_site = null;
23074 $this->_user = null;
23075
23076 if ( ! $is_network_action ) {
23077 fs_redirect( $this->get_activation_url() );
23078 } else if ( is_numeric( $blog_id ) ) {
23079 $this->switch_to_blog( $this->_storage->network_install_blog_id );
23080 }
23081 }
23082 } else {
23083 if ( $this->is_addon_activated( $plugin_id ) ) {
23084 $fs_addon = self::get_instance_by_id( $plugin_id );
23085 $fs_addon->_deactivate_license();
23086 }
23087 }
23088
23089 return;
23090
23091 case 'check_updates':
23092 check_admin_referer( $action );
23093 $this->check_updates();
23094
23095 return;
23096
23097 case 'change_owner':
23098 $state = fs_request_get( 'state', 'init' );
23099 switch ( $state ) {
23100 case 'init':
23101 // The nonce is injected by the error handler in `_email_address_update_ajax_handler` function.
23102 check_admin_referer( 'change_owner' );
23103
23104 $candidate_email = fs_request_get( 'candidate_email' );
23105 $transfer_type = fs_request_get( 'transfer_type' );
23106
23107 if ( $this->init_change_owner( $candidate_email, $transfer_type ) ) {
23108 if ( 'transfer' === $transfer_type ) {
23109 $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>' ) );
23110 } else {
23111 $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>' ) );
23112 }
23113 }
23114 break;
23115 case 'owner_confirmed':
23116 // We cannot (or need not to) check the nonce and referer here, because the link comes from the email sent by our API.
23117 $candidate_email = fs_request_get( 'candidate_email', '' );
23118
23119 if ( ! is_email($candidate_email ) ) {
23120 return;
23121 }
23122
23123 $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>' ) );
23124 break;
23125 case 'candidate_confirmed':
23126 // We do not need to validate the authenticity of this request here, because the `complete_change_owner` does that for us through API calls.
23127 if ( $this->complete_change_owner() ) {
23128 $this->_admin_notices->add_sticky(
23129 sprintf( $this->get_text_inline( '%s is the new owner of the account.', 'change-owner-request_candidate-confirmed' ), '<b>' . $this->_user->email . '</b>' ),
23130 'ownership_changed',
23131 $this->get_text_x_inline( 'Congrats', 'as congratulations', 'congrats' ) . '!'
23132 );
23133 } else {
23134 // @todo Handle failed ownership change message.
23135 }
23136 break;
23137 }
23138
23139 return;
23140
23141 case 'update_user_name':
23142 check_admin_referer( 'update_user_name' );
23143
23144 $result = $this->update_user_name();
23145
23146 if ( isset( $result->error ) ) {
23147 $this->_admin_notices->add(
23148 $this->get_text_inline( 'Please provide your full name.', 'name-update-failed-message' ),
23149 $oops_text,
23150 'error'
23151 );
23152 } else {
23153 $this->_admin_notices->add( $this->get_text_inline( 'Your name was successfully updated.', 'name-updated-message' ) );
23154 }
23155
23156 return;
23157
23158 #region Actions that might be called from external links (e.g. email)
23159
23160 /**
23161 * !!IMPORTANT!!: We cannot check for a valid nonce in this region, because the links could be coming from emails.
23162 */
23163
23164 case 'cancel_trial':
23165 $result = $this->cancel_subscription_or_trial( $plugin_id );
23166 if ( $this->is_api_error( $result ) ) {
23167 $this->_admin_notices->add(
23168 $result->error->message,
23169 $this->get_text_x_inline( 'Oops', 'exclamation', 'oops' ) . '...',
23170 'error'
23171 );
23172 }
23173
23174 return;
23175
23176 case 'verify_email':
23177 $this->verify_email();
23178
23179 return;
23180
23181 case 'sync_user':
23182 $this->_handle_account_user_sync();
23183
23184 return;
23185
23186 case $this->get_unique_affix() . '_sync_license':
23187 $this->_sync_license();
23188
23189 return;
23190
23191 case 'download_latest':
23192 $this->download_latest_directly( $plugin_id );
23193
23194 return;
23195
23196 #endregion
23197 }
23198
23199 if ( WP_FS__IS_POST_REQUEST ) {
23200 $properties = array( 'site_secret_key', 'site_id', 'site_public_key' );
23201 foreach ( $properties as $p ) {
23202 if ( 'update_' . $p === $action ) {
23203 check_admin_referer( $action );
23204
23205 $this->_logger->log( $action );
23206
23207 $site_property = substr( $p, strlen( 'site_' ) );
23208 $site_property_value = fs_request_get( 'fs_' . $p . '_' . $this->get_unique_affix(), '' );
23209 $this->get_site()->{$site_property} = $site_property_value;
23210
23211 // Store account after modification.
23212 $this->_store_site();
23213
23214 $this->do_action( 'account_property_edit', 'site', $site_property, $site_property_value );
23215
23216 $this->_admin_notices->add( sprintf(
23217 /* translators: %s: User's account property (e.g. email address, name) */
23218 $this->get_text_inline( 'You have successfully updated your %s.', 'x-updated' ),
23219 '<b>' . str_replace( '_', ' ', $p ) . '</b>'
23220 ) );
23221
23222 return;
23223 }
23224 }
23225 }
23226 }
23227
23228 /**
23229 * Adds CSS classes for the body tag in the admin.
23230 *
23231 * @param string $classes Space-separated string of class names.
23232 *
23233 * @return string $classes FS Admin body tag class names.
23234 */
23235 public function fs_addons_body_class( $classes ) {
23236 $classes .= ' plugins-php';
23237 return $classes;
23238 }
23239
23240 /**
23241 * Account page resources load.
23242 *
23243 * @author Vova Feldman (@svovaf)
23244 * @since 1.0.6
23245 */
23246 function _account_page_load() {
23247 $this->_logger->entrance();
23248
23249 $this->_logger->info( var_export( $_REQUEST, true ) );
23250
23251 fs_enqueue_local_style( 'fs_account', '/admin/account.css' );
23252
23253 if ( $this->has_addons() ) {
23254 wp_enqueue_script( 'plugin-install' );
23255 add_thickbox();
23256 add_filter( 'admin_body_class', array( $this, 'fs_addons_body_class' ) );
23257 }
23258
23259 if ( $this->has_paid_plan() &&
23260 ! $this->has_any_license() &&
23261 ! $this->is_sync_executed() &&
23262 $this->is_tracking_allowed()
23263 ) {
23264 /**
23265 * If no licenses found and no sync job was executed during the last 24 hours,
23266 * just execute the sync job right away (blocking execution).
23267 *
23268 * @since 1.1.7.3
23269 */
23270 $this->run_manual_sync();
23271 }
23272
23273 $this->_handle_account_edits();
23274
23275 if (
23276 is_object( $this->_license ) &&
23277 $this->_license->user_id == $this->_user->id &&
23278 ! $this->is_whitelabeled( true )
23279 ) {
23280 $this->_admin_notices->add(
23281 sprintf(
23282 $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' ),
23283 sprintf(
23284 '<a href="#" class="fs-toggle-whitelabel-mode">%s</a>',
23285 $this->get_text_inline( 'Click here', 'click-here' )
23286 )
23287 ),
23288 '',
23289 'success',
23290 false,
23291 'license_not_whitelabeled'
23292 );
23293 }
23294
23295 $this->do_action( 'account_page_load_before_departure' );
23296 }
23297
23298 /**
23299 * Renders the "Affiliation" page.
23300 *
23301 * @author Leo Fajardo (@leorw)
23302 * @since 1.2.3
23303 */
23304 function _affiliation_page_render() {
23305 $this->_logger->entrance();
23306
23307 $this->fetch_affiliate_and_terms();
23308
23309 fs_enqueue_local_style( 'fs_affiliation', '/admin/affiliation.css' );
23310
23311 $is_bundle_context = $this->has_bundle_context();
23312
23313 $plugin_title = $this->get_plugin_title();
23314
23315 if ( $is_bundle_context ) {
23316 $plugin_title = $this->plugin_affiliate_terms->plugin_title;
23317
23318 // Add the suffix "Bundle" only if the word is not present in the title itself.
23319 if ( false === mb_stripos( $plugin_title, fs_text_inline( 'Bundle', 'bundle' ) ) ) {
23320 $plugin_title = $this->apply_filters(
23321 'formatted_bundle_title',
23322 $plugin_title . ' ' . fs_text_inline( 'Bundle', 'bundle' )
23323 );
23324 }
23325 }
23326
23327 $vars = array(
23328 'id' => $this->_module_id,
23329 'plugin_title' => $plugin_title,
23330 );
23331 echo $this->apply_filters( "/forms/affiliation.php", fs_get_template( '/forms/affiliation.php', $vars ) );
23332 }
23333
23334
23335 /**
23336 * Render account page.
23337 *
23338 * @author Vova Feldman (@svovaf)
23339 * @since 1.0.0
23340 */
23341 function _account_page_render() {
23342 $this->_logger->entrance();
23343
23344 $template = 'account.php';
23345 $vars = array( 'id' => $this->_module_id );
23346
23347 /**
23348 * Added filter to the template to allow developers wrapping the template
23349 * in custom HTML (e.g. within a wizard/tabs).
23350 *
23351 * @author Vova Feldman (@svovaf)
23352 * @since 1.2.1.6
23353 */
23354 echo $this->apply_filters( "templates/{$template}", fs_get_template( $template, $vars ) );
23355 }
23356
23357 /**
23358 * Render account connect page.
23359 *
23360 * @author Vova Feldman (@svovaf)
23361 * @since 1.0.7
23362 */
23363 function _connect_page_render() {
23364 $this->_logger->entrance();
23365
23366 $vars = array( 'id' => $this->_module_id );
23367
23368 /**
23369 * Added filter to the template to allow developers wrapping the template
23370 * in custom HTML (e.g. within a wizard/tabs).
23371 *
23372 * @author Vova Feldman (@svovaf)
23373 * @since 1.2.1.6
23374 */
23375 echo $this->apply_filters( 'templates/connect.php', fs_get_template( 'connect.php', $vars ) );
23376 }
23377
23378 /**
23379 * Load required resources before add-ons page render.
23380 *
23381 * @author Vova Feldman (@svovaf)
23382 * @since 1.0.6
23383 */
23384 function _addons_page_load() {
23385 $this->_logger->entrance();
23386
23387 fs_enqueue_local_style( 'fs_addons', '/admin/add-ons.css' );
23388
23389 wp_enqueue_script( 'plugin-install' );
23390 add_thickbox();
23391 add_filter( 'admin_body_class', array( $this, 'fs_addons_body_class' ) );
23392
23393 if ( ! $this->is_registered() && $this->is_org_repo_compliant() ) {
23394 $this->_admin_notices->add(
23395 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>' ),
23396 $this->get_text_x_inline( 'Heads up', 'advance notice of something that will need attention.', 'heads-up' ),
23397 'update-nag'
23398 );
23399 }
23400 }
23401
23402 /**
23403 * Render add-ons page.
23404 *
23405 * @author Vova Feldman (@svovaf)
23406 * @since 1.0.6
23407 */
23408 function _addons_page_render() {
23409 $this->_logger->entrance();
23410
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/add-ons.php', fs_get_template( 'add-ons.php', $vars ) );
23421 }
23422
23423 /* Pricing & Upgrade
23424 ------------------------------------------------------------------------------------------------------------------*/
23425 /**
23426 * Render pricing page.
23427 *
23428 * @author Vova Feldman (@svovaf)
23429 * @since 1.0.0
23430 */
23431 function _pricing_page_render() {
23432 $this->_logger->entrance();
23433
23434 fs_enqueue_local_style( 'fs_common', '/admin/common.css' );
23435 fs_enqueue_local_style( 'fs_checkout', '/admin/checkout.css' );
23436
23437 $vars = array( 'id' => $this->_module_id );
23438
23439 if ( 'true' === fs_request_get( 'checkout', false ) ) {
23440 echo $this->apply_filters( 'templates/checkout.php', fs_get_template( 'checkout.php', $vars ) );
23441 } else {
23442 echo $this->apply_filters( 'templates/pricing.php', fs_get_template( 'pricing.php', $vars ) );
23443 }
23444 }
23445
23446 /**
23447 * @author Leo Fajardo (@leorw)
23448 * @since 2.3.1
23449 */
23450 function _add_pricing_ajax_handler() {
23451 $this->add_ajax_action( 'pricing_ajax_action', array( &$this, '_fs_pricing_ajax_action_handler' ) );
23452 }
23453
23454 /**
23455 * @author Leo Fajardo (@leorw)
23456 * @since 2.3.1
23457 */
23458 function _fs_pricing_ajax_action_handler() {
23459 $this->check_ajax_referer( 'pricing_ajax_action' );
23460
23461 $result = null;
23462 $pricing_action = fs_request_get( 'pricing_action' );
23463
23464 switch ( $pricing_action ) {
23465 case 'fetch_pricing_data':
23466 $params = array(
23467 'is_enriched' => true,
23468 'trial' => fs_request_get_bool( 'trial' ),
23469 'sandbox' => fs_request_get_raw( 'sandbox' ),
23470 's_ctx_type' => fs_request_get_raw( 's_ctx_type' ),
23471 's_ctx_id' => fs_request_get_raw( 's_ctx_id' ),
23472 's_ctx_ts' => fs_request_get_raw( 's_ctx_ts' ),
23473 's_ctx_secure' => fs_request_get_raw( 's_ctx_secure' ),
23474 );
23475
23476 $bundle_id = $this->get_bundle_id();
23477 $bundle_public_key = $this->get_bundle_public_key();
23478
23479 $has_bundle_context = ( FS_Plugin::is_valid_id( $bundle_id ) && ! empty( $bundle_public_key ) );
23480
23481 if ( ! $has_bundle_context ) {
23482 $api = $this->get_api_plugin_scope();
23483 } else {
23484 $api = FS_Api::instance(
23485 $bundle_id,
23486 'plugin',
23487 $bundle_id,
23488 $bundle_public_key,
23489 ! $this->is_live(),
23490 false,
23491 $this->get_sdk_version()
23492 );
23493
23494 $params['plugin_id'] = $this->get_id();
23495 $params['plugin_public_key'] = $this->get_public_key();
23496 }
23497
23498 $result = $api->get( 'pricing.json?' . http_build_query( $params ) );
23499 break;
23500 case 'start_trial':
23501 $trial_plan_id = fs_request_get( 'plan_id' );
23502
23503 if ( $this->is_registered() && $this->is_tracking_allowed() ) {
23504 $plan = $this->_get_plan_by_id( $trial_plan_id );
23505
23506 if ( ! $plan ) {
23507 $this->shoot_ajax_failure( 'Invalid plan ID.' );
23508 return;
23509 }
23510
23511 $result = $this->start_trial( $plan->name, true );
23512 } else {
23513 // @todo - This fails for sandbox trial at the moment if the trial was already utilized.
23514 $result = $this->opt_in(
23515 false,
23516 false,
23517 false,
23518 false,
23519 false,
23520 $trial_plan_id
23521 );
23522 }
23523 }
23524
23525 if ( is_object( $result ) && $this->is_api_error( $result ) ) {
23526 $this->_logger->api_error( $result );
23527
23528 self::shoot_ajax_failure(
23529 isset( $result->error ) ?
23530 ( is_string( $result->error ) ? $result->error : $result->error->message ) :
23531 var_export( $result, true )
23532 );
23533 }
23534
23535 $this->shoot_ajax_success( $result );
23536 }
23537
23538 #----------------------------------------------------------------------------------
23539 #region Contact Us
23540 #----------------------------------------------------------------------------------
23541
23542 /**
23543 * Render contact-us page.
23544 *
23545 * @author Vova Feldman (@svovaf)
23546 * @since 1.0.3
23547 */
23548 function _contact_page_render() {
23549 $this->_logger->entrance();
23550
23551 $vars = array( 'id' => $this->_module_id );
23552
23553 /**
23554 * Added filter to the template to allow developers wrapping the template
23555 * in custom HTML (e.g. within a wizard/tabs).
23556 *
23557 * @author Vova Feldman (@svovaf)
23558 * @since 2.1.3
23559 */
23560 echo $this->apply_filters( 'templates/contact.php', fs_get_template( 'contact.php', $vars ) );
23561 }
23562
23563 #endregion ------------------------------------------------------------------------
23564
23565 /**
23566 * Hide all admin notices to prevent distractions.
23567 *
23568 * @author Vova Feldman (@svovaf)
23569 * @since 1.0.3
23570 *
23571 * @uses remove_all_actions()
23572 */
23573 private static function _hide_admin_notices() {
23574 remove_all_actions( 'admin_notices' );
23575 remove_all_actions( 'network_admin_notices' );
23576 remove_all_actions( 'all_admin_notices' );
23577 remove_all_actions( 'user_admin_notices' );
23578 }
23579
23580 static function _clean_admin_content_section_hook() {
23581 $hide_admin_notices = true;
23582
23583 if ( fs_request_is_action( 'allow_clone_resolution_notice' ) ) {
23584 check_admin_referer( 'fs_allow_clone_resolution_notice' );
23585
23586 $hide_admin_notices = false;
23587 }
23588
23589 if ( $hide_admin_notices ) {
23590 self::_hide_admin_notices();
23591 }
23592
23593 // Hide footer.
23594 echo '<style>#wpfooter { display: none !important; }</style>';
23595 }
23596
23597 /**
23598 * Attach to admin_head hook to hide all admin notices.
23599 *
23600 * @author Vova Feldman (@svovaf)
23601 * @since 1.0.3
23602 */
23603 static function _clean_admin_content_section() {
23604 add_action( 'admin_head', 'Freemius::_clean_admin_content_section_hook' );
23605 }
23606
23607 /* CSS & JavaScript
23608 ------------------------------------------------------------------------------------------------------------------*/
23609 /* function _enqueue_script($handle, $src) {
23610 $url = plugins_url( substr( WP_FS__DIR_JS, strlen( $this->_plugin_dir_path ) ) . '/assets/js/' . $src );
23611
23612 $this->_logger->entrance( 'script = ' . $url );
23613
23614 wp_enqueue_script( $handle, $url );
23615 }*/
23616
23617 /* SDK
23618 ------------------------------------------------------------------------------------------------------------------*/
23619 private $_user_api;
23620
23621 /**
23622 *
23623 * @author Vova Feldman (@svovaf)
23624 * @since 1.0.2
23625 *
23626 * @param bool $flush
23627 *
23628 * @return FS_Api
23629 */
23630 function get_api_user_scope( $flush = false ) {
23631 if ( ! isset( $this->_user_api ) || $flush ) {
23632 $this->_user_api = $this->get_api_user_scope_by_user( $this->_user );
23633 }
23634
23635 return $this->_user_api;
23636 }
23637
23638 /**
23639 * @author Vova Feldman (@svovaf)
23640 * @since 2.0.0
23641 *
23642 * @param \FS_User $user
23643 *
23644 * @return \FS_Api
23645 */
23646 private function get_api_user_scope_by_user( FS_User $user ) {
23647 return FS_Api::instance(
23648 $this->_module_id,
23649 'user',
23650 $user->id,
23651 $user->public_key,
23652 ! $this->is_live(),
23653 $user->secret_key,
23654 $this->get_sdk_version()
23655 );
23656 }
23657
23658 /**
23659 *
23660 * @author Leo Fajardo (@leorw)
23661 * @since 2.0.0
23662 *
23663 * @param bool $flush
23664 *
23665 * @return FS_Api
23666 */
23667 private function get_current_or_network_user_api_scope( $flush = false ) {
23668 if ( ! $this->_is_network_active ||
23669 ( isset( $this->_user ) && $this->_user instanceof FS_User )
23670 ) {
23671 return $this->get_api_user_scope( $flush );
23672 }
23673
23674 $user = $this->get_current_or_network_user();
23675
23676 $this->_user_api = FS_Api::instance(
23677 $this->_module_id,
23678 'user',
23679 $user->id,
23680 $user->public_key,
23681 ! $this->is_live(),
23682 $user->secret_key,
23683 $this->get_sdk_version()
23684 );
23685
23686 return $this->_user_api;
23687 }
23688
23689 private $_site_api;
23690
23691 /**
23692 *
23693 * @author Vova Feldman (@svovaf)
23694 * @since 1.0.2
23695 *
23696 * @param bool $flush
23697 *
23698 * @return FS_Api
23699 */
23700 private function get_api_site_scope( $flush = false ) {
23701 if ( ! isset( $this->_site_api ) || $flush ) {
23702 $this->_site_api = FS_Api::instance(
23703 $this->_module_id,
23704 'install',
23705 $this->_site->id,
23706 $this->_site->public_key,
23707 ! $this->is_live(),
23708 $this->_site->secret_key,
23709 $this->get_sdk_version(),
23710 self::get_unfiltered_site_url()
23711 );
23712 }
23713
23714 return $this->_site_api;
23715 }
23716
23717 /**
23718 * @author Leo Fajardo (@leorw)
23719 * @since 2.5.0
23720 *
23721 * @param string $path
23722 * @param string $method
23723 * @param array $params
23724 * @param bool $flush_instance
23725 *
23726 * @return array|mixed|string|void
23727 * @throws Freemius_Exception
23728 */
23729 private function api_site_call( $path, $method = 'GET', $params = array(), $flush_instance = false ) {
23730 $result = $this->get_api_site_scope( $flush_instance )->call( $path, $method, $params );
23731
23732 /**
23733 * 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.
23734 *
23735 * @author Leo Fajardo (@leorw)
23736 * @since 2.5.0
23737 */
23738 if (
23739 $this->is_registered() &&
23740 FS_Api::is_api_result_entity( $result ) &&
23741 isset( $result->url )
23742 ) {
23743 $stored_local_url = trailingslashit( $this->_site->url );
23744 $stored_remote_url = trailingslashit( $result->url );
23745
23746 if ( $stored_local_url !== $stored_remote_url ) {
23747 $this->_site->url = $result->url;
23748 $this->_store_site();
23749 }
23750
23751 if ( fs_strip_url_protocol( $stored_remote_url ) !== self::get_unfiltered_site_url( null, true, true ) ) {
23752 FS_Clone_Manager::instance()->maybe_run_clone_resolution();
23753 }
23754 }
23755
23756 return $result;
23757 }
23758
23759 private $_plugin_api;
23760
23761 /**
23762 * Get plugin public API scope.
23763 *
23764 * @author Vova Feldman (@svovaf)
23765 * @since 1.0.7
23766 *
23767 * @return FS_Api
23768 */
23769 function get_api_plugin_scope() {
23770 if ( ! isset( $this->_plugin_api ) ) {
23771 $this->_plugin_api = FS_Api::instance(
23772 $this->_module_id,
23773 'plugin',
23774 $this->_plugin->id,
23775 $this->_plugin->public_key,
23776 ! $this->is_live(),
23777 false,
23778 $this->get_sdk_version()
23779 );
23780 }
23781
23782 return $this->_plugin_api;
23783 }
23784
23785 /**
23786 * Get bundle public API scope.
23787 *
23788 * @author Vova Feldman (@svovaf)
23789 * @since 2.3.1
23790 *
23791 * @return FS_Api
23792 */
23793 function get_api_bundle_scope() {
23794 return FS_Api::instance(
23795 $this->get_bundle_id(),
23796 'plugin',
23797 $this->get_bundle_id(),
23798 $this->get_bundle_public_key(),
23799 ! $this->is_live(),
23800 false,
23801 $this->get_sdk_version()
23802 );
23803 }
23804
23805 /**
23806 * Get site API scope object (fallback to public plugin scope when not registered).
23807 *
23808 * @author Vova Feldman (@svovaf)
23809 * @since 1.0.7
23810 *
23811 * @return FS_Api
23812 */
23813 function get_api_site_or_plugin_scope() {
23814 return $this->is_registered() ?
23815 $this->get_api_site_scope() :
23816 $this->get_api_plugin_scope();
23817 }
23818
23819 /**
23820 * @author Leo Fajardo (@leorw)
23821 * @since 2.2.3.1
23822 *
23823 * @param object $result
23824 */
23825 private function maybe_modify_api_curl_error_message( $result ) {
23826 if (
23827 'cUrlMissing' !== $result->error->type &&
23828 ( 'CurlException' !== $result->error->type || CURLE_COULDNT_CONNECT != $result->error->code ) &&
23829 ( 'HttpRequestFailed' !== $result->error->type || false === strpos( $result->error->message, 'cURL error ' . CURLE_COULDNT_CONNECT ) )
23830 ) {
23831 return;
23832 }
23833
23834 $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' ) .
23835 ' ' .
23836 $this->esc_html_inline(
23837 sprintf(
23838 'Please contact your hosting provider and ask them to whitelist %s for external connection.',
23839 implode(
23840 ', ',
23841 $this->apply_filters( 'api_domains', array(
23842 'api.freemius.com',
23843 'wp.freemius.com'
23844 ) )
23845 )
23846 ),
23847 'connectivity-whitelist'
23848 ) .
23849 ' ' .
23850 sprintf(
23851 $this->esc_html_inline( 'Once you are done, deactivate the %s and activate it again.', 'connectivity-reactivate-module' ),
23852 $this->get_module_type()
23853 );
23854 }
23855
23856 /**
23857 * Show trial promotional notice (if any trial exist).
23858 *
23859 * @author Vova Feldman (@svovaf)
23860 * @since 1.0.9
23861 *
23862 * @param FS_Plugin_Plan[] $plans
23863 */
23864 function _check_for_trial_plans( $plans ) {
23865 /**
23866 * 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.
23867 *
23868 * @author Vova Feldman (@svovaf)
23869 * @since 2.1.2
23870 */
23871 if ( ! is_array( $plans ) && is_object( $plans ) ) {
23872 $plans = array( $plans );
23873 }
23874
23875 if ( ! $this->is_array_instanceof( $plans, 'FS_Plugin_Plan' ) ) {
23876 $plans = array();
23877 }
23878
23879 $this->_storage->has_trial_plan = FS_Plan_Manager::instance()->has_trial_plan( $plans );
23880 }
23881
23882 /**
23883 * During trial promotion the "upgrade" submenu item turns to
23884 * "start trial" to encourage the trial. Since we want to keep
23885 * the same menu item handler and there's no robust way to
23886 * add new arguments to the menu item link's querystring,
23887 * use JavaScript to find the menu item and update the href of
23888 * the link.
23889 *
23890 * @author Vova Feldman (@svovaf)
23891 * @since 1.2.1.5
23892 */
23893 function _fix_start_trial_menu_item_url() {
23894 $template_args = array( 'id' => $this->_module_id );
23895 fs_require_template( 'add-trial-to-pricing.php', $template_args );
23896 }
23897
23898 /**
23899 * Check if module is currently in a trial promotion mode.
23900 *
23901 * @author Vova Feldman (@svovaf)
23902 * @since 1.2.2.7
23903 *
23904 * @return bool
23905 */
23906 function is_in_trial_promotion() {
23907 return $this->_admin_notices->has_sticky( 'trial_promotion' );
23908 }
23909
23910 /**
23911 * Show trial promotional notice (if any trial exist).
23912 *
23913 * @author Vova Feldman (@svovaf)
23914 * @since 1.0.9
23915 *
23916 * @return bool If trial notice added.
23917 */
23918 function _add_trial_notice() {
23919 if ( ! $this->is_user_admin() ) {
23920 return false;
23921 }
23922
23923 if ( ! $this->is_user_in_admin() ) {
23924 return false;
23925 }
23926
23927 if ( $this->_is_network_active ) {
23928 if ( fs_is_network_admin() ) {
23929 // Network level trial is disabled at the moment.
23930 return false;
23931 }
23932
23933 if ( ! $this->is_delegated_connection() ) {
23934 // Only delegated sites should support trials.
23935 return false;
23936 }
23937 }
23938
23939 // Check if trial message is already shown.
23940 if ( $this->is_in_trial_promotion() ) {
23941 add_action( 'admin_footer', array( &$this, '_fix_start_trial_menu_item_url' ) );
23942
23943 $this->_menu->add_counter_to_menu_item( 1, 'fs-trial' );
23944
23945 return false;
23946 }
23947
23948 if ( $this->is_premium() && ! WP_FS__DEV_MODE ) {
23949 // Don't show trial if running the premium code, unless running in DEV mode.
23950 return false;
23951 }
23952
23953 if ( ! $this->has_trial_plan() ) {
23954 // No plans with trial.
23955 return false;
23956 }
23957
23958 if ( ! $this->apply_filters( 'show_trial', true ) ) {
23959 // Developer explicitly asked not to show the trial promo.
23960 return false;
23961 }
23962
23963 if ( $this->is_registered() ) {
23964 // Check if trial already utilized.
23965 if ( $this->_site->is_trial_utilized() ) {
23966 return false;
23967 }
23968
23969 if ( $this->is_paying_or_trial() ) {
23970 // Don't show trial if paying or already in trial.
23971 return false;
23972 }
23973 }
23974
23975 if ( $this->is_activation_mode() || $this->is_pending_activation() ) {
23976 // If not yet opted-in/skipped, or pending activation, don't show trial.
23977 return false;
23978 }
23979
23980 $last_time_trial_promotion_shown = $this->_storage->get( 'trial_promotion_shown', false );
23981 $was_promotion_shown_before = ( false !== $last_time_trial_promotion_shown );
23982
23983 // Show promotion if never shown before and 24 hours after initial activation with FS.
23984 if ( ! $was_promotion_shown_before &&
23985 $this->_storage->install_timestamp > ( time() - $this->apply_filters( 'show_first_trial_after_n_sec', WP_FS__TIME_24_HOURS_IN_SEC ) )
23986 ) {
23987 return false;
23988 }
23989
23990 // OR if promotion was shown before, try showing it every 30 days.
23991 if ( $was_promotion_shown_before &&
23992 $this->apply_filters( 'reshow_trial_after_every_n_sec', 30 * WP_FS__TIME_24_HOURS_IN_SEC ) > time() - $last_time_trial_promotion_shown
23993 ) {
23994 return false;
23995 }
23996
23997 $trial_period = $this->_trial_days;
23998 $require_payment = $this->_is_trial_require_payment;
23999 $trial_url = $this->get_trial_url();
24000 $plans_string = strtolower( $this->get_text_inline( 'Awesome', 'awesome' ) );
24001
24002 if ( $this->is_registered() ) {
24003 // If opted-in, override trial with up to date data from API.
24004 $trial_plans = FS_Plan_Manager::instance()->get_visible_trial_plans( $this->_plans );
24005 $trial_plans_count = count( $trial_plans );
24006
24007 if ( 0 === $trial_plans_count ) {
24008 // If there's no plans with a trial just exit.
24009 return false;
24010 }
24011
24012 /**
24013 * @var FS_Plugin_Plan $paid_plan
24014 */
24015 $paid_plan = $trial_plans[0];
24016 $require_payment = $paid_plan->is_require_subscription;
24017 $trial_period = $paid_plan->trial_period;
24018
24019 $total_paid_plans = count( $this->_plans ) - ( FS_Plan_Manager::instance()->has_free_plan( $this->_plans ) ? 1 : 0 );
24020
24021 if ( $total_paid_plans !== $trial_plans_count ) {
24022 // Not all paid plans have a trial - generate a string of those that have it.
24023 for ( $i = 0; $i < $trial_plans_count; $i ++ ) {
24024 $plans_string .= sprintf(
24025 ' <a href="%s">%s</a>',
24026 $trial_url,
24027 $trial_plans[ $i ]->title
24028 );
24029
24030 if ( $i < $trial_plans_count - 2 ) {
24031 $plans_string .= ', ';
24032 } else if ( $i == $trial_plans_count - 2 ) {
24033 $plans_string .= ' and ';
24034 }
24035 }
24036 }
24037 }
24038
24039 $message = sprintf(
24040 $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' ),
24041 sprintf( '<b>%s</b>', $this->get_plugin_name() ),
24042 $plans_string,
24043 $trial_period
24044 );
24045
24046 // "No Credit-Card Required" or "No Commitment for N Days".
24047 $cc_string = $require_payment ?
24048 sprintf( $this->get_text_inline( 'No commitment for %s days - cancel anytime!', 'no-commitment-for-x-days' ), $trial_period ) :
24049 $this->get_text_inline( 'No credit card required', 'no-cc-required' ) . '!';
24050
24051
24052 // Start trial button.
24053 $button = ' ' . sprintf(
24054 '<div><a class="button button-primary" href="%s">%s &nbsp;&#10140;</a></div>',
24055 $trial_url,
24056 $this->get_text_x_inline( 'Start free trial', 'call to action', 'start-free-trial' )
24057 );
24058
24059 $message_text = $this->apply_filters( 'trial_promotion_message', "{$message} {$cc_string}" );
24060
24061 $this->_admin_notices->add_sticky(
24062 "<div class=\"fs-trial-message-container\"><div>{$message_text}</div> {$button}</div>",
24063 'trial_promotion',
24064 '',
24065 'promotion'
24066 );
24067
24068 $this->_storage->trial_promotion_shown = WP_FS__SCRIPT_START_TIME;
24069
24070 return true;
24071 }
24072
24073 /**
24074 * Lets users/customers know that the product has an affiliate program.
24075 *
24076 * @author Leo Fajardo (@leorw)
24077 * @since 1.2.2.11
24078 *
24079 * @return bool Returns true if the notice has been added.
24080 */
24081 function _add_affiliate_program_notice() {
24082 if ( ! $this->is_user_admin() ) {
24083 return false;
24084 }
24085
24086 if ( ! $this->is_user_in_admin() ) {
24087 return false;
24088 }
24089
24090 // Check if the notice is already shown.
24091 if ( $this->_admin_notices->has_sticky( 'affiliate_program' ) ) {
24092 return false;
24093 }
24094
24095 if (
24096 // Product has no affiliate program.
24097 ! $this->has_affiliate_program() ||
24098 // User has applied for an affiliate account.
24099 ! empty( $this->_storage->affiliate_application_data )
24100 ) {
24101 return false;
24102 }
24103
24104 if ( ! $this->apply_filters( 'show_affiliate_program_notice', true ) ) {
24105 // Developer explicitly asked not to show the notice about the affiliate program.
24106 return false;
24107 }
24108
24109 if ( $this->is_activation_mode() || $this->is_pending_activation() ) {
24110 // If not yet opted in/skipped, or pending activation, don't show the notice.
24111 return false;
24112 }
24113
24114 $last_time_notice_was_shown = $this->_storage->get( 'affiliate_program_notice_shown', false );
24115 $was_notice_shown_before = ( false !== $last_time_notice_was_shown );
24116
24117 /**
24118 * Do not show the notice if it was already shown before or less than 30 days have passed since the initial
24119 * activation with FS.
24120 */
24121 if ( $was_notice_shown_before ||
24122 $this->_storage->install_timestamp > ( time() - ( WP_FS__TIME_24_HOURS_IN_SEC * 30 ) )
24123 ) {
24124 return false;
24125 }
24126
24127 if ( ! $this->is_paying() &&
24128 FS_Plugin::AFFILIATE_MODERATION_CUSTOMERS == $this->_plugin->affiliate_moderation
24129 ) {
24130 // If the user is not a customer and the affiliate program is only for customers, don't show the notice.
24131 return false;
24132 }
24133
24134 $message = sprintf(
24135 $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' ),
24136 sprintf( '<strong>%s</strong>', $this->get_plugin_name() ),
24137 $this->get_module_label( true )
24138 );
24139
24140 // HTML code for the "Learn more..." button.
24141 $button = ' ' . sprintf(
24142 '<a style="display: block; margin-top: 10px;" href="%s"><button class="button button-primary">%s &nbsp;&#10140;</button></a>',
24143 $this->_get_admin_page_url( 'affiliation' ),
24144 $this->get_text_inline( 'Learn more', 'learn-more' ) . '...'
24145 );
24146
24147 $this->_admin_notices->add_sticky(
24148 $this->apply_filters( 'affiliate_program_notice', "{$message} {$button}" ),
24149 'affiliate_program',
24150 '',
24151 'promotion'
24152 );
24153
24154 $this->_storage->affiliate_program_notice_shown = WP_FS__SCRIPT_START_TIME;
24155
24156 return true;
24157 }
24158
24159 /**
24160 * @author Vova Feldman (@svovaf)
24161 * @since 1.2.1.5
24162 */
24163 function _enqueue_common_css() {
24164 if ( $this->has_paid_plan() && ! $this->is_paying() ) {
24165 // Add basic CSS for admin-notices and menu-item colors.
24166 fs_enqueue_local_style( 'fs_common', '/admin/common.css' );
24167 }
24168 }
24169
24170 /**
24171 * @author Leo Fajardo (@leorw)
24172 * @since 1.2.2
24173 */
24174 function _show_theme_activation_optin_dialog() {
24175 fs_enqueue_local_style( 'fs_connect', '/admin/connect.css' );
24176
24177 add_action( 'admin_footer', array( &$this, '_add_fs_theme_activation_dialog' ) );
24178 }
24179
24180 /**
24181 * @author Leo Fajardo (@leorw)
24182 * @since 1.2.2
24183 */
24184 function _add_fs_theme_activation_dialog() {
24185 global $pagenow;
24186
24187 if ( 'themes.php' !== $pagenow ) {
24188 return;
24189 }
24190
24191 $vars = array( 'id' => $this->_module_id );
24192 fs_require_once_template( 'connect.php', $vars );
24193 }
24194
24195 /* Action Links
24196 ------------------------------------------------------------------------------------------------------------------*/
24197 private $_action_links_hooked = false;
24198 private $_action_links = array();
24199
24200 /**
24201 * Hook to plugin action links filter.
24202 *
24203 * @author Vova Feldman (@svovaf)
24204 * @since 1.0.0
24205 */
24206 private function hook_plugin_action_links() {
24207 $this->_logger->entrance();
24208
24209 $this->_action_links_hooked = true;
24210
24211 $this->_logger->log( 'Adding action links hooks.' );
24212
24213 // Add action link to settings page.
24214 add_filter( 'plugin_action_links_' . $this->_plugin_basename, array(
24215 &$this,
24216 '_modify_plugin_action_links_hook'
24217 ), WP_FS__DEFAULT_PRIORITY, 2 );
24218 add_filter( 'network_admin_plugin_action_links_' . $this->_plugin_basename, array(
24219 &$this,
24220 '_modify_plugin_action_links_hook'
24221 ), WP_FS__DEFAULT_PRIORITY, 2 );
24222 }
24223
24224 /**
24225 * Add plugin action link.
24226 *
24227 * @author Vova Feldman (@svovaf)
24228 * @since 1.0.0
24229 *
24230 * @param $label
24231 * @param $url
24232 * @param bool $external
24233 * @param int $priority
24234 * @param bool $key
24235 */
24236 function add_plugin_action_link( $label, $url, $external = false, $priority = WP_FS__DEFAULT_PRIORITY, $key = false ) {
24237 $this->_logger->entrance();
24238
24239 if ( ! isset( $this->_action_links[ $priority ] ) ) {
24240 $this->_action_links[ $priority ] = array();
24241 }
24242
24243 if ( false === $key ) {
24244 $key = preg_replace( "/[^A-Za-z0-9 ]/", '', strtolower( $label ) );
24245 }
24246
24247 $this->_action_links[ $priority ][] = array(
24248 'label' => $label,
24249 'href' => $url,
24250 'key' => $key,
24251 'external' => $external
24252 );
24253 }
24254
24255 /**
24256 * Adds Upgrade and Add-Ons links to the main Plugins page link actions collection.
24257 *
24258 * @author Vova Feldman (@svovaf)
24259 * @since 1.0.0
24260 */
24261 function _add_upgrade_action_link() {
24262 $this->_logger->entrance();
24263
24264 $is_activation_mode = $this->is_activation_mode();
24265
24266 $add_action_links = $this->should_add_submenu_or_action_links( $is_activation_mode );
24267
24268 /**
24269 * The following logic is based on the logic in `add_submenu_items()` method that decides when the "Upgrade"
24270 * and "Add-Ons" menus should be added.
24271 *
24272 * @author Leo Fajardo (@leorw)
24273 * @since 2.3.0
24274 */
24275 $add_upgrade_link = (
24276 $add_action_links ||
24277 ( $is_activation_mode && $this->is_only_premium() )
24278 ) && ! WP_FS__DEMO_MODE && ( ! $this->is_whitelabeled() );
24279
24280 $add_addons_link = ( $add_action_links && $this->has_addons() );
24281
24282 if ( ! $add_upgrade_link && ! $add_addons_link ) {
24283 return;
24284 }
24285
24286 if (
24287 $add_upgrade_link &&
24288 $this->is_pricing_page_visible() &&
24289 $this->is_submenu_item_visible( 'pricing' )
24290 ) {
24291 $this->add_plugin_action_link(
24292 $this->get_text_inline( 'Upgrade', 'upgrade' ),
24293 $this->get_upgrade_url(),
24294 false,
24295 7,
24296 'upgrade'
24297 );
24298 }
24299
24300 if (
24301 $add_addons_link &&
24302 $this->has_addons() &&
24303 $this->is_submenu_item_visible( 'addons' )
24304 ) {
24305 $this->add_plugin_action_link(
24306 $this->get_text_inline( 'Add-Ons', 'add-ons' ),
24307 $this->_get_admin_page_url( 'addons' ),
24308 false,
24309 9,
24310 'addons'
24311 );
24312 }
24313 }
24314
24315 /**
24316 * Adds "Activate License" or "Change License" link to the main Plugins page link actions collection.
24317 *
24318 * @author Leo Fajardo (@leorw)
24319 * @since 1.1.9
24320 */
24321 function _add_license_action_link() {
24322 $this->_logger->entrance();
24323
24324 if ( ! self::is_ajax() ) {
24325 // Inject license activation dialog UI and client side code.
24326 add_action( 'admin_footer', array( &$this, '_add_license_activation_dialog_box' ) );
24327 }
24328
24329 $link_text = $this->is_free_plan() ?
24330 $this->get_text_inline( 'Activate License', 'activate-license' ) :
24331 $this->get_text_inline( 'Change License', 'change-license' );
24332
24333 $this->add_plugin_action_link(
24334 $link_text,
24335 '#',
24336 false,
24337 11,
24338 ( 'activate-license ' . $this->get_unique_affix() )
24339 );
24340 }
24341
24342 /**
24343 * @author Leo Fajardo (@leorw)
24344 * @since 2.0.2
24345 */
24346 function _add_premium_version_upgrade_selection_action() {
24347 $this->_logger->entrance();
24348
24349 if ( ! self::is_ajax() ) {
24350 add_action( 'admin_footer', array( &$this, '_add_premium_version_upgrade_selection_dialog_box' ) );
24351 }
24352 }
24353
24354 /**
24355 * Adds "Opt In" or "Opt Out" link to the main "Plugins" page link actions collection.
24356 *
24357 * @author Leo Fajardo (@leorw)
24358 * @since 1.2.1.5
24359 */
24360 function _add_tracking_links() {
24361 if ( ! current_user_can( 'manage_options' ) ) {
24362 return;
24363 }
24364
24365 $this->_logger->entrance();
24366
24367 if ( $this->is_only_premium() && $this->is_free_plan() ) {
24368 // 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.
24369 return;
24370 }
24371
24372 if (
24373 $this->is_addon() &&
24374 ! $this->is_only_premium()
24375 ) {
24376 $parent = $this->get_parent_instance();
24377
24378 if ( is_object( $parent ) && $parent->is_anonymous() ) {
24379 return;
24380 }
24381 }
24382
24383 if ( fs_is_network_admin() ) {
24384 if ( ! $this->_is_network_active ) {
24385 // Don't add tracking links when browsing the network WP Admin and the plugin is not network active.
24386 return;
24387 } else if ( $this->is_network_delegated_connection() ) {
24388 // Don't add tracking links when browsing the network WP Admin and the activation has been delegated to site admins.
24389 return;
24390 }
24391 } else {
24392 if ( $this->_is_network_active && ! $this->is_delegated_connection() ) {
24393 // Don't add tracking links when browsing the sub-site WP Admin, the plugin is network active, and the connection was not delegated.
24394 return;
24395 }
24396 }
24397
24398 if ( fs_request_is_action_secure( $this->get_unique_affix() . '_reconnect' ) ) {
24399 if ( ! $this->is_registered() && $this->is_anonymous() ) {
24400 $this->connect_again();
24401
24402 return;
24403 }
24404 }
24405
24406 if ( ( $this->is_plugin() && ! self::is_plugins_page() ) ||
24407 ( $this->is_theme() && ! self::is_themes_page() )
24408 ) {
24409 // Only show tracking links on the plugins and themes pages.
24410 return;
24411 }
24412
24413 if (
24414 $this->is_activation_mode() &&
24415 $this->is_premium() &&
24416 ! $this->is_registered()
24417 ) {
24418 // If not yet registered and running the premium code base, a license activation link will already be shown.
24419 return;
24420 }
24421
24422 if ( $this->is_registered() && $this->is_tracking_allowed() ) {
24423 if ( ! $this->is_premium() && ! $this->is_enable_anonymous() ) {
24424 // If opted in and tracking is allowed, don't allow to opt out if not premium and anonymous mode is disabled.
24425 return;
24426 }
24427 }
24428
24429 if ( $this->add_ajax_action( 'toggle_permission_tracking', array( &$this, '_toggle_permission_tracking_callback' ) ) ) {
24430 return;
24431 }
24432
24433 $link_text_id = '';
24434 $url = '#';
24435
24436 if ( $this->is_registered( true ) ) {
24437 if ( $this->is_registered() && $this->is_tracking_allowed() ) {
24438 $link_text_id = $this->get_text_inline( 'Opt Out', 'opt-out' );
24439 } else {
24440 $link_text_id = $this->get_text_inline( 'Opt In', 'opt-in' );
24441 }
24442 } else if ( $this->is_anonymous() || $this->is_activation_mode() ) {
24443 /**
24444 * Show opt-in link only if skipped or in activation mode.
24445 */
24446 $link_text_id = $this->get_text_inline( 'Opt In', 'opt-in' );
24447
24448 $params = ! $this->is_anonymous() ?
24449 array() :
24450 array(
24451 'nonce' => wp_create_nonce( $this->get_unique_affix() . '_reconnect' ),
24452 'fs_action' => ( $this->get_unique_affix() . '_reconnect' ),
24453 );
24454
24455 $url = $this->get_activation_url( $params );
24456 }
24457
24458 add_action( 'admin_footer', array( &$this, '_add_optout_dialog' ) );
24459
24460 if ( ! empty( $link_text_id ) && $this->is_plugin() && self::is_plugins_page() ) {
24461 $this->add_plugin_action_link(
24462 $link_text_id,
24463 $url,
24464 false,
24465 13,
24466 "opt-in-or-opt-out {$this->_slug}"
24467 );
24468 }
24469 }
24470
24471 /**
24472 * Get the URL of the page that should be loaded right after the plugin activation.
24473 *
24474 * @author Vova Feldman (@svovaf)
24475 * @since 1.1.7.4
24476 *
24477 * @return string
24478 */
24479 function get_after_plugin_activation_redirect_url() {
24480 $url = false;
24481
24482 if ( ! $this->is_addon() || ! $this->has_free_plan() ) {
24483 $first_time_path = $this->_menu->get_first_time_path(
24484 fs_is_network_admin() && $this->_is_network_active
24485 );
24486
24487 if ( $this->is_activation_mode() ) {
24488 $url = $this->get_activation_url();
24489 } else if ( ! empty( $first_time_path ) ) {
24490 $url = $first_time_path;
24491 } else {
24492 $page = '';
24493 if ( ! empty( $this->_dynamically_added_top_level_page_hook_name ) ) {
24494 if ( $this->is_network_registered() ) {
24495 $page = 'account';
24496 } else if ( $this->is_pending_activation() || $this->is_network_anonymous() ) {
24497 $this->maybe_set_slug_and_network_menu_exists_flag();
24498 }
24499 }
24500
24501 $url = $this->_get_admin_page_url( $page );
24502 }
24503 } else {
24504 $plugin_fs = false;
24505
24506 if ( $this->is_parent_plugin_installed() ) {
24507 $plugin_fs = self::get_parent_instance();
24508 }
24509
24510 if ( is_object( $plugin_fs ) ) {
24511 if ( ! $plugin_fs->is_registered() ) {
24512 // Forward to parent plugin connect when parent not registered.
24513 $url = $plugin_fs->get_activation_url();
24514 } else {
24515 // Forward to account page.
24516 $url = $plugin_fs->_get_admin_page_url( 'account' );
24517 }
24518 }
24519 }
24520
24521 return $url;
24522 }
24523
24524 /**
24525 * Forward page to activation page.
24526 *
24527 * @author Vova Feldman (@svovaf)
24528 * @since 1.0.3
24529 */
24530 function _redirect_on_activation_hook() {
24531 if ( $this->apply_filters( 'redirect_on_activation', true ) ) {
24532 $url = $this->get_after_plugin_activation_redirect_url();
24533
24534 if ( is_string( $url ) ) {
24535 fs_redirect( $url );
24536 }
24537 }
24538 }
24539
24540 /**
24541 * Modify plugin's page action links collection.
24542 *
24543 * @author Vova Feldman (@svovaf)
24544 * @since 1.0.0
24545 *
24546 * @param array $links
24547 * @param $file
24548 *
24549 * @return array
24550 */
24551 function _modify_plugin_action_links_hook( $links, $file ) {
24552 $this->_logger->entrance();
24553
24554 $passed_deactivate = false;
24555 $deactivate_link = '';
24556 $before_deactivate = array();
24557 $after_deactivate = array();
24558 foreach ( $links as $key => $link ) {
24559 if ( 'deactivate' === $key ) {
24560 $deactivate_link = $link;
24561 $passed_deactivate = true;
24562 continue;
24563 }
24564
24565 if ( ! $passed_deactivate ) {
24566 $before_deactivate[ $key ] = $link;
24567 } else {
24568 $after_deactivate[ $key ] = $link;
24569 }
24570 }
24571
24572 ksort( $this->_action_links );
24573
24574 foreach ( $this->_action_links as $new_links ) {
24575 foreach ( $new_links as $link ) {
24576 $before_deactivate[ $link['key'] ] = '<a href="' . $link['href'] . '"' . ( $link['external'] ? ' target="_blank" rel="noopener"' : '' ) . '>' . $link['label'] . '</a>';
24577 }
24578 }
24579
24580 if ( ! empty( $deactivate_link ) ) {
24581 /**
24582 * This HTML element is used to identify the correct plugin when attaching an event to its Deactivate link.
24583 *
24584 * @since 1.2.1.6 Always show the deactivation feedback form since we added automatic free version deactivation upon premium code activation.
24585 */
24586 $deactivate_link .= '<i class="fs-module-id" data-module-id="' . $this->_module_id . '"></i>';
24587
24588 // Append deactivation link.
24589 $before_deactivate['deactivate'] = $deactivate_link;
24590 }
24591
24592 return array_merge( $before_deactivate, $after_deactivate );
24593 }
24594
24595 /**
24596 * Adds admin message.
24597 *
24598 * @author Vova Feldman (@svovaf)
24599 * @since 1.0.4
24600 *
24601 * @param string $message
24602 * @param string $title
24603 * @param string $type
24604 */
24605 function add_admin_message( $message, $title = '', $type = 'success' ) {
24606 $this->_admin_notices->add( $message, $title, $type );
24607 }
24608
24609 /**
24610 * Adds sticky admin message.
24611 *
24612 * @author Vova Feldman (@svovaf)
24613 * @since 1.1.0
24614 *
24615 * @param string $message
24616 * @param string $id
24617 * @param string $title
24618 * @param string $type
24619 */
24620 function add_sticky_admin_message( $message, $id, $title = '', $type = 'success' ) {
24621 $this->_admin_notices->add_sticky( $message, $id, $title, $type );
24622 }
24623
24624 /**
24625 * Check if the paid version of the module is installed.
24626 *
24627 * @author Vova Feldman (@svovaf)
24628 * @since 2.2.0
24629 *
24630 * @return bool
24631 */
24632 private function is_premium_version_installed() {
24633 $premium_plugin_basename = $this->premium_plugin_basename();
24634
24635 if ( $this->is_theme() ) {
24636 return $this->can_activate_theme( $this->get_premium_slug() );
24637 }
24638
24639 return file_exists( fs_normalize_path( WP_PLUGIN_DIR . '/' . $premium_plugin_basename ) );
24640 }
24641
24642 /**
24643 * Helper function that returns the final steps for the upgrade completion.
24644 *
24645 * If the module is already running the premium code, returns an empty string.
24646 *
24647 * @author Vova Feldman (@svovaf)
24648 * @since 1.2.1
24649 *
24650 * @param string $plan_title
24651 *
24652 * @return string
24653 */
24654 private function get_complete_upgrade_instructions( $plan_title = '' ) {
24655 $this->_logger->entrance();
24656
24657 $activate_license_string = $this->get_license_network_activation_notice();
24658
24659 if ( ! $this->has_premium_version() || $this->is_premium() ) {
24660 return '' . $activate_license_string;
24661 }
24662
24663 if ( empty( $plan_title ) ) {
24664 $plan_title = $this->get_plan_title();
24665 }
24666
24667 if ( $this->is_premium_version_installed() ) {
24668 /**
24669 * If the premium version is already installed, instead of showing the installation instructions,
24670 * tell the current user to activate it.
24671 *
24672 * @author Leo Fajardo (@leorw)
24673 * @since 2.2.1
24674 */
24675 $premium_theme_slug_or_plugin_basename = $this->is_theme() ?
24676 $this->get_premium_slug() :
24677 $this->premium_plugin_basename();
24678
24679 return sprintf(
24680 /* translators: %1$s: Product title; %2$s: Plan title */
24681 $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' ),
24682 sprintf( '<em>%s</em>', esc_html( $this->get_plugin_title() ) ),
24683 $plan_title,
24684 sprintf(
24685 '<a style="margin-left: 10px;" href="%s"><button class="button button-primary">%s</button></a>',
24686 ( $this->is_theme() ?
24687 wp_nonce_url( 'themes.php?action=activate&amp;stylesheet=' . $premium_theme_slug_or_plugin_basename, 'switch-theme_' . $premium_theme_slug_or_plugin_basename ) :
24688 wp_nonce_url( 'plugins.php?action=activate&amp;plugin=' . $premium_theme_slug_or_plugin_basename, 'activate-plugin_' . $premium_theme_slug_or_plugin_basename ) ),
24689 esc_html( sprintf(
24690 /* translators: %s: Plan title */
24691 $this->get_text_inline( 'Activate %s features', 'activate-x-features' ),
24692 $plan_title
24693 ) )
24694 )
24695 );
24696 } else {
24697 // @since 1.2.1.5 The free version is auto deactivated.
24698 $deactivation_step = version_compare( $this->version, '1.2.1.5', '<' ) ?
24699 ( '<li>' . $this->esc_html_inline( 'Deactivate the free version', 'deactivate-free-version' ) . '.</li>' ) :
24700 '';
24701
24702 return sprintf(
24703 ' %s: <ol><li>%s.</li>%s<li>%s (<a href="%s" target="_blank" rel="noopener">%s</a>).</li></ol>',
24704 $this->get_text_inline( 'Please follow these steps to complete the upgrade', 'follow-steps-to-complete-upgrade' ),
24705 ( empty( $activate_license_string ) ? '' : $activate_license_string . '</li><li>' ) .
24706 $this->get_latest_download_link( sprintf(
24707 /* translators: %s: Plan title */
24708 $this->get_text_inline( 'Download the latest %s version', 'download-latest-x-version' ),
24709 $plan_title
24710 ) ),
24711 $deactivation_step,
24712 $this->get_text_inline( 'Upload and activate the downloaded version', 'upload-and-activate' ),
24713 $this->apply_filters( 'upload_and_install_video_url', '//bit.ly/wp-' . $this->_module_type . '-upload' ),
24714 $this->get_text_inline( 'How to upload and activate?', 'howto-upload-activate' )
24715 );
24716 }
24717 }
24718
24719 /**
24720 * @author Leo Fajardo (@leorw)
24721 * @since 2.5.3
24722 *
24723 * @param string $message_before_the_instructions
24724 * @param string $message_id
24725 * @param string $plan_title
24726 */
24727 private function add_complete_upgrade_instructions_notice(
24728 $message_before_the_instructions,
24729 $message_id,
24730 $plan_title = ''
24731 ) {
24732 $this->_admin_notices->add_sticky(
24733 $message_before_the_instructions .
24734 $this->get_complete_upgrade_instructions( $plan_title ),
24735 $message_id,
24736 $this->get_text_x_inline( 'Yee-haw', 'interjection expressing joy or exuberance', 'yee-haw' ) . '!'
24737 );
24738 }
24739
24740 /**
24741 * @author Leo Fajardo (@leorw)
24742 * @since 2.5.3
24743 *
24744 * @param bool $is_upgrade
24745 */
24746 private function add_after_plan_activation_or_upgrade_instructions_notice( $is_upgrade = true ) {
24747 $this->add_complete_upgrade_instructions_notice(
24748 $is_upgrade ?
24749 $this->get_text_inline( 'Your plan was successfully upgraded.', 'plan-upgraded-message' ) :
24750 $this->get_text_inline( 'Your plan was successfully activated.', 'plan-activated-message' ),
24751 'plan_upgraded'
24752 );
24753 }
24754
24755 /**
24756 * @author Leo Fajardo (@leorw)
24757 * @since 2.1.0
24758 *
24759 * @param string $url
24760 * @param array $request
24761 * @param int $success_cache_expiration
24762 * @param int $failure_cache_expiration
24763 * @param bool $maybe_enrich_request_for_debug
24764 *
24765 * @return WP_Error|array
24766 */
24767 static function safe_remote_post(
24768 &$url,
24769 $request,
24770 $success_cache_expiration = 0,
24771 $failure_cache_expiration = 0,
24772 $maybe_enrich_request_for_debug = true
24773 ) {
24774 $should_cache = ($success_cache_expiration + $failure_cache_expiration > 0);
24775
24776 $cache_key = $should_cache ? md5( fs_strip_url_protocol($url) . json_encode( $request ) ) : false;
24777
24778 $response = (!WP_FS__DEBUG_SDK && ( false !== $cache_key )) ?
24779 get_transient( $cache_key ) :
24780 false;
24781
24782 if ( false === $response ) {
24783 if ( $maybe_enrich_request_for_debug ) {
24784 FS_DebugManager::enrich_request_for_debug( $url, $request );
24785 }
24786
24787 if ( ! isset( $request['method'] ) ) {
24788 $request['method'] = 'POST';
24789 }
24790
24791 $response = FS_Api::remote_request( $url, $request );
24792
24793 if (
24794 'https://' === substr( $url, 0, 8 ) &&
24795 FS_Api::is_ssl_error_response( $response )
24796 ) {
24797 // Failed due to old version of cURL or Open SSL (SSLv3 is not supported by CloudFlare).
24798 $url = 'http://' . substr( $url, 8 );
24799
24800 $request['timeout'] = 15;
24801 $response = FS_Api::remote_request( $url, $request );
24802 }
24803
24804 if ( false !== $cache_key ) {
24805 set_transient(
24806 $cache_key,
24807 $response,
24808 ( ( $response instanceof WP_Error ) ?
24809 $failure_cache_expiration :
24810 $success_cache_expiration )
24811 );
24812 }
24813 }
24814
24815 return $response;
24816 }
24817
24818 /**
24819 * This method is used to enrich the after upgrade notice instructions when the upgraded
24820 * license cannot be activated network wide (license quota isn't large enough).
24821 *
24822 * @author Vova Feldman (@svovaf)
24823 * @since 2.0.0
24824 *
24825 * @return string
24826 */
24827 private function get_license_network_activation_notice() {
24828 if ( ! $this->_is_network_active ) {
24829 // Module isn't network level activated.
24830 return '';
24831 }
24832
24833 if ( ! fs_is_network_admin() ) {
24834 // Not network level admin.
24835 return '';
24836 }
24837
24838 if ( get_blog_count() == 1 ) {
24839 // There's only a single site in the network so if there's a context license it was already activated.
24840 return '';
24841 }
24842
24843 if ( ! is_object( $this->_license ) ) {
24844 // No context license.
24845 return '';
24846 }
24847
24848 if ( $this->_license->is_single_site() && 0 < $this->_license->activated ) {
24849 // 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).
24850 return '';
24851 }
24852
24853 if ( $this->can_activate_license_on_network( $this->_license ) ) {
24854 // 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).
24855 return '';
24856 }
24857
24858 return sprintf(
24859 $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' ),
24860 '<a href="' . $this->get_account_url( false, array( 'activate_license' => 'true' ) ) . '">',
24861 '</a>'
24862 );
24863 }
24864
24865 /**
24866 * @author Vova Feldman (@svovaf)
24867 * @since 1.2.1.7
24868 *
24869 * @param string $key
24870 *
24871 * @return string
24872 */
24873 function get_text( $key ) {
24874 return fs_text( $key, $this->_slug );
24875 }
24876
24877 /**
24878 * @author Vova Feldman (@svovaf)
24879 * @since 1.2.3
24880 *
24881 * @param string $text Translatable string.
24882 * @param string $key String key for overrides.
24883 *
24884 * @return string
24885 */
24886 function get_text_inline( $text, $key = '' ) {
24887 return _fs_text_inline( $text, $key, $this->_slug );
24888 }
24889
24890 /**
24891 * @author Vova Feldman (@svovaf)
24892 * @since 1.2.3
24893 *
24894 * @param string $text Translatable string.
24895 * @param string $context Context information for the translators.
24896 * @param string $key String key for overrides.
24897 *
24898 * @return string
24899 */
24900 function get_text_x_inline( $text, $context, $key ) {
24901 return _fs_text_x_inline( $text, $context, $key, $this->_slug );
24902 }
24903
24904 /**
24905 * @author Vova Feldman (@svovaf)
24906 * @since 1.2.3
24907 *
24908 * @param string $text Translatable string.
24909 * @param string $key String key for overrides.
24910 *
24911 * @return string
24912 */
24913 function esc_html_inline( $text, $key ) {
24914 return esc_html( _fs_text_inline( $text, $key, $this->_slug ) );
24915 }
24916
24917 #----------------------------------------------------------------------------------
24918 #region Versioning
24919 #----------------------------------------------------------------------------------
24920
24921 /**
24922 * Check if Freemius in SDK upgrade mode.
24923 *
24924 * @author Vova Feldman (@svovaf)
24925 * @since 1.0.9
24926 *
24927 * @return bool
24928 */
24929 function is_sdk_upgrade_mode() {
24930 return isset( $this->_storage->sdk_upgrade_mode ) ?
24931 $this->_storage->sdk_upgrade_mode :
24932 false;
24933 }
24934
24935 /**
24936 * Turn SDK upgrade mode off.
24937 *
24938 * @author Vova Feldman (@svovaf)
24939 * @since 1.0.9
24940 */
24941 function set_sdk_upgrade_complete() {
24942 $this->_storage->sdk_upgrade_mode = false;
24943 }
24944
24945 /**
24946 * Check if plugin upgrade mode.
24947 *
24948 * @author Vova Feldman (@svovaf)
24949 * @since 1.0.9
24950 *
24951 * @return bool
24952 */
24953 function is_plugin_upgrade_mode() {
24954 return isset( $this->_storage->plugin_upgrade_mode ) ?
24955 $this->_storage->plugin_upgrade_mode :
24956 false;
24957 }
24958
24959 /**
24960 * Turn plugin upgrade mode off.
24961 *
24962 * @author Vova Feldman (@svovaf)
24963 * @since 1.0.9
24964 */
24965 function set_plugin_upgrade_complete() {
24966 $this->_storage->plugin_upgrade_mode = false;
24967
24968 $license_migration = ! empty( $this->_storage->license_migration ) ?
24969 $this->_storage->license_migration :
24970 array();
24971
24972 $license_migration['is_migrating'] = false;
24973
24974 $this->_storage->license_migration = $license_migration;
24975 }
24976
24977 #endregion
24978
24979 #----------------------------------------------------------------------------------
24980 #region Permissions
24981 #----------------------------------------------------------------------------------
24982
24983 /**
24984 * Check if specific permission requested.
24985 *
24986 * @author Vova Feldman (@svovaf)
24987 * @since 1.1.6
24988 *
24989 * @param string $permission
24990 *
24991 * @return bool
24992 */
24993 function is_permission_requested( $permission ) {
24994 return isset( $this->_permissions[ $permission ] ) && ( true === $this->_permissions[ $permission ] );
24995 }
24996
24997 #endregion
24998
24999 #----------------------------------------------------------------------------------
25000 #region Auto Activation
25001 #----------------------------------------------------------------------------------
25002
25003 /**
25004 * Hints the SDK if running an auto-installation.
25005 *
25006 * @var bool
25007 */
25008 private $_isAutoInstall = false;
25009
25010 /**
25011 * After upgrade callback to install and auto activate a plugin.
25012 * This code will only be executed on explicit request from the user,
25013 * following the practice Jetpack are using with their theme installations.
25014 *
25015 * @link https://make.wordpress.org/plugins/2017/03/16/clarification-of-guideline-8-executable-code-and-installs/
25016 *
25017 * @author Vova Feldman (@svovaf)
25018 * @since 1.2.1.7
25019 */
25020 function _install_premium_version_ajax_action() {
25021 $this->_logger->entrance();
25022
25023 $this->check_ajax_referer( 'install_premium_version' );
25024
25025 if ( ! $this->is_registered() ) {
25026 // Not registered.
25027 self::shoot_ajax_failure( array(
25028 'message' => $this->get_text_inline( 'Auto installation only works for opted-in users.', 'auto-install-error-not-opted-in' ),
25029 'code' => 'premium_installed',
25030 ) );
25031 }
25032
25033 $plugin_id = fs_request_get( 'target_module_id', $this->get_id() );
25034
25035 if ( ! FS_Plugin::is_valid_id( $plugin_id ) ) {
25036 // Invalid ID.
25037 self::shoot_ajax_failure( array(
25038 'message' => $this->get_text_inline( 'Invalid module ID.', 'auto-install-error-invalid-id' ),
25039 'code' => 'invalid_module_id',
25040 ) );
25041 }
25042
25043 if ( $plugin_id == $this->get_id() ) {
25044 if ( $this->is_premium() ) {
25045 // Already using the premium code version.
25046 self::shoot_ajax_failure( array(
25047 'message' => $this->get_text_inline( 'Premium version already active.', 'auto-install-error-premium-activated' ),
25048 'code' => 'premium_installed',
25049 ) );
25050 }
25051 if ( ! $this->can_use_premium_code() ) {
25052 // Don't have access to the premium code.
25053 self::shoot_ajax_failure( array(
25054 'message' => $this->get_text_inline( 'You do not have a valid license to access the premium version.', 'auto-install-error-invalid-license' ),
25055 'code' => 'invalid_license',
25056 ) );
25057 }
25058 if ( ! $this->has_release_on_freemius() ) {
25059 // Plugin is a serviceware, no premium code version.
25060 self::shoot_ajax_failure( array(
25061 'message' => $this->get_text_inline( 'Plugin is a "Serviceware" which means it does not have a premium code version.', 'auto-install-error-serviceware' ),
25062 'code' => 'premium_version_missing',
25063 ) );
25064 }
25065 } else {
25066 $addon = $this->get_addon( $plugin_id );
25067
25068 if ( ! is_object( $addon ) ) {
25069 // Invalid add-on ID.
25070 self::shoot_ajax_failure( array(
25071 'message' => $this->get_text_inline( 'Invalid module ID.', 'auto-install-error-invalid-id' ),
25072 'code' => 'invalid_module_id',
25073 ) );
25074 }
25075
25076 if ( $this->is_addon_activated( $plugin_id, true ) ) {
25077 // Premium add-on version is already activated.
25078 self::shoot_ajax_failure( array(
25079 'message' => $this->get_text_inline( 'Premium add-on version already installed.', 'auto-install-error-premium-addon-activated' ),
25080 'code' => 'premium_installed',
25081 ) );
25082 }
25083 }
25084
25085 $this->_isAutoInstall = true;
25086
25087 // Try to install and activate.
25088 $updater = FS_Plugin_Updater::instance( $this );
25089 $result = $updater->install_and_activate_plugin( $plugin_id );
25090
25091 if ( is_array( $result ) && ! empty( $result['message'] ) ) {
25092 self::shoot_ajax_failure( array(
25093 'message' => $result['message'],
25094 'code' => $result['code'],
25095 ) );
25096 }
25097
25098 self::shoot_ajax_success( $result );
25099 }
25100
25101 /**
25102 * Displays module activation dialog box after a successful upgrade
25103 * where the user explicitly requested to auto download and install
25104 * the premium version.
25105 *
25106 * @author Vova Feldman (@svovaf)
25107 * @since 1.2.1.7
25108 */
25109 function _add_auto_installation_dialog_box() {
25110 $this->_logger->entrance();
25111
25112 if ( ! $this->is_registered() ) {
25113 // Not registered.
25114 return;
25115 }
25116
25117 $plugin_id = fs_request_get( 'plugin_id', $this->get_id() );
25118
25119 if ( ! FS_Plugin::is_valid_id( $plugin_id ) ) {
25120 // Invalid module ID.
25121 return;
25122 }
25123
25124 if ( $plugin_id == $this->get_id() ) {
25125 if ( $this->is_premium() ) {
25126 // Already using the premium code version.
25127 return;
25128 }
25129 if ( ! $this->can_use_premium_code() ) {
25130 // Don't have access to the premium code.
25131 return;
25132 }
25133 if ( ! $this->has_release_on_freemius() ) {
25134 // Plugin is a serviceware, no premium code version.
25135 return;
25136 }
25137 } else {
25138 $addon = $this->get_addon( $plugin_id );
25139
25140 if ( ! is_object( $addon ) ) {
25141 // Invalid add-on ID.
25142 return;
25143 }
25144
25145 if ( $this->is_addon_activated( $plugin_id, true ) ) {
25146 // Premium add-on version is already activated.
25147 return;
25148 }
25149 }
25150
25151 $vars = array(
25152 'id' => $this->_module_id,
25153 'target_module_id' => $plugin_id,
25154 'slug' => $this->_slug,
25155 );
25156
25157 fs_require_template( 'auto-installation.php', $vars );
25158 }
25159
25160 #endregion
25161
25162 #--------------------------------------------------------------------------------
25163 #region Tabs Integration
25164 #--------------------------------------------------------------------------------
25165
25166 #region Module's Original Tabs
25167
25168 /**
25169 * Inject a JavaScript logic to capture the theme tabs HTML.
25170 *
25171 * @author Vova Feldman (@svovaf)
25172 * @since 1.2.2.7
25173 */
25174 function _tabs_capture() {
25175 $this->_logger->entrance();
25176
25177 if (
25178 ! $this->is_product_settings_page() ||
25179 ! $this->should_page_include_tabs() ||
25180 ! $this->is_matching_url( $this->main_menu_url() )
25181 ) {
25182 return;
25183 }
25184
25185 $params = array(
25186 'id' => $this->_module_id,
25187 );
25188
25189 fs_require_once_template( 'tabs-capture-js.php', $params );
25190 }
25191
25192 /**
25193 * Cache theme's tabs HTML for a week. The cache will also be set as expired
25194 * after version and type (free/premium) changes, in addition to the week period.
25195 *
25196 * @author Vova Feldman (@svovaf)
25197 * @since 1.2.2.7
25198 */
25199 function _store_tabs_ajax_action() {
25200 $this->_logger->entrance();
25201
25202 $this->check_ajax_referer( 'store_tabs' );
25203
25204 // Init filesystem if not yet initiated.
25205 WP_Filesystem();
25206
25207 // Get POST body HTML data.
25208 global $wp_filesystem;
25209 $tabs_html = $wp_filesystem->get_contents( "php://input" );
25210
25211 if ( is_string( $tabs_html ) ) {
25212 $tabs_html = trim( $tabs_html );
25213 }
25214
25215 if ( ! is_string( $tabs_html ) || empty( $tabs_html ) ) {
25216 self::shoot_ajax_failure();
25217 }
25218
25219 $this->_cache->set( 'tabs', $tabs_html, 7 * WP_FS__TIME_24_HOURS_IN_SEC );
25220
25221 self::shoot_ajax_success();
25222 }
25223
25224 /**
25225 * Cache theme's settings page custom styles. The cache will also be set as expired
25226 * after version and type (free/premium) changes, in addition to the week period.
25227 *
25228 * @author Vova Feldman (@svovaf)
25229 * @since 1.2.2.7
25230 */
25231 function _store_tabs_styles() {
25232 $this->_logger->entrance();
25233
25234 if (
25235 ! $this->is_product_settings_page() ||
25236 ! $this->should_page_include_tabs() ||
25237 ! $this->is_matching_url( $this->main_menu_url() )
25238 ) {
25239 return;
25240 }
25241
25242 $wp_styles = wp_styles();
25243
25244 $theme_styles_url = get_template_directory_uri();
25245
25246 $stylesheets = array();
25247 foreach ( $wp_styles->queue as $handler ) {
25248 if ( fs_starts_with( $handler, 'fs_' ) ) {
25249 // Assume that stylesheets that their handler starts with "fs_" belong to the SDK.
25250 continue;
25251 }
25252
25253 /**
25254 * @var _WP_Dependency $stylesheet
25255 */
25256 $stylesheet = $wp_styles->registered[ $handler ];
25257
25258 if ( fs_starts_with( $stylesheet->src, $theme_styles_url ) ) {
25259 $stylesheets[] = $stylesheet->src;
25260 }
25261 }
25262
25263 if ( ! empty( $stylesheets ) ) {
25264 $this->_cache->set( 'tabs_stylesheets', $stylesheets, 7 * WP_FS__TIME_24_HOURS_IN_SEC );
25265 }
25266 }
25267
25268 /**
25269 * Check if module's original settings page has any tabs.
25270 *
25271 * @author Vova Feldman (@svovaf)
25272 * @since 1.2.2.7
25273 *
25274 * @return bool
25275 */
25276 private function has_tabs() {
25277 return $this->_cache->has( 'tabs' );
25278 }
25279
25280 /**
25281 * Get module's settings page HTML content, starting
25282 * from the beginning of the <div class="wrap"> element,
25283 * until the tabs HTML (including).
25284 *
25285 * @author Vova Feldman (@svovaf)
25286 * @since 1.2.2.7
25287 *
25288 * @return string
25289 */
25290 private function get_tabs_html() {
25291 $this->_logger->entrance();
25292
25293 return $this->_cache->get( 'tabs' );
25294 }
25295
25296 /**
25297 * Check if page should include tabs.
25298 *
25299 * @author Vova Feldman (@svovaf)
25300 * @since 1.2.2.7
25301 *
25302 * @return bool
25303 */
25304 private function should_page_include_tabs() {
25305 if ( ! $this->has_settings_menu() ) {
25306 // Don't add tabs if no settings at all.
25307 return false;
25308 }
25309
25310 if ( self::NAVIGATION_TABS !== $this->_navigation ) {
25311 // Only add tabs to themes for now.
25312 return false;
25313 }
25314
25315 if ( $this->is_theme() && ! $this->has_paid_plan() && ! $this->has_addons() ) {
25316 // Only add tabs to monetizing themes.
25317 return false;
25318 }
25319
25320 if ( ! $this->is_product_settings_page() ) {
25321 // Only add tabs if browsing one of the product's setting pages.
25322 return false;
25323 }
25324
25325 if ( $this->is_activation_mode() && $this->is_activation_page() ) {
25326 // Don't include tabs in the activation page.
25327 return false;
25328 }
25329
25330 if ( $this->is_admin_page( 'pricing' ) && fs_request_get_bool( 'checkout' ) ) {
25331 // Don't add tabs on checkout page, we want to reduce distractions
25332 // as much as possible.
25333 return false;
25334 }
25335
25336 return true;
25337 }
25338
25339 /**
25340 * Add the tabs HTML before the setting's page content and
25341 * enqueue any required stylesheets.
25342 *
25343 * @author Vova Feldman (@svovaf)
25344 * @since 1.2.2.7
25345 *
25346 * @return bool If tabs were included.
25347 */
25348 function _add_tabs_before_content() {
25349 $this->_logger->entrance();
25350
25351 if ( ! $this->should_page_include_tabs() ) {
25352 return false;
25353 }
25354
25355 $tabs_html = $this->get_tabs_html();
25356
25357 if ( empty( $tabs_html ) ) {
25358 return false;
25359 }
25360
25361 /**
25362 * Enqueue the original stylesheets that are included in the
25363 * theme settings page. That way, if the theme settings has
25364 * some custom _styled_ content above the tabs UI, this
25365 * will make sure that the styling is preserved.
25366 */
25367 $stylesheets = $this->_cache->get( 'tabs_stylesheets', array() );
25368 if ( is_array( $stylesheets ) ) {
25369 for ( $i = 0, $len = count( $stylesheets ); $i < $len; $i ++ ) {
25370 wp_enqueue_style( "fs_{$this->_module_id}_tabs_{$i}", $stylesheets[ $i ] );
25371 }
25372 }
25373
25374 // Cut closing </div> tag.
25375 echo substr( trim( $tabs_html ), 0, - 6 );
25376
25377 return true;
25378 }
25379
25380 /**
25381 * Add the tabs closing HTML after the setting's page content.
25382 *
25383 * @author Vova Feldman (@svovaf)
25384 * @since 1.2.2.7
25385 *
25386 * @return bool If tabs closing HTML was included.
25387 */
25388 function _add_tabs_after_content() {
25389 $this->_logger->entrance();
25390
25391 if ( ! $this->should_page_include_tabs() ) {
25392 return false;
25393 }
25394
25395 echo '</div>';
25396
25397 return true;
25398 }
25399
25400 #endregion
25401
25402 /**
25403 * Add in-page JavaScript to inject the Freemius tabs into
25404 * the module's setting tabs section.
25405 *
25406 * @author Vova Feldman (@svovaf)
25407 * @since 1.2.2.7
25408 */
25409 function _add_freemius_tabs() {
25410 $this->_logger->entrance();
25411
25412 if ( ! $this->should_page_include_tabs() ) {
25413 return;
25414 }
25415
25416 $params = array( 'id' => $this->_module_id );
25417 fs_require_once_template( 'tabs.php', $params );
25418 }
25419
25420 #endregion
25421
25422 #--------------------------------------------------------------------------------
25423 #region Customizer Integration for Themes
25424 #--------------------------------------------------------------------------------
25425
25426 /**
25427 * @author Vova Feldman (@svovaf)
25428 * @since 1.2.2.7
25429 *
25430 * @param WP_Customize_Manager $customizer
25431 */
25432 function _customizer_register( $customizer ) {
25433 $this->_logger->entrance();
25434
25435 if ( $this->is_pricing_page_visible() ) {
25436 require_once WP_FS__DIR_INCLUDES . '/customizer/class-fs-customizer-upsell-control.php';
25437
25438 $customizer->add_section( 'freemius_upsell', array(
25439 'title' => '&#9733; ' . $this->get_text_inline( 'View paid features', 'view-paid-features' ),
25440 'priority' => 1,
25441 ) );
25442 $customizer->add_setting( 'freemius_upsell', array(
25443 'sanitize_callback' => 'esc_html',
25444 ) );
25445
25446 $customizer->add_control( new FS_Customizer_Upsell_Control( $customizer, 'freemius_upsell', array(
25447 'fs' => $this,
25448 'section' => 'freemius_upsell',
25449 'priority' => 100,
25450 ) ) );
25451 }
25452
25453 if ( $this->is_page_visible( 'contact' ) || $this->is_page_visible( 'support' ) ) {
25454 require_once WP_FS__DIR_INCLUDES . '/customizer/class-fs-customizer-support-section.php';
25455
25456 // Main Documentation Link In Customizer Root.
25457 $customizer->add_section( new FS_Customizer_Support_Section( $customizer, 'freemius_support', array(
25458 'fs' => $this,
25459 'priority' => 1000,
25460 ) ) );
25461 }
25462 }
25463
25464 #endregion
25465
25466 /**
25467 * If the theme has a paid version, add some custom
25468 * styling to the theme's premium version (if exists)
25469 * to highlight that it's the premium version of the
25470 * same theme, making it easier for identification
25471 * after the user upgrades and upload it to the site.
25472 *
25473 * @author Vova Feldman (@svovaf)
25474 * @since 1.2.2.7
25475 */
25476 function _style_premium_theme() {
25477 $this->_logger->entrance();
25478
25479 if ( ! self::is_themes_page() ) {
25480 // Only include in the themes page.
25481 return;
25482 }
25483
25484 if ( ! $this->has_paid_plan() ) {
25485 // Only include if has any paid plans.
25486 return;
25487 }
25488
25489 $params = null;
25490 fs_require_once_template( '/js/jquery.content-change.php', $params );
25491
25492 $params = array(
25493 'slug' => $this->_slug,
25494 'id' => $this->_module_id,
25495 );
25496
25497 fs_require_template( '/js/style-premium-theme.php', $params );
25498 }
25499
25500 /**
25501 * This method will return the absolute URL of the module's local icon.
25502 *
25503 * When you are running your plugin or theme on a **localhost** environment, if the icon
25504 * is not found in the local assets folder, try to fetch the icon URL from Freemius. If not set and
25505 * it's a plugin hosted on WordPress.org, try fetching the icon URL from wordpress.org.
25506 * If an icon is found, this method will automatically attempt to download the icon and store it
25507 * in /freemius/assets/img/{slug}.{png|jpg|gif|svg}.
25508 *
25509 * It's important to mention that this method is NOT phoning home since the developer will deploy
25510 * the product with the local icon in the assets folder. The download process just simplifies
25511 * the process for the developer.
25512 *
25513 * @author Vova Feldman (@svovaf)
25514 * @since 2.0.0
25515 *
25516 * @return string
25517 */
25518 function get_local_icon_url() {
25519 global $fs_active_plugins;
25520
25521 /**
25522 * @since 1.1.7.5
25523 */
25524 $local_path = $this->apply_filters( 'plugin_icon', false );
25525
25526 if ( is_string( $local_path ) ) {
25527 $icons = array( $local_path );
25528 } else {
25529 $img_dir = WP_FS__DIR_IMG;
25530
25531 // Locate the main assets folder.
25532 if ( ! empty( $fs_active_plugins->plugins ) ) {
25533 $plugin_or_theme_img_dir = ( $this->is_plugin() ? WP_PLUGIN_DIR : get_theme_root( get_stylesheet() ) );
25534
25535 foreach ( $fs_active_plugins->plugins as $sdk_path => &$data ) {
25536 if ( $data->plugin_path == $this->get_plugin_basename() ) {
25537 $img_dir = $plugin_or_theme_img_dir
25538 . '/'
25539 /**
25540 * The basename will be `themes` or the basename of a custom themes directory.
25541 *
25542 * @author Leo Fajardo (@leorw)
25543 * @since 2.2.3
25544 */
25545 . str_replace( '../' . basename( $plugin_or_theme_img_dir ) . '/', '', $sdk_path )
25546 . '/assets/img';
25547
25548 break;
25549 }
25550 }
25551 }
25552
25553 // Try to locate the icon in the assets folder.
25554 $icons = glob( fs_normalize_path( $img_dir . "/{$this->_slug}.*" ) );
25555
25556 if ( ! is_array( $icons ) || 0 === count( $icons ) ) {
25557 if ( ! WP_FS__IS_LOCALHOST && $this->is_theme() ) {
25558 $icons = array(
25559 fs_normalize_path( $img_dir . '/theme-icon.png' )
25560 );
25561 } else {
25562 $icon_found = false;
25563 $local_path = fs_normalize_path( "{$img_dir}/{$this->_slug}.png" );
25564
25565 if ( ! function_exists( 'get_filesystem_method' ) ) {
25566 require_once ABSPATH . 'wp-admin/includes/file.php';
25567 }
25568
25569 $have_write_permissions = ( 'direct' === get_filesystem_method( array(), fs_normalize_path( $img_dir ) ) );
25570
25571 /**
25572 * IMPORTANT: THIS CODE WILL NEVER RUN AFTER THE PLUGIN IS IN THE REPO.
25573 *
25574 * This code will only be executed once during the testing
25575 * of the plugin in a local environment. The plugin icon file WILL
25576 * already exist in the assets folder when the plugin is deployed to
25577 * the repository.
25578 */
25579 if ( WP_FS__IS_LOCALHOST && $have_write_permissions ) {
25580 // Fetch icon from Freemius.
25581 $icon = $this->fetch_remote_icon_url();
25582
25583 // Fetch icon from WordPress.org.
25584 if ( empty( $icon ) && $this->is_plugin() && $this->is_org_repo_compliant() ) {
25585 if ( ! function_exists( 'plugins_api' ) ) {
25586 require_once ABSPATH . 'wp-admin/includes/plugin-install.php';
25587 }
25588
25589 $plugin_information = plugins_api( 'plugin_information', array(
25590 'slug' => $this->_slug,
25591 'fields' => array(
25592 'sections' => false,
25593 'tags' => false,
25594 'icons' => true
25595 )
25596 ) );
25597
25598 if (
25599 ! is_wp_error( $plugin_information )
25600 && isset( $plugin_information->icons )
25601 && ! empty( $plugin_information->icons )
25602 ) {
25603 /**
25604 * Get the smallest icon.
25605 *
25606 * @author Leo Fajardo (@leorw)
25607 * @since 1.2.2
25608 */
25609 $icon = end( $plugin_information->icons );
25610 }
25611 }
25612
25613 if ( ! empty( $icon ) ) {
25614 if ( 0 !== strpos( $icon, 'http' ) ) {
25615 $icon = 'http:' . $icon;
25616 }
25617
25618 /**
25619 * Get a clean file extension, e.g.: "jpg" and not "jpg?rev=1305765".
25620 *
25621 * @author Leo Fajardo (@leorw)
25622 * @since 1.2.2
25623 */
25624 $ext = pathinfo( strtok( $icon, '?' ), PATHINFO_EXTENSION );
25625
25626 $local_path = fs_normalize_path( "{$img_dir}/{$this->_slug}.{$ext}" );
25627
25628 // Try to download the icon.
25629 $icon_found = fs_download_image( $icon, $local_path );
25630 }
25631 }
25632
25633 if ( ! $icon_found ) {
25634 // No icons found, fallback to default icon.
25635 if ( $have_write_permissions ) {
25636 // If have write permissions, copy default icon.
25637 copy( fs_normalize_path( $img_dir . "/{$this->_module_type}-icon.png" ), $local_path );
25638 } else {
25639 // If doesn't have write permissions, use default icon path.
25640 $local_path = fs_normalize_path( $img_dir . "/{$this->_module_type}-icon.png" );
25641 }
25642 }
25643
25644 $icons = array( $local_path );
25645 }
25646 }
25647 }
25648
25649 $icon_dir = dirname( $icons[0] );
25650
25651 return fs_img_url( substr( $icons[0], strlen( $icon_dir ) ), $icon_dir );
25652 }
25653
25654 /**
25655 * Fetch module's extended info.
25656 *
25657 * @author Vova Feldman (@svovaf)
25658 * @since 2.0.0
25659 *
25660 * @return object|mixed
25661 */
25662 private function fetch_module_info() {
25663 return $this->get_api_plugin_scope()->get( 'info.json', false, WP_FS__TIME_WEEK_IN_SEC );
25664 }
25665
25666 /**
25667 * Fetch module's remote icon URL.
25668 *
25669 * @author Vova Feldman (@svovaf)
25670 * @since 2.0.0
25671 *
25672 * @return string
25673 */
25674 function fetch_remote_icon_url() {
25675 $info = $this->fetch_module_info();
25676
25677 return ( $this->is_api_result_object( $info, 'icon' ) && is_string( $info->icon ) ) ?
25678 $info->icon :
25679 '';
25680 }
25681
25682 #--------------------------------------------------------------------------------
25683 #region GDPR
25684 #--------------------------------------------------------------------------------
25685
25686 /**
25687 * @author Leo Fajardo (@leorw)
25688 * @since 2.1.0
25689 *
25690 * @param array $user_plugins
25691 *
25692 * @return string
25693 */
25694 private function get_gdpr_admin_notice_string( $user_plugins ) {
25695 $this->_logger->entrance();
25696
25697 $addons = self::get_all_addons();
25698
25699 foreach ( $user_plugins as $user_plugin ) {
25700 $has_addons = isset( $addons[ $user_plugin->id ] );
25701
25702 if ( WP_FS__MODULE_TYPE_PLUGIN === $user_plugin->type && ! $has_addons ) {
25703 if ( $this->_module_id == $user_plugin->id ) {
25704 $addons = $this->get_addons();
25705 $has_addons = ( ! empty( $addons ) );
25706 } else {
25707 $plugin_api = FS_Api::instance(
25708 $user_plugin->id,
25709 'plugin',
25710 $user_plugin->id,
25711 $user_plugin->public_key,
25712 ! $user_plugin->is_live,
25713 false,
25714 $this->get_sdk_version()
25715 );
25716
25717 $addons_result = $plugin_api->get( '/addons.json?enriched=true', true );
25718
25719 if ( $this->is_api_result_object( $addons_result, 'plugins' ) &&
25720 is_array( $addons_result->plugins ) &&
25721 ! empty( $addons_result->plugins )
25722 ) {
25723 $has_addons = true;
25724 }
25725 }
25726 }
25727
25728 $user_plugin->has_addons = $has_addons;
25729 }
25730
25731 $is_single_parent_product = ( 1 === count( $user_plugins ) );
25732
25733 $multiple_products_text = '';
25734
25735 if ( $is_single_parent_product ) {
25736 $single_parent_product = reset( $user_plugins );
25737
25738 $thank_you = sprintf(
25739 "<span data-plugin-id='%d'>%s</span>",
25740 $single_parent_product->id,
25741 sprintf(
25742 $single_parent_product->has_addons ?
25743 $this->get_text_inline( 'Thank you so much for using %s and its add-ons!', 'thank-you-for-using-product-and-its-addons' ) :
25744 $this->get_text_inline( 'Thank you so much for using %s!', 'thank-you-for-using-product' ),
25745 sprintf('<b><i>%s</i></b>', $single_parent_product->title)
25746 )
25747 );
25748
25749 $already_opted_in = sprintf(
25750 $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' ),
25751 ( WP_FS__MODULE_TYPE_THEME === $single_parent_product->type ) ? WP_FS__MODULE_TYPE_THEME : WP_FS__MODULE_TYPE_PLUGIN
25752 );
25753 } else {
25754 $thank_you = $this->get_text_inline( 'Thank you so much for using our products!', 'thank-you-for-using-products' );
25755 $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' );
25756
25757 $products_and_add_ons = '';
25758 foreach ( $user_plugins as $user_plugin ) {
25759 if ( ! empty( $products_and_add_ons ) ) {
25760 $products_and_add_ons .= ', ';
25761 }
25762
25763 if ( ! $user_plugin->has_addons ) {
25764 $products_and_add_ons .= sprintf(
25765 "<span data-plugin-id='%d'>%s</span>",
25766 $user_plugin->id,
25767 $user_plugin->title
25768 );
25769 } else {
25770 $products_and_add_ons .= sprintf(
25771 "<span data-plugin-id='%d'>%s</span>",
25772 $user_plugin->id,
25773 sprintf(
25774 $this->get_text_inline( '%s and its add-ons', 'product-and-its-addons' ),
25775 $user_plugin->title
25776 )
25777 );
25778 }
25779 }
25780
25781 $multiple_products_text = sprintf(
25782 "<small class='products'><strong>%s:</strong> %s</small>",
25783 $this->get_text_inline( 'Products', 'products' ),
25784 $products_and_add_ons
25785 );
25786 }
25787
25788 $actions = sprintf(
25789 '<ul><li>%s<span class="action-description"> - %s</span></li><li>%s<span class="action-description"> - %s</span></li></ul>',
25790 sprintf('<button class="button button-primary allow-marketing">%s</button>', $this->get_text_inline( 'Yes', 'yes' ) ),
25791 $this->get_text_inline( 'send me security & feature updates, educational content and offers.', 'send-updates' ),
25792 sprintf('<button class="button button-secondary">%s</button>', $this->get_text_inline( 'No', 'no' ) ),
25793 sprintf(
25794 $this->get_text_inline( 'do %sNOT%s send me security & feature updates, educational content and offers.', 'do-not-send-updates' ),
25795 '<span class="underlined">',
25796 '</span>'
25797 )
25798 );
25799
25800 return sprintf(
25801 '%s %s %s',
25802 $thank_you,
25803 $already_opted_in,
25804 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://ec.europa.eu/info/law/law-topic/data-protection_en/" target="_blank" rel="noopener noreferrer">', '</a>' ) .
25805 '<br><br>' .
25806 '<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>' .
25807 $actions .
25808 ( $is_single_parent_product ? '' : $multiple_products_text )
25809 );
25810 }
25811
25812 /**
25813 * This method is called for opted-in users to fetch the is_marketing_allowed flag of the user for all the
25814 * plugins and themes they've opted in to.
25815 *
25816 * @author Leo Fajardo (@leorw)
25817 * @since 2.1.0
25818 *
25819 * @param string $user_email
25820 * @param string $license_key
25821 * @param array $plugin_ids
25822 * @param string|null $license_key
25823 *
25824 * @return array|false
25825 */
25826 private function fetch_user_marketing_flag_status_by_plugins( $user_email, $license_key, $plugin_ids ) {
25827 $request = array(
25828 'method' => 'POST',
25829 'body' => array(),
25830 'timeout' => WP_FS__DEBUG_SDK ? 60 : 30,
25831 );
25832
25833 if ( is_string( $user_email ) ) {
25834 $request['body']['email'] = $user_email;
25835 } else {
25836 $request['body']['license_key'] = $license_key;
25837 }
25838
25839 $result = array();
25840
25841 $url = WP_FS__ADDRESS . '/action/service/user_plugin/';
25842 $total_plugin_ids = count( $plugin_ids );
25843
25844 $plugin_ids_count_per_request = 10;
25845 for ( $i = 1; $i <= $total_plugin_ids; $i += $plugin_ids_count_per_request ) {
25846 $plugin_ids_set = array_slice( $plugin_ids, $i - 1, $plugin_ids_count_per_request );
25847
25848 $request['body']['plugin_ids'] = $plugin_ids_set;
25849
25850 $response = self::safe_remote_post(
25851 $url,
25852 $request,
25853 WP_FS__TIME_24_HOURS_IN_SEC,
25854 WP_FS__TIME_12_HOURS_IN_SEC
25855 );
25856
25857 if ( ! is_wp_error( $response ) ) {
25858 $decoded = is_string( $response['body'] ) ?
25859 json_decode( $response['body'] ) :
25860 null;
25861
25862 if (
25863 !is_object($decoded) ||
25864 !isset($decoded->success) ||
25865 true !== $decoded->success ||
25866 !isset( $decoded->data ) ||
25867 !is_array( $decoded->data )
25868 ) {
25869 return false;
25870 }
25871
25872 $result = array_merge( $result, $decoded->data );
25873 }
25874 }
25875
25876 return $result;
25877 }
25878
25879 /**
25880 * @author Leo Fajardo (@leorw)
25881 * @since 2.1.0
25882 */
25883 function _maybe_show_gdpr_admin_notice() {
25884 if ( ! $this->is_user_in_admin() ) {
25885 return;
25886 }
25887
25888 if ( ! $this->should_handle_gdpr_admin_notice() ) {
25889 return;
25890 }
25891
25892 if ( ! $this->is_user_admin() ) {
25893 return;
25894 }
25895
25896 require_once WP_FS__DIR_INCLUDES . '/class-fs-user-lock.php';
25897
25898 $lock = FS_User_Lock::instance();
25899
25900 /**
25901 * Try to acquire a 60-sec lock based on the WP user and thread/process ID.
25902 */
25903 if ( ! $lock->try_lock( 60 ) ) {
25904 return;
25905 }
25906
25907 /**
25908 * @var $current_wp_user WP_User
25909 */
25910 $current_wp_user = self::_get_current_wp_user();
25911
25912 /**
25913 * @var FS_User $current_fs_user
25914 */
25915 $current_fs_user = Freemius::_get_user_by_email( $current_wp_user->user_email );
25916
25917 $ten_years_in_sec = 10 * 365 * WP_FS__TIME_24_HOURS_IN_SEC;
25918
25919 if ( ! is_object( $current_fs_user ) ) {
25920 // 10-year lock.
25921 $lock->lock( $ten_years_in_sec );
25922
25923 return;
25924 }
25925
25926 $gdpr = FS_GDPR_Manager::instance();
25927
25928 if ( $gdpr->is_opt_in_notice_shown() ) {
25929 // 30-day lock.
25930 $lock->lock( 30 * WP_FS__TIME_24_HOURS_IN_SEC );
25931
25932 return;
25933 }
25934
25935 if ( ! $gdpr->should_show_opt_in_notice() ) {
25936 // 10-year lock.
25937 $lock->lock( $ten_years_in_sec );
25938
25939 return;
25940 }
25941
25942 $last_time_notice_shown = $gdpr->last_time_notice_was_shown();
25943 $was_notice_shown_before = ( false !== $last_time_notice_shown );
25944
25945 if ( $was_notice_shown_before &&
25946 30 * WP_FS__TIME_24_HOURS_IN_SEC > time() - $last_time_notice_shown
25947 ) {
25948 // If the notice was shown before, show it again after 30 days from the last time it was shown.
25949 return;
25950 }
25951
25952 /**
25953 * Find all plugin IDs that were installed by the current admin.
25954 */
25955 $plugin_ids_map = self::get_user_opted_in_module_ids_map( $current_fs_user->id );
25956
25957 if ( empty( $plugin_ids_map )) {
25958 $lock->lock( $ten_years_in_sec );
25959
25960 return;
25961 }
25962
25963 $user_plugins = $this->fetch_user_marketing_flag_status_by_plugins(
25964 $current_fs_user->email,
25965 null,
25966 array_keys( $plugin_ids_map )
25967 );
25968
25969 if ( empty( $user_plugins ) ) {
25970 $lock->lock(
25971 is_array($user_plugins) ?
25972 $ten_years_in_sec :
25973 // Lock for 24-hours on errors.
25974 WP_FS__TIME_24_HOURS_IN_SEC
25975 );
25976
25977 return;
25978 }
25979
25980 $has_unset_marketing_optin = false;
25981
25982 foreach ( $user_plugins as $user_plugin ) {
25983 if ( true == $user_plugin->is_marketing_allowed ) {
25984 unset( $plugin_ids_map[ $user_plugin->plugin_id ] );
25985 }
25986
25987 if ( ! $has_unset_marketing_optin && is_null( $user_plugin->is_marketing_allowed ) ) {
25988 $has_unset_marketing_optin = true;
25989 }
25990 }
25991
25992 if ( empty( $plugin_ids_map ) ||
25993 ( $was_notice_shown_before && ! $has_unset_marketing_optin )
25994 ) {
25995 $lock->lock( $ten_years_in_sec );
25996
25997 return;
25998 }
25999
26000 $modules = array_merge(
26001 array_values( self::maybe_get_entities_account_option( 'plugins', array() ) ),
26002 array_values( self::maybe_get_entities_account_option( 'themes', array() ) )
26003 );
26004
26005 foreach ( $modules as $module ) {
26006 if ( ! FS_Plugin::is_valid_id( $module->parent_plugin_id ) && isset( $plugin_ids_map[ $module->id ] ) ) {
26007 $plugin_ids_map[ $module->id ] = $module;
26008 }
26009 }
26010
26011 $plugin_title = null;
26012 if ( 1 === count( $plugin_ids_map ) ) {
26013 $module = reset( $plugin_ids_map );
26014 $plugin_title = $module->title;
26015 }
26016
26017 $gdpr->add_opt_in_sticky_notice(
26018 $this->get_gdpr_admin_notice_string( $plugin_ids_map ),
26019 $plugin_title
26020 );
26021
26022 $this->add_gdpr_optin_ajax_handler_and_style();
26023
26024 $gdpr->notice_was_just_shown();
26025
26026 // 30-day lock.
26027 $lock->lock( 30 * WP_FS__TIME_24_HOURS_IN_SEC );
26028 }
26029
26030 /**
26031 * Prevents the GDPR opt-in admin notice from being added if the user has already chosen to allow or not allow
26032 * marketing.
26033 *
26034 * @author Leo Fajardo (@leorw)
26035 * @since 2.1.0
26036 */
26037 private function disable_opt_in_notice_and_lock_user() {
26038 FS_GDPR_Manager::instance()->disable_opt_in_notice();
26039
26040 require_once WP_FS__DIR_INCLUDES . '/class-fs-user-lock.php';
26041
26042 // 10-year lock.
26043 FS_User_Lock::instance()->lock( 10 * 365 * WP_FS__TIME_24_HOURS_IN_SEC );
26044 }
26045
26046 /**
26047 * @author Leo Fajardo (@leorw)
26048 * @since 2.5.4
26049 */
26050 static function _add_api_connectivity_notice_handler_js() {
26051 fs_require_once_template( 'api-connectivity-message-js.php' );
26052 }
26053
26054 /**
26055 * @author Leo Fajardo (@leorw)
26056 * @since 2.1.0
26057 */
26058 function _add_gdpr_optin_js() {
26059 $vars = array( 'id' => $this->_module_id );
26060
26061 fs_require_once_template( 'gdpr-optin-js.php', $vars );
26062 }
26063
26064 /**
26065 * @author Leo Fajardo (@leorw)
26066 * @since 2.1.0
26067 */
26068 function enqueue_gdpr_optin_notice_style() {
26069 fs_enqueue_local_style( 'fs_gdpr_optin_notice', '/admin/gdpr-optin-notice.css' );
26070 }
26071
26072 /**
26073 * @author Leo Fajardo (@leorw)
26074 * @since 2.1.0
26075 */
26076 function _maybe_add_gdpr_optin_ajax_handler() {
26077 $this->add_ajax_action( 'fetch_is_marketing_required_flag_value', array( &$this, '_fetch_is_marketing_required_flag_value_ajax_action' ) );
26078
26079 if ( FS_GDPR_Manager::instance()->is_opt_in_notice_shown() ) {
26080 $this->add_gdpr_optin_ajax_handler_and_style();
26081 }
26082 }
26083
26084 /**
26085 * @author Leo Fajardo (@leorw)
26086 * @since 2.1.0
26087 */
26088 function _fetch_is_marketing_required_flag_value_ajax_action() {
26089 $this->_logger->entrance();
26090
26091 $this->check_ajax_referer( 'fetch_is_marketing_required_flag_value' );
26092
26093 $license_key = fs_request_get_raw( 'license_key' );
26094
26095 if ( empty($license_key) ) {
26096 self::shoot_ajax_failure( $this->get_text_inline( 'License key is empty.', 'empty-license-key' ) );
26097 }
26098
26099 $user_plugins = $this->fetch_user_marketing_flag_status_by_plugins(
26100 null,
26101 $license_key,
26102 array( $this->_module_id )
26103 );
26104
26105 if ( ! is_array( $user_plugins ) ||
26106 empty($user_plugins) ||
26107 !isset($user_plugins[0]->plugin_id) ||
26108 $user_plugins[0]->plugin_id != $this->_module_id
26109 ) {
26110 /**
26111 * If faced an error or if the module ID do not match to the current module, ask for GDPR opt-in.
26112 *
26113 * @author Vova Feldman (@svovaf)
26114 */
26115 self::shoot_ajax_success( array(
26116 'is_marketing_allowed' => null,
26117 'license_owner_id' => null
26118 ) );
26119 }
26120
26121 self::shoot_ajax_success( array(
26122 'is_marketing_allowed' => $user_plugins[0]->is_marketing_allowed,
26123 'license_owner_id' => ( isset( $user_plugins[0]->license_owner_id ) ? $user_plugins[0]->license_owner_id : null )
26124 ) );
26125 }
26126
26127 /**
26128 * @author Leo Fajardo (@leorw)
26129 * @since 2.3.2
26130 *
26131 * @param number[] $install_ids
26132 *
26133 * @return array {
26134 * An array of objects containing the installs' licenses owners data.
26135 *
26136 * @property number $id User ID.
26137 * @property string $email User email (can be masked email).
26138 * }
26139 */
26140 private function fetch_installs_licenses_owners_data( $install_ids ) {
26141 $this->_logger->entrance();
26142
26143 $response = $this->get_api_user_scope()->get(
26144 '/licenses_owners.json?install_ids=' . implode( ',', $install_ids )
26145 );
26146
26147 $license_owners = array();
26148
26149 if ( $this->is_api_result_object( $response, 'owners' ) ) {
26150 $license_owners = $response->owners;
26151 }
26152
26153 return $license_owners;
26154 }
26155
26156 /**
26157 * @author Leo Fajardo (@leorw)
26158 * @since 2.1.0
26159 */
26160 private function add_gdpr_optin_ajax_handler_and_style() {
26161 // Add GDPR action AJAX callback.
26162 $this->add_ajax_action( 'gdpr_optin_action', array( &$this, '_gdpr_optin_ajax_action' ) );
26163
26164 add_action( 'admin_footer', array( &$this, '_add_gdpr_optin_js' ) );
26165 add_action( 'admin_enqueue_scripts', array( &$this, 'enqueue_gdpr_optin_notice_style' ) );
26166 }
26167
26168 /**
26169 * @author Leo Fajardo (@leorw)
26170 * @since 2.1.0
26171 */
26172 function _gdpr_optin_ajax_action() {
26173 $this->_logger->entrance();
26174
26175 $this->check_ajax_referer( 'gdpr_optin_action' );
26176
26177 if ( ! fs_request_has( 'is_marketing_allowed' ) || ! fs_request_has( 'plugin_ids' ) ) {
26178 self::shoot_ajax_failure();
26179 }
26180
26181 $current_wp_user = self::_get_current_wp_user();
26182
26183 $plugin_ids = fs_request_get( 'plugin_ids', array() );
26184 if ( ! is_array( $plugin_ids ) || empty( $plugin_ids ) ) {
26185 self::shoot_ajax_failure();
26186 }
26187
26188 $modules = array_merge(
26189 array_values( self::maybe_get_entities_account_option( 'plugins', array() ) ),
26190 array_values( self::maybe_get_entities_account_option( 'themes', array() ) )
26191 );
26192
26193 foreach ( $modules as $key => $module ) {
26194 if ( ! in_array( $module->id, $plugin_ids ) ) {
26195 unset( $modules[ $key ] );
26196 }
26197 }
26198
26199 if ( empty( $modules ) ) {
26200 self::shoot_ajax_failure();
26201 }
26202
26203 $user_api = $this->get_api_user_scope_by_user( Freemius::_get_user_by_email( $current_wp_user->user_email ) );
26204
26205 foreach ( $modules as $module ) {
26206 $user_api->call( "?plugin_id={$module->id}", 'put', array(
26207 'is_marketing_allowed' => ( true == fs_request_get_bool( 'is_marketing_allowed' ) )
26208 ) );
26209 }
26210
26211 FS_GDPR_Manager::instance()->remove_opt_in_notice();
26212
26213 require_once WP_FS__DIR_INCLUDES . '/class-fs-user-lock.php';
26214
26215 // 10-year lock.
26216 FS_User_Lock::instance()->lock( 10 * 365 * WP_FS__TIME_24_HOURS_IN_SEC );
26217
26218 self::shoot_ajax_success();
26219 }
26220
26221 /**
26222 * 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.
26223 *
26224 * @author Vova Feldman (@svovaf)
26225 * @since 2.1.0
26226 *
26227 * @return bool
26228 */
26229 private function should_handle_gdpr_admin_notice() {
26230 return $this->apply_filters(
26231 'handle_gdpr_admin_notice',
26232 // Default to false.
26233 false
26234 );
26235 }
26236
26237 #endregion
26238
26239 #----------------------------------------------------------------------------------
26240 #region Marketing
26241 #----------------------------------------------------------------------------------
26242
26243 /**
26244 * Check if current user purchased any other plugins before.
26245 *
26246 * @author Vova Feldman (@svovaf)
26247 * @since 1.0.9
26248 *
26249 * @return bool
26250 */
26251 function has_purchased_before() {
26252 // TODO: Implement has_purchased_before() method.
26253 throw new Exception( 'not implemented' );
26254 }
26255
26256 /**
26257 * Check if current user classified as an agency.
26258 *
26259 * @author Vova Feldman (@svovaf)
26260 * @since 1.0.9
26261 *
26262 * @return bool
26263 */
26264 function is_agency() {
26265 // TODO: Implement is_agency() method.
26266 throw new Exception( 'not implemented' );
26267 }
26268
26269 /**
26270 * Check if current user classified as a developer.
26271 *
26272 * @author Vova Feldman (@svovaf)
26273 * @since 1.0.9
26274 *
26275 * @return bool
26276 */
26277 function is_developer() {
26278 // TODO: Implement is_developer() method.
26279 throw new Exception( 'not implemented' );
26280 }
26281
26282 /**
26283 * Check if current user classified as a business.
26284 *
26285 * @author Vova Feldman (@svovaf)
26286 * @since 1.0.9
26287 *
26288 * @return bool
26289 */
26290 function is_business() {
26291 // TODO: Implement is_business() method.
26292 throw new Exception( 'not implemented' );
26293 }
26294
26295 #endregion
26296
26297 #----------------------------------------------------------------------------------
26298 #region Helper
26299 #----------------------------------------------------------------------------------
26300
26301 /**
26302 * If running with a secret key, assume it's the developer and show pending plans as well.
26303 *
26304 * @author Vova Feldman (@svovaf)
26305 * @since 2.1.2
26306 *
26307 * @param string $path
26308 *
26309 * @return string
26310 */
26311 function add_show_pending( $path ) {
26312 if ( ! $this->has_secret_key() ) {
26313 return $path;
26314 }
26315
26316 return $path . ( false !== strpos( $path, '?' ) ? '&' : '?' ) . 'show_pending=true';
26317 }
26318
26319 #endregion
26320 }
26321