PluginProbe
TablePress – Tables in WordPress made easy / 2.4.3
TablePress – Tables in WordPress made easy v2.4.3
3.3.4 3.3.3 3.3.2 3.3.1 trunk 1.12 1.14 1.9.2 2.0.4 2.1.7 2.1.8 2.2 2.2.1 2.2.2 2.2.3 2.2.4 2.2.5 2.3 2.3.1 2.3.2 2.4 2.4.1 2.4.2 2.4.3 2.4.4 All 44 releases
tablepress / libraries / freemius / includes / class-freemius.php

class-freemius.php in TablePress – Tables in WordPress made easy 2.4.3, at libraries/freemius/includes/class-freemius.php

26,120 lines 732.7 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2 /**
3 * @package Freemius
4 * @copyright Copyright (c) 2015, Freemius, Inc.
5 * @license https://www.gnu.org/licenses/gpl-3.0.html GNU General Public License Version 3
6 * @since 1.0.3
7 */
8 if ( ! defined( 'ABSPATH' ) ) {
9 exit;
10 }
11
12 // "final class"
13 class Freemius extends Freemius_Abstract {
14 /**
15 * SDK Version
16 *
17 * @var string
18 */
19 public $version = WP_FS__SDK_VERSION;
20
21 #region Plugin Info
22
23 /**
24 * @since 1.0.1
25 *
26 * @var string
27 */
28 private $_slug;
29
30 /**
31 * @since 1.0.0
32 *
33 * @var string
34 */
35 private $_plugin_basename;
36 /**
37 * @since 2.2.1
38 *
39 * @var string
40 */
41 private $_premium_plugin_basename;
42 /**
43 * @since 1.0.0
44 *
45 * @var string
46 */
47 private $_free_plugin_basename;
48 /**
49 * @since 1.0.0
50 *
51 * @var string
52 */
53 private $_plugin_dir_path;
54 /**
55 * @since 1.0.0
56 *
57 * @var string
58 */
59 private $_plugin_dir_name;
60 /**
61 * @since 1.0.0
62 *
63 * @var string
64 */
65 private $_plugin_main_file_path;
66 /**
67 * @var string[]
68 */
69 private $_plugin_data;
70 /**
71 * @since 1.0.9
72 *
73 * @var string
74 */
75 private $_plugin_name;
76 /**
77 * @since 1.2.2
78 *
79 * @var string
80 */
81 private $_module_type;
82
83 #endregion Plugin Info
84
85 /**
86 * @since 1.0.9
87 *
88 * @var bool If false, don't turn Freemius on.
89 */
90 private $_is_on;
91
92 /**
93 * @since 1.1.3
94 *
95 * @var bool If false, don't turn Freemius on.
96 */
97 private $_is_anonymous;
98
99 /**
100 * @since 1.0.9
101 * @var bool If false, issues with connectivity to Freemius API.
102 */
103 private $_has_api_connection;
104
105 /**
106 * @since 1.0.9
107 * @since 2.0.0 Default to true since we need the property during the instance construction, prior to the dynamic_init() execution.
108 * @var bool Hints the SDK if plugin can support anonymous mode (if skip connect is visible).
109 */
110 private $_enable_anonymous = true;
111
112 /**
113 * @since 1.1.7.5
114 * @var bool Hints the SDK if plugin should run in anonymous mode (only adds feedback form).
115 */
116 private $_anonymous_mode;
117
118 /**
119 * @since 1.1.9
120 * @var bool Hints the SDK if plugin have any free plans.
121 */
122 private $_is_premium_only;
123
124 /**
125 * @since 1.2.1.6
126 * @var bool Hints the SDK if plugin have premium code version at all.
127 */
128 private $_has_premium_version;
129
130 /**
131 * @since 1.2.1.6
132 * @var bool Hints the SDK if plugin should ignore pending mode by simulating a skip.
133 */
134 private $_ignore_pending_mode;
135
136 /**
137 * @since 1.0.8
138 * @var bool Hints the SDK if the plugin has any paid plans.
139 */
140 private $_has_paid_plans;
141
142 /**
143 * @since 1.2.1.5
144 * @var int Hints the SDK if the plugin offers a trial period. If negative, no trial, if zero - has a trial but
145 * without a specified period, if positive - the number of trial days.
146 */
147 private $_trial_days = - 1;
148
149 /**
150 * @since 1.2.1.5
151 * @var bool Hints the SDK if the trial requires a payment method or not.
152 */
153 private $_is_trial_require_payment = false;
154
155 /**
156 * @since 1.0.7
157 * @var bool Hints the SDK if the plugin is WordPress.org compliant.
158 */
159 private $_is_org_compliant;
160
161 /**
162 * @since 1.0.7
163 * @var bool Hints the SDK if the plugin is has add-ons.
164 */
165 private $_has_addons;
166
167 /**
168 * @since 2.4.5
169 * @var string Navigation type: 'menu' or 'tabs'.
170 */
171 private $_navigation;
172
173 const NAVIGATION_MENU = 'menu';
174 const NAVIGATION_TABS = 'tabs';
175
176 /**
177 * @since 1.1.6
178 * @var string[]bool.
179 */
180 private $_permissions;
181
182 /**
183 * @var FS_Storage
184 */
185 private $_storage;
186
187 /**
188 * @since 1.2.2.7
189 * @var FS_Cache_Manager
190 */
191 private $_cache;
192
193 /**
194 * @since 1.0.0
195 *
196 * @var FS_Logger
197 */
198 private $_logger;
199 /**
200 * @since 1.0.4
201 *
202 * @var FS_Plugin
203 */
204 private $_plugin = false;
205 /**
206 * @since 1.0.4
207 *
208 * @var FS_Plugin|false
209 */
210 private $_parent_plugin = false;
211 /**
212 * @since 1.1.1
213 *
214 * @var Freemius
215 */
216 private $_parent = false;
217 /**
218 * @since 1.0.1
219 *
220 * @var FS_User
221 */
222 private $_user = false;
223 /**
224 * @since 1.0.1
225 *
226 * @var FS_Site
227 */
228 private $_site = false;
229 /**
230 * @since 1.0.1
231 *
232 * @var FS_Plugin_License
233 */
234 private $_license;
235 /**
236 * @since 1.0.2
237 *
238 * @var FS_Plugin_Plan[]
239 */
240 private $_plans = false;
241 /**
242 * @var FS_Plugin_License[]
243 * @since 1.0.5
244 */
245 private $_licenses = false;
246
247 /**
248 * @since 1.0.1
249 *
250 * @var FS_Admin_Menu_Manager
251 */
252 private $_menu;
253
254 /**
255 * @var FS_Admin_Notices
256 */
257 private $_admin_notices;
258
259 /**
260 * @since 1.1.6
261 *
262 * @var FS_Admin_Notices
263 */
264 private static $_global_admin_notices;
265
266 /**
267 * @var FS_Logger
268 * @since 1.0.0
269 */
270 private static $_static_logger;
271
272 /**
273 * @var FS_Options
274 * @since 1.0.2
275 */
276 private static $_accounts;
277
278 /**
279 * @since 1.2.2
280 *
281 * @var number
282 */
283 private $_module_id;
284
285 /**
286 * @var Freemius[]
287 */
288 private static $_instances = array();
289
290 /**
291 * @since 1.2.3
292 *
293 * @var FS_Affiliate
294 */
295 private $affiliate = null;
296
297 /**
298 * @since 1.2.3
299 *
300 * @var FS_AffiliateTerms
301 */
302 private $plugin_affiliate_terms = null;
303
304 /**
305 * @since 1.2.3
306 *
307 * @var FS_AffiliateTerms
308 */
309 private $custom_affiliate_terms = null;
310
311 /**
312 * @since 2.0.0
313 *
314 * @var bool
315 */
316 private $_is_multisite_integrated;
317
318 /**
319 * @since 2.0.0
320 *
321 * @var bool True if the current request is for a network admin screen and the plugin is network active.
322 */
323 private $_is_network_active;
324
325 /**
326 * @since 2.0.0
327 *
328 * @var int|null The original blog ID the plugin was loaded with.
329 */
330 private $_blog_id = null;
331
332 /**
333 * @since 2.0.0
334 *
335 * @var int|null The current execution context. When true, run on network context. When int, run on the specified blog context.
336 */
337 private $_context_is_network_or_blog_id = null;
338
339 /**
340 * @since 2.0.0
341 *
342 * @var string
343 */
344 private $_dynamically_added_top_level_page_hook_name = '';
345
346 /**
347 * @author Leo Fajardo (@leorw)
348 * @since 2.3.1
349 *
350 * @var bool
351 */
352 private $is_whitelabeled;
353
354 /**
355 * @author Leo Fajardo (@leorw)
356 * @since 2.4.0
357 *
358 * @var bool
359 */
360 private $_is_bundle_license_auto_activation_enabled = false;
361
362 #region Uninstall Reasons IDs
363
364 const REASON_NO_LONGER_NEEDED = 1;
365 const REASON_FOUND_A_BETTER_PLUGIN = 2;
366 const REASON_NEEDED_FOR_A_SHORT_PERIOD = 3;
367 const REASON_BROKE_MY_SITE = 4;
368 const REASON_SUDDENLY_STOPPED_WORKING = 5;
369 const REASON_CANT_PAY_ANYMORE = 6;
370 const REASON_OTHER = 7;
371 const REASON_DIDNT_WORK = 8;
372 const REASON_DONT_LIKE_TO_SHARE_MY_INFORMATION = 9;
373 const REASON_COULDNT_MAKE_IT_WORK = 10;
374 const REASON_GREAT_BUT_NEED_SPECIFIC_FEATURE = 11;
375 const REASON_NOT_WORKING = 12;
376 const REASON_NOT_WHAT_I_WAS_LOOKING_FOR = 13;
377 const REASON_DIDNT_WORK_AS_EXPECTED = 14;
378 const REASON_TEMPORARY_DEACTIVATION = 15;
379
380 #endregion
381
382 /**
383 * @author Leo Fajardo (@leorw)
384 * @since 2.3.1
385 *
386 * @var boolean|null
387 */
388 private $_use_external_pricing = null;
389 /**
390 * @author Leo Fajardo (@leorw)
391 * @since 2.4.2
392 *
393 * @var string|null
394 */
395 private $_pricing_js_path = null;
396
397 const VERSION_MAX_CHARS = 16;
398 const LANGUAGE_MAX_CHARS = 8;
399
400 /* Ctor
401 ------------------------------------------------------------------------------------------------------------------*/
402
403 /**
404 * Main singleton instance.
405 *
406 * @author Vova Feldman (@svovaf)
407 * @since 1.0.0
408 *
409 * @param number $module_id
410 * @param string|bool $slug
411 * @param bool $is_init Since 1.2.1 Is initiation sequence.
412 */
413 private function __construct( $module_id, $slug = false, $is_init = false ) {
414 $main_file = false;
415
416 if ( $is_init && is_numeric( $module_id ) && is_string( $slug ) ) {
417 $main_file = $this->store_id_slug_type_path_map( $module_id, $slug );
418 }
419
420 $this->_module_id = $module_id;
421 $this->_slug = $this->get_slug();
422 $this->_module_type = $this->get_module_type();
423
424 $this->_blog_id = is_multisite() ? get_current_blog_id() : null;
425
426 $this->_storage = FS_Storage::instance( $this->_module_type, $this->_slug );
427
428 // 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.
429 if (
430 ! isset( $this->_storage->last_load_timestamp ) ||
431 $this->_storage->last_load_timestamp < ( time() - ( WP_FS__TIME_24_HOURS_IN_SEC ) )
432 ) {
433 $this->_storage->last_load_timestamp = time();
434 }
435
436 $this->_cache = FS_Cache_Manager::get_manager( WP_FS___OPTION_PREFIX . "cache_{$module_id}" );
437
438 $this->_logger = FS_Logger::get_logger( WP_FS__SLUG . '_' . $this->get_unique_affix(), WP_FS__DEBUG_SDK, WP_FS__ECHO_DEBUG_SDK );
439
440 $this->_plugin_main_file_path = $this->_find_caller_plugin_file( $is_init, $main_file );
441 $this->_plugin_dir_path = plugin_dir_path( $this->_plugin_main_file_path );
442 $this->_plugin_basename = $this->get_plugin_basename();
443 $this->_free_plugin_basename = str_replace( '-premium/', '/', $this->_plugin_basename );
444
445 $this->_is_multisite_integrated = (
446 defined( "WP_FS__PRODUCT_{$module_id}_MULTISITE" ) &&
447 ( true === constant( "WP_FS__PRODUCT_{$module_id}_MULTISITE" ) )
448 );
449
450 $this->_is_network_active = (
451 is_multisite() &&
452 $this->_is_multisite_integrated &&
453 // Themes are always network activated, but the ACTUAL activation is per site.
454 $this->is_plugin() &&
455 (
456 is_plugin_active_for_network( $this->_plugin_basename ) ||
457 // Plugin network level activation or uninstall.
458 ( fs_is_network_admin() && is_plugin_inactive( $this->_plugin_basename ) )
459 )
460 );
461
462 $this->_storage->set_network_active(
463 $this->_is_network_active,
464 $this->is_delegated_connection()
465 );
466
467 if ( ! isset( $this->_storage->is_network_activated ) ) {
468 $this->_storage->is_network_activated = $this->_is_network_active;
469 }
470
471 if ( $this->_storage->is_network_activated != $this->_is_network_active ) {
472 // Update last activation level.
473 $this->_storage->is_network_activated = $this->_is_network_active;
474
475 $this->maybe_adjust_storage();
476 }
477
478 #region Migration
479
480 if ( is_multisite() ) {
481 /**
482 * If the install_timestamp exists on the site level but doesn't exist on the
483 * network level storage, it means that we need to process the storage with migration.
484 *
485 * 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.
486 *
487 * @author Vova Feldman (@svovaf)
488 * @since 2.0.0
489 */
490 if ( false === $this->_storage->get( 'install_timestamp', false, true ) &&
491 false !== $this->_storage->get( 'install_timestamp', false, false )
492 ) {
493 // Initiate storage migration.
494 $this->_storage->migrate_to_network();
495
496 // Migrate module cache to network level storage.
497 $this->_cache->migrate_to_network();
498 }
499 }
500
501 #endregion
502
503 $base_name_split = explode( '/', $this->_plugin_basename );
504 $this->_plugin_dir_name = $base_name_split[0];
505
506 if ( $this->_logger->is_on() ) {
507 $this->_logger->info( 'plugin_main_file_path = ' . $this->_plugin_main_file_path );
508 $this->_logger->info( 'plugin_dir_path = ' . $this->_plugin_dir_path );
509 $this->_logger->info( 'plugin_basename = ' . $this->_plugin_basename );
510 $this->_logger->info( 'free_plugin_basename = ' . $this->_free_plugin_basename );
511 $this->_logger->info( 'plugin_dir_name = ' . $this->_plugin_dir_name );
512 }
513
514 // Remember link between file to slug.
515 $this->store_file_slug_map();
516
517 // Store plugin's initial install timestamp.
518 if ( ! isset( $this->_storage->install_timestamp ) ) {
519 $this->_storage->install_timestamp = WP_FS__SCRIPT_START_TIME;
520 }
521
522 if ( ! is_object( $this->_plugin ) ) {
523 $this->_plugin = FS_Plugin_Manager::instance( $this->_module_id )->get();
524 }
525
526 $this->_admin_notices = FS_Admin_Notices::instance(
527 $this->_slug . ( $this->is_theme() ? ':theme' : '' ),
528 /**
529 * Ensure that the admin notice will always have a title by using the stored plugin title if available and
530 * retrieving the title via the "get_plugin_name" method if there is no stored plugin title available.
531 *
532 * @author Leo Fajardo (@leorw)
533 * @since 1.2.2
534 */
535 ( is_object( $this->_plugin ) && isset( $this->_plugin->title ) ?
536 $this->_plugin->title :
537 $this->get_plugin_name()
538 ),
539 $this->get_unique_affix()
540 );
541
542 if ( 'true' === fs_request_get( 'fs_clear_api_cache' ) ||
543 fs_request_is_action( 'restart_freemius' )
544 ) {
545 FS_Api::clear_cache();
546 $this->_cache->clear();
547 }
548
549 $this->register_constructor_hooks();
550
551 /**
552 * Starting from version 2.0.0, `FS_Site` entities no longer have the `plan` property and have `plan_id`
553 * instead. This should be called before calling `_load_account()`, otherwise, `$this->_site` will not be
554 * loaded in `_load_account` for versions of SDK starting from 2.0.0.
555 *
556 * @author Leo Fajardo (@leorw)
557 */
558 self::migrate_install_plan_to_plan_id( $this->_storage );
559
560 $this->_load_account();
561
562 $this->_version_updates_handler();
563 }
564
565 /**
566 * @author Leo Fajardo (@leorw)
567 * @since 2.3.0
568 */
569 private function maybe_adjust_storage() {
570 $install_timestamp = null;
571 $prev_is_premium = null;
572
573 $options_to_update = array();
574
575 $is_network_admin = fs_is_network_admin();
576
577 $network_install_timestamp = $this->_storage->get( 'install_timestamp', null, true );
578
579 if ( ! $is_network_admin ) {
580 if ( is_null( $network_install_timestamp ) ) {
581 // Plugin was not network-activated before.
582 return;
583 }
584
585 if ( is_null( $this->_storage->get( 'install_timestamp', null, false ) ) ) {
586 // Set the `install_timestamp` only if it's not yet set.
587 $install_timestamp = $network_install_timestamp;
588 }
589
590 $prev_is_premium = $this->_storage->get( 'prev_is_premium', null, true );
591 } else {
592 $current_wp_user = self::_get_current_wp_user();
593 $current_fs_user = self::_get_user_by_email( $current_wp_user->user_email );
594 $network_user_info = array();
595
596 $skips_count = 0;
597
598 $sites = self::get_sites();
599 $sites_count = count( $sites );
600
601 $blog_id_2_install_map = array();
602
603 $is_first_non_ignored_blog = true;
604
605 foreach ( $sites as $site ) {
606 $blog_id = self::get_site_blog_id( $site );
607
608 $blog_install_timestamp = $this->_storage->get( 'install_timestamp', null, $blog_id );
609
610 if ( is_null( $blog_install_timestamp ) ) {
611 // Plugin has not been installed on this blog.
612 continue;
613 }
614
615 $is_earlier_install = (
616 ! is_null( $install_timestamp ) &&
617 $blog_install_timestamp < $install_timestamp
618 );
619
620 $install = $this->get_install_by_blog_id( $blog_id );
621
622 $update_network_user_info = false;
623
624 if ( ! is_object( $install ) ) {
625 if ( ! $this->_storage->get( 'is_anonymous', false, $blog_id ) ) {
626 // The opt-in decision (whether to skip or opt in) is yet to be made.
627 continue;
628 }
629
630 $skips_count ++;
631 } else {
632 $blog_id_2_install_map[ $blog_id ] = $install;
633
634 if ( empty( $network_user_info ) ) {
635 // Set the network user info for the 1st time. Choose any user information whether or not it is for the current WP user.
636 $update_network_user_info = true;
637 }
638
639 if ( ! $update_network_user_info &&
640 is_object( $current_fs_user ) &&
641 $network_user_info['user_id'] != $current_fs_user->id &&
642 $install->user_id == $current_fs_user->id
643 ) {
644 // If an install that is owned by the current WP user is found, use its user information instead.
645 $update_network_user_info = true;
646 }
647
648 if ( ! $update_network_user_info &&
649 $is_earlier_install &&
650 ( ! is_object( $current_fs_user ) || $current_fs_user->id == $install->user_id )
651 ) {
652 // 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.
653 $update_network_user_info = true;
654 }
655 }
656
657 if ( $update_network_user_info ) {
658 $network_user_info = array(
659 'user_id' => $install->user_id,
660 'blog_id' => $blog_id
661 );
662 }
663
664 $site_prev_is_premium = $this->_storage->get( 'prev_is_premium', null, $blog_id );
665
666 if ( $is_first_non_ignored_blog ) {
667 $prev_is_premium = $site_prev_is_premium;
668
669 if ( is_null( $network_install_timestamp ) ) {
670 $install_timestamp = $blog_install_timestamp;
671 }
672
673 $is_first_non_ignored_blog = false;
674
675 continue;
676 }
677
678 if ( ! is_null( $prev_is_premium ) && $prev_is_premium !== $site_prev_is_premium ) {
679 // If a different `$site_prev_is_premium` value is found, do not include the option in the collection of options to update.
680 $prev_is_premium = null;
681 }
682
683 if ( $is_earlier_install ) {
684 // If an earlier install timestamp is found.
685 $install_timestamp = $blog_install_timestamp;
686 }
687 }
688
689 $installs_count = count( $blog_id_2_install_map );
690
691 if ( $sites_count === ( $installs_count + $skips_count ) ) {
692 if ( ! empty( $network_user_info ) ) {
693 $options_to_update['network_user_id'] = $network_user_info['user_id'];
694 $options_to_update['network_install_blog_id'] = $network_user_info['blog_id'];
695
696 foreach ( $blog_id_2_install_map as $blog_id => $install ) {
697 if ( $install->user_id == $network_user_info['user_id'] ) {
698 continue;
699 }
700
701 $this->_storage->store( 'is_delegated_connection', true, $blog_id );
702 }
703 }
704
705 if ( $sites_count === $skips_count ) {
706 /**
707 * Assume network-level skipping as the intended action if all actions identified were only
708 * skipping of the connection (i.e., no opt-ins and delegated connections so far).
709 */
710 $options_to_update['is_anonymous_ms'] = true;
711 } else if ( $sites_count === $installs_count ) {
712 /**
713 * Assume network-level opt-in as the intended action if all actions identified were only opt-ins
714 * (i.e., no delegation and skipping of the connections so far).
715 */
716 $options_to_update['is_network_connected'] = true;
717 }
718 }
719 }
720
721 if ( ! is_null( $install_timestamp ) ) {
722 $options_to_update['install_timestamp'] = $install_timestamp;
723 }
724
725 if ( ! is_null( $prev_is_premium ) ) {
726 $options_to_update['prev_is_premium'] = $prev_is_premium;
727 }
728
729 if ( ! empty( $options_to_update ) ) {
730 $this->adjust_storage( $options_to_update, $is_network_admin );
731 }
732 }
733
734 /**
735 * @author Leo Fajardo (@leorw)
736 * @since 2.3.0
737 *
738 * @param array $options
739 * @param bool $is_network_admin
740 */
741 private function adjust_storage( $options, $is_network_admin ) {
742 foreach ( $options as $name => $value ) {
743 $this->_storage->store( $name, $value, $is_network_admin ? true : null );
744 }
745 }
746
747 /**
748 * Checks whether this module has a settings menu.
749 *
750 * @author Leo Fajardo (@leorw)
751 * @since 1.2.2
752 *
753 * @return bool
754 */
755 function has_settings_menu() {
756 return ( $this->_is_network_active && fs_is_network_admin() ) ?
757 $this->_menu->has_network_menu() :
758 $this->_menu->has_menu();
759 }
760
761 /**
762 * 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.
763 *
764 * @author Vova Feldman (@svovaf)
765 * @since 2.4.5
766 *
767 * @return bool
768 */
769 function show_opt_in_on_themes_page() {
770 if ( ! $this->is_free_wp_org_theme() ) {
771 return false;
772 }
773
774 if ( ! $this->has_settings_menu() ) {
775 return true;
776 }
777
778 return $this->show_settings_with_tabs();
779 }
780
781 /**
782 * If `true` the opt-in should be shown on the product's main setting page.
783 *
784 * @author Vova Feldman (@svovaf)
785 * @since 2.4.5
786 *
787 * @return bool
788 *
789 * @uses show_opt_in_on_themes_page();
790 */
791 function show_opt_in_on_setting_page() {
792 return ! $this->show_opt_in_on_themes_page();
793 }
794
795 /**
796 * If `true` the settings should be shown using tabs.
797 *
798 * @author Vova Feldman (@svovaf)
799 * @since 2.4.5
800 *
801 * @return bool
802 */
803 function show_settings_with_tabs() {
804 return ( self::NAVIGATION_TABS === $this->_navigation );
805 }
806
807 /**
808 * Check if the context module is free wp.org theme.
809 *
810 * This method is helpful because:
811 * 1. wp.org themes are limited to a single submenu item,
812 * and sub-submenu items are most likely not allowed (never verified).
813 * 2. wp.org themes are not allowed to redirect the user
814 * after the theme activation, therefore, the agreed UX
815 * is showing the opt-in as a modal dialog box after
816 * activation (approved by @otto42, @emiluzelac, @greenshady, @grapplerulrich).
817 *
818 * @author Vova Feldman (@svovaf)
819 * @since 1.2.2.7
820 *
821 * @return bool
822 */
823 function is_free_wp_org_theme() {
824 return (
825 $this->is_theme() &&
826 $this->is_org_repo_compliant() &&
827 ! $this->is_premium()
828 );
829 }
830
831 /**
832 * Checks whether this a submenu item is visible.
833 *
834 * @author Vova Feldman (@svovaf)
835 * @since 1.2.2.6
836 * @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.
837 *
838 * @param string $slug
839 * @param bool $is_tabs_visibility_check This is used to decide if the associated tab should be shown or hidden.
840 *
841 * @return bool
842 */
843 function is_submenu_item_visible( $slug, $is_tabs_visibility_check = false ) {
844 if ( $this->is_admin_page( $slug ) ) {
845 /**
846 * It is the current context page, so show the submenu item
847 * so the user will have the right context page, even if it
848 * was set to hidden.
849 */
850 return true;
851 }
852
853 if ( ! $this->has_settings_menu() ) {
854 // No menu settings at all.
855 return false;
856 }
857
858 if (
859 ! $is_tabs_visibility_check &&
860 $this->is_org_repo_compliant() &&
861 $this->show_settings_with_tabs()
862 ) {
863 /**
864 * wp.org themes are limited to a single submenu item, and
865 * sub-submenu items are most likely not allowed (never verified).
866 */
867 return false;
868 }
869
870 return $this->_menu->is_submenu_item_visible( $slug );
871 }
872
873 /**
874 * Check if a Freemius page should be accessible via the UI.
875 *
876 * @author Vova Feldman (@svovaf)
877 * @since 1.2.2.7
878 *
879 * @param string $slug
880 *
881 * @return bool
882 */
883 function is_page_visible( $slug ) {
884 if ( $this->is_admin_page( $slug ) ) {
885 return true;
886 }
887
888 return $this->_menu->is_submenu_item_visible( $slug, true, true );
889 }
890
891 /**
892 * @author Vova Feldman (@svovaf)
893 * @since 1.0.9
894 */
895 private function _version_updates_handler() {
896 if ( ! isset( $this->_storage->sdk_version ) || $this->_storage->sdk_version != $this->version ) {
897 // Freemius version upgrade mode.
898 $this->_storage->sdk_last_version = $this->_storage->sdk_version;
899 $this->_storage->sdk_version = $this->version;
900
901 if ( empty( $this->_storage->sdk_last_version ) ||
902 version_compare( $this->_storage->sdk_last_version, $this->version, '<' )
903 ) {
904 $this->_storage->sdk_upgrade_mode = true;
905 $this->_storage->sdk_downgrade_mode = false;
906 } else {
907 $this->_storage->sdk_downgrade_mode = true;
908 $this->_storage->sdk_upgrade_mode = false;
909
910 }
911
912 $this->do_action( 'sdk_version_update', $this->_storage->sdk_last_version, $this->version );
913 }
914
915 $plugin_version = $this->get_plugin_version();
916 if ( ! isset( $this->_storage->plugin_version ) || $this->_storage->plugin_version != $plugin_version ) {
917 // Plugin version upgrade mode.
918 $this->_storage->plugin_last_version = $this->_storage->plugin_version;
919 $this->_storage->plugin_version = $plugin_version;
920
921 if ( empty( $this->_storage->plugin_last_version ) ||
922 version_compare( $this->_storage->plugin_last_version, $plugin_version, '<' )
923 ) {
924 $this->_storage->plugin_upgrade_mode = true;
925 $this->_storage->plugin_downgrade_mode = false;
926 } else {
927 $this->_storage->plugin_downgrade_mode = true;
928 $this->_storage->plugin_upgrade_mode = false;
929 }
930
931 if ( ! empty( $this->_storage->plugin_last_version ) ) {
932 // Different version of the plugin was installed before, therefore it's an update.
933 $this->_storage->is_plugin_new_install = false;
934 }
935
936 $this->do_action( 'plugin_version_update', $this->_storage->plugin_last_version, $plugin_version );
937 }
938 }
939
940 #--------------------------------------------------------------------------------
941 #region Data Migration on SDK Update
942 #--------------------------------------------------------------------------------
943
944 /**
945 * @author Vova Feldman (@svovaf)
946 * @since 1.1.5
947 *
948 * @param string $sdk_prev_version
949 * @param string $sdk_version
950 */
951 function _sdk_version_update( $sdk_prev_version, $sdk_version ) {
952 if ( empty( $sdk_prev_version ) ) {
953 return;
954 }
955
956 if (
957 version_compare( $sdk_prev_version, '2.5.1', '<' ) &&
958 version_compare( $sdk_version, '2.5.1', '>=' )
959 ) {
960 if ( $this->is_registered( true ) ) {
961 /**
962 * Migrate to new permissions layer.
963 */
964 require_once WP_FS__DIR_INCLUDES . '/supplements/fs-migration-2.5.1.php';
965
966 $install_by_blog_id = is_multisite() ?
967 $this->get_blog_install_map() :
968 array( 0 => $this->_site );
969
970 fs_migrate_251( $this, $install_by_blog_id );
971 }
972 }
973 }
974
975 /**
976 * @author Leo Fajardo (@leorw)
977 * @since 2.0.0
978 *
979 * @param \FS_Storage $storage
980 * @param bool|int|null $blog_id
981 */
982 private static function migrate_install_plan_to_plan_id( FS_Storage $storage, $blog_id = null ) {
983 if ( empty( $storage->sdk_version ) ) {
984 // New installation of the plugin, no need to upgrade.
985 return;
986 }
987
988 if ( ! version_compare( $storage->sdk_version, '2.0.0', '<' ) ) {
989 // Previous version is >= 2.0.0, so no need to migrate.
990 return;
991 }
992
993 // Alias.
994 $module_type = $storage->get_module_type();
995 $module_slug = $storage->get_module_slug();
996
997 $installs = self::get_all_sites( $module_type, $blog_id );
998 $install = isset( $installs[ $module_slug ] ) ? $installs[ $module_slug ] : null;
999
1000 if ( ! is_object( $install ) ) {
1001 return;
1002 }
1003
1004 if ( isset( $install->plan ) && is_object( $install->plan ) ) {
1005 if ( isset( $install->plan->id ) && ! empty( $install->plan->id ) ) {
1006 $install->plan_id = self::_decrypt( $install->plan->id );
1007 }
1008
1009 unset( $install->plan );
1010
1011 $installs[ $module_slug ] = clone $install;
1012
1013 self::set_account_option_by_module(
1014 $module_type,
1015 'sites',
1016 $installs,
1017 true,
1018 $blog_id
1019 );
1020 }
1021 }
1022
1023 /**
1024 * @author Vova Feldman (@svovaf)
1025 * @since 1.2.2.7
1026 *
1027 * @param string $plugin_prev_version
1028 * @param string $plugin_version
1029 */
1030 function _after_version_update( $plugin_prev_version, $plugin_version ) {
1031 if ( $this->is_theme() ) {
1032 // Expire the cache of the previous tabs since the theme may
1033 // have setting updates.
1034 $this->_cache->expire( 'tabs' );
1035 $this->_cache->expire( 'tabs_stylesheets' );
1036 }
1037 }
1038
1039 /**
1040 * A special migration logic for the $_accounts, executed for all the plugins in the system:
1041 * - Moves some data to the network level storage.
1042 * - If the plugin's connection was skipped for all sites, set the plugin as if it was network skipped.
1043 * - If the plugin's connection was ignored for all sites, don't do anything in terms of the network connection.
1044 * - 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.
1045 * - 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.
1046 * - 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.
1047 *
1048 * @author Vova Feldman (@svovaf)
1049 * @since 2.0.0
1050 */
1051 private static function migrate_accounts_to_network() {
1052 $sites = self::get_sites();
1053 $sites_count = count( $sites );
1054 $connection_status = array();
1055 $plugin_slugs = array();
1056 foreach ( $sites as $site ) {
1057 $blog_id = self::get_site_blog_id( $site );
1058
1059 self::$_accounts->migrate_to_network( $blog_id );
1060
1061 /**
1062 * Build a list of all Freemius powered plugins slugs.
1063 */
1064 $id_slug_type_path_map = self::$_accounts->get_option( 'id_slug_type_path_map', array(), $blog_id );
1065 foreach ( $id_slug_type_path_map as $module_id => $data ) {
1066 if ( WP_FS__MODULE_TYPE_PLUGIN === $data['type'] ) {
1067 $plugin_slugs[ $data['slug'] ] = true;
1068 }
1069 }
1070
1071 $installs = self::get_account_option( 'sites', WP_FS__MODULE_TYPE_PLUGIN, $blog_id );
1072
1073 if ( is_array( $installs ) ) {
1074 foreach ( $installs as $slug => $install ) {
1075 if ( ! isset( $connection_status[ $slug ] ) ) {
1076 $connection_status[ $slug ] = array();
1077 }
1078
1079 if ( is_object( $install ) &&
1080 FS_Site::is_valid_id( $install->id ) &&
1081 FS_User::is_valid_id( $install->user_id )
1082 ) {
1083 $connection_status[ $slug ][ $blog_id ] = $install->user_id;
1084 }
1085 }
1086 }
1087 }
1088
1089 foreach ( $plugin_slugs as $slug => $true ) {
1090 if ( ! isset( $connection_status[ $slug ] ) ) {
1091 $connection_status[ $slug ] = array();
1092 }
1093
1094 foreach ( $sites as $site ) {
1095 $blog_id = self::get_site_blog_id( $site );
1096
1097 if ( isset( $connection_status[ $slug ][ $blog_id ] ) ) {
1098 continue;
1099 }
1100
1101 $storage = FS_Storage::instance( WP_FS__MODULE_TYPE_PLUGIN, $slug );
1102
1103 $is_anonymous = $storage->get( 'is_anonymous', null, $blog_id );
1104
1105 if ( ! is_null( $is_anonymous ) ) {
1106 // Since 1.1.3 is_anonymous is an array.
1107 if ( is_array( $is_anonymous ) && isset( $is_anonymous['is'] ) ) {
1108 $is_anonymous = $is_anonymous['is'];
1109 }
1110
1111 if ( is_bool( $is_anonymous ) && true === $is_anonymous ) {
1112 $connection_status[ $slug ][ $blog_id ] = 'skipped';
1113 }
1114 }
1115
1116 if ( ! isset( $connection_status[ $slug ][ $blog_id ] ) ) {
1117 $connection_status[ $slug ][ $blog_id ] = 'ignored';
1118 }
1119 }
1120 }
1121
1122 $super_admins = array();
1123
1124 foreach ( $connection_status as $slug => $blogs_status ) {
1125 $skips = 0;
1126 $ignores = 0;
1127 $connections = 0;
1128 $opted_in_users = array();
1129 $opted_in_super_admins = array();
1130
1131 $storage = FS_Storage::instance( WP_FS__MODULE_TYPE_PLUGIN, $slug );
1132
1133 foreach ( $blogs_status as $blog_id => $status_or_user_id ) {
1134 if ( 'skipped' === $status_or_user_id ) {
1135 $skips ++;
1136 } else if ( 'ignored' === $status_or_user_id ) {
1137 $ignores ++;
1138 } else if ( FS_User::is_valid_id( $status_or_user_id ) ) {
1139 $connections ++;
1140
1141 if ( ! isset( $opted_in_users[ $status_or_user_id ] ) ) {
1142 $opted_in_users[ $status_or_user_id ] = array();
1143 }
1144
1145 $opted_in_users[ $status_or_user_id ][] = $blog_id;
1146
1147 if ( isset( $super_admins[ $status_or_user_id ] ) ||
1148 self::is_super_admin( $status_or_user_id )
1149 ) {
1150 // Cache super-admin data.
1151 $super_admins[ $status_or_user_id ] = true;
1152
1153 // Remember opted-in super-admins for the plugin.
1154 $opted_in_super_admins[ $status_or_user_id ] = true;
1155 }
1156 }
1157 }
1158
1159 $main_super_admin_user_id = null;
1160 $all_migrated = false;
1161 if ( $sites_count == $skips ) {
1162 // All sites were skipped -> network skip by copying the anonymous mode from any of the sites.
1163 $storage->is_anonymous_ms = $storage->is_anonymous;
1164
1165 $all_migrated = true;
1166 } else if ( $sites_count == $ignores ) {
1167 // Don't do anything, still in activation mode.
1168
1169 $all_migrated = true;
1170 } else if ( 0 < count( $opted_in_super_admins ) ) {
1171 // Find the super-admin with the majority of installs.
1172 $max_installs_by_super_admin = 0;
1173 foreach ( $opted_in_super_admins as $user_id => $true ) {
1174 $installs_count = count( $opted_in_users[ $user_id ] );
1175
1176 if ( $installs_count > $max_installs_by_super_admin ) {
1177 $max_installs_by_super_admin = $installs_count;
1178 $main_super_admin_user_id = $user_id;
1179 }
1180 }
1181
1182 if ( $sites_count == $connections && 1 == count( $opted_in_super_admins ) ) {
1183 // Super-admin opted-in for all sites in the network.
1184 $storage->is_network_connected = true;
1185
1186 $all_migrated = true;
1187 }
1188
1189 // Store network user.
1190 $storage->network_user_id = $main_super_admin_user_id;
1191
1192 $storage->network_install_blog_id = ( $sites_count == $connections ) ?
1193 // Since all sites are opted-in, associating with the main site.
1194 get_current_blog_id() :
1195 // Associating with the 1st found opted-in site.
1196 $opted_in_users[ $main_super_admin_user_id ][0];
1197
1198 /**
1199 * Make sure we migrate the plan ID of the network install, otherwise, if after the migration
1200 * the 1st page that will be loaded is the network level WP Admin and $storage->network_install_blog_id
1201 * is different than the main site of the network, the $this->_site will not be set since the plan_id
1202 * will be empty.
1203 */
1204 $storage->migrate_to_network();
1205 self::migrate_install_plan_to_plan_id( $storage, $storage->network_install_blog_id );
1206 } else {
1207 // At least one opt-in. All the opt-in were created by a non-super-admin.
1208 if ( 0 == $ignores ) {
1209 // All sites were opted-in or skipped, all by non-super-admin. So delegate all.
1210 $storage->store( 'is_delegated_connection', true, true );
1211
1212 $all_migrated = true;
1213 }
1214 }
1215
1216 if ( ! $all_migrated ) {
1217 /**
1218 * Delegate all sites that were:
1219 * 1) Opted-in by a user that is NOT the main-super-admin.
1220 * 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.
1221 */
1222 foreach ( $blogs_status as $blog_id => $status_or_user_id ) {
1223 if ( $status_or_user_id == $main_super_admin_user_id ) {
1224 continue;
1225 }
1226
1227 if ( FS_User::is_valid_id( $status_or_user_id ) ||
1228 ( 'skipped' === $status_or_user_id && is_null( $main_super_admin_user_id ) )
1229 ) {
1230 $storage->store( 'is_delegated_connection', true, $blog_id );
1231 }
1232 }
1233 }
1234
1235
1236 if ( ( $connections + $skips > 0 ) ) {
1237 if ( $ignores > 0 ) {
1238 /**
1239 * If admin already opted-in or skipped in any of the network sites, and also
1240 * have sites which the connection decision was not yet taken, set this plugin
1241 * into network activation mode so the super-admin can choose what to do with
1242 * the rest of the sites.
1243 */
1244 self::set_network_upgrade_mode( $storage );
1245 }
1246 }
1247 }
1248 }
1249
1250 /**
1251 * Set a module into network upgrade mode.
1252 *
1253 * @author Vova Feldman (@svovaf)
1254 * @since 2.0.0
1255 *
1256 * @param \FS_Storage $storage
1257 *
1258 * @return bool
1259 */
1260 public static function set_network_upgrade_mode( FS_Storage $storage ) {
1261 return $storage->is_network_activation = true;
1262 }
1263
1264 /**
1265 * Will return true after upgrading to the SDK with the network level integration,
1266 * when the super-admin involvement is required regarding the rest of the sites.
1267 *
1268 * @author Vova Feldman (@svovaf)
1269 * @since 2.0.0
1270 *
1271 * @return bool
1272 */
1273 function is_network_upgrade_mode() {
1274 return $this->_storage->get( 'is_network_activation' );
1275 }
1276
1277 /**
1278 * Clear flag after the upgrade mode completion.
1279 *
1280 * @author Vova Feldman (@svovaf)
1281 * @since 2.0.0
1282 *
1283 * @return bool True if network activation was on and now completed.
1284 */
1285 private function network_upgrade_mode_completed() {
1286 if ( fs_is_network_admin() && $this->is_network_upgrade_mode() ) {
1287 $this->_storage->remove( 'is_network_activation' );
1288
1289 return true;
1290 }
1291
1292 return false;
1293 }
1294
1295 #endregion
1296
1297 /**
1298 * This action is connected to the 'plugins_loaded' hook and helps to determine
1299 * if this is a new plugin installation or a plugin update.
1300 *
1301 * There are 3 different use-cases:
1302 * 1) New plugin installation right with Freemius:
1303 * 1.1 _activate_plugin_event_hook() will be executed first
1304 * 1.2 Since $this->_storage->is_plugin_new_install is not set,
1305 * and $this->_storage->plugin_last_version is not set,
1306 * $this->_storage->is_plugin_new_install will be set to TRUE.
1307 * 1.3 When _plugins_loaded() will be executed, $this->_storage->is_plugin_new_install will
1308 * be already set to TRUE.
1309 *
1310 * 2) Plugin update, didn't have Freemius before, and now have the SDK:
1311 * 2.1 _activate_plugin_event_hook() will not be executed, because
1312 * the activation hook do NOT fires on updates since WP 3.1.
1313 * 2.2 When _plugins_loaded() will be executed, $this->_storage->is_plugin_new_install will
1314 * be empty, therefore, it will be set to FALSE.
1315 *
1316 * 3) Plugin update, had Freemius in prev version as well:
1317 * 3.1 _version_updates_handler() will be executed 1st, since FS was installed
1318 * before, $this->_storage->plugin_last_version will NOT be empty,
1319 * therefore, $this->_storage->is_plugin_new_install will be set to FALSE.
1320 * 3.2 When _plugins_loaded() will be executed, $this->_storage->is_plugin_new_install is
1321 * already set, therefore, it will not be modified.
1322 *
1323 * Use-case #3 is backward compatible, #3.1 will be executed since 1.0.9.
1324 *
1325 * NOTE:
1326 * The only fallback of this mechanism is if an admin updates a plugin based on use-case #2,
1327 * and then, the next immediate PageView is the plugin's main settings page, it will not
1328 * show the opt-in right away. The reason it will happen is because Freemius execution
1329 * will be turned off till the plugin is fully loaded at least once
1330 * (till $this->_storage->was_plugin_loaded is TRUE).
1331 *
1332 * @author Vova Feldman (@svovaf)
1333 * @since 1.1.9
1334 *
1335 */
1336 function _plugins_loaded() {
1337 // Update flag that plugin was loaded with Freemius at least once.
1338 $this->_storage->was_plugin_loaded = true;
1339
1340 /**
1341 * Bug fix - only set to false when it's a plugin, due to the
1342 * execution sequence of the theme hooks and our methods, if
1343 * this will be set for themes, Freemius will always assume
1344 * it's a theme update.
1345 *
1346 * @author Vova Feldman (@svovaf)
1347 * @since 1.2.2.2
1348 */
1349 if ( $this->is_plugin() &&
1350 ! isset( $this->_storage->is_plugin_new_install )
1351 ) {
1352 $this->_storage->is_plugin_new_install = (
1353 ! is_plugin_active( $this->_plugin_basename ) &&
1354 empty( $this->_storage->plugin_last_version )
1355 );
1356 }
1357 }
1358
1359 function _run_garbage_collector() {
1360 if ( true !== fs_get_optional_constant( 'WP_FS__ENABLE_GARBAGE_COLLECTOR', true ) ) {
1361 return;
1362 }
1363
1364 if ( ! $this->is_user_in_admin() ) {
1365 return;
1366 }
1367
1368 require_once WP_FS__DIR_INCLUDES . '/class-fs-lock.php';
1369
1370 $lock = new FS_Lock( 'garbage_collection' );
1371
1372 if ( $lock->is_locked() ) {
1373 return;
1374 }
1375
1376 // Create a 1-day lock.
1377 $lock->lock( WP_FS__TIME_24_HOURS_IN_SEC );
1378
1379 FS_Garbage_Collector::instance()->clean();
1380 }
1381
1382 /**
1383 * Opens the support forum subemenu item in a new browser page.
1384 *
1385 * @author Vova Feldman (@svovaf)
1386 * @since 2.1.4
1387 */
1388 static function _open_support_forum_in_new_page() {
1389 ?>
1390 <script type="text/javascript">
1391 (function ($) {
1392 $('.fs-submenu-item.wp-support-forum').parent().attr( { target: '_blank', rel: 'noopener noreferrer' } );
1393 })(jQuery);
1394 </script>
1395 <?php
1396 }
1397
1398 /**
1399 * @author Vova Feldman (@svovaf)
1400 * @since 1.0.9
1401 */
1402 private function register_constructor_hooks() {
1403 $this->_logger->entrance();
1404
1405 if ( is_admin() ) {
1406 add_action( 'admin_init', array( &$this, '_hook_action_links_and_register_account_hooks' ) );
1407
1408 if ( $this->is_plugin() ) {
1409 if ( self::is_plugin_install_page() && true !== fs_request_get_bool( 'fs_allow_updater_and_dialog' ) ) {
1410 /**
1411 * Unless the `fs_allow_updater_and_dialog` URL param exists and its value is `true`, make
1412 * Freemius-related updates unavailable on the "Add Plugins" admin page (/plugin-install.php)
1413 * so that they won't interfere with the .org plugins' functionalities on that page (e.g.
1414 * updating of a .org plugin).
1415 */
1416 add_filter( 'site_transient_update_plugins', array( 'Freemius', '_remove_fs_updates_from_plugin_install_page' ), 10, 2 );
1417 } else if ( self::is_plugins_page() || self::is_updates_page() ) {
1418 /**
1419 * 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.
1420 *
1421 * @author Leo Fajardo (@leorw)
1422 * @since 2.2.3
1423 */
1424 add_action( 'admin_footer', array( 'Freemius', '_prepend_fs_allow_updater_and_dialog_flag_url_param' ) );
1425 }
1426
1427 $plugin_dir = dirname( $this->_plugin_dir_path ) . '/';
1428
1429 /**
1430 * @since 1.2.2
1431 *
1432 * Hook to both free and premium version activations to support
1433 * auto deactivation on the other version activation.
1434 */
1435 register_activation_hook(
1436 $plugin_dir . $this->_free_plugin_basename,
1437 array( &$this, '_activate_plugin_event_hook' )
1438 );
1439
1440 register_activation_hook(
1441 $plugin_dir . $this->premium_plugin_basename(),
1442 array( &$this, '_activate_plugin_event_hook' )
1443 );
1444 } else {
1445 add_action( 'after_switch_theme', array( &$this, '_activate_theme_event_hook' ), 10, 2 );
1446
1447 add_action( 'admin_footer', array( &$this, '_style_premium_theme' ) );
1448 }
1449
1450 /**
1451 * Part of the mechanism to identify new plugin install vs. plugin update.
1452 *
1453 * @author Vova Feldman (@svovaf)
1454 * @since 1.1.9
1455 */
1456 if ( empty( $this->_storage->was_plugin_loaded ) ) {
1457 /**
1458 * During the plugin activation (not theme), 'plugins_loaded' will be already executed
1459 * when the logic gets here since the activation logic first add the activate plugins,
1460 * then triggers 'plugins_loaded', and only then include the code of the plugin that
1461 * is activated. Which means that _plugins_loaded() will NOT be executed during the
1462 * plugin activation, and that IS intentional.
1463 *
1464 * @author Vova Feldman (@svovaf)
1465 */
1466 if ( $this->is_plugin() &&
1467 $this->is_activation_mode( false ) &&
1468 0 == did_action( 'plugins_loaded' )
1469 ) {
1470 add_action( 'plugins_loaded', array( &$this, '_plugins_loaded' ) );
1471 } else {
1472 // If was activated before, then it was already loaded before.
1473 $this->_plugins_loaded();
1474 }
1475 }
1476
1477 add_action( 'plugins_loaded', array( &$this, '_run_garbage_collector' ) );
1478
1479 if ( ! self::is_ajax() ) {
1480 if ( ! $this->is_addon() ) {
1481 add_action( 'init', array( &$this, '_add_default_submenu_items' ), WP_FS__LOWEST_PRIORITY );
1482 }
1483 }
1484
1485 if ( $this->_storage->handle_gdpr_admin_notice ) {
1486 add_action( 'init', array( &$this, '_maybe_show_gdpr_admin_notice' ) );
1487 }
1488
1489 add_action( 'init', array( &$this, '_maybe_add_gdpr_optin_ajax_handler') );
1490 add_action( 'init', array( &$this, '_maybe_add_pricing_ajax_handler' ) );
1491 }
1492
1493 if ( $this->is_plugin() ) {
1494 if ( version_compare( $GLOBALS['wp_version'], '5.1', '<' ) ) {
1495 add_action( 'wpmu_new_blog', array( $this, '_after_new_blog_callback' ), 10, 6 );
1496 } else {
1497 add_action( 'wp_initialize_site', array( $this, '_after_wp_initialize_site_callback' ), 11, 2 );
1498 }
1499
1500 register_deactivation_hook( $this->_plugin_main_file_path, array( &$this, '_deactivate_plugin_hook' ) );
1501 }
1502
1503 if ( is_multisite() ) {
1504 add_action( 'deactivate_blog', array( &$this, '_after_site_deactivated_callback' ) );
1505 add_action( 'archive_blog', array( &$this, '_after_site_deactivated_callback' ) );
1506 add_action( 'make_spam_blog', array( &$this, '_after_site_deactivated_callback' ) );
1507
1508 if ( version_compare( $GLOBALS['wp_version'], '5.1', '<' ) ) {
1509 add_action( 'deleted_blog', array( $this, '_after_site_deleted_callback' ), 10, 2 );
1510 } else {
1511 add_action( 'wp_delete_site', array( $this, '_after_wpsite_deleted_callback' ) );
1512 }
1513
1514 add_action( 'activate_blog', array( &$this, '_after_site_reactivated_callback' ) );
1515 add_action( 'unarchive_blog', array( &$this, '_after_site_reactivated_callback' ) );
1516 add_action( 'make_ham_blog', array( &$this, '_after_site_reactivated_callback' ) );
1517 }
1518
1519 if ( $this->is_theme() &&
1520 self::is_customizer() &&
1521 $this->apply_filters( 'show_customizer_upsell', true )
1522 ) {
1523 // Register customizer upsell.
1524 add_action( 'customize_register', array( &$this, '_customizer_register' ) );
1525 }
1526
1527 add_action( 'admin_init', array( &$this, '_redirect_on_clicked_menu_link' ), WP_FS__LOWEST_PRIORITY );
1528
1529 if ( $this->is_theme() && ! $this->is_migration() ) {
1530 add_action( 'admin_init', array( &$this, '_add_tracking_links' ) );
1531 }
1532
1533 add_action( 'admin_init', array( &$this, '_add_license_activation' ) );
1534 add_action( 'admin_init', array( &$this, '_add_premium_version_upgrade_selection' ) );
1535 add_action( 'admin_init', array( &$this, '_add_beta_mode_update_handler' ) );
1536 add_action( 'admin_init', array( &$this, '_add_user_change_option' ) );
1537 add_action( 'admin_init', array( &$this, '_add_email_address_update_option' ) );
1538
1539 $this->add_ajax_action( 'update_billing', array( &$this, '_update_billing_ajax_action' ) );
1540 $this->add_ajax_action( 'start_trial', array( &$this, '_start_trial_ajax_action' ) );
1541 $this->add_ajax_action( 'set_data_debug_mode', array( &$this, '_set_data_debug_mode' ) );
1542 $this->add_ajax_action( 'toggle_whitelabel_mode', array( &$this, '_toggle_whitelabel_mode_ajax_handler' ) );
1543
1544 if ( $this->_is_network_active && fs_is_network_admin() ) {
1545 $this->add_ajax_action( 'network_activate', array( &$this, '_network_activate_ajax_action' ) );
1546 }
1547
1548 $this->add_ajax_action( 'install_premium_version', array(
1549 &$this,
1550 '_install_premium_version_ajax_action'
1551 ) );
1552
1553 $this->add_ajax_action( 'submit_affiliate_application', array( &$this, '_submit_affiliate_application' ) );
1554
1555 $this->add_action( 'after_plans_sync', array( &$this, '_check_for_trial_plans' ) );
1556
1557 $this->add_action( 'sdk_version_update', array( &$this, '_sdk_version_update' ), WP_FS__DEFAULT_PRIORITY, 2 );
1558
1559 $this->add_action(
1560 'plugin_version_update',
1561 array( &$this, '_after_version_update' ),
1562 WP_FS__DEFAULT_PRIORITY,
1563 2
1564 );
1565 $this->add_filter( 'after_code_type_change', array( &$this, '_after_code_type_change' ) );
1566
1567 add_action( 'admin_init', array( &$this, '_add_trial_notice' ) ); // @phpstan-ignore-line
1568 add_action( 'admin_init', array( &$this, '_add_affiliate_program_notice' ) ); // @phpstan-ignore-line
1569 add_action( 'admin_enqueue_scripts', array( &$this, '_enqueue_common_css' ) );
1570
1571 /**
1572 * Handle request to reset anonymous mode for `get_reconnect_url()` or reset the pending activation mode.
1573 *
1574 * @author Vova Feldman (@svovaf)
1575 * @since 1.2.1.5
1576 */
1577 if (
1578 (
1579 fs_request_is_action( 'reset_anonymous_mode' ) ||
1580 fs_request_is_action( 'reset_pending_activation_mode' )
1581 ) &&
1582 $this->get_unique_affix() === fs_request_get_raw( 'fs_unique_affix' )
1583 ) {
1584 add_action( 'admin_init', array( &$this, 'connect_again' ) );
1585 }
1586
1587 FS_DebugManager::register_hooks();
1588 }
1589
1590 /**
1591 * Register the required hooks right after the settings parse is completed.
1592 *
1593 * @author Vova Feldman (@svovaf)
1594 * @since 2.3.1
1595 */
1596 private function register_after_settings_parse_hooks() {
1597 if ( is_admin() &&
1598 $this->is_theme() &&
1599 $this->is_premium() &&
1600 ! $this->has_active_valid_license()
1601 ) {
1602 $this->add_ajax_action(
1603 'delete_theme_update_data',
1604 array( &$this, '_delete_theme_update_data_action' )
1605 );
1606 }
1607
1608 if ( $this->show_settings_with_tabs() ) {
1609 /**
1610 * Include the required hooks to capture the theme settings' page tabs
1611 * and cache them.
1612 *
1613 * @author Vova Feldman (@svovaf)
1614 * @since 1.2.2.7
1615 */
1616 if ( ! $this->_cache->has_valid( 'tabs' ) ) {
1617 add_action( 'admin_footer', array( &$this, '_tabs_capture' ) );
1618 // Add license activation AJAX callback.
1619 $this->add_ajax_action( 'store_tabs', array( &$this, '_store_tabs_ajax_action' ) );
1620
1621 add_action( 'admin_enqueue_scripts', array( &$this, '_store_tabs_styles' ), 9999999 );
1622 }
1623
1624 add_action(
1625 'admin_footer',
1626 array( &$this, '_add_freemius_tabs' ),
1627 /**
1628 * The tabs JS code must be executed after the tabs capture logic (_tabs_capture()).
1629 * That's why the priority is 11 while the tabs capture logic is added
1630 * with priority 10.
1631 *
1632 * @author Vova Feldman (@svovaf)
1633 */
1634 11
1635 );
1636 }
1637
1638 if ( ! self::is_ajax() ) {
1639 if ( ! $this->is_addon() || $this->is_only_premium() ) {
1640 add_action(
1641 ( $this->_is_network_active && fs_is_network_admin() ? 'network_' : '' ) . 'admin_menu',
1642 array( &$this, '_prepare_admin_menu' ),
1643 WP_FS__LOWEST_PRIORITY
1644 );
1645 }
1646 }
1647 }
1648
1649 /**
1650 * Makes Freemius-related updates unavailable on the "Add Plugins" admin page (/plugin-install.php) so that
1651 * they won't interfere with the .org plugins' functionalities on that page (e.g. updating of a .org plugin).
1652 *
1653 * @author Leo Fajardo (@leorw)
1654 * @since 2.2.3
1655 *
1656 * @param object $updates
1657 * @param string|null $transient
1658 *
1659 * @return object
1660 */
1661 static function _remove_fs_updates_from_plugin_install_page( $updates, $transient = null ) {
1662 if ( is_object( $updates ) && isset( $updates->response ) ) {
1663 foreach ( $updates->response as $file => $plugin ) {
1664 if ( isset( $plugin->package ) && false !== strpos( $plugin->package, 'api.freemius' ) ) {
1665 unset( $updates->response[ $file ] );
1666 }
1667 }
1668 }
1669
1670 return $updates;
1671 }
1672
1673 /**
1674 * Prepends the `fs_allow_updater_and_dialog` param to the plugin information URLs to tell the SDK to handle
1675 * the information that is shown on the plugin details dialog that is shown when the relevant link is clicked.
1676 *
1677 * @author Leo Fajardo (@leorw)
1678 * @since 2.2.3
1679 *
1680 * @return void
1681 */
1682 static function _prepend_fs_allow_updater_and_dialog_flag_url_param() {
1683 $slug_basename_map = array();
1684 foreach ( self::$_instances as $instance ) {
1685 if ( ! $instance->is_plugin() ) {
1686 continue;
1687 }
1688
1689 $slug_basename_map[ $instance->get_slug() ] = $instance->premium_plugin_basename();
1690 }
1691 ?>
1692 <script type="text/javascript">
1693 (function( $ ) {
1694 var slugBasenameMap = <?php echo json_encode( $slug_basename_map ) ?>;
1695 for ( var slug in slugBasenameMap ) {
1696 var basename = slugBasenameMap[ slug ];
1697
1698 // Try to get the plugin rows if on the "Plugins" page.
1699 var $pluginRows = $( '.wp-list-table.plugins tr[data-plugin="' + basename + '"]');
1700
1701 if ( 0 === $pluginRows.length ) {
1702 // Try to get the plugin rows if on the "Updates" page.
1703 var $pluginCheckbox = $( '#update-plugins-table input[type="checkbox"][value="' + basename + '"]' );
1704 if ( 0 !== $pluginCheckbox.length ) {
1705 $pluginRows = $pluginCheckbox.parents( 'tr:first' );
1706 }
1707 }
1708
1709 if ( 0 === $pluginRows.length ) {
1710 // No plugin rows found.
1711 continue;
1712 }
1713
1714 // Find the "View details" links and add the `fs_allow_updater_and_dialog` param to the URL.
1715 $pluginRows.find( 'a[href*="plugin-install.php?tab=plugin-information"]' ).each(function() {
1716 var $this = $( this ),
1717 href = $this.attr( 'href' ).replace( '?tab=', '?fs_allow_updater_and_dialog=true&tab=');
1718
1719 $this.attr( 'href', href );
1720 });
1721 }
1722 })( jQuery );
1723 </script>
1724 <?php
1725 }
1726
1727 /**
1728 * @author Leo Fajardo (@leorw)
1729 * @since 2.3.0
1730 */
1731 static function _maybe_add_beta_label_styles() {
1732 $has_any_beta_version = false;
1733
1734 foreach ( self::$_instances as $instance ) {
1735 if ( $instance->is_beta() ) {
1736 $has_any_beta_version = true;
1737 break;
1738 }
1739 }
1740
1741 if ( $has_any_beta_version ) {
1742 fs_enqueue_local_style( 'fs_plugins', '/admin/plugins.css' );
1743 }
1744 }
1745
1746 /**
1747 * @author Leo Fajardo (@leorw)
1748 * @since 2.3.0
1749 */
1750 static function _maybe_add_beta_label_to_plugins_and_handle_confirmation() {
1751 $beta_data = array();
1752
1753 foreach ( self::$_instances as $instance ) {
1754 if ( ! $instance->is_premium() ) {
1755 continue;
1756 }
1757
1758 /**
1759 * If there's an available beta version update, a confirmation message will be shown when the
1760 * "Update now" link on the "Plugins" or "Themes" page is clicked.
1761 */
1762 $has_beta_update = $instance->has_beta_update();
1763
1764 $is_beta = (
1765 // The "Beta" label is added separately for themes.
1766 $instance->is_plugin() &&
1767 $instance->is_beta()
1768 );
1769
1770 if ( ! $is_beta && ! $has_beta_update ) {
1771 continue;
1772 }
1773
1774 $beta_data[ $instance->get_plugin_basename() ] = array( 'is_installed_version_beta' => $is_beta );
1775
1776 if ( ! $has_beta_update ) {
1777 continue;
1778 }
1779
1780 $beta_data[ $instance->get_plugin_basename() ]['beta_version_update_confirmation_message'] = sprintf(
1781 '%s %s',
1782 sprintf(
1783 fs_esc_attr_inline(
1784 '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.',
1785 'beta-version-update-caution',
1786 $instance->get_slug()
1787 ),
1788 $instance->get_plugin_title()
1789 ),
1790 fs_esc_attr_inline( 'Would you like to proceed with the update?', 'update-confirmation', $instance->get_slug() )
1791 );
1792 }
1793
1794 if ( empty( $beta_data ) ) {
1795 return;
1796 }
1797 ?>
1798 <script type="text/javascript">
1799 ( function( $ ) {
1800 var betaData = <?php echo json_encode( $beta_data ) ?>;
1801
1802 for ( var pluginBasename in betaData ) {
1803 if ( ! betaData.hasOwnProperty( pluginBasename ) ) {
1804 continue;
1805 }
1806
1807 if ( ! betaData[ pluginBasename ].is_installed_version_beta ) {
1808 continue;
1809 }
1810
1811 var $parentContainer = $( '.wp-list-table.plugins tr[data-plugin="' + pluginBasename + '"]' );
1812 if ( 0 === $parentContainer.length ) {
1813 continue;
1814 }
1815
1816 $parentContainer.find( '.plugin-title > strong:first-child').append(
1817 '<span class="fs-tag fs-info"><?php fs_esc_js_echo_inline( 'Beta', 'beta' ) ?></span>'
1818 );
1819 }
1820
1821 setTimeout( function() {
1822 // Wait a little bit before adding the event handler, otherwise, it will be overridden by the core WP logic.
1823 $( '.plugins .update-message .update-link, .themes .theme .update-message' ).on( 'click', function() {
1824 var $parentContainer = $( this ).parents( 'tr:first' );
1825 pluginBasename = ( 0 !== $parentContainer.length ) ?
1826 $parentContainer.data( 'plugin' ) :
1827 $( this ).parents( '.theme:first' ).data( 'slug' );
1828
1829 if (
1830 betaData[ pluginBasename ] &&
1831 betaData[ pluginBasename ].beta_version_update_confirmation_message &&
1832 ! confirm( betaData[ pluginBasename ].beta_version_update_confirmation_message )
1833 ) {
1834 return false;
1835 }
1836 } );
1837 }, 20 );
1838 } )( jQuery );
1839 </script>
1840 <?php
1841 }
1842
1843 /**
1844 * Keeping the uninstall hook registered for free or premium plugin version may result to a fatal error that
1845 * could happen when a user tries to uninstall either version while one of them is still active. Uninstalling a
1846 * plugin will trigger inclusion of the free or premium version and if one of them is active during the
1847 * uninstallation, a fatal error may occur in case the plugin's class or functions are already defined.
1848 *
1849 * @author Leo Fajardo (@leorw)
1850 *
1851 * @since 1.2.0
1852 */
1853 private function unregister_uninstall_hook() {
1854 $uninstallable_plugins = (array) get_option( 'uninstall_plugins' );
1855 unset( $uninstallable_plugins[ $this->_free_plugin_basename ] );
1856 unset( $uninstallable_plugins[ $this->premium_plugin_basename() ] );
1857
1858 update_option( 'uninstall_plugins', $uninstallable_plugins );
1859 }
1860
1861 /**
1862 * @since 1.2.0 Invalidate module's main file cache, otherwise, FS_Plugin_Updater will not fetch updates.
1863 *
1864 * @param bool $store_prev_path
1865 */
1866 private function clear_module_main_file_cache( $store_prev_path = true ) {
1867 if ( ! isset( $this->_storage->plugin_main_file ) ||
1868 empty( $this->_storage->plugin_main_file->path )
1869 ) {
1870 return;
1871 }
1872
1873 if ( ! $store_prev_path ) {
1874 /**
1875 * Storing the previous path is not needed when clearing the cache after an SDK version update since
1876 * the main purpose of the cache clearing in that event is to correct a wrong plugin main file path
1877 * which causes data mix-up between plugins (e.g. titles and versions of an add-on and its parent plugin).
1878 *
1879 * @author Leo Fajardo (@leorw)
1880 * @since 2.2.1
1881 */
1882 unset( $this->_storage->plugin_main_file->path );
1883 } else {
1884 $plugin_main_file = clone $this->_storage->plugin_main_file;
1885
1886 // Store cached path (2nd layer cache).
1887 $plugin_main_file->prev_path = $plugin_main_file->path;
1888
1889 // Clear cached path.
1890 unset( $plugin_main_file->path );
1891
1892 $this->_storage->plugin_main_file = $plugin_main_file;
1893 }
1894
1895 /**
1896 * Clear global cached path.
1897 *
1898 * @author Leo Fajardo (@leorw)
1899 * @since 1.2.2
1900 */
1901 $id_slug_type_path_map = self::$_accounts->get_option( 'id_slug_type_path_map' );
1902 unset( $id_slug_type_path_map[ $this->_module_id ]['path'] );
1903 self::$_accounts->set_option( 'id_slug_type_path_map', $id_slug_type_path_map, true );
1904 }
1905
1906 /**
1907 * @author Leo Fajardo (@leorw)
1908 * @since 2.0.0
1909 */
1910 function _hook_action_links_and_register_account_hooks() {
1911 if ( $this->is_migration() ) {
1912 return;
1913 }
1914
1915 if (
1916 ( self::is_plugins_page() && $this->is_plugin() ) ||
1917 ( self::is_themes_page() && $this->is_theme() ) ||
1918 fs_request_is_action_secure( $this->get_unique_affix() . '_reconnect' )
1919 ) {
1920 $this->_add_tracking_links();
1921 }
1922
1923 if ( self::is_plugins_page() && $this->is_plugin() ) {
1924 $this->hook_plugin_action_links();
1925 }
1926
1927 $this->_register_account_hooks();
1928 }
1929
1930 /**
1931 * @author Vova Feldman (@svovaf)
1932 * @since 1.0.9
1933 */
1934 private function _register_account_hooks() {
1935 if ( ! is_admin() ) {
1936 return;
1937 }
1938
1939 /**
1940 * Always show the deactivation feedback form since we added
1941 * automatic free version deactivation upon premium code activation.
1942 *
1943 * @since 1.2.1.6
1944 */
1945 $this->add_ajax_action(
1946 'submit_uninstall_reason',
1947 array( &$this, '_submit_uninstall_reason_action' )
1948 );
1949
1950 $this->add_ajax_action(
1951 'cancel_subscription_or_trial',
1952 array( &$this, 'cancel_subscription_or_trial_ajax_action' )
1953 );
1954
1955 if ( ! $this->is_addon() || $this->is_parent_plugin_installed() ) {
1956 if ( ( $this->is_plugin() && self::is_plugins_page() ) ||
1957 ( $this->is_theme() && self::is_themes_page() )
1958 ) {
1959 add_action( 'admin_footer', array( &$this, '_add_deactivation_feedback_dialog_box' ) );
1960 }
1961 }
1962 }
1963
1964 /**
1965 * Leverage backtrace to find caller plugin file path.
1966 *
1967 * @param bool $is_init Is initiation sequence.
1968 * @param string $main_file Since 2.5.0 expects the module's main file path to potentially purge the cached path.
1969 *
1970 * @return string
1971 * @since 1.0.6
1972 *
1973 * @author Vova Feldman (@svovaf)
1974 */
1975 private function _find_caller_plugin_file( $is_init = false, $main_file = '' ) {
1976 // Try to load the cached value of the file path.
1977 if ( isset( $this->_storage->plugin_main_file ) ) {
1978 $plugin_main_file = $this->_storage->plugin_main_file;
1979 if ( ! empty( $plugin_main_file->path ) ) {
1980 $absolute_path = $this->get_absolute_path( $plugin_main_file->path );
1981 if ( file_exists( $absolute_path ) ) {
1982 if ( $is_init && $absolute_path !== $this->get_absolute_path( $main_file ) ) {
1983 // Update cached path if not matching the actual path.
1984 $plugin_main_file->path = $main_file;
1985 $this->_storage->plugin_main_file = $plugin_main_file;
1986 }
1987
1988 return $absolute_path;
1989 }
1990 }
1991 }
1992
1993 /**
1994 * @since 1.2.1
1995 *
1996 * `clear_module_main_file_cache()` is clearing the plugin's cached path on
1997 * deactivation. Therefore, if any plugin/theme was initiating `Freemius`
1998 * with that plugin's slug, it was overriding the empty plugin path with a wrong path.
1999 *
2000 * So, we've added a special mechanism with a 2nd layer of cache that uses `prev_path`
2001 * when the class instantiator isn't the module.
2002 */
2003 if ( ! $is_init ) {
2004 // Fetch prev path cache.
2005 if ( isset( $this->_storage->plugin_main_file ) &&
2006 ! empty( $this->_storage->plugin_main_file->prev_path )
2007 ) {
2008 $absolute_path = $this->get_absolute_path( $this->_storage->plugin_main_file->prev_path );
2009 if ( file_exists( $absolute_path ) ) {
2010 return $absolute_path;
2011 }
2012 }
2013
2014 wp_die(
2015 $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' ) .
2016 " Module: {$this->_slug}; SDK: " . WP_FS__SDK_VERSION . ";",
2017 $this->get_text_inline( 'Error', 'error' ),
2018 array( 'back_link' => true )
2019 );
2020 }
2021
2022 /**
2023 * @since 1.2.1
2024 *
2025 * Only the original instantiator that calls dynamic_init can modify the module's path.
2026 */
2027 // Find caller module.
2028 $this->_storage->plugin_main_file = (object) array(
2029 'path' => $main_file,
2030 );
2031
2032 return $this->get_absolute_path( $main_file );
2033 }
2034
2035 /**
2036 * @author Leo Fajardo (@leorw)
2037 * @since 1.2.3
2038 *
2039 * @param string $path
2040 *
2041 * @return string
2042 */
2043 private function get_relative_path( $path ) {
2044 $module_root_dir = $this->get_module_root_dir_path();
2045 if ( 0 === strpos( $path, $module_root_dir ) ) {
2046 $path = substr( $path, strlen( $module_root_dir ) );
2047 }
2048
2049 return $path;
2050 }
2051
2052 /**
2053 * @author Leo Fajardo (@leorw)
2054 * @since 1.2.3
2055 *
2056 * @param string $path
2057 * @param string|bool $module_type
2058 *
2059 * @return string
2060 */
2061 private function get_absolute_path( $path, $module_type = false ) {
2062 $module_root_dir = $this->get_module_root_dir_path( $module_type );
2063 if ( 0 !== strpos( $path, $module_root_dir ) ) {
2064 $path = fs_normalize_path( $module_root_dir . $path );
2065 }
2066
2067 return $path;
2068 }
2069
2070 /**
2071 * @author Leo Fajardo (@leorw)
2072 * @since 1.2.3
2073 *
2074 * @param string|bool $module_type
2075 *
2076 * @return string
2077 */
2078 private function get_module_root_dir_path( $module_type = false ) {
2079 $is_plugin = empty( $module_type ) ?
2080 $this->is_plugin() :
2081 ( WP_FS__MODULE_TYPE_PLUGIN === $module_type );
2082
2083 return fs_normalize_path( trailingslashit( $is_plugin ?
2084 WP_PLUGIN_DIR :
2085 get_theme_root( get_stylesheet() ) ) );
2086 }
2087
2088 /**
2089 * @author Leo Fajardo (@leorw)
2090 *
2091 * @param number $module_id
2092 * @param string $slug
2093 *
2094 * @return string Since 2.5.0 return the module's main file path.
2095 *
2096 * @since 1.2.2
2097 */
2098 private function store_id_slug_type_path_map( $module_id, $slug ) {
2099 $id_slug_type_path_map = self::$_accounts->get_option( 'id_slug_type_path_map', array() );
2100
2101 $store_option = false;
2102
2103 if ( ! isset( $id_slug_type_path_map[ $module_id ] ) ) {
2104 $id_slug_type_path_map[ $module_id ] = array(
2105 'slug' => $slug
2106 );
2107
2108 $store_option = true;
2109 } else if (
2110 isset( $id_slug_type_path_map[ $module_id ]['slug'] ) &&
2111 $slug !== $id_slug_type_path_map[ $module_id ]['slug']
2112 ) {
2113 $id_slug_type_path_map[ $module_id ]['slug'] = $slug;
2114 $store_option = true;
2115 }
2116
2117 $find_caller = empty( $id_slug_type_path_map[ $module_id ]['path'] );
2118
2119 if ( ! $find_caller ) {
2120 /**
2121 * This verification is for cases when suddenly the same module
2122 * is installed but with a different folder name.
2123 *
2124 * @author Vova Feldman (@svovaf)
2125 * @since 1.2.3
2126 */
2127 $find_caller = ! file_exists( $this->get_absolute_path(
2128 $id_slug_type_path_map[ $module_id ]['path'],
2129 $id_slug_type_path_map[ $module_id ]['type']
2130 ) );
2131 }
2132
2133 foreach ( $id_slug_type_path_map as $id => $data ) {
2134 if ( empty( $id ) ) {
2135 // Remove maps with empty module ID.
2136 unset( $id_slug_type_path_map[ $id ] );
2137 $store_option = true;
2138 continue;
2139 }
2140
2141 /**
2142 * 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.
2143 *
2144 * @author Vova Feldman (@svovaf)
2145 * @since 2.5.0
2146 */
2147 if ( ! $find_caller ) {
2148 if ( $id == $module_id ) {
2149 continue;
2150 }
2151
2152 if (
2153 isset( $data['path'] ) &&
2154 $data['path'] === $id_slug_type_path_map[ $module_id ]['path']
2155 ) {
2156 $find_caller = true;
2157 }
2158 }
2159 }
2160
2161 if ( $find_caller ) {
2162 $caller_main_file_and_type = $this->get_caller_main_file_and_type( $module_id );
2163
2164 $id_slug_type_path_map[ $module_id ]['type'] = $caller_main_file_and_type->module_type;
2165 $id_slug_type_path_map[ $module_id ]['path'] = $caller_main_file_and_type->path;
2166
2167 $store_option = true;
2168 }
2169
2170 if ( $store_option ) {
2171 self::$_accounts->set_option( 'id_slug_type_path_map', $id_slug_type_path_map, true );
2172 }
2173
2174 return $id_slug_type_path_map[ $module_id ]['path'];
2175 }
2176
2177 /**
2178 * Identifies the caller type: plugin or theme.
2179 *
2180 * @author Leo Fajardo (@leorw)
2181 * @since 1.2.2
2182 *
2183 * @author Vova Feldman (@svovaf)
2184 * @since 1.2.2.3 Find the earliest module in the call stack that calls to the SDK. This fix is for cases when
2185 * add-ons are relying on loading the SDK from the parent module, and also allows themes including the
2186 * SDK an internal file instead of directly from functions.php.
2187 * @since 1.2.1.7 Knows how to handle cases when an add-on includes the parent module logic.
2188 *
2189 * @param number $module_id @since 2.5.0
2190 */
2191 private function get_caller_main_file_and_type( $module_id ) {
2192 self::require_plugin_essentials();
2193
2194 $all_plugins = fs_get_plugins( true );
2195 $all_plugins_paths = array();
2196
2197 // Get active plugin's main files real full names (might be symlinks).
2198 foreach ( $all_plugins as $relative_path => $data ) {
2199 if ( false === strpos( fs_normalize_path( $relative_path ), '/' ) ) {
2200 /**
2201 * Ignore plugins that don't have a folder (e.g. Hello Dolly) since they
2202 * can't really include the SDK.
2203 *
2204 * @author Vova Feldman
2205 * @since 1.2.1.7
2206 */
2207 continue;
2208 }
2209
2210 $all_plugins_paths[] = fs_normalize_path( realpath( WP_PLUGIN_DIR . '/' . $relative_path ) );
2211 }
2212
2213 $caller_file_candidate = false;
2214 $caller_map = array();
2215 $module_type = WP_FS__MODULE_TYPE_PLUGIN;
2216 $themes_dir = fs_normalize_path( get_theme_root( get_stylesheet() ) );
2217 $plugin_dir_to_skip = false;
2218
2219 for ( $i = 1, $bt = debug_backtrace(), $len = count( $bt ); $i < $len; $i ++ ) {
2220 if ( empty( $bt[ $i ]['file'] ) ) {
2221 continue;
2222 }
2223
2224 if ( $i > 1 && ! empty( $bt[ $i - 1 ]['file'] ) && $bt[ $i ]['file'] === $bt[ $i - 1 ]['file'] ) {
2225 // If file same as the prev file in the stack, skip it.
2226 continue;
2227 }
2228
2229 if ( ! empty( $bt[ $i ]['function'] ) && in_array( $bt[ $i ]['function'], array(
2230 'do_action',
2231 'apply_filter',
2232 // The string split is stupid, but otherwise, theme check
2233 // throws info notices.
2234 'requir' . 'e_once',
2235 'requir' . 'e',
2236 'includ' . 'e_once',
2237 'includ' . 'e',
2238 'install_and_activate_plugin',
2239 'try_activate_plugin',
2240 'activate_plugin'
2241 ) )
2242 ) {
2243 if ( 'activate_plugin' === $bt[ $i ]['function'] ) {
2244 /**
2245 * Store the directory of the activator plugin so that any other file that starts with it
2246 * cannot be mistakenly chosen as a candidate caller file.
2247 *
2248 * @author Leo Fajardo
2249 *
2250 * @since 2.3.0
2251 */
2252 $caller_file_path = fs_normalize_path( $bt[ $i ]['file'] );
2253
2254 foreach ( $all_plugins_paths as $plugin_path ) {
2255 $plugin_dir = fs_normalize_path( dirname( $plugin_path ) . '/' );
2256 if ( false !== strpos( $caller_file_path, $plugin_dir ) ) {
2257 $plugin_dir_to_skip = $plugin_dir;
2258
2259 break;
2260 }
2261 }
2262 }
2263
2264 // Ignore call stack hooks and files inclusion.
2265 continue;
2266 }
2267
2268 $caller_file_path = fs_normalize_path( $bt[ $i ]['file'] );
2269
2270 if ( ! empty( $plugin_dir_to_skip ) ) {
2271 /**
2272 * Skip if it's an activator plugin file to avoid mistakenly choosing it as a candidate caller file.
2273 *
2274 * @author Leo Fajardo
2275 *
2276 * @since 2.3.0
2277 */
2278 if ( 0 === strpos( $caller_file_path, $plugin_dir_to_skip ) ) {
2279 continue;
2280 }
2281 }
2282
2283 if ( 'functions.php' === basename( $caller_file_path ) ) {
2284 /**
2285 * 1. Assumes that theme's starting execution file is functions.php.
2286 * 2. This complex logic fixes symlink issues (e.g. with Vargant).
2287 *
2288 * @author Vova Feldman (@svovaf)
2289 * @since 1.2.2.5
2290 */
2291
2292 if ( $caller_file_path == fs_normalize_path( realpath( trailingslashit( $themes_dir ) . basename( dirname( $caller_file_path ) ) . '/' . basename( $caller_file_path ) ) ) ) {
2293 $module_type = WP_FS__MODULE_TYPE_THEME;
2294
2295 /**
2296 * Relative path of the theme, e.g.:
2297 * `my-theme/functions.php`
2298 *
2299 * @author Leo Fajardo (@leorw)
2300 */
2301 $caller_file_candidate = basename( dirname( $caller_file_path ) ) .
2302 '/' .
2303 basename( $caller_file_path );
2304
2305 continue;
2306 }
2307 }
2308
2309 $caller_file_hash = md5( $caller_file_path );
2310
2311 if ( ! isset( $caller_map[ $caller_file_hash ] ) ) {
2312 foreach ( $all_plugins_paths as $plugin_path ) {
2313 if ( empty( $plugin_path ) ) {
2314 continue;
2315 }
2316
2317 if ( false !== strpos( $caller_file_path, fs_normalize_path( dirname( $plugin_path ) . '/' ) ) ) {
2318 $caller_map[ $caller_file_hash ] = fs_normalize_path( $plugin_path );
2319 break;
2320 }
2321 }
2322 }
2323
2324 if ( isset( $caller_map[ $caller_file_hash ] ) ) {
2325 $module_type = WP_FS__MODULE_TYPE_PLUGIN;
2326 $caller_file_candidate = plugin_basename( $caller_map[ $caller_file_hash ] );
2327 }
2328 }
2329
2330 $caller_main_file_and_type = (object) array(
2331 'module_type' => $module_type,
2332 'path' => $caller_file_candidate
2333 );
2334
2335 return apply_filters( "fs_{$module_id}_caller_main_file_and_type", $caller_main_file_and_type );
2336 }
2337
2338 #----------------------------------------------------------------------------------
2339 #region Deactivation Feedback Form
2340 #----------------------------------------------------------------------------------
2341
2342 /**
2343 * Displays a confirmation and feedback dialog box when the user clicks on the "Deactivate" link on the plugins
2344 * page.
2345 *
2346 * @author Vova Feldman (@svovaf)
2347 * @author Leo Fajardo (@leorw)
2348 *
2349 * @since 1.1.2
2350 */
2351 function _add_deactivation_feedback_dialog_box() {
2352 if (
2353 $this->is_clone() ||
2354 ( is_object( $this->_site ) && ! $this->is_registered() )
2355 ) {
2356 return;
2357 }
2358
2359 $subscription_cancellation_dialog_box_template_params = $this->apply_filters( 'show_deactivation_subscription_cancellation', true ) ?
2360 $this->_get_subscription_cancellation_dialog_box_template_params() :
2361 array();
2362
2363 /**
2364 * @since 2.3.0 Developers can optionally hide the deactivation feedback form using the 'show_deactivation_feedback_form' filter.
2365 */
2366 $show_deactivation_feedback_form = ! self::is_deactivation_snoozed();
2367 if ( $this->has_filter( 'show_deactivation_feedback_form' ) ) {
2368 $show_deactivation_feedback_form = $this->apply_filters( 'show_deactivation_feedback_form', true );
2369 } else if ( $this->is_addon() ) {
2370 /**
2371 * If the add-on's 'show_deactivation_feedback_form' is not set, try to inherit the value from the parent.
2372 */
2373 $show_deactivation_feedback_form = $this->get_parent_instance()->apply_filters( 'show_deactivation_feedback_form', true );
2374 }
2375
2376 $uninstall_confirmation_message = $this->apply_filters( 'uninstall_confirmation_message', '' );
2377
2378 if (
2379 empty( $subscription_cancellation_dialog_box_template_params ) &&
2380 ! $show_deactivation_feedback_form &&
2381 empty( $uninstall_confirmation_message )
2382 ) {
2383 return;
2384 }
2385
2386 $vars = array( 'id' => $this->_module_id );
2387
2388 if ( $show_deactivation_feedback_form ) {
2389 /* Check the type of user:
2390 * 1. Long-term (long-term)
2391 * 2. Non-registered and non-anonymous short-term (non-registered-and-non-anonymous-short-term).
2392 * 3. Short-term (short-term)
2393 */
2394 $is_long_term_user = true;
2395
2396 // Check if the site is at least 2 days old.
2397 $time_installed = $this->_storage->install_timestamp;
2398
2399 // Difference in seconds.
2400 $date_diff = time() - $time_installed;
2401
2402 // Convert seconds to days.
2403 $date_diff_days = floor( $date_diff / ( 60 * 60 * 24 ) );
2404
2405 if ( $date_diff_days < 2 ) {
2406 $is_long_term_user = false;
2407 }
2408
2409 $is_long_term_user = $this->apply_filters( 'is_long_term_user', $is_long_term_user );
2410
2411 if ( $is_long_term_user ) {
2412 $user_type = 'long-term';
2413 } else {
2414 if ( ! $this->is_registered() && ! $this->is_anonymous() ) {
2415 $user_type = 'non-registered-and-non-anonymous-short-term';
2416 } else {
2417 $user_type = 'short-term';
2418 }
2419 }
2420
2421 $uninstall_reasons = $this->_get_uninstall_reasons( $user_type );
2422
2423 $vars['reasons'] = $uninstall_reasons;
2424 }
2425
2426 $vars['subscription_cancellation_dialog_box_template_params'] = &$subscription_cancellation_dialog_box_template_params;
2427 $vars['show_deactivation_feedback_form'] = $show_deactivation_feedback_form;
2428 $vars['uninstall_confirmation_message'] = $uninstall_confirmation_message;
2429
2430 /**
2431 * Load the HTML template for the deactivation feedback dialog box.
2432 *
2433 * @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.
2434 */
2435 fs_require_template( 'forms/deactivation/form.php', $vars );
2436 }
2437
2438 /**
2439 * @author Leo Fajardo (@leorw)
2440 * @since 1.1.2
2441 *
2442 * @param string $user_type
2443 *
2444 * @return array The uninstall reasons for the specified user type.
2445 */
2446 function _get_uninstall_reasons( $user_type = 'long-term' ) {
2447 $module_type = $this->_module_type;
2448
2449 $internal_message_template_var = array(
2450 'id' => $this->_module_id
2451 );
2452
2453 $plan = $this->get_plan();
2454
2455 if ( $this->is_registered() && is_object( $plan ) && $plan->has_technical_support() ) {
2456 $contact_support_template = fs_get_template( 'forms/deactivation/contact.php', $internal_message_template_var );
2457 } else {
2458 $contact_support_template = '';
2459 }
2460
2461 $reason_found_better_plugin = array(
2462 'id' => self::REASON_FOUND_A_BETTER_PLUGIN,
2463 'text' => sprintf( $this->get_text_inline( 'I found a better %s', 'reason-found-a-better-plugin' ), $module_type ),
2464 'input_type' => 'textfield',
2465 'input_placeholder' => sprintf( $this->get_text_inline( "What's the %s's name?", 'placeholder-plugin-name' ), $module_type ),
2466 );
2467
2468 $reason_temporary_deactivation = array(
2469 'id' => self::REASON_TEMPORARY_DEACTIVATION,
2470 'text' => sprintf(
2471 $this->get_text_inline( "It's a temporary %s - I'm troubleshooting an issue", 'reason-temporary-x' ),
2472 strtolower( $this->is_plugin() ?
2473 $this->get_text_inline( 'Deactivation', 'deactivation' ) :
2474 $this->get_text_inline( 'Theme Switch', 'theme-switch' )
2475 )
2476 ),
2477 'input_type' => '',
2478 'input_placeholder' => ''
2479 );
2480
2481 $reason_other = array(
2482 'id' => self::REASON_OTHER,
2483 'text' => $this->get_text_inline( 'Other', 'reason-other' ),
2484 'input_type' => 'textfield',
2485 'input_placeholder' => ''
2486 );
2487
2488 $long_term_user_reasons = array(
2489 array(
2490 'id' => self::REASON_NO_LONGER_NEEDED,
2491 'text' => sprintf( $this->get_text_inline( 'I no longer need the %s', 'reason-no-longer-needed' ), $module_type ),
2492 'input_type' => '',
2493 'input_placeholder' => ''
2494 ),
2495 $reason_found_better_plugin,
2496 array(
2497 'id' => self::REASON_NEEDED_FOR_A_SHORT_PERIOD,
2498 'text' => sprintf( $this->get_text_inline( 'I only needed the %s for a short period', 'reason-needed-for-a-short-period' ), $module_type ),
2499 'input_type' => '',
2500 'input_placeholder' => ''
2501 ),
2502 array(
2503 'id' => self::REASON_BROKE_MY_SITE,
2504 'text' => sprintf( $this->get_text_inline( 'The %s broke my site', 'reason-broke-my-site' ), $module_type ),
2505 'input_type' => '',
2506 'input_placeholder' => '',
2507 'internal_message' => $contact_support_template
2508 ),
2509 array(
2510 'id' => self::REASON_SUDDENLY_STOPPED_WORKING,
2511 'text' => sprintf( $this->get_text_inline( 'The %s suddenly stopped working', 'reason-suddenly-stopped-working' ), $module_type ),
2512 'input_type' => '',
2513 'input_placeholder' => '',
2514 'internal_message' => $contact_support_template
2515 )
2516 );
2517
2518 if ( $this->is_paying() ) {
2519 $long_term_user_reasons[] = array(
2520 'id' => self::REASON_CANT_PAY_ANYMORE,
2521 'text' => $this->get_text_inline( "I can't pay for it anymore", 'reason-cant-pay-anymore' ),
2522 'input_type' => 'textfield',
2523 'input_placeholder' => $this->get_text_inline( 'What price would you feel comfortable paying?', 'placeholder-comfortable-price' )
2524 );
2525 }
2526
2527 $reason_dont_share_info = array(
2528 'id' => self::REASON_DONT_LIKE_TO_SHARE_MY_INFORMATION,
2529 'text' => $this->get_text_inline( "I don't like to share my information with you", 'reason-dont-like-to-share-my-information' ),
2530 'input_type' => '',
2531 'input_placeholder' => ''
2532 );
2533
2534 /**
2535 * If the current user has selected the "don't share data" reason in the deactivation feedback modal, inform the
2536 * user by showing additional message that he doesn't have to share data and can just choose to skip the opt-in
2537 * (the Skip button is included in the message to show). This message will only be shown if anonymous mode is
2538 * enabled and the user's account is currently not in pending activation state (similar to the way the Skip
2539 * button in the opt-in form is shown/hidden).
2540 */
2541 if ( $this->is_enable_anonymous() && ! $this->is_pending_activation() ) {
2542 $reason_dont_share_info['internal_message'] = fs_get_template( 'forms/deactivation/retry-skip.php', $internal_message_template_var );
2543 }
2544
2545 $uninstall_reasons = array(
2546 'long-term' => $long_term_user_reasons,
2547 'non-registered-and-non-anonymous-short-term' => array(
2548 array(
2549 'id' => self::REASON_DIDNT_WORK,
2550 'text' => sprintf( $this->get_text_inline( "The %s didn't work", 'reason-didnt-work' ), $module_type ),
2551 'input_type' => '',
2552 'input_placeholder' => ''
2553 ),
2554 $reason_dont_share_info,
2555 $reason_found_better_plugin
2556 ),
2557 'short-term' => array(
2558 array(
2559 'id' => self::REASON_COULDNT_MAKE_IT_WORK,
2560 'text' => $this->get_text_inline( "I couldn't understand how to make it work", 'reason-couldnt-make-it-work' ),
2561 'input_type' => '',
2562 'input_placeholder' => '',
2563 'internal_message' => $contact_support_template
2564 ),
2565 $reason_found_better_plugin,
2566 array(
2567 'id' => self::REASON_GREAT_BUT_NEED_SPECIFIC_FEATURE,
2568 '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 ),
2569 'input_type' => 'textarea',
2570 'input_placeholder' => $this->get_text_inline( 'What feature?', 'placeholder-feature' )
2571 ),
2572 array(
2573 'id' => self::REASON_NOT_WORKING,
2574 'text' => sprintf( $this->get_text_inline( 'The %s is not working', 'reason-not-working' ), $module_type ),
2575 'input_type' => 'textarea',
2576 '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' )
2577 ),
2578 array(
2579 'id' => self::REASON_NOT_WHAT_I_WAS_LOOKING_FOR,
2580 'text' => $this->get_text_inline( "It's not what I was looking for", 'reason-not-what-i-was-looking-for' ),
2581 'input_type' => 'textarea',
2582 'input_placeholder' => $this->get_text_inline( "What you've been looking for?", 'placeholder-what-youve-been-looking-for' )
2583 ),
2584 array(
2585 'id' => self::REASON_DIDNT_WORK_AS_EXPECTED,
2586 'text' => sprintf( $this->get_text_inline( "The %s didn't work as expected", 'reason-didnt-work-as-expected' ), $module_type ),
2587 'input_type' => 'textarea',
2588 'input_placeholder' => $this->get_text_inline( 'What did you expect?', 'placeholder-what-did-you-expect' )
2589 )
2590 )
2591 );
2592
2593 // Randomize the reasons for the current user type.
2594 shuffle( $uninstall_reasons[ $user_type ] );
2595
2596 // Keep the following reasons as the last items in the list.
2597 $uninstall_reasons[ $user_type ][] = $reason_temporary_deactivation;
2598 $uninstall_reasons[ $user_type ][] = $reason_other;
2599
2600 $uninstall_reasons = $this->apply_filters( 'uninstall_reasons', $uninstall_reasons );
2601
2602 return $uninstall_reasons[ $user_type ];
2603 }
2604
2605 /**
2606 * Called after the user has submitted his reason for deactivating the plugin.
2607 *
2608 * @author Leo Fajardo (@leorw)
2609 * @since 1.1.2
2610 */
2611 function _submit_uninstall_reason_action() {
2612 $this->_logger->entrance();
2613
2614 $this->check_ajax_referer( 'submit_uninstall_reason' );
2615
2616 $reason_id = fs_request_get( 'reason_id' );
2617
2618 // Check if the given reason ID is an unsigned integer.
2619 if ( ! ctype_digit( $reason_id ) ) {
2620 exit;
2621 }
2622
2623 $reason_info = trim( fs_request_get( 'reason_info', '' ) );
2624 if ( ! empty( $reason_info ) ) {
2625 $reason_info = substr( $reason_info, 0, 128 );
2626 }
2627
2628 $reason = (object) array(
2629 'id' => $reason_id,
2630 'info' => $reason_info,
2631 'is_anonymous' => fs_request_get_bool( 'is_anonymous' )
2632 );
2633
2634 $this->_storage->store( 'uninstall_reason', $reason );
2635
2636 if ( self::REASON_TEMPORARY_DEACTIVATION == $reason->id ) {
2637 $snooze_period = fs_request_get( 'snooze_period' );
2638
2639 if ( is_numeric( $snooze_period ) && 0 < $snooze_period ) {
2640 self::snooze_deactivation_form( (int) $snooze_period );
2641 }
2642 }
2643
2644 /**
2645 * If the module type is "theme", trigger the uninstall event here (on theme deactivation) since themes do
2646 * not support uninstall hook.
2647 *
2648 * @author Leo Fajardo (@leorw)
2649 * @since 1.2.2
2650 */
2651 if ( $this->is_theme() ) {
2652 if ( $this->is_premium() && ! $this->has_active_valid_license() ) {
2653 FS_Plugin_Updater::instance( $this )->delete_update_data();
2654 }
2655
2656 $this->_uninstall_plugin_event( false );
2657 $this->remove_sdk_reference();
2658 }
2659
2660 // Print '1' for successful operation.
2661 echo 1;
2662 exit;
2663 }
2664
2665 #--------------------------------------------------------------------------------
2666 #region Deactivation Feedback Snoozing
2667 #--------------------------------------------------------------------------------
2668
2669 /**
2670 * @author Vova Feldman (@svovaf)
2671 * @since 2.4.3
2672 *
2673 * @param int $period
2674 *
2675 * @return bool True if the value was set, false otherwise.
2676 */
2677 private static function snooze_deactivation_form( $period ) {
2678 return ( 0 < $period && self::reset_deactivation_snoozing( $period ) );
2679 }
2680
2681 /**
2682 * Check if deactivation feedback form is snoozed.
2683 *
2684 * @author Vova Feldman (@svovaf)
2685 * @since 2.4.3
2686 *
2687 * @return bool
2688 */
2689 static function is_deactivation_snoozed() {
2690 $is_snoozed = ( ! is_multisite() || fs_is_network_admin() ) ?
2691 get_transient( 'fs_snooze_period' ) :
2692 get_site_transient( 'fs_snooze_period' );
2693
2694
2695 return ( 'true' === $is_snoozed );
2696 }
2697
2698 /**
2699 * Reset deactivation snoozing. When `$period` is `0` will stop deactivation snoozing by deleting the transients. Otherwise, will set the transients for the selected period.
2700 *
2701 * @param int $period Period in seconds.
2702 *
2703 * @author Vova Feldman (@svovaf)
2704 * @since 2.4.3
2705 */
2706 public static function reset_deactivation_snoozing( $period = 0 ) {
2707 $value = ( 0 === $period ) ? null : 'true';
2708
2709 if ( ! is_multisite() || fs_is_network_admin() ) {
2710 return set_transient( 'fs_snooze_period', $value, $period );
2711 } else {
2712 return set_site_transient( 'fs_snooze_period', $value, $period );
2713 }
2714 }
2715
2716 /**
2717 * The deactivation snooze expiration UNIX timestamp (in sec).
2718 *
2719 * @author Vova Feldman (@svovaf)
2720 * @since 2.4.3
2721 *
2722 * @return int
2723 */
2724 static function deactivation_snooze_expires_at() {
2725 return ( ! is_multisite() || fs_is_network_admin() ) ?
2726 (int) get_option( '_transient_timeout_fs_snooze_period' ) :
2727 (int) get_site_option( '_site_transient_timeout_fs_snooze_period' );
2728 }
2729
2730 #endregion
2731
2732 /**
2733 * @author Leo Fajardo (@leorw)
2734 * @since 2.1.4
2735 */
2736 function cancel_subscription_or_trial_ajax_action() {
2737 $this->_logger->entrance();
2738
2739 $this->check_ajax_referer( 'cancel_subscription_or_trial' );
2740
2741 $result = $this->cancel_subscription_or_trial( fs_request_get( 'plugin_id', $this->get_id() ), false );
2742
2743 if ( $this->is_api_error( $result ) ) {
2744 $this->shoot_ajax_failure( $result->error->message );
2745 }
2746
2747 $this->shoot_ajax_success();
2748 }
2749
2750 /**
2751 * @author Leo Fajardo (@leorw)
2752 * @since 2.1.4
2753 *
2754 * @param number $plugin_id
2755 *
2756 * @return object
2757 */
2758 private function cancel_subscription_or_trial( $plugin_id ) {
2759 $fs = null;
2760 if ( $plugin_id == $this->get_id() ) {
2761 $fs = $this;
2762 } else if ( $this->is_addon_activated( $plugin_id ) ) {
2763 $fs = self::get_instance_by_id( $plugin_id );
2764 }
2765
2766 $result = null;
2767
2768 if ( ! is_null( $fs ) ) {
2769 $result = $fs->is_paid_trial() ?
2770 $fs->_cancel_trial() :
2771 $fs->_downgrade_site();
2772 }
2773
2774 return $result;
2775 }
2776
2777 /**
2778 * @author Leo Fajardo (@leorw)
2779 * @since 2.0.2
2780 */
2781 function _delete_theme_update_data_action() {
2782 FS_Plugin_Updater::instance( $this )->delete_update_data();
2783 }
2784
2785 #endregion
2786
2787 #----------------------------------------------------------------------------------
2788 #region Instance
2789 #----------------------------------------------------------------------------------
2790
2791 /**
2792 * Main singleton instance.
2793 *
2794 * @author Vova Feldman (@svovaf)
2795 * @since 1.0.0
2796 *
2797 * @param number $module_id
2798 * @param string|bool $slug
2799 * @param bool $is_init Is initiation sequence.
2800 *
2801 * @return Freemius|false
2802 */
2803 static function instance( $module_id, $slug = false, $is_init = false ) {
2804 if ( empty( $module_id ) ) {
2805 return false;
2806 }
2807
2808 /**
2809 * 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.
2810 */
2811 self::_load_required_static();
2812
2813 if ( ! is_numeric( $module_id ) ) {
2814 if ( ! $is_init && true === $slug ) {
2815 $is_init = true;
2816 }
2817
2818 $slug = $module_id;
2819
2820 $module = FS_Plugin_Manager::instance( $slug )->get();
2821
2822 if ( is_object( $module ) ) {
2823 $module_id = $module->id;
2824 }
2825 }
2826
2827 $key = 'm_' . $module_id;
2828
2829 if ( ! isset( self::$_instances[ $key ] ) ) {
2830 self::$_instances[ $key ] = new Freemius( $module_id, $slug, $is_init );
2831 }
2832
2833 return self::$_instances[ $key ];
2834 }
2835
2836 /**
2837 * @author Vova Feldman (@svovaf)
2838 * @since 1.0.6
2839 *
2840 * @param number $addon_id
2841 *
2842 * @return bool
2843 */
2844 private static function has_instance( $addon_id ) {
2845 return isset( self::$_instances[ 'm_' . $addon_id ] );
2846 }
2847
2848 /**
2849 * @author Leo Fajardo (@leorw)
2850 * @since 1.2.2
2851 *
2852 * @param string|number $id_or_slug
2853 * @param string $module_type
2854 *
2855 * @return number|false
2856 */
2857 private static function get_module_id( $id_or_slug, $module_type = WP_FS__MODULE_TYPE_PLUGIN ) {
2858 if ( is_numeric( $id_or_slug ) ) {
2859 return $id_or_slug;
2860 }
2861
2862 foreach ( self::$_instances as $instance ) {
2863 // Also check the module type since there can be a plugin and a theme with the same slug.
2864 if ( ( $module_type === $instance->get_module_type() ) && ( $id_or_slug === $instance->get_slug() ) ) {
2865 return $instance->get_id();
2866 }
2867 }
2868
2869 return false;
2870 }
2871
2872 /**
2873 * @author Vova Feldman (@svovaf)
2874 * @since 1.0.6
2875 *
2876 * @param number $id
2877 *
2878 * @return false|Freemius
2879 */
2880 static function get_instance_by_id( $id ) {
2881 return isset ( self::$_instances[ 'm_' . $id ] ) ?
2882 self::$_instances[ 'm_' . $id ] :
2883 false;
2884 }
2885
2886 /**
2887 *
2888 * @author Vova Feldman (@svovaf)
2889 * @since 1.0.1
2890 *
2891 * @param string $plugin_file
2892 * @param string $module_type
2893 *
2894 * @return false|Freemius
2895 */
2896 static function get_instance_by_file( $plugin_file, $module_type = WP_FS__MODULE_TYPE_PLUGIN ) {
2897 $slug = self::find_slug_by_basename( $plugin_file );
2898
2899 return ( false !== $slug ) ?
2900 self::instance( self::get_module_id( $slug, $module_type ) ) :
2901 false;
2902 }
2903
2904 /**
2905 * @author Vova Feldman (@svovaf)
2906 * @since 1.0.6
2907 *
2908 * @return false|Freemius
2909 */
2910 function get_parent_instance() {
2911 return self::get_instance_by_id( $this->_plugin->parent_plugin_id );
2912 }
2913
2914 /**
2915 * @author Vova Feldman (@svovaf)
2916 * @since 1.0.6
2917 *
2918 * @param string|number $id_or_slug
2919 *
2920 * @return false|Freemius
2921 */
2922 function get_addon_instance( $id_or_slug ) {
2923 $addon_id = self::get_module_id( $id_or_slug );
2924
2925 return self::instance( $addon_id );
2926 }
2927
2928 /**
2929 * @return Freemius[]
2930 */
2931 static function _get_all_instances() {
2932 return self::$_instances;
2933 }
2934
2935 #endregion ------------------------------------------------------------------
2936
2937 /**
2938 * @author Vova Feldman (@svovaf)
2939 * @since 1.0.6
2940 *
2941 * @return bool
2942 */
2943 function is_parent_plugin_installed() {
2944 $is_active = self::has_instance( $this->_plugin->parent_plugin_id );
2945
2946 if ( $is_active ) {
2947 return true;
2948 }
2949
2950 /**
2951 * Parent module might be a theme. If that's the case, the add-on's FS
2952 * instance will be loaded prior to the theme's FS instance, therefore,
2953 * we need to check if it's active with a "look ahead".
2954 *
2955 * @author Vova Feldman
2956 * @since 1.2.2.3
2957 */
2958 global $fs_active_plugins;
2959 if ( is_object( $fs_active_plugins ) && is_array( $fs_active_plugins->plugins ) ) {
2960 $active_theme = wp_get_theme();
2961
2962 foreach ( $fs_active_plugins->plugins as $sdk => $module ) {
2963 if ( WP_FS__MODULE_TYPE_THEME === $module->type ) {
2964 if ( $module->plugin_path == $active_theme->get_stylesheet() ) {
2965 // Parent module is a theme and it's currently active.
2966 return true;
2967 }
2968 }
2969 }
2970 }
2971
2972 return false;
2973 }
2974
2975 /**
2976 * Check if add-on parent plugin in activation mode.
2977 *
2978 * @author Vova Feldman (@svovaf)
2979 * @since 1.0.7
2980 *
2981 * @return bool
2982 */
2983 function is_parent_in_activation() {
2984 $parent_fs = $this->get_parent_instance();
2985 if ( ! is_object( $parent_fs ) ) {
2986 return false;
2987 }
2988
2989 return ( $parent_fs->is_activation_mode() );
2990 }
2991
2992 /**
2993 * Is plugin in activation mode.
2994 *
2995 * @author Vova Feldman (@svovaf)
2996 * @since 1.0.7
2997 *
2998 * @param bool $and_on
2999 *
3000 * @return bool
3001 */
3002 function is_activation_mode( $and_on = true ) {
3003 return fs_is_network_admin() ?
3004 $this->is_network_activation_mode( $and_on ) :
3005 $this->is_site_activation_mode( $and_on );
3006 }
3007
3008 /**
3009 * Is plugin in activation mode.
3010 *
3011 * @author Vova Feldman (@svovaf)
3012 * @since 1.0.7
3013 *
3014 * @param bool $and_on
3015 *
3016 * @return bool
3017 */
3018 function is_site_activation_mode( $and_on = true ) {
3019 return (
3020 ( $this->is_on() || ! $and_on ) &&
3021 (
3022 ( $this->is_premium() && true === $this->_storage->require_license_activation ) ||
3023 (
3024 ( ! $this->is_registered() ||
3025 ( $this->is_only_premium() && ! $this->has_features_enabled_license() ) ) &&
3026 ( ! $this->is_enable_anonymous() ||
3027 ( ! $this->is_anonymous() && ! $this->is_pending_activation() ) )
3028 )
3029 )
3030 );
3031 }
3032
3033 /**
3034 * Checks if the SDK in network activation mode.
3035 *
3036 * @author Leo Fajardo (@leorw)
3037 * @since 2.0.0
3038 *
3039 * @param bool $and_on
3040 *
3041 * @return bool
3042 */
3043 private function is_network_activation_mode( $and_on = true ) {
3044 if ( ! $this->_is_network_active ) {
3045 // Not network activated.
3046 return false;
3047 }
3048
3049 if ( $this->is_network_upgrade_mode() ) {
3050 // Special flag to enforce network activation mode to decide what to do with the sites that are not yet opted-in nor skipped.
3051 return true;
3052 }
3053
3054 if ( ! $this->is_site_activation_mode( $and_on ) ) {
3055 // 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.
3056 return false;
3057 }
3058
3059 if ( $this->is_network_delegated_connection() ) {
3060 // Super-admin delegated the connection to the site admins -> not activation mode.
3061 return false;
3062 }
3063
3064 if ( $this->is_network_anonymous() && true !== $this->_storage->require_license_activation ) {
3065 // Super-admin skipped the connection network wide -> not activation mode.
3066 return false;
3067 }
3068
3069 if ( $this->is_network_registered() ) {
3070 // Super-admin connected at least one site -> not activation mode.
3071 return false;
3072 }
3073
3074 return true;
3075 }
3076
3077 /**
3078 * Check if current page is the opt-in/pending-activation page.
3079 *
3080 * @author Vova Feldman (@svovaf)
3081 * @since 1.2.1.7
3082 *
3083 * @return bool
3084 */
3085 function is_activation_page() {
3086 if ( $this->_menu->is_activation_page( $this->show_opt_in_on_themes_page() ) ) {
3087 return true;
3088 }
3089
3090 if ( ! $this->is_activation_mode() ) {
3091 return false;
3092 }
3093
3094 // Check if current page is matching the activation page.
3095 return $this->is_matching_url( $this->get_activation_url() );
3096 }
3097
3098 /**
3099 * Check if URL path's are matching and that all querystring
3100 * arguments of the $sub_url exist in the $url with the same values.
3101 *
3102 * WARNING:
3103 * 1. This method doesn't check if the sub/domain are matching.
3104 * 2. Ignore case sensitivity.
3105 *
3106 * @author Vova Feldman (@svovaf)
3107 * @since 1.2.1.7
3108 *
3109 * @param string $sub_url
3110 * @param string $url If argument is not set, check if the sub_url matching the current's page URL.
3111 *
3112 * @return bool
3113 */
3114 private function is_matching_url( $sub_url, $url = '' ) {
3115 if ( empty( $url ) ) {
3116 $url = $_SERVER['REQUEST_URI'];
3117 }
3118
3119 $url = strtolower( $url );
3120 $sub_url = strtolower( $sub_url );
3121
3122 if ( parse_url( $sub_url, PHP_URL_PATH ) !== parse_url( $url, PHP_URL_PATH ) ) {
3123 // Different path - DO NOT OVERRIDE PAGE.
3124 return false;
3125 }
3126
3127 $url_params = fs_parse_url_params( $url );
3128 $sub_url_params = fs_parse_url_params( $sub_url );
3129
3130 foreach ( $sub_url_params as $key => $val ) {
3131 if ( ! isset( $url_params[ $key ] ) || $val != $url_params[ $key ] ) {
3132 // Not matching query string - DO NOT OVERRIDE PAGE.
3133 return false;
3134 }
3135 }
3136
3137 return true;
3138 }
3139
3140 /**
3141 * Get the basenames of all active plugins for specific blog. Including network activated plugins.
3142 *
3143 * @author Vova Feldman (@svovaf)
3144 * @since 2.0.0
3145 *
3146 * @param int $blog_id
3147 *
3148 * @return string[]
3149 */
3150 private static function get_active_plugins_basenames( $blog_id = 0 ) {
3151 if ( is_multisite() && $blog_id > 0 ) {
3152 $active_basenames = get_blog_option( $blog_id, 'active_plugins' );
3153 } else {
3154 $active_basenames = get_option( 'active_plugins' );
3155 }
3156
3157 if ( ! is_array( $active_basenames ) ) {
3158 $active_basenames = array();
3159 }
3160
3161 if ( is_multisite() ) {
3162 $network_active_basenames = get_site_option( 'active_sitewide_plugins' );
3163
3164 if ( is_array( $network_active_basenames ) && ! empty( $network_active_basenames ) ) {
3165 $active_basenames = array_merge( $active_basenames, array_keys( $network_active_basenames ) );
3166 }
3167 }
3168
3169 return $active_basenames;
3170 }
3171
3172 /**
3173 * @author Leo Fajardo (@leorw)
3174 * @since 2.3.0
3175 *
3176 * @param int $blog_id
3177 *
3178 * @return array
3179 */
3180 static function get_active_plugins_directories_map( $blog_id = 0 ) {
3181 $active_basenames = self::get_active_plugins_basenames( $blog_id );
3182
3183 $map = array();
3184
3185 foreach ( $active_basenames as $active_basename ) {
3186 $active_basename = fs_normalize_path( $active_basename );
3187
3188 if ( false === strpos( $active_basename, '/' ) ) {
3189 continue;
3190 }
3191
3192 $map[ dirname( $active_basename ) ] = true;
3193 }
3194
3195 return $map;
3196 }
3197
3198 /**
3199 * Get collection of all active plugins. Including network activated plugins.
3200 *
3201 * @author Vova Feldman (@svovaf)
3202 * @since 1.0.9
3203 *
3204 * @param int $blog_id Since 2.0.0
3205 *
3206 * @return array[string]array
3207 */
3208 private static function get_active_plugins( $blog_id = 0 ) {
3209 self::require_plugin_essentials();
3210
3211 $active_plugin = array();
3212 $all_plugins = fs_get_plugins();
3213 $active_plugins_basenames = self::get_active_plugins_basenames( $blog_id );
3214
3215 foreach ( $active_plugins_basenames as $plugin_basename ) {
3216 $active_plugin[ $plugin_basename ] = $all_plugins[ $plugin_basename ];
3217 }
3218
3219 return $active_plugin;
3220 }
3221
3222 /**
3223 * Get collection of all site active plugins for a specified blog.
3224 *
3225 * @author Vova Feldman (@svovaf)
3226 * @since 2.0.0
3227 *
3228 * @param int $blog_id
3229 *
3230 * @return array[string]array
3231 */
3232 private static function get_site_active_plugins( $blog_id = 0 ) {
3233 $active_basenames = ( is_multisite() && $blog_id > 0 ) ?
3234 get_blog_option( $blog_id, 'active_plugins' ) :
3235 get_option( 'active_plugins' );
3236
3237 $active = array();
3238
3239 if ( ! is_array( $active_basenames ) ) {
3240 return $active;
3241 }
3242
3243 foreach ( $active_basenames as $basename ) {
3244 $active[ $basename ] = array(
3245 'is_active' => true,
3246 'Version' => '1.0', // Dummy version.
3247 'slug' => self::get_plugin_slug( $basename ),
3248 );
3249 }
3250
3251 return $active;
3252 }
3253
3254 /**
3255 * Get collection of all plugins with their activation status for a specified blog.
3256 *
3257 * @author Vova Feldman (@svovaf)
3258 * @since 1.1.8
3259 *
3260 * @param int $blog_id Since 2.0.0
3261 *
3262 * @return array Key is the plugin file path and the value is an array of the plugin data.
3263 */
3264 private static function get_all_plugins( $blog_id = 0 ) {
3265 self::require_plugin_essentials();
3266
3267 $all_plugins = fs_get_plugins();
3268
3269 $active_plugins_basenames = self::get_active_plugins_basenames( $blog_id );
3270
3271 foreach ( $all_plugins as $basename => &$data ) {
3272 // By default set to inactive (next foreach update the active plugins).
3273 $data['is_active'] = false;
3274 // Enrich with plugin slug.
3275 $data['slug'] = self::get_plugin_slug( $basename );
3276 }
3277
3278 // Flag active plugins.
3279 foreach ( $active_plugins_basenames as $basename ) {
3280 if ( isset( $all_plugins[ $basename ] ) ) {
3281 $all_plugins[ $basename ]['is_active'] = true;
3282 }
3283 }
3284
3285 return $all_plugins;
3286 }
3287
3288 /**
3289 * Get collection of all plugins and if they are network level activated.
3290 *
3291 * @author Vova Feldman (@svovaf)
3292 * @since 2.0.0
3293 *
3294 * @return array Key is the plugin basename and the value is an array of the plugin data.
3295 */
3296 private static function get_network_plugins() {
3297 self::require_plugin_essentials();
3298
3299 $all_plugins = fs_get_plugins();
3300
3301 $network_active_basenames = is_multisite() ?
3302 get_site_option( 'active_sitewide_plugins' ) :
3303 array();
3304
3305 foreach ( $all_plugins as $basename => &$data ) {
3306 // By default set to inactive (next foreach update the active plugins).
3307 $data['is_active'] = false;
3308 // Enrich with plugin slug.
3309 $data['slug'] = self::get_plugin_slug( $basename );
3310 }
3311
3312 // Flag active plugins.
3313 foreach ( $network_active_basenames as $basename ) {
3314 if ( isset( $all_plugins[ $basename ] ) ) {
3315 $all_plugins[ $basename ]['is_active'] = true;
3316 }
3317 }
3318
3319 return $all_plugins;
3320 }
3321
3322 /**
3323 * Cached result of get_site_transient( 'update_plugins' )
3324 *
3325 * @author Vova Feldman (@svovaf)
3326 * @since 1.1.8
3327 *
3328 * @var object
3329 */
3330 private static $_plugins_info;
3331
3332 /**
3333 * Helper function to get specified plugin's slug.
3334 *
3335 * @author Vova Feldman (@svovaf)
3336 * @since 1.1.8
3337 *
3338 * @param $basename
3339 *
3340 * @return string
3341 */
3342 private static function get_plugin_slug( $basename ) {
3343 if ( ! isset( self::$_plugins_info ) ) {
3344 self::$_plugins_info = get_site_transient( 'update_plugins' );
3345 }
3346
3347 $slug = '';
3348
3349 if ( is_object( self::$_plugins_info ) ) {
3350 if ( isset( self::$_plugins_info->no_update ) &&
3351 isset( self::$_plugins_info->no_update[ $basename ] ) &&
3352 ! empty( self::$_plugins_info->no_update[ $basename ]->slug )
3353 ) {
3354 $slug = self::$_plugins_info->no_update[ $basename ]->slug;
3355 } else if ( isset( self::$_plugins_info->response ) &&
3356 isset( self::$_plugins_info->response[ $basename ] ) &&
3357 ! empty( self::$_plugins_info->response[ $basename ]->slug )
3358 ) {
3359 $slug = self::$_plugins_info->response[ $basename ]->slug;
3360 }
3361 }
3362
3363 if ( empty( $slug ) ) {
3364 // Try to find slug from FS data.
3365 $slug = self::find_slug_by_basename( $basename );
3366 }
3367
3368 if ( empty( $slug ) ) {
3369 // Fallback to plugin's folder name.
3370 $slug = dirname( $basename );
3371 }
3372
3373 return $slug;
3374 }
3375
3376 private static $_statics_loaded = false;
3377
3378 /**
3379 * Load static resources.
3380 *
3381 * @author Vova Feldman (@svovaf)
3382 * @since 1.0.1
3383 */
3384 private static function _load_required_static() {
3385 if ( self::$_statics_loaded ) {
3386 return;
3387 }
3388
3389 self::$_static_logger = FS_Logger::get_logger( WP_FS__SLUG, WP_FS__DEBUG_SDK, WP_FS__ECHO_DEBUG_SDK );
3390
3391 self::$_static_logger->entrance();
3392
3393 self::$_accounts = FS_Options::instance( WP_FS__ACCOUNTS_OPTION_NAME, true );
3394
3395 if ( is_multisite() ) {
3396 $has_skipped_migration = (
3397 // 'id_slug_type_path_map' - was never stored on older versions, therefore, not exists on the site level.
3398 null === self::$_accounts->get_option( 'id_slug_type_path_map', null, false ) &&
3399 // 'file_slug_map' stored on the site level, so it was running an SDK version before it was integrated with MS-network.
3400 null !== self::$_accounts->get_option( 'file_slug_map', null, false )
3401 );
3402
3403 /**
3404 * If the file_slug_map exists on the site level but doesn't exist on the
3405 * network level storage, it means that we need to process the storage with migration.
3406 *
3407 * 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.
3408 *
3409 * @author Vova Feldman (@svovaf)
3410 * @since 2.0.0
3411 */
3412 if (
3413 ( $has_skipped_migration && true !== self::$_accounts->get_option( 'ms_migration_complete', false, true ) ) ||
3414 ( null === self::$_accounts->get_option( 'file_slug_map', null, true ) &&
3415 null !== self::$_accounts->get_option( 'file_slug_map', null, false ) )
3416 ) {
3417 self::migrate_options_to_network();
3418 }
3419 }
3420
3421 self::$_global_admin_notices = FS_Admin_Notices::instance( 'global' );
3422
3423 FS_DebugManager::load_required_static();
3424
3425 if ( 0 == did_action( 'plugins_loaded' ) ) {
3426 add_action( 'plugins_loaded', array( 'Freemius', '_load_textdomain' ), 1 );
3427 }
3428
3429 $clone_manager = FS_Clone_Manager::instance();
3430 add_action( 'init', array( $clone_manager, '_init' ) );
3431
3432 add_action( 'admin_footer', array( 'Freemius', '_open_support_forum_in_new_page' ) );
3433
3434 if ( self::is_plugins_page() || self::is_themes_page() ) {
3435 add_action( 'admin_print_footer_scripts', array( 'Freemius', '_maybe_add_beta_label_styles' ), 9 );
3436
3437 /**
3438 * Specifically use this hook so that the JS event handlers will work properly on the "Themes"
3439 * page.
3440 *
3441 * @author Leo Fajardo (@leorw)
3442 * @since 2.3.0
3443 */
3444 add_action( 'admin_footer-' . self::get_current_page(), array( 'Freemius', '_maybe_add_beta_label_to_plugins_and_handle_confirmation') );
3445 }
3446
3447 self::$_statics_loaded = true;
3448 }
3449
3450 public static function get_static_logger() {
3451 return self::$_static_logger;
3452 }
3453
3454 public static function get_accounts() {
3455 return self::$_accounts;
3456 }
3457
3458 #--------------------------------------------------------------------------------
3459 #region Clone
3460 #--------------------------------------------------------------------------------
3461
3462 /**
3463 * @author Leo Fajardo (@leorw)
3464 * @since 2.5.0
3465 *
3466 * @param bool $only_if_manual_resolution_is_not_hidden
3467 *
3468 * @return bool
3469 */
3470 private function is_unresolved_clone( $only_if_manual_resolution_is_not_hidden = false ) {
3471 if ( ! $this->is_clone( $only_if_manual_resolution_is_not_hidden ) ) {
3472 return false;
3473 }
3474
3475 return FS_Clone_Manager::instance()->has_temporary_duplicate_mode_expired();
3476 }
3477
3478 /**
3479 * @author Leo Fajardo (@leorw)
3480 * @since 2.5.0
3481 *
3482 * @param bool $only_if_manual_resolution_is_not_hidden
3483 */
3484 function is_clone( $only_if_manual_resolution_is_not_hidden = false ) {
3485 if ( ! is_object( $this->_site ) ) {
3486 return false;
3487 }
3488
3489 $blog_id = null;
3490
3491 if (
3492 fs_is_network_admin() &&
3493 FS_Site::is_valid_id( $this->_storage->network_install_blog_id )
3494 ) {
3495 // Ensure that we're comparing the network install's URL with the relevant subsite's URL.
3496 $blog_id = $this->_storage->network_install_blog_id;
3497 }
3498
3499 $site_url = Freemius::get_unfiltered_site_url( $blog_id, true, true );
3500
3501 if ( ! $this->_site->is_clone( $site_url ) ) {
3502 return false;
3503 }
3504
3505 return (
3506 ! $only_if_manual_resolution_is_not_hidden ||
3507 ! FS_Clone_Manager::instance()->should_hide_manual_resolution()
3508 );
3509 }
3510
3511 /**
3512 * @author Leo Fajardo (@leorw)
3513 * @since 2.5.0
3514 *
3515 * @param int|null $blog_id
3516 * @param bool $strip_protocol
3517 * @param bool $add_trailing_slash
3518 *
3519 * @return string
3520 */
3521 static function get_unfiltered_site_url( $blog_id = null, $strip_protocol = false, $add_trailing_slash = false ) {
3522 $url = ( ! is_multisite() && defined( 'WP_SITEURL' ) ) ? WP_SITEURL : self::get_site_url_from_wp_option( $blog_id );
3523
3524 if ( $strip_protocol ) {
3525 $url = fs_strip_url_protocol( $url );
3526 }
3527
3528 if ( $add_trailing_slash ) {
3529 $url = trailingslashit( $url );
3530 }
3531
3532 return $url;
3533 }
3534
3535 /**
3536 * @author Leo Fajardo (@leorw)
3537 * @since 2.6.0
3538 *
3539 * @param int|null $blog_id
3540 *
3541 * @return string
3542 */
3543 private static function get_site_url_from_wp_option( $blog_id = null ) {
3544 global $wp_filter;
3545
3546 $site_url_filters = array(
3547 'site_url' => null,
3548 'pre_option_siteurl' => null,
3549 'default_option_siteurl' => null,
3550 'option_siteurl' => null,
3551 );
3552
3553 // Detach all URL-related filters to get the actual site's URL (stripped of potential manipulations by multilingual plugins).
3554 foreach ( $site_url_filters as $hook_name => $site_url_filter ) {
3555 if ( ! empty( $wp_filter[ $hook_name ] ) ) {
3556 $site_url_filters[ $hook_name ] = $wp_filter[ $hook_name ];
3557 unset( $wp_filter[ $hook_name ] );
3558 }
3559 }
3560
3561 $url = get_site_url( $blog_id );
3562
3563 // Re-attach the filters back.
3564 foreach ( $site_url_filters as $hook_name => $site_url_filter ) {
3565 if ( ! empty( $site_url_filter ) ) {
3566 $wp_filter[ $hook_name ] = $site_url_filter;
3567 }
3568 }
3569
3570 return $url;
3571 }
3572
3573 /**
3574 * @author Leo Fajardo (@leorw)
3575 * @since 2.5.0
3576 *
3577 * @param number $site_id
3578 */
3579 function fetch_install_by_id( $site_id ) {
3580 return $this->get_current_or_network_user_api_scope()->get( "/installs/{$site_id}.json" );
3581 }
3582
3583 /**
3584 * @author Leo Fajardo (@leorw)
3585 * @since 2.5.0
3586 *
3587 * @return string|object|bool
3588 */
3589 function _handle_long_term_duplicate() {
3590 $this->_logger->entrance();
3591
3592 $this->delete_current_install( false );
3593
3594 $license_key = false;
3595
3596 if (
3597 is_object( $this->_license ) &&
3598 ! $this->_license->is_utilized(
3599 ( WP_FS__IS_LOCALHOST_FOR_SERVER || FS_Site::is_localhost_by_address( self::get_unfiltered_site_url() ) )
3600 )
3601 ) {
3602 $license_key = $this->_license->secret_key;
3603 }
3604
3605 return $this->opt_in(
3606 false,
3607 false,
3608 false,
3609 $license_key,
3610 false,
3611 false,
3612 false,
3613 null,
3614 array(),
3615 false
3616 );
3617 }
3618
3619 #endregion
3620
3621 /**
3622 * @author Leo Fajardo (@leorw)
3623 *
3624 * @since 2.1.3
3625 */
3626 public static function migrate_options_to_network() {
3627 self::migrate_accounts_to_network();
3628
3629 // Migrate API options from site level to network level.
3630 $api_network_options = FS_Option_Manager::get_manager( WP_FS__OPTIONS_OPTION_NAME, true, true );
3631 $api_network_options->migrate_to_network();
3632
3633 // Migrate API cache to network level storage.
3634 FS_Cache_Manager::get_manager( WP_FS__API_CACHE_OPTION_NAME )->migrate_to_network();
3635
3636 self::$_accounts->set_option( 'ms_migration_complete', true, true );
3637 }
3638
3639 #----------------------------------------------------------------------------------
3640 #region Localization
3641 #----------------------------------------------------------------------------------
3642
3643 /**
3644 * Load framework's text domain.
3645 *
3646 * @author Vova Feldman (@svovaf)
3647 * @since 1.2.1
3648 */
3649 static function _load_textdomain() {
3650 if ( ! is_admin() ) {
3651 return;
3652 }
3653
3654 global $fs_active_plugins;
3655
3656 // Works both for plugins and themes.
3657 load_plugin_textdomain(
3658 'freemius',
3659 false,
3660 $fs_active_plugins->newest->sdk_path . '/languages/'
3661 );
3662 }
3663
3664 #endregion
3665
3666 #----------------------------------------------------------------------------------
3667 #region Connectivity Issues
3668 #----------------------------------------------------------------------------------
3669
3670 /**
3671 * Check if Freemius should be turned on for the current plugin install.
3672 *
3673 * Note:
3674 * $this->_is_on is updated in has_api_connectivity()
3675 *
3676 * @author Vova Feldman (@svovaf)
3677 * @since 1.0.9
3678 *
3679 * @return bool
3680 */
3681 function is_on() {
3682 self::$_static_logger->entrance();
3683
3684 if ( is_object( $this->_site ) && ! $this->is_registered() ) {
3685 return false;
3686 }
3687
3688 if ( isset( $this->_is_on ) ) {
3689 return $this->_is_on;
3690 }
3691
3692 // If already installed or pending then sure it's on :)
3693 if ( $this->is_registered() || $this->is_pending_activation() ) {
3694 $this->_is_on = true;
3695
3696 return true;
3697 }
3698
3699 return false;
3700 }
3701
3702 /**
3703 * @author Vova Feldman (@svovaf)
3704 * @since 1.1.7.3
3705 *
3706 * @param bool $flush_if_no_connectivity
3707 *
3708 * @return bool
3709 */
3710 private function should_run_connectivity_test( $flush_if_no_connectivity = false ) {
3711 if ( ! isset( $this->_storage->connectivity_test ) ) {
3712 // Connectivity test was never executed, or cache was cleared.
3713 return true;
3714 }
3715
3716 if ( WP_FS__PING_API_ON_IP_OR_HOST_CHANGES ) {
3717 if ( WP_FS__IS_HTTP_REQUEST ) {
3718 if ( $_SERVER['HTTP_HOST'] != $this->_storage->connectivity_test['host'] ) {
3719 // Domain changed.
3720 return true;
3721 }
3722
3723 if ( WP_FS__REMOTE_ADDR != $this->_storage->connectivity_test['server_ip'] ) {
3724 // Server IP changed.
3725 return true;
3726 }
3727 }
3728 }
3729
3730 if ( $this->_storage->connectivity_test['is_connected'] &&
3731 $this->_storage->connectivity_test['is_active']
3732 ) {
3733 // API connected and Freemius is active - no need to run connectivity check.
3734 return false;
3735 }
3736
3737 if ( $flush_if_no_connectivity ) {
3738 /**
3739 * If explicitly asked to flush when no connectivity - do it only
3740 * if at least 10 sec passed from the last API connectivity test.
3741 */
3742 return ( isset( $this->_storage->connectivity_test['timestamp'] ) &&
3743 ( WP_FS__SCRIPT_START_TIME - $this->_storage->connectivity_test['timestamp'] ) > 10 );
3744 }
3745
3746 /**
3747 * @since 1.1.7 Don't check for connectivity on plugin downgrade.
3748 */
3749 $version = $this->get_plugin_version();
3750 if ( version_compare( $version, $this->_storage->connectivity_test['version'], '>' ) ) {
3751 // If it's a plugin version upgrade and Freemius is off or no connectivity, run connectivity test.
3752 return true;
3753 }
3754
3755 return false;
3756 }
3757
3758 /**
3759 * @author Leo Fajardo (@leorw)
3760 * @since 2.5.4
3761 *
3762 * @param bool $is_update
3763 *
3764 * @return bool
3765 */
3766 private function should_turn_fs_on( $is_update = true ) {
3767 if (
3768 empty( $this->_plugin->opt_in_moderation ) ||
3769 ! is_array( $this->_plugin->opt_in_moderation )
3770 ) {
3771 return true;
3772 }
3773
3774 $optin_config = $this->_plugin->opt_in_moderation;
3775
3776 if (
3777 WP_FS__IS_LOCALHOST &&
3778 ( ! isset( $optin_config['localhost'] ) || false !== $optin_config['localhost'] )
3779 ) {
3780 return true;
3781 }
3782
3783 $optin_config_key = $is_update ?
3784 'updates' :
3785 'new';
3786
3787 if ( ! isset( $optin_config[ $optin_config_key ] ) ) {
3788 return true;
3789 }
3790
3791 $visibility_percentage = $optin_config[ $optin_config_key ];
3792
3793 if ( 0 == $visibility_percentage ) {
3794 return false;
3795 }
3796
3797 if ( ! is_numeric( $visibility_percentage ) ) {
3798 return true;
3799 }
3800
3801 $min = 1;
3802 $max = 100;
3803
3804 if ( function_exists( 'random_int' ) ) {
3805 $random = random_int( $min, $max ); // phpcs:ignore PHPCompatibility.FunctionUse.NewFunctions.random_intFound
3806 } else {
3807 $random = rand( $min, $max );
3808 }
3809
3810 return ( $random <= $visibility_percentage );
3811 }
3812
3813 /**
3814 * Check if there's any connectivity issue to Freemius API.
3815 *
3816 * @author Vova Feldman (@svovaf)
3817 * @since 1.0.9
3818 *
3819 * @param bool $flush_if_no_connectivity
3820 *
3821 * @return bool|null
3822 */
3823 function has_api_connectivity( $flush_if_no_connectivity = false ) {
3824 $this->_logger->entrance();
3825
3826 if ( isset( $this->_has_api_connection ) && ( $this->_has_api_connection || ! $flush_if_no_connectivity ) ) {
3827 return $this->_has_api_connection;
3828 }
3829
3830 if ( WP_FS__SIMULATE_NO_API_CONNECTIVITY &&
3831 isset( $this->_storage->connectivity_test ) &&
3832 true === $this->_storage->connectivity_test['is_connected']
3833 ) {
3834 $this->clear_connectivity_info();
3835 }
3836
3837 if ( ! $this->should_run_connectivity_test( $flush_if_no_connectivity ) ) {
3838 $this->_has_api_connection = $this->_storage->connectivity_test['is_connected'];
3839 /**
3840 * @since 1.1.6 During dev mode, if there's connectivity - turn Freemius on regardless the configuration.
3841 *
3842 * @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.
3843 */
3844 $this->_is_on = $this->_storage->connectivity_test['is_active'] ||
3845 $this->is_premium() ||
3846 ( WP_FS__DEV_MODE && $this->_has_api_connection && ! WP_FS__SIMULATE_FREEMIUS_OFF );
3847
3848 return $this->_has_api_connection;
3849 }
3850
3851 if (
3852 ! empty( $this->_storage->connectivity_test ) &&
3853 isset( $this->_storage->connectivity_test['is_active'] )
3854 ) {
3855 $is_connected = isset( $this->_storage->connectivity_test['is_connected'] ) ?
3856 $this->_storage->connectivity_test['is_connected'] :
3857 null;
3858 $is_active = ( $this->_storage->connectivity_test['is_active'] || is_object( $this->_site ) );
3859 } else {
3860 $is_connected = null;
3861 $is_active = $this->should_turn_fs_on( $this->apply_filters( 'is_plugin_update', $this->is_plugin_update() ) );
3862 }
3863
3864 $this->store_connectivity_info( (object) array( 'is_active' => $is_active ), $is_connected );
3865
3866 if ( $is_active ) {
3867 $this->_is_on = true;
3868 }
3869
3870 return $this->_has_api_connection;
3871 }
3872
3873 /**
3874 * @author Leo Fajardo (@leorw)
3875 * @since 2.5.4
3876 */
3877 private function clear_connectivity_info() {
3878 unset( $this->_storage->connectivity_test );
3879
3880 FS_Api::clear_force_http_flag();
3881 }
3882
3883 /**
3884 * @author Vova Feldman (@svovaf)
3885 * @since 1.1.7.4
3886 *
3887 * @param object $pong
3888 * @param bool|null $is_connected
3889 */
3890 private function store_connectivity_info( $pong, $is_connected ) {
3891 $this->_logger->entrance();
3892
3893 $version = $this->get_plugin_version();
3894
3895 if ( false === $is_connected || WP_FS__SIMULATE_FREEMIUS_OFF ) {
3896 $is_active = false;
3897 } else {
3898 $is_active = ( isset( $pong->is_active ) && true == $pong->is_active );
3899 }
3900
3901 $is_active = $this->apply_filters(
3902 'is_on',
3903 $is_active,
3904 $this->is_plugin_update(),
3905 $version
3906 );
3907
3908 $this->_storage->connectivity_test = array(
3909 'is_connected' => $is_connected,
3910 'host' => $_SERVER['HTTP_HOST'],
3911 'server_ip' => WP_FS__REMOTE_ADDR,
3912 'is_active' => $is_active,
3913 'timestamp' => WP_FS__SCRIPT_START_TIME,
3914 // Last version with connectivity attempt.
3915 'version' => $version,
3916 );
3917
3918 $this->_has_api_connection = $is_connected;
3919 $this->_is_on = $is_active || ( WP_FS__DEV_MODE && $is_connected && ! WP_FS__SIMULATE_FREEMIUS_OFF );
3920 }
3921
3922 /**
3923 * @author Leo Fajardo (@leorw)
3924 * @since 2.5.4
3925 *
3926 * @param bool $is_connected
3927 */
3928 private function update_connectivity_info( $is_connected ) {
3929 $this->store_connectivity_info(
3930 // 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.
3931 (object) array( 'is_active' => true ),
3932 $is_connected
3933 );
3934 }
3935
3936 /**
3937 * Force turning Freemius on.
3938 *
3939 * @author Vova Feldman (@svovaf)
3940 * @since 1.1.8.1
3941 *
3942 * @return bool TRUE if successfully turned on.
3943 */
3944 private function turn_on() {
3945 $this->_logger->entrance();
3946
3947 if ( $this->is_on() || ! isset( $this->_storage->connectivity_test['is_active'] ) ) {
3948 return false;
3949 }
3950
3951 $updated_connectivity = $this->_storage->connectivity_test;
3952 $updated_connectivity['is_active'] = true;
3953 $updated_connectivity['timestamp'] = WP_FS__SCRIPT_START_TIME;
3954 $this->_storage->connectivity_test = $updated_connectivity;
3955
3956 $this->_is_on = true;
3957
3958 return true;
3959 }
3960
3961 /**
3962 * Anonymous and unique site identifier (Hash).
3963 *
3964 * @author Vova Feldman (@svovaf)
3965 * @since 1.1.0
3966 *
3967 * @param null|int $blog_id Since 2.0.0
3968 *
3969 * @return string
3970 */
3971 function get_anonymous_id( $blog_id = null ) {
3972 $unique_id = self::$_accounts->get_option( 'unique_id', null, $blog_id );
3973
3974 if ( empty( $unique_id ) || ! is_string( $unique_id ) ) {
3975 $key = self::get_unfiltered_site_url( $blog_id, true );
3976
3977 $secure_auth = defined( 'SECURE_AUTH_KEY' ) ? SECURE_AUTH_KEY : '';
3978 if ( empty( $secure_auth ) ||
3979 false !== strpos( $secure_auth, ' ' ) ||
3980 'put your unique phrase here' === $secure_auth
3981 ) {
3982 // Protect against default auth key.
3983 $secure_auth = md5( microtime() );
3984 }
3985
3986 /**
3987 * Base the unique identifier on the WP secure authentication key. Which
3988 * turns the key into a secret anonymous identifier. This will help us
3989 * to avoid duplicate installs generation on the backend upon opt-in.
3990 *
3991 * @author Vova Feldman (@svovaf)
3992 * @since 1.2.3
3993 */
3994 $unique_id = md5( $key . $secure_auth );
3995
3996 self::$_accounts->set_option( 'unique_id', $unique_id, true, $blog_id );
3997 }
3998
3999 $this->_logger->departure( $unique_id );
4000
4001 return $unique_id;
4002 }
4003
4004 /**
4005 * Returns anonymous network ID.
4006 *
4007 * @since 2.4.3
4008 *
4009 * @return string
4010 */
4011 function get_anonymous_network_id() {
4012 return $this->get_anonymous_id( get_network()->site_id );
4013 }
4014
4015 /**
4016 * @author Vova Feldman (@svovaf)
4017 * @since 1.1.7.4
4018 *
4019 * @return \WP_User
4020 */
4021 static function _get_current_wp_user() {
4022 self::require_pluggable_essentials();
4023 self::wp_cookie_constants();
4024
4025 return wp_get_current_user();
4026 }
4027
4028 /**
4029 * Define cookie constants which are required by Freemius::_get_current_wp_user() since
4030 * it uses wp_get_current_user() which needs the cookie constants set. When a plugin
4031 * is network activated the cookie constants are only configured after the network
4032 * plugins activation, therefore, if we don't define those constants WP will throw
4033 * PHP warnings/notices.
4034 *
4035 * @author Vova Feldman (@svovaf)
4036 * @since 2.1.1
4037 */
4038 private static function wp_cookie_constants() {
4039 if ( defined( 'LOGGED_IN_COOKIE' ) &&
4040 ( defined( 'AUTH_COOKIE' ) || defined( 'SECURE_AUTH_COOKIE' ) )
4041 ) {
4042 return;
4043 }
4044
4045 /**
4046 * Used to guarantee unique hash cookies
4047 *
4048 * @since 1.5.0
4049 */
4050 if ( ! defined( 'COOKIEHASH' ) ) {
4051 $siteurl = get_site_option( 'siteurl' );
4052 if ( $siteurl ) {
4053 define( 'COOKIEHASH', md5( $siteurl ) );
4054 } else {
4055 define( 'COOKIEHASH', '' );
4056 }
4057 }
4058
4059 if ( ! defined( 'LOGGED_IN_COOKIE' ) ) {
4060 define( 'LOGGED_IN_COOKIE', 'wordpress_logged_in_' . COOKIEHASH );
4061 }
4062
4063 /**
4064 * @since 2.5.0
4065 */
4066 if ( ! defined( 'AUTH_COOKIE' ) ) {
4067 define( 'AUTH_COOKIE', 'wordpress_' . COOKIEHASH );
4068 }
4069
4070 /**
4071 * @since 2.6.0
4072 */
4073 if ( ! defined( 'SECURE_AUTH_COOKIE' ) ) {
4074 define( 'SECURE_AUTH_COOKIE', 'wordpress_sec_' . COOKIEHASH );
4075 }
4076 }
4077
4078 /**
4079 * @author Vova Feldman (@svovaf)
4080 * @since 2.1.0
4081 *
4082 * @return int
4083 */
4084 static function get_current_wp_user_id() {
4085 $wp_user = self::_get_current_wp_user();
4086
4087 return $wp_user->ID;
4088 }
4089
4090 /**
4091 * @author Vova Feldman (@svovaf)
4092 * @since 1.2.1.7
4093 *
4094 * @param string $email
4095 *
4096 * @return bool
4097 */
4098 static function is_valid_email( $email ) {
4099 if ( false === filter_var( $email, FILTER_VALIDATE_EMAIL ) ) {
4100 return false;
4101 }
4102
4103 $parts = explode( '@', $email );
4104
4105 if ( 2 !== count( $parts ) || empty( $parts[1] ) ) {
4106 return false;
4107 }
4108
4109 $blacklist = array(
4110 'admin.',
4111 'webmaster.',
4112 'localhost.',
4113 'dev.',
4114 'development.',
4115 'test.',
4116 'stage.',
4117 'staging.',
4118 );
4119
4120 // Make sure domain is not one of the blacklisted.
4121 foreach ( $blacklist as $invalid ) {
4122 if ( 0 === strpos( $parts[1], $invalid ) ) {
4123 return false;
4124 }
4125 }
4126
4127 // Get the UTF encoded domain name.
4128 /**
4129 * @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.
4130 * @author - @swashata
4131 */
4132 $is_new_idn_available = (
4133 version_compare( PHP_VERSION, '5.6.40') > 0 &&
4134 defined( 'IDNA_DEFAULT' ) &&
4135 defined( 'INTL_IDNA_VARIANT_UTS46' )
4136 );
4137 if ( $is_new_idn_available ) {
4138 $domain = idn_to_ascii( $parts[1], IDNA_DEFAULT, INTL_IDNA_VARIANT_UTS46 );
4139 } else {
4140 $domain = idn_to_ascii( $parts[1] ); // phpcs:ignore PHPCompatibility.ParameterValues.NewIDNVariantDefault.NotSet
4141 }
4142
4143 $domain = $domain . '.';
4144
4145 return ( checkdnsrr( $domain, 'MX' ) || checkdnsrr( $domain, 'A' ) );
4146 }
4147
4148 #endregion
4149
4150 #----------------------------------------------------------------------------------
4151 #region Email
4152 #----------------------------------------------------------------------------------
4153
4154 /**
4155 * Generates and sends an HTML email with customizable sections.
4156 *
4157 * @author Leo Fajardo (@leorw)
4158 * @since 1.1.2
4159 *
4160 * @param string $to_address
4161 * @param string $subject
4162 * @param array $sections
4163 * @param array $headers
4164 *
4165 * @return bool Whether the email contents were sent successfully.
4166 */
4167 private function send_email(
4168 $to_address,
4169 $subject,
4170 $sections = array(),
4171 $headers = array()
4172 ) {
4173 $default_sections = $this->get_email_sections();
4174
4175 // Insert new sections or replace the default email sections.
4176 if ( is_array( $sections ) && ! empty( $sections ) ) {
4177 foreach ( $sections as $section_id => $custom_section ) {
4178 if ( ! isset( $default_sections[ $section_id ] ) ) {
4179 // If the section does not exist, add it.
4180 $default_sections[ $section_id ] = $custom_section;
4181 } else {
4182 // If the section already exists, override it.
4183 $current_section = $default_sections[ $section_id ];
4184
4185 // Replace the current section's title if a custom section title exists.
4186 if ( isset( $custom_section['title'] ) ) {
4187 $current_section['title'] = $custom_section['title'];
4188 }
4189
4190 // Insert new rows under the current section or replace the default rows.
4191 if ( isset( $custom_section['rows'] ) && is_array( $custom_section['rows'] ) && ! empty( $custom_section['rows'] ) ) {
4192 foreach ( $custom_section['rows'] as $row_id => $row ) {
4193 $current_section['rows'][ $row_id ] = $row;
4194 }
4195 }
4196
4197 $default_sections[ $section_id ] = $current_section;
4198 }
4199 }
4200 }
4201
4202 $vars = array( 'sections' => $default_sections );
4203 $message = fs_get_template( 'email.php', $vars );
4204
4205 // Set the type of email to HTML.
4206 $headers[] = 'Content-type: text/html; charset=UTF-8';
4207
4208 $header_string = implode( "\r\n", $headers );
4209
4210 return wp_mail(
4211 $to_address,
4212 $subject,
4213 $message,
4214 $header_string
4215 );
4216 }
4217
4218 /**
4219 * Generates the data for the sections of the email content.
4220 *
4221 * @author Leo Fajardo (@leorw)
4222 * @since 1.1.2
4223 *
4224 * @return array
4225 */
4226 private function get_email_sections() {
4227 // Retrieve the current user's information so that we can get the user's email, first name, and last name below.
4228 $current_user = self::_get_current_wp_user();
4229
4230 // Retrieve the cURL version information so that we can get the version number below.
4231 $curl_version_information = curl_version();
4232
4233 $active_plugin = self::get_active_plugins();
4234
4235 // Generate the list of active plugins separated by new line.
4236 $active_plugin_string = '';
4237 foreach ( $active_plugin as $plugin ) {
4238 $active_plugin_string .= sprintf(
4239 '<a href="%s">%s</a> [v%s]<br>',
4240 $plugin['PluginURI'],
4241 $plugin['Name'],
4242 $plugin['Version']
4243 );
4244 }
4245
4246 $server_ip = WP_FS__REMOTE_ADDR;
4247
4248 // Add PHP info for deeper investigation.
4249 ob_start();
4250 phpinfo();
4251 $php_info = ob_get_clean();
4252
4253 $api_domain = substr( FS_API__ADDRESS, strpos( FS_API__ADDRESS, ':' ) + 3 );
4254
4255 // Generate the default email sections.
4256 $sections = array(
4257 'sdk' => array(
4258 'title' => 'SDK',
4259 'rows' => array(
4260 'fs_version' => array( 'FS Version', $this->version ),
4261 'curl_version' => array( 'cURL Version', $curl_version_information['version'] )
4262 )
4263 ),
4264 'plugin' => array(
4265 'title' => ucfirst( $this->get_module_type() ),
4266 'rows' => array(
4267 'name' => array( 'Name', $this->get_plugin_name() ),
4268 'version' => array( 'Version', $this->get_plugin_version() )
4269 )
4270 ),
4271 'api' => array(
4272 'title' => 'API Subdomain',
4273 'rows' => array(
4274 'dns' => array(
4275 'DNS_CNAME',
4276 function_exists( 'dns_get_record' ) ?
4277 var_export( dns_get_record( $api_domain, DNS_CNAME ), true ) :
4278 'dns_get_record() disabled/blocked'
4279 ),
4280 'ip' => array(
4281 'IP',
4282 function_exists( 'gethostbyname' ) ?
4283 gethostbyname( $api_domain ) :
4284 'gethostbyname() disabled/blocked'
4285 ),
4286 ),
4287 ),
4288 'site' => array(
4289 'title' => 'Site',
4290 'rows' => array(
4291 'unique_id' => array( 'Unique ID', $this->get_anonymous_id() ),
4292 'address' => array( 'Address', site_url() ),
4293 'host' => array(
4294 'HTTP_HOST',
4295 ( ! empty( $_SERVER['HTTP_HOST'] ) ? $_SERVER['HTTP_HOST'] : '' )
4296 ),
4297 'hosting' => array(
4298 'Hosting Company' => fs_request_has( 'hosting_company' ) ?
4299 fs_request_get( 'hosting_company' ) :
4300 'Unknown',
4301 ),
4302 'server_addr' => array(
4303 'SERVER_ADDR',
4304 '<a href="http://www.projecthoneypot.org/ip_' . $server_ip . '">' . $server_ip . '</a>'
4305 )
4306 )
4307 ),
4308 'user' => array(
4309 'title' => 'User',
4310 'rows' => array(
4311 'email' => array( 'Email', $current_user->user_email ),
4312 'first' => array( 'First', $current_user->user_firstname ),
4313 'last' => array( 'Last', $current_user->user_lastname )
4314 )
4315 ),
4316 'plugins' => array(
4317 'title' => 'Plugins',
4318 'rows' => array(
4319 'active_plugins' => array( 'Active Plugins', $active_plugin_string )
4320 )
4321 ),
4322 'php_info' => array(
4323 'title' => 'PHP Info',
4324 'rows' => array(
4325 'info' => array( $php_info )
4326 ),
4327 )
4328 );
4329
4330 // Allow the sections to be modified by other code.
4331 $sections = $this->apply_filters( 'email_template_sections', $sections );
4332
4333 return $sections;
4334 }
4335
4336 #endregion
4337
4338 #----------------------------------------------------------------------------------
4339 #region Initialization
4340 #----------------------------------------------------------------------------------
4341
4342 /**
4343 * Init plugin's Freemius instance.
4344 *
4345 * @author Vova Feldman (@svovaf)
4346 * @since 1.0.1
4347 *
4348 * @param number $id
4349 * @param string $public_key
4350 * @param bool $is_live
4351 * @param bool $is_premium
4352 */
4353 function init( $id, $public_key, $is_live = true, $is_premium = true ) {
4354 $this->_logger->entrance();
4355
4356 $this->dynamic_init( array(
4357 'id' => $id,
4358 'public_key' => $public_key,
4359 'is_live' => $is_live,
4360 'is_premium' => $is_premium,
4361 ) );
4362 }
4363
4364 /**
4365 * Dynamic initiator, originally created to support initiation
4366 * with parent_id for add-ons.
4367 *
4368 * @author Vova Feldman (@svovaf)
4369 * @since 1.0.6
4370 *
4371 * @param array $plugin_info
4372 *
4373 * @throws Freemius_Exception
4374 */
4375 function dynamic_init( array $plugin_info ) {
4376 $this->_logger->entrance();
4377
4378 $this->parse_settings( $plugin_info );
4379
4380 $this->register_after_settings_parse_hooks();
4381
4382 /**
4383 * 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.
4384 *
4385 * @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.
4386 */
4387 if ( $this->is_anonymous() ) {
4388 $is_network_level = ( $this->_is_network_active && fs_is_network_admin() );
4389
4390 if (
4391 ! $is_network_level ||
4392 FS_Site::is_valid_id( $this->_storage->network_install_blog_id )
4393 ) {
4394 if ( $this->is_paying_or_trial() ) {
4395 $this->reset_anonymous_mode( $is_network_level );
4396 }
4397 } else {
4398 $network = get_network();
4399
4400 if ( is_object( $network ) ) {
4401 $main_blog_id = $network->site_id;
4402 $first_install = $this->get_install_by_blog_id( $main_blog_id );
4403
4404 if ( is_object( $first_install ) ) {
4405 $this->_storage->network_install_blog_id = $main_blog_id;
4406 $this->_storage->network_user_id = $first_install->user_id;
4407 }
4408 }
4409 }
4410 }
4411
4412 if ( $this->should_stop_execution() ) {
4413 return;
4414 }
4415
4416 if ( ! $this->is_registered() ) {
4417 if ( $this->is_anonymous() ) {
4418 // If user skipped, no need to test connectivity.
4419 $this->_has_api_connection = true;
4420 $this->_is_on = true;
4421 } else {
4422 if ( false === $this->has_api_connectivity() ) {
4423 return;
4424 } else {
4425 if ( $this->_anonymous_mode ) {
4426 // Simulate anonymous mode.
4427 $this->_is_anonymous = true;
4428 }
4429 }
4430 }
4431 }
4432
4433 /**
4434 * This should be executed even if Freemius is off for the core module,
4435 * otherwise, the add-ons dialog box won't work properly. This is especially
4436 * relevant when the developer decided to turn FS off for existing users.
4437 *
4438 * @author Vova Feldman (@svovaf)
4439 */
4440 if ( $this->is_user_in_admin() &&
4441 'plugin-information' === fs_request_get( 'tab', false ) &&
4442 $this->should_use_freemius_updater_and_dialog() &&
4443 (
4444 ( $this->is_addon() && $this->get_slug() == fs_request_get( 'plugin', false ) ) ||
4445 ( $this->has_addons() && $this->get_id() == fs_request_get( 'parent_plugin_id', false ) )
4446 )
4447 ) {
4448 require_once WP_FS__DIR_INCLUDES . '/fs-plugin-info-dialog.php';
4449
4450 new FS_Plugin_Info_Dialog( $this->is_addon() ? $this->get_parent_instance() : $this );
4451 }
4452
4453 // Check if Freemius is on for the current plugin.
4454 // This MUST be executed after all the plugin variables has been loaded.
4455 if ( ! $this->is_registered() && ! $this->is_on() ) {
4456 return;
4457 }
4458
4459 if ( $this->has_api_connectivity() ) {
4460 if ( self::is_cron() ) {
4461 $this->hook_callback_to_sync_cron();
4462 } else if ( $this->is_user_in_admin() ) {
4463 /**
4464 * Schedule daily data sync cron if:
4465 *
4466 * 1. User opted-in (for tracking).
4467 * 2. If skipped, but later upgraded (opted-in via upgrade).
4468 *
4469 * @author Vova Feldman (@svovaf)
4470 * @since 1.1.7.3
4471 *
4472 */
4473 if ( $this->is_registered() && $this->is_tracking_allowed() ) {
4474 $this->maybe_schedule_sync_cron();
4475 }
4476
4477 /**
4478 * Check if requested for manual blocking background sync.
4479 */
4480 if ( fs_request_has( 'background_sync' ) ) {
4481 self::require_pluggable_essentials();
4482 self::wp_cookie_constants();
4483
4484 $this->run_manual_sync();
4485 }
4486 }
4487 }
4488
4489 if ( $this->is_registered() ) {
4490 FS_Clone_Manager::instance()->maybe_resolve_new_subsite_install_automatically( $this );
4491
4492 $this->hook_callback_to_install_sync();
4493 }
4494
4495 if ( $this->is_addon() ) {
4496 if ( $this->is_parent_plugin_installed() ) {
4497 // Link to parent FS.
4498 $this->_parent = self::get_instance_by_id( $this->_plugin->parent_plugin_id );
4499
4500 // Get parent plugin reference.
4501 $this->_parent_plugin = $this->_parent->get_plugin();
4502 }
4503 }
4504
4505 if ( $this->is_user_in_admin() ) {
4506 if ( $this->is_registered() && fs_request_has( 'purchase_completed' ) ) {
4507 $this->_admin_notices->add_sticky(
4508 sprintf(
4509 /* translators: %s: License type (e.g. you have a professional license) */
4510 $this->get_text_inline( 'You have purchased a %s license.', 'you-have-x-license' ),
4511 fs_request_get( 'purchased_plan' )
4512 ) .
4513 sprintf(
4514 $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' ),
4515 $this->get_module_label( true ),
4516 ( FS_Plugin::is_valid_id( $this->get_bundle_id() ) ? "products' " : '' ),
4517 ( FS_Plugin::is_valid_id( $this->get_bundle_id() ) ? 's' : '' ),
4518 sprintf(
4519 '<strong>%s</strong>',
4520 fs_request_get( 'purchase_email' )
4521 )
4522 ),
4523 'plan_purchased',
4524 $this->get_text_x_inline( 'Yee-haw', 'interjection expressing joy or exuberance', 'yee-haw' ) . '!'
4525 );
4526 }
4527
4528 if ( $this->is_addon() ) {
4529 if ( ! $this->is_parent_plugin_installed() ) {
4530 $parent_name = $this->get_option( $plugin_info, 'parent_name', null );
4531
4532 if ( isset( $plugin_info['parent'] ) ) {
4533 $parent_name = $this->get_option( $plugin_info['parent'], 'name', null );
4534 }
4535
4536 $this->_admin_notices->add(
4537 ( ! empty( $parent_name ) ?
4538 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 ) :
4539 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() )
4540 ),
4541 $this->get_text_x_inline( 'Oops', 'exclamation', 'oops' ) . '...',
4542 'error'
4543 );
4544
4545 return;
4546 } else {
4547 $is_network_admin = fs_is_network_admin();
4548
4549 if ( ! $this->_parent->is_registered() && $this->is_registered() ) {
4550 // If add-on activated and parent not, automatically install parent for the user.
4551 $this->activate_parent_account( $this->_parent );
4552 } else if (
4553 $this->_parent->is_registered() &&
4554 ! $this->is_registered() &&
4555 /**
4556 * If not registered for add-on and the following conditions for the add-on are met, activate add-on account.
4557 * * Network active and in network admin - network activate add-on account.
4558 * * Network active and not in network admin - activate add-on account for the current blog.
4559 * * Not network active and not in network admin - activate add-on account for the current blog.
4560 *
4561 * If not registered for add-on, not network active, and in network admin, do not handle the add-on activation.
4562 *
4563 * @author Leo Fajardo (@leorw)
4564 * @since 2.3.0
4565 */
4566 ( $this->is_network_active() || ! $is_network_admin )
4567 ) {
4568 $premium_license = null;
4569
4570 if (
4571 ! $this->has_free_plan() &&
4572 $this->is_bundle_license_auto_activation_enabled() &&
4573 $this->_parent->is_activated_with_bundle_license()
4574 ) {
4575 /**
4576 * If the add-on has no free plan, try to activate the account only when there's a bundle license.
4577 *
4578 * @author Leo Fajardo (@leorw)
4579 * @since 2.4.0
4580 */
4581 $bundle_license = $this->get_active_parent_license( $this->_parent->_get_license()->secret_key, false );
4582
4583 if (
4584 is_object( $bundle_license ) &&
4585 ! empty( $bundle_license->products ) &&
4586 in_array( $this->get_id(), $bundle_license->products )
4587 ) {
4588 $premium_license = $bundle_license;
4589 }
4590 }
4591
4592 if ( $this->has_free_plan() || is_object( $premium_license) ) {
4593 // If parent plugin activated, automatically install add-on for the user.
4594 $this->_activate_addon_account(
4595 $this->_parent,
4596 ( $this->is_network_active() && $is_network_admin ) ?
4597 true :
4598 get_current_blog_id(),
4599 $premium_license
4600 );
4601 }
4602 }
4603
4604 // @todo This should be only executed on activation. It should be migrated to register_activation_hook() together with other activation related logic.
4605 if ( $this->is_premium() ) {
4606 // Remove add-on download admin-notice.
4607 $this->_parent->_admin_notices->remove_sticky( array(
4608 'addon_plan_upgraded_' . $this->_slug,
4609 'no_addon_license_' . $this->_slug,
4610 ) );
4611 }
4612
4613 // $this->deactivate_premium_only_addon_without_license();
4614 }
4615 }
4616
4617 add_action( 'admin_init', array( &$this, '_admin_init_action' ) );
4618
4619 // if ( $this->is_registered() ||
4620 // $this->is_anonymous() ||
4621 // $this->is_pending_activation()
4622 // ) {
4623 // $this->_init_admin();
4624 // }
4625 }
4626
4627 /**
4628 * Should be called outside `$this->is_user_in_admin()` scope
4629 * because the updater has some logic that needs to be executed
4630 * during AJAX calls.
4631 *
4632 * Currently, we need to hook to the `http_request_host_is_external` filter.
4633 * In the future, there might be additional logic added.
4634 *
4635 * @author Vova Feldman
4636 * @since 1.2.1.6
4637 */
4638 if (
4639 $this->should_use_freemius_updater_and_dialog() &&
4640 (
4641 $this->is_premium() ||
4642 /**
4643 * If not premium but the premium version is installed, also instantiate the updater so that the
4644 * plugin information dialog of the premium version will have the information from the server.
4645 *
4646 * @author Leo Fajardo (@leorw)
4647 * @since 2.2.3
4648 */
4649 ( file_exists( fs_normalize_path( WP_PLUGIN_DIR . '/' . $this->premium_plugin_basename() ) ) )
4650 ) &&
4651 $this->has_release_on_freemius() &&
4652 ( ! $this->is_unresolved_clone( true ) )
4653 ) {
4654 FS_Plugin_Updater::instance( $this );
4655 }
4656
4657 $this->do_action( 'initiated' );
4658
4659 if ( $this->_storage->prev_is_premium !== $this->_plugin->is_premium ) {
4660 if ( isset( $this->_storage->prev_is_premium ) ) {
4661 $this->apply_filters(
4662 'after_code_type_change',
4663 // New code type.
4664 $this->_plugin->is_premium
4665 );
4666 } else {
4667 // Set for code type for the first time.
4668 $this->_storage->prev_is_premium = $this->_plugin->is_premium;
4669 }
4670 }
4671
4672 if ( ! $this->is_addon() ) {
4673 if ( $this->is_registered() ) {
4674 // Fix for upgrade from versions < 1.0.9.
4675 if ( ! isset( $this->_storage->activation_timestamp ) ) {
4676 $this->_storage->activation_timestamp = WP_FS__SCRIPT_START_TIME;
4677 }
4678
4679 $this->do_action( 'after_init_plugin_registered' );
4680 } else if ( $this->is_anonymous() ) {
4681 $this->do_action( 'after_init_plugin_anonymous' );
4682 } else if ( $this->is_pending_activation() ) {
4683 $this->do_action( 'after_init_plugin_pending_activations' );
4684 }
4685 } else {
4686 if ( $this->is_registered() ) {
4687 $this->do_action( 'after_init_addon_registered' );
4688 } else if ( $this->is_anonymous() ) {
4689 $this->do_action( 'after_init_addon_anonymous' );
4690 } else if ( $this->is_pending_activation() ) {
4691 $this->do_action( 'after_init_addon_pending_activations' );
4692 }
4693 }
4694 }
4695
4696 /**
4697 * @author Leo Fajardo (@leorw)
4698 * @since 2.2.3
4699 *
4700 * @return bool
4701 */
4702 private function should_use_freemius_updater_and_dialog() {
4703 return (
4704 /**
4705 * Allow updater and dialog when the `fs_allow_updater_and_dialog` URL query param exists and has `true`
4706 * value, or when the current page is not the "Add Plugins" page (/plugin-install.php) and the `action`
4707 * URL query param doesn't exist or its value is not `install-plugin` so that there will be no conflicts
4708 * with the .org plugins' functionalities (e.g. installation from the "Add Plugins" page and viewing
4709 * plugin details from .org).
4710 */
4711 ( true === fs_request_get_bool( 'fs_allow_updater_and_dialog' ) ) ||
4712 (
4713 ! self::is_plugin_install_page() &&
4714 // Disallow updater and dialog when installing a plugin, otherwise .org "add-on" plugins will be affected.
4715 ( 'install-plugin' !== fs_request_get( 'action' ) )
4716 )
4717 );
4718 }
4719
4720 /**
4721 * @param string[] $permissions
4722 * @param bool $is_enabled
4723 * @param int|null $blog_id
4724 *
4725 * @return true|object `true` on success, API error object on failure.
4726 */
4727 private function update_site_permissions( array $permissions, $is_enabled, $blog_id = null ) {
4728 $this->_logger->entrance();
4729
4730 $params = array(
4731 'permissions' => implode( ',', $permissions ),
4732 'is_enabled' => $is_enabled,
4733 );
4734
4735 $current_blog_id = get_current_blog_id();
4736 $is_blog_switched = false;
4737 if ( is_numeric( $blog_id ) && $current_blog_id != $blog_id ) {
4738 $is_blog_switched = $this->switch_to_blog( $blog_id );
4739 }
4740
4741 $result = $this->api_site_call( '/permissions.json', 'put', $params );
4742
4743 if ( $is_blog_switched ) {
4744 $this->switch_to_blog( $current_blog_id );
4745 }
4746
4747 if (
4748 ! $this->is_api_result_object( $result ) ||
4749 ! isset( $result->install_id )
4750 ) {
4751 $this->_logger->api_error( $result );
4752
4753 return $result;
4754 }
4755
4756 return true;
4757 }
4758
4759 /**
4760 * @param string[] $permissions
4761 * @param bool $is_enabled
4762 * @param bool $has_site_delegated_connection
4763 *
4764 * @return true|object `true` on success, API error object on failure.
4765 */
4766 private function update_network_permissions(
4767 array $permissions,
4768 $is_enabled,
4769 &$has_site_delegated_connection
4770 ) {
4771 $this->_logger->entrance();
4772
4773 $install_id_2_blog_id = array();
4774 $install_by_blog_id = $this->get_blog_install_map();
4775
4776 $has_site_delegated_connection = false;
4777
4778 foreach ( $install_by_blog_id as $blog_id => $install ) {
4779 if ( $this->is_site_delegated_connection( $blog_id ) ) {
4780 // Only update permissions of non-delegated installs.
4781 $has_site_delegated_connection = true;
4782 continue;
4783 }
4784
4785 $install_id_2_blog_id[ $install->id ] = $blog_id;
4786 }
4787
4788 if ( empty( $install_id_2_blog_id ) ) {
4789 return true;
4790 }
4791
4792 $params = array(
4793 'permissions' => implode( ',', $permissions ),
4794 'is_enabled' => $is_enabled,
4795 'install_ids' => implode( ',', array_keys( $install_id_2_blog_id ) ),
4796 );
4797
4798 // Send update to FS.
4799 $result = $this->get_current_or_network_user_api_scope()->call(
4800 "/plugins/{$this->_module_id}/installs/permissions.json",
4801 'put',
4802 $params
4803 );
4804
4805 if ( ! $this->is_api_result_object( $result, 'installs_metadata' ) ) {
4806 $this->_logger->api_error( $result );
4807
4808 return $result;
4809 }
4810
4811 return true;
4812 }
4813
4814 /**
4815 * @param mixed $result
4816 *
4817 * @return string
4818 */
4819 private function get_api_error_message( $result ) {
4820 $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:',
4821 'unexpected-api-error' ), $this->_module_type ) . ' ';
4822
4823 if (
4824 $this->is_api_error( $result ) &&
4825 isset( $result->error )
4826 ) {
4827 $code = empty( $result->error->code ) ? '' : " Code: {$result->error->code}";
4828
4829 $error_message .= "<b>{$result->error->message}{$code}</b>";
4830 } else {
4831 $error_message .= var_export( $result, true );
4832 }
4833
4834 return $error_message;
4835 }
4836
4837 /**
4838 * @author Vova Feldman (@svovaf)
4839 * @since 2.5.1
4840 */
4841 function _toggle_permission_tracking_callback() {
4842 $this->_logger->entrance();
4843
4844 $this->check_ajax_referer( 'toggle_permission_tracking' );
4845
4846 if ( ! $this->is_registered( true ) ) {
4847 self::shoot_ajax_failure( 'User never opted-in.' );
4848 }
4849
4850 $is_enabled = fs_request_get_bool( 'is_enabled' );
4851 $permissions = fs_request_get( 'permissions' );
4852
4853 if ( ! is_string( $permissions ) ) {
4854 self::shoot_ajax_failure( 'The permissions param must be a string.' );
4855 }
4856
4857 $permissions = explode( ',', $permissions );
4858
4859 $result = $this->toggle_permission_tracking( $permissions, $is_enabled );
4860
4861 if ( true !== $result ) {
4862 self::shoot_ajax_failure( $this->get_api_error_message( $result ) );
4863 }
4864
4865 self::shoot_ajax_success();
4866 }
4867
4868 /**
4869 * @param string[] $permissions
4870 * @param bool $is_enabled
4871 * @param int|null $blog_id
4872 *
4873 * @return bool|mixed `true` if updated successfully or no update is needed.
4874 */
4875 private function toggle_permission_tracking( $permissions, $is_enabled, $blog_id = null ) {
4876 if ( ! $this->is_registered( true ) ) {
4877 // User never opted-in.
4878 return false;
4879 }
4880
4881 // Check if permissions are already set as needed.
4882 if ( FS_Permission_Manager::instance( $this )->are_permissions( $permissions, $is_enabled, $blog_id ) ) {
4883 /**
4884 * Note:
4885 * 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.
4886 */
4887 return true;
4888 }
4889
4890 $api_managed_permissions = array_intersect(
4891 $permissions,
4892 FS_Permission_Manager::get_api_managed_permission_ids()
4893 );
4894
4895 if (
4896 in_array( FS_Permission_Manager::PERMISSION_ESSENTIALS, $permissions ) &&
4897 ! in_array( FS_Permission_Manager::PERMISSION_SITE, $permissions )
4898 ) {
4899 $api_managed_permissions[] = FS_Permission_Manager::PERMISSION_SITE;
4900 }
4901
4902 if ( ! empty( $api_managed_permissions ) ) {
4903 $has_site_delegated_connection = false;
4904
4905 if (
4906 ! $is_enabled &&
4907 ! in_array( FS_Permission_Manager::PERMISSION_EXTENSIONS, $api_managed_permissions ) &&
4908 false === FS_Permission_Manager::instance( $this )->is_extensions_tracking_allowed( $blog_id )
4909 ) {
4910 /**
4911 * 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.
4912 *
4913 * @todo Remove this entire `if` after implementing granular opt-in that also sends the permissions to the API when opting in.
4914 */
4915 $api_managed_permissions[] = FS_Permission_Manager::PERMISSION_EXTENSIONS;
4916 }
4917
4918 if ( is_null( $blog_id ) && fs_is_network_admin() ) {
4919 $result = $this->update_network_permissions(
4920 $api_managed_permissions,
4921 $is_enabled,
4922 $has_site_delegated_connection
4923 );
4924 } else {
4925 $result = $this->update_site_permissions(
4926 $api_managed_permissions,
4927 $is_enabled,
4928 $blog_id
4929 );
4930 }
4931
4932 if ( true !== $result ) {
4933 return $result;
4934 }
4935
4936 if ( in_array( FS_Permission_Manager::PERMISSION_SITE, $api_managed_permissions ) ) {
4937 if ( $is_enabled ) {
4938 $this->schedule_sync_cron();
4939 } else {
4940 $this->clear_sync_cron( ! $has_site_delegated_connection );
4941 }
4942 }
4943
4944 if ( in_array( FS_Permission_Manager::PERMISSION_USER, $api_managed_permissions ) ) {
4945 $this->toggle_user_permission( $is_enabled, $blog_id );
4946 }
4947 }
4948
4949 $this->update_tracking_permissions(
4950 $permissions,
4951 $is_enabled,
4952 $blog_id
4953 );
4954
4955 return true;
4956 }
4957
4958 /**
4959 * @param bool $is_enabled
4960 * @param int|null $blog_id
4961 */
4962 private function toggle_user_permission( $is_enabled, $blog_id = null ) {
4963 $network_or_blog_ids = is_numeric( $blog_id ) ?
4964 $blog_id :
4965 fs_is_network_admin();
4966
4967 if ( $is_enabled ) {
4968 $this->reset_anonymous_mode( $network_or_blog_ids );
4969 } else {
4970 $this->skip_connection( $network_or_blog_ids );
4971 }
4972 }
4973
4974 /**
4975 * Opt-in back into usage tracking.
4976 *
4977 * Note: This will only work if the user opted-in previously.
4978 *
4979 * Returns:
4980 * 1. FALSE - If the user never opted-in.
4981 * 2. TRUE - If successfully opted-in back to usage tracking.
4982 * 3. object - API result on failure.
4983 *
4984 * @author Leo Fajardo (@leorw)
4985 * @since 1.2.1.5
4986 *
4987 * @bool $is_enabled
4988 *
4989 * @return bool|object
4990 */
4991 private function toggle_site_tracking( $is_enabled, $blog_id = null ) {
4992 $this->_logger->entrance();
4993
4994 return $this->toggle_permission_tracking(
4995 FS_Permission_Manager::instance( $this )->get_site_tracking_permission_names(),
4996 $is_enabled,
4997 $blog_id
4998 );
4999 }
5000
5001 /**
5002 * If user opted-in and later disabled usage-tracking,
5003 * re-allow tracking for licensing and updates.
5004 *
5005 * @author Leo Fajardo (@leorw)
5006 * @since 1.2.1.5
5007 *
5008 * @param bool $is_context_single_site
5009 */
5010 private function reconnect_locally( $is_context_single_site = false ) {
5011 $this->_logger->entrance();
5012
5013 if ( ! $this->is_registered() ) {
5014 return;
5015 }
5016
5017 if ( ! fs_is_network_admin() || $is_context_single_site ) {
5018 if ( $this->is_tracking_prohibited() ) {
5019 FS_Permission_Manager::instance( $this )->update_site_tracking( true );
5020 }
5021 } else {
5022 $installs_map = $this->get_blog_install_map();
5023 foreach ( $installs_map as $blog_id => $install ) {
5024 /**
5025 * @var FS_Site $install
5026 */
5027 if ( ! $this->is_tracking_allowed( $blog_id, $install ) ) {
5028 FS_Permission_Manager::instance( $this )->update_site_tracking( true, $blog_id );
5029 }
5030 }
5031 }
5032 }
5033
5034 /**
5035 * 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.
5036 *
5037 * @param string[] $permissions
5038 * @param bool $is_enabled
5039 * @param int|null $blog_id
5040 *
5041 * @return array
5042 */
5043 private function update_tracking_permissions( $permissions, $is_enabled, $blog_id = null ) {
5044 // Alias.
5045 $permission_manager = FS_Permission_Manager::instance( $this );
5046
5047 $network_or_blog_ids = is_numeric( $blog_id ) ?
5048 $blog_id :
5049 fs_is_network_admin();
5050
5051 if ( true === $network_or_blog_ids ) {
5052 // Update the permission for all non-delegated sub-sites.
5053 $blog_ids = $this->get_non_delegated_blog_ids();
5054
5055 // Add the network-level to the array, to update the permission on the network-level storage.
5056 array_unshift( $blog_ids, null );
5057 }
5058 else
5059 {
5060 if ( false === $network_or_blog_ids ) {
5061 $network_or_blog_ids = null;
5062 }
5063
5064 $blog_ids = is_array( $network_or_blog_ids ) ?
5065 $network_or_blog_ids :
5066 array( $network_or_blog_ids );
5067 }
5068
5069 $result = array();
5070 foreach ( $permissions as $permission ) {
5071 $permission = trim( $permission );
5072 $is_permission_supported = true;
5073
5074 foreach ( $blog_ids as $id ) {
5075 $is_permission_supported = $permission_manager->update_permission_tracking_flag(
5076 $permission,
5077 $is_enabled,
5078 $id
5079 );
5080 }
5081
5082 if ( ! $is_permission_supported ) {
5083 $permission = 'no_match';
5084 }
5085
5086 $result[ $permission ] = $is_enabled;
5087 }
5088
5089 return $result;
5090 }
5091
5092 /**
5093 * Parse plugin's settings (as defined by the plugin dev).
5094 *
5095 * @author Vova Feldman (@svovaf)
5096 * @since 1.1.7.3
5097 *
5098 * @param array $plugin_info
5099 *
5100 * @throws \Freemius_Exception
5101 */
5102 private function parse_settings( &$plugin_info ) {
5103 $this->_logger->entrance();
5104
5105 $id = $this->get_numeric_option( $plugin_info, 'id', false );
5106 $public_key = $this->get_option( $plugin_info, 'public_key', false );
5107 $secret_key = $this->get_option( $plugin_info, 'secret_key', null );
5108 $parent_id = $this->get_numeric_option( $plugin_info, 'parent_id', null );
5109 $parent_name = $this->get_option( $plugin_info, 'parent_name', null );
5110
5111 /**
5112 * @author Vova Feldman (@svovaf)
5113 * @since 1.1.9 Try to pull secret key from external config.
5114 */
5115 if ( is_null( $secret_key ) && defined( "WP_FS__{$this->_slug}_SECRET_KEY" ) ) {
5116 $secret_key = constant( "WP_FS__{$this->_slug}_SECRET_KEY" );
5117 }
5118
5119 if ( isset( $plugin_info['parent'] ) ) {
5120 $parent_id = $this->get_numeric_option( $plugin_info['parent'], 'id', null );
5121 // $parent_slug = $this->get_option( $plugin_info['parent'], 'slug', null );
5122 // $parent_public_key = $this->get_option( $plugin_info['parent'], 'public_key', null );
5123 // $parent_name = $this->get_option( $plugin_info['parent'], 'name', null );
5124 }
5125
5126 if ( false === $id ) {
5127 throw new Freemius_Exception( array(
5128 'error' => array(
5129 'type' => 'ParameterNotSet',
5130 'message' => 'Plugin id parameter is not set.',
5131 'code' => 'plugin_id_not_set',
5132 'http' => 500,
5133 )
5134 ) );
5135 }
5136 if ( false === $public_key ) {
5137 throw new Freemius_Exception( array(
5138 'error' => array(
5139 'type' => 'ParameterNotSet',
5140 'message' => 'Plugin public_key parameter is not set.',
5141 'code' => 'plugin_public_key_not_set',
5142 'http' => 500,
5143 )
5144 ) );
5145 }
5146
5147 $plugin = ( $this->_plugin instanceof FS_Plugin ) ?
5148 $this->_plugin :
5149 new FS_Plugin();
5150
5151 $premium_suffix = $this->get_option( $plugin_info, 'premium_suffix', '(Premium)' );
5152
5153 $plugin->update( array(
5154 'id' => $id,
5155 'type' => $this->get_option( $plugin_info, 'type', $this->_module_type ),
5156 'public_key' => $public_key,
5157 'slug' => $this->_slug,
5158 'premium_slug' => $this->get_option( $plugin_info, 'premium_slug', "{$this->_slug}-premium" ),
5159 'parent_plugin_id' => $parent_id,
5160 'version' => $this->get_plugin_version(),
5161 'title' => $this->get_plugin_name( $premium_suffix ),
5162 'file' => $this->_plugin_basename,
5163 'is_premium' => $this->get_bool_option( $plugin_info, 'is_premium', true ),
5164 'premium_suffix' => $premium_suffix,
5165 'is_live' => $this->get_bool_option( $plugin_info, 'is_live', true ),
5166 'affiliate_moderation' => $this->get_option( $plugin_info, 'has_affiliation' ),
5167 'bundle_id' => $this->get_option( $plugin_info, 'bundle_id', null ),
5168 'bundle_public_key' => $this->get_option( $plugin_info, 'bundle_public_key', null ),
5169 'opt_in_moderation' => $this->get_option(
5170 $plugin_info,
5171 'opt_in',
5172 // For backward compatibility, we support both parameter names: opt_in and opt_in_moderation.
5173 $this->get_option( $plugin_info, 'opt_in_moderation', null )
5174 ),
5175 ) );
5176
5177 if ( $plugin->is_updated() ) {
5178 // Update plugin details.
5179 $this->_plugin = FS_Plugin_Manager::instance( $this->_module_id )->store( $plugin );
5180 }
5181 // Set the secret key after storing the plugin, we don't want to store the key in the storage.
5182 $this->_plugin->secret_key = $secret_key;
5183
5184 /**
5185 * 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).
5186 *
5187 * @author Vova Feldman
5188 * @since 2.4.5
5189 */
5190 if ( $this->is_network_active() && fs_is_network_admin() ) {
5191 if ( isset( $plugin_info['menu_network'] ) &&
5192 is_array( $plugin_info['menu_network'] ) &&
5193 ! empty( $plugin_info['menu_network'] )
5194 ) {
5195 $plugin_info['menu'] = $plugin_info['menu_network'];
5196 }
5197 }
5198
5199 if ( ! isset( $plugin_info['menu'] ) ) {
5200 $plugin_info['menu'] = array();
5201
5202 if ( ! empty( $this->_storage->sdk_last_version ) &&
5203 version_compare( $this->_storage->sdk_last_version, '1.1.2', '<=' )
5204 ) {
5205 // Backward compatibility to 1.1.2
5206 $plugin_info['menu']['slug'] = isset( $plugin_info['menu_slug'] ) ?
5207 $plugin_info['menu_slug'] :
5208 $this->_slug;
5209 }
5210 }
5211
5212 $this->_menu = FS_Admin_Menu_Manager::instance(
5213 $this->_module_id,
5214 $this->_module_type,
5215 $this->get_unique_affix()
5216 );
5217
5218 $this->_menu->init( $plugin_info['menu'], $this->is_addon() );
5219
5220 $this->_has_addons = $this->get_bool_option( $plugin_info, 'has_addons', false );
5221 $this->_has_paid_plans = $this->get_bool_option( $plugin_info, 'has_paid_plans', true );
5222 $this->_has_premium_version = $this->get_bool_option( $plugin_info, 'has_premium_version', $this->_has_paid_plans );
5223 $this->_ignore_pending_mode = $this->get_bool_option( $plugin_info, 'ignore_pending_mode', false );
5224 $this->_is_org_compliant = $this->get_bool_option( $plugin_info, 'is_org_compliant', true );
5225 $this->_is_premium_only = $this->get_bool_option( $plugin_info, 'is_premium_only', false );
5226 if ( $this->_is_premium_only ) {
5227 // If premium only plugin, disable anonymous mode.
5228 $this->_enable_anonymous = false;
5229 $this->_anonymous_mode = false;
5230 } else {
5231 $this->_enable_anonymous = $this->get_bool_option( $plugin_info, 'enable_anonymous', true );
5232 $this->_anonymous_mode = $this->get_bool_option( $plugin_info, 'anonymous_mode', false );
5233 }
5234 $this->_permissions = $this->get_option( $plugin_info, 'permissions', array() );
5235 $this->_is_bundle_license_auto_activation_enabled = $this->get_option( $plugin_info, 'bundle_license_auto_activation', false );
5236
5237 if ( ! empty( $plugin_info['trial'] ) ) {
5238 $this->_trial_days = $this->get_numeric_option(
5239 $plugin_info['trial'],
5240 'days',
5241 // Default to 0 - trial without days specification.
5242 0
5243 );
5244
5245 $this->_is_trial_require_payment = $this->get_bool_option( $plugin_info['trial'], 'is_require_payment', false );
5246 }
5247
5248 $this->_navigation = $this->get_option(
5249 $plugin_info,
5250 'navigation',
5251 $this->is_free_wp_org_theme() ?
5252 self::NAVIGATION_TABS :
5253 self::NAVIGATION_MENU
5254 );
5255 }
5256
5257 /**
5258 * @param string[] $options
5259 * @param string $key
5260 * @param mixed $default
5261 *
5262 * @return bool
5263 */
5264 private function get_option( &$options, $key, $default = false ) {
5265 return ! empty( $options[ $key ] ) ? $options[ $key ] : $default;
5266 }
5267
5268 private function get_bool_option( &$options, $key, $default = false ) {
5269 return isset( $options[ $key ] ) && is_bool( $options[ $key ] ) ? $options[ $key ] : $default;
5270 }
5271
5272 private function get_numeric_option( &$options, $key, $default = false ) {
5273 return isset( $options[ $key ] ) && is_numeric( $options[ $key ] ) ? $options[ $key ] : $default;
5274 }
5275
5276 /**
5277 * Gate keeper.
5278 *
5279 * @author Vova Feldman (@svovaf)
5280 * @since 1.1.7.3
5281 *
5282 * @return bool
5283 */
5284 private function should_stop_execution() {
5285 if ( empty( $this->_storage->was_plugin_loaded ) ) {
5286 /**
5287 * Don't execute Freemius until plugin was fully loaded at least once,
5288 * to give the opportunity for the activation hook to run before pinging
5289 * the API for connectivity test. This logic is relevant for the
5290 * identification of new plugin install vs. plugin update.
5291 *
5292 * @author Vova Feldman (@svovaf)
5293 * @since 1.1.9
5294 */
5295 return true;
5296 }
5297
5298 if ( $this->is_activation_mode() ) {
5299 if ( ! is_admin() ) {
5300 /**
5301 * If in activation mode, don't execute Freemius outside the admin dashboard.
5302 *
5303 * @author Vova Feldman (@svovaf)
5304 * @since 1.1.7.3
5305 */
5306 return true;
5307 }
5308
5309 if ( ! WP_FS__IS_HTTP_REQUEST ) {
5310 /**
5311 * If in activation and executed without HTTP context (e.g. CLI, Cronjob),
5312 * then don't start Freemius.
5313 *
5314 * @author Vova Feldman (@svovaf)
5315 * @since 1.1.6.3
5316 *
5317 * @link https://wordpress.org/support/topic/errors-in-the-freemius-class-when-running-in-wordpress-in-cli
5318 */
5319 return true;
5320 }
5321
5322 if ( self::is_cron() ) {
5323 /**
5324 * If in activation mode, don't execute Freemius during wp crons
5325 * (wp crons have HTTP context - called as HTTP request).
5326 *
5327 * @author Vova Feldman (@svovaf)
5328 * @since 1.1.7.3
5329 */
5330 return true;
5331 }
5332
5333 if ( self::is_ajax() ) {
5334 /**
5335 * During activation, if running in AJAX mode, unless there's a sticky
5336 * connectivity issue notice, don't run Freemius.
5337 *
5338 * @author Vova Feldman (@svovaf)
5339 * @since 1.1.7.3
5340 */
5341 return true;
5342 }
5343 }
5344
5345 return false;
5346 }
5347
5348 /**
5349 * Triggered after code type has changed.
5350 *
5351 * @author Vova Feldman (@svovaf)
5352 * @since 1.1.9.1
5353 */
5354 function _after_code_type_change() {
5355 $this->_logger->entrance();
5356
5357 if ( $this->is_theme() ) {
5358 // Expire the cache of the previous tabs since the theme may
5359 // have setting updates after code type has changed.
5360 $this->_cache->expire( 'tabs' );
5361 $this->_cache->expire( 'tabs_stylesheets' );
5362 }
5363
5364 if ( ! $this->is_addon() ) {
5365 add_action(
5366 is_admin() ? 'admin_init' : 'init',
5367 array( &$this, '_plugin_code_type_changed' )
5368 );
5369 }
5370
5371 if ( $this->is_registered() && $this->is_premium() ) {
5372 // Purge cached payments after switching to the premium version.
5373 // @todo This logic doesn't handle purging the cache for serviceware module upgrade.
5374 $this->get_api_user_scope()->purge_cache( "/plugins/{$this->_module_id}/payments.json?include_addons=true" );
5375 }
5376 }
5377
5378 /**
5379 * Handles plugin's code type change (free <--> premium).
5380 *
5381 * @author Vova Feldman (@svovaf)
5382 * @since 1.0.9
5383 */
5384 function _plugin_code_type_changed() {
5385 $this->_logger->entrance();
5386
5387 if ( $this->is_premium() ) {
5388 $this->reconnect_locally();
5389
5390 // Activated premium code.
5391 $this->do_action( 'after_premium_version_activation' );
5392
5393 // Remove all sticky messages related to download of the premium version.
5394 $this->_admin_notices->remove_sticky( array(
5395 'trial_started',
5396 'plan_upgraded',
5397 'plan_changed',
5398 'license_activated',
5399 ) );
5400
5401 $notice = '';
5402 if ( ! $this->is_only_premium() ) {
5403 $notice = sprintf( $this->get_text_inline( 'Premium %s version was successfully activated.', 'premium-activated-message' ), $this->_module_type );
5404 }
5405
5406 $license_notice = $this->get_license_network_activation_notice();
5407 if ( ! empty( $license_notice ) ) {
5408 $notice .= ' ' . $license_notice;
5409 }
5410
5411 if ( ! empty( $notice ) ) {
5412 $this->_admin_notices->add_sticky(
5413 trim( $notice ),
5414 'premium_activated',
5415 $this->get_text_x_inline( 'W00t',
5416 'Used to express elation, enthusiasm, or triumph (especially in electronic communication).', 'woot' ) . '!'
5417 );
5418 }
5419 } else {
5420 // Remove sticky message related to premium code activation.
5421 $this->_admin_notices->remove_sticky( 'premium_activated' );
5422
5423 // Activated free code (after had the premium before).
5424 $this->do_action( 'after_free_version_reactivation' );
5425
5426 if ( $this->is_paying() && ! $this->is_premium() ) {
5427 $this->add_complete_upgrade_instructions_notice(
5428 sprintf(
5429 /* translators: %s: License type (e.g. you have a professional license) */
5430 $this->get_text_inline( 'You have a %s license.', 'you-have-x-license' ),
5431 $this->get_plan_title()
5432 ),
5433 'plan_upgraded'
5434 );
5435 }
5436 }
5437
5438 if ( $this->is_registered() ) {
5439 // Schedule code type changes event.
5440 $this->schedule_install_sync();
5441 }
5442
5443 /**
5444 * Unregister the uninstall hook for the other version of the plugin (with different code type) to avoid
5445 * triggering a fatal error when uninstalling that plugin. For example, after deactivating the "free" version
5446 * of a specific plugin, its uninstall hook should be unregistered after the "premium" version has been
5447 * activated. If we don't do that, a fatal error will occur when we try to uninstall the "free" version since
5448 * the main file of the "free" version will be loaded first before calling the hooked callback. Since the
5449 * free and premium versions are almost identical (same class or have same functions), a fatal error like
5450 * "Cannot redeclare class MyClass" or "Cannot redeclare my_function()" will occur.
5451 */
5452 $this->unregister_uninstall_hook();
5453
5454 $this->clear_module_main_file_cache();
5455
5456 // Update is_premium of latest version.
5457 $this->_storage->prev_is_premium = $this->_plugin->is_premium;
5458 }
5459
5460 #endregion
5461
5462 #----------------------------------------------------------------------------------
5463 #region Add-ons
5464 #----------------------------------------------------------------------------------
5465
5466 /**
5467 * Check if add-on installed and activated on site.
5468 *
5469 * @author Vova Feldman (@svovaf)
5470 * @since 1.0.6
5471 *
5472 * @param string|number $id_or_slug
5473 * @param bool|null $is_premium Since 1.2.1.7 can check for specified add-on version.
5474 *
5475 * @return bool
5476 */
5477 function is_addon_activated( $id_or_slug, $is_premium = null ) {
5478 $this->_logger->entrance();
5479
5480 $addon_id = self::get_module_id( $id_or_slug );
5481 $is_activated = self::has_instance( $addon_id );
5482
5483 if ( ! $is_activated ) {
5484 return false;
5485 }
5486
5487 if ( is_bool( $is_premium ) ) {
5488 // Check if the specified code version is activate.
5489 $addon = $this->get_addon_instance( $addon_id );
5490 $is_activated = ( $is_premium === $addon->is_premium() );
5491 }
5492
5493 return $is_activated;
5494 }
5495
5496 /**
5497 * Check if add-on was connected to install
5498 *
5499 * @author Vova Feldman (@svovaf)
5500 * @since 1.1.7
5501 *
5502 * @param string|number $id_or_slug
5503 *
5504 * @return bool
5505 */
5506 function is_addon_connected( $id_or_slug ) {
5507 $this->_logger->entrance();
5508
5509 $sites = self::get_all_sites( WP_FS__MODULE_TYPE_PLUGIN );
5510
5511 $addon_id = self::get_module_id( $id_or_slug );
5512 $addon = $this->get_addon( $addon_id );
5513 $slug = $addon->slug;
5514 if ( ! isset( $sites[ $slug ] ) ) {
5515 return false;
5516 }
5517
5518 $site = $sites[ $slug ];
5519
5520 $plugin = FS_Plugin_Manager::instance( $addon_id )->get();
5521
5522 if ( $plugin->parent_plugin_id != $this->_plugin->id ) {
5523 // The given slug do NOT belong to any of the plugin's add-ons.
5524 return false;
5525 }
5526
5527 return ( is_object( $site ) &&
5528 is_numeric( $site->id ) &&
5529 is_numeric( $site->user_id ) &&
5530 FS_Plugin_Plan::is_valid_id( $site->plan_id )
5531 );
5532 }
5533
5534 /**
5535 * Determines if add-on installed.
5536 *
5537 * NOTE: This is a heuristic and only works if the folder/file named as the slug.
5538 *
5539 * @author Vova Feldman (@svovaf)
5540 * @since 1.0.6
5541 *
5542 * @param string|number $id_or_slug
5543 *
5544 * @return bool
5545 */
5546 function is_addon_installed( $id_or_slug ) {
5547 $this->_logger->entrance();
5548
5549 $addon_id = self::get_module_id( $id_or_slug );
5550
5551 return file_exists( fs_normalize_path( WP_PLUGIN_DIR . '/' . $this->get_addon_basename( $addon_id ) ) );
5552 }
5553
5554 /**
5555 * Get add-on basename.
5556 *
5557 * @author Vova Feldman (@svovaf)
5558 * @since 1.0.6
5559 *
5560 * @param string|number $id_or_slug
5561 *
5562 * @return string
5563 */
5564 function get_addon_basename( $id_or_slug ) {
5565 $addon_id = self::get_module_id( $id_or_slug );
5566
5567 if ( $this->is_addon_activated( $addon_id ) ) {
5568 return self::instance( $addon_id )->get_plugin_basename();
5569 }
5570
5571 $addon = $this->get_addon( $addon_id );
5572 $premium_basename = "{$addon->premium_slug}/{$addon->slug}.php";
5573
5574 if ( file_exists( fs_normalize_path( WP_PLUGIN_DIR . '/' . $premium_basename ) ) ) {
5575 return $premium_basename;
5576 }
5577
5578 $all_plugins = $this->get_all_plugins();
5579
5580 foreach ( $all_plugins as $basename => $data ) {
5581 if ( $addon->slug === $data['slug'] ||
5582 $addon->premium_slug === $data['slug']
5583 ) {
5584 return $basename;
5585 }
5586 }
5587
5588 $free_basename = "{$addon->slug}/{$addon->slug}.php";
5589
5590 return $free_basename;
5591 }
5592
5593 /**
5594 * Get installed add-ons instances.
5595 *
5596 * @author Vova Feldman (@svovaf)
5597 * @since 1.0.6
5598 *
5599 * @return Freemius[]
5600 */
5601 function get_installed_addons() {
5602 if ( $this->is_addon() ) {
5603 // Add-on cannot have add-ons.
5604 return array();
5605 }
5606
5607 $installed_addons = array();
5608
5609 foreach ( self::$_instances as $instance ) {
5610 if ( $instance->is_addon_of( $this->_plugin->id ) ) {
5611 $installed_addons[] = $instance;
5612 }
5613 }
5614
5615 return $installed_addons;
5616 }
5617
5618 /**
5619 * Check if any add-ons of the plugin are installed.
5620 *
5621 * @author Leo Fajardo (@leorw)
5622 * @since 1.1.1
5623 *
5624 * @return bool
5625 */
5626 function has_installed_addons() {
5627 if ( ! $this->has_addons() ) {
5628 return false;
5629 }
5630
5631 foreach ( self::$_instances as $instance ) {
5632 if ( $instance->is_addon() && is_object( $instance->_parent_plugin ) ) {
5633 if ( $this->_plugin->id == $instance->_parent_plugin->id ) {
5634 return true;
5635 }
5636 }
5637 }
5638
5639 return false;
5640 }
5641
5642 /**
5643 * Tell Freemius that the current plugin is an add-on.
5644 *
5645 * @author Vova Feldman (@svovaf)
5646 * @since 1.0.6
5647 *
5648 * @param number $parent_plugin_id The parent plugin ID
5649 */
5650 function init_addon( $parent_plugin_id ) {
5651 $this->_plugin->parent_plugin_id = $parent_plugin_id;
5652 }
5653
5654 /**
5655 * @author Vova Feldman (@svovaf)
5656 * @since 1.0.6
5657 *
5658 * @return bool
5659 */
5660 function is_addon() {
5661 return (
5662 isset( $this->_plugin->parent_plugin_id ) &&
5663 is_numeric( $this->_plugin->parent_plugin_id )
5664 );
5665 }
5666
5667 /**
5668 * @author Vova Feldman (@svovaf)
5669 * @since 2.3.2
5670 *
5671 * @param number $parent_product_id
5672 *
5673 * @return bool
5674 */
5675 function is_addon_of( $parent_product_id ) {
5676 return (
5677 $this->is_addon() &&
5678 $parent_product_id == $this->_plugin->parent_plugin_id
5679 );
5680 }
5681
5682 /**
5683 * Deactivate add-on if it's premium only and the user does't have a valid license.
5684 *
5685 * @param bool $is_after_trial_cancel
5686 *
5687 * @return bool If add-on was deactivated.
5688 */
5689 private function deactivate_premium_only_addon_without_license( $is_after_trial_cancel = false ) {
5690 if ( ! $this->has_free_plan() &&
5691 ! $this->has_features_enabled_license() &&
5692 ! $this->_has_premium_license()
5693 ) {
5694 if ( $this->is_registered() ) {
5695 // IF wrapper is turned off because activation_timestamp is currently only stored for plugins (not addons).
5696 // if (empty($this->_storage->activation_timestamp) ||
5697 // (WP_FS__SCRIPT_START_TIME - $this->_storage->activation_timestamp) > 30
5698 // ) {
5699 /**
5700 * @todo When it's first fail, there's no reason to try and re-sync because the licenses were just synced after initial activation.
5701 *
5702 * Retry syncing the user add-on licenses.
5703 */
5704 // Sync licenses.
5705 $this->_sync_licenses();
5706 // }
5707
5708 // Try to activate premium license.
5709 $this->_activate_license( true );
5710 }
5711
5712 if ( ! $this->has_free_plan() &&
5713 ! $this->has_features_enabled_license() &&
5714 ! $this->_has_premium_license()
5715 ) {
5716 // @todo Check if deactivate plugins also call the deactivation hook.
5717
5718 $this->_parent->_admin_notices->add_sticky(
5719 sprintf(
5720 ( $is_after_trial_cancel ?
5721 $this->_parent->get_text_inline(
5722 '%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.',
5723 'addon-trial-cancelled-message'
5724 ) :
5725 $this->_parent->get_text_inline(
5726 '%s is a premium only add-on. You have to purchase a license first before activating the plugin.',
5727 'addon-no-license-message'
5728 )
5729 ),
5730 '<b>' . $this->_plugin->title . '</b>'
5731 ) . ' ' . sprintf(
5732 '<a href="%s" aria-label="%s" class="button button-primary" style="margin-left: 10px; vertical-align: middle;">%s &nbsp;&#10140;</a>',
5733 $this->_parent->addon_url( $this->_slug ),
5734 esc_attr( sprintf( $this->_parent->get_text_inline( 'More information about %s', 'more-information-about-x' ), $this->_plugin->title ) ),
5735 $this->_parent->get_text_inline( 'Purchase License', 'purchase-license' )
5736 ),
5737 'no_addon_license_' . $this->_slug,
5738 ( $is_after_trial_cancel ? '' : $this->_parent->get_text_x_inline( 'Oops', 'exclamation', 'oops' ) . '...' ),
5739 ( $is_after_trial_cancel ? 'success' : 'error' )
5740 );
5741
5742 deactivate_plugins( array( $this->_plugin_basename ), true );
5743
5744 return true;
5745 }
5746 }
5747
5748 return false;
5749 }
5750
5751 #endregion
5752
5753 #----------------------------------------------------------------------------------
5754 #region Sandbox
5755 #----------------------------------------------------------------------------------
5756
5757 /**
5758 * Set Freemius into sandbox mode for debugging.
5759 *
5760 * @author Vova Feldman (@svovaf)
5761 * @since 1.0.4
5762 *
5763 * @param string $secret_key
5764 */
5765 function init_sandbox( $secret_key ) {
5766 $this->_plugin->secret_key = $secret_key;
5767
5768 // Update plugin details.
5769 FS_Plugin_Manager::instance( $this->_module_id )->update( $this->_plugin, true );
5770 }
5771
5772 /**
5773 * Check if running payments in sandbox mode.
5774 *
5775 * @author Vova Feldman (@svovaf)
5776 * @since 1.0.4
5777 *
5778 * @return bool
5779 */
5780 function is_payments_sandbox() {
5781 return ( ! $this->is_live() ) || isset( $this->_plugin->secret_key );
5782 }
5783
5784 #endregion
5785
5786 /**
5787 * Check if running test vs. live plugin.
5788 *
5789 * @author Vova Feldman (@svovaf)
5790 * @since 1.0.5
5791 *
5792 * @return bool
5793 */
5794 function is_live() {
5795 return $this->_plugin->is_live;
5796 }
5797
5798 /**
5799 * Check if super-admin skipped connection for all sites in the network.
5800 *
5801 * @author Vova Feldman (@svovaf)
5802 * @since 2.0.0
5803 */
5804 function is_network_anonymous() {
5805 if ( ! $this->_is_network_active ) {
5806 return false;
5807 }
5808
5809 $is_anonymous_ms = $this->_storage->get( 'is_anonymous_ms' );
5810
5811 if ( empty( $is_anonymous_ms ) ) {
5812 return false;
5813 }
5814
5815 return $is_anonymous_ms['is'];
5816 }
5817
5818 /**
5819 * Check if super-admin opted-in for all sites in the network.
5820 *
5821 * @author Vova Feldman (@svovaf)
5822 * @since 2.0.0
5823 */
5824 function is_network_connected() {
5825 if ( ! $this->_is_network_active ) {
5826 return false;
5827 }
5828
5829 return $this->_storage->get( 'is_network_connected' );
5830 }
5831
5832 /**
5833 * Check if the user skipped connecting the account with Freemius.
5834 *
5835 * @author Vova Feldman (@svovaf)
5836 * @since 1.0.7
5837 *
5838 * @return bool
5839 */
5840 function is_anonymous() {
5841 if ( ! isset( $this->_is_anonymous ) ) {
5842 if ( $this->is_network_anonymous() ) {
5843 $this->_is_anonymous = true;
5844 } else if ( fs_is_network_admin() ) {
5845 /**
5846 * When not-network-anonymous, yet, running in the network admin, consider as anonymous only when ALL non-delegated sites are set to anonymous.
5847 */
5848 $non_delegated_sites = $this->get_non_delegated_blog_ids();
5849
5850 foreach ( $non_delegated_sites as $blog_id ) {
5851 $is_anonymous = $this->_storage->get( 'is_anonymous', false, $blog_id );
5852
5853 if ( empty( $is_anonymous ) || false === $is_anonymous[ 'is' ] ) {
5854 $this->_is_anonymous = false;
5855 break;
5856 }
5857 }
5858
5859 if ( false !== $this->_is_anonymous ) {
5860 $this->_is_anonymous = true;
5861 }
5862 } else {
5863 if ( ! isset( $this->_storage->is_anonymous ) ) {
5864 // Not skipped.
5865 $this->_is_anonymous = false;
5866 } else if ( is_bool( $this->_storage->is_anonymous ) ) {
5867 // For back compatibility, since the variable was boolean before.
5868 $this->_is_anonymous = $this->_storage->is_anonymous;
5869
5870 // Upgrade stored data format to 1.1.3 format.
5871 $this->set_anonymous_mode( $this->_storage->is_anonymous );
5872 } else {
5873 // Version 1.1.3 and later.
5874 $this->_is_anonymous = $this->_storage->is_anonymous['is'];
5875 }
5876 }
5877 }
5878
5879 return $this->_is_anonymous;
5880 }
5881
5882 /**
5883 * Check if the user skipped the connection of a specified site.
5884 *
5885 * @author Vova Feldman (@svovaf)
5886 * @since 2.0.0
5887 *
5888 * @param int $blog_id
5889 *
5890 * @return bool
5891 */
5892 function is_anonymous_site( $blog_id = 0 ) {
5893 if ( $this->is_network_anonymous() ) {
5894 return true;
5895 }
5896
5897 $is_anonymous = $this->_storage->get( 'is_anonymous', false, $blog_id );
5898
5899 if ( empty( $is_anonymous ) ) {
5900 return false;
5901 }
5902
5903 return $is_anonymous['is'];
5904 }
5905
5906 /**
5907 * Check if user connected his account and install pending email activation.
5908 *
5909 * @author Vova Feldman (@svovaf)
5910 * @since 1.0.7
5911 *
5912 * @return bool
5913 */
5914 function is_pending_activation() {
5915 return $this->_storage->get( 'is_pending_activation', false );
5916 }
5917
5918 /**
5919 * @author Leo Fajardo (@leorw)
5920 * @since 2.5.0
5921 */
5922 private function clear_pending_activation_mode() {
5923 // Remove the pending activation sticky notice (if it still exists).
5924 $this->_admin_notices->remove_sticky( 'activation_pending' );
5925
5926 // Clear the plugin's pending activation mode.
5927 unset( $this->_storage->is_pending_activation );
5928 }
5929
5930 /**
5931 * Check if plugin must be WordPress.org compliant.
5932 *
5933 * @since 1.0.7
5934 *
5935 * @return bool
5936 */
5937 function is_org_repo_compliant() {
5938 return $this->_is_org_compliant;
5939 }
5940
5941 #--------------------------------------------------------------------------------
5942 #region WP Cron Common
5943 #--------------------------------------------------------------------------------
5944
5945 /**
5946 * @author Vova Feldman (@svovaf)
5947 * @since 2.0.0
5948 *
5949 * @param string $name Cron name.
5950 *
5951 * @return object
5952 */
5953 private function get_cron_data( $name ) {
5954 $this->_logger->entrance( $name );
5955
5956 /**
5957 * @var object $cron_data
5958 */
5959 return $this->_storage->get( "{$name}_cron", null );
5960 }
5961
5962 /**
5963 * @author Vova Feldman (@svovaf)
5964 * @since 2.0.0
5965 *
5966 * @param string $name Cron name.
5967 */
5968 private function clear_cron_data( $name ) {
5969 $this->_logger->entrance( $name );
5970
5971 $this->_storage->remove( "{$name}_cron" );
5972 }
5973
5974 /**
5975 * @author Vova Feldman (@svovaf)
5976 * @since 2.0.0
5977 *
5978 * @param string $name Cron name.
5979 * @param int $cron_blog_id The cron executing blog ID.
5980 */
5981 private function set_cron_data( $name, $cron_blog_id = 0 ) {
5982 $this->_logger->entrance( $name );
5983
5984 $this->_storage->store( "{$name}_cron", (object) array(
5985 'version' => $this->get_plugin_version(),
5986 'blog_id' => $cron_blog_id,
5987 'sdk_version' => $this->version,
5988 'timestamp' => WP_FS__SCRIPT_START_TIME,
5989 'on' => true,
5990 ) );
5991 }
5992
5993 /**
5994 * Get the cron's executing blog ID.
5995 *
5996 * @author Vova Feldman (@svovaf)
5997 * @since 2.0.0
5998 *
5999 * @param string $name Cron name.
6000 *
6001 * @return int
6002 */
6003 private function get_cron_blog_id( $name ) {
6004 $this->_logger->entrance( $name );
6005
6006 if ( ! is_multisite() ) {
6007 // Not a multisite.
6008 return 0;
6009 }
6010
6011 $cron_data = $this->get_cron_data( $name );
6012
6013 return ( is_object( $cron_data ) && is_numeric( $cron_data->blog_id ) ) ?
6014 $cron_data->blog_id :
6015 0;
6016 }
6017
6018 /**
6019 * @author Vova Feldman (@svovaf)
6020 * @since 2.0.0
6021 *
6022 * @param string $name Cron name.
6023 *
6024 * @return bool
6025 */
6026 private function is_cron_on( $name ) {
6027 $this->_logger->entrance( $name );
6028
6029 /**
6030 * @var object $cron_data
6031 */
6032 $cron_data = $this->get_cron_data( $name );
6033
6034 return ( ! is_null( $cron_data ) && true === $cron_data->on );
6035 }
6036
6037 /**
6038 * Unix timestamp for previous cron execution or false if never executed.
6039 *
6040 * @author Vova Feldman (@svovaf)
6041 * @since 2.0.0
6042 *
6043 * @param string $name Cron name.
6044 *
6045 * @return int|false
6046 */
6047 private function cron_last_execution( $name ) {
6048 $this->_logger->entrance( $name );
6049
6050 return $this->_storage->get( "{$name}_timestamp" );
6051 }
6052
6053 /**
6054 * Set cron execution time to now.
6055 *
6056 * @author Vova Feldman (@svovaf)
6057 * @since 2.0.0
6058 *
6059 * @param string $name Cron name.
6060 */
6061 private function set_cron_execution_timestamp( $name ) {
6062 $this->_logger->entrance( $name );
6063
6064 $this->_storage->store( "{$name}_timestamp", time() );
6065 }
6066
6067 /**
6068 * Sets the keepalive time to now.
6069 *
6070 * @author Leo Fajardo (@leorw)
6071 * @since 2.2.3
6072 *
6073 * @param bool|null $use_network_level_storage
6074 */
6075 private function set_keepalive_timestamp( $use_network_level_storage = null ) {
6076 $this->_logger->entrance();
6077
6078 $this->_storage->store( 'keepalive_timestamp', time(), $use_network_level_storage );
6079 }
6080
6081 /**
6082 * Check if cron was executed in the last $period of seconds.
6083 *
6084 * @author Vova Feldman (@svovaf)
6085 * @since 2.0.0
6086 *
6087 * @param string $name Cron name.
6088 * @param int $period In seconds
6089 *
6090 * @return bool
6091 */
6092 private function is_cron_executed( $name, $period = WP_FS__TIME_24_HOURS_IN_SEC ) {
6093 $this->_logger->entrance( $name );
6094
6095 $last_execution = $this->cron_last_execution( $name );
6096
6097 if ( ! is_numeric( $last_execution ) ) {
6098 return false;
6099 }
6100
6101 return ( $last_execution > ( WP_FS__SCRIPT_START_TIME - $period ) );
6102 }
6103
6104 /**
6105 * WP Cron is executed on a site level. When running in a multisite network environment
6106 * with the network integration activated, for optimization reasons, we are consolidating
6107 * the installs data sync cron to be executed only from a single site.
6108 *
6109 * @author Vova Feldman (@svovaf)
6110 * @since 2.0.0
6111 *
6112 * @param int $except_blog_id Target any except the excluded blog ID.
6113 *
6114 * @return int
6115 */
6116 private function get_cron_target_blog_id( $except_blog_id = 0 ) {
6117 if ( ! is_multisite() ) {
6118 return 0;
6119 }
6120
6121 if ( $this->_is_network_active ) {
6122 $network_install_blog_id = $this->_storage->network_install_blog_id;
6123
6124 if (
6125 is_numeric( $network_install_blog_id ) &&
6126 $except_blog_id != $network_install_blog_id &&
6127 self::is_site_active( $network_install_blog_id )
6128 ) {
6129 // Try to run cron from the main network blog.
6130 $install = $this->get_install_by_blog_id( $network_install_blog_id );
6131
6132 if (
6133 is_object( $install ) &&
6134 $this->is_tracking_allowed( $network_install_blog_id, $install )
6135 ) {
6136 return $network_install_blog_id;
6137 }
6138 }
6139 }
6140
6141 // Get first opted-in blog ID with active tracking.
6142 $installs = $this->get_blog_install_map();
6143 foreach ( $installs as $blog_id => $install ) {
6144 if ( $except_blog_id != $blog_id &&
6145 self::is_site_active( $blog_id ) &&
6146 $this->is_tracking_allowed( $blog_id, $install )
6147 ) {
6148 return $blog_id;
6149 }
6150 }
6151
6152 return 0;
6153 }
6154
6155 /**
6156 * @author Vova Feldman (@svovaf)
6157 * @since 2.0.0
6158 *
6159 * @param string $name Cron name.
6160 * @param string $action_tag Callback action tag.
6161 * @param bool $is_network_clear If set to TRUE, clear sync cron even if there are installs that are still connected.
6162 */
6163 private function clear_cron( $name, $action_tag = '', $is_network_clear = false ) {
6164 $this->_logger->entrance( $name );
6165
6166 if ( ! $this->is_cron_on( $name ) ) {
6167 return;
6168 }
6169
6170 $clear_cron = true;
6171 if ( ! $is_network_clear && $this->_is_network_active ) {
6172 $installs = $this->get_blog_install_map();
6173
6174 foreach ( $installs as $blog_id => $install ) {
6175 /**
6176 * @var FS_Site $install
6177 */
6178 if ( $this->is_tracking_allowed( $blog_id, $install ) ) {
6179 $clear_cron = false;
6180 break;
6181 }
6182 }
6183 }
6184
6185 if ( ! $clear_cron ) {
6186 return;
6187 }
6188
6189 $cron_blog_id = $this->get_cron_blog_id( $name );
6190
6191 $this->clear_cron_data( $name );
6192
6193 if ( 0 < $cron_blog_id ) {
6194 switch_to_blog( $cron_blog_id );
6195 }
6196
6197 if ( empty( $action_tag ) ) {
6198 $action_tag = $name;
6199 }
6200
6201 wp_clear_scheduled_hook( $this->get_action_tag( $action_tag ) );
6202
6203 if ( 0 < $cron_blog_id ) {
6204 restore_current_blog();
6205 }
6206 }
6207
6208 /**
6209 * Unix timestamp for next cron execution or false if not scheduled.
6210 *
6211 * @author Vova Feldman (@svovaf)
6212 * @since 2.0.0
6213 *
6214 * @param string $name Cron name.
6215 * @param string $action_tag Callback action tag.
6216 *
6217 * @return int|false
6218 */
6219 private function get_next_scheduled_cron( $name, $action_tag = '' ) {
6220 $this->_logger->entrance( $name );
6221
6222 if ( ! $this->is_cron_on( $name ) ) {
6223 return false;
6224 }
6225
6226 $cron_blog_id = $this->get_cron_blog_id( $name );
6227
6228 if ( 0 < $cron_blog_id ) {
6229 switch_to_blog( $cron_blog_id );
6230 }
6231
6232 if ( empty( $action_tag ) ) {
6233 $action_tag = $name;
6234 }
6235
6236 $next_scheduled = wp_next_scheduled( $this->get_action_tag( $action_tag ) );
6237
6238 if ( 0 < $cron_blog_id ) {
6239 restore_current_blog();
6240 }
6241
6242 return $next_scheduled;
6243 }
6244
6245 /**
6246 * @author Vova Feldman (@svovaf)
6247 * @since 2.0.0
6248 *
6249 * @param string $name Cron name.
6250 * @param string $action_tag Callback action tag.
6251 * @param string $recurrence 'single' or 'daily'.
6252 * @param int $start_at Defaults to now.
6253 * @param bool $randomize_start If true, schedule first job randomly during the next 12 hours. Otherwise, schedule job to start right away.
6254 * @param int $except_blog_id Target any except the excluded blog ID.
6255 */
6256 private function schedule_cron(
6257 $name,
6258 $action_tag = '',
6259 $recurrence = 'single',
6260 $start_at = WP_FS__SCRIPT_START_TIME,
6261 $randomize_start = true,
6262 $except_blog_id = 0
6263 ) {
6264 $this->_logger->entrance( $name );
6265
6266 $this->clear_cron( $name, $action_tag, true );
6267
6268 $cron_blog_id = $this->get_cron_target_blog_id( $except_blog_id );
6269
6270 if ( is_multisite() && 0 == $cron_blog_id ) {
6271 // Don't schedule cron since couldn't find a target blog.
6272 return;
6273 }
6274
6275 if ( 0 < $cron_blog_id ) {
6276 switch_to_blog( $cron_blog_id );
6277 }
6278
6279 if ( 'daily' === $recurrence ) {
6280 if ( $randomize_start ) {
6281 // Schedule first sync with a random 12 hour time range from now.
6282 $start_at += rand( 0, ( WP_FS__TIME_24_HOURS_IN_SEC / 2 ) );
6283 }
6284
6285 // Schedule daily WP cron.
6286 wp_schedule_event(
6287 $start_at,
6288 'daily',
6289 $this->get_action_tag( $action_tag )
6290 );
6291 } else if ( 'single' === $recurrence ) {
6292 // Schedule single cron.
6293 wp_schedule_single_event(
6294 $start_at,
6295 $this->get_action_tag( $action_tag )
6296 );
6297 }
6298
6299 $this->set_cron_data( $name, $cron_blog_id );
6300
6301 if ( 0 < $cron_blog_id ) {
6302 restore_current_blog();
6303 }
6304 }
6305
6306 /**
6307 * Consolidated cron execution for performance optimization. The max number of API requests is based on the number of unique opted-in users.
6308 * that doesn't halt page loading.
6309 *
6310 * @author Vova Feldman (@svovaf)
6311 * @since 2.0.0
6312 *
6313 * @param string $name Cron name.
6314 * @param callable $callable The function that should be executed.
6315 */
6316 private function execute_cron( $name, $callable ) {
6317 $this->_logger->entrance( $name );
6318
6319 // Store the last time data sync was executed.
6320 $this->set_cron_execution_timestamp( $name );
6321
6322 // Check if API is temporary down.
6323 if ( FS_Api::is_temporary_down() ) {
6324 return;
6325 }
6326
6327 // @todo Add logic that identifies API latency, and reschedule the next background sync randomly between 8-16 hours.
6328
6329 $users_2_blog_ids = array();
6330
6331 if ( ! is_multisite() ) {
6332 // Add dummy blog.
6333 $users_2_blog_ids[0] = array( 0 );
6334 } else {
6335 $installs = $this->get_blog_install_map();
6336 foreach ( $installs as $blog_id => $install ) {
6337 if ( $this->is_tracking_allowed( $blog_id, $install ) ) {
6338 if ( ! isset( $users_2_blog_ids[ $install->user_id ] ) ) {
6339 $users_2_blog_ids[ $install->user_id ] = array();
6340 }
6341
6342 $users_2_blog_ids[ $install->user_id ][] = $blog_id;
6343 }
6344 }
6345 }
6346
6347 $current_blog_id = get_current_blog_id();
6348
6349 foreach ( $users_2_blog_ids as $user_id => $blog_ids ) {
6350 if ( 0 < $blog_ids[0] ) {
6351 $this->switch_to_blog( $blog_ids[0] );
6352 }
6353
6354 call_user_func_array( $callable, array( $blog_ids, ( is_multisite() ? $current_blog_id : null ) ) );
6355
6356 foreach ( $blog_ids as $blog_id ) {
6357 $this->do_action( "after_{$name}_cron", $blog_id );
6358 }
6359 }
6360
6361 if ( is_multisite() ) {
6362 $this->switch_to_blog( $current_blog_id, fs_is_network_admin() ? $this->get_network_install() : null );
6363
6364 $this->do_action( "after_{$name}_cron_multisite" );
6365 }
6366 }
6367
6368 #endregion
6369
6370 #----------------------------------------------------------------------------------
6371 #region Daily Sync Cron
6372 #----------------------------------------------------------------------------------
6373
6374
6375 /**
6376 * @author Vova Feldman (@svovaf)
6377 * @since 2.0.0
6378 *
6379 * @return bool
6380 */
6381 private function is_sync_cron_scheduled() {
6382 return $this->is_cron_on( 'sync' );
6383 }
6384
6385 /**
6386 * Get the sync cron's executing blog ID.
6387 *
6388 * @author Vova Feldman (@svovaf)
6389 * @since 2.0.0
6390 *
6391 * @return int
6392 */
6393 private function get_sync_cron_blog_id() {
6394 return $this->get_cron_blog_id( 'sync' );
6395 }
6396
6397 /**
6398 * @author Vova Feldman (@svovaf)
6399 * @since 1.1.7.3
6400 */
6401 private function run_manual_sync() {
6402 if ( ! $this->is_user_admin() ) {
6403 return;
6404 }
6405
6406 // Run manual sync.
6407 $this->_sync_cron();
6408
6409 // Reschedule next cron to run 24 hours from now (performance optimization).
6410 $this->schedule_sync_cron( time() + WP_FS__TIME_24_HOURS_IN_SEC, false );
6411 }
6412
6413 /**
6414 * Data sync cron job. Replaces the background sync non blocking HTTP request
6415 * that doesn't halt page loading.
6416 *
6417 * @author Vova Feldman (@svovaf)
6418 * @since 1.1.7.3
6419 * @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.
6420 */
6421 function _sync_cron() {
6422 $this->_logger->entrance();
6423
6424 $this->execute_cron( 'sync', array( &$this, '_sync_cron_method' ) );
6425 }
6426
6427 /**
6428 * The actual data sync cron logic.
6429 *
6430 * @author Vova Feldman (@svovaf)
6431 * @since 2.0.0
6432 *
6433 * @param int[] $blog_ids
6434 * @param int|null $current_blog_id @since 2.2.3. This is passed from the `execute_cron` method and used by the
6435 * `_sync_plugin_license` method in order to switch to the previous blog when sending
6436 * updates for a single site in case `execute_cron` has switched to a different blog.
6437 */
6438 function _sync_cron_method( array $blog_ids, $current_blog_id = null ) {
6439 if ( $this->is_registered() ) {
6440 if ( $this->has_paid_plan() ) {
6441 // Initiate background plan sync.
6442 $this->_sync_license( true, false, $current_blog_id );
6443
6444 if ( $this->is_paying() ) {
6445 // Check for premium plugin updates.
6446 $this->check_updates( true );
6447 }
6448 } else {
6449 // Sync install(s) (only if something changed locally).
6450 if ( 1 < count( $blog_ids ) ) {
6451 $this->sync_installs();
6452 } else {
6453 $this->sync_install();
6454 }
6455
6456 $this->maybe_sync_install_user();
6457 }
6458 }
6459 }
6460
6461 /**
6462 * Check if sync was executed in the last $period of seconds.
6463 *
6464 * @author Vova Feldman (@svovaf)
6465 * @since 1.1.7.3
6466 *
6467 * @param int $period In seconds
6468 *
6469 * @return bool
6470 */
6471 private function is_sync_executed( $period = WP_FS__TIME_24_HOURS_IN_SEC ) {
6472 return $this->is_cron_executed( 'sync', $period );
6473 }
6474
6475 /**
6476 * @author Vova Feldman (@svovaf)
6477 * @since 1.1.7.3
6478 *
6479 * @return bool
6480 */
6481 private function is_sync_cron_on() {
6482 return $this->is_cron_on( 'sync' );
6483 }
6484
6485 /**
6486 * @author Leo Fajardo (@leorw)
6487 * @since 2.5.0
6488 */
6489 private function maybe_schedule_sync_cron() {
6490 $next_schedule = $this->next_sync_cron();
6491
6492 // The event is properly scheduled, so no need to reschedule it.
6493 if (
6494 is_numeric( $next_schedule ) &&
6495 $next_schedule > time()
6496 ) {
6497 return;
6498 }
6499
6500 $this->schedule_sync_cron();
6501 }
6502
6503 /**
6504 * @author Vova Feldman (@svovaf)
6505 * @since 1.1.7.3
6506 *
6507 * @param int $start_at Defaults to now.
6508 * @param bool $randomize_start If true, schedule first job randomly during the next 12 hours. Otherwise, schedule job to start right away.
6509 * @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.
6510 */
6511 private function schedule_sync_cron(
6512 $start_at = WP_FS__SCRIPT_START_TIME,
6513 $randomize_start = true,
6514 $except_blog_id = 0
6515 ) {
6516 $this->schedule_cron(
6517 'sync',
6518 'data_sync',
6519 'daily',
6520 $start_at,
6521 $randomize_start,
6522 $except_blog_id
6523 );
6524 }
6525
6526 /**
6527 * Add the actual sync function to the cron job hook.
6528 *
6529 * @author Vova Feldman (@svovaf)
6530 * @since 1.1.7.3
6531 */
6532 private function hook_callback_to_sync_cron() {
6533 $this->add_action( 'data_sync', array( &$this, '_sync_cron' ) );
6534 }
6535
6536 /**
6537 * @author Vova Feldman (@svovaf)
6538 * @since 1.1.7.3
6539 *
6540 * @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.
6541 */
6542 private function clear_sync_cron( $is_network_clear = false ) {
6543 $this->_logger->entrance();
6544
6545 $this->clear_cron( 'sync', 'data_sync', $is_network_clear );
6546 }
6547
6548 /**
6549 * Unix timestamp for next sync cron execution or false if not scheduled.
6550 *
6551 * @author Vova Feldman (@svovaf)
6552 * @since 1.1.7.3
6553 *
6554 * @return int|false
6555 */
6556 function next_sync_cron() {
6557 return $this->get_next_scheduled_cron( 'sync', 'data_sync' );
6558 }
6559
6560 /**
6561 * Unix timestamp for previous sync cron execution or false if never executed.
6562 *
6563 * @author Vova Feldman (@svovaf)
6564 * @since 1.1.7.3
6565 *
6566 * @return int|false
6567 */
6568 function last_sync_cron() {
6569 return $this->cron_last_execution( 'sync' );
6570 }
6571
6572 #endregion Daily Sync Cron ------------------------------------------------------------------
6573
6574 #----------------------------------------------------------------------------------
6575 #region Async Install Sync
6576 #----------------------------------------------------------------------------------
6577
6578 /**
6579 * @author Vova Feldman (@svovaf)
6580 * @since 1.1.7.3
6581 *
6582 * @return bool
6583 */
6584 private function is_install_sync_scheduled() {
6585 return $this->is_cron_on( 'install_sync' );
6586 }
6587
6588 /**
6589 * Get the sync cron's executing blog ID.
6590 *
6591 * @author Vova Feldman (@svovaf)
6592 * @since 2.0.0
6593 *
6594 * @return int
6595 */
6596 private function get_install_sync_cron_blog_id() {
6597 return $this->get_cron_blog_id( 'install_sync' );
6598 }
6599
6600 /**
6601 * Instead of running blocking install sync event, execute non blocking scheduled wp-cron.
6602 *
6603 * @author Vova Feldman (@svovaf)
6604 * @since 1.1.7.3
6605 *
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_install_sync( $except_blog_id = 0 ) {
6609 if ( $this->is_clone() ) {
6610 return;
6611 }
6612
6613 $this->schedule_cron( 'install_sync', 'install_sync', 'single', WP_FS__SCRIPT_START_TIME, false, $except_blog_id );
6614 }
6615
6616 /**
6617 * Unix timestamp for previous install sync cron execution or false if never executed.
6618 *
6619 * @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.
6620 *
6621 * @author Vova Feldman (@svovaf)
6622 * @since 1.1.7.3
6623 *
6624 * @return int|false
6625 */
6626 function last_install_sync() {
6627 return $this->cron_last_execution( 'install_sync' );
6628 }
6629
6630 /**
6631 * Unix timestamp for next install sync cron execution or false if not scheduled.
6632 *
6633 * @author Vova Feldman (@svovaf)
6634 * @since 1.1.7.3
6635 *
6636 * @return int|false
6637 */
6638 function next_install_sync() {
6639 return $this->get_next_scheduled_cron( 'install_sync', 'install_sync' );
6640 }
6641
6642 /**
6643 * Add the actual install sync function to the cron job hook.
6644 *
6645 * @author Vova Feldman (@svovaf)
6646 * @since 1.1.7.3
6647 */
6648 private function hook_callback_to_install_sync() {
6649 $this->add_action( 'install_sync', array( &$this, '_run_sync_install' ) );
6650 }
6651
6652 /**
6653 * @author Vova Feldman (@svovaf)
6654 * @since 1.1.7.3
6655 *
6656 * @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.
6657 */
6658 private function clear_install_sync_cron( $is_network_clear = false ) {
6659 $this->_logger->entrance();
6660
6661 $this->clear_cron( 'install_sync', 'install_sync', $is_network_clear );
6662 }
6663
6664 /**
6665 * @author Vova Feldman (@svovaf)
6666 * @since 1.1.7.3
6667 * @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.
6668 */
6669 public function _run_sync_install() {
6670 $this->_logger->entrance();
6671
6672 $this->execute_cron( 'sync', array( &$this, '_sync_install_cron_method' ) );
6673 }
6674
6675 /**
6676 * The actual install(s) sync cron logic.
6677 *
6678 * @author Vova Feldman (@svovaf)
6679 * @since 2.0.0
6680 *
6681 * @param int[] $blog_ids
6682 * @param int|null $current_blog_id
6683 */
6684 function _sync_install_cron_method( array $blog_ids, $current_blog_id = null ) {
6685 if ( $this->is_registered() ) {
6686 if ( 1 < count( $blog_ids ) ) {
6687 $this->sync_installs( array(), true );
6688 } else {
6689 $this->sync_install( array(), true );
6690 }
6691
6692 $this->maybe_sync_install_user();
6693 }
6694 }
6695
6696 #endregion Async Install Sync ------------------------------------------------------------------
6697
6698 /**
6699 * Show a notice that activation is currently pending.
6700 *
6701 * @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.
6702 *
6703 * @author Vova Feldman (@svovaf)
6704 * @since 1.0.7
6705 *
6706 * @param bool|string $email_address
6707 * @param bool $is_pending_trial Since 1.2.1.5
6708 * @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.
6709 * @param bool $has_upgrade_context Since 2.5.3
6710 * @param bool $support_email_address Since 2.5.3
6711 */
6712 function _add_pending_activation_notice(
6713 $email_address = false,
6714 $is_pending_trial = false,
6715 $is_suspicious_email = false,
6716 $has_upgrade_context = false,
6717 $support_email_address = false
6718 ) {
6719 if ( ! is_string( $email_address ) ) {
6720 $current_user = self::_get_current_wp_user();
6721 $email_address = $current_user->user_email;
6722 }
6723
6724 $formatted_message_args = array(
6725 "<b>{$this->get_plugin_name()}</b>",
6726 "<b>{$email_address}</b>",
6727 );
6728
6729 if ( ! $has_upgrade_context || ! fs_is_network_admin() ) {
6730 /* translators: %3$s: action (e.g.: "start the trial" or "complete the opt-in") */
6731 $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' );
6732
6733 $formatted_message_args[] = $is_pending_trial ?
6734 $this->get_text_inline( 'start the trial', 'start-the-trial' ) :
6735 $this->get_text_inline( 'complete the opt-in', 'complete-the-opt-in' );
6736
6737 $notice_title = $this->get_text_inline( 'Thanks!', 'thanks' );
6738 } else {
6739 /* translators: %3$s: What the user is expected to receive via email (e.g.: "the installation instructions" or "a license key") */
6740 $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.' );
6741
6742 if ( $this->has_release_on_freemius() ) {
6743 $formatted_message_args[] = $this->get_text_x_inline(
6744 'the installation instructions',
6745 'Part of the message telling the user what they should receive via email.',
6746 'the-installation-instructions-phrase'
6747 );
6748 } else {
6749 $formatted_message_args[] = $this->get_text_x_inline(
6750 'a license key',
6751 'Part of the message telling the user what they should receive via email.',
6752 'a-license-key-phrase'
6753 );
6754
6755 $formatted_message .= ( ' ' . sprintf(
6756 /* translators: %s: activation link (e.g.: <a>Click here</a>) */
6757 $this->get_text_inline( '%s to activate the license once you get it.', 'license-activation-link-message' ),
6758 sprintf(
6759 '<b><a href="%s">%s</a></b>',
6760 $this->get_activation_url( array(
6761 'fs_action' => 'reset_pending_activation_mode',
6762 'require_license' => 'true',
6763 'fs_unique_affix' => $this->get_unique_affix(),
6764 ) ),
6765 $this->get_text_x_inline( 'Click here', 'Part of an activation link message.', 'click-here' )
6766 )
6767 ) );
6768 }
6769
6770 $formatted_message_args[] = ( ! empty( $support_email_address ) ) ?
6771 ( "<b>{$support_email_address}</b>" ) :
6772 $this->get_text_x_inline(
6773 "the product's support email address",
6774 'Part of the message that tells the user to check their spam folder for a specific email.',
6775 'product-support-email-address-phrase'
6776 );
6777
6778 $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' ) );
6779
6780 $notice_title = $this->get_text_inline( 'Thanks for upgrading.', 'after-upgrade-thank-you-message' );
6781 }
6782
6783 $this->_admin_notices->add_sticky(
6784 vsprintf( $formatted_message, $formatted_message_args ),
6785 'activation_pending',
6786 $notice_title
6787 );
6788 }
6789
6790 /**
6791 * Check if currently in plugin activation.
6792 *
6793 * @author Vova Feldman (@svovaf)
6794 * @since 1.1.4
6795 *
6796 * @return bool
6797 */
6798 function is_plugin_activation() {
6799 $result = get_transient( "fs_{$this->_module_type}_{$this->_slug}_activated" );
6800
6801 return !empty($result);
6802 }
6803
6804 /**
6805 *
6806 * NOTE: admin_menu action executed before admin_init.
6807 *
6808 * @author Vova Feldman (@svovaf)
6809 * @since 1.0.7
6810 */
6811 function _admin_init_action() {
6812 $is_migration = $this->is_migration();
6813
6814 /**
6815 * Automatically redirect to connect/activation page after plugin activation.
6816 *
6817 * @since 1.1.7 Do NOT redirect to opt-in when running in network admin mode.
6818 */
6819 if ( $this->is_plugin_activation() ) {
6820 delete_transient( "fs_{$this->_module_type}_{$this->_slug}_activated" );
6821
6822 if ( isset( $_GET['activate-multi'] ) ) {
6823 /**
6824 * Don't redirect if activating multiple plugins at once (bulk activation).
6825 */
6826 } else if (
6827 self::is_deactivation_snoozed() &&
6828 (
6829 // Either running the free code base.
6830 ! $this->is_premium() ||
6831 // Or if has a free version.
6832 ! $this->is_only_premium() ||
6833 // If premium only, don't redirect if license is activated.
6834 ( $this->is_registered() && ! $this->can_use_premium_code() )
6835 )
6836 ) {
6837 /**
6838 * 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.
6839 */
6840 } else if ( ! $is_migration ) {
6841 $this->_redirect_on_activation_hook();
6842 return;
6843 }
6844 }
6845
6846 if ( $is_migration ) {
6847 return;
6848 }
6849
6850 if ( fs_request_is_action( $this->get_unique_affix() . '_skip_activation' ) ) {
6851 check_admin_referer( $this->get_unique_affix() . '_skip_activation' );
6852
6853 $this->skip_connection( fs_is_network_admin() );
6854
6855 fs_redirect( $this->get_after_activation_url( 'after_skip_url' ) );
6856 }
6857
6858 if ( $this->is_network_activation_mode() &&
6859 fs_request_is_action( $this->get_unique_affix() . '_delegate_activation' )
6860 ) {
6861 check_admin_referer( $this->get_unique_affix() . '_delegate_activation' );
6862
6863 $this->delegate_connection();
6864
6865 fs_redirect( $this->get_after_activation_url( 'after_delegation_url' ) );
6866 }
6867
6868 $this->_add_upgrade_action_link();
6869
6870 if ( ! ( ! $this->_is_network_active && fs_is_network_admin() ) &&
6871 (
6872 ( true === $this->_storage->require_license_activation ) ||
6873 // Not registered nor anonymous.
6874 ( ! $this->is_registered() && ! $this->is_anonymous() ) ||
6875 // OR, network level and in network upgrade mode.
6876 ( fs_is_network_admin() && $this->_is_network_active && $this->is_network_upgrade_mode() )
6877 )
6878 ) {
6879 if ( ! $this->is_pending_activation() ) {
6880 if ( ! $this->is_activation_page() ) {
6881 /**
6882 * If a user visits any other admin page before activating the premium-only theme with a valid
6883 * license, reactivate the previous theme.
6884 *
6885 * @author Leo Fajardo (@leorw)
6886 * @since 1.2.2
6887 */
6888 if ( $this->is_theme() &&
6889 ! $this->has_settings_menu() &&
6890 ! isset( $_REQUEST['fs_action'] ) &&
6891 $this->can_activate_previous_theme()
6892 ) {
6893 if ( $this->is_only_premium() ) {
6894 $this->activate_previous_theme();
6895 return;
6896 }
6897
6898 if ( true === $this->_storage->require_license_activation ) {
6899 $this->_storage->require_license_activation = false;
6900 }
6901 }
6902
6903 if ( ! fs_is_network_admin() &&
6904 $this->is_network_activation_mode() &&
6905 ! $this->is_delegated_connection()
6906 ) {
6907 return;
6908 }
6909
6910 if ( $this->is_plugin_new_install() || $this->is_only_premium() ) {
6911 if ( ! $this->_anonymous_mode &&
6912 ( ! $this->is_addon() || ! $this->_parent->is_anonymous() ) ) {
6913 // Show notice for new plugin installations.
6914 $this->_admin_notices->add(
6915 sprintf(
6916 $this->get_text_inline( 'You are just one step away - %s', 'you-are-step-away' ),
6917 sprintf( '<b><a href="%s">%s</a></b>',
6918 $this->get_activation_url( array(), ! $this->is_delegated_connection() ),
6919 sprintf( $this->get_text_x_inline( 'Complete "%s" Activation Now',
6920 '%s - plugin name. As complete "PluginX" activation now', 'activate-x-now' ), $this->get_plugin_name() )
6921 )
6922 ),
6923 '',
6924 'update-nag'
6925 );
6926 }
6927 } else {
6928 if ( $this->should_add_sticky_optin_notice() ) {
6929 $this->add_sticky_optin_admin_notice();
6930 }
6931
6932 if ( $this->has_filter( 'optin_pointer_element' ) ) {
6933 // Don't show admin nag if plugin update.
6934 wp_enqueue_script( 'wp-pointer' );
6935 wp_enqueue_style( 'wp-pointer' );
6936
6937 $this->_enqueue_connect_essentials();
6938
6939 add_action( 'admin_print_footer_scripts', array(
6940 $this,
6941 '_add_connect_pointer_script'
6942 ) );
6943 }
6944 }
6945 }
6946 }
6947
6948 if ( $this->show_opt_in_on_themes_page() &&
6949 $this->is_activation_page()
6950 ) {
6951 $this->_show_theme_activation_optin_dialog();
6952 }
6953 }
6954 }
6955
6956 /**
6957 * @author Vova Feldman (@svovaf)
6958 * @since 2.0.0
6959 *
6960 * @return bool
6961 */
6962 private function should_add_sticky_optin_notice() {
6963 if ( $this->is_addon() && $this->_parent->is_anonymous() ) {
6964 return false;
6965 }
6966
6967 if ( fs_is_network_admin() ) {
6968 if ( ! $this->_is_network_active ) {
6969 return false;
6970 }
6971
6972 if ( ! $this->is_network_activation_mode() ) {
6973 return false;
6974 }
6975
6976 return ! isset( $this->_storage->sticky_optin_added_ms );
6977 }
6978
6979 if ( ! $this->is_activation_mode() ) {
6980 return false;
6981 }
6982
6983 // If running from a blog admin and delegated the connection.
6984 return ! isset( $this->_storage->sticky_optin_added );
6985 }
6986
6987 /**
6988 * @author Leo Fajardo (@leorw)
6989 * @since 2.0.0
6990 */
6991 private function add_sticky_optin_admin_notice() {
6992 if ( ! $this->_is_network_active || ! fs_is_network_admin() ) {
6993 $this->_storage->sticky_optin_added = true;
6994 } else {
6995 $this->_storage->sticky_optin_added_ms = true;
6996 }
6997
6998 // Show notice for new plugin installations.
6999 $this->_admin_notices->add_sticky(
7000 sprintf(
7001 $this->get_text_inline( 'We made a few tweaks to the %s, %s', 'few-plugin-tweaks' ),
7002 $this->_module_type,
7003 sprintf( '<b><a href="%s">%s</a></b>',
7004 $this->get_activation_url(),
7005 sprintf( $this->get_text_inline( 'Opt in to make "%s" better!', 'optin-x-now' ), $this->get_plugin_name() )
7006 )
7007 ),
7008 'connect_account',
7009 '',
7010 'update-nag'
7011 );
7012 }
7013
7014 /**
7015 * Enqueue connect requires scripts and styles.
7016 *
7017 * @author Vova Feldman (@svovaf)
7018 * @since 1.1.4
7019 */
7020 function _enqueue_connect_essentials() {
7021 wp_enqueue_script( 'jquery' );
7022 wp_enqueue_script( 'json2' );
7023
7024 fs_enqueue_local_script( 'postmessage', 'nojquery.ba-postmessage.js' );
7025 fs_enqueue_local_script( 'fs-postmessage', 'postmessage.js' );
7026 }
7027
7028 /**
7029 * Add connect / opt-in pointer.
7030 *
7031 * @author Vova Feldman (@svovaf)
7032 * @since 1.1.4
7033 */
7034 function _add_connect_pointer_script() {
7035 $vars = array( 'id' => $this->_module_id );
7036 $pointer_content = fs_get_template( 'connect.php', $vars );
7037 ?>
7038 <script type="text/javascript">// <![CDATA[
7039 jQuery(document).ready(function ($) {
7040 if ('undefined' !== typeof(jQuery().pointer)) {
7041
7042 var element = <?php echo $this->apply_filters( 'optin_pointer_element', '$("#non_existing_element");' ) ?>;
7043
7044 if (element.length > 0) {
7045 var optin = $(element).pointer($.extend(true, {}, {
7046 content : <?php echo json_encode( $pointer_content ) ?>,
7047 position : {
7048 edge : 'left',
7049 align: 'center'
7050 },
7051 buttons : function () {
7052 // Don't show pointer buttons.
7053 return '';
7054 },
7055 pointerWidth: 482
7056 }, <?php echo $this->apply_filters( 'optin_pointer_options_json', '{}' ) ?>));
7057
7058 <?php
7059 echo $this->apply_filters( 'optin_pointer_execute', "
7060
7061 optin.pointer('open');
7062
7063 // Tag the opt-in pointer with custom class.
7064 $('.wp-pointer #fs_connect')
7065 .parents('.wp-pointer.wp-pointer-top')
7066 .addClass('fs-opt-in-pointer');
7067
7068 ", 'element', 'optin' ) ?>
7069 }
7070 }
7071 });
7072 // ]]></script>
7073 <?php
7074 }
7075
7076 /**
7077 * Return current page's URL.
7078 *
7079 * @author Vova Feldman (@svovaf)
7080 * @since 1.0.7
7081 *
7082 * @return string
7083 */
7084 static function current_page_url() {
7085 $url = 'http';
7086
7087 if ( isset( $_SERVER["HTTPS"] ) ) {
7088 if ( $_SERVER["HTTPS"] == "on" ) {
7089 $url .= "s";
7090 }
7091 }
7092 $url .= "://";
7093 if ( $_SERVER["SERVER_PORT"] != "80" ) {
7094 $url .= $_SERVER["SERVER_NAME"] . ":" . $_SERVER["SERVER_PORT"] . $_SERVER["REQUEST_URI"];
7095 } else {
7096 $url .= $_SERVER["SERVER_NAME"] . $_SERVER["REQUEST_URI"];
7097 }
7098
7099 return esc_url( $url );
7100 }
7101
7102 /**
7103 * Check if the current page is the plugin's main admin settings page.
7104 *
7105 * @author Vova Feldman (@svovaf)
7106 * @since 1.0.7
7107 *
7108 * @return bool
7109 */
7110 function _is_plugin_page() {
7111 return fs_is_plugin_page( $this->_menu->get_raw_slug() ) ||
7112 fs_is_plugin_page( $this->_slug );
7113 }
7114
7115 /* Events
7116 ------------------------------------------------------------------------------------------------------------------*/
7117 /**
7118 * Delete site install from Database.
7119 *
7120 * @author Vova Feldman (@svovaf)
7121 * @since 1.0.1
7122 *
7123 * @param bool $store
7124 * @param int|null $blog_id Since 2.0.0
7125 *
7126 * @return false|int The install ID if deleted. Otherwise, FALSE (when install not exist).
7127 */
7128 function _delete_site( $store = true, $blog_id = null ) {
7129 return self::_delete_site_by_slug( $this->_slug, $this->_module_type, $store, $blog_id );
7130 }
7131
7132 /**
7133 * Delete site install from Database.
7134 *
7135 * @author Vova Feldman (@svovaf)
7136 * @since 1.2.2.7
7137 *
7138 * @param string $slug
7139 * @param string $module_type
7140 * @param bool $store
7141 * @param int|null $blog_id Since 2.0.0
7142 *
7143 * @return false|int The install ID if deleted. Otherwise, FALSE (when install not exist).
7144 */
7145 static function _delete_site_by_slug( $slug, $module_type, $store = true, $blog_id = null ) {
7146 $sites = self::get_all_sites( $module_type, $blog_id );
7147
7148 $install_id = false;
7149
7150 if ( isset( $sites[ $slug ] ) ) {
7151 if ( is_object( $sites[ $slug ] ) ) {
7152 $install_id = $sites[ $slug ]->id;
7153 }
7154
7155 unset( $sites[ $slug ] );
7156
7157 self::set_account_option_by_module( $module_type, 'sites', $sites, $store, $blog_id );
7158 }
7159
7160 return $install_id;
7161 }
7162
7163 /**
7164 * Delete plugin's plans information.
7165 *
7166 * @param bool $store Flush to Database if true.
7167 * @param bool $keep_associated_plans If set to false, delete all plans, even if a plan is associated with an install.
7168 *
7169 * @author Vova Feldman (@svovaf)
7170 * @since 1.0.9
7171 */
7172 private function _delete_plans( $store = true, $keep_associated_plans = true ) {
7173 $this->_logger->entrance();
7174
7175 $plans = self::get_all_plans( $this->_module_type );
7176
7177 $plans_to_keep = array();
7178
7179 if ( $keep_associated_plans ) {
7180 $plans_ids_to_keep = $this->get_plans_ids_associated_with_installs();
7181 foreach ( $plans_ids_to_keep as $plan_id ) {
7182 $plan = self::_get_plan_by_id( $plan_id );
7183 if ( is_object( $plan ) ) {
7184 $plans_to_keep[] = self::_encrypt_entity( $plan );
7185 }
7186 }
7187 }
7188
7189 if ( ! empty( $plans_to_keep ) ) {
7190 $plans[ $this->_slug ] = $plans_to_keep;
7191 } else {
7192 unset( $plans[ $this->_slug ] );
7193 }
7194
7195 $this->set_account_option( 'plans', $plans, $store );
7196 }
7197
7198 /**
7199 * Delete all plugin licenses.
7200 *
7201 * @author Vova Feldman (@svovaf)
7202 * @since 1.0.9
7203 *
7204 * @param bool $store
7205 */
7206 private function _delete_licenses( $store = true ) {
7207 $this->_logger->entrance();
7208
7209 $all_licenses = self::get_all_licenses();
7210
7211 unset( $all_licenses[ $this->_module_id ] );
7212
7213 self::$_accounts->set_option( 'all_licenses', $all_licenses, $store );
7214 }
7215
7216 /**
7217 * Check if Freemius was added on new plugin installation.
7218 *
7219 * @author Vova Feldman (@svovaf)
7220 * @since 1.1.5
7221 *
7222 * @return bool
7223 */
7224 function is_plugin_new_install() {
7225 return isset( $this->_storage->is_plugin_new_install ) &&
7226 $this->_storage->is_plugin_new_install;
7227 }
7228
7229 /**
7230 * Check if it's the first plugin release that is running Freemius.
7231 *
7232 * @author Vova Feldman (@svovaf)
7233 * @since 1.2.1.5
7234 *
7235 * @return bool
7236 */
7237 function is_first_freemius_powered_version() {
7238 return empty( $this->_storage->plugin_last_version );
7239 }
7240
7241 /**
7242 * @author Leo Fajardo (@leorw)
7243 * @since 1.2.2
7244 *
7245 * @return bool|string
7246 */
7247 private function get_previous_theme_slug() {
7248 return isset( $this->_storage->previous_theme ) ?
7249 $this->_storage->previous_theme :
7250 false;
7251 }
7252
7253 /**
7254 * @author Leo Fajardo (@leorw)
7255 * @since 1.2.2
7256 *
7257 * @return bool
7258 */
7259 private function can_activate_previous_theme() {
7260 return $this->can_activate_theme( $this->get_previous_theme_slug() );
7261 }
7262
7263 /**
7264 * @author Leo Fajardo (@leorw)
7265 * @since 2.5.0
7266 *
7267 * @return bool
7268 */
7269 private function can_activate_theme( $slug ) {
7270 if ( false !== $slug && current_user_can( 'switch_themes' ) ) {
7271 $theme_instance = wp_get_theme( $slug );
7272
7273 return $theme_instance->exists();
7274 }
7275
7276 return false;
7277 }
7278
7279 /**
7280 * @author Leo Fajardo (@leorw)
7281 * @since 1.2.2
7282 */
7283 private function activate_previous_theme() {
7284 switch_theme( $this->get_previous_theme_slug() );
7285 unset( $this->_storage->previous_theme );
7286
7287 global $pagenow;
7288 if ( 'themes.php' === $pagenow ) {
7289 /**
7290 * Refresh the active theme information.
7291 *
7292 * @author Leo Fajardo (@leorw)
7293 * @since 1.2.2
7294 */
7295 fs_redirect( $this->admin_url( $pagenow ) );
7296 }
7297 }
7298
7299 /**
7300 * @author Leo Fajardo (@leorw)
7301 * @since 1.2.2
7302 *
7303 * @return string
7304 */
7305 function get_previous_theme_activation_url() {
7306 if ( ! $this->can_activate_previous_theme() ) {
7307 return '';
7308 }
7309
7310 /**
7311 * Activation URL
7312 *
7313 * @author Leo Fajardo (@leorw)
7314 * @since 1.2.2
7315 */
7316 return wp_nonce_url(
7317 $this->admin_url( 'themes.php?action=activate&stylesheet=' . urlencode( $this->get_previous_theme_slug() ) ),
7318 'switch-theme_' . $this->get_previous_theme_slug()
7319 );
7320 }
7321
7322 /**
7323 * Saves the slug of the previous theme if it still exists so that it can be used by the logic in the opt-in
7324 * form that decides whether to add a close button to the opt-in dialog or not. So after a premium-only theme is
7325 * activated, the close button will appear and will reactivate the previous theme if clicked. If the previous
7326 * theme doesn't exist, then there will be no close button.
7327 *
7328 * @author Leo Fajardo (@leorw)
7329 * @since 1.2.2
7330 *
7331 * @param string $slug_or_name Old theme's slug or name.
7332 * @param bool|WP_Theme $old_theme WP_Theme instance of the old theme if it still exists.
7333 */
7334 function _activate_theme_event_hook( $slug_or_name, $old_theme = false ) {
7335 $this->_storage->previous_theme = ( false !== $old_theme ) ?
7336 $old_theme->get_stylesheet() :
7337 $slug_or_name;
7338
7339 $this->_activate_plugin_event_hook();
7340 }
7341
7342 /**
7343 * Plugin activated hook.
7344 *
7345 * @author Vova Feldman (@svovaf)
7346 * @since 1.0.1
7347 *
7348 * @uses FS_Api
7349 */
7350 function _activate_plugin_event_hook() {
7351 $this->_logger->entrance( 'slug = ' . $this->_slug );
7352
7353 if ( ! $this->is_user_admin() ) {
7354 return;
7355 }
7356
7357 $this->unregister_uninstall_hook();
7358
7359 // Clear API cache on activation.
7360 FS_Api::clear_cache();
7361
7362 $is_premium_version_activation = $this->is_plugin() ?
7363 ( current_filter() !== ( 'activate_' . $this->_free_plugin_basename ) ) :
7364 $this->is_premium();
7365
7366 if ( $is_premium_version_activation && $this->is_pending_activation() ) {
7367 $this->clear_pending_activation_mode();
7368 }
7369
7370 $this->_logger->info( 'Activating ' . ( $is_premium_version_activation ? 'premium' : 'free' ) . ' plugin version.' );
7371
7372 if ( $this->is_plugin() ) {
7373 // This logic is relevant only to plugins since both the free and premium versions of a plugin can be active at the same time.
7374 // 1. If running in the activation of the FREE module, get the basename of the PREMIUM.
7375 // 2. If running in the activation of the PREMIUM module, get the basename of the FREE.
7376 $other_version_basename = $is_premium_version_activation ?
7377 $this->_free_plugin_basename :
7378 $this->premium_plugin_basename();
7379
7380 if ( ! $this->_is_network_active ) {
7381 /**
7382 * Themes are always network activated, but the ACTUAL activation is per site.
7383 *
7384 * During the activation, the plugin isn't yet active, therefore,
7385 * _is_network_active will be set to false even if it's a network level
7386 * activation. So we need to fix that by looking at the is_network_admin() value.
7387 *
7388 * @author Vova Feldman
7389 */
7390 $this->_is_network_active = (
7391 $this->_is_multisite_integrated &&
7392 fs_is_network_admin()
7393 );
7394 }
7395
7396 /**
7397 * If the other module version is active, deactivate it.
7398 *
7399 * is_plugin_active() checks if the plugin is active on the site or the network level and
7400 * deactivate_plugins() deactivates the plugin whether it's activated on the site or network level.
7401 *
7402 * @author Leo Fajardo (@leorw)
7403 * @since 1.2.2
7404 */
7405 if (
7406 is_plugin_active( $other_version_basename ) &&
7407 $this->apply_filters( 'deactivate_on_activation', true )
7408 ) {
7409 deactivate_plugins( $other_version_basename );
7410 }
7411 }
7412
7413 if ( $this->is_registered() ) {
7414 if ( $is_premium_version_activation ) {
7415 $this->reconnect_locally();
7416 }
7417
7418
7419 // Schedule re-activation event and sync.
7420 // $this->sync_install( array(), true );
7421 $this->schedule_install_sync();
7422
7423 // If activating the premium module version, add an admin notice to congratulate for an upgrade completion.
7424 if ( $is_premium_version_activation ) {
7425 $this->_admin_notices->add(
7426 sprintf( $this->get_text_inline( 'The upgrade of %s was successfully completed.', 'successful-version-upgrade-message' ), sprintf( '<b>%s</b>', $this->_plugin->title ) ),
7427 $this->get_text_x_inline( 'W00t',
7428 'Used to express elation, enthusiasm, or triumph (especially in electronic communication).', 'woot' ) . '!'
7429 );
7430 }
7431 } else if ( $this->is_anonymous() ) {
7432 if ( isset( $this->_storage->is_anonymous_ms ) && $this->_storage->is_anonymous_ms['is'] ) {
7433 $plugin_version = $this->_storage->is_anonymous_ms['version'];
7434 $network = true;
7435 } else {
7436 $plugin_version = isset( $this->_storage->is_anonymous ) ?
7437 $this->_storage->is_anonymous['version'] :
7438 null;
7439 $network = false;
7440 }
7441
7442 /**
7443 * Reset "skipped" click cache on the following:
7444 * 1. Freemius DEV mode.
7445 * 2. WordPress DEBUG mode.
7446 * 3. If a plugin and the user skipped the exact same version before.
7447 *
7448 * @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).
7449 *
7450 * @todo 4. If explicitly asked to retry after every activation.
7451 */
7452 if ( WP_FS__DEV_MODE ||
7453 (
7454 ( $this->is_plugin() || ( defined( 'WP_DEBUG' ) && WP_DEBUG ) ) &&
7455 $this->get_plugin_version() == $plugin_version
7456 )
7457 ) {
7458 $this->reset_anonymous_mode( $network );
7459 }
7460 }
7461
7462 $is_trial_or_has_features_enabled_license = ( $this->is_trial() || $this->has_features_enabled_license() );
7463
7464 if ( $this->is_addon() && ! $is_trial_or_has_features_enabled_license ) {
7465 /**
7466 * When activating an add-on, try to also activate a license.
7467 *
7468 * @author Leo Fajardo (@leorw)
7469 * @since 2.3.0
7470 */
7471 if ( ! $this->_is_network_active ) {
7472 $this->maybe_activate_addon_license();
7473 } else {
7474 $this->maybe_network_activate_addon_license();
7475 }
7476
7477 /**
7478 * Avoid redirecting to the license activation screen after automatically activating an add-on license.
7479 *
7480 * @author Leo Fajardo (@leorw)
7481 * @since 2.3.0
7482 */
7483 $is_trial_or_has_features_enabled_license = ( $this->is_trial() || $this->has_features_enabled_license() );
7484
7485 if ( $is_trial_or_has_features_enabled_license && true === $this->_storage->require_license_activation ) {
7486 $this->_storage->require_license_activation = false;
7487 }
7488 }
7489
7490 if (
7491 $is_premium_version_activation &&
7492 (
7493 ( ! $this->is_registered() && $this->is_anonymous() ) ||
7494 (
7495 $this->is_registered() &&
7496 ! $is_trial_or_has_features_enabled_license
7497 )
7498 )
7499 ) {
7500 $this->_storage->require_license_activation = true;
7501 }
7502
7503 if ( ! isset( $this->_storage->is_plugin_new_install ) ) {
7504 /**
7505 * If no previous version of plugin's version exist, it means that it's either
7506 * the first time that the plugin installed on the site, or the plugin was installed
7507 * before but didn't have Freemius integrated.
7508 *
7509 * Since register_activation_hook() do NOT fires on updates since 3.1, and only fires
7510 * on manual activation via the dashboard, is_plugin_activation() is TRUE
7511 * only after immediate activation.
7512 *
7513 * @since 1.1.4
7514 * @link https://make.wordpress.org/core/2010/10/27/plugin-activation-hooks-no-longer-fire-for-updates/
7515 */
7516 $this->_storage->is_plugin_new_install = empty( $this->_storage->plugin_last_version );
7517 }
7518
7519 /**
7520 * Also flush when activating the premium version so that even if Freemius was off before, the API
7521 * connectivity test can be run again.
7522 *
7523 * @author Leo Fajardo (@leorw)
7524 * @since 2.2.3.1
7525 */
7526 $has_api_connectivity = $this->has_api_connectivity( WP_FS__DEV_MODE || $is_premium_version_activation );
7527
7528 if ( ! $this->_anonymous_mode &&
7529 ( false !== $has_api_connectivity ) &&
7530 ! $this->_isAutoInstall
7531 ) {
7532 // Store hint that the plugin was just activated to enable auto-redirection to settings.
7533 set_transient( "fs_{$this->_module_type}_{$this->_slug}_activated", true, 60 );
7534 }
7535
7536 /**
7537 * Activation hook is executed after the plugin's main file is loaded, therefore,
7538 * after the plugin was loaded. The logic is located at activate_plugin()
7539 * ./wp-admin/includes/plugin.php.
7540 *
7541 * @author Vova Feldman (@svovaf)
7542 * @since 1.1.9
7543 */
7544 $this->_storage->was_plugin_loaded = true;
7545 }
7546
7547 /**
7548 * @author Leo Fajardo (@leorw)
7549 * @since 2.3.0
7550 */
7551 private function maybe_activate_addon_license() {
7552 $parent_fs = $this->get_parent_instance();
7553
7554 if (
7555 ! is_object( $parent_fs ) ||
7556 ( ! $parent_fs->is_registered() && ! $parent_fs->is_network_registered() )
7557 ) {
7558 // Try to activate a license only if the parent plugin is active and has a valid `install`.
7559 return;
7560 }
7561
7562 $license = $this->get_active_parent_license();
7563 if ( ! is_object( $license ) ) {
7564 return;
7565 }
7566
7567 if (
7568 $this->is_bundle_license_auto_activation_enabled() &&
7569 ! empty( $license->products )
7570 ) {
7571 $this->activate_bundle_license( $license );
7572
7573 return;
7574 }
7575
7576 if ( ! $this->is_registered() ) {
7577 // Opt in with a license key.
7578 $this->opt_in(
7579 $parent_fs->get_current_or_network_user()->email,
7580 false,
7581 false,
7582 $license->secret_key
7583 );
7584 } else {
7585 // Activate the license.
7586 $install = $this->api_site_call(
7587 '/',
7588 'put',
7589 array( 'license_key' => $this->apply_filters( 'license_key', $license->secret_key ) )
7590 );
7591
7592 if ( ! FS_Api::is_api_error( $install ) ) {
7593 $this->_sync_addon_license( $this->get_id(), true );
7594 }
7595 }
7596 }
7597
7598 /**
7599 * @author Leo Fajardo (@leorw)
7600 * @since 2.3.0
7601 *
7602 * @param FS_Plugin_License $license
7603 */
7604 private function maybe_network_activate_addon_license( $license = null ) {
7605 $parent_fs = $this->get_parent_instance();
7606 if ( ! is_object( $parent_fs ) || ( ! $parent_fs->is_registered() && ! $parent_fs->is_network_registered() ) ) {
7607 // Try to activate a license only if the parent plugin is active and has a valid `install`.
7608 return;
7609 }
7610
7611 $license = ( ! is_null( $license ) ) ?
7612 $license :
7613 $this->get_active_parent_license();
7614
7615 if ( ! is_object( $license ) ) {
7616 return;
7617 }
7618
7619 if (
7620 $this->is_bundle_license_auto_activation_enabled() &&
7621 ! empty( $license->products )
7622 ) {
7623 $this->activate_bundle_license( $license );
7624
7625 return;
7626 }
7627
7628 if ( ! $this->is_network_registered() ) {
7629 $sites = $this->get_sites_for_network_level_optin();
7630
7631 if ( count( $sites ) > $license->left() ) {
7632 // If the add-on is network active, try to activate the license only if it can be activated on all sites.
7633 return;
7634 }
7635
7636 // Opt in with a license key.
7637 $this->opt_in(
7638 $parent_fs->get_user()->email,
7639 false,
7640 false,
7641 $license->secret_key,
7642 false,
7643 false,
7644 false,
7645 null,
7646 $sites
7647 );
7648 } else {
7649 $blog_2_install_map = array();
7650 $site_ids = array();
7651
7652 $all_sites = Freemius::get_sites();
7653
7654 foreach ( $all_sites as $site ) {
7655 $blog_id = Freemius::get_site_blog_id( $site );
7656 $install = $this->get_install_by_blog_id( $blog_id );
7657
7658 if ( is_object( $install ) && FS_Plugin_License::is_valid_id( $install->license_id ) ) {
7659 // Skip license activation for installs that are already associated with a license.
7660 continue;
7661 }
7662
7663 if ( is_object( $install ) ) {
7664 $blog_2_install_map[ $blog_id ] = $install;
7665 } else {
7666 $site_ids[] = $blog_id;
7667 }
7668 }
7669
7670 if ( ( count( $blog_2_install_map ) + count( $site_ids ) ) > $license->left() ) {
7671 return;
7672 }
7673
7674 $user = $this->get_current_or_network_user();
7675
7676 if ( ! empty( $blog_2_install_map ) ) {
7677 $result = $this->activate_license_on_many_installs( $user, $license->secret_key, $blog_2_install_map );
7678
7679 if ( true !== $result ) {
7680 return;
7681 }
7682 }
7683
7684 if ( ! empty( $site_ids ) ) {
7685 $this->activate_license_on_many_sites( $user, $license->secret_key, $site_ids );
7686 }
7687 }
7688 }
7689
7690 /**
7691 * 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.
7692 *
7693 * @author Leo Fajardo (@leorw)
7694 * @since 2.4.0
7695 *
7696 * @param FS_Plugin_License $license
7697 * @param array $sites
7698 * @param int $blog_id
7699 */
7700 private function maybe_activate_bundle_license( FS_Plugin_License $license = null, $sites = array(), $blog_id = 0 ) {
7701 if ( ! is_object( $license ) && $this->has_active_valid_license() ) {
7702 $license = $this->_license;
7703 }
7704
7705 if ( ! is_object( $license ) ) {
7706 return;
7707 }
7708
7709 $parent_license = ( ! empty( $license->products ) ) ?
7710 $license :
7711 $this->get_active_parent_license( $license->secret_key );
7712
7713 if ( is_object( $parent_license ) ) {
7714 $this->activate_bundle_license( $parent_license, $sites, $blog_id );
7715 }
7716 }
7717
7718 /**
7719 * Try to activate a bundle license for all the bundle products installed on the site.
7720 * (1) If a child product install already has a license, the bundle license won't be activated.
7721 * (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.
7722 * (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.
7723 *
7724 * @author Leo Fajardo (@leorw)
7725 * @since 2.4.0
7726 *
7727 * @param FS_Plugin_License $license
7728 * @param array $sites
7729 * @param int $current_blog_id
7730 */
7731 private function activate_bundle_license( $license, $sites = array(), $current_blog_id = 0 ) {
7732 $is_network_admin = fs_is_network_admin();
7733
7734 $installs_by_blog_map = array();
7735 $site_info_by_blog_map = array();
7736
7737 /**
7738 * Try to activate the license for all supported products.
7739 *
7740 * @author Leo Fajardo
7741 */
7742 foreach ( $license->products as $product_id ) {
7743 $fs = self::get_instance_by_id( $product_id );
7744
7745 if ( ! is_object( $fs ) ) {
7746 continue;
7747 }
7748
7749 if ( ! $fs->has_paid_plan() ) {
7750 continue;
7751 }
7752
7753 if (
7754 ! $fs->is_addon() &&
7755 ! FS_Plan_Manager::instance()->has_paid_plan( $fs->_plans )
7756 ) {
7757 /**
7758 * The parent product can be free-only but can have its `has_paid_plan` flag set to `true` when
7759 * there is a context bundle.
7760 */
7761 continue;
7762 }
7763
7764 if ( $current_blog_id > 0 ) {
7765 $fs->switch_to_blog( $current_blog_id );
7766 }
7767
7768 if ( $fs->has_active_valid_license() ) {
7769 continue;
7770 }
7771
7772 if ( ! $is_network_admin || $current_blog_id > 0 ) {
7773 if ( $fs->is_network_active() && ! $fs->is_delegated_connection( $current_blog_id ) ) {
7774 // Do not try to activate the license in the site level if the product is network active and the connection was not delegated.
7775 continue;
7776 }
7777 } else {
7778 if ( ! $fs->is_network_active() ) {
7779 // Do not try to activate the license in the network level if the product is not network active.
7780 continue;
7781 }
7782
7783 if ( $fs->is_network_delegated_connection() ) {
7784 // Do not try to activate the license in the network level if the activation has been delegated to site admins.
7785 continue;
7786 }
7787
7788 $has_install_with_license = false;
7789
7790 // 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.
7791 $filtered_sites = array();
7792
7793 if ( empty( $sites ) ) {
7794 $all_sites = self::get_sites();
7795
7796 foreach ( $all_sites as $site ) {
7797 $sites[] = array( 'blog_id' => self::get_site_blog_id( $site ) );
7798 }
7799 } else {
7800 // Populate the map here to avoid calling `$fs->get_site_info( $site );` in the other `for` loop below.
7801 foreach ( $sites as $site ) {
7802 if ( ! isset( $site['blog_id'] ) || ! is_numeric( $site['blog_id'] ) ) {
7803 continue;
7804 }
7805
7806 $site_info_by_blog_map[ $site['blog_id'] ] = $site;
7807 }
7808 }
7809
7810 foreach ( $sites as $site ) {
7811 if ( ! isset( $site['blog_id'] ) || ! is_numeric( $site['blog_id'] ) ) {
7812 continue;
7813 }
7814
7815 $blog_id = $site['blog_id'];
7816
7817 if ( ! isset( $installs_by_blog_map[ $blog_id ] ) ) {
7818 $installs_by_blog_map[ $blog_id ] = self::get_all_sites( $fs->get_module_type(), $blog_id );
7819 }
7820
7821 $installs = $installs_by_blog_map[ $blog_id ];
7822 $install = null;
7823
7824 if ( isset( $installs[ $fs->get_slug() ] ) ) {
7825 $install = $installs[ $fs->get_slug() ];
7826
7827 if (
7828 is_object( $install ) &&
7829 (
7830 ! FS_Site::is_valid_id( $install->id ) ||
7831 ! FS_User::is_valid_id( $install->user_id ) ||
7832 ! FS_Plugin_Plan::is_valid_id( $install->plan_id )
7833 )
7834 ) {
7835 $install = null;
7836 }
7837 }
7838
7839 if (
7840 is_object( $install ) &&
7841 FS_Plugin_License::is_valid_id( $install->license_id )
7842 ) {
7843 $has_install_with_license = true;
7844 break;
7845 }
7846
7847 if ( $fs->is_site_delegated_connection( $blog_id ) ) {
7848 // Site activation delegated, don't activate bundle license on the site in the network admin.
7849 continue;
7850 }
7851
7852 if ( ! isset( $site_info_by_blog_map[ $blog_id ] ) ) {
7853 $site_info_by_blog_map[ $blog_id ] = $fs->get_site_info( $site );
7854 }
7855
7856 $filtered_sites[] = $site_info_by_blog_map[ $blog_id ];
7857 }
7858
7859 if ( $has_install_with_license || empty( $filtered_sites ) ) {
7860 // 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.
7861 continue;
7862 }
7863
7864 $sites = $filtered_sites;
7865 }
7866
7867 $fs->activate_migrated_license(
7868 $license->secret_key,
7869 null,
7870 null,
7871 $sites,
7872 ( $current_blog_id > 0 ? $current_blog_id : null )
7873 );
7874 }
7875 }
7876
7877 /**
7878 * Returns a parent license that can be activated for the context product.
7879 *
7880 * @author Leo Fajardo (@leorw)
7881 * @since 2.3.0
7882 *
7883 * @param string|null $license_key
7884 * @param bool $flush
7885 *
7886 * @return FS_Plugin_License
7887 */
7888 function get_active_parent_license( $license_key = null, $flush = true ) {
7889 $parent_licenses_endpoint = "/plugins/{$this->get_id()}/parent_licenses.json?filter=activatable";
7890
7891 $fs = $this;
7892
7893 if ( $this->is_addon() ) {
7894 $parent_instance = $this->get_parent_instance();
7895
7896 if ( is_object( $parent_instance ) && $parent_instance->is_registered() ) {
7897 $fs = $parent_instance;
7898 }
7899 }
7900
7901 $foreign_licenses = $fs->get_foreign_licenses_info(
7902 self::get_all_licenses( $this->get_parent_id() )
7903 );
7904
7905 if ( ! empty ( $foreign_licenses ) ) {
7906 $foreign_licenses = array(
7907 // Prefix with `+` to tell the server to include foreign licenses in the licenses collection.
7908 'ids' => ( urlencode( '+' ) . implode( ',', $foreign_licenses['ids'] ) ),
7909 'license_keys' => implode( ',', array_map( 'urlencode', $foreign_licenses['license_keys'] ) )
7910 );
7911
7912 $parent_licenses_endpoint = add_query_arg( $foreign_licenses, $parent_licenses_endpoint );
7913 }
7914
7915 $result = $fs->get_current_or_network_user_api_scope()->get( $parent_licenses_endpoint, $flush );
7916
7917 if (
7918 ! $this->is_api_result_object( $result, 'licenses' ) ||
7919 ! is_array( $result->licenses ) ||
7920 empty( $result->licenses )
7921 ) {
7922 return null;
7923 }
7924
7925 $parent_license = null;
7926
7927 if ( empty( $license_key ) ) {
7928 $parent_license = $result->licenses[0];
7929 } else {
7930 foreach ( $result->licenses as $license ) {
7931 if ( $license_key === $license->secret_key ) {
7932 $parent_license = $license;
7933 break;
7934 }
7935 }
7936 }
7937
7938 if ( ! is_null( $parent_license ) ) {
7939 $parent_license = new FS_Plugin_License( $parent_license );
7940 }
7941
7942 return $parent_license;
7943 }
7944
7945 /**
7946 * @author Leo Fajardo (@leorw)
7947 * @since 2.3.0
7948 *
7949 * @return array
7950 */
7951 function get_sites_for_network_level_optin() {
7952 $sites = array();
7953 $all_sites = self::get_sites();
7954
7955 foreach ( $all_sites as $site ) {
7956 $blog_id = self::get_site_blog_id( $site );
7957
7958 if ( ! $this->is_site_delegated_connection( $blog_id ) &&
7959 ! $this->is_installed_on_site( $blog_id )
7960 ) {
7961 $sites[] = $this->get_site_info( $site );
7962 }
7963 }
7964
7965 return $sites;
7966 }
7967
7968 /**
7969 * Delete account.
7970 *
7971 * @author Vova Feldman (@svovaf)
7972 * @since 1.0.3
7973 *
7974 * @param bool $check_user Enforce checking if user have plugins activation privileges.
7975 */
7976 function delete_account_event( $check_user = true ) {
7977 $this->_logger->entrance( 'slug = ' . $this->_slug );
7978
7979 if ( $check_user && ! $this->is_user_admin() ) {
7980 return;
7981 }
7982
7983 $this->do_action( 'before_account_delete' );
7984
7985 // Clear all admin notices.
7986 $this->_admin_notices->clear_all_sticky( false );
7987
7988 $this->_delete_site( false );
7989
7990 $delete_network_common_data = true;
7991
7992 if ( $this->_is_network_active ) {
7993 $installs = $this->get_blog_install_map();
7994
7995 // Don't delete common network data unless no other installs left.
7996 $delete_network_common_data = empty( $installs );
7997 }
7998
7999 if ( $delete_network_common_data ) {
8000 $this->_delete_plans( false );
8001
8002 $this->_delete_licenses( false );
8003
8004 // Delete add-ons related to plugin's account.
8005 $this->_delete_account_addons( false );
8006 }
8007
8008 // @todo Delete plans and licenses of add-ons.
8009
8010 self::$_accounts->store();
8011
8012 /**
8013 * IMPORTANT:
8014 * Clear crons must be executed before clearing all storage.
8015 * Otherwise, the cron will not be cleared.
8016 */
8017 if ( $delete_network_common_data ) {
8018 $this->clear_sync_cron();
8019 }
8020
8021 $this->clear_install_sync_cron();
8022
8023 // Clear all storage data.
8024 $this->_storage->clear_all( true, array(
8025 'is_delegated_connection',
8026 'connectivity_test',
8027 'is_on',
8028 ), false );
8029
8030 // Send delete event.
8031 $this->get_api_site_scope()->call( '/', 'delete' );
8032
8033 $this->do_action( 'after_account_delete' );
8034 }
8035
8036 /**
8037 * Delete network level account.
8038 *
8039 * @author Vova Feldman (@svovaf)
8040 * @since 2.0.0
8041 *
8042 * @param bool $check_user Enforce checking if user have plugins activation privileges.
8043 */
8044 function delete_network_account_event( $check_user = true ) {
8045 $this->_logger->entrance( 'slug = ' . $this->_slug );
8046
8047 if ( $check_user && ! $this->is_user_admin() ) {
8048 return;
8049 }
8050
8051 $this->do_action( 'before_network_account_delete' );
8052
8053 // Clear all admin notices.
8054 $this->_admin_notices->clear_all_sticky();
8055
8056 $this->_delete_plans( false, false );
8057
8058 $this->_delete_licenses( false );
8059
8060 // Delete add-ons related to plugin's account.
8061 $this->_delete_account_addons( false );
8062
8063 // @todo Delete plans and licenses of add-ons.
8064
8065 self::$_accounts->store( true );
8066
8067 /**
8068 * IMPORTANT:
8069 * Clear crons must be executed before clearing all storage.
8070 * Otherwise, the cron will not be cleared.
8071 */
8072 $this->clear_sync_cron( true );
8073 $this->clear_install_sync_cron( true );
8074
8075 $sites = self::get_sites();
8076
8077 $install_ids = array();
8078 foreach ( $sites as $site ) {
8079 $blog_id = self::get_site_blog_id( $site );
8080
8081 if ( $this->is_site_delegated_connection( $blog_id ) ) {
8082 continue;
8083 }
8084
8085 $install_id = $this->_delete_site( true, $blog_id );
8086
8087 // Clear all storage data.
8088 $this->_storage->clear_all( true, array( 'connectivity_test' ), $blog_id );
8089
8090 if ( FS_Site::is_valid_id( $install_id ) ) {
8091 $install_ids[] = $install_id;
8092 }
8093
8094 switch_to_blog( $blog_id );
8095
8096 $this->do_action( 'after_account_delete' );
8097
8098 restore_current_blog();
8099 }
8100
8101 $this->_storage->clear_all( true, array(
8102 'connectivity_test',
8103 'is_on',
8104 ), true );
8105
8106 // Send delete event.
8107 if ( ! empty( $install_ids ) ) {
8108 $result = $this->get_current_or_network_user_api_scope()->call( "/plugins/{$this->_module_id}/installs.json?ids=" . implode( ',', $install_ids ), 'delete' );
8109 }
8110
8111 $this->do_action( 'after_network_account_delete' );
8112 }
8113
8114 /**
8115 * Plugin deactivation hook.
8116 *
8117 * @author Vova Feldman (@svovaf)
8118 * @since 1.0.1
8119 */
8120 function _deactivate_plugin_hook() {
8121 $this->_logger->entrance( 'slug = ' . $this->_slug );
8122
8123 if ( ! $this->is_user_admin() ) {
8124 return;
8125 }
8126
8127 $is_network_deactivation = fs_is_network_admin();
8128 $storage_keys_for_removal = array();
8129
8130 $this->_admin_notices->clear_all_sticky();
8131
8132 $storage_keys_for_removal[] = 'sticky_optin_added';
8133 if ( isset( $this->_storage->sticky_optin_added ) ) {
8134 unset( $this->_storage->sticky_optin_added );
8135 }
8136
8137 if ( ! isset( $this->_storage->is_plugin_new_install ) ) {
8138 // Remember that plugin was already installed.
8139 $this->_storage->is_plugin_new_install = false;
8140 }
8141
8142 // Hook to plugin uninstall.
8143 register_uninstall_hook( $this->_plugin_main_file_path, array( 'Freemius', '_uninstall_plugin_hook' ) );
8144
8145 $this->clear_module_main_file_cache();
8146 $this->clear_sync_cron( $this->_is_network_active );
8147 $this->clear_install_sync_cron();
8148
8149 if ( $this->is_registered() ) {
8150 if ( $this->is_premium() && ! $this->has_active_valid_license() ) {
8151 FS_Plugin_Updater::instance( $this )->delete_update_data();
8152 }
8153
8154 if ( $is_network_deactivation ) {
8155 // Send deactivation event.
8156 $this->sync_installs( array(
8157 'is_active' => false,
8158 ) );
8159 } else {
8160 // Send deactivation event.
8161 $this->sync_install( array(
8162 'is_active' => false,
8163 ) );
8164 }
8165 } else {
8166 if ( false === $this->has_api_connectivity() && ! $this->is_premium() ) {
8167 // Reset connectivity test cache.
8168 $this->clear_connectivity_info();
8169
8170 $storage_keys_for_removal[] = 'connectivity_test';
8171 }
8172 }
8173
8174 if ( $is_network_deactivation ) {
8175 if ( isset( $this->_storage->sticky_optin_added_ms ) ) {
8176 unset( $this->_storage->sticky_optin_added_ms );
8177 }
8178
8179 if ( ! empty( $storage_keys_for_removal ) ) {
8180 $sites = self::get_sites();
8181
8182 foreach ( $sites as $site ) {
8183 $blog_id = self::get_site_blog_id( $site );
8184
8185 foreach ( $storage_keys_for_removal as $key ) {
8186 $this->_storage->remove( $key, false, $blog_id );
8187 }
8188
8189 $this->_storage->save( $blog_id );
8190 }
8191 }
8192 }
8193
8194 // Clear API cache on deactivation.
8195 FS_Api::clear_cache();
8196
8197 $this->remove_sdk_reference();
8198 }
8199
8200 /**
8201 * @author Vova Feldman (@svovaf)
8202 * @since 1.1.6
8203 */
8204 private function remove_sdk_reference() {
8205 global $fs_active_plugins;
8206
8207 foreach ( $fs_active_plugins->plugins as $sdk_path => $data ) {
8208 if ( $this->_plugin_basename == $data->plugin_path ) {
8209 unset( $fs_active_plugins->plugins[ $sdk_path ] );
8210 break;
8211 }
8212 }
8213
8214 fs_fallback_to_newest_active_sdk();
8215 }
8216
8217 /**
8218 * @author Vova Feldman (@svovaf)
8219 * @since 1.1.3
8220 *
8221 * @param bool $is_anonymous
8222 * @param bool|int $network_or_blog_id Since 2.0.0
8223 */
8224 private function set_anonymous_mode( $is_anonymous = true, $network_or_blog_id = 0 ) {
8225 // Store information regarding skip to try and opt-in the user
8226 // again in the future.
8227 $skip_info = array(
8228 'is' => $is_anonymous,
8229 'timestamp' => WP_FS__SCRIPT_START_TIME,
8230 'version' => $this->get_plugin_version(),
8231 );
8232
8233 if ( true === $network_or_blog_id ) {
8234 $this->_storage->is_anonymous_ms = $skip_info;
8235 } else {
8236 $this->_storage->store( 'is_anonymous', $skip_info, $network_or_blog_id );
8237 }
8238
8239 $this->network_upgrade_mode_completed();
8240
8241 // Update anonymous mode cache.
8242 $this->_is_anonymous = $is_anonymous;
8243 }
8244
8245 /**
8246 * @author Vova Feldman (@svovaf)
8247 * @since 2.5.1
8248 *
8249 * @param bool|int $network_or_blog_id
8250 */
8251 private function unset_anonymous_mode( $network_or_blog_id = 0 ) {
8252 if ( true === $network_or_blog_id ) {
8253 unset( $this->_storage->is_anonymous_ms );
8254 } else {
8255 $this->_storage->remove( 'is_anonymous', true, $network_or_blog_id );
8256 }
8257 }
8258
8259 /**
8260 * @author Vova Feldman (@svovaf)
8261 * @since 2.0.0
8262 *
8263 * @param int $blog_id Site ID.
8264 * @param int $user_id User ID.
8265 * @param string $domain Site domain.
8266 * @param string $path Site path.
8267 * @param int $network_id Network ID. Only relevant on multi-network installations.
8268 * @param array $meta Metadata. Used to set initial site options.
8269 *
8270 * @uses Freemius::is_license_network_active() to check if the context license was network activated by the super-admin.
8271 * @uses Freemius::is_network_connected() to check if the super-admin network opted-in.
8272 * @uses Freemius::is_network_anonymous() to check if the super-admin network skipped.
8273 * @uses Freemius::is_network_delegated_connection() to check if the super-admin network delegated the connection to the site admins.
8274 */
8275 public function _after_new_blog_callback( $blog_id, $user_id, $domain, $path, $network_id, $meta ) {
8276 $this->_logger->entrance();
8277
8278 if ( ! $this->_is_network_active ) {
8279 FS_Clone_Manager::instance()->store_blog_install_info( $blog_id );
8280 return;
8281 }
8282
8283 $site = null;
8284 $new_blog_id = $blog_id;
8285
8286 if ( $this->is_premium() &&
8287 $this->is_network_connected() &&
8288 is_object( $this->_license ) &&
8289 $this->_license->can_activate( FS_Site::is_localhost_by_address( $domain ) ) &&
8290 $this->is_license_network_active( $blog_id )
8291 ) {
8292 /**
8293 * 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.
8294 */
8295 $current_blog_id = get_current_blog_id();
8296 $license = clone $this->_license;
8297
8298 $this->switch_to_blog( $blog_id );
8299
8300 // Opt-in with network user.
8301 $this->install_with_user(
8302 $this->get_network_user(),
8303 $license->secret_key,
8304 false,
8305 false,
8306 false
8307 );
8308
8309 if ( is_object( $this->_site ) ) {
8310 if ( $this->_site->license_id == $license->id ) {
8311 /**
8312 * If the license was activated successfully, sync the license data from the remote server.
8313 */
8314 $this->_license = $license;
8315 $this->sync_site_license();
8316 }
8317 }
8318
8319 $site = $this->_site;
8320
8321 $this->switch_to_blog( $current_blog_id );
8322
8323 if ( is_object( $site ) ) {
8324 FS_Clone_Manager::instance()->store_blog_install_info( $blog_id, $site );
8325
8326 // Already connected (with or without a license), so no need to continue.
8327 return;
8328 }
8329 }
8330
8331 if ( $this->is_network_anonymous() ) {
8332 /**
8333 * Opt-in was network skipped so automatically skip the opt-in for the new site.
8334 */
8335 $this->skip_site_connection( $blog_id );
8336 } else if ( $this->is_network_delegated_connection() ) {
8337 /**
8338 * Opt-in was network delegated so automatically delegate the opt-in for the new site's admin.
8339 */
8340 $this->delegate_site_connection( $blog_id );
8341 } else if ( $this->is_network_connected() ) {
8342 /**
8343 * Opt-in was network activated so automatically opt-in with the network user and new site admin.
8344 */
8345 $current_blog_id = get_current_blog_id();
8346
8347 $this->switch_to_blog( $blog_id );
8348
8349 // Opt-in with network user.
8350 $this->install_with_user(
8351 $this->get_network_user(),
8352 false,
8353 false,
8354 false,
8355 false
8356 );
8357
8358 $site = $this->_site;
8359
8360 $this->switch_to_blog( $current_blog_id );
8361 } else {
8362 /**
8363 * If the super-admin mixed different options (connect, skip, delegated):
8364 * a) If at least one site connection was delegated, then automatically delegate connection.
8365 * 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.
8366 */
8367 $has_delegated_site = false;
8368
8369 $sites = self::get_sites();
8370 foreach ( $sites as $wp_site ) {
8371 $blog_id = self::get_site_blog_id( $wp_site );
8372
8373 if ( $this->is_site_delegated_connection( $blog_id ) ) {
8374 $has_delegated_site = true;
8375 break;
8376 }
8377 }
8378
8379 if ( $has_delegated_site ) {
8380 $this->delegate_site_connection( $blog_id );
8381 } else {
8382 $this->skip_site_connection( $blog_id );
8383 }
8384 }
8385
8386 /**
8387 * 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.
8388 *
8389 * @author Leo Fajardo (@leorw)
8390 * @since 2.5.0
8391 */
8392 FS_Clone_Manager::instance()->store_blog_install_info( $new_blog_id, $site );
8393 }
8394
8395 /**
8396 * @author Vova Feldman (@svovaf)
8397 * @since 2.5.0
8398 *
8399 * @param \WP_Site $new_site
8400 * @param array $args
8401 */
8402 public function _after_wp_initialize_site_callback( WP_Site $new_site, $args ) {
8403 $this->_logger->entrance();
8404
8405 $this->_after_new_blog_callback(
8406 $new_site->id,
8407 // Dummy user ID (not in use).
8408 0,
8409 $new_site->domain,
8410 $new_site->path,
8411 $new_site->network_id,
8412 // Dummy meta, not in use.
8413 array()
8414 );
8415 }
8416
8417 /**
8418 * @author Vova Feldman (@svovaf)
8419 * @since 1.1.3
8420 *
8421 * @param bool|int|int[] $network_or_blog_ids Since 2.0.0.
8422 */
8423 private function reset_anonymous_mode( $network_or_blog_ids = false ) {
8424 if ( true === $network_or_blog_ids ) {
8425 $this->unset_anonymous_mode( true );
8426
8427 if ( fs_is_network_admin() ) {
8428 $this->_is_anonymous = null;
8429 }
8430
8431 // Rest anonymous mode for all non-delegated sub-sites.
8432 $blog_ids = $this->get_non_delegated_blog_ids();
8433 }
8434 else
8435 {
8436 if ( false === $network_or_blog_ids ) {
8437 $network_or_blog_ids = 0;
8438 }
8439
8440 $blog_ids = is_array( $network_or_blog_ids ) ?
8441 $network_or_blog_ids :
8442 array( $network_or_blog_ids );
8443
8444 foreach ( $blog_ids as $blog_id ) {
8445 if ( 0 === $blog_id || get_current_blog_id() == $blog_id ) {
8446 $this->_is_anonymous = null;
8447 }
8448 }
8449 }
8450
8451 foreach ( $blog_ids as $blog_id ) {
8452 $this->unset_anonymous_mode( $blog_id );
8453 }
8454
8455 /**
8456 * Ensure that this field is also "false", otherwise, if the current module's type is "theme" and the module
8457 * has no menus, the opt-in popup will not be shown immediately (in this case, the user will have to click
8458 * on the admin notice that contains the opt-in link in order to trigger the opt-in popup).
8459 *
8460 * @author Leo Fajardo (@leorw)
8461 * @since 1.2.2
8462 */
8463 if ( ! $this->_is_network_active ) {
8464 $this->_is_anonymous = null;
8465 }
8466 }
8467
8468 /**
8469 * @author Leo Fajardo (@leorw)
8470 * @since 2.5.3
8471 */
8472 private function update_license_required_permissions_if_anonymous() {
8473 if ( ! $this->is_anonymous() ) {
8474 return;
8475 }
8476
8477 $this->reset_anonymous_mode( fs_is_network_admin() );
8478
8479 FS_Permission_Manager::instance( $this )->update_permissions_tracking_flag( array(
8480 'essentials' => true,
8481 'events' => true,
8482 'diagnostic' => false,
8483 'extensions' => false,
8484 'site' => false,
8485 ) );
8486 }
8487
8488 /**
8489 * This is used to ensure that before redirecting to the opt-in page after resetting the anonymous mode or
8490 * deleting the account in the network level, the URL of the page to redirect to is correct.
8491 *
8492 * @author Leo Fajardo (@leorw)
8493 *
8494 * @since 2.1.3
8495 */
8496 private function maybe_set_slug_and_network_menu_exists_flag() {
8497 if ( ! empty( $this->_dynamically_added_top_level_page_hook_name ) ) {
8498 $this->_menu->set_slug_and_network_menu_exists_flag( $this->_menu->has_menu() ?
8499 $this->_menu->get_slug() :
8500 $this->_slug
8501 );
8502 }
8503 }
8504
8505 /**
8506 * Clears the anonymous mode and redirects to the opt-in screen.
8507 *
8508 * @author Vova Feldman (@svovaf)
8509 * @since 1.1.7
8510 */
8511 function connect_again() {
8512 if ( ! $this->is_anonymous() && ! $this->is_pending_activation() ) {
8513 return;
8514 }
8515
8516 if ( $this->is_anonymous() ) {
8517 $this->reset_anonymous_mode( fs_is_network_admin() );
8518 }
8519
8520 $activation_url_params = array();
8521
8522 if ( $this->is_pending_activation() ) {
8523 $this->clear_pending_activation_mode();
8524
8525 if ( fs_request_get_bool( 'require_license' ) ) {
8526 $activation_url_params['require_license'] = true;
8527 }
8528 }
8529
8530 $this->maybe_set_slug_and_network_menu_exists_flag();
8531
8532 fs_redirect( $this->get_activation_url( $activation_url_params ) );
8533 }
8534
8535 /**
8536 * Skip account connect, and set anonymous mode.
8537 *
8538 * @author Vova Feldman (@svovaf)
8539 * @since 1.1.1
8540 *
8541 * @param bool|int|int[] $network_or_blog_ids Since 2.5.1
8542 */
8543 function skip_connection( $network_or_blog_ids = false ) {
8544 $this->_logger->entrance();
8545
8546 $this->_admin_notices->remove_sticky( 'connect_account' );
8547
8548 if ( true === $network_or_blog_ids ) {
8549 $this->set_anonymous_mode( true, true );
8550
8551 if ( fs_is_network_admin() ) {
8552 $this->_is_anonymous = null;
8553 }
8554
8555 // Rest anonymous mode for all non-delegated sub-sites.
8556 $blog_ids = $this->get_non_delegated_blog_ids();
8557 }
8558 else
8559 {
8560 if ( false === $network_or_blog_ids ) {
8561 $network_or_blog_ids = 0;
8562 }
8563
8564 $blog_ids = is_array( $network_or_blog_ids ) ?
8565 $network_or_blog_ids :
8566 array( $network_or_blog_ids );
8567
8568 foreach ( $blog_ids as $blog_id ) {
8569 if ( 0 === $blog_id || get_current_blog_id() == $blog_id ) {
8570 $this->_is_anonymous = null;
8571 }
8572 }
8573 }
8574
8575 foreach ( $blog_ids as $blog_id ) {
8576 $this->skip_site_connection( $blog_id );
8577 }
8578
8579 $this->network_upgrade_mode_completed();
8580 }
8581
8582 /**
8583 * Skip connection for specific site in the network.
8584 *
8585 * @author Vova Feldman (@svovaf)
8586 * @since 2.0.0
8587 *
8588 * @param int|null $blog_id
8589 * @param bool $send_skip
8590 */
8591 private function skip_site_connection( $blog_id = null ) {
8592 $this->_logger->entrance();
8593
8594 $this->_admin_notices->remove_sticky( 'connect_account', $blog_id );
8595
8596 $this->set_anonymous_mode( true, $blog_id );
8597 }
8598
8599 /**
8600 * Plugin version update hook.
8601 *
8602 * @author Vova Feldman (@svovaf)
8603 * @since 1.0.4
8604 */
8605 private function update_plugin_version_event() {
8606 $this->_logger->entrance();
8607
8608 if ( ! $this->is_registered() ) {
8609 return;
8610 }
8611
8612 $this->schedule_install_sync();
8613 // $this->sync_install( array(), true );
8614 }
8615
8616 /**
8617 * Generate an MD5 signature of a plugins collection.
8618 * This helper methods used to identify changes in a plugins collection.
8619 *
8620 * @author Vova Feldman (@svovaf)
8621 * @since 2.0.0
8622 *
8623 * @param array [string]array $plugins
8624 *
8625 * @return string
8626 */
8627 private function get_plugins_thumbprint( $plugins ) {
8628 ksort( $plugins );
8629
8630 $thumbprint = '';
8631 foreach ( $plugins as $basename => $data ) {
8632 $thumbprint .= $data['slug'] . ',' .
8633 $data['Version'] . ',' .
8634 ( $data['is_active'] ? '1' : '0' ) . ';';
8635 }
8636
8637 return md5( $thumbprint );
8638 }
8639
8640 /**
8641 * Return a list of modified plugins since the last sync.
8642 *
8643 * Note:
8644 * There's no point to store a plugins counter since even if the number of
8645 * plugins didn't change, we still need to check if the versions are all the
8646 * same and the activity state is similar.
8647 *
8648 * @author Vova Feldman (@svovaf)
8649 * @since 1.1.8
8650 *
8651 * @return array|false
8652 */
8653 private function get_plugins_data_for_api() {
8654 // Alias.
8655 $site_active_plugins_option_name = 'active_plugins';
8656 $network_plugins_option_name = 'all_plugins';
8657
8658 /**
8659 * Collection of all site level active plugins.
8660 */
8661 $site_active_plugins_cache = self::$_accounts->get_option( $site_active_plugins_option_name );
8662
8663 if ( ! is_object( $site_active_plugins_cache ) ) {
8664 $site_active_plugins_cache = (object) array(
8665 'timestamp' => '',
8666 'md5' => '',
8667 'plugins' => array(),
8668 );
8669 }
8670
8671 $time = time();
8672
8673 if ( ! empty( $site_active_plugins_cache->timestamp ) &&
8674 ( $time - $site_active_plugins_cache->timestamp ) < WP_FS__TIME_5_MIN_IN_SEC
8675 ) {
8676 // Don't send plugin updates if last update was in the past 5 min.
8677 return false;
8678 }
8679
8680 // Write timestamp to lock the logic.
8681 $site_active_plugins_cache->timestamp = $time;
8682 self::$_accounts->set_option( $site_active_plugins_option_name, $site_active_plugins_cache, true );
8683
8684 // Reload options from DB.
8685 self::$_accounts->load( true );
8686 $site_active_plugins_cache = self::$_accounts->get_option( $site_active_plugins_option_name );
8687
8688 if ( $time != $site_active_plugins_cache->timestamp ) {
8689 // If timestamp is different, then another thread captured the lock.
8690 return false;
8691 }
8692
8693 /**
8694 * Collection of all plugins (network level).
8695 */
8696 $network_plugins_cache = self::$_accounts->get_option( $network_plugins_option_name );
8697
8698 if ( ! is_object( $network_plugins_cache ) ) {
8699 $network_plugins_cache = (object) array(
8700 'timestamp' => '',
8701 'md5' => '',
8702 'plugins' => array(),
8703 );
8704 }
8705
8706 // Check if there's a change in plugins.
8707 $network_plugins = self::get_network_plugins();
8708 $site_active_plugins = self::get_site_active_plugins();
8709
8710 $network_plugins_thumbprint = $this->get_plugins_thumbprint( $network_plugins );
8711 $site_active_plugins_thumbprint = $this->get_plugins_thumbprint( $site_active_plugins );
8712
8713 // Check if plugins status changed (version or active/inactive).
8714 $network_plugins_changed = ( $network_plugins_cache->md5 !== $network_plugins_thumbprint );
8715 $site_active_plugins_changed = ( $site_active_plugins_cache->md5 !== $site_active_plugins_thumbprint );
8716
8717 if ( ! $network_plugins_changed &&
8718 ! $site_active_plugins_changed
8719 ) {
8720 // No changes.
8721 return array();
8722 }
8723
8724 $plugins_update_data = array();
8725
8726 foreach ( $network_plugins_cache->plugins as $basename => $data ) {
8727 if ( ! isset( $network_plugins[ $basename ] ) ) {
8728 // Plugin uninstalled.
8729 $uninstalled_plugin_data = $data;
8730 $uninstalled_plugin_data['is_active'] = false;
8731 $uninstalled_plugin_data['is_uninstalled'] = true;
8732 $plugins_update_data[] = $uninstalled_plugin_data;
8733
8734 unset( $network_plugins[ $basename ] );
8735
8736 unset( $network_plugins_cache->plugins[ $basename ] );
8737 unset( $site_active_plugins_cache->plugins[ $basename ] );
8738
8739 continue;
8740 }
8741
8742 $was_active = $data['is_active'] ||
8743 ( isset( $site_active_plugins_cache->plugins[ $basename ] ) &&
8744 true === $site_active_plugins_cache->plugins[ $basename ]['is_active'] );
8745 $is_active = $network_plugins[ $basename ]['is_active'] ||
8746 ( isset( $site_active_plugins[ $basename ] ) &&
8747 $site_active_plugins[ $basename ]['is_active'] );
8748
8749 if ( ! isset( $site_active_plugins_cache->plugins[ $basename ] ) &&
8750 isset( $site_active_plugins[ $basename ] )
8751 ) {
8752 // Plugin was site level activated.
8753 $site_active_plugins_cache->plugins[ $basename ] = $network_plugins[ $basename ];
8754 $site_active_plugins_cache->plugins[ $basename ]['is_active'] = true;
8755 } else if ( isset( $site_active_plugins_cache->plugins[ $basename ] ) &&
8756 ! isset( $site_active_plugins[ $basename ] )
8757 ) {
8758 // Plugin was site level deactivated.
8759 unset( $site_active_plugins_cache->plugins[ $basename ] );
8760 }
8761
8762 $prev_version = $data['version'];
8763 $current_version = $network_plugins[ $basename ]['Version'];
8764
8765 if ( $was_active !== $is_active || $prev_version !== $current_version ) {
8766 // Plugin activated or deactivated, or version changed.
8767
8768 if ( $was_active !== $is_active ) {
8769 if ( $data['is_active'] != $network_plugins[ $basename ]['is_active'] ) {
8770 $network_plugins_cache->plugins[ $basename ]['is_active'] = $data['is_active'];
8771 }
8772 }
8773
8774 if ( $prev_version !== $current_version ) {
8775 $network_plugins_cache->plugins[ $basename ]['Version'] = $current_version;
8776 }
8777
8778 $updated_plugin_data = $data;
8779 $updated_plugin_data['is_active'] = $is_active;
8780 $updated_plugin_data['version'] = $current_version;
8781 $updated_plugin_data['title'] = $network_plugins[ $basename ]['Name'];
8782 $plugins_update_data[] = $updated_plugin_data;
8783 }
8784 }
8785
8786 // Find new plugins that weren't yet seen before.
8787 foreach ( $network_plugins as $basename => $data ) {
8788 if ( ! isset( $network_plugins_cache->plugins[ $basename ] ) ) {
8789 // New plugin.
8790 $new_plugin = array(
8791 'slug' => $data['slug'],
8792 'version' => $data['Version'],
8793 'title' => $data['Name'],
8794 'is_active' => $data['is_active'],
8795 'is_uninstalled' => false,
8796 );
8797
8798 $network_plugins_cache->plugins[ $basename ] = $new_plugin;
8799
8800 $is_site_level_active = (
8801 isset( $site_active_plugins[ $basename ] ) &&
8802 $site_active_plugins[ $basename ]['is_active']
8803 );
8804
8805 /**
8806 * If not network active, set the activity status based on the site-level plugin status.
8807 */
8808 if ( ! $new_plugin['is_active'] ) {
8809 $new_plugin['is_active'] = $is_site_level_active;
8810 }
8811
8812 $plugins_update_data[] = $new_plugin;
8813
8814 if ( isset( $site_active_plugins[ $basename ] ) ) {
8815 $site_active_plugins_cache->plugins[ $basename ] = $new_plugin;
8816 $site_active_plugins_cache->plugins[ $basename ]['is_active'] = $is_site_level_active;
8817 }
8818 }
8819 }
8820
8821 $site_active_plugins_cache->md5 = $site_active_plugins_thumbprint;
8822 $site_active_plugins_cache->timestamp = $time;
8823 self::$_accounts->set_option( $site_active_plugins_option_name, $site_active_plugins_cache, true );
8824
8825 $network_plugins_cache->md5 = $network_plugins_thumbprint;
8826 $network_plugins_cache->timestamp = $time;
8827 self::$_accounts->set_option( $network_plugins_option_name, $network_plugins_cache, true );
8828
8829 return $plugins_update_data;
8830 }
8831
8832 /**
8833 * Return a list of modified themes since the last sync.
8834 *
8835 * Note:
8836 * There's no point to store a themes counter since even if the number of
8837 * themes didn't change, we still need to check if the versions are all the
8838 * same and the activity state is similar.
8839 *
8840 * @author Vova Feldman (@svovaf)
8841 * @since 1.1.8
8842 *
8843 * @return array|false
8844 */
8845 private function get_themes_data_for_api() {
8846 // Alias.
8847 $option_name = 'all_themes';
8848
8849 $all_cached_themes = self::$_accounts->get_option( $option_name );
8850
8851 if ( ! is_object( $all_cached_themes ) ) {
8852 $all_cached_themes = (object) array(
8853 'timestamp' => '',
8854 'md5' => '',
8855 'themes' => array(),
8856 );
8857 }
8858
8859 $time = time();
8860
8861 if ( ! empty( $all_cached_themes->timestamp ) &&
8862 ( $time - $all_cached_themes->timestamp ) < WP_FS__TIME_5_MIN_IN_SEC
8863 ) {
8864 // Don't send theme updates if last update was in the past 5 min.
8865 return false;
8866 }
8867
8868 // Write timestamp to lock the logic.
8869 $all_cached_themes->timestamp = $time;
8870 self::$_accounts->set_option( $option_name, $all_cached_themes, true );
8871
8872 // Reload options from DB.
8873 self::$_accounts->load( true );
8874 $all_cached_themes = self::$_accounts->get_option( $option_name );
8875
8876 if ( $time != $all_cached_themes->timestamp ) {
8877 // If timestamp is different, then another thread captured the lock.
8878 return false;
8879 }
8880
8881 // Get active theme.
8882 $active_theme = wp_get_theme();
8883 $active_theme_stylesheet = $active_theme->get_stylesheet();
8884
8885 // Check if there's a change in themes.
8886 $all_themes = wp_get_themes();
8887
8888 // Check if themes changed.
8889 ksort( $all_themes );
8890
8891 $themes_signature = '';
8892 foreach ( $all_themes as $slug => $data ) {
8893 $is_active = ( $slug === $active_theme_stylesheet );
8894 $themes_signature .= $slug . ',' .
8895 $data->version . ',' .
8896 ( $is_active ? '1' : '0' ) . ';';
8897 }
8898
8899 // Check if themes status changed (version or active/inactive).
8900 $themes_changed = ( $all_cached_themes->md5 !== md5( $themes_signature ) );
8901
8902 $themes_update_data = array();
8903
8904 if ( $themes_changed ) {
8905 // Change in themes, report changes.
8906
8907 // Update existing themes info.
8908 foreach ( $all_cached_themes->themes as $slug => $data ) {
8909 $is_active = ( $slug === $active_theme_stylesheet );
8910
8911 if ( ! isset( $all_themes[ $slug ] ) ) {
8912 // Plugin uninstalled.
8913 $uninstalled_theme_data = $data;
8914 $uninstalled_theme_data['is_active'] = false;
8915 $uninstalled_theme_data['is_uninstalled'] = true;
8916 $themes_update_data[] = $uninstalled_theme_data;
8917
8918 unset( $all_themes[ $slug ] );
8919 unset( $all_cached_themes->themes[ $slug ] );
8920 } else if ( $data['is_active'] !== $is_active ||
8921 $data['version'] !== $all_themes[ $slug ]->version
8922 ) {
8923 // Plugin activated or deactivated, or version changed.
8924
8925 $all_cached_themes->themes[ $slug ]['is_active'] = $is_active;
8926 $all_cached_themes->themes[ $slug ]['version'] = $all_themes[ $slug ]->version;
8927
8928 $themes_update_data[] = $all_cached_themes->themes[ $slug ];
8929 }
8930 }
8931
8932 // Find new themes that weren't yet seen before.
8933 foreach ( $all_themes as $slug => $data ) {
8934 if ( ! isset( $all_cached_themes->themes[ $slug ] ) ) {
8935 $is_active = ( $slug === $active_theme_stylesheet );
8936
8937 // New plugin.
8938 $new_plugin = array(
8939 'slug' => $slug,
8940 'version' => $data->version,
8941 'title' => $data->name,
8942 'is_active' => $is_active,
8943 'is_uninstalled' => false,
8944 );
8945
8946 $themes_update_data[] = $new_plugin;
8947 $all_cached_themes->themes[ $slug ] = $new_plugin;
8948 }
8949 }
8950
8951 $all_cached_themes->md5 = md5( $themes_signature );
8952 $all_cached_themes->timestamp = time();
8953 self::$_accounts->set_option( $option_name, $all_cached_themes, true );
8954 }
8955
8956 return $themes_update_data;
8957 }
8958
8959 /**
8960 * Get site data for API install request.
8961 *
8962 * @author Vova Feldman (@svovaf)
8963 * @since 1.1.2
8964 *
8965 * @param string[] $override
8966 * @param bool $include_plugins Since 1.1.8 by default include plugin changes.
8967 * @param bool $include_themes Since 1.1.8 by default include plugin changes.
8968 * @param bool $include_blog_data Since 2.3.0 by default include the current blog's data (language, title, and URL).
8969 *
8970 * @return array
8971 */
8972 private function get_install_data_for_api(
8973 array $override,
8974 $include_plugins = true,
8975 $include_themes = true,
8976 $include_blog_data = true
8977 ) {
8978 // Alias.
8979 $permissions = FS_Permission_Manager::instance( $this );
8980
8981 if ( $permissions->is_extensions_tracking_allowed() ) {
8982 if ( ! defined( 'WP_FS__TRACK_PLUGINS' ) || false !== WP_FS__TRACK_PLUGINS ) {
8983 /**
8984 * @since 1.1.8 Also send plugin updates.
8985 */
8986 if ( $include_plugins && ! isset( $override['plugins'] ) ) {
8987 $plugins = $this->get_plugins_data_for_api();
8988 if ( ! empty( $plugins ) ) {
8989 $override['plugins'] = $plugins;
8990 }
8991 }
8992 }
8993
8994 if ( ! defined( 'WP_FS__TRACK_THEMES' ) || false !== WP_FS__TRACK_THEMES ) {
8995 /**
8996 * @since 1.1.8 Also send themes updates.
8997 */
8998 if ( $include_themes && ! isset( $override['themes'] ) ) {
8999 $themes = $this->get_themes_data_for_api();
9000 if ( ! empty( $themes ) ) {
9001 $override['themes'] = $themes;
9002 }
9003 }
9004 }
9005 }
9006
9007 $versions = $this->get_versions();
9008
9009 $blog_data = array();
9010 if ( $include_blog_data ) {
9011 $blog_data['url'] = self::get_unfiltered_site_url();
9012
9013 if ( $permissions->is_diagnostic_tracking_allowed() ) {
9014 $blog_data = array_merge( $blog_data, array(
9015 'language' => self::get_sanitized_language(),
9016 'title' => get_bloginfo( 'name' ),
9017 ) );
9018 }
9019 }
9020
9021 return array_merge( $versions, $blog_data, array(
9022 'version' => $this->get_plugin_version(),
9023 'is_premium' => $this->is_premium(),
9024 // Special params.
9025 'is_active' => true,
9026 'is_uninstalled' => false,
9027 ), $override );
9028 }
9029
9030 /**
9031 * Update installs details.
9032 *
9033 * @todo V1 of multiste network support doesn't support plugin and theme data sending.
9034 *
9035 * @author Vova Feldman (@svovaf)
9036 * @since 2.0.0
9037 *
9038 * @param string[] string $override
9039 * @param bool $only_diff
9040 * @param bool $is_keepalive
9041 * @param bool $include_plugins Since 1.1.8 by default include plugin changes.
9042 * @param bool $include_themes Since 1.1.8 by default include plugin changes.
9043 *
9044 * @return array
9045 */
9046 private function get_installs_data_for_api(
9047 array $override,
9048 $only_diff = false,
9049 $is_keepalive = false,
9050 $include_plugins = true,
9051 $include_themes = true
9052 ) {
9053 /**
9054 * @since 1.1.8 Also send plugin updates.
9055 */
9056 // if ( $include_plugins && ! isset( $override['plugins'] ) ) {
9057 // $plugins = $this->get_plugins_data_for_api();
9058 // if ( ! empty( $plugins ) ) {
9059 // $override['plugins'] = $plugins;
9060 // }
9061 // }
9062 /**
9063 * @since 1.1.8 Also send themes updates.
9064 */
9065 // if ( $include_themes && ! isset( $override['themes'] ) ) {
9066 // $themes = $this->get_themes_data_for_api();
9067 // if ( ! empty( $themes ) ) {
9068 // $override['themes'] = $themes;
9069 // }
9070 // }
9071
9072 // Common properties.
9073 $versions = $this->get_versions();
9074 $common = array_merge( $versions, array(
9075 'version' => $this->get_plugin_version(),
9076 'is_premium' => $this->is_premium(),
9077 ), $override );
9078
9079
9080 $is_common_diff_for_any_site = false;
9081 $common_diff_union = array();
9082
9083 $installs_data = array();
9084
9085 $sites = self::get_sites();
9086
9087 $subsite_data_for_api_by_install_id = array();
9088 $install_url_by_install_id = array();
9089 $subsite_registration_date_by_install_id = array();
9090
9091 foreach ( $sites as $site ) {
9092 $blog_id = self::get_site_blog_id( $site );
9093
9094 $install = $this->get_install_by_blog_id( $blog_id );
9095
9096 if ( is_object( $install ) ) {
9097 if ( $install->user_id != $this->_user->id ) {
9098 // Install belongs to a different owner.
9099 continue;
9100 }
9101
9102 if ( ! $this->is_tracking_allowed( $blog_id, $install ) ) {
9103 // Don't send updates regarding opted-out installs.
9104 continue;
9105 }
9106
9107 $install_data = $this->get_site_info( $site, true );
9108
9109 if ( FS_Clone_Manager::instance()->is_temporary_duplicate_by_blog_id( $install_data['blog_id'] ) ) {
9110 continue;
9111 }
9112
9113 $uid = $install_data['uid'];
9114 $url = $install_data['url'];
9115 $registration_date = $install_data['registration_date'];
9116
9117 if ( isset( $subsite_data_for_api_by_install_id[ $install->id ] ) ) {
9118 $clone_subsite_data = $subsite_data_for_api_by_install_id[ $install->id ];
9119 $clone_install_url = $install_url_by_install_id[ $install->id ];
9120 $clone_subsite_registration_date = $subsite_registration_date_by_install_id[ $install->id ];
9121
9122 $skip = false;
9123
9124 if (
9125 ! empty( $install_data['registration_date'] ) &&
9126 ! empty( $clone_subsite_registration_date )
9127 ) {
9128 /**
9129 * 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.
9130 *
9131 * @author Leo Fajardo (@leorw)
9132 * @since 2.5.1
9133 */
9134 $skip = ( strtotime( $install_data['registration_date'] ) > strtotime( $clone_subsite_registration_date ) );
9135 } else if (
9136 /**
9137 * 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.
9138 *
9139 * @author Leo Fajardo (@leorw)
9140 * @since 2.5.0
9141 */
9142 fs_strip_url_protocol( untrailingslashit( $clone_install_url ) ) === fs_strip_url_protocol( untrailingslashit( $clone_subsite_data['url'] ) ) ||
9143 fs_strip_url_protocol( untrailingslashit( $install->url ) ) !== fs_strip_url_protocol( untrailingslashit( $url ) )
9144 ) {
9145 $skip = true;
9146 }
9147
9148 if ( $skip ) {
9149 // 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.
9150 FS_Clone_Manager::instance()->store_blog_install_info( $blog_id );
9151 continue;
9152 }
9153 }
9154
9155 unset( $install_data['blog_id'] );
9156 unset( $install_data['uid'] );
9157 unset( $install_data['url'] );
9158 unset( $install_data['registration_date'] );
9159
9160 $install_data['is_active'] = $this->is_active_for_site( $blog_id );
9161 $install_data['is_uninstalled'] = $install->is_uninstalled;
9162
9163 $common_diff = null;
9164 $is_common_diff = false;
9165 if ( $only_diff ) {
9166 $install_data = $this->get_install_diff_for_api( $install_data, $install, $override );
9167 $common_diff = $this->get_install_diff_for_api( $common, $install, $override );
9168
9169 $is_common_diff = ! empty( $common_diff );
9170
9171 if ( $is_common_diff ) {
9172 foreach ( $common_diff as $k => $v ) {
9173 if ( ! isset( $common_diff_union[ $k ] ) ) {
9174 $common_diff_union[ $k ] = $v;
9175 }
9176 }
9177 }
9178
9179 $is_common_diff_for_any_site = $is_common_diff_for_any_site || $is_common_diff;
9180 }
9181
9182 if ( ! empty( $install_data ) || $is_common_diff || $is_keepalive ) {
9183 // Add install ID and site unique ID.
9184 $install_data['id'] = $install->id;
9185 $install_data['uid'] = $uid;
9186 $install_data['url'] = $url;
9187
9188 $subsite_data_for_api_by_install_id[ $install->id ] = $install_data;
9189 $install_url_by_install_id[ $install->id ] = $install->url;
9190 $subsite_registration_date_by_install_id[ $install->id ] = $registration_date;
9191 }
9192 }
9193 }
9194
9195 restore_current_blog();
9196
9197 $installs_data = array_merge(
9198 $installs_data,
9199 array_values( $subsite_data_for_api_by_install_id )
9200 );
9201
9202 if ( 0 < count( $installs_data ) && ( $is_common_diff_for_any_site || ! $only_diff ) ) {
9203 if ( ! $only_diff ) {
9204 $installs_data[] = $common;
9205 } else if ( ! empty( $common_diff_union ) ) {
9206 $installs_data[] = $common_diff_union;
9207 }
9208 }
9209
9210 foreach ( $installs_data as &$data ) {
9211 $data = (object) $data;
9212 }
9213
9214 return $installs_data;
9215 }
9216
9217 /**
9218 * Compare site actual data to the stored install data and return the differences for an API data sync.
9219 *
9220 * @author Vova Feldman (@svovaf)
9221 * @since 2.0.0
9222 *
9223 * @param array $site
9224 * @param FS_Site $install
9225 * @param string[] string $override
9226 *
9227 * @return array
9228 */
9229 private function get_install_diff_for_api( $site, $install, $override = array() ) {
9230 $diff = array();
9231 $special = array();
9232 $special_override = false;
9233
9234 foreach ( $site as $p => $v ) {
9235 if ( property_exists( $install, $p ) ) {
9236 if ( ( is_bool( $install->{$p} ) || ! empty( $install->{$p} ) ) &&
9237 $install->{$p} != $v
9238 ) {
9239 $val = self::get_api_sanitized_property( $p, $v );
9240
9241 if ( $install->{$p} != $val ) {
9242 $install->{$p} = $val;
9243 $diff[ $p ] = $val;
9244 }
9245 }
9246 } else {
9247 $special[ $p ] = $v;
9248
9249 if ( isset( $override[ $p ] ) ||
9250 'plugins' === $p ||
9251 'themes' === $p
9252 ) {
9253 $special_override = true;
9254 }
9255 }
9256 }
9257
9258 if ( $special_override || 0 < count( $diff ) ) {
9259 // Add special params only if has at least one
9260 // standard param, or if explicitly requested to
9261 // override a special param or a param which is not exist
9262 // in the install object.
9263 $diff = array_merge( $diff, $special );
9264 }
9265
9266 return $diff;
9267 }
9268
9269 /**
9270 * @author Leo Fajardo (@leorw)
9271 * @since 2.5.1
9272 */
9273 private function send_pending_clone_update_once() {
9274 $this->_logger->entrance();
9275
9276 if ( ! empty( $this->_storage->clone_id ) ) {
9277 return;
9278 }
9279
9280 $install_clone = $this->get_api_site_scope()->call(
9281 '/clones',
9282 'post',
9283 array( 'site_url' => self::get_unfiltered_site_url() )
9284 );
9285
9286 if ( $this->is_api_result_entity( $install_clone ) ) {
9287 $this->_storage->clone_id = $install_clone->id;
9288 }
9289 }
9290
9291 /**
9292 * @author Leo Fajardo (@leorw)
9293 * @since 2.5.1
9294 *
9295 * @param string $resolution_type
9296 * @param FS_Site $clone_context_install
9297 */
9298 function send_clone_resolution_update( $resolution_type, $clone_context_install ) {
9299 $this->_logger->entrance();
9300
9301 if ( empty( $this->_storage->clone_id ) ) {
9302 return;
9303 }
9304
9305 $new_install_id = null;
9306 $current_site = null;
9307
9308 $flush = false;
9309
9310 /**
9311 * 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.
9312 */
9313 if ( $clone_context_install->id != $this->_site->id ) {
9314 $new_install_id = $this->_site->id;
9315 $current_site = $this->_site;
9316 $this->_site = $clone_context_install;
9317
9318 $flush = true;
9319 }
9320
9321 $this->get_api_site_scope( $flush )->call(
9322 "/clones/{$this->_storage->clone_id}",
9323 'put',
9324 array(
9325 'resolution' => $resolution_type,
9326 'new_install_id' => $new_install_id,
9327 )
9328 );
9329
9330 if ( is_object( $current_site ) ) {
9331 /**
9332 * Ensure that the install scope entity is updated back to the previous install entity.
9333 */
9334 $this->_site = $current_site;
9335
9336 // Restore the previous install scope entity of the API.
9337 $this->get_api_site_scope( true );
9338 }
9339 }
9340
9341 /**
9342 * Update install only if changed.
9343 *
9344 * @author Vova Feldman (@svovaf)
9345 * @since 1.0.9
9346 *
9347 * @param string[] string $override
9348 * @param bool $flush
9349 * @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.
9350 *
9351 * @return false|object|string
9352 */
9353 private function send_install_update( $override = array(), $flush = false, $is_two_way_sync = false ) {
9354 $this->_logger->entrance();
9355
9356 $check_properties = $this->get_install_data_for_api( $override );
9357
9358 if ( $flush ) {
9359 $params = $check_properties;
9360 } else {
9361 $params = $this->get_install_diff_for_api( $check_properties, $this->_site, $override );
9362 }
9363
9364 if ( empty( $params ) ) {
9365 $keepalive_only_update = $this->should_send_keepalive_update();
9366
9367 if ( ! $keepalive_only_update ) {
9368 /**
9369 * There are no updates to send including keepalive.
9370 *
9371 * @author Leo Fajardo (@leorw)
9372 * @since 2.2.3
9373 */
9374 return false;
9375 }
9376 }
9377
9378 if ( $is_two_way_sync ) {
9379 /**
9380 * Update last install sync timestamp during a two-way sync call as we expect that updates are sent during this call.
9381 *
9382 * @author Leo Fajardo (@leorw)
9383 * @since 2.2.3
9384 */
9385 if ( ! is_multisite() ) {
9386 // Update last install sync timestamp.
9387 $this->set_cron_execution_timestamp( 'install_sync' );
9388 }
9389
9390 $params['uid'] = $this->get_anonymous_id();
9391 }
9392
9393 $this->set_keepalive_timestamp();
9394
9395 // Send updated values to FS.
9396 $site = $this->api_site_call( '/', 'put', $params, true );
9397
9398 if ( $is_two_way_sync && $this->is_api_result_entity( $site ) ) {
9399 /**
9400 * Clear scheduled install sync after a two-way sync call.
9401 *
9402 * @author Leo Fajardo (@leorw)
9403 * @since 2.2.3
9404 */
9405 if ( ! is_multisite() ) {
9406 // I successfully sent install update, clear scheduled sync if exist.
9407 $this->clear_install_sync_cron();
9408 }
9409 }
9410
9411 return $site;
9412 }
9413
9414 /**
9415 * Update installs only if changed.
9416 *
9417 * @author Vova Feldman (@svovaf)
9418 * @since 2.0.0
9419 *
9420 * @param string[] string $override
9421 * @param bool $flush
9422 * @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.
9423 *
9424 * @return false|object|string
9425 */
9426 private function send_installs_update( $override = array(), $flush = false, $is_two_way_sync = false ) {
9427 $this->_logger->entrance();
9428
9429 /**
9430 * Pass `true` to use the network level storage since the update is for many installs.
9431 *
9432 * @author Leo Fajardo (@leorw)
9433 * @since 2.2.3
9434 */
9435 $should_send_keepalive = $this->should_send_keepalive_update( true );
9436
9437 $installs_data = $this->get_installs_data_for_api( $override, ! $flush, $should_send_keepalive );
9438
9439 if ( empty( $installs_data ) ) {
9440 return false;
9441 }
9442
9443 if ( $is_two_way_sync ) {
9444 // Update last install sync timestamp during a two-way sync call as we expect that updates are sent during this call.
9445 $this->set_cron_execution_timestamp( 'install_sync' );
9446 }
9447
9448 /**
9449 * Pass `true` to use the network level storage since the update is for many installs.
9450 *
9451 * @author Leo Fajardo (@leorw)
9452 * @since 2.2.3
9453 */
9454 $this->set_keepalive_timestamp( true );
9455
9456 // Send updated values to FS.
9457 $result = $this->get_api_user_scope()->call( "/plugins/{$this->_plugin->id}/installs.json", 'put', $installs_data );
9458
9459 if ( $is_two_way_sync && $this->is_api_result_object( $result, 'installs' ) ) {
9460 // I successfully sent a two-way installs update, clear the scheduled install sync if it exists.
9461 $this->clear_install_sync_cron();
9462 }
9463
9464 return $result;
9465 }
9466
9467 /**
9468 * @author Leo Fajardo (@leorw)
9469 *
9470 * @param bool|null $use_network_level_storage
9471 *
9472 * @return bool
9473 */
9474 private function should_send_keepalive_update( $use_network_level_storage = null ) {
9475 $keepalive_timestamp = $this->_storage->get( 'keepalive_timestamp', 0, $use_network_level_storage );
9476
9477 if ( $keepalive_timestamp < ( time() - WP_FS__TIME_WEEK_IN_SEC ) ) {
9478 // If updated more than 7 days ago, trigger a keepalive and update the time it was triggered.
9479 return true;
9480 } else {
9481 // 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.
9482 return ( 7 == rand( 1, 7 ) );
9483 }
9484 }
9485
9486 /**
9487 * Syncs the install owner's data if needed (i.e., if the install owner is different from the loaded user).
9488 *
9489 * @author Leo Fajardo (@leorw)
9490 * @since 2.3.2
9491 */
9492 private function maybe_sync_install_user() {
9493 if ( $this->_user->id == $this->_site->user_id ) {
9494 return;
9495 }
9496
9497 // Fetch user data and store if found.
9498 $this->sync_user_by_current_install();
9499 }
9500
9501 /**
9502 * Update install only if changed.
9503 *
9504 * @author Vova Feldman (@svovaf)
9505 * @since 1.0.9
9506 *
9507 * @param string[] string $override
9508 * @param bool $flush
9509 */
9510 function sync_install( $override = array(), $flush = false ) {
9511 $this->_logger->entrance();
9512
9513 $site = $this->send_install_update( $override, $flush, true );
9514
9515 if ( false === $site ) {
9516 // No sync required.
9517 return;
9518 }
9519
9520 if ( ! $this->is_api_result_entity( $site ) ) {
9521 // Failed to sync, don't update locally.
9522 return;
9523 }
9524
9525 $this->_site = new FS_Site( $site );
9526
9527 $this->_store_site( true );
9528 }
9529
9530 /**
9531 * Update install only if changed.
9532 *
9533 * @author Vova Feldman (@svovaf)
9534 * @since 1.0.9
9535 *
9536 * @param string[] string $override
9537 * @param bool $flush
9538 */
9539 private function sync_installs( $override = array(), $flush = false ) {
9540 $this->_logger->entrance();
9541
9542 $result = $this->send_installs_update( $override, $flush, true );
9543
9544 if ( false === $result ) {
9545 // No sync required.
9546 return;
9547 }
9548
9549 if ( ! $this->is_api_result_object( $result, 'installs' ) ) {
9550 // Failed to sync, don't update locally.
9551 return;
9552 }
9553
9554 $address_to_blog_map = $this->get_address_to_blog_map();
9555
9556 foreach ( $result->installs as $install ) {
9557 $this->_site = new FS_Site( $install );
9558
9559 $address = trailingslashit( fs_strip_url_protocol( $install->url ) );
9560 $blog_id = $address_to_blog_map[ $address ];
9561
9562 $this->_store_site( true, $blog_id );
9563 }
9564 }
9565
9566 /**
9567 * Track install's custom event.
9568 *
9569 * IMPORTANT:
9570 * Custom event tracking is currently only supported for specific clients.
9571 * If you are not one of them, please don't use this method. If you will,
9572 * the API will simply ignore your request based on the plugin ID.
9573 *
9574 * Need custom tracking for your plugin or theme?
9575 * If you are interested in custom event tracking please contact yo@freemius.com
9576 * for further details.
9577 *
9578 * @author Vova Feldman (@svovaf)
9579 * @since 1.2.1
9580 *
9581 * @param string $name Event name.
9582 * @param array $properties Associative key/value array with primitive values only
9583 * @param bool $process_at A valid future date-time in the following format Y-m-d H:i:s.
9584 * @param bool $once If true, event will be tracked only once. IMPORTANT: Still trigger the API call.
9585 *
9586 * @return object|false Event data or FALSE on failure.
9587 *
9588 * @throws \Freemius_InvalidArgumentException
9589 */
9590 public function track_event( $name, $properties = array(), $process_at = false, $once = false ) {
9591 $this->_logger->entrance( http_build_query( array( 'name' => $name, 'once' => $once ) ) );
9592
9593 if ( ! $this->is_registered() ) {
9594 return false;
9595 }
9596
9597 $event = array( 'type' => $name );
9598
9599 if ( is_numeric( $process_at ) && $process_at > time() ) {
9600 $event['process_at'] = $process_at;
9601 }
9602
9603 if ( $once ) {
9604 $event['once'] = true;
9605 }
9606
9607 if ( ! empty( $properties ) ) {
9608 // Verify associative array values are primitive.
9609 foreach ( $properties as $k => $v ) {
9610 if ( ! is_scalar( $v ) ) {
9611 throw new Freemius_InvalidArgumentException( 'The $properties argument must be an associative key/value array with primitive values only.' );
9612 }
9613 }
9614
9615 $event['properties'] = $properties;
9616 }
9617
9618 $result = $this->get_api_site_scope()->call( 'events.json', 'post', $event );
9619
9620 return $this->is_api_error( $result ) ?
9621 false :
9622 $result;
9623 }
9624
9625 /**
9626 * Track install's custom event only once, but it still triggers the API call.
9627 *
9628 * IMPORTANT:
9629 * Custom event tracking is currently only supported for specific clients.
9630 * If you are not one of them, please don't use this method. If you will,
9631 * the API will simply ignore your request based on the plugin ID.
9632 *
9633 * Need custom tracking for your plugin or theme?
9634 * If you are interested in custom event tracking please contact yo@freemius.com
9635 * for further details.
9636 *
9637 * @author Vova Feldman (@svovaf)
9638 * @since 1.2.1
9639 *
9640 * @param string $name Event name.
9641 * @param array $properties Associative key/value array with primitive values only
9642 * @param bool $process_at A valid future date-time in the following format Y-m-d H:i:s.
9643 *
9644 * @return object|false Event data or FALSE on failure.
9645 *
9646 * @throws \Freemius_InvalidArgumentException
9647 *
9648 * @user Freemius::track_event()
9649 */
9650 public function track_event_once( $name, $properties = array(), $process_at = false ) {
9651 return $this->track_event( $name, $properties, $process_at, true );
9652 }
9653
9654 /**
9655 * Plugin uninstall hook.
9656 *
9657 * @author Vova Feldman (@svovaf)
9658 * @since 1.0.1
9659 *
9660 * @param bool $check_user Enforce checking if user have plugins activation privileges.
9661 */
9662 function _uninstall_plugin_event( $check_user = true ) {
9663 $this->_logger->entrance( 'slug = ' . $this->_slug );
9664
9665 if ( $check_user && ! current_user_can( 'activate_plugins' ) ) {
9666 return;
9667 }
9668
9669 $params = array();
9670 $uninstall_reason = null;
9671 if ( isset( $this->_storage->uninstall_reason ) ) {
9672 $uninstall_reason = $this->_storage->uninstall_reason;
9673 $params['reason_id'] = $uninstall_reason->id;
9674 $params['reason_info'] = $uninstall_reason->info;
9675 }
9676
9677 if ( ! $this->is_registered() ) {
9678 // Send anonymous uninstall event only if user submitted a feedback.
9679 if ( isset( $uninstall_reason ) ) {
9680 if ( isset( $uninstall_reason->is_anonymous ) && ! $uninstall_reason->is_anonymous ) {
9681 $this->opt_in( false, false, false, false, true );
9682 } else {
9683 $params['uid'] = $this->get_anonymous_id();
9684 $this->get_api_plugin_scope()->call( 'uninstall.json', 'put', $params );
9685 }
9686 }
9687 } else {
9688 $params = array_merge( $params, array(
9689 'is_active' => false,
9690 'is_uninstalled' => true,
9691 ) );
9692
9693 if ( $this->_is_network_active ) {
9694 // Send uninstall event.
9695 $this->send_installs_update( $params );
9696 } else {
9697 // Send uninstall event and handle the result.
9698 $this->sync_install( $params );
9699 }
9700 }
9701
9702 // @todo Decide if we want to delete plugin information from db.
9703 }
9704
9705 /**
9706 * Set the basename of the current product and hook _activate_plugin_event_hook() to the activation action.
9707 *
9708 * @author Vova Feldman (@svovaf)
9709 * @since 2.2.1
9710 *
9711 * @param string $is_premium
9712 * @param string $caller
9713 *
9714 * @return void
9715 */
9716 function set_basename( $is_premium, $caller ) {
9717 $basename = plugin_basename( $caller );
9718
9719 $current_basename = $is_premium ?
9720 $this->_premium_plugin_basename :
9721 $this->_free_plugin_basename;
9722
9723 if ( $current_basename == $basename ) {
9724 // Basename value set correctly.
9725 return;
9726 }
9727
9728 if ( $is_premium ) {
9729 $this->_premium_plugin_basename = $basename;
9730 } else {
9731 $this->_free_plugin_basename = $basename;
9732 }
9733
9734 $plugin_dir = dirname( $this->_plugin_dir_path ) . '/';
9735
9736 register_activation_hook(
9737 $plugin_dir . $basename,
9738 array( &$this, '_activate_plugin_event_hook' )
9739 );
9740 }
9741
9742 /**
9743 * @author Vova Feldman (@svovaf)
9744 * @since 1.1.1
9745 * @since 2.2.1 If the context product is in its premium version, use the current module's basename, even if it was renamed.
9746 *
9747 * @return string
9748 */
9749 function premium_plugin_basename() {
9750 if ( ! isset( $this->_premium_plugin_basename ) ) {
9751 $this->_premium_plugin_basename = $this->is_premium() ?
9752 // The product is premium, so use the current basename.
9753 $this->_plugin_basename :
9754 $this->get_premium_slug() . '/' . basename( $this->_free_plugin_basename );
9755 }
9756
9757 return $this->_premium_plugin_basename;
9758 }
9759
9760 /**
9761 * Uninstall plugin hook. Called only when connected his account with Freemius for active sites tracking.
9762 *
9763 * @author Vova Feldman (@svovaf)
9764 * @since 1.0.2
9765 */
9766 public static function _uninstall_plugin_hook() {
9767 self::_load_required_static();
9768
9769 self::$_static_logger->entrance();
9770
9771 if ( ! current_user_can( 'activate_plugins' ) ) {
9772 return;
9773 }
9774
9775 $plugin_file = substr( current_filter(), strlen( 'uninstall_' ) );
9776
9777 self::$_static_logger->info( 'plugin = ' . $plugin_file );
9778
9779 define( 'WP_FS__UNINSTALL_MODE', true );
9780
9781 $fs = self::get_instance_by_file( $plugin_file );
9782
9783 if ( is_object( $fs ) ) {
9784 $fs->remove_sdk_reference();
9785
9786 self::require_plugin_essentials();
9787
9788 if ( is_plugin_active( $fs->_free_plugin_basename ) ||
9789 is_plugin_active( $fs->premium_plugin_basename() )
9790 ) {
9791 // Deleting Free or Premium plugin version while the other version still installed.
9792 return;
9793 }
9794
9795 if (
9796 ! $fs->is_clone() &&
9797 /**
9798 * 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).
9799 *
9800 * @author Leo Fajardo
9801 */
9802 ( ! is_object( $fs->_site ) || $fs->is_registered() )
9803 ) {
9804 $fs->_uninstall_plugin_event();
9805 }
9806
9807 $fs->do_action( 'after_uninstall' );
9808 }
9809 }
9810
9811 #----------------------------------------------------------------------------------
9812 #region Plugin Information
9813 #----------------------------------------------------------------------------------
9814
9815 /**
9816 * Load WordPress core plugin.php essential module.
9817 *
9818 * @author Vova Feldman (@svovaf)
9819 * @since 1.1.1
9820 */
9821 private static function require_plugin_essentials() {
9822 if ( ! function_exists( 'get_plugins' ) ) {
9823 self::$_static_logger->log( 'Including wp-admin/includes/plugin.php...' );
9824
9825 require_once ABSPATH . 'wp-admin/includes/plugin.php';
9826 }
9827 }
9828
9829 /**
9830 * Load WordPress core pluggable.php module.
9831 *
9832 * @author Vova Feldman (@svovaf)
9833 * @since 1.1.2
9834 */
9835 private static function require_pluggable_essentials() {
9836 if ( ! function_exists( 'wp_get_current_user' ) ) {
9837 require_once ABSPATH . 'wp-includes/pluggable.php';
9838 }
9839 }
9840
9841 /**
9842 * Return plugin data.
9843 *
9844 * @author Vova Feldman (@svovaf)
9845 * @since 1.0.1
9846 *
9847 * @param bool $reparse_plugin_metadata
9848 *
9849 * @return array
9850 */
9851 function get_plugin_data( $reparse_plugin_metadata = false ) {
9852 if ( ! isset( $this->_plugin_data ) || $reparse_plugin_metadata ) {
9853 self::require_plugin_essentials();
9854
9855 if ( $this->is_plugin() ) {
9856 /**
9857 * @author Vova Feldman (@svovaf)
9858 * @since 1.2.0 When using get_plugin_data() do NOT translate plugin data.
9859 *
9860 * @link https://github.com/Freemius/wordpress-sdk/issues/77
9861 */
9862 $plugin_data = get_plugin_data(
9863 $this->_plugin_main_file_path,
9864 false,
9865 false
9866 );
9867 } else {
9868 $theme_data = wp_get_theme();
9869
9870 if ( $this->_plugin_basename !== $theme_data->get_stylesheet() && is_child_theme() ) {
9871 $parent_theme = $theme_data->parent();
9872
9873 if ( ( $parent_theme instanceof WP_Theme ) && $this->_plugin_basename === $parent_theme->get_stylesheet() ) {
9874 $theme_data = $parent_theme;
9875 }
9876 }
9877
9878 $plugin_data = array(
9879 'Name' => $theme_data->get( 'Name' ),
9880 'Version' => $theme_data->get( 'Version' ),
9881 'Author' => $theme_data->get( 'Author' ),
9882 'Description' => $theme_data->get( 'Description' ),
9883 'PluginURI' => $theme_data->get( 'ThemeURI' ),
9884 );
9885 }
9886
9887 $this->_plugin_data = $plugin_data;
9888 }
9889
9890 return $this->_plugin_data;
9891 }
9892
9893 /**
9894 * @author Vova Feldman (@svovaf)
9895 * @since 1.0.1
9896 * @since 1.2.2.5 If slug not set load slug by module ID.
9897 *
9898 * @return string Plugin slug.
9899 */
9900 function get_slug() {
9901 if ( ! isset( $this->_slug ) ) {
9902 $id_slug_type_path_map = self::$_accounts->get_option( 'id_slug_type_path_map', array() );
9903 $this->_slug = $id_slug_type_path_map[ $this->_module_id ]['slug'];
9904 }
9905
9906 return $this->_slug;
9907 }
9908
9909 /**
9910 * @author Leo Fajardo (@leorw)
9911 * @since 2.2.1
9912 *
9913 * @return string
9914 */
9915 function get_premium_slug() {
9916 return ( is_object( $this->_plugin ) && ! empty( $this->_plugin->premium_slug ) ) ?
9917 $this->_plugin->premium_slug :
9918 "{$this->_slug}-premium";
9919 }
9920
9921 /**
9922 * Retrieve the desired folder name for the product.
9923 *
9924 * @author Vova Feldman (@svovaf)
9925 * @since 1.2.1.7
9926 *
9927 * @return string Plugin slug.
9928 */
9929 function get_target_folder_name() {
9930 return $this->can_use_premium_code() ?
9931 $this->_plugin->premium_slug :
9932 $this->_slug;
9933 }
9934
9935 /**
9936 * @author Vova Feldman (@svovaf)
9937 * @since 1.0.1
9938 *
9939 * @return number Plugin ID.
9940 */
9941 function get_id() {
9942 return $this->_plugin->id;
9943 }
9944
9945 /**
9946 * @author Leo Fajardo (@leorw)
9947 * @since 2.2.4
9948 *
9949 * @return number|null Bundle ID.
9950 */
9951 function get_bundle_id() {
9952 return ( isset( $this->_plugin->bundle_id ) && FS_Plugin::is_valid_id( $this->_plugin->bundle_id ) ) ?
9953 $this->_plugin->bundle_id :
9954 null;
9955 }
9956
9957 /**
9958 * @author Vova Feldman (@svovaf)
9959 * @since 2.3.1
9960 *
9961 * @return string|null Bundle public key.
9962 */
9963 function get_bundle_public_key() {
9964 return isset( $this->_plugin->bundle_public_key ) ?
9965 $this->_plugin->bundle_public_key :
9966 null;
9967 }
9968
9969 /**
9970 * Get whether the SDK has been initiated in the context of a Bundle.
9971 *
9972 * This will return true, if `bundle_id` is present in the SDK init parameters.
9973 *
9974 * ```php
9975 * $my_fs = fs_dynamic_init( array(
9976 * // ...
9977 * 'bundle_id' => 'XXXX', // Will return true since we have bundle id.
9978 * 'bundle_public_key' => 'pk_XXXX',
9979 * ) );
9980 * ```
9981 *
9982 * @author Swashata Ghosh (@swashata)
9983 * @since 2.5.0
9984 *
9985 * @return bool True if we are running in bundle context, false otherwise.
9986 */
9987 private function has_bundle_context() {
9988 return ! is_null( $this->get_bundle_id() );
9989 }
9990
9991 /**
9992 * @author Vova Feldman (@svovaf)
9993 * @since 1.2.1.5
9994 *
9995 * @return string Freemius SDK version
9996 */
9997 function get_sdk_version() {
9998 return $this->version;
9999 }
10000
10001 /**
10002 * @author Vova Feldman (@svovaf)
10003 * @since 1.2.1.5
10004 *
10005 * @return number Parent plugin ID (if parent exist).
10006 */
10007 function get_parent_id() {
10008 return $this->is_addon() ?
10009 $this->get_parent_instance()->get_id() :
10010 $this->_plugin->id;
10011 }
10012
10013 /**
10014 * @author Vova Feldman (@svovaf)
10015 * @since 2.3.1
10016 *
10017 * @return string
10018 */
10019 function get_usage_tracking_terms_url() {
10020 return $this->apply_filters(
10021 'usage_tracking_terms_url',
10022 "https://freemius.com/product/opt-in/{$this->_plugin->id}/{$this->_slug}/"
10023 );
10024 }
10025
10026 /**
10027 * @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.
10028 * @since 2.5.8
10029 *
10030 * @return string
10031 */
10032 function get_license_activation_terms_url() {
10033 return $this->apply_filters(
10034 'license_activation_terms_url',
10035 "https://freemius.com/product/license-activation/{$this->_plugin->id}/{$this->_slug}/"
10036 );
10037 }
10038
10039 /**
10040 * @author Vova Feldman (@svovaf)
10041 * @since 2.3.1
10042 *
10043 * @return string
10044 */
10045 function get_eula_url() {
10046 return $this->apply_filters(
10047 'eula_url',
10048 "https://freemius.com/product/{$this->_plugin->id}/{$this->_slug}/legal/eula/"
10049 );
10050 }
10051
10052 /**
10053 * @author Vova Feldman (@svovaf)
10054 * @since 1.0.1
10055 *
10056 * @return string Plugin public key.
10057 */
10058 function get_public_key() {
10059 return $this->_plugin->public_key;
10060 }
10061
10062 /**
10063 * Will be available only on sandbox mode.
10064 *
10065 * @author Vova Feldman (@svovaf)
10066 * @since 1.0.4
10067 *
10068 * @return mixed Plugin secret key.
10069 */
10070 function get_secret_key() {
10071 return $this->_plugin->secret_key;
10072 }
10073
10074 /**
10075 * @author Vova Feldman (@svovaf)
10076 * @since 1.1.1
10077 *
10078 * @return bool
10079 */
10080 function has_secret_key() {
10081 return ! empty( $this->_plugin->secret_key );
10082 }
10083
10084 /**
10085 * @author Vova Feldman (@svovaf)
10086 * @since 1.0.9
10087 *
10088 * @param string|bool $premium_suffix
10089 *
10090 * @return string
10091 */
10092 function get_plugin_name( $premium_suffix = false ) {
10093 $this->_logger->entrance();
10094
10095 /**
10096 * This `if-else` can be squeezed into a single `if` but I intentionally split it for code readability.
10097 *
10098 * @author Vova Feldman
10099 */
10100 if ( ! isset( $this->_plugin_name ) ) {
10101 // Name is not yet set.
10102 $this->set_name( $premium_suffix );
10103 } else if (
10104 ! empty( $premium_suffix ) &&
10105 ( ! is_object( $this->_plugin ) || $this->_plugin->premium_suffix !== $premium_suffix )
10106 ) {
10107 // Name is already set, but there's a change in the premium suffix.
10108 $this->set_name( $premium_suffix );
10109 }
10110
10111 return $this->_plugin_name;
10112 }
10113
10114 /**
10115 * Calculates and stores the product's name. This helper function was created specifically for get_plugin_name() just to make the code clearer.
10116 *
10117 * @author Vova Feldman (@svovaf)
10118 * @since 2.2.1
10119 *
10120 * @param string $premium_suffix
10121 */
10122 private function set_name( $premium_suffix = '' ) {
10123 $plugin_data = $this->get_plugin_data();
10124
10125 // Get name.
10126 $this->_plugin_name = $plugin_data['Name'];
10127
10128 if ( is_string( $premium_suffix ) ) {
10129 $premium_suffix = trim( $premium_suffix );
10130
10131 if ( ! empty( $premium_suffix ) ) {
10132 // Check if plugin name contains " (premium)" or a custom suffix and remove it.
10133 $suffix = ( ' ' . strtolower( $premium_suffix ) );
10134 $suffix_len = strlen( $suffix );
10135
10136 if ( strlen( $plugin_data['Name'] ) > $suffix_len &&
10137 $suffix === substr( strtolower( $plugin_data['Name'] ), - $suffix_len )
10138 ) {
10139 $this->_plugin_name = substr( $plugin_data['Name'], 0, - $suffix_len );
10140 }
10141 }
10142 }
10143
10144 $this->_logger->departure( 'Name = ' . $this->_plugin_name );
10145 }
10146
10147 /**
10148 * @author Vova Feldman (@svovaf)
10149 * @since 1.0.0
10150 *
10151 * @param bool $reparse_plugin_metadata
10152 *
10153 * @return string
10154 */
10155 function get_plugin_version( $reparse_plugin_metadata = false ) {
10156 $this->_logger->entrance();
10157
10158 $plugin_data = $this->get_plugin_data( $reparse_plugin_metadata );
10159
10160 $this->_logger->departure( 'Version = ' . $plugin_data['Version'] );
10161
10162 return $this->apply_filters( 'plugin_version', $plugin_data['Version'] );
10163 }
10164
10165 /**
10166 * @author Vova Feldman (@svovaf)
10167 * @since 1.2.1.7
10168 *
10169 * @return string
10170 */
10171 function get_plugin_title() {
10172 $this->_logger->entrance();
10173
10174 $title = $this->_plugin->title;
10175
10176 return $this->apply_filters( 'plugin_title', $title );
10177 }
10178
10179 /**
10180 * @author Vova Feldman (@svovaf)
10181 * @since 1.2.2.7
10182 *
10183 * @param bool $lowercase
10184 *
10185 * @return string
10186 */
10187 function get_module_label( $lowercase = false ) {
10188 $label = $this->is_addon() ?
10189 $this->get_text_inline( 'Add-On', 'addon' ) :
10190 ( $this->is_plugin() ?
10191 $this->get_text_inline( 'Plugin', 'plugin' ) :
10192 $this->get_text_inline( 'Theme', 'theme' ) );
10193
10194 if ( $lowercase ) {
10195 $label = strtolower( $label );
10196 }
10197
10198 return $label;
10199 }
10200
10201 /**
10202 * @author Vova Feldman (@svovaf)
10203 * @since 1.0.4
10204 *
10205 * @return string
10206 */
10207 function get_plugin_basename() {
10208 if ( ! isset( $this->_plugin_basename ) ) {
10209 if ( $this->is_plugin() ) {
10210 $this->_plugin_basename = plugin_basename( $this->_plugin_main_file_path );
10211 } else {
10212 $this->_plugin_basename = basename( dirname( $this->_plugin_main_file_path ) );
10213 }
10214 }
10215
10216 return $this->_plugin_basename;
10217 }
10218
10219 function get_plugin_folder_name() {
10220 $this->_logger->entrance();
10221
10222 $plugin_folder = $this->_plugin_basename;
10223
10224 while ( '.' !== dirname( $plugin_folder ) ) {
10225 $plugin_folder = dirname( $plugin_folder );
10226 }
10227
10228 $this->_logger->departure( 'Folder Name = ' . $plugin_folder );
10229
10230 return $plugin_folder;
10231 }
10232
10233 #endregion ------------------------------------------------------------------
10234
10235 /* Account
10236 ------------------------------------------------------------------------------------------------------------------*/
10237
10238 /**
10239 * Find plugin's slug by plugin's basename.
10240 *
10241 * @author Vova Feldman (@svovaf)
10242 * @since 1.0.9
10243 *
10244 * @param string $plugin_base_name
10245 *
10246 * @return false|string
10247 */
10248 private static function find_slug_by_basename( $plugin_base_name ) {
10249 $file_slug_map = self::$_accounts->get_option( 'file_slug_map', array() );
10250
10251 if ( ! array( $file_slug_map ) || ! isset( $file_slug_map[ $plugin_base_name ] ) ) {
10252 return false;
10253 }
10254
10255 return $file_slug_map[ $plugin_base_name ];
10256 }
10257
10258 /**
10259 * Store the map between the plugin's basename to the slug.
10260 *
10261 * @author Vova Feldman (@svovaf)
10262 * @since 1.0.9
10263 */
10264 private function store_file_slug_map() {
10265 $file_slug_map = self::$_accounts->get_option( 'file_slug_map', array() );
10266
10267 if ( ! array( $file_slug_map ) ) {
10268 $file_slug_map = array();
10269 }
10270
10271 if ( ! isset( $file_slug_map[ $this->_plugin_basename ] ) ||
10272 $file_slug_map[ $this->_plugin_basename ] !== $this->_slug
10273 ) {
10274 $file_slug_map[ $this->_plugin_basename ] = $this->_slug;
10275 self::$_accounts->set_option( 'file_slug_map', $file_slug_map, true );
10276 }
10277 }
10278
10279 /**
10280 * @return array[number]FS_User
10281 */
10282 static function get_all_users() {
10283 $users = self::maybe_get_entities_account_option( 'users', array() );
10284
10285 if ( ! is_array( $users ) ) {
10286 $users = array();
10287 }
10288
10289 return $users;
10290 }
10291
10292 /**
10293 * @param string $module_type
10294 * @param null|int $blog_id Since 2.0.0
10295 *
10296 * @return array[string]FS_Site
10297 */
10298 public static function get_all_sites(
10299 $module_type = WP_FS__MODULE_TYPE_PLUGIN,
10300 $blog_id = null,
10301 $is_backup = false
10302 ) {
10303 $sites = self::get_account_option(
10304 ( $is_backup ? 'prev_' : '' ) . 'sites',
10305 $module_type,
10306 $blog_id
10307 );
10308
10309 if ( ! is_array( $sites ) ) {
10310 $sites = array();
10311 }
10312
10313 return $sites;
10314 }
10315
10316 /**
10317 * @author Leo Fajardo (@leorw)
10318 *
10319 * @since 1.2.2
10320 *
10321 * @param string $option_name
10322 * @param string $module_type
10323 * @param null|int $network_level_or_blog_id Since 2.0.0
10324 *
10325 * @return mixed
10326 */
10327 public static function get_account_option( $option_name, $module_type = null, $network_level_or_blog_id = null ) {
10328 if ( ! is_null( $module_type ) && WP_FS__MODULE_TYPE_PLUGIN !== $module_type ) {
10329 $option_name = $module_type . '_' . $option_name;
10330 }
10331
10332 return self::maybe_get_entities_account_option( $option_name, array(), $network_level_or_blog_id );
10333 }
10334
10335 /**
10336 * @author Leo Fajardo (@leorw)
10337 *
10338 * @since 1.2.2
10339 *
10340 * @param string $option_name
10341 * @param mixed $option_value
10342 * @param bool $store
10343 * @param null|int $network_level_or_blog_id Since 2.0.0
10344 */
10345 private function set_account_option( $option_name, $option_value, $store, $network_level_or_blog_id = null ) {
10346 self::set_account_option_by_module(
10347 $this->_module_type,
10348 $option_name,
10349 $option_value,
10350 $store,
10351 $network_level_or_blog_id
10352 );
10353 }
10354
10355 /**
10356 * @author Vova Feldman (@svovaf)
10357 *
10358 * @since 1.2.2.7
10359 *
10360 * @param string $module_type
10361 * @param string $option_name
10362 * @param mixed $option_value
10363 * @param bool $store
10364 * @param null|int $network_level_or_blog_id Since 2.0.0
10365 */
10366 private static function set_account_option_by_module(
10367 $module_type,
10368 $option_name,
10369 $option_value,
10370 $store,
10371 $network_level_or_blog_id = null
10372 ) {
10373 if ( WP_FS__MODULE_TYPE_PLUGIN != $module_type ) {
10374 $option_name = $module_type . '_' . $option_name;
10375 }
10376
10377 self::$_accounts->set_option( $option_name, $option_value, $store, $network_level_or_blog_id );
10378 }
10379
10380 /**
10381 * This method can also return non-entity or non-entities collection option like the `user_id_license_ids_map` option.
10382 *
10383 * @author Leo Fajardo (@leorw)
10384 * @since 2.3.1
10385 *
10386 * @param string $option_name
10387 * @param mixed $default
10388 * @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).
10389 *
10390 * @return mixed|FS_Plugin[]|FS_User[]|FS_Site[]|FS_Plugin_License[]|FS_Plugin_Plan[]|FS_Plugin_Tag[]
10391 */
10392 private static function maybe_get_entities_account_option( $option_name, $default = null, $network_level_or_blog_id = null ) {
10393 $option = self::$_accounts->get_option( $option_name, $default, $network_level_or_blog_id );
10394
10395 $class_name = '';
10396
10397 if ( fs_starts_with( $option_name, WP_FS__MODULE_TYPE_THEME . '_' ) ) {
10398 $option_name = str_replace( WP_FS__MODULE_TYPE_THEME . '_', '', $option_name );
10399 }
10400
10401 switch ( $option_name ) {
10402 case 'plugins':
10403 case 'themes':
10404 case 'addons':
10405 $class_name = FS_Plugin::get_class_name();
10406 break;
10407 case 'users':
10408 $class_name = FS_User::get_class_name();
10409 break;
10410 case 'sites':
10411 $class_name = FS_Site::get_class_name();
10412 break;
10413 case 'licenses':
10414 case 'all_licenses':
10415 $class_name = FS_Plugin_License::get_class_name();
10416 break;
10417 case 'plans':
10418 $class_name = FS_Plugin_Plan::get_class_name();
10419 break;
10420 case 'updates':
10421 $class_name = FS_Plugin_Tag::get_class_name();
10422 break;
10423 }
10424
10425 if ( empty( $class_name ) ) {
10426 return $option;
10427 }
10428
10429 return fs_get_entities( $option, $class_name );
10430 }
10431
10432 /**
10433 * @author Vova Feldman (@svovaf)
10434 * @since 1.0.6
10435 *
10436 * @param number|null $module_id
10437 *
10438 * @return FS_Plugin_License[]
10439 */
10440 private static function get_all_licenses( $module_id = null ) {
10441 $licenses = self::get_account_option( 'all_licenses' );
10442
10443 if ( ! is_array( $licenses ) ) {
10444 $licenses = array();
10445 }
10446
10447 if ( is_null( $module_id ) ) {
10448 return $licenses;
10449 }
10450
10451 $licenses = isset( $licenses[ $module_id ] ) ?
10452 $licenses[ $module_id ] :
10453 array();
10454
10455 return $licenses;
10456 }
10457
10458 /**
10459 * @author Leo Fajardo (@leorw)
10460 * @since 2.0.0
10461 *
10462 * @param number $module_id
10463 * @param number|null $user_id
10464 *
10465 * @return array
10466 */
10467 private static function get_user_id_license_ids_map( $module_id, $user_id = null ) {
10468 $all_modules_user_id_license_ids_map = self::get_account_option( 'user_id_license_ids_map' );
10469
10470 if ( ! is_array( $all_modules_user_id_license_ids_map ) ) {
10471 $all_modules_user_id_license_ids_map = array();
10472 }
10473
10474 $user_id_license_ids_map = isset( $all_modules_user_id_license_ids_map[ $module_id ] ) ?
10475 $all_modules_user_id_license_ids_map[ $module_id ] :
10476 array();
10477
10478 if ( FS_User::is_valid_id( $user_id ) ) {
10479 $user_id_license_ids_map = isset( $user_id_license_ids_map[ $user_id ] ) ?
10480 $user_id_license_ids_map[ $user_id ] :
10481 array();
10482 }
10483
10484 return $user_id_license_ids_map;
10485 }
10486
10487 /**
10488 * @author Leo Fajardo (@leorw)
10489 * @since 2.0.0
10490 *
10491 * @param array $new_user_id_license_ids_map
10492 * @param number $module_id
10493 * @param number|null $user_id
10494 */
10495 private static function store_user_id_license_ids_map( $new_user_id_license_ids_map, $module_id, $user_id = null ) {
10496 $all_modules_user_id_license_ids_map = self::get_account_option( 'user_id_license_ids_map' );
10497 if ( ! is_array( $all_modules_user_id_license_ids_map ) ) {
10498 $all_modules_user_id_license_ids_map = array();
10499 }
10500
10501 if ( ! isset( $all_modules_user_id_license_ids_map[ $module_id ] ) ) {
10502 $all_modules_user_id_license_ids_map[ $module_id ] = array();
10503 }
10504
10505 if ( FS_User::is_valid_id( $user_id ) ) {
10506 $all_modules_user_id_license_ids_map[ $module_id ][ $user_id ] = $new_user_id_license_ids_map;
10507 } else {
10508 $all_modules_user_id_license_ids_map[ $module_id ] = $new_user_id_license_ids_map;
10509 }
10510
10511 self::$_accounts->set_option( 'user_id_license_ids_map', $all_modules_user_id_license_ids_map, true );
10512 }
10513
10514 /**
10515 * Get a collection of the user's linked license IDs.
10516 *
10517 * @author Vova Feldman (@svovaf)
10518 * @since 2.0.0
10519 *
10520 * @param number $user_id
10521 *
10522 * @return number[]
10523 */
10524 private function get_user_linked_license_ids( $user_id ) {
10525 return self::get_user_id_license_ids_map( $this->_module_id, $user_id );
10526 }
10527
10528 /**
10529 * Override the user's linked license IDs with a new IDs collection.
10530 *
10531 * @author Vova Feldman (@svovaf)
10532 * @since 2.0.0
10533 *
10534 * @param number $user_id
10535 * @param number[] $license_ids
10536 */
10537 private function set_user_linked_license_ids( $user_id, array $license_ids ) {
10538 self::store_user_id_license_ids_map( $license_ids, $this->_module_id, $user_id );
10539 }
10540
10541 /**
10542 * Link a specified license ID to a given user.
10543 *
10544 * @author Vova Feldman (@svovaf)
10545 * @since 2.0.0
10546 *
10547 * @param number $license_id
10548 * @param number $user_id
10549 */
10550 private function link_license_2_user( $license_id, $user_id ) {
10551 $license_ids = $this->get_user_linked_license_ids( $user_id );
10552
10553 if ( in_array( $license_id, $license_ids ) ) {
10554 // License already linked.
10555 return;
10556 }
10557
10558 $license_ids[] = $license_id;
10559
10560 $this->set_user_linked_license_ids( $user_id, $license_ids );
10561 }
10562
10563 /**
10564 * @param string|bool $module_type
10565 *
10566 * @return FS_Plugin_Plan[]
10567 */
10568 private static function get_all_plans( $module_type = false ) {
10569 $plans = self::get_account_option( 'plans', $module_type );
10570
10571 if ( ! is_array( $plans ) ) {
10572 $plans = array();
10573 }
10574
10575 return $plans;
10576 }
10577
10578 /**
10579 * @author Vova Feldman (@svovaf)
10580 * @since 1.0.4
10581 *
10582 * @return FS_Plugin_Tag[]
10583 */
10584 private static function get_all_updates() {
10585 $updates = self::maybe_get_entities_account_option( 'updates', array() );
10586
10587 if ( ! is_array( $updates ) ) {
10588 $updates = array();
10589 }
10590
10591 return $updates;
10592 }
10593
10594 /**
10595 * @author Vova Feldman (@svovaf)
10596 * @since 1.0.6
10597 *
10598 * @return array<number,FS_Plugin[]>|false
10599 */
10600 public static function get_all_addons() {
10601 $addons = self::maybe_get_entities_account_option( 'addons', array() );
10602
10603 if ( ! is_array( $addons ) ) {
10604 $addons = array();
10605 }
10606
10607 return $addons;
10608 }
10609
10610 /**
10611 * @author Vova Feldman (@svovaf)
10612 * @since 1.0.6
10613 *
10614 * @return number[]|false
10615 */
10616 public static function get_all_account_addons() {
10617 $addons = self::$_accounts->get_option( 'account_addons', array() );
10618
10619 if ( ! is_array( $addons ) ) {
10620 $addons = array();
10621 }
10622
10623 return $addons;
10624 }
10625
10626 /**
10627 * Check if user has connected his account (opted-in).
10628 *
10629 * Note:
10630 * If the user opted-in and opted-out on a later stage,
10631 * this will still return true. If you want to check if the
10632 * user is currently opted-in, use:
10633 * `$fs->is_registered() && $fs->is_tracking_allowed()`
10634 *
10635 * @author Vova Feldman (@svovaf)
10636 * @since 1.0.1
10637 *
10638 * @param bool $ignore_anonymous_state Since 2.5.1
10639 *
10640 * @return bool
10641 */
10642 function is_registered( $ignore_anonymous_state = false ) {
10643 return (
10644 is_object( $this->_user ) &&
10645 (
10646 $this->is_premium() ||
10647 $ignore_anonymous_state ||
10648 ! $this->is_anonymous()
10649 )
10650 );
10651 }
10652
10653 /**
10654 * Returns TRUE if the user opted-in and didn't disconnect (opt-out).
10655 *
10656 * @author Leo Fajardo (@leorw)
10657 * @since 1.2.1.5
10658 *
10659 * @return bool
10660 */
10661 function is_tracking_allowed( $blog_id = null, $install = null ) {
10662 if ( is_null( $install ) ) {
10663 $install = is_null( $blog_id ) ?
10664 $this->_site :
10665 $this->get_install_by_blog_id( $blog_id );
10666 }
10667
10668 return (
10669 is_object( $install ) &&
10670 FS_Permission_Manager::instance( $this )->is_homepage_url_tracking_allowed( $blog_id )
10671 );
10672 }
10673
10674 /**
10675 * Returns TRUE if the user never opted-in or manually opted-out.
10676 *
10677 * @author Vova Feldman (@svovaf)
10678 * @since 1.2.1.5
10679 *
10680 * @param int|null $blog_id
10681 *
10682 * @return bool
10683 */
10684 function is_tracking_prohibited( $blog_id = null ) {
10685 return (
10686 ! $this->is_registered( true ) ||
10687 ! $this->is_tracking_allowed( $blog_id )
10688 );
10689 }
10690
10691 /**
10692 * @author Leo Fajardo (@leorw)
10693 * @since 2.4.0
10694 *
10695 * @return bool
10696 */
10697 function is_bundle_license_auto_activation_enabled() {
10698 return $this->is_addon() ?
10699 ( is_object( $this->_parent ) && $this->_parent->is_bundle_license_auto_activation_enabled() ) :
10700 $this->_is_bundle_license_auto_activation_enabled;
10701 }
10702
10703 /**
10704 * @author Vova Feldman (@svovaf)
10705 * @since 1.0.4
10706 *
10707 * @return FS_Plugin
10708 */
10709 function get_plugin() {
10710 return $this->_plugin;
10711 }
10712
10713 /**
10714 * @author Vova Feldman (@svovaf)
10715 * @since 1.0.3
10716 *
10717 * @return FS_User
10718 */
10719 function get_user() {
10720 return $this->_user;
10721 }
10722
10723 /**
10724 * @author Vova Feldman (@svovaf)
10725 * @since 1.0.3
10726 *
10727 * @return FS_Site
10728 */
10729 function get_site() {
10730 return $this->_site;
10731 }
10732
10733 /**
10734 * @author Daniele Alessandra (@danielealessandra)
10735 * @return FS_Storage
10736 * @since 2.6.2
10737 *
10738 */
10739 public function get_storage() {
10740 return $this->_storage;
10741 }
10742
10743 /**
10744 * @author Leo Fajardo (@leorw)
10745 * @since 2.5.0
10746 */
10747 function store_site( $site ) {
10748 $this->_site = $site;
10749 $this->_store_site( true );
10750 }
10751
10752 /**
10753 * 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).
10754 *
10755 * @author Leo Fajardo (@leorw)
10756 * @since 2.5.0
10757 */
10758 function delete_current_install( $back_up ) {
10759 // Back up and delete the unique ID.
10760 if ( $back_up ) {
10761 self::$_accounts->set_option( 'prev_unique_id', $this->get_anonymous_id() );
10762 }
10763
10764 self::$_accounts->set_option( 'unique_id', null );
10765
10766 if ( $back_up ) {
10767 // 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).
10768 $this->back_up_site();
10769 }
10770
10771 $this->_delete_site();
10772 $this->_site = null;
10773 }
10774
10775 /**
10776 * @author Leo Fajardo (@leorw)
10777 * @since 2.5.0
10778 */
10779 function restore_backup_site() {
10780 self::$_accounts->set_option(
10781 'unique_id',
10782 self::$_accounts->get_option( 'prev_unique_id' )
10783 );
10784
10785 $sites = self::get_all_sites( $this->_module_type, null, true );
10786 $this->store_site( clone $sites[ $this->_slug ] );
10787 }
10788
10789 /**
10790 * Get plugin add-ons.
10791 *
10792 * @author Vova Feldman (@svovaf)
10793 * @since 1.0.6
10794 *
10795 * @since 1.1.7.3 If not yet loaded, fetch data from the API.
10796 *
10797 * @param bool $flush
10798 *
10799 * @return FS_Plugin[]|false
10800 */
10801 function get_addons( $flush = false ) {
10802 $this->_logger->entrance();
10803
10804 if ( ! $this->_has_addons ) {
10805 return false;
10806 }
10807
10808 $addons = $this->sync_addons( $flush );
10809
10810 return ( ! is_array( $addons ) || empty( $addons ) ) ?
10811 false :
10812 $addons;
10813 }
10814
10815 /**
10816 * @author Vova Feldman (@svovaf)
10817 * @since 1.0.6
10818 *
10819 * @return number[]|false
10820 */
10821 function get_account_addons() {
10822 $this->_logger->entrance();
10823
10824 $addons = self::get_all_account_addons();
10825
10826 if ( ! is_array( $addons ) ||
10827 ! isset( $addons[ $this->_plugin->id ] ) ||
10828 ! is_array( $addons[ $this->_plugin->id ] ) ||
10829 0 === count( $addons[ $this->_plugin->id ] )
10830 ) {
10831 return false;
10832 }
10833
10834 return $addons[ $this->_plugin->id ];
10835 }
10836
10837 /**
10838 * Check if user has any
10839 *
10840 * @author Vova Feldman (@svovaf)
10841 * @since 1.1.6
10842 *
10843 * @return bool
10844 */
10845 function has_account_addons() {
10846 $addons = $this->get_account_addons();
10847
10848 return is_array( $addons ) && ( 0 < count( $addons ) );
10849 }
10850
10851
10852 /**
10853 * Get add-on by ID (from local data).
10854 *
10855 * @author Vova Feldman (@svovaf)
10856 * @since 1.0.6
10857 *
10858 * @param number $id
10859 *
10860 * @return FS_Plugin|false
10861 */
10862 function get_addon( $id ) {
10863 $this->_logger->entrance();
10864
10865 $addons = $this->get_addons();
10866
10867 if ( is_array( $addons ) ) {
10868 foreach ( $addons as $addon ) {
10869 if ( $id == $addon->id ) {
10870 return $addon;
10871 }
10872 }
10873 }
10874
10875 return false;
10876 }
10877
10878 /**
10879 * Get add-on by slug (from local data).
10880 *
10881 * @author Vova Feldman (@svovaf)
10882 * @since 1.0.6
10883 *
10884 * @param string $slug
10885 *
10886 * @param bool $flush
10887 *
10888 * @return FS_Plugin|false
10889 */
10890 function get_addon_by_slug( $slug, $flush = false ) {
10891 $this->_logger->entrance();
10892
10893 $addons = $this->get_addons( $flush );
10894
10895 if ( is_array( $addons ) ) {
10896 foreach ( $addons as $addon ) {
10897 if ( $slug === $addon->slug ) {
10898 return $addon;
10899 }
10900 }
10901 }
10902
10903 return false;
10904 }
10905
10906 /**
10907 * @var array<number,object[]> {
10908 * @key number Add-on ID.
10909 * @val object[] The add-on's plans and prices object.
10910 * }
10911 */
10912 private $plans_and_pricing_by_addon_id;
10913
10914 /**
10915 * @author Leo Fajardo (@leorw)
10916 * @since 2.3.0
10917 *
10918 * @return array<number,object[]> {
10919 * @key number Add-on ID.
10920 * @val object[] The add-on's plans and prices object.
10921 * }
10922 */
10923 function _get_addons_plans_and_pricing_map_by_id() {
10924 if ( ! isset( $this->plans_and_pricing_by_addon_id ) ) {
10925 $result = $this->get_api_plugin_scope()->get( $this->add_show_pending( "/addons/pricing.json?type=visible" ) );
10926
10927 $plans_and_pricing_by_addon_id = array();
10928 if ( $this->is_api_result_object( $result, 'addons' ) ) {
10929 foreach ( $result->addons as $addon ) {
10930 $plans_and_pricing_by_addon_id[ $addon->id ] = $addon->plans;
10931 }
10932 }
10933
10934 $this->plans_and_pricing_by_addon_id = $plans_and_pricing_by_addon_id;
10935 }
10936
10937 return $this->plans_and_pricing_by_addon_id;
10938 }
10939
10940 /**
10941 * @author Leo Fajardo (@leorw)
10942 * @since 2.3.0
10943 *
10944 * @param number $addon_id
10945 * @param bool $is_installed
10946 *
10947 * @return array
10948 */
10949 function _get_addon_info( $addon_id, $is_installed ) {
10950 $addon = $this->get_addon( $addon_id );
10951
10952 if ( ! is_object( $addon ) ) {
10953 // Unexpected call.
10954 return array();
10955 }
10956
10957 $slug = $addon->slug;
10958
10959 $addon_storage = FS_Storage::instance( WP_FS__MODULE_TYPE_PLUGIN, $slug );
10960
10961 if ( ! fs_is_network_admin() ) {
10962 // Get blog-level activated installations.
10963 $sites = self::maybe_get_entities_account_option( 'sites', array() );
10964 } else {
10965 $sites = null;
10966
10967 if ( $this->is_addon_activated( $addon_id ) &&
10968 $this->get_addon_instance( $addon_id )->is_network_active()
10969 ) {
10970 if ( FS_Site::is_valid_id( $addon_storage->network_install_blog_id ) ) {
10971 // Get network-level activated installations.
10972 $sites = self::maybe_get_entities_account_option(
10973 'sites',
10974 array(),
10975 $addon_storage->network_install_blog_id
10976 );
10977 }
10978 }
10979 }
10980
10981 $addon_info = array(
10982 'is_connected' => false,
10983 'slug' => $slug,
10984 'title' => $addon->title,
10985 'is_whitelabeled' => $addon_storage->is_whitelabeled
10986 );
10987
10988 if ( ! $is_installed ) {
10989 $plans_and_pricing_by_addon_id = $this->_get_addons_plans_and_pricing_map_by_id();
10990
10991 if ( isset( $plans_and_pricing_by_addon_id[ $addon_id ] ) ) {
10992 $has_paid_plan = false;
10993 $plans = $plans_and_pricing_by_addon_id[ $addon_id ];
10994
10995 if ( is_array( $plans ) && count( $plans ) > 0 ) {
10996 foreach ( $plans as $plan ) {
10997 if ( isset( $plan->pricing ) &&
10998 is_array( $plan->pricing ) &&
10999 count( $plan->pricing ) > 0
11000 ) {
11001 $has_paid_plan = true;
11002 break;
11003 }
11004 }
11005 }
11006
11007 $addon_info['has_paid_plan'] = $has_paid_plan;
11008 }
11009 }
11010
11011 if ( ! is_array( $sites ) || ! isset( $sites[ $slug ] ) ) {
11012 return $addon_info;
11013 }
11014
11015 $site = $sites[ $slug ];
11016
11017 $addon_info['is_connected'] = (
11018 ( $addon->parent_plugin_id == $this->get_id() ) &&
11019 is_object( $site ) &&
11020 FS_Site::is_valid_id( $site->id ) &&
11021 FS_User::is_valid_id( $site->user_id ) &&
11022 FS_Plugin_Plan::is_valid_id( $site->plan_id )
11023 );
11024
11025 if ( $addon_info['is_connected'] && $is_installed ) {
11026 return $addon_info;
11027 }
11028
11029 $addon_info['site'] = $site;
11030
11031 $plugins_data = self::maybe_get_entities_account_option( WP_FS__MODULE_TYPE_PLUGIN . 's', array() );
11032 if ( isset( $plugins_data[ $slug ] ) ) {
11033 $plugin_data = $plugins_data[ $slug ];
11034
11035 $addon_info['version'] = $plugin_data->version;
11036 }
11037
11038 $all_plans = self::maybe_get_entities_account_option( 'plans', array() );
11039 if ( isset( $all_plans[ $slug ] ) ) {
11040 $plans = $all_plans[ $slug ];
11041
11042 foreach ( $plans as $plan ) {
11043 if ( $site->plan_id == Freemius::_decrypt( $plan->id ) ) {
11044 $addon_info['plan_name'] = Freemius::_decrypt( $plan->name );
11045 $addon_info['plan_title'] = Freemius::_decrypt( $plan->title );
11046 break;
11047 }
11048 }
11049 }
11050
11051 $licenses = self::maybe_get_entities_account_option( 'all_licenses', array() );
11052 if ( is_array( $licenses ) && isset( $licenses[ $addon_id ] ) ) {
11053 foreach ( $licenses[ $addon_id ] as $license ) {
11054 if ( $license->id == $site->license_id ) {
11055 $addon_info['license'] = $license;
11056 break;
11057 }
11058 }
11059 }
11060
11061 if ( isset( $addon_info['license'] ) ) {
11062 if ( isset( $addon_storage->subscriptions ) &&
11063 ! empty( $addon_storage->subscriptions )
11064 ) {
11065 $addon_subscriptions = fs_get_entities( $addon_storage->subscriptions, FS_Subscription::get_class_name() );
11066
11067 foreach ( $addon_subscriptions as $subscription ) {
11068 if ( $subscription->license_id == $site->license_id ) {
11069 $addon_info['subscription'] = $subscription;
11070 break;
11071 }
11072 }
11073 }
11074 }
11075
11076 return $addon_info;
11077 }
11078
11079 /**
11080 * @author Vova Feldman (@svovaf)
11081 * @since 2.0.0
11082 *
11083 * @param number $user_id
11084 *
11085 * @return FS_User
11086 */
11087 static function _get_user_by_id( $user_id ) {
11088 self::$_static_logger->entrance( "user_id = {$user_id}" );
11089
11090 $users = self::get_all_users();
11091
11092 if ( is_array( $users ) ) {
11093 if ( isset( $users[ $user_id ] ) &&
11094 $users[ $user_id ] instanceof FS_User &&
11095 $user_id == $users[ $user_id ]->id
11096 ) {
11097 return $users[ $user_id ];
11098 }
11099
11100 // If user wasn't found by the key, iterate over all the users collection.
11101 foreach ( $users as $user ) {
11102 /**
11103 * @var FS_User $user
11104 */
11105 if ( $user_id == $user->id ) {
11106 return $user;
11107 }
11108 }
11109 }
11110
11111 return null;
11112 }
11113
11114 /**
11115 * Checks if a Freemius user_id is associated with a super-admin.
11116 *
11117 * @author Vova Feldman (@svovaf)
11118 * @since 2.0.0
11119 *
11120 * @param number $user_id
11121 *
11122 * @return bool
11123 */
11124 private static function is_super_admin( $user_id ) {
11125 $is_super_admin = false;
11126
11127 $user = self::_get_user_by_id( $user_id );
11128
11129 if ( $user instanceof FS_User && ! empty( $user->email ) ) {
11130 self::require_pluggable_essentials();
11131
11132 $wp_user = get_user_by( 'email', $user->email );
11133
11134 if ( $wp_user instanceof WP_User ) {
11135 $super_admins = get_super_admins();
11136 $is_super_admin = ( is_array( $super_admins ) && in_array( $wp_user->user_login, $super_admins ) );
11137 }
11138 }
11139
11140 return $is_super_admin;
11141 }
11142
11143 #----------------------------------------------------------------------------------
11144 #region Plans & Licensing
11145 #----------------------------------------------------------------------------------
11146
11147 /**
11148 * Check if running premium plugin code.
11149 *
11150 * @author Vova Feldman (@svovaf)
11151 * @since 1.0.5
11152 *
11153 * @return bool
11154 */
11155 function is_premium() {
11156 /**
11157 * `$this->_plugin` will be `false` when `is_activation_mode` calls this method directly from the
11158 * `register_constructor_hooks` method.
11159 *
11160 * @author Leo Fajardo (@leorw)
11161 * @since 2.2.3
11162 */
11163 return is_object( $this->_plugin ) ?
11164 $this->_plugin->is_premium :
11165 false;
11166 }
11167
11168 /**
11169 * Get site's plan ID.
11170 *
11171 * @author Vova Feldman (@svovaf)
11172 * @since 1.0.2
11173 *
11174 * @return number
11175 */
11176 function get_plan_id() {
11177 return $this->_site->plan_id;
11178 }
11179
11180 /**
11181 * Get site's plan title.
11182 *
11183 * @author Vova Feldman (@svovaf)
11184 * @since 1.0.2
11185 *
11186 * @return string
11187 */
11188 function get_plan_title() {
11189 $plan = $this->get_plan();
11190
11191 return is_object( $plan ) ? $plan->title : 'PLAN_TITLE';
11192 }
11193
11194 /**
11195 * Get site's plan name.
11196 *
11197 * @author Vova Feldman (@svovaf)
11198 * @since 2.0.0
11199 *
11200 * @return string
11201 */
11202 function get_plan_name() {
11203 $plan = $this->get_plan();
11204
11205 return is_object( $plan ) ? $plan->name : 'PLAN_NAME';
11206 }
11207
11208 /**
11209 * @author Vova Feldman (@svovaf)
11210 * @since 1.0.9
11211 *
11212 * @return FS_Plugin_Plan|false
11213 */
11214 function get_plan() {
11215 if ( ! is_object( $this->_site ) ) {
11216 return false;
11217 }
11218
11219 return FS_Plugin_Plan::is_valid_id( $this->_site->plan_id ) ?
11220 $this->_get_plan_by_id( $this->_site->plan_id ) :
11221 false;
11222 }
11223
11224 /**
11225 * @author Vova Feldman (@svovaf)
11226 * @since 1.0.3
11227 *
11228 * @return bool
11229 */
11230 function is_trial() {
11231 $this->_logger->entrance();
11232
11233 if ( ! $this->is_registered( true ) || ! is_object( $this->_site ) ) {
11234 return false;
11235 }
11236
11237 return $this->_site->is_trial();
11238 }
11239
11240 /**
11241 * Check if currently in a trial with payment method (credit card or paypal).
11242 *
11243 * @author Vova Feldman (@svovaf)
11244 * @since 1.1.7
11245 *
11246 * @return bool
11247 */
11248 function is_paid_trial() {
11249 $this->_logger->entrance();
11250
11251 if ( ! $this->is_trial() ) {
11252 return false;
11253 }
11254
11255 if ( ! $this->has_active_valid_license() ) {
11256 return false;
11257 }
11258
11259 if ( $this->_site->trial_plan_id != $this->_license->plan_id ) {
11260 return false;
11261 }
11262
11263 /**
11264 * @var FS_Subscription $subscription
11265 */
11266 $subscription = $this->_get_subscription( $this->_license->id );
11267
11268 return ( is_object( $subscription ) && $subscription->is_active() );
11269 }
11270
11271 /**
11272 * Check if trial already utilized.
11273 *
11274 * @since 1.0.9
11275 *
11276 * @return bool
11277 */
11278 function is_trial_utilized() {
11279 $this->_logger->entrance();
11280
11281 if ( ! $this->is_registered() ) {
11282 return false;
11283 }
11284
11285 return $this->_site->is_trial_utilized();
11286 }
11287
11288 /**
11289 * Get trial plan information (if in trial).
11290 *
11291 * @author Vova Feldman (@svovaf)
11292 * @since 1.0.9
11293 *
11294 * @return bool|FS_Plugin_Plan
11295 */
11296 function get_trial_plan() {
11297 $this->_logger->entrance();
11298
11299 if ( ! $this->is_trial() ) {
11300 return false;
11301 }
11302
11303 // Try to load plan from local cache.
11304 $trial_plan = $this->_get_plan_by_id( $this->_site->trial_plan_id );
11305
11306 if ( ! is_object( $trial_plan ) ) {
11307 $trial_plan = $this->_fetch_site_plan( $this->_site->trial_plan_id );
11308
11309 /**
11310 * If managed to fetch the plan, add it to the plans collection.
11311 */
11312 if ( $trial_plan instanceof FS_Plugin_Plan ) {
11313 if ( ! is_array( $this->_plans ) ) {
11314 $this->_plans = array();
11315 }
11316
11317 $this->_plans[] = $trial_plan;
11318 $this->_store_plans();
11319 }
11320 }
11321
11322 if ( $trial_plan instanceof FS_Plugin_Plan ) {
11323 return $trial_plan;
11324 }
11325
11326 /**
11327 * If for some reason failed to get the trial plan, fallback to a dummy name and title.
11328 */
11329 $trial_plan = new FS_Plugin_Plan();
11330 $trial_plan->id = $this->_site->trial_plan_id;
11331 $trial_plan->name = 'pro';
11332 $trial_plan->title = 'Pro';
11333
11334 return $trial_plan;
11335 }
11336
11337 /**
11338 * Check if the user has an activate, non-expired license on current plugin's install.
11339 *
11340 * @since 1.0.9
11341 *
11342 * @return bool
11343 */
11344 function is_paying() {
11345 $this->_logger->entrance();
11346
11347 if ( ! $this->is_registered( true ) ) {
11348 return false;
11349 }
11350
11351 if ( ! $this->has_paid_plan() ) {
11352 return false;
11353 }
11354
11355 return (
11356 ! $this->is_trial() &&
11357 'free' !== $this->get_plan_name() &&
11358 $this->has_active_valid_license()
11359 );
11360 }
11361
11362 /**
11363 * @author Vova Feldman (@svovaf)
11364 * @since 1.0.4
11365 *
11366 * @return bool
11367 */
11368 function is_free_plan() {
11369 if ( ! $this->is_registered() ) {
11370 return true;
11371 }
11372
11373 if ( ! $this->has_paid_plan() ) {
11374 return true;
11375 }
11376
11377 return (
11378 'free' === $this->get_plan_name() ||
11379 ! $this->has_features_enabled_license()
11380 );
11381 }
11382
11383 /**
11384 * @author Vova Feldman (@svovaf)
11385 * @since 1.0.5
11386 *
11387 * @return bool
11388 */
11389 function _has_premium_license() {
11390 $this->_logger->entrance();
11391
11392 $premium_license = $this->_get_available_premium_license();
11393
11394 return ( false !== $premium_license );
11395 }
11396
11397 /**
11398 * Check if user has any licenses associated with the plugin (including expired or blocking).
11399 *
11400 * @author Vova Feldman (@svovaf)
11401 * @since 1.1.7.3
11402 *
11403 * @param bool $including_foreign
11404 *
11405 * @return bool
11406 */
11407 function has_any_license( $including_foreign = true ) {
11408 if ( ! is_array( $this->_licenses ) || 0 === count( $this->_licenses ) ) {
11409 return false;
11410 }
11411
11412 if ( $including_foreign ) {
11413 return true;
11414 }
11415
11416 foreach ( $this->_licenses as $license ) {
11417 if ( $this->_user->id == $license->user_id ) {
11418 return true;
11419 }
11420 }
11421
11422 return false;
11423 }
11424
11425 /**
11426 * @author Vova Feldman (@svovaf)
11427 * @since 1.0.5
11428 *
11429 * @param bool|null $is_localhost
11430 *
11431 * @return FS_Plugin_License|false
11432 */
11433 function _get_available_premium_license( $is_localhost = null ) {
11434 $this->_logger->entrance();
11435
11436 $licenses = $this->get_available_premium_licenses( $is_localhost );
11437 if ( ! empty( $licenses ) ) {
11438 return $licenses[0];
11439 }
11440
11441 return false;
11442 }
11443
11444 /**
11445 * @author Vova Feldman (@svovaf)
11446 * @since 1.0.5
11447 *
11448 * @param bool|null $is_localhost
11449 *
11450 * @return FS_Plugin_License[]
11451 */
11452 function get_available_premium_licenses( $is_localhost = null ) {
11453 $this->_logger->entrance();
11454
11455 $licenses = array();
11456 if ( ! $this->has_paid_plan() ) {
11457 return $licenses;
11458 }
11459
11460 if ( is_array( $this->_licenses ) ) {
11461 foreach ( $this->_licenses as $license ) {
11462 if ( ! $license->can_activate( $is_localhost ) ) {
11463 continue;
11464 }
11465
11466 $licenses[] = $license;
11467 }
11468 }
11469
11470 return $licenses;
11471 }
11472
11473 /**
11474 * Sync local plugin plans with remote server.
11475 *
11476 * 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).
11477 *
11478 * @author Vova Feldman (@svovaf)
11479 * @since 1.0.5
11480 *
11481 * @return FS_Plugin_Plan[]|object
11482 */
11483 function _sync_plans() {
11484 $plans = $this->_fetch_plugin_plans();
11485
11486 if ( $this->is_array_instanceof( $plans, 'FS_Plugin_Plan' ) ) {
11487 $plans_map = array();
11488 foreach ( $plans as $plan ) {
11489 $plans_map[ $plan->id ] = true;
11490 }
11491
11492 $plans_ids_to_keep = $this->get_plans_ids_associated_with_installs();
11493
11494 foreach ( $plans_ids_to_keep as $plan_id ) {
11495 if ( isset( $plans_map[ $plan_id ] ) ) {
11496 continue;
11497 }
11498
11499 $missing_plan = self::_get_plan_by_id( $plan_id );
11500
11501 if ( is_object( $missing_plan ) ) {
11502 $plans[] = $missing_plan;
11503 }
11504 }
11505
11506 $this->_plans = $plans;
11507 $this->_store_plans();
11508 }
11509
11510 $this->do_action( 'after_plans_sync', $plans );
11511
11512 return $this->_plans;
11513 }
11514
11515 /**
11516 * Check if specified plan exists locally. If not, fetch it and store it.
11517 *
11518 * @author Vova Feldman (@svovaf)
11519 * @since 2.0.0
11520 *
11521 * @param number $plan_id
11522 *
11523 * @return \FS_Plugin_Plan|object The plan entity or the API error object on failure.
11524 */
11525 private function sync_plan_if_not_exist( $plan_id ) {
11526 $plan = self::_get_plan_by_id( $plan_id );
11527
11528 if ( is_object( $plan ) ) {
11529 // Plan already exists.
11530 return $plan;
11531 }
11532
11533 $plan = $this->fetch_plan_by_id( $plan_id );
11534
11535 if ( $plan instanceof FS_Plugin_Plan ) {
11536 $this->_plans[] = $plan;
11537 $this->_store_plans();
11538
11539 return $plan;
11540 }
11541
11542 return $plan;
11543 }
11544
11545 /**
11546 * Check if specified license exists locally. If not, fetch it and store it.
11547 *
11548 * @author Vova Feldman (@svovaf)
11549 * @since 2.0.0
11550 *
11551 * @param number $license_id
11552 * @param string $license_key
11553 *
11554 * @return \FS_Plugin_Plan|object The plan entity or the API error object on failure.
11555 */
11556 private function sync_license_if_not_exist( $license_id, $license_key ) {
11557 $license = $this->_get_license_by_id( $license_id );
11558
11559 if ( is_object( $license ) ) {
11560 // License already exists.
11561 return $license;
11562 }
11563
11564 $license = $this->fetch_license_by_key( $license_id, $license_key );
11565
11566 if ( $license instanceof FS_Plugin_License ) {
11567 $this->_licenses[] = $license;
11568
11569 $this->set_license( $license );
11570
11571 $this->_store_licenses();
11572
11573 return $license;
11574 }
11575
11576 return $license;
11577 }
11578
11579 /**
11580 * Get a collection of unique plan IDs that are associated with any installs in the network.
11581 *
11582 * @author Leo Fajardo (@leorw)
11583 * @since 2.0.0
11584 *
11585 * @return number[]
11586 */
11587 private function get_plans_ids_associated_with_installs() {
11588 if ( ! is_multisite() ) {
11589 if ( ! is_object( $this->_site ) ||
11590 ! FS_Plugin_Plan::is_valid_id( $this->_site->plan_id )
11591 ) {
11592 return array();
11593 }
11594
11595 return array( $this->_site->plan_id );
11596 }
11597
11598 $plan_ids = array();
11599 $sites = self::get_sites();
11600 foreach ( $sites as $site ) {
11601 $blog_id = self::get_site_blog_id( $site );
11602 $install = $this->get_install_by_blog_id( $blog_id );
11603
11604 if ( ! is_object( $install ) ||
11605 ! FS_Plugin_Plan::is_valid_id( $install->plan_id )
11606 ) {
11607 continue;
11608 }
11609
11610 $plan_ids[ $install->plan_id ] = true;
11611 }
11612
11613 return array_keys( $plan_ids );
11614 }
11615
11616 /**
11617 * Get a collection of unique license IDs that are associated with any installs in the network.
11618 *
11619 * @author Leo Fajardo (@leorw)
11620 * @since 2.0.0
11621 *
11622 * @return number[]
11623 */
11624 private function get_license_ids_associated_with_installs() {
11625 if ( ! $this->_is_network_active ) {
11626 if ( ! is_object( $this->_site ) ||
11627 ! FS_Plugin_License::is_valid_id( $this->_site->license_id )
11628 ) {
11629 return array();
11630 }
11631
11632 return array( $this->_site->license_id );
11633 }
11634
11635 $license_ids = array();
11636 $sites = self::get_sites();
11637 foreach ( $sites as $site ) {
11638 $blog_id = self::get_site_blog_id( $site );
11639 $install = $this->get_install_by_blog_id( $blog_id );
11640
11641 if ( ! is_object( $install ) ||
11642 ! FS_Plugin_License::is_valid_id( $install->license_id )
11643 ) {
11644 continue;
11645 }
11646
11647 $license_ids[ $install->license_id ] = true;
11648 }
11649
11650 return array_keys( $license_ids );
11651 }
11652
11653 /**
11654 * @author Vova Feldman (@svovaf)
11655 * @since 1.0.5
11656 *
11657 * @param number $id
11658 *
11659 * @return FS_Plugin_Plan|false
11660 */
11661 function _get_plan_by_id( $id ) {
11662 $this->_logger->entrance();
11663
11664 if ( ! is_array( $this->_plans ) || 0 === count( $this->_plans ) ) {
11665 $this->_sync_plans();
11666 }
11667
11668 foreach ( $this->_plans as $plan ) {
11669 if ( $id == $plan->id ) {
11670 return $plan;
11671 }
11672 }
11673
11674 return false;
11675 }
11676
11677 /**
11678 * @author Vova Feldman (@svovaf)
11679 * @since 1.1.8.1
11680 *
11681 * @param string $name
11682 *
11683 * @return FS_Plugin_Plan|false
11684 */
11685 private function get_plan_by_name( $name ) {
11686 $this->_logger->entrance();
11687
11688 if ( ! is_array( $this->_plans ) || 0 === count( $this->_plans ) ) {
11689 $this->_sync_plans();
11690 }
11691
11692 foreach ( $this->_plans as $plan ) {
11693 if ( $name == $plan->name ) {
11694 return $plan;
11695 }
11696 }
11697
11698 return false;
11699 }
11700
11701 /**
11702 * Sync local licenses with remote server.
11703 *
11704 * @author Vova Feldman (@svovaf)
11705 * @since 1.0.6
11706 *
11707 * @param number|bool $site_license_id
11708 * @param number|null $blog_id
11709 *
11710 * @return FS_Plugin_License[]|object
11711 */
11712 function _sync_licenses( $site_license_id = false, $blog_id = null ) {
11713 $this->_logger->entrance();
11714
11715 $is_network_admin = fs_is_network_admin();
11716
11717 if ( $is_network_admin && is_null( $blog_id ) ) {
11718 $all_licenses = self::get_all_licenses( $this->_module_id );
11719 } else {
11720 $all_licenses = $this->get_user_licenses( $this->_user->id );
11721 }
11722
11723 $foreign_licenses = $this->get_foreign_licenses_info( $all_licenses, $site_license_id );
11724
11725 $all_licenses_map = array();
11726 foreach ( $all_licenses as $license ) {
11727 $all_licenses_map[ $license->id ] = true;
11728 }
11729
11730 $licenses = $this->_fetch_licenses( false, $site_license_id, $foreign_licenses, $blog_id );
11731
11732 if ( $this->is_array_instanceof( $licenses, 'FS_Plugin_License' ) ) {
11733 $licenses_map = array();
11734 foreach ( $licenses as $license ) {
11735 $licenses_map[ $license->id ] = true;
11736 }
11737
11738 // $license_ids_to_keep = $this->get_license_ids_associated_with_installs();
11739 // foreach ( $license_ids_to_keep as $license_id ) {
11740 // if ( isset( $licenses_map[ $license_id ] ) ) {
11741 // continue;
11742 // }
11743 //
11744 // $missing_license = self::_get_license_by_id( $license_id, false );
11745 // if ( is_object( $missing_license ) ) {
11746 // $licenses[] = $missing_license;
11747 // $licenses_map[ $missing_license->id ] = true;
11748 // }
11749 // }
11750
11751 $user_license_ids = $this->get_user_linked_license_ids( $this->_user->id );
11752
11753 foreach ( $user_license_ids as $key => $license_id ) {
11754 if ( ! isset( $licenses_map[ $license_id ] ) ) {
11755 // Remove access to licenses that no longer exist.
11756 unset( $user_license_ids[ $key ] );
11757 }
11758 }
11759
11760 if ( ! empty( $user_license_ids ) ) {
11761 foreach ( $licenses_map as $license_id => $value ) {
11762 if ( ! isset( $all_licenses_map[ $license_id ] ) ) {
11763 // Associate new licenses with the user who triggered the license syncing.
11764 $user_license_ids[] = $license_id;
11765 }
11766 }
11767
11768 $user_license_ids = array_unique( $user_license_ids );
11769 } else {
11770 $user_license_ids = array_keys( $licenses_map );
11771 }
11772
11773 if ( ! $is_network_admin || ! is_null( $blog_id ) ) {
11774 $user_licenses = array();
11775 foreach ( $licenses as $license ) {
11776 if ( ! in_array( $license->id, $user_license_ids ) ) {
11777 continue;
11778 }
11779
11780 $user_licenses[] = $license;
11781 }
11782
11783 $this->_licenses = $user_licenses;
11784 } else {
11785 $this->_licenses = $licenses;
11786 }
11787
11788 $this->set_user_linked_license_ids( $this->_user->id, $user_license_ids );
11789
11790 $this->_store_licenses( true, $this->_module_id, $licenses );
11791 }
11792
11793 // Update current license.
11794 if ( is_object( $this->_license ) ) {
11795 $license = $this->_get_license_by_id( $this->_license->id );
11796
11797 if ( is_object( $license ) ) {
11798 /**
11799 * `$license` can be `false` in case a user change action has just been completed and this method
11800 * has synced the `$this->_licenses` collection for the new user. In this case, the
11801 * `$this->_licenses` collection may have only the newly activated license that is associated with
11802 * the new user. `set_license` will eventually be called in the same request by the logic that
11803 * follows outside this method which will detect that the install's license has been updated, and
11804 * then `_update_site_license` will be called which in turn will call `set_license`.
11805 *
11806 * @author Leo Fajardo (@leorw)
11807 * @since 2.3.2
11808 */
11809 $this->set_license( $license );
11810 }
11811 }
11812
11813 return $this->_licenses;
11814 }
11815
11816 /**
11817 * @author Vova Feldman (@svovaf)
11818 * @since 1.0.5
11819 *
11820 * @param number $id
11821 * @param bool $sync_licenses
11822 *
11823 * @return FS_Plugin_License|false
11824 */
11825 function _get_license_by_id( $id, $sync_licenses = true ) {
11826 $this->_logger->entrance();
11827
11828 if ( ! FS_Plugin_License::is_valid_id( $id ) ) {
11829 return false;
11830 }
11831
11832 /**
11833 * When running from the network level admin and opted-in from the network,
11834 * check if the license exists in the network user licenses collection.
11835 *
11836 * @author Vova Feldman (@svovaf)
11837 * @since 2.0.0
11838 */
11839 if ( fs_is_network_admin() &&
11840 $this->is_network_registered() &&
11841 ( ! is_object( $this->_user ) || $this->_storage->network_user_id != $this->_user->id )
11842 ) {
11843 $licenses = $this->get_user_licenses( $this->_storage->network_user_id );
11844
11845 foreach ( $licenses as $license ) {
11846 if ( $id == $license->id ) {
11847 return $license;
11848 }
11849 }
11850 }
11851
11852 if ( ! $this->has_any_license() && $sync_licenses ) {
11853 $this->_sync_licenses( $id );
11854 }
11855
11856 if ( is_array( $this->_licenses ) ) {
11857 foreach ( $this->_licenses as $license ) {
11858 if ( $id == $license->id ) {
11859 return $license;
11860 }
11861 }
11862 }
11863
11864 return false;
11865 }
11866
11867 /**
11868 * 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.
11869 *
11870 * @author Vova Feldman (@svovaf)
11871 * @since 2.0.0
11872 *
11873 * @param number $id
11874 *
11875 * @return FS_Plugin_License
11876 */
11877 private function get_license_by_id( $id ) {
11878 $licenses = self::get_all_licenses( $this->_module_id );
11879
11880 if ( is_array( $licenses ) && ! empty( $licenses ) ) {
11881 foreach ( $licenses as $license ) {
11882 if ( $id == $license->id ) {
11883 return $license;
11884 }
11885 }
11886 }
11887
11888 return null;
11889 }
11890
11891 /**
11892 * Synchronize the site's context license by fetching the license form the API and updating the local data with it.
11893 *
11894 * @author Vova Feldman (@svovaf)
11895 * @since 2.0.0
11896 *
11897 * @return \FS_Plugin_License|mixed
11898 */
11899 private function sync_site_license() {
11900 $api = $this->get_api_user_scope();
11901
11902 $result = $api->get( "/licenses/{$this->_license->id}.json?license_key=" . urlencode( $this->_license->secret_key ), true );
11903
11904 if ( ! $this->is_api_result_entity( $result ) ) {
11905 return $result;
11906 }
11907
11908 $license = $this->_update_site_license( new FS_Plugin_License( $result ) );
11909 $this->_store_licenses();
11910
11911 return $license;
11912 }
11913
11914 /**
11915 * Get all user's available licenses for the current module.
11916 *
11917 * @author Vova Feldman (@svovaf)
11918 * @since 2.0.0
11919 *
11920 * @param number $user_id
11921 *
11922 * @return FS_Plugin_License[]
11923 */
11924 private function get_user_licenses( $user_id ) {
11925 $all_licenses = self::get_all_licenses( $this->_module_id );
11926 if ( empty( $all_licenses ) ) {
11927 return array();
11928 }
11929
11930 $user_license_ids = $this->get_user_linked_license_ids( $user_id );
11931 if ( empty( $user_license_ids ) ) {
11932 return array();
11933 }
11934
11935 $licenses = array();
11936 foreach ( $all_licenses as $license ) {
11937 if ( in_array( $license->id, $user_license_ids ) ) {
11938 $licenses[] = $license;
11939 }
11940 }
11941
11942 return $licenses;
11943 }
11944
11945 /**
11946 * Checks if the context license is network activated except on the given blog ID.
11947 *
11948 * @author Vova Feldman (@svovaf)
11949 * @since 2.0.0
11950 *
11951 * @param int $except_blog_id
11952 *
11953 * @return bool
11954 */
11955 private function is_license_network_active( $except_blog_id = 0 ) {
11956 $this->_logger->entrance();
11957
11958 if ( ! is_object( $this->_license ) ) {
11959 return false;
11960 }
11961
11962 $sites = self::get_sites();
11963
11964 if ( $this->_license->total_activations() < ( count( $sites ) - 1 ) ) {
11965 // There are more sites than the number of activations, so license cannot be network activated.
11966 return false;
11967 }
11968
11969 foreach ( $sites as $site ) {
11970 $blog_id = self::get_site_blog_id( $site );
11971
11972 if ( $except_blog_id == $blog_id ) {
11973 // Skip excluded blog.
11974 continue;
11975 }
11976
11977 $install = $this->get_install_by_blog_id( $blog_id );
11978
11979 if ( is_object( $install ) && $install->license_id != $this->_license->id ) {
11980 return false;
11981 }
11982 }
11983
11984 return true;
11985 }
11986
11987 /**
11988 * 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.
11989 *
11990 * Notice: On success, this method will also update the license activations counters (without updating the license in the storage).
11991 *
11992 * @author Vova Feldman (@svovaf)
11993 * @since 2.0.0
11994 *
11995 * @param \FS_User $user
11996 * @param \FS_Plugin_License $license
11997 *
11998 * @return bool
11999 */
12000 private function try_activate_license_on_network( FS_User $user, FS_Plugin_License $license ) {
12001 $this->_logger->entrance();
12002
12003 $result = $this->can_activate_license_on_network( $license );
12004
12005 if ( false === $result ) {
12006 return false;
12007 }
12008
12009 $installs_without_license = $result['installs'];
12010 if ( ! empty( $installs_without_license ) ) {
12011 $this->activate_license_on_many_installs( $user, $license->secret_key, $installs_without_license );
12012 }
12013
12014 $disconnected_site_ids = $result['sites'];
12015 if ( ! empty( $disconnected_site_ids ) ) {
12016 $this->activate_license_on_many_sites( $user, $license->secret_key, $disconnected_site_ids );
12017 }
12018
12019 $this->link_license_2_user( $license->id, $user->id );
12020
12021 // Sync license after activations.
12022 $license->activated += $result['production_count'];
12023 $license->activated_local += $result['localhost_count'];
12024
12025 // $this->_store_licenses()
12026
12027 return true;
12028 }
12029
12030 /**
12031 * Checks if the given license can be activated on the whole network.
12032 *
12033 * @author Vova Feldman (@svovaf)
12034 * @since 2.0.0
12035 *
12036 * @param \FS_Plugin_License $license
12037 *
12038 * @return false|array {
12039 * @type array[int]FS_Site $installs Blog ID to install map.
12040 * @type int[] $sites Non-connected blog IDs.
12041 * @type int $production_count Production sites count.
12042 * @type int $localhost_count Production sites count.
12043 * }
12044 */
12045 private function can_activate_license_on_network( FS_Plugin_License $license ) {
12046 $sites = self::get_sites();
12047
12048 $production_count = 0;
12049 $localhost_count = 0;
12050
12051 $installs_without_license = array();
12052 $disconnected_site_ids = array();
12053
12054 foreach ( $sites as $site ) {
12055 $blog_id = self::get_site_blog_id( $site );
12056 $install = $this->get_install_by_blog_id( $blog_id );
12057
12058 if ( is_object( $install ) ) {
12059 if ( FS_Plugin_License::is_valid_id( $install->license_id ) ) {
12060 // License already activated on the install.
12061 continue;
12062 }
12063
12064 $url = $install->url;
12065
12066 $installs_without_license[ $blog_id ] = $install;
12067 } else {
12068 $url = is_object( $site ) ?
12069 $site->siteurl :
12070 self::get_unfiltered_site_url( $blog_id );
12071
12072 $disconnected_site_ids[] = $blog_id;
12073 }
12074
12075 if ( FS_Site::is_localhost_by_address( $url ) ) {
12076 $localhost_count ++;
12077 } else {
12078 $production_count ++;
12079 }
12080 }
12081
12082 if ( ! $license->can_activate_bulk( $production_count, $localhost_count ) ) {
12083 return false;
12084 }
12085
12086 return array(
12087 'installs' => $installs_without_license,
12088 'sites' => $disconnected_site_ids,
12089 'production_count' => $production_count,
12090 'localhost_count' => $localhost_count,
12091 );
12092 }
12093
12094 /**
12095 * Activate a given license on a collection of installs.
12096 *
12097 * @author Vova Feldman (@svovaf)
12098 * @since 2.0.0
12099 *
12100 * @param \FS_User $user
12101 * @param string $license_key
12102 * @param array $blog_2_install_map {
12103 * @key int Blog ID.
12104 * @value FS_Site Blog's associated install.
12105 * }
12106 *
12107 * @return mixed|true
12108 */
12109 private function activate_license_on_many_installs(
12110 FS_User $user,
12111 $license_key,
12112 array $blog_2_install_map
12113 ) {
12114 $params = array(
12115 array( 'license_key' => $this->apply_filters( 'license_key', $license_key ) )
12116 );
12117
12118 $install_2_blog_map = array();
12119 foreach ( $blog_2_install_map as $blog_id => $install ) {
12120 $params[] = array( 'id' => $install->id, 'url' => $install->url );
12121
12122 $install_2_blog_map[ $install->id ] = $blog_id;
12123 }
12124
12125 $result = $this->get_api_user_scope_by_user( $user )->call(
12126 "plugins/{$this->_plugin->id}/installs.json",
12127 'PUT',
12128 $params
12129 );
12130
12131 if ( ! $this->is_api_result_object( $result, 'installs' ) ) {
12132 return $result;
12133 }
12134
12135 foreach ( $result->installs as $r_install ) {
12136 $install = new FS_Site( $r_install );
12137 $install->is_disconnected = false;
12138
12139 // Update install.
12140 $this->_store_site(
12141 true,
12142 $install_2_blog_map[ $r_install->id ],
12143 $install
12144 );
12145 }
12146
12147 return true;
12148 }
12149
12150 /**
12151 * Activate a given license on a collection of blogs/sites that are not yet opted-in.
12152 *
12153 * @author Vova Feldman (@svovaf)
12154 * @since 2.3.1
12155 *
12156 * @param \FS_User $user
12157 * @param string $license_key
12158 *
12159 * @return true|mixed True if successful, otherwise, the API result.
12160 */
12161 private function activate_license_on_site( FS_User $user, $license_key ) {
12162 return $this->activate_license_on_many_sites( $user, $license_key );
12163 }
12164
12165 /**
12166 * Activate a given license on a collection of blogs/sites that are not yet opted-in.
12167 *
12168 * @author Vova Feldman (@svovaf)
12169 * @since 2.0.0
12170 *
12171 * @param \FS_User $user
12172 * @param string $license_key
12173 * @param int[] $site_ids
12174 *
12175 * @return true|mixed True if successful, otherwise, the API result.
12176 */
12177 private function activate_license_on_many_sites(
12178 FS_User $user,
12179 $license_key,
12180 array $site_ids = array()
12181 ) {
12182 $sites = array();
12183 foreach ( $site_ids as $site_id ) {
12184 $sites[] = $this->get_site_info( array( 'blog_id' => $site_id ) );
12185 }
12186
12187 // Install the plugin.
12188 $result = $this->create_installs_with_user(
12189 $user,
12190 $license_key,
12191 false,
12192 $sites,
12193 false,
12194 true
12195 );
12196
12197 if ( ! $this->is_api_result_entity( $result ) &&
12198 ! $this->is_api_result_object( $result, 'installs' )
12199 ) {
12200 return $result;
12201 }
12202
12203 $installs = array();
12204
12205 if ( $this->is_api_result_entity( $result ) ) {
12206 $install = new FS_Site( $result );
12207
12208 $this->_user = $user;
12209
12210 $this->_store_site( true, null, $install );
12211
12212 $this->_site = $install;
12213
12214 $this->reset_anonymous_mode();
12215 } else {
12216 foreach ( $result->installs as $install ) {
12217 $installs[] = new FS_Site( $install );
12218 }
12219
12220 // Map site addresses to their blog IDs.
12221 $address_to_blog_map = $this->get_address_to_blog_map();
12222
12223 $first_blog_id = null;
12224
12225 foreach ( $installs as $install ) {
12226 $address = trailingslashit( fs_strip_url_protocol( $install->url ) );
12227 $blog_id = $address_to_blog_map[ $address ];
12228
12229 $this->_store_site( true, $blog_id, $install );
12230
12231 $this->reset_anonymous_mode( $blog_id );
12232
12233 if ( is_null( $first_blog_id ) ) {
12234 $first_blog_id = $blog_id;
12235 }
12236 }
12237
12238 if ( ! FS_Site::is_valid_id( $this->_storage->network_install_blog_id ) ) {
12239 $this->_storage->network_install_blog_id = $first_blog_id;
12240 }
12241 }
12242
12243 return true;
12244 }
12245
12246 /**
12247 * Sync site's license with user licenses.
12248 *
12249 * @author Vova Feldman (@svovaf)
12250 * @since 1.0.6
12251 *
12252 * @param FS_Plugin_License|null $new_license
12253 *
12254 * @return FS_Plugin_License|null
12255 */
12256 function _update_site_license( $new_license ) {
12257 $this->_logger->entrance();
12258
12259 /**
12260 * In case this call will be removed in the future, the `_sync_licenses()` method needs to be updated
12261 * accordingly so that it will also handle the case when an ownership change is done via license
12262 * activation.
12263 *
12264 * @author Leo Fajardo (@leorw)
12265 * @since 2.3.2
12266 */
12267 $this->set_license( $new_license );
12268
12269 if ( ! is_object( $new_license ) ) {
12270 $this->_site->license_id = null;
12271 $this->_sync_site_subscription( null );
12272
12273 return $this->_license;
12274 }
12275
12276 $this->_site->license_id = $this->_license->id;
12277
12278 if ( ! is_array( $this->_licenses ) ) {
12279 $this->_licenses = array();
12280 }
12281
12282 $is_license_found = false;
12283 for ( $i = 0, $len = count( $this->_licenses ); $i < $len; $i ++ ) {
12284 if ( $new_license->id == $this->_licenses[ $i ]->id ) {
12285 $this->_licenses[ $i ] = $new_license;
12286
12287 $is_license_found = true;
12288 break;
12289 }
12290 }
12291
12292 // If new license just append.
12293 if ( ! $is_license_found ) {
12294 $this->_licenses[] = $new_license;
12295 }
12296
12297 $this->_sync_site_subscription( $new_license );
12298
12299 return $this->_license;
12300 }
12301
12302 /**
12303 * @author Vova Feldman (@svovaf)
12304 * @since 2.3.1
12305 *
12306 * @param \FS_Plugin_License $license
12307 */
12308 private function set_license( FS_Plugin_License $license = null ) {
12309 $this->_license = $license;
12310
12311 $this->maybe_update_whitelabel_flag( $license );
12312 }
12313
12314 /**
12315 * @author Leo Fajardo (@leorw)
12316 * @since 2.3.1
12317 *
12318 * @param FS_Plugin_License $license
12319 */
12320 private function maybe_update_whitelabel_flag( $license ) {
12321 $is_whitelabeled = isset( $this->_storage->is_whitelabeled ) ?
12322 $this->_storage->is_whitelabeled :
12323 false;
12324
12325 if ( is_object( $license ) ) {
12326 $license_user = self::_get_user_by_id( $license->user_id );
12327
12328 if ( ! is_object( $license_user ) ) {
12329 // If foreign license, do not update the `is_whitelabeled` flag.
12330 return;
12331 }
12332
12333 if ( $this->is_addon() ) {
12334 /**
12335 * Store the last license data to the parent's storage since it's needed only when showing the
12336 * "Start Debug" dialog which is triggered from the "Account" page. This way, there's no need to
12337 * iterate over the add-ons just to get the last license data.
12338 */
12339 $this->get_parent_instance()->store_last_activated_license_data( $license, $license_user );
12340 } else {
12341 $this->store_last_activated_license_data( $license );
12342 }
12343
12344 if ( $license->is_whitelabeled ) {
12345 // Activated a developer license, data should be hidden.
12346 $is_whitelabeled = true;
12347 } else if ( $this->is_registered() && $this->_user->id == $license->user_id ) {
12348 // The account owner activated a regular license key, no need to hide the data.
12349 $is_whitelabeled = false;
12350 }
12351 }
12352
12353 $this->_storage->is_whitelabeled = $is_whitelabeled;
12354
12355 // Reset the whitelabeled status after update.
12356 $this->is_whitelabeled = null;
12357 if ( $this->is_addon() ) {
12358 $parent_fs = $this->get_parent_instance();
12359
12360 if ( is_object( $parent_fs ) ) {
12361 $parent_fs->is_whitelabeled = null;
12362 }
12363 }
12364 }
12365
12366 /**
12367 * @author Leo Fajardo (@leorw)
12368 * @since 2.3.1
12369 *
12370 * @param FS_Plugin_License $license
12371 * @param FS_User $license_user
12372 */
12373 private function store_last_activated_license_data( FS_Plugin_License $license, $license_user = null ) {
12374 if ( ! is_object( $license_user ) ) {
12375 $this->_storage->last_license_key = md5( $license->secret_key );
12376 $this->_storage->last_license_user_id = null;
12377 } else {
12378 $this->_storage->last_license_user_key = md5( $license_user->secret_key );
12379 $this->_storage->last_license_user_id = $license_user->id;
12380 }
12381 }
12382
12383 /**
12384 * @author Leo Fajardo (@leorw)
12385 * @since 2.3.1
12386 *
12387 * @param bool $ignore_data_debug_mode
12388 *
12389 * @return bool
12390 */
12391 function is_whitelabeled_by_flag( $ignore_data_debug_mode = false ) {
12392 if ( true !== $this->_storage->is_whitelabeled ) {
12393 return false;
12394 } else if ( $ignore_data_debug_mode ) {
12395 return true;
12396 }
12397
12398 $fs = $this->is_addon() ?
12399 $this->get_parent_instance() :
12400 $this;
12401
12402 return ! $fs->is_data_debug_mode();
12403 }
12404
12405 /**
12406 * @author Leo Fajardo (@leorw)
12407 * @since 2.3.1
12408 *
12409 * @return number
12410 */
12411 function get_last_license_user_id() {
12412 return ( FS_User::is_valid_id( $this->_storage->last_license_user_id ) ) ?
12413 $this->_storage->last_license_user_id :
12414 null;
12415 }
12416
12417 /**
12418 * @author Leo Fajardo (@leorw)
12419 * @since 2.3.1
12420 *
12421 * @param int $blog_id
12422 * @param bool $ignore_data_debug_mode
12423 *
12424 * @return bool
12425 */
12426 function is_whitelabeled( $ignore_data_debug_mode = false, $blog_id = null ) {
12427 if ( ! is_null( $blog_id ) ) {
12428 $this->switch_to_blog( $blog_id );
12429 }
12430
12431 if ( ! is_null( $this->is_whitelabeled ) ) {
12432 $is_whitelabeled = $this->is_whitelabeled;
12433 } else {
12434 $is_whitelabeled = false;
12435
12436 $is_whitelabeled_flag = $this->is_whitelabeled_by_flag( true );
12437
12438 if ( ! $this->has_addons() ) {
12439 $is_whitelabeled = $is_whitelabeled_flag;
12440 } else if ( $is_whitelabeled_flag ) {
12441 $is_whitelabeled = true;
12442 } else {
12443 if ( $this->is_registered() || $this->is_premium() ) {
12444 $addon_ids = $this->get_updated_account_addons();
12445 } else {
12446 $addons = self::get_all_addons();
12447
12448 $plugin_addons = isset( $addons[ $this->_plugin->id ] ) ?
12449 $addons[ $this->_plugin->id ] :
12450 array();
12451
12452 $addon_ids = array();
12453 foreach ( $plugin_addons as $addon ) {
12454 $addon_ids[] = $addon->id;
12455 }
12456 }
12457
12458 $installed_addons = $this->get_installed_addons();
12459 foreach ( $installed_addons as $fs_addon ) {
12460 $addon_ids[] = $fs_addon->get_id();
12461 }
12462
12463 if ( ! empty( $addon_ids ) ) {
12464 $addon_ids = array_unique( $addon_ids );
12465
12466 $is_network_level = (
12467 fs_is_network_admin() &&
12468 $this->is_network_active()
12469 );
12470
12471 foreach ( $addon_ids as $addon_id ) {
12472 $addon = $this->get_addon( $addon_id );
12473
12474 if ( ! is_object( $addon ) ) {
12475 continue;
12476 }
12477
12478 $addon_storage = FS_Storage::instance( WP_FS__MODULE_TYPE_PLUGIN, $addon->slug );
12479 $fs_addon = $this->is_addon_activated( $addon_id ) ?
12480 self::get_addon_instance( $addon_id ) :
12481 null;
12482
12483 $was_addon_network_activated = false;
12484
12485 if ( is_object( $fs_addon ) ) {
12486 $was_addon_network_activated = $fs_addon->is_network_active();
12487 } else if ( $is_network_level ) {
12488 $was_addon_network_activated = $addon_storage->get( 'was_plugin_loaded', false, true );
12489 }
12490
12491 $network_delegated_connection = (
12492 $was_addon_network_activated &&
12493 $addon_storage->get( 'is_delegated_connection', false, true )
12494 );
12495
12496 if (
12497 $is_network_level &&
12498 ( ! $was_addon_network_activated || $network_delegated_connection )
12499 ) {
12500 $sites = self::get_sites();
12501
12502 /**
12503 * If in network admin area and the add-on was not network-activated or network-activated
12504 * and network-delegated, find any add-on whose is_whitelabeled flag is true.
12505 */
12506 foreach ( $sites as $site ) {
12507 $site_info = $this->get_site_info( $site );
12508
12509 if ( $addon_storage->get( 'is_whitelabeled', false, $site_info['blog_id'] ) ) {
12510 $is_whitelabeled = true;
12511 break;
12512 }
12513 }
12514
12515 if ( $is_whitelabeled ) {
12516 break;
12517 }
12518 } else {
12519 /**
12520 * This will be executed when any of the following is met:
12521 * 1. Add-on was network-activated, not network-delegated, and in network admin area.
12522 * 2. Add-on was network-activated, network-delegated, and in site admin area.
12523 * 3. Add-on was not network-activated and in site admin area.
12524 */
12525 if ( true === $addon_storage->is_whitelabeled ) {
12526 $is_whitelabeled = true;
12527 break;
12528 }
12529 }
12530 }
12531 }
12532 }
12533
12534 $this->is_whitelabeled = $is_whitelabeled;
12535
12536 if ( ! $is_whitelabeled || ! $this->is_data_debug_mode() ) {
12537 $this->_admin_notices->remove_sticky( 'data_debug_mode_enabled' );
12538 }
12539
12540 if ( ! is_null( $blog_id ) ) {
12541 $this->restore_current_blog();
12542 }
12543 }
12544
12545 return (
12546 $is_whitelabeled &&
12547 ( $ignore_data_debug_mode || ! $this->is_data_debug_mode() )
12548 );
12549 }
12550
12551 /**
12552 * Sync site's subscription.
12553 *
12554 * @author Vova Feldman (@svovaf)
12555 * @since 1.0.9
12556 *
12557 * @param FS_Plugin_License|null $license
12558 *
12559 * @return bool|\FS_Subscription
12560 */
12561 private function _sync_site_subscription( $license ) {
12562 if ( ! is_object( $license ) ) {
12563 $this->delete_unused_subscriptions();
12564
12565 return false;
12566 }
12567
12568 // Load subscription details if not lifetime.
12569 $subscription = $license->is_lifetime() ?
12570 false :
12571 $this->_fetch_site_license_subscription();
12572
12573 if ( is_object( $subscription ) && ! isset( $subscription->error ) ) {
12574 $this->store_subscription( $subscription );
12575 } else {
12576 $this->delete_unused_subscriptions();
12577 }
12578
12579 return $subscription;
12580 }
12581
12582 /**
12583 * @author Vova Feldman (@svovaf)
12584 * @since 1.0.6
12585 *
12586 * @return bool|\FS_Plugin_License
12587 */
12588 function _get_license() {
12589 if ( ! fs_is_network_admin() || is_object( $this->_license ) ) {
12590 return $this->_license;
12591 }
12592
12593 return $this->_get_available_premium_license();
12594 }
12595
12596 /**
12597 * @param number $license_id
12598 *
12599 * @return null|\FS_Subscription
12600 */
12601 function _get_subscription( $license_id ) {
12602 if ( ! isset( $this->_storage->subscriptions ) ||
12603 empty( $this->_storage->subscriptions )
12604 ) {
12605 return null;
12606 }
12607
12608 foreach ( fs_get_entities( $this->_storage->subscriptions, FS_Subscription::get_class_name() ) as $subscription ) {
12609 if ( $subscription->license_id == $license_id ) {
12610 return $subscription;
12611 }
12612 }
12613
12614 return null;
12615 }
12616
12617 /**
12618 * @author Leo Fajardo (@leorw)
12619 * @since 2.0.0
12620 *
12621 * @param FS_Subscription $subscription
12622 */
12623 function store_subscription( FS_Subscription $subscription ) {
12624 if ( ! isset( $this->_storage->subscriptions ) ) {
12625 $this->_storage->subscriptions = array();
12626 }
12627
12628 if ( empty( $this->_storage->subscriptions ) || ! is_multisite() ) {
12629 $this->_storage->subscriptions = array( $subscription );
12630
12631 return;
12632 }
12633
12634 $subscriptions = fs_get_entities( $this->_storage->subscriptions, FS_Subscription::get_class_name() );
12635
12636 $updated_subscription = false;
12637 foreach ( $subscriptions as $key => $existing_subscription ) {
12638 if ( $existing_subscription->id == $subscription->id ) {
12639 $subscriptions[ $key ] = $subscription;
12640 $updated_subscription = true;
12641 break;
12642 }
12643 }
12644
12645 if ( ! $updated_subscription ) {
12646 $subscriptions[] = $subscription;
12647 }
12648
12649 $this->_storage->subscriptions = $subscriptions;
12650 }
12651
12652 /**
12653 * @author Leo Fajardo (@leorw)
12654 * @since 2.0.0
12655 */
12656 function delete_unused_subscriptions() {
12657 if ( ! isset( $this->_storage->subscriptions ) ||
12658 empty( $this->_storage->subscriptions ) ||
12659 // Clean up only if there are already at least 3 subscriptions.
12660 ( count( $this->_storage->subscriptions ) < 3 )
12661 ) {
12662 return;
12663 }
12664
12665 if ( ! is_multisite() ) {
12666 // If not multisite, there should only be 1 subscription, so just clear the array.
12667 $this->_storage->subscriptions = array();
12668
12669 return;
12670 }
12671
12672 $subscriptions_to_keep_by_license_id_map = array();
12673 $sites = self::get_sites();
12674 foreach ( $sites as $site ) {
12675 $blog_id = self::get_site_blog_id( $site );
12676 $install = $this->get_install_by_blog_id( $blog_id );
12677
12678 if ( ! is_object( $install ) ||
12679 ! FS_Plugin_License::is_valid_id( $install->license_id )
12680 ) {
12681 continue;
12682 }
12683
12684 $subscriptions_to_keep_by_license_id_map[ $install->license_id ] = true;
12685 }
12686
12687 if ( empty( $subscriptions_to_keep_by_license_id_map ) ) {
12688 $this->_storage->subscriptions = array();
12689
12690 return;
12691 }
12692
12693 foreach ( $this->_storage->subscriptions as $key => $subscription ) {
12694 if ( ! isset( $subscriptions_to_keep_by_license_id_map[ $subscription->license_id ] ) ) {
12695 unset( $this->_storage->subscriptions[ $key ] );
12696 }
12697 }
12698 }
12699
12700 /**
12701 * @author Vova Feldman (@svovaf)
12702 * @since 1.0.2
12703 *
12704 * @param string $plan Plan name
12705 * @param bool $exact If true, looks for exact plan. If false, also check "higher" plans.
12706 *
12707 * @return bool
12708 */
12709 function is_plan( $plan, $exact = false ) {
12710 $this->_logger->entrance();
12711
12712 if ( ! $this->is_registered() ) {
12713 return false;
12714 }
12715
12716 $plan = strtolower( $plan );
12717
12718 $current_plan_name = $this->get_plan_name();
12719
12720 if ( $current_plan_name === $plan ) {
12721 // Exact plan.
12722 return true;
12723 } else if ( $exact ) {
12724 // Required exact, but plans are different.
12725 return false;
12726 }
12727
12728 $current_plan_order = - 1;
12729 $required_plan_order = PHP_INT_MAX;
12730 for ( $i = 0, $len = count( $this->_plans ); $i < $len; $i ++ ) {
12731 if ( $plan === $this->_plans[ $i ]->name ) {
12732 $required_plan_order = $i;
12733 } else if ( $current_plan_name === $this->_plans[ $i ]->name ) {
12734 $current_plan_order = $i;
12735 }
12736 }
12737
12738 return ( $current_plan_order > $required_plan_order );
12739 }
12740
12741 /**
12742 * Check if module has only one plan.
12743 *
12744 * @author Vova Feldman (@svovaf)
12745 * @since 1.2.1.7
12746 *
12747 * @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.
12748 *
12749 * @return bool
12750 */
12751 function is_single_plan( $double_check = false ) {
12752 $this->_logger->entrance();
12753
12754 if ( ! $this->is_registered() ||
12755 ! is_array( $this->_plans ) ||
12756 0 === count( $this->_plans )
12757 ) {
12758 return true;
12759 }
12760
12761 $has_free_plan = $this->has_free_plan();
12762
12763 if ( ! $has_free_plan && $double_check ) {
12764 foreach ( $this->_plans as $plan ) {
12765 if ( $plan->is_free() ) {
12766 $has_free_plan = true;
12767 break;
12768 }
12769 }
12770 }
12771
12772 return ( 1 === ( count( $this->_plans ) - ( $has_free_plan ? 1 : 0 ) ) );
12773 }
12774
12775 /**
12776 * Check if plan based on trial. If not in trial mode, should return false.
12777 *
12778 * @since 1.0.9
12779 *
12780 * @param string $plan Plan name
12781 * @param bool $exact If true, looks for exact plan. If false, also check "higher" plans.
12782 *
12783 * @return bool
12784 */
12785 function is_trial_plan( $plan, $exact = false ) {
12786 $this->_logger->entrance();
12787
12788 if ( ! $this->is_registered() ) {
12789 return false;
12790 }
12791
12792 if ( ! $this->is_trial() ) {
12793 return false;
12794 }
12795
12796 $trial_plan = $this->get_trial_plan();
12797
12798 if ( $trial_plan->name === $plan ) {
12799 // Exact plan.
12800 return true;
12801 } else if ( $exact ) {
12802 // Required exact, but plans are different.
12803 return false;
12804 }
12805
12806 $current_plan_order = - 1;
12807 $required_plan_order = - 1;
12808 for ( $i = 0, $len = count( $this->_plans ); $i < $len; $i ++ ) {
12809 if ( $plan === $this->_plans[ $i ]->name ) {
12810 $required_plan_order = $i;
12811 } else if ( $trial_plan->name === $this->_plans[ $i ]->name ) {
12812 $current_plan_order = $i;
12813 }
12814 }
12815
12816 return ( $current_plan_order > $required_plan_order );
12817 }
12818
12819 /**
12820 * Check if plugin has any paid plans.
12821 *
12822 * @author Vova Feldman (@svovaf)
12823 * @since 1.0.7
12824 *
12825 * @return bool
12826 */
12827 function has_paid_plan() {
12828 return $this->_has_paid_plans ||
12829 FS_Plan_Manager::instance()->has_paid_plan( $this->_plans );
12830 }
12831
12832 /**
12833 * Check if plugin has any plan with a trail.
12834 *
12835 * @author Vova Feldman (@svovaf)
12836 * @since 1.0.9
12837 *
12838 * @return bool
12839 */
12840 function has_trial_plan() {
12841 /**
12842 * @author Vova Feldman(@svovaf)
12843 * @since 1.2.1.5
12844 *
12845 * Allow setting a trial from the SDK without calling the API.
12846 * But, if the user did opt-in, continue using the real data from the API.
12847 */
12848 if ( $this->_trial_days >= 0 ) {
12849 return true;
12850 }
12851
12852 return $this->_storage->get( 'has_trial_plan', false );
12853 }
12854
12855 /**
12856 * Check if plugin has any free plan, or is it premium only.
12857 *
12858 * Note: If no plans configured, assume plugin is free.
12859 *
12860 * @author Vova Feldman (@svovaf)
12861 * @since 1.0.7
12862 *
12863 * @return bool
12864 */
12865 function has_free_plan() {
12866 return ! $this->is_only_premium();
12867 }
12868
12869 /**
12870 * Displays a license activation dialog box when the user clicks on the "Activate License"
12871 * or "Change License" link on the plugins
12872 * page.
12873 *
12874 * @author Leo Fajardo (@leorw)
12875 * @since 1.1.9
12876 */
12877 function _add_license_activation_dialog_box() {
12878 $vars = array(
12879 'id' => $this->_module_id,
12880 );
12881
12882 fs_require_template( 'forms/license-activation.php', $vars );
12883 fs_require_template( 'forms/resend-key.php', $vars );
12884 }
12885
12886 /**
12887 * Displays an email address update dialog box when the user clicks on the email address "Edit" button on the "Account" page.
12888 *
12889 * @author Leo Fajardo (@leorw)
12890 * @since 2.5.0
12891 */
12892 function _add_email_address_update_dialog_box() {
12893 $vars = array( 'id' => $this->_module_id );
12894
12895 fs_require_template( 'forms/email-address-update.php', $vars );
12896 }
12897
12898 /**
12899 * @author Leo Fajardo (@leorw)
12900 * @since 2.5.0
12901 */
12902 function _add_email_address_update_option() {
12903 if ( ! $this->should_handle_user_change() ) {
12904 return;
12905 }
12906
12907 // Add email address update AJAX handler.
12908 $this->add_ajax_action( 'update_email_address', array( &$this, '_email_address_update_ajax_handler' ) );
12909 }
12910
12911 /**
12912 * @author Leo Fajardo (@leorw)
12913 * @since 2.5.0
12914 */
12915 function _email_address_update_ajax_handler() {
12916 $this->check_ajax_referer( 'update_email_address' );
12917
12918 $new_email_address = fs_request_get( 'email_address' );
12919 $transfer_type = fs_request_get( 'transfer_type' );
12920
12921 $result = $this->update_email( $new_email_address );
12922
12923 if ( ! FS_Api::is_api_error( $result ) ) {
12924 self::shoot_ajax_success();
12925 }
12926
12927 $error = '';
12928
12929 if ( FS_Api::is_api_error_object( $result ) ) {
12930 switch ( $result->error->code ) {
12931 case 'user_exist':
12932 case 'account_verification_required':
12933 $error = array(
12934 'code' => 'change_ownership',
12935 'url' => $this->get_account_url( 'change_owner', array(
12936 'state' => 'init',
12937 'candidate_email' => $new_email_address,
12938 'transfer_type' => $transfer_type,
12939 ) ),
12940 );
12941
12942 break;
12943 }
12944 }
12945
12946 if ( empty( $error ) ) {
12947 $error = is_object( $result ) ?
12948 var_export( $result->error, true ) :
12949 $result;
12950 }
12951
12952 self::shoot_ajax_failure( $error );
12953 }
12954
12955 /**
12956 * Returns a collection of IDs of installs that are associated with the context product and its add-ons, and activated with foreign licenses.
12957 *
12958 * @author Leo Fajardo (@leorw)
12959 * @since 2.3.2
12960 *
12961 * @return number[]
12962 */
12963 function get_installs_ids_with_foreign_licenses() {
12964 $installs = array();
12965
12966 if (
12967 is_object( $this->_license ) &&
12968 $this->_site->user_id != $this->_license->user_id
12969 ) {
12970 $installs[] = $this->_site->id;
12971 }
12972
12973 /**
12974 * Also try to get foreign licenses for the context product's add-ons.
12975 */
12976 $installs_by_slug_map = $this->get_parent_and_addons_installs_info();
12977
12978 foreach ( $installs_by_slug_map as $slug => $install_info ) {
12979 if ( $slug == $this->get_slug() ) {
12980 continue;
12981 }
12982
12983 $install = $install_info['install'];
12984 $license = $install_info['license'];
12985
12986 if (
12987 is_object( $license ) &&
12988 $install->user_id != $license->user_id
12989 ) {
12990 $installs[] = $install->id;
12991 }
12992 }
12993
12994 return $installs;
12995 }
12996
12997 /**
12998 * Displays the "Change User" dialog box when the user clicks on the "Change User" button on the "Account" page.
12999 *
13000 * @author Leo Fajardo (@leorw)
13001 * @since 2.3.2
13002 *
13003 * @param number[] $install_ids
13004 */
13005 function _add_user_change_dialog_box( $install_ids ) {
13006 $vars = array(
13007 'id' => $this->_module_id,
13008 'license_owners' => $this->fetch_installs_licenses_owners_data( $install_ids )
13009 );
13010
13011 fs_require_template( 'forms/user-change.php', $vars );
13012 }
13013
13014 /**
13015 * @author Leo Fajardo (@leorw)
13016 * @since 2.3.1
13017 */
13018 function _add_data_debug_mode_dialog_box() {
13019 $vars = array(
13020 'id' => $this->_module_id,
13021 );
13022
13023 fs_require_template( 'forms/data-debug-mode.php', $vars );
13024 }
13025
13026 /**
13027 * Displays a subscription cancellation dialog box when the user clicks on the "Deactivate License"
13028 * link on the "Account" page or deactivates a plugin and there's an active subscription that is
13029 * either associated with a non-lifetime single-site license or non-lifetime multisite license that
13030 * is only activated on a single production site.
13031 *
13032 * @author Leo Fajardo (@leorw)
13033 * @since 2.2.1
13034 *
13035 * @param bool $is_license_deactivation
13036 *
13037 * @return array
13038 */
13039 function _get_subscription_cancellation_dialog_box_template_params( $is_license_deactivation = false ) {
13040 if ( fs_is_network_admin() ) {
13041 // Subscription cancellation dialog box is currently not supported for multisite networks.
13042 return array();
13043 }
13044
13045 if ( $this->is_whitelabeled() ) {
13046 return array();
13047 }
13048
13049 $license = $this->_get_license();
13050
13051 /**
13052 * 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.
13053 *
13054 * @author Leo Fajardo (@leorw) (Comment added by Vova Feldman @svovaf)
13055 * @since 2.2.1
13056 */
13057 if ( ! is_object( $license ) ||
13058 $license->is_lifetime() ||
13059 ( ! $license->is_single_site() && $license->activated > 1 )
13060 ) {
13061 return array();
13062 }
13063
13064 /**
13065 * @var FS_Subscription $subscription
13066 */
13067 $subscription = $this->_get_subscription( $license->id );
13068 if ( ! is_object( $subscription ) || ! $subscription->is_active() ) {
13069 return array();
13070 }
13071
13072 return array(
13073 'id' => $this->_module_id,
13074 'license' => $license,
13075 'has_trial' => $this->is_paid_trial(),
13076 'is_license_deactivation' => $is_license_deactivation,
13077 );
13078 }
13079
13080 /**
13081 * @author Leo Fajardo (@leorw)
13082 * @since 2.0.2
13083 */
13084 function _add_premium_version_upgrade_selection_dialog_box() {
13085 $modules_update = get_site_transient( $this->is_theme() ? 'update_themes' : 'update_plugins' );
13086 if ( ! isset( $modules_update->response[ $this->_plugin_basename ] ) ) {
13087 return;
13088 }
13089
13090 $vars = array(
13091 'id' => $this->_module_id,
13092 'new_version' => is_object( $modules_update->response[ $this->_plugin_basename ] ) ?
13093 $modules_update->response[ $this->_plugin_basename ]->new_version :
13094 $modules_update->response[ $this->_plugin_basename ]['new_version']
13095 );
13096
13097 fs_require_template( 'forms/premium-versions-upgrade-metadata.php', $vars );
13098 fs_require_once_template( 'forms/premium-versions-upgrade-handler.php', $vars );
13099 }
13100
13101 /**
13102 * Displays the opt-out dialog box when the user clicks on the "Opt Out" link on the "Plugins"
13103 * page.
13104 *
13105 * @author Leo Fajardo (@leorw)
13106 * @since 1.2.1.5
13107 */
13108 function _add_optout_dialog() {
13109 if ( $this->is_theme() ) {
13110 $vars = null;
13111 fs_require_once_template( '/js/jquery.content-change.php', $vars );
13112 }
13113
13114 $vars = array( 'id' => $this->_module_id );
13115 fs_require_template( 'forms/optout.php', $vars );
13116 }
13117
13118 /**
13119 * Prepare page to include all required UI and logic for the license activation dialog.
13120 *
13121 * @author Vova Feldman (@svovaf)
13122 * @since 1.2.0
13123 */
13124 function _add_license_activation() {
13125 if ( $this->is_migration() ) {
13126 return;
13127 }
13128
13129 if ( ! $this->is_user_admin() ) {
13130 // Only admins can activate a license.
13131 return;
13132 }
13133
13134 if ( ! $this->has_paid_plan() ) {
13135 // Module doesn't have any paid plans.
13136 return;
13137 }
13138
13139 if (
13140 $this->has_premium_version() &&
13141 ! $this->is_premium() &&
13142 /**
13143 * Also handle the case when an upgrade was made using the free version.
13144 *
13145 * @author Leo Fajardo (@leorw)
13146 * @since 2.3.2
13147 */
13148 ! is_object( $this->_get_license() )
13149 ) {
13150 // Only add license activation logic to the premium version, or in case of a serviceware plugin, also in the free version.
13151 return;
13152 }
13153
13154 // Add license activation link and AJAX request handler.
13155 if ( self::is_plugins_page() ) {
13156 $is_network_admin = fs_is_network_admin();
13157
13158 if (
13159 ( $is_network_admin && $this->is_network_active() && ! $this->is_network_delegated_connection() ) ||
13160 ( ! $is_network_admin && ( ! $this->is_network_active() || $this->is_delegated_connection() ) )
13161 ) {
13162 if (
13163 $this->is_premium() ||
13164 ( $this->has_paid_plan() && ! $this->has_premium_version() )
13165 ) {
13166 /**
13167 * @since 1.2.0 Add license action link only on plugins page.
13168 */
13169 $this->_add_license_action_link();
13170 }
13171 }
13172 }
13173
13174 // Add license activation AJAX callback.
13175 $this->add_ajax_action( 'activate_license', array( &$this, '_activate_license_ajax_action' ) );
13176
13177 // Add resend license AJAX callback.
13178 $this->add_ajax_action( 'resend_license_key', array( &$this, '_resend_license_key_ajax_action' ) );
13179 }
13180
13181 /**
13182 * Prepares page to include all required UI and logic for the "Change User" dialog.
13183 *
13184 * @author Leo Fajardo (@leorw)
13185 * @since 2.3.2
13186 */
13187 function _add_user_change_option() {
13188 if ( ! $this->should_handle_user_change() ) {
13189 return;
13190 }
13191
13192 $installs_ids_with_foreign_licenses = $this->get_installs_ids_with_foreign_licenses();
13193
13194 if ( empty( $installs_ids_with_foreign_licenses ) ) {
13195 // Handle user change only when the parent product or one of its add-ons is activated with a foreign license.
13196 return;
13197 }
13198
13199 // Add user change AJAX handler.
13200 $this->add_ajax_action( 'change_user', array( &$this, '_user_change_ajax_action' ) );
13201 }
13202
13203 /**
13204 * @author Leo Fajardo (@leorw)
13205 * @since 2.3.2
13206 */
13207 function should_handle_user_change() {
13208 if ( ! $this->is_user_admin() ) {
13209 // Only admins can change user.
13210 return false;
13211 }
13212
13213 if ( $this->is_addon() ) {
13214 return false;
13215 }
13216
13217 if ( ! $this->is_registered() ) {
13218 return false;
13219 }
13220
13221 if (
13222 $this->is_network_active() &&
13223 ( fs_is_network_admin() || ! $this->is_site_delegated_connection() )
13224 ) {
13225 // Handle only on site-level "Account" section for now.
13226 return false;
13227 }
13228
13229 return true;
13230 }
13231
13232 /**
13233 * @author Leo Fajardo (@leorw)
13234 * @since 2.0.2
13235 */
13236 function _add_premium_version_upgrade_selection() {
13237 if ( ! $this->is_user_admin() ) {
13238 return;
13239 }
13240
13241 if ( ! $this->is_premium() || $this->has_any_active_valid_license() ) {
13242 // This is relevant only to the free versions and premium versions without an active license.
13243 return;
13244 }
13245
13246 if ( self::is_updates_page() || ( $this->is_plugin() && self::is_plugins_page() ) ) {
13247 $this->_add_premium_version_upgrade_selection_action();
13248 }
13249 }
13250
13251 /**
13252 * @author Edgar Melkonyan
13253 * @since 2.4.1
13254 *
13255 * @throws Freemius_Exception
13256 */
13257 function _toggle_whitelabel_mode_ajax_handler() {
13258 $this->_logger->entrance();
13259
13260 $this->check_ajax_referer( 'toggle_whitelabel_mode' );
13261
13262 if ( ! $this->is_user_admin() ) {
13263 // Only for admins.
13264 self::shoot_ajax_failure();
13265 }
13266
13267 $license = $this->get_api_user_scope()->call(
13268 "/licenses/{$this->_site->license_id}.json",
13269 'put',
13270 array( 'is_whitelabeled' => ! $this->_license->is_whitelabeled )
13271 );
13272
13273 if ( ! $this->is_api_result_entity( $license ) ) {
13274 self::shoot_ajax_failure(
13275 FS_Api::is_api_error_object( $license ) ?
13276 $license->error->message :
13277 fs_text_inline( "An unknown error has occurred while trying to toggle the license's white-label mode.", 'unknown-error-occurred', $this->get_slug() )
13278 );
13279 }
13280
13281 $this->_license->is_whitelabeled = $license->is_whitelabeled;
13282 $this->_store_licenses();
13283
13284 $this->_sync_license();
13285
13286 if ( ! $license->is_whitelabeled ) {
13287 $this->_admin_notices->remove_sticky( 'license_whitelabeled' );
13288 } else {
13289 $this->_admin_notices->add_sticky(
13290 sprintf(
13291 $this->get_text_inline(
13292 '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.',
13293 'license_whitelabeled'
13294 ),
13295 "<strong>{$this->get_plugin_title()}</strong>",
13296 sprintf( '<a href="https://users.freemius.com" target="_blank">%s</a>', $this->get_text_inline( 'User Dashboard', 'user-dashboard' ) ),
13297 sprintf( '<a href="#" class="fs-toggle-whitelabel-mode">%s</a>', $this->get_text_inline( 'revert it now', 'revert-it-now' ) )
13298 ),
13299 'license_whitelabeled'
13300 );
13301 }
13302
13303 self::shoot_ajax_response( array( 'success' => true ) );
13304 }
13305
13306 /**
13307 * @author Leo Fajardo (@leorw)
13308 * @since 2.3.0
13309 */
13310 function _add_beta_mode_update_handler() {
13311 if ( ! $this->is_user_admin() ) {
13312 return;
13313 }
13314
13315 if ( ! $this->is_premium() ) {
13316 return;
13317 }
13318
13319 $this->add_ajax_action( 'set_beta_mode', array( &$this, '_set_beta_mode_ajax_handler' ) );
13320 }
13321
13322 /**
13323 * @author Leo Fajardo (@leorw)
13324 * @since 2.3.0
13325 */
13326 function _set_beta_mode_ajax_handler() {
13327 $this->_logger->entrance();
13328
13329 $this->check_ajax_referer( 'set_beta_mode' );
13330
13331 if ( ! $this->is_user_admin() ) {
13332 // Only for admins.
13333 self::shoot_ajax_failure();
13334 }
13335
13336 $is_beta = trim( fs_request_get( 'is_beta', '', 'post' ) );
13337
13338 if ( empty( $is_beta ) || ! in_array( $is_beta, array( 'true', 'false' ) ) ) {
13339 self::shoot_ajax_failure();
13340 }
13341
13342 $site = $this->api_site_call(
13343 '',
13344 'put',
13345 array(
13346 'is_beta' => ( 'true' == $is_beta ),
13347 'fields' => 'is_beta'
13348 )
13349 );
13350
13351 if ( ! $this->is_api_result_entity( $site ) ) {
13352 self::shoot_ajax_failure(
13353 FS_Api::is_api_error_object( $site ) ?
13354 $site->error->message :
13355 fs_text_inline( "An unknown error has occurred while trying to set the user's beta mode.", 'unknown-error-occurred', $this->get_slug() )
13356 );
13357 }
13358
13359 $this->_site->is_beta = $site->is_beta;
13360 $this->_store_site();
13361
13362 self::shoot_ajax_response( array( 'success' => true ) );
13363 }
13364
13365 /**
13366 * License activation WP AJAX handler.
13367 *
13368 * @author Leo Fajardo (@leorw)
13369 * @since 1.1.9
13370 *
13371 * @uses Freemius::activate_license()
13372 */
13373 function _activate_license_ajax_action() {
13374 $this->_logger->entrance();
13375
13376 $this->check_ajax_referer( 'activate_license' );
13377
13378 $license_key = trim( fs_request_get_raw( 'license_key' ) );
13379
13380 if ( empty( $license_key ) ) {
13381 $license_id = trim( fs_request_get_raw( 'license_id' ) );
13382
13383 if ( FS_Plugin_License::is_valid_id( $license_id ) ) {
13384 $license = $this->_get_license_by_id( $license_id, false );
13385
13386 if ( is_object( $license ) ) {
13387 $license_key = $license->secret_key;
13388 }
13389 }
13390 }
13391
13392 if ( empty( $license_key ) ) {
13393 exit;
13394 }
13395
13396 $sites = fs_is_network_admin() ?
13397 fs_request_get( 'sites', array(), 'post' ) :
13398 array();
13399
13400 $result = $this->activate_license(
13401 $license_key,
13402 $sites,
13403 fs_request_get_bool( 'is_marketing_allowed', null ),
13404 fs_request_get( 'blog_id', null ),
13405 fs_request_get( 'module_id', null, 'post' ),
13406 fs_request_get( 'user_id', null ),
13407 fs_request_get_bool( 'is_extensions_tracking_allowed', null ),
13408 fs_request_get_bool( 'is_diagnostic_tracking_allowed', null )
13409 );
13410
13411 if (
13412 $result['success'] &&
13413 $this->is_bundle_license_auto_activation_enabled()
13414 ) {
13415 $license = new FS_Plugin_License();
13416 $license->secret_key = $license_key;
13417
13418 $this->maybe_activate_bundle_license( $license, $sites );
13419 }
13420
13421 echo json_encode( $result );
13422
13423 exit;
13424 }
13425
13426 /**
13427 * User change WP AJAX handler.
13428 *
13429 * @author Leo Fajardo (@leorw)
13430 * @since 2.3.2
13431 */
13432 function _user_change_ajax_action() {
13433 $this->_logger->entrance();
13434
13435 $this->check_ajax_referer( 'change_user' );
13436
13437 $new_email_address = trim( fs_request_get( 'email_address', '' ) );
13438 $new_user_id = fs_request_get( 'user_id' );
13439
13440 if ( empty( $new_email_address ) && ! FS_User::is_valid_id( $new_user_id ) ) {
13441 self::shoot_ajax_failure( fs_text_inline( 'Invalid new user ID or email address.', 'invalid-new-user-id-or-email', $this->get_slug() ) );
13442 }
13443
13444 $params = array();
13445
13446 if ( ! empty( $new_email_address ) ) {
13447 $params['user_email'] = $new_email_address;
13448 } else {
13449 $params['user_id'] = $new_user_id;
13450 }
13451
13452 $installs_info_by_slug_map = $this->get_parent_and_addons_installs_info();
13453 $install_ids = array();
13454
13455 foreach ( $installs_info_by_slug_map as $slug => $install_info ) {
13456 $install_ids[ $slug ] = $install_info['install']->id;
13457 }
13458
13459 $params['install_ids'] = implode( ',', array_values( $install_ids ) );
13460
13461 $install = $this->get_api_site_scope()->call( $this->add_show_pending( '/' ), 'put', $params );
13462
13463 if ( FS_Api::is_api_error( $install ) ) {
13464 $error = '';
13465
13466 if ( is_object( $install ) ) {
13467 switch ( $install->error->code ) {
13468 case 'user_exist':
13469 $error = (
13470 $this->get_text_x_inline( 'Oops', 'exclamation', 'oops' ) . '...' .
13471 $this->get_text_inline( 'Sorry, we could not complete the email update. Another user with the same email is already registered.', 'user-exist-message' ) . ' ' .
13472 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>' ) .
13473 sprintf(
13474 '<a style="line-height: 40px;" href="%s"><button class="button button-primary">%s &nbsp;&#10140;</button></a>',
13475 $this->get_account_url( 'change_owner', array(
13476 'state' => 'init',
13477 'candidate_email' => $new_email_address
13478 ) ),
13479 $this->get_text_inline( 'Change Ownership', 'change-ownership' )
13480 )
13481 );
13482 break;
13483 }
13484 }
13485
13486 if ( empty( $error ) ) {
13487 $error = FS_Api::is_api_error_object( $install ) ?
13488 $install->error->message :
13489 var_export( $install->error, true );
13490 }
13491
13492 self::shoot_ajax_failure( $error );
13493 } else {
13494 if (
13495 // If successful ownership change.
13496 $this->get_user()->id != $install->user_id ||
13497 ! empty( $new_email_address )
13498 ) {
13499 $this->complete_ownership_change_by_license( $install->user_id, $install_ids );
13500 }
13501 }
13502
13503 self::shoot_ajax_success();
13504 }
13505
13506 /**
13507 * @author Leo Fajardo (@leorw)
13508 * @since 2.3.2.14
13509 */
13510 function starting_migration() {
13511 if ( ! empty( $this->_storage->license_migration ) ) {
13512 // Do not overwrite the data if already set.
13513 return;
13514 }
13515
13516 $this->_storage->license_migration = array(
13517 'is_migrating' => true,
13518 'start_timestamp' => time()
13519 );
13520 }
13521
13522 /**
13523 * @author Leo Fajardo (@leorw)
13524 * @since 2.3.2.14
13525 */
13526 function is_migration() {
13527 if ( $this->is_addon() ) {
13528 return $this->get_parent_instance()->is_migration();
13529 }
13530
13531 if ( empty( $this->_storage->license_migration ) ) {
13532 return false;
13533 }
13534
13535 if ( ! $this->_storage->license_migration['is_migrating'] ) {
13536 return false;
13537 }
13538
13539 return (
13540 // Return `true` if the migration is within 5 minutes from the starting time.
13541 ( time() - $this->_storage->license_migration['start_timestamp'] ) <= WP_FS__TIME_5_MIN_IN_SEC
13542 );
13543 }
13544
13545 /**
13546 *
13547 * A helper method to activate migrated licenses. If the product is network activated and integrated, the method will network activate the license.
13548 *
13549 * @author Vova Feldman (@svovaf)
13550 * @since 2.3.0
13551 *
13552 * @param string $license_key
13553 * @param null|bool $is_marketing_allowed
13554 * @param null|number $plugin_id
13555 * @param array $sites
13556 * @param int $blog_id
13557 *
13558 * @return array {
13559 * @var bool $success
13560 * @var string $error
13561 * @var string $next_page
13562 * }
13563 *
13564 * @uses Freemius::activate_license()
13565 */
13566 function activate_migrated_license(
13567 $license_key,
13568 $is_marketing_allowed = null,
13569 $plugin_id = null,
13570 $sites = array(),
13571 $blog_id = null
13572 ) {
13573 $this->_logger->entrance();
13574
13575 $result = $this->activate_license(
13576 $license_key,
13577 ( empty( $sites ) && is_null( $blog_id ) && $this->is_network_active() ) ?
13578 $this->get_sites_for_network_level_optin() :
13579 $sites,
13580 $is_marketing_allowed,
13581 $blog_id,
13582 $plugin_id
13583 );
13584
13585 // No need to show the sticky after license activation notice after migrating a license.
13586 $this->_admin_notices->remove_sticky( 'plan_upgraded' );
13587
13588 return $result;
13589 }
13590
13591 /**
13592 * @author Leo Fajardo (@leorw)
13593 * @since 2.3.1
13594 *
13595 * @return string
13596 */
13597 function get_pricing_js_path() {
13598 if ( ! isset( $this->_pricing_js_path ) ) {
13599 $pricing_js_path = $this->apply_filters( 'freemius_pricing_js_path', '' );
13600
13601 if ( empty( $pricing_js_path ) ) {
13602 global $fs_active_plugins;
13603
13604 foreach ( $fs_active_plugins->plugins as $sdk_path => $data ) {
13605 if ( $data->plugin_path == $this->get_plugin_basename() ) {
13606 $plugin_or_theme_root_dir = ( $this->is_plugin() ? WP_PLUGIN_DIR : get_theme_root( get_stylesheet() ) );
13607
13608 $pricing_js_path = $plugin_or_theme_root_dir
13609 . '/'
13610 // The basename will be `plugins`, `themes`, or the basename of a custom plugins or themes directory.
13611 . str_replace( '../' . basename( $plugin_or_theme_root_dir ) . '/', '', $sdk_path )
13612 . '/includes/freemius-pricing/freemius-pricing.js';
13613
13614 break;
13615 }
13616 }
13617 }
13618
13619 $this->_pricing_js_path = $pricing_js_path;
13620 }
13621
13622 return $this->_pricing_js_path;
13623 }
13624
13625 /**
13626 * @author Leo Fajardo (@leorw)
13627 * @since 2.3.1
13628 *
13629 * @return bool
13630 */
13631 function should_use_external_pricing() {
13632 if ( is_null( $this->_use_external_pricing ) ) {
13633 $pricing_js_path = $this->get_pricing_js_path();
13634
13635 $this->_use_external_pricing = ( empty( $pricing_js_path ) || ! file_exists( $pricing_js_path ) );
13636 }
13637
13638 return $this->_use_external_pricing;
13639 }
13640
13641 /**
13642 * The implementation of this method was previously in `_activate_license_ajax_action()`.
13643 *
13644 * @author Vova Feldman (@svovaf)
13645 * @since 2.2.4
13646 * @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).
13647 * @param string $license_key
13648 * @param array $sites
13649 * @param null|bool $is_marketing_allowed
13650 * @param null|int $blog_id
13651 * @param null|number $plugin_id
13652 * @param null|number $license_owner_id
13653 * @param bool|null $is_extensions_tracking_allowed
13654 * @param bool|null $is_diagnostic_tracking_allowed Since 2.5.0.2 to allow license activation with minimal data footprint.
13655 *
13656 *
13657 * @return array {
13658 * @var bool $success
13659 * @var string $error
13660 * @var string $next_page
13661 * }
13662 */
13663 private function activate_license(
13664 $license_key,
13665 $sites = array(),
13666 $is_marketing_allowed = null,
13667 $blog_id = null,
13668 $plugin_id = null,
13669 $license_owner_id = null,
13670 $is_extensions_tracking_allowed = null,
13671 $is_diagnostic_tracking_allowed = null
13672 ) {
13673 $this->_logger->entrance();
13674
13675 $license_key = trim( $license_key );
13676
13677 $is_network_activation_or_migration = (
13678 fs_is_network_admin() ||
13679 ( ! empty( $sites ) && $this->is_migration() )
13680 );
13681
13682 if ( ! $is_network_activation_or_migration ) {
13683 // If the license activation is executed outside the context of a network admin, ignore the sites collection.
13684 $sites = array();
13685 }
13686
13687 $fs = ( empty($plugin_id) || $plugin_id == $this->_module_id ) ?
13688 $this :
13689 $this->get_addon_instance( $plugin_id );
13690
13691 FS_Permission_Manager::instance( $this )->update_permissions_tracking_flag( array(
13692 FS_Permission_Manager::PERMISSION_DIAGNOSTIC => $is_diagnostic_tracking_allowed,
13693 FS_Permission_Manager::PERMISSION_EXTENSIONS => $is_extensions_tracking_allowed,
13694 ) );
13695
13696 $error = false;
13697 $next_page = false;
13698
13699 $has_valid_blog_id = is_numeric( $blog_id );
13700
13701 $user = null;
13702
13703 if ( $fs->is_addon() && $fs->get_parent_instance()->is_registered() ) {
13704 /**
13705 * When activating an add-on's license and the parent is opted-in, activate the license with the parent's opted-in user context.
13706 *
13707 * @author Vova Feldman (@svovaf)
13708 */
13709 $user = $fs->get_parent_instance()->get_current_or_network_user();
13710 } else if ( $fs->is_registered() ) {
13711 $user = $fs->get_current_or_network_user();
13712 }
13713
13714 if ( $has_valid_blog_id ) {
13715 /**
13716 * If a specific blog ID was provided, activate the license only on the specific blog that is associated with the given blog ID.
13717 *
13718 * @author Leo Fajardo (@leorw)
13719 */
13720 $fs->switch_to_blog( $blog_id );
13721 }
13722
13723 if ( is_object( $user ) ) {
13724 $result = true;
13725
13726 if ( $is_network_activation_or_migration && ! $has_valid_blog_id ) {
13727 // If no specific blog ID was provided, activate the license for all sites in the network.
13728 $blog_2_install_map = array();
13729 $site_ids = array();
13730
13731 foreach ( $sites as $site ) {
13732 if ( ! isset( $site['blog_id'] ) || ! is_numeric( $site['blog_id'] ) ) {
13733 continue;
13734 }
13735
13736 $install = $fs->get_install_by_blog_id( $site['blog_id'] );
13737
13738 if ( is_object( $install ) ) {
13739 $blog_2_install_map[ $site['blog_id'] ] = $install;
13740 } else {
13741 $site_ids[] = $site['blog_id'];
13742 }
13743 }
13744
13745 if ( ! empty( $blog_2_install_map ) ) {
13746 $result = $fs->activate_license_on_many_installs( $user, $license_key, $blog_2_install_map );
13747 }
13748
13749 if ( true === $result && ! empty( $site_ids ) ) {
13750 $result = $fs->activate_license_on_many_sites( $user, $license_key, $site_ids );
13751 }
13752 } else {
13753 if ( $fs->is_registered() ) {
13754 $params = array(
13755 'license_key' => $fs->apply_filters( 'license_key', $license_key )
13756 );
13757
13758 $install_ids = array();
13759
13760 $change_owner = FS_User::is_valid_id( $license_owner_id );
13761
13762 if ( $change_owner ) {
13763 $params['user_id'] = $license_owner_id;
13764
13765 $installs_info_by_slug_map = $fs->get_parent_and_addons_installs_info();
13766
13767 foreach ( $installs_info_by_slug_map as $slug => $install_info ) {
13768 $install_ids[ $slug ] = $install_info['install']->id;
13769 }
13770
13771 $params['install_ids'] = implode( ',', array_values( $install_ids ) );
13772 }
13773
13774 $api = $fs->get_api_site_scope();
13775
13776 $result = $api->call( $fs->add_show_pending( '/' ), 'put', $params );
13777
13778 if ( ! FS_Api::is_api_error( $result ) ) {
13779 $install = $result;
13780
13781 $fs->reconnect_locally( $has_valid_blog_id );
13782
13783 if (
13784 $change_owner &&
13785 // If successful ownership change.
13786 $fs->get_user()->id != $install->user_id
13787 ) {
13788 $fs->complete_ownership_change_by_license( $install->user_id, $install_ids );
13789 }
13790 }
13791 } else /* ( $fs->is_addon() && $fs->get_parent_instance()->is_registered() ) */ {
13792 $result = $fs->activate_license_on_site( $user, $license_key );
13793 }
13794 }
13795
13796 $is_connected = null;
13797
13798 if ( true !== $result && ! FS_Api::is_api_result_entity( $result ) ) {
13799 if ( FS_Api::is_blocked( $result ) ) {
13800 $result->error->message = $this->generate_api_blocked_notice_message_from_result( $result );
13801
13802 $is_connected = false;
13803 }
13804
13805 $error = FS_Api::is_api_error_object( $result ) ?
13806 $result->error->message :
13807 var_export( $result, true );
13808 } else {
13809 $is_connected = true;
13810
13811 $fs->network_upgrade_mode_completed();
13812
13813 $fs->_user = $user;
13814
13815 if ( fs_is_network_admin() && ! $has_valid_blog_id ) {
13816 $fs->_site = $fs->get_network_install();
13817 }
13818
13819 $fs->_sync_license( true, $has_valid_blog_id );
13820
13821 $this->maybe_sync_install_user();
13822
13823 $next_page = $fs->is_addon() ?
13824 $fs->get_parent_instance()->get_account_url() :
13825 $fs->get_after_activation_url( 'after_connect_url' );
13826 }
13827
13828 $fs->update_connectivity_info( $is_connected );
13829 } else {
13830 $next_page = $fs->opt_in(
13831 false,
13832 false,
13833 false,
13834 $license_key,
13835 false,
13836 false,
13837 false,
13838 $is_marketing_allowed,
13839 $sites
13840 );
13841
13842 if ( isset( $next_page->error ) ) {
13843 $error = $next_page->error;
13844 } else {
13845 if ( $is_network_activation_or_migration ) {
13846 /**
13847 * Get the list of sites that were just opted-in (and license activated).
13848 * This is an optimization for the next part below saving some DB queries.
13849 */
13850 $connected_sites = array();
13851 foreach ( $sites as $site ) {
13852 if ( isset( $site['blog_id'] ) && is_numeric( $site['blog_id'] ) ) {
13853 $connected_sites[ $site['blog_id'] ] = true;
13854 }
13855 }
13856
13857 $all_sites = self::get_sites();
13858 $pending_blog_ids = array();
13859
13860 /**
13861 * 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.
13862 *
13863 * @author Vova Feldman (@svovaf)
13864 */
13865 foreach ( $all_sites as $site ) {
13866 $blog_id = self::get_site_blog_id( $site );
13867
13868 if ( isset( $connected_sites[ $blog_id ] ) ) {
13869 // Site was just connected.
13870 continue;
13871 }
13872
13873 if ( $fs->is_installed_on_site( $blog_id ) ) {
13874 // Site was already connected before.
13875 continue;
13876 }
13877
13878 if ( $fs->is_site_delegated_connection( $blog_id ) ) {
13879 // Site's connection was delegated.
13880 continue;
13881 }
13882
13883 if ( $fs->is_anonymous_site( $blog_id ) ) {
13884 // Site connection was already skipped.
13885 continue;
13886 }
13887
13888 $pending_blog_ids[] = $blog_id;
13889 }
13890
13891 if ( ! empty( $pending_blog_ids ) ) {
13892 if ( $fs->is_freemium() && $fs->is_enable_anonymous() ) {
13893 $fs->skip_connection( $pending_blog_ids );
13894 } else {
13895 $fs->delegate_connection( $pending_blog_ids );
13896 }
13897 }
13898 }
13899 }
13900 }
13901
13902 if ( false === $error && true === $fs->_storage->require_license_activation ) {
13903 $fs->_storage->require_license_activation = false;
13904 }
13905
13906 $result = array(
13907 'success' => ( false === $error )
13908 );
13909
13910 if ( false !== $error ) {
13911 $result['error'] = $fs->apply_filters( 'opt_in_error_message', $error );
13912 } else {
13913 if ( $fs->is_addon() || $fs->has_addons() ) {
13914 /**
13915 * Purge the valid user licenses cache so that when the "Account" or the "Add-Ons" page is loaded,
13916 * an updated valid user licenses collection will be fetched from the server which is used to also
13917 * update the account add-ons (add-ons the user has licenses for).
13918 *
13919 * @author Leo Fajardo (@leorw)
13920 * @since 2.2.4
13921 */
13922 $fs->purge_valid_user_licenses_cache();
13923 }
13924
13925 $result['next_page'] = $next_page;
13926 }
13927
13928 return $result;
13929 }
13930
13931 /**
13932 * @author Leo Fajardo (@leorw)
13933 * @since 2.3.2
13934 *
13935 * @return array {
13936 * @key string Product slug.
13937 * @value array {
13938 * @property FS_Site $site
13939 * @property FS_Plugin_License $license
13940 * }
13941 * }
13942 */
13943 private function get_parent_and_addons_installs_info() {
13944 $fs = $this->is_addon() ?
13945 $this->get_parent_instance() :
13946 $this;
13947
13948 $installed_addons_ids = array();
13949
13950 $installed_addons_instances = $fs->get_installed_addons();
13951 foreach ( $installed_addons_instances as $instance ) {
13952 $installed_addons_ids[] = $instance->get_id();
13953 }
13954
13955 $addons_ids = array_unique( array_merge(
13956 $installed_addons_ids,
13957 $fs->get_updated_account_addons()
13958 ) );
13959
13960 // Add parent product info.
13961 $installs_info_by_slug_map = array(
13962 $fs->get_slug() => array(
13963 'install' => $fs->get_site(),
13964 'license' => $fs->_get_license()
13965 )
13966 );
13967
13968 foreach ( $addons_ids as $addon_id ) {
13969 $is_installed = isset( $installed_addons_ids_map[ $addon_id ] );
13970
13971 $addon_info = $fs->_get_addon_info( $addon_id, $is_installed );
13972
13973 if ( ! isset( $addon_info['is_connected'] ) || ! $addon_info['is_connected'] ) {
13974 // Add-on is not associated with an install entity.
13975 continue;
13976 }
13977
13978 $installs_info_by_slug_map[ $addon_info['slug'] ] = array(
13979 'install' => $addon_info['site'],
13980 'license' => isset( $addon_info['license'] ) ?
13981 $addon_info['license'] :
13982 null
13983 );
13984 }
13985
13986 return $installs_info_by_slug_map;
13987 }
13988
13989 /**
13990 * @author Leo Fajardo (@leorw)
13991 * @since 1.2.3.1
13992 */
13993 function _network_activate_ajax_action() {
13994 $this->_logger->entrance();
13995
13996 $this->check_ajax_referer( 'network_activate' );
13997
13998 $plugin_id = fs_request_get( 'module_id', '', 'post' );
13999 $fs = ( $plugin_id == $this->_module_id ) ?
14000 $this :
14001 $this->get_addon_instance( $plugin_id );
14002
14003 $error = false;
14004
14005 $sites = fs_request_get( 'sites', array(), 'post' );
14006 if ( is_array( $sites ) && ! empty( $sites ) ) {
14007 $sites_by_action = array(
14008 'allow' => array(),
14009 'delegate' => array(),
14010 'skip' => array()
14011 );
14012
14013 foreach ( $sites as $site ) {
14014 $sites_by_action[ $site['action'] ][] = $site;
14015 }
14016
14017 $total_sites = count( $sites );
14018 $total_sites_to_delegate = count( $sites_by_action['delegate'] );
14019
14020 $next_page = '';
14021
14022 $has_any_install = fs_request_get_bool( 'has_any_install' );
14023
14024 if ( $total_sites === $total_sites_to_delegate &&
14025 ! $this->is_network_upgrade_mode() &&
14026 ! $has_any_install
14027 ) {
14028 $this->delegate_connection();
14029 } else {
14030 if ( ! empty( $sites_by_action['delegate'] ) ) {
14031 $this->delegate_connection( self::get_sites_blog_ids( $sites_by_action['delegate'] ) );
14032 }
14033
14034 if ( ! empty( $sites_by_action['skip'] ) ) {
14035 $this->skip_connection( self::get_sites_blog_ids( $sites_by_action['skip'] ) );
14036 }
14037
14038 if ( empty( $sites_by_action['allow'] ) ) {
14039 if ( $has_any_install ) {
14040 $first_install = $fs->find_first_install();
14041
14042 if ( ! is_null( $first_install ) ) {
14043 $fs->_site = $first_install['install'];
14044 $fs->_storage->network_install_blog_id = $first_install['blog_id'];
14045
14046 $fs->_user = self::_get_user_by_id( $fs->_site->user_id );
14047 $fs->_storage->network_user_id = $fs->_user->id;
14048 }
14049 }
14050 } else {
14051 if ( ! $fs->is_registered() || ! $this->_is_network_active ) {
14052 $next_page = $fs->opt_in(
14053 false,
14054 false,
14055 false,
14056 false,
14057 false,
14058 false,
14059 false,
14060 fs_request_get_bool( 'is_marketing_allowed', null ),
14061 $sites_by_action['allow']
14062 );
14063 } else {
14064 $next_page = $fs->install_with_user(
14065 $this->get_network_user(),
14066 false,
14067 false,
14068 false,
14069 true,
14070 $sites_by_action['allow']
14071 );
14072 }
14073
14074 if ( is_object( $next_page ) && isset( $next_page->error ) ) {
14075 $error = $next_page->error;
14076 }
14077 }
14078 }
14079
14080 if ( empty( $next_page ) ) {
14081 $next_page = $this->get_after_activation_url( 'after_network_activation_url' );
14082 }
14083 } else {
14084 $error = $this->get_text_inline( 'Invalid site details collection.', 'invalid_site_details_collection' );
14085 }
14086
14087 $result = array(
14088 'success' => ( false === $error )
14089 );
14090
14091 if ( false !== $error ) {
14092 $result['error'] = $error;
14093 } else {
14094 $result['next_page'] = $next_page;
14095 }
14096
14097 echo json_encode( $result );
14098
14099 exit;
14100 }
14101
14102 /**
14103 * Billing update AJAX callback.
14104 *
14105 * @author Vova Feldman (@svovaf)
14106 * @since 1.2.1.5
14107 */
14108 function _update_billing_ajax_action() {
14109 $this->_logger->entrance();
14110
14111 $this->check_ajax_referer( 'update_billing' );
14112
14113 if ( ! $this->is_user_admin() ) {
14114 // Only for admins.
14115 self::shoot_ajax_failure();
14116 }
14117
14118 $billing = fs_request_get( 'billing' );
14119
14120 $api = $this->get_api_user_scope();
14121 $result = $api->call( '/billing.json', 'put', array_merge( $billing, array(
14122 'plugin_id' => $this->get_parent_id(),
14123 ) ) );
14124
14125 if ( ! $this->is_api_result_entity( $result ) ) {
14126 self::shoot_ajax_failure();
14127 }
14128
14129 // Purge cached billing.
14130 $this->get_api_user_scope()->purge_cache( 'billing.json' );
14131
14132 self::shoot_ajax_success();
14133 }
14134
14135 /**
14136 * Trial start for anonymous users (AJAX callback).
14137 *
14138 * @author Vova Feldman (@svovaf)
14139 * @since 1.2.1.5
14140 */
14141 function _start_trial_ajax_action() {
14142 $this->_logger->entrance();
14143
14144 $this->check_ajax_referer( 'start_trial' );
14145
14146 if ( ! $this->is_user_admin() ) {
14147 // Only for admins.
14148 self::shoot_ajax_failure();
14149 }
14150
14151 $trial_data = fs_request_get( 'trial' );
14152
14153 $next_page = $this->opt_in(
14154 false,
14155 false,
14156 false,
14157 false,
14158 false,
14159 $trial_data['plan_id']
14160 );
14161
14162 if ( is_object( $next_page ) && $this->is_api_error( $next_page ) ) {
14163 self::shoot_ajax_failure(
14164 isset( $next_page->error ) ?
14165 $next_page->error->message :
14166 var_export( $next_page, true )
14167 );
14168 }
14169
14170 $this->shoot_ajax_success( array(
14171 'next_page' => $next_page,
14172 ) );
14173 }
14174
14175 /**
14176 * @author Leo Fajardo (@leorw)
14177 * @since 1.2.0
14178 */
14179 function _resend_license_key_ajax_action() {
14180 $this->_logger->entrance();
14181
14182 $this->check_ajax_referer( 'resend_license_key' );
14183
14184 $email_address = sanitize_email( trim( fs_request_get( 'email', '', 'post' ) ) );
14185
14186 if ( empty( $email_address ) ) {
14187 exit;
14188 }
14189
14190 $error = false;
14191
14192 $api = $this->get_api_plugin_scope();
14193 $result = $api->call( '/licenses/resend.json', 'post',
14194 array(
14195 'email' => $email_address,
14196 'url' => home_url(),
14197 )
14198 );
14199
14200 if ( is_object( $result ) && isset( $result->error ) ) {
14201 $error = $result->error;
14202
14203 if ( in_array( $error->code, array( 'invalid_email', 'no_user' ) ) ) {
14204 $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' );
14205 } else if ( 'no_license' === $error->code ) {
14206 $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' );
14207 } else {
14208 $error = $error->message;
14209 }
14210 }
14211
14212 $licenses = array(
14213 'success' => ( false === $error )
14214 );
14215
14216 if ( false !== $error ) {
14217 $licenses['error'] = sprintf( '%s... %s', $this->get_text_x_inline( 'Oops', 'exclamation', 'oops' ), strtolower( $error ) );
14218 }
14219
14220 echo json_encode( $licenses );
14221
14222 exit;
14223 }
14224
14225 /**
14226 * @author Vova Feldman (@svovaf)
14227 * @since 1.2.1.8
14228 *
14229 * @var string
14230 */
14231 private static $_pagenow;
14232
14233 /**
14234 * Get current page or the referer if executing a WP AJAX request.
14235 *
14236 * @author Vova Feldman (@svovaf)
14237 * @since 1.2.1.8
14238 *
14239 * @return string
14240 */
14241 static function get_current_page() {
14242 if ( ! isset( self::$_pagenow ) ) {
14243 global $pagenow;
14244 if ( empty( $pagenow ) && is_admin() && is_multisite() ) {
14245 /**
14246 * It appears that `$pagenow` is not yet initialized in some network admin pages when this method
14247 * is called, so initialize it here using some pieces of code from `wp-includes/vars.php`.
14248 *
14249 * @author Leo Fajardo (@leorw)
14250 * @since 2.2.3
14251 */
14252 if ( is_network_admin() ) {
14253 preg_match( '#/wp-admin/network/?(.*?)$#i', $_SERVER['PHP_SELF'], $self_matches );
14254 } else if ( is_user_admin() ) {
14255 preg_match( '#/wp-admin/user/?(.*?)$#i', $_SERVER['PHP_SELF'], $self_matches );
14256 } else {
14257 preg_match( '#/wp-admin/?(.*?)$#i', $_SERVER['PHP_SELF'], $self_matches );
14258 }
14259
14260 $pagenow = $self_matches[1];
14261 $pagenow = trim( $pagenow, '/' );
14262 $pagenow = preg_replace( '#\?.*?$#', '', $pagenow );
14263 if ( '' === $pagenow || 'index' === $pagenow || 'index.php' === $pagenow ) {
14264 $pagenow = 'index.php';
14265 } else {
14266 preg_match( '#(.*?)(/|$)#', $pagenow, $self_matches );
14267 $pagenow = strtolower( $self_matches[1] );
14268 if ( '.php' !== substr($pagenow, -4, 4) )
14269 $pagenow .= '.php'; // for Options +Multiviews: /wp-admin/themes/index.php (themes.php is queried)
14270 }
14271 }
14272
14273 self::$_pagenow = $pagenow;
14274
14275 if ( self::is_ajax() &&
14276 'admin-ajax.php' === $pagenow
14277 ) {
14278 $referer = fs_get_raw_referer();
14279
14280 if ( is_string( $referer ) ) {
14281 $parts = explode( '?', $referer );
14282
14283 self::$_pagenow = basename( $parts[0] );
14284 }
14285 }
14286 }
14287
14288 return self::$_pagenow;
14289 }
14290
14291 /**
14292 * Helper method to check if user in the plugins page.
14293 *
14294 * @author Vova Feldman (@svovaf)
14295 * @since 1.2.1.5
14296 *
14297 * @return bool
14298 */
14299 static function is_plugins_page() {
14300 return ( 'plugins.php' === self::get_current_page() );
14301 }
14302
14303 /**
14304 * @author Leo Fajardo (@leorw)
14305 * @since 2.2.3
14306 *
14307 * @return bool
14308 */
14309 static function is_plugin_install_page() {
14310 return ( 'plugin-install.php' === self::get_current_page() );
14311 }
14312
14313 /**
14314 * @author Leo Fajardo (@leorw)
14315 * @since 2.0.2
14316 *
14317 * @return bool
14318 */
14319 static function is_updates_page() {
14320 return ( 'update-core.php' === self::get_current_page() );
14321 }
14322
14323 /**
14324 * Helper method to check if user in the themes page.
14325 *
14326 * @author Vova Feldman (@svovaf)
14327 * @since 1.2.2.6
14328 *
14329 * @return bool
14330 */
14331 static function is_themes_page() {
14332 return ( 'themes.php' === self::get_current_page() );
14333 }
14334
14335 #----------------------------------------------------------------------------------
14336 #region Affiliation
14337 #----------------------------------------------------------------------------------
14338
14339 /**
14340 * @author Leo Fajardo (@leorw)
14341 * @since 1.2.3
14342 *
14343 * @return bool
14344 */
14345 function has_affiliate_program() {
14346 if ( ! is_object( $this->_plugin ) ) {
14347 return false;
14348 }
14349
14350 return $this->_plugin->has_affiliate_program();
14351 }
14352
14353 /**
14354 * Get Plugin ID under which we will track affiliate application.
14355 *
14356 * This could either be the Bundle ID or the main plugin ID.
14357 *
14358 * @return number Bundle ID if developer has provided one, else the main plugin ID.
14359 */
14360 private function get_plugin_id_for_affiliate_terms() {
14361 return $this->has_bundle_context() ?
14362 $this->get_bundle_id() :
14363 $this->_plugin->id;
14364 }
14365
14366 /**
14367 * @author Leo Fajardo (@leorw)
14368 * @since 1.2.4
14369 */
14370 private function fetch_affiliate_terms() {
14371 if ( ! is_object( $this->plugin_affiliate_terms ) ) {
14372 /**
14373 * In case we have a bundle set in SDK configuration, we would like to use that for affiliates, not the main plugin.
14374 */
14375 $plugins_api = $this->has_bundle_context() ?
14376 $this->get_api_bundle_scope() :
14377 $this->get_api_plugin_scope();
14378
14379 $affiliate_terms = $plugins_api->get( '/aff.json?type=affiliation', false );
14380
14381 /**
14382 * 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.
14383 */
14384 if ( ! $this->is_api_result_entity( $affiliate_terms ) ) {
14385 return;
14386 }
14387
14388 $this->plugin_affiliate_terms = new FS_AffiliateTerms( $affiliate_terms );
14389 }
14390 }
14391
14392 /**
14393 * @author Leo Fajardo (@leorw)
14394 * @since 1.2.4
14395 */
14396 private function fetch_affiliate_and_custom_terms() {
14397 if ( ! empty( $this->_storage->affiliate_application_data ) ) {
14398 $application_data = $this->_storage->affiliate_application_data;
14399 $flush = ( ! isset( $application_data['status'] ) || 'pending' === $application_data['status'] );
14400
14401 $plugin_id_for_affiliate = $this->get_plugin_id_for_affiliate_terms();
14402
14403 $users_api = $this->get_api_user_scope();
14404 $result = $users_api->get( "/plugins/{$plugin_id_for_affiliate}/aff/{$this->plugin_affiliate_terms->id}/affiliates.json", $flush );
14405 if ( $this->is_api_result_object( $result, 'affiliates' ) ) {
14406 if ( ! empty( $result->affiliates ) ) {
14407 $affiliate = new FS_Affiliate( $result->affiliates[0] );
14408
14409 if ( ! isset( $application_data['status'] ) || $application_data['status'] !== $affiliate->status ) {
14410 $application_data['status'] = $affiliate->status;
14411 $this->_storage->affiliate_application_data = $application_data;
14412 }
14413
14414 if ( $affiliate->is_using_custom_terms ) {
14415 $affiliate_terms = $users_api->get( "/plugins/{$this->_plugin->id}/affiliates/{$affiliate->id}/aff/{$affiliate->custom_affiliate_terms_id}.json", $flush );
14416 if ( $this->is_api_result_entity( $affiliate_terms ) ) {
14417 $this->custom_affiliate_terms = new FS_AffiliateTerms( $affiliate_terms );
14418 }
14419 }
14420
14421 $this->affiliate = $affiliate;
14422 }
14423 }
14424 }
14425 }
14426
14427 /**
14428 * @author Leo Fajardo (@leorw)
14429 * @since 1.2.3
14430 */
14431 private function fetch_affiliate_and_terms() {
14432 $this->_logger->entrance();
14433
14434 $this->fetch_affiliate_terms();
14435 $this->fetch_affiliate_and_custom_terms();
14436 }
14437
14438 /**
14439 * @author Leo Fajardo (@leorw)
14440 * @since 1.2.3
14441 *
14442 * @return FS_Affiliate
14443 */
14444 function get_affiliate() {
14445 return $this->affiliate;
14446 }
14447
14448
14449 /**
14450 * @author Leo Fajardo (@leorw)
14451 * @since 1.2.3
14452 *
14453 * @return FS_AffiliateTerms
14454 */
14455 function get_affiliate_terms() {
14456 return is_object( $this->custom_affiliate_terms ) ?
14457 $this->custom_affiliate_terms :
14458 $this->plugin_affiliate_terms;
14459 }
14460
14461 /**
14462 * @author Leo Fajardo (@leorw)
14463 * @since 1.2.3
14464 */
14465 function _submit_affiliate_application() {
14466 $this->_logger->entrance();
14467
14468 $this->check_ajax_referer( 'submit_affiliate_application' );
14469
14470 if ( ! $this->is_user_admin() ) {
14471 // Only for admins.
14472 self::shoot_ajax_failure();
14473 }
14474
14475 $affiliate = fs_request_get( 'affiliate' );
14476
14477 if ( empty( $affiliate['promotion_methods'] ) ) {
14478 unset( $affiliate['promotion_methods'] );
14479 }
14480
14481 if ( ! empty( $affiliate['additional_domains'] ) ) {
14482 $affiliate['additional_domains'] = array_unique( $affiliate['additional_domains'] );
14483 }
14484
14485 if ( ! $this->is_registered() ) {
14486 $email_address = isset( $affiliate['email'] ) ? $affiliate['email'] : '';
14487
14488 if ( ! is_email( $email_address ) ) {
14489 self::shoot_ajax_failure('Invalid email address.');
14490 }
14491
14492 // Opt in but don't track usage.
14493 $next_page = $this->opt_in(
14494 $email_address,
14495 false,
14496 false,
14497 false,
14498 false,
14499 false,
14500 true
14501 );
14502
14503 if ( is_object( $next_page ) && $this->is_api_error( $next_page ) ) {
14504 self::shoot_ajax_failure(
14505 isset( $next_page->error ) ?
14506 $next_page->error->message :
14507 var_export( $next_page, true )
14508 );
14509 } else if ( $this->is_pending_activation() ) {
14510 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' ) );
14511 }
14512 }
14513
14514 $this->fetch_affiliate_terms();
14515
14516 $plugin_id_for_affiliate = $this->get_plugin_id_for_affiliate_terms();
14517
14518 $api = $this->get_api_user_scope();
14519 $result = $api->call(
14520 ( "/plugins/{$plugin_id_for_affiliate}/aff/{$this->plugin_affiliate_terms->id}/affiliates.json" ),
14521 'post',
14522 $affiliate
14523 );
14524
14525 if ( $this->is_api_error( $result ) ) {
14526 self::shoot_ajax_failure(
14527 isset( $result->error ) ?
14528 $result->error->message :
14529 var_export( $result, true )
14530 );
14531 } else {
14532 if ( $this->_admin_notices->has_sticky( 'affiliate_program' ) ) {
14533 $this->_admin_notices->remove_sticky( 'affiliate_program' );
14534 }
14535
14536 $affiliate_application_data = array(
14537 'status' => 'pending',
14538 'stats_description' => $affiliate['stats_description'],
14539 'promotion_method_description' => $affiliate['promotion_method_description'],
14540 );
14541
14542 if ( ! empty( $affiliate['promotion_methods'] ) ) {
14543 $affiliate_application_data['promotion_methods'] = $affiliate['promotion_methods'];
14544 }
14545
14546 if ( ! empty( $affiliate['domain'] ) ) {
14547 $affiliate_application_data['domain'] = $affiliate['domain'];
14548 }
14549
14550 if ( ! empty( $affiliate['additional_domains'] ) ) {
14551 $affiliate_application_data['additional_domains'] = $affiliate['additional_domains'];
14552 }
14553
14554 $this->_storage->affiliate_application_data = $affiliate_application_data;
14555 }
14556
14557 // Purge cached affiliate.
14558 $api->purge_cache( 'affiliate.json' );
14559
14560 self::shoot_ajax_success( $result );
14561 }
14562
14563 /**
14564 * @author Leo Fajardo (@leorw)
14565 * @since 1.2.3
14566 *
14567 * @return array|null
14568 */
14569 function get_affiliate_application_data() {
14570 if ( empty( $this->_storage->affiliate_application_data ) ) {
14571 return null;
14572 }
14573
14574 return $this->_storage->affiliate_application_data;
14575 }
14576
14577 #endregion Affiliation ------------------------------------------------------------
14578
14579 #----------------------------------------------------------------------------------
14580 #region URL Generators
14581 #----------------------------------------------------------------------------------
14582
14583 /**
14584 * Alias to pricing_url().
14585 *
14586 * @author Vova Feldman (@svovaf)
14587 * @since 1.0.2
14588 *
14589 * @uses pricing_url()
14590 *
14591 * @param string $period Billing cycle
14592 * @param bool $is_trial
14593 *
14594 * @return string
14595 */
14596 function get_upgrade_url( $period = WP_FS__PERIOD_ANNUALLY, $is_trial = false ) {
14597 return $this->pricing_url( $period, $is_trial );
14598 }
14599
14600 /**
14601 * @author Vova Feldman (@svovaf)
14602 * @since 1.0.9
14603 *
14604 * @uses get_upgrade_url()
14605 *
14606 * @return string
14607 */
14608 function get_trial_url() {
14609 return $this->get_upgrade_url( WP_FS__PERIOD_ANNUALLY, true );
14610 }
14611
14612 /**
14613 * @author Leo Fajardo (@leorw)
14614 * @since 2.1.4
14615 *
14616 * @param string $new_version
14617 *
14618 * @return string
14619 */
14620 function version_upgrade_checkout_link( $new_version ) {
14621 if ( ! is_object( $this->_license ) ) {
14622 $url = $this->pricing_url();
14623
14624 $purchase_license_text = $this->get_text_inline( 'Buy a license now', 'buy-license-now' );
14625 } else {
14626 $subscription = $this->_get_subscription( $this->_license->id );
14627
14628 $url = $this->checkout_url(
14629 is_object( $subscription ) ?
14630 ( 1 == $subscription->billing_cycle ? WP_FS__PERIOD_MONTHLY : WP_FS__PERIOD_ANNUALLY ) :
14631 WP_FS__PERIOD_LIFETIME,
14632 false,
14633 array( 'licenses' => $this->_license->quota )
14634 );
14635
14636 $purchase_license_text = $this->get_text_inline( 'Renew your license now', 'renew-license-now' );
14637 }
14638
14639 return sprintf(
14640 $this->get_text_inline( '%s to access version %s security & feature updates, and support.', 'x-for-updates-and-support' ),
14641 sprintf(
14642 '<a href="%s">%s</a>',
14643 $this->apply_filters( 'update_notice_checkout_url', $url ),
14644 $purchase_license_text
14645 ),
14646 $new_version
14647 );
14648 }
14649
14650 /**
14651 * Plugin's pricing URL.
14652 *
14653 * @author Vova Feldman (@svovaf)
14654 * @since 1.0.4
14655 *
14656 * @param string $billing_cycle Billing cycle
14657 *
14658 * @param bool $is_trial
14659 *
14660 * @return string
14661 */
14662 function pricing_url( $billing_cycle = WP_FS__PERIOD_ANNUALLY, $is_trial = false ) {
14663 $this->_logger->entrance();
14664
14665 $params = array(
14666 'billing_cycle' => $billing_cycle
14667 );
14668
14669 if ( $is_trial ) {
14670 $params['trial'] = 'true';
14671 }
14672
14673 $url = $this->is_addon() ?
14674 $this->_parent->addon_url( $this->_slug ) :
14675 $this->_get_admin_page_url( 'pricing', $params );
14676
14677 return $this->get_pricing_url_with_filter( $url );
14678 }
14679
14680 /**
14681 * Retrieves the filtered pricing URL.
14682 *
14683 * @author Leo Fajardo (@leorw)
14684 * @since 2.7.4
14685 *
14686 * @param string $url
14687 *
14688 * @return string
14689 */
14690 private function get_pricing_url_with_filter( $url ) {
14691 return $this->apply_filters( 'pricing_url', $url );
14692 }
14693
14694 /**
14695 * Checkout page URL.
14696 *
14697 * @author Vova Feldman (@svovaf)
14698 * @since 1.0.6
14699 *
14700 * @param string $billing_cycle Billing cycle
14701 * @param bool $is_trial
14702 * @param array $extra (optional) Extra parameters, override other query params.
14703 * @param bool|null $network
14704 *
14705 * @return string
14706 */
14707 function checkout_url(
14708 $billing_cycle = WP_FS__PERIOD_ANNUALLY,
14709 $is_trial = false,
14710 $extra = array(),
14711 $network = null
14712 ) {
14713 $this->_logger->entrance();
14714
14715 $params = array(
14716 'checkout' => 'true',
14717 'billing_cycle' => $billing_cycle,
14718 );
14719
14720 if ( $is_trial ) {
14721 $params['trial'] = 'true';
14722 }
14723
14724 /**
14725 * Params in extra override other params.
14726 */
14727 $params = array_merge( $params, $extra );
14728
14729 return $this->apply_filters( 'checkout_url', $this->_get_admin_page_url( 'pricing', $params, $network ) );
14730 }
14731
14732 /**
14733 * Add-on checkout URL.
14734 *
14735 * @author Vova Feldman (@svovaf)
14736 * @since 1.1.7
14737 *
14738 * @param number $addon_id
14739 * @param number $pricing_id
14740 * @param string $billing_cycle
14741 * @param bool $is_trial
14742 * @param bool|null $network
14743 *
14744 * @return string
14745 */
14746 function addon_checkout_url(
14747 $addon_id,
14748 $pricing_id,
14749 $billing_cycle = WP_FS__PERIOD_ANNUALLY,
14750 $is_trial = false,
14751 $network = null
14752 ) {
14753 return $this->checkout_url( $billing_cycle, $is_trial, array(
14754 'plugin_id' => $addon_id,
14755 'pricing_id' => $pricing_id,
14756 ), $network );
14757 }
14758
14759 #endregion
14760
14761 #endregion ------------------------------------------------------------------
14762
14763 /**
14764 * Check if plugin has any add-ons.
14765 *
14766 * @author Vova Feldman (@svovaf)
14767 * @since 1.0.5
14768 *
14769 * @since 1.1.7.3 Base logic only on the parameter provided by the developer in the init function.
14770 *
14771 * @return bool
14772 */
14773 function has_addons() {
14774 $this->_logger->entrance();
14775
14776 return $this->_has_addons;
14777 }
14778
14779 /**
14780 * Check if plugin can work in anonymous mode.
14781 *
14782 * @author Vova Feldman (@svovaf)
14783 * @since 1.0.9
14784 *
14785 * @return bool
14786 *
14787 * @deprecated Please use is_enable_anonymous() instead.
14788 */
14789 function enable_anonymous() {
14790 return $this->_enable_anonymous;
14791 }
14792
14793 /**
14794 * Check if plugin can work in anonymous mode.
14795 *
14796 * @author Vova Feldman (@svovaf)
14797 * @since 1.1.9
14798 *
14799 * @return bool
14800 */
14801 function is_enable_anonymous() {
14802 return $this->_enable_anonymous;
14803 }
14804
14805 /**
14806 * Check if plugin is premium only (no free plans).
14807 *
14808 * @author Vova Feldman (@svovaf)
14809 * @since 1.1.9
14810 *
14811 * @return bool
14812 */
14813 function is_only_premium() {
14814 return $this->_is_premium_only;
14815 }
14816
14817 /**
14818 * Checks if the plugin's type is "plugin". The other type is "theme".
14819 *
14820 * @author Leo Fajardo (@leorw)
14821 * @since 1.2.2
14822 *
14823 * @return bool
14824 */
14825 function is_plugin() {
14826 return ( WP_FS__MODULE_TYPE_PLUGIN === $this->_module_type );
14827 }
14828
14829 /**
14830 * @author Leo Fajardo (@leorw)
14831 * @since 1.2.2
14832 *
14833 * @return string
14834 */
14835 function get_module_type() {
14836 if ( ! isset( $this->_module_type ) ) {
14837 $id_slug_type_path_map = self::$_accounts->get_option( 'id_slug_type_path_map', array() );
14838 $this->_module_type = $id_slug_type_path_map[ $this->_module_id ]['type'];
14839 }
14840
14841 return $this->_module_type;
14842 }
14843
14844 /**
14845 * @author Leo Fajardo (@leorw)
14846 * @since 1.2.2
14847 *
14848 * @return string
14849 */
14850 function get_plugin_main_file_path() {
14851 return $this->_plugin_main_file_path;
14852 }
14853
14854 /**
14855 * Check if module has a premium code version.
14856 *
14857 * Serviceware module might be freemium without any
14858 * premium code version, where the paid features
14859 * are all part of the service.
14860 *
14861 * @author Vova Feldman (@svovaf)
14862 * @since 1.2.1.6
14863 *
14864 * @return bool
14865 */
14866 function has_premium_version() {
14867 return $this->_has_premium_version;
14868 }
14869
14870 /**
14871 * Check if feature supported with current site's plan.
14872 *
14873 * @author Vova Feldman (@svovaf)
14874 * @since 1.0.1
14875 *
14876 * @todo IMPLEMENT
14877 *
14878 * @param number $feature_id
14879 *
14880 * @throws Exception
14881 */
14882 function is_feature_supported( $feature_id ) {
14883 throw new Exception( 'not implemented' );
14884 }
14885
14886 /**
14887 * @author Vova Feldman (@svovaf)
14888 * @since 1.0.1
14889 *
14890 * @return bool Is running in SSL/HTTPS
14891 */
14892 function is_ssl() {
14893 return WP_FS__IS_HTTPS;
14894 }
14895
14896 /**
14897 * @author Vova Feldman (@svovaf)
14898 * @since 1.0.9
14899 *
14900 * @return bool Is running in AJAX call.
14901 *
14902 * @link http://wordpress.stackexchange.com/questions/70676/how-to-check-if-i-am-in-admin-ajax
14903 */
14904 static function is_ajax() {
14905 return ( defined( 'DOING_AJAX' ) && DOING_AJAX );
14906 }
14907
14908 /**
14909 * Check if it's an AJAX call targeted for the current module.
14910 *
14911 * @author Vova Feldman (@svovaf)
14912 * @since 1.2.0
14913 *
14914 * @param array|string $actions Collection of AJAX actions.
14915 *
14916 * @return bool
14917 */
14918 function is_ajax_action( $actions ) {
14919 // Verify it's an ajax call.
14920 if ( ! self::is_ajax() ) {
14921 return false;
14922 }
14923
14924 // Verify the call is relevant for the plugin.
14925 if ( $this->_module_id != fs_request_get( 'module_id' ) ) {
14926 return false;
14927 }
14928
14929 // Verify it's one of the specified actions.
14930 if ( is_string( $actions ) ) {
14931 $actions = explode( ',', $actions );
14932 }
14933
14934 if ( is_array( $actions ) && 0 < count( $actions ) ) {
14935 $ajax_action = fs_request_get( 'action' );
14936
14937 foreach ( $actions as $action ) {
14938 if ( $ajax_action === $this->get_action_tag( $action ) ) {
14939 return true;
14940 }
14941 }
14942 }
14943
14944 return false;
14945 }
14946
14947 /**
14948 * Check if it's an AJAX call targeted for current request.
14949 *
14950 * @author Vova Feldman (@svovaf)
14951 * @since 1.2.0
14952 *
14953 * @param array|string $actions Collection of AJAX actions.
14954 * @param number|null $module_id
14955 *
14956 * @return bool
14957 */
14958 static function is_ajax_action_static( $actions, $module_id = null ) {
14959 // Verify it's an ajax call.
14960 if ( ! self::is_ajax() ) {
14961 return false;
14962 }
14963
14964
14965 if ( ! empty( $module_id ) ) {
14966 // Verify the call is relevant for the plugin.
14967 if ( $module_id != fs_request_get( 'module_id' ) ) {
14968 return false;
14969 }
14970 }
14971
14972 // Verify it's one of the specified actions.
14973 if ( is_string( $actions ) ) {
14974 $actions = explode( ',', $actions );
14975 }
14976
14977 if ( is_array( $actions ) && 0 < count( $actions ) ) {
14978 $ajax_action = fs_request_get( 'action' );
14979
14980 foreach ( $actions as $action ) {
14981 if ( $ajax_action === self::get_ajax_action_static( $action, $module_id ) ) {
14982 return true;
14983 }
14984 }
14985 }
14986
14987 return false;
14988 }
14989
14990 /**
14991 * @author Vova Feldman (@svovaf)
14992 * @since 1.1.7
14993 *
14994 * @return bool
14995 */
14996 static function is_cron() {
14997 return ( defined( 'DOING_CRON' ) && DOING_CRON );
14998 }
14999
15000 /**
15001 * @author Leo Fajardo (@leorw)
15002 * @since 2.5.0
15003 *
15004 * @return bool
15005 */
15006 static function is_admin_post() {
15007 return ( 'admin-post.php' === self::get_current_page() );
15008 }
15009
15010 /**
15011 * Check if a real user is visiting the admin dashboard.
15012 *
15013 * @author Vova Feldman (@svovaf)
15014 * @since 1.1.7
15015 *
15016 * @return bool
15017 */
15018 function is_user_in_admin() {
15019 return (
15020 is_admin() &&
15021 ! self::is_ajax() &&
15022 ! self::is_cron() &&
15023 ! self::is_admin_post()
15024 );
15025 }
15026
15027 /**
15028 * Check if a real user is in the customizer view.
15029 *
15030 * @author Vova Feldman (@svovaf)
15031 * @since 1.2.2.7
15032 *
15033 * @return bool
15034 */
15035 static function is_customizer() {
15036 return is_customize_preview();
15037 }
15038
15039 /**
15040 * Check if running in HTTPS and if site's plan matching the specified plan.
15041 *
15042 * @param string $plan
15043 * @param bool $exact
15044 *
15045 * @return bool
15046 */
15047 function is_ssl_and_plan( $plan, $exact = false ) {
15048 return ( $this->is_ssl() && $this->is_plan( $plan, $exact ) );
15049 }
15050
15051 /**
15052 * Construct plugin's settings page URL.
15053 *
15054 * @author Vova Feldman (@svovaf)
15055 * @since 1.0.4
15056 *
15057 * @param string $page
15058 * @param array $params
15059 * @param bool|null $network
15060 *
15061 * @return string
15062 */
15063 function _get_admin_page_url( $page = '', $params = array(), $network = null ) {
15064 if ( is_null( $network ) ) {
15065 $network = (
15066 $this->_is_network_active &&
15067 ( fs_is_network_admin() || ! $this->is_delegated_connection() )
15068 );
15069 }
15070
15071 if ( 0 < count( $params ) ) {
15072 foreach ( $params as $k => $v ) {
15073 $params[ $k ] = urlencode( $v );
15074 }
15075 }
15076
15077 $page_param = $this->_menu->get_slug( $page );
15078
15079 if ( empty( $page ) &&
15080 // Show the opt-in as an overlay for free wp.org themes or themes without any settings page.
15081 $this->show_opt_in_on_themes_page()
15082 ) {
15083 $params[ $this->get_unique_affix() . '_show_optin' ] = 'true';
15084
15085 return add_query_arg(
15086 $params,
15087 $this->admin_url( 'themes.php', 'admin', $network )
15088 );
15089 }
15090
15091 if ( ! $this->has_settings_menu() ) {
15092 if ( ! empty( $page ) ) {
15093 // Module doesn't have a setting page, but since the request is for
15094 // a specific Freemius page, use the admin.php path.
15095 return add_query_arg( array_merge( $params, array(
15096 'page' => $page_param,
15097 ) ), $this->admin_url( 'admin.php', 'admin', $network ) );
15098 } else {
15099 if ( $this->is_activation_mode() ) {
15100 /**
15101 * @author Vova Feldman
15102 * @since 1.2.1.6
15103 *
15104 * If plugin doesn't have a settings page, create one for the opt-in screen.
15105 */
15106 return add_query_arg( array_merge( $params, array(
15107 'page' => $this->_slug,
15108 ) ), $this->admin_url( 'admin.php', 'admin', $network ) );
15109 } else {
15110 // Plugin without a settings page.
15111 return add_query_arg(
15112 $params,
15113 $this->admin_url( 'plugins.php', 'admin', $network )
15114 );
15115 }
15116 }
15117 }
15118
15119 // Module has a submenu settings page.
15120 if ( ! $this->_menu->is_top_level() ) {
15121 $parent_slug = $this->_menu->get_parent_slug();
15122 $menu_file = ( false !== strpos( $parent_slug, '.php' ) ) ?
15123 $parent_slug :
15124 'admin.php';
15125
15126 return add_query_arg( array_merge( $params, array(
15127 'page' => $page_param,
15128 ) ), $this->admin_url( $menu_file, 'admin', $network ) );
15129 }
15130
15131 // Module has a top level CPT settings page.
15132 if ( $this->_menu->is_cpt() ) {
15133 if ( empty( $page ) && $this->is_activation_mode() ) {
15134 return add_query_arg( array_merge( $params, array(
15135 'page' => $page_param
15136 ) ), $this->admin_url( 'admin.php', 'admin', $network ) );
15137 } else {
15138 if ( ! empty( $page ) ) {
15139 $params['page'] = $page_param;
15140 }
15141
15142 return add_query_arg(
15143 $params,
15144 $this->admin_url( $this->_menu->get_raw_slug(), 'admin', $network )
15145 );
15146 }
15147 }
15148
15149 // Module has a custom top level settings page.
15150 return add_query_arg( array_merge( $params, array(
15151 'page' => $page_param,
15152 ) ), $this->admin_url( 'admin.php', 'admin', $network ) );
15153 }
15154
15155 #--------------------------------------------------------------------------------
15156 #region Multisite
15157 #--------------------------------------------------------------------------------
15158
15159 /**
15160 * @author Leo Fajardo (@leorw)
15161 * @since 2.0.0
15162 *
15163 * @return bool
15164 */
15165 function is_network_active() {
15166 return $this->_is_network_active;
15167 }
15168
15169 /**
15170 * Delegate activation for the given sites in the network (or all sites if `null`) to site admins.
15171 *
15172 * @author Leo Fajardo (@leorw)
15173 * @since 2.0.0
15174 *
15175 * @param bool|int[] $all_or_blog_ids
15176 */
15177 private function delegate_connection( $all_or_blog_ids = true ) {
15178 $this->_logger->entrance();
15179
15180 $this->_admin_notices->remove_sticky( 'connect_account' );
15181
15182 if ( true === $all_or_blog_ids ) {
15183 // All sites delegation.
15184 $this->_storage->store( 'is_delegated_connection', true, true );
15185 } else {
15186 // Specified sites delegation.
15187 foreach ( $all_or_blog_ids as $blog_id ) {
15188 $this->delegate_site_connection( $blog_id );
15189 }
15190 }
15191
15192 $this->network_upgrade_mode_completed();
15193 }
15194
15195 /**
15196 * Delegate specific network site conncetion to the site admin.
15197 *
15198 * @author Vova Feldman (@svovaf)
15199 * @since 2.0.0
15200 *
15201 * @param int $blog_id
15202 */
15203 private function delegate_site_connection( $blog_id ) {
15204 $this->_storage->store( 'is_delegated_connection', true, $blog_id );
15205 }
15206
15207 /**
15208 * Check if super-admin delegated the connection of ALL sites to the site admins.
15209 *
15210 * @author Vova Feldman (@svovaf)
15211 * @since 2.0.0
15212 *
15213 * @return bool
15214 */
15215 function is_network_delegated_connection() {
15216 if ( ! $this->_is_network_active ) {
15217 return false;
15218 }
15219
15220 return $this->_storage->get( 'is_delegated_connection', false, true );
15221 }
15222
15223 /**
15224 * @author Leo Fajardo (@leorw)
15225 * @since 2.0.0
15226 *
15227 * @param int $blog_id
15228 *
15229 * @return bool
15230 */
15231 function is_site_delegated_connection( $blog_id = 0 ) {
15232 if ( ! $this->_is_network_active ) {
15233 return false;
15234 }
15235
15236 if ( 0 == $blog_id ) {
15237 $blog_id = get_current_blog_id();
15238 }
15239
15240 return $this->_storage->get( 'is_delegated_connection', false, $blog_id );
15241 }
15242
15243 /**
15244 * Check if delegated the connection. When running within the network admin,
15245 * and haven't specified the blog ID, checks if network level delegated. If running
15246 * within a site admin or specified a blog ID, check if delegated the connection for
15247 * the current context site.
15248 *
15249 * If executed outside the the admin, check if delegated the connection
15250 * for the current context site OR the whole network.
15251 *
15252 * @author Vova Feldman (@svovaf)
15253 * @since 2.0.0
15254 *
15255 * @param int $blog_id If set, checks if network delegated or blog specific delegated.
15256 *
15257 * @return bool
15258 */
15259 function is_delegated_connection( $blog_id = 0 ) {
15260 if ( ! $this->_is_network_active ) {
15261 return false;
15262 }
15263
15264 if ( fs_is_network_admin() && 0 == $blog_id ) {
15265 return $this->is_network_delegated_connection();
15266 }
15267
15268 return (
15269 $this->is_network_delegated_connection() ||
15270 $this->is_site_delegated_connection( $blog_id )
15271 );
15272 }
15273
15274 /**
15275 * Check if the current module is active for the site.
15276 *
15277 * @author Vova Feldman (@svovaf)
15278 * @since 2.0.0
15279 *
15280 * @param int $blog_id
15281 *
15282 * @return bool
15283 */
15284 function is_active_for_site( $blog_id ) {
15285 if ( ! is_multisite() ) {
15286 // Not a multisite and this code is executed, means that the plugin is active.
15287 return true;
15288 }
15289
15290 if ( $this->is_theme() ) {
15291 // All themes are site level activated.
15292 return true;
15293 }
15294
15295 if ( $this->_is_network_active ) {
15296 // Plugin was network activated so it's active.
15297 return true;
15298 }
15299
15300 return in_array( $this->_plugin_basename, (array) get_blog_option( $blog_id, 'active_plugins', array() ) );
15301 }
15302
15303 /**
15304 * @todo Implement pagination when accessing the subsites collection.
15305 *
15306 * @author Leo Fajardo (@leorw)
15307 * @since 2.0.0
15308 *
15309 * @param int $limit Default to 1,000
15310 * @param int $offset Default to 0
15311 *
15312 * @return array Active & public sites collection.
15313 */
15314 static function get_sites( $limit = 1000, $offset = 0 ) {
15315 if ( ! is_multisite() ) {
15316 return array();
15317 }
15318
15319 /**
15320 * For consistency with get_blog_list() which only return active public sites.
15321 *
15322 * @author Vova Feldman (@svovaf)
15323 */
15324 $args = array(
15325 /**
15326 * Commented out in order to handle the migration of site options whether the site is public or not.
15327 *
15328 * @author Leo Fajardo (@leorw)
15329 * @since 2.2.1
15330 */
15331 // 'public' => 1,
15332 'archived' => 0,
15333 'mature' => 0,
15334 'spam' => 0,
15335 'deleted' => 0,
15336 'number' => $limit,
15337 'offset' => $offset,
15338 );
15339
15340 return get_sites( $args );
15341 }
15342
15343 /**
15344 * Checks if a given blog is active.
15345 *
15346 * @author Vova Feldman (@svovaf)
15347 * @since 2.0.0
15348 *
15349 * @param $blog_id
15350 *
15351 * @return bool
15352 */
15353 private static function is_site_active( $blog_id ) {
15354 global $wpdb;
15355
15356 $blog_info = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM {$wpdb->blogs} WHERE blog_id = %d", $blog_id ) );
15357
15358 if ( ! is_object( $blog_info ) ) {
15359 return false;
15360 }
15361
15362 return (
15363 true == $blog_info->public &&
15364 false == $blog_info->archived &&
15365 false == $blog_info->mature &&
15366 false == $blog_info->spam &&
15367 false == $blog_info->deleted
15368 );
15369 }
15370
15371 /**
15372 * Get a mapping between the site addresses to their blog IDs.
15373 *
15374 * @author Vova Feldman (@svovaf)
15375 * @since 2.0.0
15376 *
15377 * @return array {
15378 * @key string Site address without protocol with a trailing slash.
15379 * @value int Site's blog ID.
15380 * }
15381 */
15382 private function get_address_to_blog_map() {
15383 $sites = self::get_sites();
15384
15385 // Map site addresses to their blog IDs.
15386 $address_to_blog_map = array();
15387 foreach ( $sites as $site ) {
15388 $blog_id = self::get_site_blog_id( $site );
15389 $address = self::get_unfiltered_site_url( $blog_id, true, true );
15390 $address_to_blog_map[ $address ] = $blog_id;
15391 }
15392
15393 return $address_to_blog_map;
15394 }
15395
15396 /**
15397 * Get a mapping between the site addresses to their blog IDs.
15398 *
15399 * @author Vova Feldman (@svovaf)
15400 * @since 2.0.0
15401 *
15402 * @return array {
15403 * @key int Site's blog ID.
15404 * @value FS_Site Associated install.
15405 * }
15406 */
15407 function get_blog_install_map() {
15408 $sites = self::get_sites();
15409
15410 // Map site blog ID to its install.
15411 $install_map = array();
15412
15413 foreach ( $sites as $site ) {
15414 $blog_id = self::get_site_blog_id( $site );
15415 $install = $this->get_install_by_blog_id( $blog_id );
15416
15417 if ( is_object( $install ) ) {
15418 $install_map[ $blog_id ] = $install;
15419 }
15420 }
15421
15422 return $install_map;
15423 }
15424
15425 /**
15426 * @author Vova Feldman (@svovaf)
15427 * @since 2.5.1
15428 *
15429 * @param bool|null $is_delegated When `true`, returns only connection delegated blog IDs. When `false`, only non-delegated blog IDs.
15430 *
15431 * @return int[]
15432 */
15433 private function get_blog_ids( $is_delegated = null ) {
15434 $blog_ids = array();
15435
15436 $sites = self::get_sites();
15437 foreach ( $sites as $site ) {
15438 $blog_id = self::get_site_blog_id( $site );
15439
15440 if (
15441 is_null( $is_delegated ) ||
15442 $is_delegated === $this->is_site_delegated_connection( $blog_id )
15443 ) {
15444 $blog_ids[] = $blog_id;
15445 }
15446 }
15447
15448 return $blog_ids;
15449 }
15450
15451 /**
15452 * @author Vova Feldman (@svovaf)
15453 * @since 2.5.1
15454 *
15455 * @return int[]
15456 */
15457 private function get_non_delegated_blog_ids() {
15458 return $this->get_blog_ids( false );
15459 }
15460
15461 /**
15462 * Gets a map of module IDs that the given user has opted-in to.
15463 *
15464 * @author Leo Fajardo (@leorw)
15465 * @since 2.1.0
15466 *
15467 * @param number $fs_user_id
15468 *
15469 * @return array {
15470 * @key number $plugin_id
15471 * @value bool Always true.
15472 * }
15473 */
15474 private static function get_user_opted_in_module_ids_map( $fs_user_id ) {
15475 self::$_static_logger->entrance();
15476
15477 if ( ! is_multisite() ) {
15478 $installs = array_merge(
15479 self::get_all_sites( WP_FS__MODULE_TYPE_PLUGIN ),
15480 self::get_all_sites( WP_FS__MODULE_TYPE_THEME )
15481 );
15482 } else {
15483 $sites = self::get_sites();
15484
15485 $installs = array();
15486 foreach ( $sites as $site ) {
15487 $blog_id = self::get_site_blog_id( $site );
15488
15489 $installs = array_merge(
15490 $installs,
15491 self::get_all_sites( WP_FS__MODULE_TYPE_PLUGIN, $blog_id ),
15492 self::get_all_sites( WP_FS__MODULE_TYPE_THEME, $blog_id )
15493 );
15494 }
15495 }
15496
15497 $module_ids_map = array();
15498 foreach ( $installs as $install ) {
15499 if ( is_object( $install ) &&
15500 FS_Site::is_valid_id( $install->id ) &&
15501 FS_User::is_valid_id( $install->user_id ) &&
15502 ( $install->user_id == $fs_user_id )
15503 ) {
15504 $module_ids_map[ $install->plugin_id ] = true;
15505 }
15506 }
15507
15508 return $module_ids_map;
15509 }
15510
15511 /**
15512 * @author Leo Fajardo (@leorw)
15513 *
15514 * @return null|array {
15515 * 'install' => FS_Site Module's install,
15516 * 'blog_id' => string The associated blog ID.
15517 * }
15518 */
15519 function find_first_install() {
15520 $sites = self::get_sites();
15521
15522 foreach ( $sites as $site ) {
15523 $blog_id = self::get_site_blog_id( $site );
15524 $install = $this->get_install_by_blog_id( $blog_id );
15525
15526 if ( is_object( $install ) ) {
15527 return array(
15528 'install' => $install,
15529 'blog_id' => $blog_id
15530 );
15531 }
15532 }
15533
15534 return null;
15535 }
15536
15537 /**
15538 * Switches the Freemius site level context to a specified blog.
15539 *
15540 * @author Vova Feldman (@svovaf)
15541 * @since 2.0.0
15542 *
15543 * @param int $blog_id
15544 * @param FS_Site $install
15545 * @param bool $flush
15546 *
15547 * @return bool Since 2.3.1 returns if a switch was made.
15548 */
15549 function switch_to_blog( $blog_id, FS_Site $install = null, $flush = false ) {
15550 if ( ! is_numeric( $blog_id ) ) {
15551 return false;
15552 }
15553
15554 if ( ! $flush && $blog_id == $this->_context_is_network_or_blog_id ) {
15555 return false;
15556 }
15557
15558 switch_to_blog( $blog_id );
15559 $this->_context_is_network_or_blog_id = $blog_id;
15560
15561 self::$_accounts->set_site_blog_context( $blog_id );
15562 $this->_storage->set_site_blog_context( $blog_id );
15563 $this->_storage->set_network_active( $this->_is_network_active, $this->is_delegated_connection( $blog_id ) );
15564
15565 $this->_site = is_object( $install ) ?
15566 $install :
15567 $this->get_install_by_blog_id( $blog_id );
15568
15569 $this->_user = false;
15570 $this->_licenses = false;
15571 $this->_license = null;
15572 $this->is_whitelabeled = null;
15573
15574 if ( is_object( $this->_site ) ) {
15575 // Try to fetch user from install.
15576 $this->_user = self::_get_user_by_id( $this->_site->user_id );
15577
15578 if ( ! is_object( $this->_user ) &&
15579 FS_User::is_valid_id( $this->_storage->prev_user_id )
15580 ) {
15581 // Try to fetch previously saved user.
15582 $this->_user = self::_get_user_by_id( $this->_storage->prev_user_id );
15583
15584 if ( ! is_object( $this->_user ) ) {
15585 // Fallback to network's user.
15586 $this->_user = $this->get_network_user();
15587 }
15588 }
15589
15590 $all_plugin_licenses = self::get_all_licenses( $this->_module_id );
15591
15592 if ( ! empty( $all_plugin_licenses ) ) {
15593 if ( ! FS_Plugin_License::is_valid_id( $this->_site->license_id ) ) {
15594 $this->_license = null;
15595 } else {
15596 $license_found = false;
15597 foreach ( $all_plugin_licenses as $license ) {
15598 if ( $license->id == $this->_site->license_id ) {
15599 // License found.
15600 $this->_license = $license;
15601 $license_found = true;
15602 break;
15603 }
15604 }
15605
15606 if ( $license_found ) {
15607 $this->link_license_2_user( $this->_license->id, $this->_user->id );
15608 }
15609 }
15610
15611 $this->_licenses = $this->get_user_licenses( $this->_user->id );
15612 }
15613 }
15614
15615 unset( $this->_site_api );
15616 unset( $this->_user_api );
15617
15618 return true;
15619 }
15620
15621 /**
15622 * Restore the blog context to the blog that originally loaded the module.
15623 *
15624 * @author Vova Feldman (@svovaf)
15625 * @since 2.0.0
15626 */
15627 function restore_current_blog() {
15628 $this->switch_to_blog( $this->_blog_id );
15629 }
15630
15631 /**
15632 * @author Vova Feldman (@svovaf)
15633 * @since 2.0.0
15634 *
15635 * @param array|WP_Site $site
15636 *
15637 * @return int
15638 */
15639 static function get_site_blog_id( &$site ) {
15640 return ( $site instanceof WP_Site ) ?
15641 $site->blog_id :
15642 ( is_object( $site ) && isset( $site->userblog_id ) ?
15643 $site->userblog_id :
15644 $site['blog_id'] );
15645 }
15646
15647 /**
15648 * @author Vova Feldman (@svovaf)
15649 * @since 2.5.1
15650 *
15651 * @param WP_Site[]|array[] $sites
15652 *
15653 * @return int[]
15654 */
15655 static function get_sites_blog_ids( $sites ) {
15656 $blog_ids = array();
15657 foreach ( $sites as $site ) {
15658 $blog_ids[] = self::get_site_blog_id( $site );
15659 }
15660
15661 return $blog_ids;
15662 }
15663
15664 /**
15665 * @author Leo Fajardo (@leorw)
15666 * @since 2.0.0
15667 *
15668 * @param array|WP_Site|null $site
15669 * @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.
15670 *
15671 * @return array
15672 */
15673 function get_site_info( $site = null, $load_registration = false ) {
15674 $this->_logger->entrance();
15675
15676 $switched = false;
15677
15678 $registration_date = null;
15679
15680 if ( is_null( $site ) ) {
15681 $url = self::get_unfiltered_site_url();
15682 $name = get_bloginfo( 'name' );
15683 $blog_id = null;
15684 } else {
15685 $blog_id = self::get_site_blog_id( $site );
15686
15687 if ( get_current_blog_id() != $blog_id ) {
15688 switch_to_blog( $blog_id );
15689 $switched = true;
15690 }
15691
15692 if ( $site instanceof WP_Site ) {
15693 $url = $site->siteurl;
15694 $name = $site->blogname;
15695 $registration_date = $site->registered;
15696 } else {
15697 $url = self::get_unfiltered_site_url( $blog_id );
15698 $name = get_bloginfo( 'name' );
15699 }
15700 }
15701
15702 if ( empty( $registration_date ) && $load_registration ) {
15703 $blog_details = get_blog_details( $blog_id, false );
15704
15705 if ( is_object( $blog_details ) && isset( $blog_details->registered ) ) {
15706 $registration_date = $blog_details->registered;
15707 }
15708 }
15709
15710 $info = array(
15711 'uid' => $this->get_anonymous_id( $blog_id ),
15712 'url' => $url,
15713 );
15714
15715 // Add these diagnostic information only if user allowed to track.
15716 if ( FS_Permission_Manager::instance( $this )->is_diagnostic_tracking_allowed() ) {
15717 $info = array_merge( $info, array(
15718 'title' => $name,
15719 'language' => self::get_sanitized_language(),
15720 ) );
15721 }
15722
15723 if ( is_numeric( $blog_id ) ) {
15724 $info['blog_id'] = $blog_id;
15725 }
15726
15727 if ( ! empty( $registration_date ) ) {
15728 $info[ 'registration_date' ] = $registration_date;
15729 }
15730
15731 if ( $switched ) {
15732 restore_current_blog();
15733 }
15734
15735 return $info;
15736 }
15737
15738 /**
15739 * Load the module's install based on the blog ID.
15740 *
15741 * @author Vova Feldman (@svovaf)
15742 * @since 2.0.0
15743 *
15744 * @param int|null $blog_id
15745 *
15746 * @return FS_Site
15747 */
15748 function get_install_by_blog_id( $blog_id = null ) {
15749 $installs = self::get_all_sites( $this->_module_type, $blog_id );
15750 $install = isset( $installs[ $this->_slug ] ) ? $installs[ $this->_slug ] : null;
15751
15752 if ( is_object( $install ) &&
15753 is_numeric( $install->id ) &&
15754 is_numeric( $install->user_id ) &&
15755 FS_Plugin_Plan::is_valid_id( $install->plan_id )
15756 ) {
15757 // Load site.
15758 $install = clone $install;
15759 }
15760
15761 return $install;
15762 }
15763
15764 /**
15765 * Check if module is installed on a specified site.
15766 *
15767 * @author Vova Feldman (@svovaf)
15768 * @since 2.0.0
15769 *
15770 * @param int|null $blog_id
15771 *
15772 * @return bool
15773 */
15774 function is_installed_on_site( $blog_id = null ) {
15775 $installs = self::get_all_sites( $this->_module_type, $blog_id );
15776 $install = isset( $installs[ $this->_slug ] ) ? $installs[ $this->_slug ] : null;
15777
15778 return (
15779 is_object( $install ) &&
15780 is_numeric( $install->id ) &&
15781 is_numeric( $install->user_id ) &&
15782 FS_Plugin_Plan::is_valid_id( $install->plan_id )
15783 );
15784 }
15785
15786 /**
15787 * Check if super-admin connected at least one site via the network opt-in.
15788 *
15789 * @author Vova Feldman (@svovaf)
15790 * @since 2.0.0
15791 *
15792 * @return bool
15793 */
15794 function is_network_registered() {
15795 if ( ! $this->_is_network_active ) {
15796 return false;
15797 }
15798
15799 return FS_User::is_valid_id( $this->_storage->network_user_id );
15800 }
15801
15802 /**
15803 * Returns the main user associated with the network.
15804 *
15805 * @author Vova Feldman (@svovaf)
15806 * @since 2.0.0
15807 *
15808 * @return FS_User
15809 */
15810 function get_network_user() {
15811 if ( ! $this->_is_network_active ) {
15812 return null;
15813 }
15814
15815 return FS_User::is_valid_id( $this->_storage->network_user_id ) ?
15816 self::_get_user_by_id( $this->_storage->network_user_id ) :
15817 null;
15818 }
15819
15820 /**
15821 * Returns the current context user or the network's main user.
15822 *
15823 * @author Vova Feldman (@svovaf)
15824 * @since 2.0.0
15825 *
15826 * @return FS_User
15827 */
15828 function get_current_or_network_user() {
15829 return ( $this->_user instanceof FS_User ) ?
15830 $this->_user :
15831 $this->get_network_user();
15832 }
15833
15834 /**
15835 * Returns the main install associated with the network.
15836 *
15837 * @author Vova Feldman (@svovaf)
15838 * @since 2.0.0
15839 *
15840 * @return FS_Site
15841 */
15842 function get_network_install() {
15843 if ( ! $this->_is_network_active ) {
15844 return null;
15845 }
15846
15847 return FS_Site::is_valid_id( $this->_storage->network_install_blog_id ) ?
15848 $this->get_install_by_blog_id( $this->_storage->network_install_blog_id ) :
15849 null;
15850 }
15851
15852 /**
15853 * Returns the blog ID that is associated with the main install.
15854 *
15855 * @author Leo Fajardo (@leorw)
15856 * @since 2.0.0
15857 *
15858 * @return int|null
15859 */
15860 function get_network_install_blog_id() {
15861 if ( ! $this->_is_network_active ) {
15862 return null;
15863 }
15864
15865 return FS_Site::is_valid_id( $this->_storage->network_install_blog_id ) ?
15866 $this->_storage->network_install_blog_id :
15867 null;
15868 }
15869
15870 /**
15871 * Returns the current context install or the network's main install.
15872 *
15873 * @author Vova Feldman (@svovaf)
15874 * @since 2.0.0
15875 *
15876 * @return FS_Site
15877 */
15878 function get_current_or_network_install() {
15879 return ( $this->_site instanceof FS_Site ) ?
15880 $this->_site :
15881 $this->get_network_install();
15882 }
15883
15884 /**
15885 * Check if executing a site level action from the network level admin.
15886 *
15887 * @author Vova Feldman (@svovaf)
15888 * @since 2.0.0
15889 *
15890 * @return false|int If yes, return the requested blog ID.
15891 */
15892 private function is_network_level_site_specific_action() {
15893 if ( ! $this->_is_network_active ) {
15894 return false;
15895 }
15896
15897 if ( ! fs_is_network_admin() ) {
15898 return false;
15899 }
15900
15901 $blog_id = fs_request_get( 'blog_id', '' );
15902
15903 return is_numeric( $blog_id ) ? $blog_id : false;
15904 }
15905
15906 /**
15907 * Check if executing an action from the network level admin.
15908 *
15909 * @author Vova Feldman (@svovaf)
15910 * @since 2.0.0
15911 *
15912 * @return bool
15913 */
15914 private function is_network_level_action() {
15915 return ( $this->_is_network_active && fs_is_network_admin() );
15916 }
15917
15918 /**
15919 * Needs to be executed after site deactivation, archive, deletion, or flag as spam.
15920 * 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.
15921 *
15922 * @author Vova Feldman (@svovaf)
15923 * @since 2.0.0
15924 *
15925 * @param int $context_blog_id
15926 */
15927 private function update_multisite_data_after_site_deactivation( $context_blog_id = 0 ) {
15928 $this->_logger->entrance();
15929
15930 if ( $this->_is_network_active ) {
15931 if ( $context_blog_id == $this->_storage->network_install_blog_id ) {
15932 $installs_map = $this->get_blog_install_map();
15933
15934 foreach ( $installs_map as $blog_id => $install ) {
15935 /**
15936 * @var FS_Site $install
15937 */
15938 if ( $context_blog_id == $blog_id ) {
15939 continue;
15940 }
15941
15942 if ( $install->user_id != $this->_storage->network_user_id ) {
15943 continue;
15944 }
15945
15946 // Switch reference to a blog that is opted-in and belong to the same super-admin.
15947 $this->_storage->network_install_blog_id = $blog_id;
15948 break;
15949 }
15950 }
15951 }
15952
15953 if ( ! $this->is_registered() ) {
15954 return;
15955 }
15956
15957 if ( $this->is_sync_cron_scheduled() &&
15958 $context_blog_id == $this->get_sync_cron_blog_id()
15959 ) {
15960 $this->schedule_sync_cron( WP_FS__SCRIPT_START_TIME, true, $context_blog_id );
15961 }
15962
15963 if ( $this->is_install_sync_scheduled() &&
15964 $context_blog_id == $this->get_install_sync_cron_blog_id()
15965 ) {
15966 $this->schedule_install_sync( $context_blog_id );
15967 }
15968 }
15969
15970 /**
15971 * Executed after site deactivation, archive, or flag as spam.
15972 *
15973 * @author Vova Feldman (@svovaf)
15974 * @since 2.0.0
15975 *
15976 * @param int $context_blog_id
15977 */
15978 public function _after_site_deactivated_callback( $context_blog_id = 0 ) {
15979 $this->_logger->entrance();
15980
15981 $install = $this->get_install_by_blog_id( $context_blog_id );
15982
15983 if ( ! is_object( $install ) ) {
15984 // Site not connected.
15985 return;
15986 }
15987
15988 $this->update_multisite_data_after_site_deactivation( $context_blog_id );
15989
15990 if ( ! $this->is_registered() ) {
15991 return;
15992 }
15993
15994 $current_blog_id = get_current_blog_id();
15995
15996 $this->switch_to_blog( $context_blog_id );
15997
15998 // Send deactivation event.
15999 $this->sync_install( array(
16000 'is_active' => false,
16001 ) );
16002
16003 $this->switch_to_blog( $current_blog_id );
16004 }
16005
16006 /**
16007 * Executed after site deletion.
16008 *
16009 * @author Vova Feldman (@svovaf)
16010 * @since 2.0.0
16011 *
16012 * @param int $context_blog_id
16013 * @param bool $drop True if site's database tables should be dropped. Default is false.
16014 */
16015 public function _after_site_deleted_callback( $context_blog_id = 0, $drop = false ) {
16016 $this->_logger->entrance();
16017
16018 $install = $this->get_install_by_blog_id( $context_blog_id );
16019
16020 if ( ! is_object( $install ) ) {
16021 // Site not connected.
16022 return;
16023 }
16024
16025 $this->update_multisite_data_after_site_deactivation( $context_blog_id );
16026
16027 if ( ! $this->is_registered() ) {
16028 return;
16029 }
16030
16031 $current_blog_id = get_current_blog_id();
16032
16033 $this->switch_to_blog( $context_blog_id );
16034
16035 if ( $drop ) {
16036 // Delete install if dropping site DB.
16037 $this->delete_account_event();
16038 } else {
16039 // Send deactivation event.
16040 $this->sync_install( array(
16041 'is_active' => false,
16042 ) );
16043 }
16044
16045 $this->switch_to_blog( $current_blog_id );
16046 }
16047
16048 /**
16049 * Executed after site deletion, called from wp_delete_site
16050 *
16051 * @author Dario Curvino (@dudo)
16052 * @since 2.5.0
16053 *
16054 * @param WP_Site $old_site
16055 */
16056 public function _after_wpsite_deleted_callback( WP_Site $old_site ) {
16057 $this->_logger->entrance();
16058
16059 $this->_after_site_deleted_callback( $old_site->blog_id, true );
16060 }
16061
16062 /**
16063 * Executed after site re-activation.
16064 *
16065 * @author Vova Feldman (@svovaf)
16066 * @since 2.0.0
16067 *
16068 * @param int $context_blog_id
16069 */
16070 public function _after_site_reactivated_callback( $context_blog_id = 0 ) {
16071 $this->_logger->entrance();
16072
16073 $install = $this->get_install_by_blog_id( $context_blog_id );
16074
16075 if ( ! is_object( $install ) ) {
16076 // Site not connected.
16077 return;
16078 }
16079
16080 if ( ! self::is_site_active( $context_blog_id ) ) {
16081 // Site not yet active (can be in spam mode, archived, deleted...).
16082 return;
16083 }
16084
16085 $current_blog_id = get_current_blog_id();
16086
16087 $this->switch_to_blog( $context_blog_id );
16088
16089 // Send re-activation event.
16090 $this->sync_install( array(
16091 'is_active' => true,
16092 ) );
16093
16094 $this->switch_to_blog( $current_blog_id );
16095 }
16096
16097 #endregion Multisite
16098
16099 /**
16100 * @author Leo Fajardo (@leorw)
16101 *
16102 * @param string $path
16103 * @param string $scheme
16104 * @param bool $network
16105 *
16106 * @return string
16107 */
16108 private function admin_url( $path = '', $scheme = 'admin', $network = true ) {
16109 return ( $this->_is_network_active && $network ) ?
16110 network_admin_url( $path, $scheme ) :
16111 admin_url( $path, $scheme );
16112 }
16113
16114 /**
16115 * Check if currently in a specified admin page.
16116 *
16117 * @author Vova Feldman (@svovaf)
16118 * @since 1.2.2.7
16119 *
16120 * @param string $page
16121 *
16122 * @return bool
16123 */
16124 function is_admin_page( $page ) {
16125 return ( $this->_menu->get_slug( $page ) === fs_request_get( 'page', '', 'get' ) );
16126 }
16127
16128 /**
16129 * Check if currently in the product's main admin page.
16130 *
16131 * @author Vova Feldman (@svovaf)
16132 * @since 2.3.1
16133 *
16134 * @return bool
16135 */
16136 function is_main_admin_page() {
16137 return $this->is_admin_page( '' );
16138 }
16139
16140 /**
16141 * Get module's main admin setting page URL.
16142 *
16143 * @author Vova Feldman (@svovaf)
16144 * @since 1.2.2.7
16145 *
16146 * @return string
16147 */
16148 function main_menu_url() {
16149 return $this->_menu->main_menu_url();
16150 }
16151
16152 /**
16153 * Check if currently on the theme's setting page or
16154 * on any of the Freemius added pages (via tabs).
16155 *
16156 * @author Vova Feldman (@svovaf)
16157 * @since 1.2.2.7
16158 *
16159 * @return bool
16160 *
16161 * @deprecated Please use is_product_settings_page() instead;
16162 */
16163 function is_theme_settings_page() {
16164 return $this->is_product_settings_page();
16165 }
16166
16167 /**
16168 * Check if currently on the product's main setting page or on any of the Freemius added pages (via tabs).
16169 *
16170 * @author Vova Feldman (@svovaf)
16171 * @since 1.2.2.7
16172 *
16173 * @return bool
16174 */
16175 function is_product_settings_page() {
16176 $page = fs_request_get( 'page', '', 'get' );
16177 $menu_slug = $this->_menu->get_slug();
16178
16179 if ( $page === $menu_slug ) {
16180 return true;
16181 }
16182
16183 return fs_starts_with(
16184 // e.g., {$menu_slug}-account, {$menu_slug}-affiliation, etc.
16185 $page,
16186 ( $menu_slug . '-' )
16187 );
16188 }
16189
16190 /**
16191 * Plugin's account page + sync license URL.
16192 *
16193 * @author Vova Feldman (@svovaf)
16194 * @since 1.1.9.1
16195 *
16196 * @param bool|number $plugin_id
16197 * @param bool $add_action_nonce
16198 * @param array $params
16199 *
16200 * @return string
16201 */
16202 function _get_sync_license_url( $plugin_id = false, $add_action_nonce = true, $params = array() ) {
16203 if ( is_numeric( $plugin_id ) ) {
16204 $params['plugin_id'] = $plugin_id;
16205 }
16206
16207 return $this->get_account_url(
16208 $this->get_unique_affix() . '_sync_license',
16209 $params,
16210 $add_action_nonce
16211 );
16212 }
16213
16214 /**
16215 * Plugin's account URL.
16216 *
16217 * @author Vova Feldman (@svovaf)
16218 * @since 1.0.4
16219 *
16220 * @param bool|string $action
16221 * @param array $params
16222 *
16223 * @param bool $add_action_nonce
16224 *
16225 * @return string
16226 */
16227 function get_account_url( $action = false, $params = array(), $add_action_nonce = true ) {
16228 if ( is_string( $action ) ) {
16229 $params['fs_action'] = $action;
16230 }
16231
16232 self::require_pluggable_essentials();
16233
16234 return ( $add_action_nonce && is_string( $action ) ) ?
16235 fs_nonce_url( $this->_get_admin_page_url( 'account', $params ), $action ) :
16236 $this->_get_admin_page_url( 'account', $params );
16237 }
16238
16239 /**
16240 * @author Vova Feldman (@svovaf)
16241 * @since 1.2.0
16242 *
16243 * @param string $tab
16244 * @param bool $action
16245 * @param array $params
16246 * @param bool $add_action_nonce
16247 *
16248 * @return string
16249 *
16250 * @uses get_account_url()
16251 */
16252 function get_account_tab_url( $tab, $action = false, $params = array(), $add_action_nonce = true ) {
16253 $params['tab'] = $tab;
16254
16255 return $this->get_account_url( $action, $params, $add_action_nonce );
16256 }
16257
16258 /**
16259 * Plugin's account URL.
16260 *
16261 * @author Vova Feldman (@svovaf)
16262 * @since 1.0.4
16263 *
16264 * @param bool|string $topic
16265 * @param bool|string $message
16266 * @param bool|string $summary Since 2.5.1.
16267 *
16268 * @return string
16269 */
16270 function contact_url( $topic = false, $message = false, $summary = false ) {
16271 $params = array();
16272 if ( is_string( $topic ) ) {
16273 $params['topic'] = $topic;
16274 }
16275 if ( is_string( $message ) ) {
16276 $params['message'] = $message;
16277 }
16278
16279 if ( is_string( $summary ) ) {
16280 $params['summary'] = $summary;
16281 }
16282
16283 if ( $this->is_addon() ) {
16284 $params['addon_id'] = $this->get_id();
16285
16286 return $this->get_parent_instance()->_get_admin_page_url( 'contact', $params );
16287 } else {
16288 return $this->_get_admin_page_url( 'contact', $params );
16289 }
16290 }
16291
16292 /**
16293 * Add-on direct info URL.
16294 *
16295 * @author Vova Feldman (@svovaf)
16296 * @since 1.1.0
16297 *
16298 * @param string $slug
16299 *
16300 * @return string
16301 */
16302 function addon_url( $slug ) {
16303 return $this->_get_admin_page_url( 'addons', array(
16304 'slug' => $slug
16305 ) );
16306 }
16307
16308 /**
16309 * Add-ons URL.
16310 *
16311 * @author Vova Feldman (@svovaf)
16312 * @since 2.4.5
16313 *
16314 * @return string
16315 */
16316 function get_addons_url() {
16317 return $this->_get_admin_page_url( 'addons' );
16318 }
16319
16320 /* Logger
16321 ------------------------------------------------------------------------------------------------------------------*/
16322 /**
16323 * @param string $id
16324 * @param bool $prefix_slug
16325 *
16326 * @return FS_Logger
16327 */
16328 function get_logger( $id = '', $prefix_slug = true ) {
16329 return FS_Logger::get_logger( ( $prefix_slug ? $this->_slug : '' ) . ( ( ! $prefix_slug || empty( $id ) ) ? '' : '_' ) . $id );
16330 }
16331
16332 /**
16333 * Note: This method is used externally so don't delete it.
16334 *
16335 * @param $id
16336 * @param bool $load_options
16337 * @param bool $prefix_slug
16338 *
16339 * @return FS_Option_Manager
16340 */
16341 function get_options_manager( $id, $load_options = false, $prefix_slug = true ) {
16342 return FS_Option_Manager::get_manager( ( $prefix_slug ? $this->_slug : '' ) . ( ( ! $prefix_slug || empty( $id ) ) ? '' : '_' ) . $id, $load_options );
16343 }
16344
16345 /* Security
16346 ------------------------------------------------------------------------------------------------------------------*/
16347 private static function _encrypt( $str ) {
16348 if ( is_null( $str ) ) {
16349 return null;
16350 }
16351
16352 /**
16353 * The encrypt/decrypt functions are used to protect
16354 * the user from messing up with some of the sensitive
16355 * data stored for the module as a JSON in the database.
16356 *
16357 * I used the same suggested hack by the theme review team.
16358 * For more details, look at the function `Base64UrlDecode()`
16359 * in `./sdk/FreemiusBase.php`.
16360 *
16361 * @todo Remove this hack once the base64 error is removed from the Theme Check.
16362 *
16363 * @author Vova Feldman (@svovaf)
16364 * @since 1.2.2
16365 */
16366 $fn = 'base64' . '_encode';
16367
16368 return $fn( $str );
16369 }
16370
16371 static function _decrypt( $str ) {
16372 if ( is_null( $str ) ) {
16373 return null;
16374 }
16375
16376 /**
16377 * The encrypt/decrypt functions are used to protect
16378 * the user from messing up with some of the sensitive
16379 * data stored for the module as a JSON in the database.
16380 *
16381 * I used the same suggested hack by the theme review team.
16382 * For more details, look at the function `Base64UrlDecode()`
16383 * in `./sdk/FreemiusBase.php`.
16384 *
16385 * @todo Remove this hack once the base64 error is removed from the Theme Check.
16386 *
16387 * @author Vova Feldman (@svovaf)
16388 * @since 1.2.2
16389 */
16390 $fn = 'base64' . '_decode';
16391
16392 return $fn( $str );
16393 }
16394
16395 /**
16396 * @author Vova Feldman (@svovaf)
16397 * @since 1.0.5
16398 *
16399 * @param FS_Entity $entity
16400 *
16401 * @return FS_Entity Return an encrypted clone entity.
16402 */
16403 private static function _encrypt_entity( FS_Entity $entity ) {
16404 $clone = clone $entity;
16405 $props = get_object_vars( $entity );
16406
16407 foreach ( $props as $key => $val ) {
16408 $clone->{$key} = self::_encrypt( $val );
16409 }
16410
16411 return $clone;
16412 }
16413
16414 /**
16415 * @author Vova Feldman (@svovaf)
16416 * @since 1.0.5
16417 *
16418 * @param FS_Entity $entity
16419 *
16420 * @return FS_Entity Return an decrypted clone entity.
16421 */
16422 private static function decrypt_entity( FS_Entity $entity ) {
16423 $clone = clone $entity;
16424 $props = get_object_vars( $entity );
16425
16426 foreach ( $props as $key => $val ) {
16427 $clone->{$key} = self::_decrypt( $val );
16428 }
16429
16430 return $clone;
16431 }
16432
16433 /**
16434 * @author Vova Feldman (@svovaf)
16435 * @since 1.0.7
16436 *
16437 * @param string $email
16438 *
16439 * @return FS_User|false
16440 */
16441 public static function _get_user_by_email( $email ) {
16442 self::$_static_logger->entrance();
16443
16444 $email = trim( strtolower( $email ) );
16445
16446 $users = self::get_all_users();
16447
16448 if ( is_array( $users ) ) {
16449 foreach ( $users as $user ) {
16450 if ( $email === trim( strtolower( $user->email ) ) ) {
16451 return $user;
16452 }
16453 }
16454 }
16455
16456 return false;
16457 }
16458
16459 #----------------------------------------------------------------------------------
16460 #region Account (Loading, Updates & Activation)
16461 #----------------------------------------------------------------------------------
16462
16463 /***
16464 * Load account information (user + site).
16465 *
16466 * @author Vova Feldman (@svovaf)
16467 * @since 1.0.1
16468 */
16469 private function _load_account() {
16470 $this->_logger->entrance();
16471
16472 $this->do_action( 'before_account_load' );
16473
16474 $users = self::get_all_users();
16475 $plans = self::get_all_plans( $this->_module_type );
16476
16477 if ( $this->_logger->is_on() && is_admin() ) {
16478 $this->_logger->log( 'users = ' . var_export( $users, true ) );
16479 $this->_logger->log( 'plans = ' . var_export( $plans, true ) );
16480 }
16481
16482 $site = fs_is_network_admin() ?
16483 $this->get_network_install() :
16484 $this->get_install_by_blog_id();
16485
16486 if ( fs_is_network_admin() &&
16487 $this->is_network_active() &&
16488 ! is_object( $site ) &&
16489 FS_Site::is_valid_id( $this->_storage->network_install_blog_id )
16490 ) {
16491 $first_install = $this->find_first_install();
16492
16493 if ( is_null( $first_install ) ) {
16494 unset( $this->_storage->network_install_blog_id );
16495 } else {
16496 $site = $first_install['install'];
16497 $this->_storage->network_install_blog_id = $first_install['blog_id'];
16498 }
16499 }
16500
16501 if ( is_object( $site ) &&
16502 is_numeric( $site->id ) &&
16503 is_numeric( $site->user_id ) &&
16504 FS_Plugin_Plan::is_valid_id( $site->plan_id )
16505 ) {
16506 // Load site.
16507 $this->_site = $site;
16508 }
16509
16510 $user = null;
16511 if ( fs_is_network_admin() && $this->_is_network_active ) {
16512 $user = $this->get_network_user();
16513 }
16514
16515 if ( is_object( $user ) ) {
16516 $this->_user = clone $user;
16517 } else if ( $this->_site ) {
16518 $user = self::_get_user_by_id( $this->_site->user_id );
16519
16520 if ( ! is_object( $user ) && FS_User::is_valid_id( $this->_storage->prev_user_id ) ) {
16521 /**
16522 * Try to load the previous owner. This recovery is used for the following use-case:
16523 * 1. Opt-in
16524 * 2. Cloning site1 to site2
16525 * 3. Ownership switch in site1 (same applies for site2)
16526 * 4. Install data sync on site2
16527 * 5. Now site2's install is associated with the new owner which does not exists locally.
16528 */
16529 $user = self::_get_user_by_id( $this->_storage->prev_user_id );
16530 }
16531
16532 if ( ! is_object( $user ) ) {
16533 /**
16534 * This is a special fault tolerance mechanism to handle a scenario that the user data is missing.
16535 */
16536 if (
16537 ! isset( $this->_storage->user_recovery_from_install_last_attempt_timestamp ) ||
16538 time() > ( $this->_storage->user_recovery_from_install_last_attempt_timestamp + FS_Clone_Manager::CLONE_RESOLUTION_MAX_EXECUTION_TIME )
16539 ) {
16540 $user = $this->sync_user_by_current_install();
16541 } else {
16542 return;
16543 }
16544
16545 if ( is_object( $user ) ) {
16546 $this->_storage->user_was_recovered_from_install = true;
16547 } else {
16548 $this->_storage->user_recovery_from_install_attempts = isset( $this->_storage->user_recovery_from_install_attempts ) ?
16549 ( $this->_storage->user_recovery_from_install_attempts + 1 ) :
16550 1;
16551
16552 if ( $this->_storage->user_recovery_from_install_attempts >= 3 ) {
16553 $this->delete_current_install( false );
16554 } else {
16555 $this->_storage->user_recovery_from_install_last_attempt_timestamp = time();
16556
16557 return;
16558 }
16559 }
16560 }
16561
16562 $this->_user = ( $user instanceof FS_User ) ?
16563 clone $user :
16564 null;
16565 }
16566
16567 if ( is_object( $this->_user ) ) {
16568 // Load licenses.
16569 $this->_licenses = $this->get_user_licenses( $this->_user->id );
16570 }
16571
16572 if ( is_object( $this->_site ) ) {
16573 // Load plans.
16574 $this->_plans = isset( $plans[ $this->_slug ] ) ?
16575 $plans[ $this->_slug ] :
16576 array();
16577
16578 if ( ! is_array( $this->_plans ) || empty( $this->_plans ) ) {
16579 $this->_sync_plans();
16580 } else {
16581 for ( $i = 0, $len = count( $this->_plans ); $i < $len; $i ++ ) {
16582 if ( $this->_plans[ $i ] instanceof FS_Plugin_Plan ) {
16583 $this->_plans[ $i ] = self::decrypt_entity( $this->_plans[ $i ] );
16584 } else {
16585 unset( $this->_plans[ $i ] );
16586 }
16587 }
16588 }
16589
16590 $this->_license = $this->_get_license_by_id( $this->_site->license_id );
16591
16592 if ( $this->_site->version != $this->get_plugin_version() ) {
16593 // If stored install version is different than current installed plugin version,
16594 // then update plugin version event.
16595 $this->update_plugin_version_event();
16596 }
16597 }
16598
16599 if ( true === $this->_storage->require_license_activation &&
16600 ! fs_request_get_bool( 'require_license', true )
16601 ) {
16602 $this->_storage->require_license_activation = false;
16603 }
16604
16605 if ( $this->is_theme() ) {
16606 $this->_register_account_hooks();
16607 }
16608
16609 if ( $this->is_user_in_admin() && $this->is_clone() ) {
16610 if ( empty( FS_Clone_Manager::instance()->get_clone_identification_timestamp() ) ) {
16611 FS_Clone_Manager::instance()->store_clone_identification_timestamp();
16612 }
16613
16614 FS_Clone_Manager::instance()->maybe_update_clone_resolution_support_flag( $this->_storage->sdk_last_version );
16615 $this->send_pending_clone_update_once();
16616 }
16617 }
16618
16619 /**
16620 * Special user recovery mechanism.
16621 *
16622 * @author Vova Feldman (@svovaf)
16623 * @since 2.0.0
16624 *
16625 * @param number|null $site_user_id
16626 *
16627 * @return \FS_User|mixed
16628 */
16629 private function sync_user_by_current_install( $site_user_id = null ) {
16630 $site_user_id = FS_Site::is_valid_id( $site_user_id ) ?
16631 $site_user_id :
16632 $this->_site->user_id;
16633
16634 $api = $this->get_api_site_scope();
16635
16636 $uid = $this->get_anonymous_id();
16637 $request_path = "/users/{$site_user_id}.json?uid={$uid}";
16638
16639 $result = $api->get( $request_path, false, WP_FS__TIME_10_MIN_IN_SEC );
16640
16641 if ( $this->is_api_result_entity( $result ) ) {
16642 $user = new FS_User( $result );
16643 $this->_user = $user;
16644 $this->_store_user();
16645
16646 return $user;
16647 }
16648
16649 $error_code = FS_Api::get_error_code( $result );
16650
16651 if ( in_array( $error_code, array( 'invalid_unique_id', 'user_cannot_be_recovered' ) ) ) {
16652 /**
16653 * Those API errors will continue coming and are not recoverable with the
16654 * current site's data. Therefore, extend the API call's cached result to 7 days.
16655 */
16656 $api->update_cache_expiration( $request_path, WP_FS__TIME_WEEK_IN_SEC );
16657 }
16658
16659 return $result;
16660 }
16661
16662 /**
16663 * @author Vova Feldman (@svovaf)
16664 * @since 1.0.1
16665 *
16666 * @param FS_User $user
16667 * @param FS_Site $site
16668 * @param bool|array $plans
16669 */
16670 private function _set_account( FS_User $user, FS_Site $site, $plans = false ) {
16671 $site->user_id = $user->id;
16672
16673 $this->_site = $site;
16674 $this->_user = $user;
16675 if ( false !== $plans ) {
16676 $this->_plans = $plans;
16677 }
16678
16679 $this->send_install_update();
16680
16681 $this->_store_account();
16682
16683 }
16684
16685 /**
16686 * Get a sanitized array with the WordPress version, SDK version, and PHP version.
16687 * Each version is trimmed after the 16th char.
16688 *
16689 * @author Vova Feldman (@svovaf)
16690 * @since 2.2.1
16691 *
16692 * @return array
16693 */
16694 private function get_versions() {
16695 $versions = array();
16696 $versions['sdk_version'] = $this->version;
16697
16698 // Collect these diagnostic information only if it's allowed.
16699 if ( FS_Permission_Manager::instance( $this )->is_diagnostic_tracking_allowed() ) {
16700 $versions['platform_version'] = get_bloginfo( 'version' );
16701 $versions['programming_language_version'] = phpversion();
16702 }
16703
16704 foreach ( $versions as $k => $version ) {
16705 $versions[ $k ] = self::get_api_sanitized_property( $k, $version );
16706 }
16707
16708 return $versions;
16709 }
16710
16711 /**
16712 * Get sanitized site language.
16713 *
16714 * @param string $language
16715 * @param int $max_len
16716 *
16717 * @since 2.5.1
16718 * @author Vova Feldman (@svovaf)
16719 *
16720 * @return string
16721 */
16722 private static function get_sanitized_language( $language = '', $max_len = self::LANGUAGE_MAX_CHARS ) {
16723 if ( empty( $language ) ) {
16724 $language = get_bloginfo( 'language' );
16725 }
16726
16727 return substr( $language, 0, $max_len );
16728 }
16729
16730 /**
16731 * Get core version stripped from pre-release and build.
16732 *
16733 * @since 2.5.1
16734 * @author Vova Feldman (@svovaf)
16735 *
16736 * @param string $version
16737 * @param int $parts
16738 * @param int $max_len
16739 * @param bool $include_pre_release
16740 *
16741 * @return string
16742 */
16743 private static function get_core_version(
16744 $version,
16745 $parts = 3,
16746 $max_len = self::VERSION_MAX_CHARS,
16747 $include_pre_release = false
16748 ) {
16749 if ( empty( $version ) ) {
16750 // Version is empty.
16751 return '';
16752 }
16753
16754 if ( is_numeric( $version ) ) {
16755 $is_float_version = is_float( $version );
16756
16757 $version = (string) $version;
16758
16759 /**
16760 * 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.
16761 */
16762 if ( $is_float_version && false === strpos( $version, '.' ) ) {
16763 $version .= '.0';
16764 }
16765 }
16766
16767 if ( ! is_string( $version ) ) {
16768 return '';
16769 }
16770
16771 if ( $parts < 1 ) {
16772 return '';
16773 }
16774
16775 $pre_release_regex = $include_pre_release ?
16776 '(\-(alpha|beta|RC)([0-9]+)?)?' :
16777 '';
16778
16779 if ( 0 === preg_match( '/^([0-9]+(\.[0-9]+){0,' . ( $parts - 1 ) . '}' . $pre_release_regex . ')/i', $version, $matches ) ) {
16780 // Version is not starting with a digit.
16781 return '';
16782 }
16783
16784 return substr( $matches[1], 0, $max_len );
16785 }
16786
16787 /**
16788 * @param string $prop
16789 * @param mixed $val
16790 *
16791 * @return mixed
16792 *@author Vova Feldman (@svovaf)
16793 *
16794 * @since 2.5.1
16795 */
16796 private static function get_api_sanitized_property( $prop, $val ) {
16797 if ( ! is_string( $val ) || empty( $val ) ) {
16798 return $val;
16799 }
16800
16801 switch ( $prop ) {
16802 case 'programming_language_version':
16803 // Get core PHP version, which can have up to 3 parts (ignore pre-releases).
16804 return self::get_core_version( $val );
16805 case 'platform_version':
16806 // Get the exact WordPress version, which can have up to 3 parts (including pre-releases).
16807 return self::get_core_version( $val, 3, self::VERSION_MAX_CHARS, true );
16808 case 'sdk_version':
16809 // Get the exact SDK version, which can have up to 4 parts.
16810 return self::get_core_version( $val, 4 );
16811 case 'version':
16812 // Get the entire version but just limited in length.
16813 return substr( $val, 0, self::VERSION_MAX_CHARS );
16814 case 'language':
16815 return self::get_sanitized_language( $val );
16816 default:
16817 return $val;
16818 }
16819 }
16820
16821 /**
16822 * @author Leo Fajardo (@leorw)
16823 * @since 2.3.0
16824 *
16825 * @return bool
16826 */
16827 function has_beta_update() {
16828 return (
16829 ! empty( $this->_storage->beta_data ) &&
16830 ( true === $this->_storage->beta_data['is_beta'] ) &&
16831 version_compare( $this->_storage->beta_data['version'], $this->get_plugin_version(), '>' )
16832 );
16833 }
16834
16835 /**
16836 * @author Leo Fajardo (@leorw)
16837 * @since 2.3.0
16838 *
16839 * @return bool
16840 */
16841 function is_beta() {
16842 return (
16843 ! empty( $this->_storage->beta_data ) &&
16844 ( true === $this->_storage->beta_data['is_beta'] ) &&
16845 ( $this->get_plugin_version() === $this->_storage->beta_data['version'] )
16846 );
16847 }
16848
16849 /**
16850 * @author Vova Feldman (@svovaf)
16851 * @since 1.1.7.4
16852 *
16853 * @param array $override_with
16854 * @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.
16855 *
16856 * @return array
16857 */
16858 function get_opt_in_params( $override_with = array(), $network_level_or_blog_id = null ) {
16859 $this->_logger->entrance();
16860
16861 $current_user = self::_get_current_wp_user();
16862
16863 $activation_action = $this->get_unique_affix() . '_activate_new';
16864 $return_url = $this->is_anonymous() ?
16865 // If skipped already, then return to the account page.
16866 $this->get_account_url( $activation_action, array(), false ) :
16867 // Return to the module's main page.
16868 $this->get_after_activation_url( 'after_connect_url', array( 'fs_action' => $activation_action ) );
16869
16870 $versions = $this->get_versions();
16871
16872 $params = array_merge( $versions, array(
16873 'user_firstname' => $current_user->user_firstname,
16874 'user_lastname' => $current_user->user_lastname,
16875 'user_email' => $current_user->user_email,
16876 'plugin_slug' => $this->_slug,
16877 'plugin_id' => $this->get_id(),
16878 'plugin_public_key' => $this->get_public_key(),
16879 'plugin_version' => $this->get_plugin_version(),
16880 'return_url' => fs_nonce_url( $return_url, $activation_action ),
16881 'account_url' => fs_nonce_url( $this->_get_admin_page_url(
16882 'account',
16883 array( 'fs_action' => 'sync_user' )
16884 ), 'sync_user' ),
16885 'is_premium' => $this->is_premium(),
16886 'is_active' => true,
16887 'is_uninstalled' => false,
16888 'is_localhost' => WP_FS__IS_LOCALHOST,
16889 ) );
16890
16891 if ( $this->is_addon() ) {
16892 $parent_fs = $this->get_parent_instance();
16893
16894 $params['parent_plugin_slug'] = $parent_fs->_slug;
16895 $params['parent_plugin_id'] = $parent_fs->get_id();
16896 }
16897
16898 if ( true === $network_level_or_blog_id ) {
16899 if ( ! isset( $override_with['sites'] ) ) {
16900 $params['sites'] = $this->get_sites_for_network_level_optin();
16901 }
16902 } else {
16903 $site = is_numeric( $network_level_or_blog_id ) ?
16904 array( 'blog_id' => $network_level_or_blog_id ) :
16905 null;
16906
16907 $site = $this->get_site_info( $site );
16908
16909 $diagnostic_info = array();
16910 if ( FS_Permission_Manager::instance( $this )->is_diagnostic_tracking_allowed() ) {
16911 $diagnostic_info = array(
16912 'site_name' => $site['title'],
16913 'language' => self::get_sanitized_language( $site['language'] ),
16914 );
16915 }
16916
16917 $params = array_merge( $params, $diagnostic_info, array(
16918 'site_uid' => $site['uid'],
16919 'site_url' => $site['url'],
16920 ) );
16921 }
16922
16923 if ( $this->is_pending_activation() &&
16924 ! empty( $this->_storage->pending_license_key )
16925 ) {
16926 $params['license_key'] = $this->_storage->pending_license_key;
16927 }
16928
16929 if ( WP_FS__SKIP_EMAIL_ACTIVATION && $this->has_secret_key() ) {
16930 // Even though rand() is known for its security issues,
16931 // the timestamp adds another layer of protection.
16932 // It would be very hard for an attacker to get the secret key form here.
16933 // Plus, this should never run in production since the secret should never
16934 // be included in the production version.
16935 $params['ts'] = WP_FS__SCRIPT_START_TIME;
16936 $params['salt'] = md5( uniqid( rand() ) );
16937 $params['secure'] = md5(
16938 $params['ts'] .
16939 $params['salt'] .
16940 $this->get_secret_key()
16941 );
16942 }
16943
16944 if ( is_multisite() && function_exists( 'get_network' ) ) {
16945 $params['network_uid'] = $this->get_anonymous_network_id();
16946 }
16947
16948 return array_merge( $params, $override_with );
16949 }
16950
16951 /**
16952 * 1. If successful opt-in or pending activation returns the next page that the user should be redirected to.
16953 * 2. If there was an API error, return the API result.
16954 *
16955 * @author Vova Feldman (@svovaf)
16956 * @since 1.1.7.4
16957 *
16958 * @param string|bool $email
16959 * @param string|bool $first
16960 * @param string|bool $last
16961 * @param string|bool $license_key
16962 * @param bool $is_uninstall If "true", this means that the module is currently being uninstalled.
16963 * In this case, the user and site info will be sent to the server but no
16964 * data will be saved to the WP installation's database.
16965 * @param number|bool $trial_plan_id
16966 * @param bool $is_disconnected Whether to opt in without tracking.
16967 * @param null|bool $is_marketing_allowed
16968 * @param array $sites If network-level opt-in, an array of containing details of sites.
16969 * @param bool $redirect
16970 *
16971 * @return string|object
16972 * @use WP_Error
16973 */
16974 function opt_in(
16975 $email = false,
16976 $first = false,
16977 $last = false,
16978 $license_key = false,
16979 $is_uninstall = false,
16980 $trial_plan_id = false,
16981 $is_disconnected = false,
16982 $is_marketing_allowed = null,
16983 $sites = array(),
16984 $redirect = true
16985 ) {
16986 $this->_logger->entrance();
16987
16988 if ( false === $email ) {
16989 $current_user = self::_get_current_wp_user();
16990 $email = $current_user->user_email;
16991 }
16992
16993 /**
16994 * @since 1.2.1 If activating with license key, ignore the context-user
16995 * since the user will be automatically loaded from the license.
16996 */
16997 if ( empty( $license_key ) ) {
16998 // Clean up pending license if opt-ing in again.
16999 $this->_storage->remove( 'pending_license_key' );
17000
17001 if ( ! $is_uninstall ) {
17002 $fs_user = Freemius::_get_user_by_email( $email );
17003 if ( is_object( $fs_user ) && ! $this->is_pending_activation() ) {
17004 return $this->install_with_user(
17005 $fs_user,
17006 false,
17007 $trial_plan_id,
17008 $redirect,
17009 true,
17010 $sites
17011 );
17012 }
17013 }
17014 }
17015
17016 $user_info = array();
17017 if ( ! empty( $email ) ) {
17018 $user_info['user_email'] = $email;
17019 }
17020 if ( ! empty( $first ) ) {
17021 $user_info['user_firstname'] = $first;
17022 }
17023 if ( ! empty( $last ) ) {
17024 $user_info['user_lastname'] = $last;
17025 }
17026
17027 if ( ! empty( $sites ) ) {
17028 $is_network = true;
17029
17030 $user_info['sites'] = $sites;
17031 } else {
17032 $is_network = false;
17033 }
17034
17035 $params = $this->get_opt_in_params( $user_info, $is_network );
17036
17037 $filtered_license_key = false;
17038 if ( is_string( $license_key ) ) {
17039 $filtered_license_key = $this->apply_filters( 'license_key', $license_key );
17040 $params['license_key'] = $filtered_license_key;
17041 } else if ( FS_Plugin_Plan::is_valid_id( $trial_plan_id ) ) {
17042 $params['trial_plan_id'] = $trial_plan_id;
17043 }
17044
17045 if ( $is_uninstall ) {
17046 $params['uninstall_params'] = array(
17047 'reason_id' => $this->_storage->uninstall_reason->id,
17048 'reason_info' => $this->_storage->uninstall_reason->info
17049 );
17050 }
17051
17052 if ( isset( $params['license_key'] ) ) {
17053 $fs_user = Freemius::_get_user_by_email( $email );
17054
17055 if ( is_object( $fs_user ) ) {
17056 /**
17057 * If opting in with a context license and the context WP Admin user already opted in
17058 * before from the current site, add the user context security params to avoid the
17059 * unnecessary email activation when the context license is owned by the same context user.
17060 *
17061 * @author Leo Fajardo (@leorw)
17062 * @since 1.2.3
17063 */
17064 $params = array_merge( $params, FS_Security::instance()->get_context_params(
17065 $fs_user,
17066 false,
17067 'install_with_existing_user'
17068 ) );
17069 }
17070 }
17071
17072 if ( is_bool( $is_marketing_allowed ) ) {
17073 $params['is_marketing_allowed'] = $is_marketing_allowed;
17074 }
17075
17076 $params['is_disconnected'] = $is_disconnected;
17077 $params['format'] = 'json';
17078 $params['is_extensions_tracking_allowed'] = FS_Permission_Manager::instance( $this )->is_extensions_tracking_allowed();
17079 $params['is_diagnostic_tracking_allowed'] = FS_Permission_Manager::instance( $this )->is_diagnostic_tracking_allowed();
17080
17081 $request = array(
17082 'method' => 'POST',
17083 'body' => $params,
17084 'timeout' => 60,
17085 );
17086
17087 $url = $this->add_show_pending( WP_FS__ADDRESS . '/action/service/user/install/' );
17088 $response = self::safe_remote_post( $url, $request );
17089
17090 if ( is_wp_error( $response ) ) {
17091 /**
17092 * @var WP_Error $response
17093 */
17094 $result = new stdClass();
17095
17096 $error_code = $response->get_error_code();
17097 $error_type = str_replace( ' ', '', ucwords( str_replace( '_', ' ', $error_code ) ) );
17098
17099 $result->error = (object) array(
17100 'type' => $error_type,
17101 'message' => $response->get_error_message(),
17102 'code' => $error_code,
17103 'http' => 402
17104 );
17105
17106 $this->maybe_modify_api_curl_error_message( $result );
17107
17108 if ( FS_Api::is_blocked( $result ) ) {
17109 $result->error->message = $this->generate_api_blocked_notice_message_from_result( $result );
17110 }
17111
17112 $is_connected = null;
17113
17114 if ( empty( $license_key ) && $this->is_enable_anonymous() ) {
17115 $this->skip_connection( fs_is_network_admin() );
17116
17117 $is_connected = ( ! FS_Api::is_blocked( $result ) );
17118 }
17119
17120 $this->update_connectivity_info( $is_connected );
17121
17122 return $result;
17123 }
17124
17125 $this->update_connectivity_info( true );
17126
17127 // Module is being uninstalled, don't handle the returned data.
17128 if ( $is_uninstall ) {
17129 return true;
17130 }
17131
17132 /**
17133 * 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.
17134 *
17135 * @author Vova Feldman (@svovaf)
17136 * @since 1.2.3
17137 * @link https://themes.trac.wordpress.org/ticket/46134#comment:5
17138 * @link https://themes.trac.wordpress.org/ticket/46134#comment:9
17139 * @link https://themes.trac.wordpress.org/ticket/46134#comment:12
17140 * @link https://themes.trac.wordpress.org/ticket/46134#comment:14
17141 */
17142 $decoded = is_string( $response['body'] ) ?
17143 json_decode( $response['body'] ) :
17144 null;
17145
17146 if ( empty( $decoded ) ) {
17147 return false;
17148 }
17149
17150 if ( ! $this->is_api_result_object( $decoded ) ) {
17151 if ( ! empty( $params['license_key'] ) ) {
17152 // Pass the fully entered license key to the failure handler.
17153 $params['license_key'] = $license_key;
17154 }
17155
17156 return $is_uninstall ?
17157 $decoded :
17158 $this->apply_filters( 'after_install_failure', $decoded, $params );
17159 } else if ( isset( $decoded->pending_activation ) && $decoded->pending_activation ) {
17160 if ( $is_network ) {
17161 $site_ids = array();
17162 foreach ( $sites as $site ) {
17163 $site_ids[] = $site['blog_id'];
17164 }
17165
17166 /**
17167 * Store the sites so that they can be installed once the user has clicked on the activation link
17168 * in the email.
17169 *
17170 * @author Leo Fajardo (@leorw)
17171 */
17172 $this->_storage->pending_sites_info = array(
17173 'blog_ids' => $site_ids,
17174 'license_key' => $license_key,
17175 'trial_plan_id' => $trial_plan_id
17176 );
17177 }
17178
17179 // Pending activation, add message.
17180 return $this->set_pending_confirmation(
17181 ( isset( $decoded->email ) ?
17182 $decoded->email :
17183 true ),
17184 false,
17185 $filtered_license_key,
17186 ! empty( $params['trial_plan_id'] ),
17187 isset( $decoded->is_suspicious_email ) && $decoded->is_suspicious_email
17188 );
17189 } else if ( isset( $decoded->install_secret_key ) ) {
17190 return $this->install_with_new_user(
17191 $decoded->user_id,
17192 $decoded->user_public_key,
17193 $decoded->user_secret_key,
17194 ( isset( $decoded->is_marketing_allowed ) && ! is_null( $decoded->is_marketing_allowed ) ?
17195 $decoded->is_marketing_allowed :
17196 null ),
17197 ( isset( $decoded->is_extensions_tracking_allowed ) && ! is_null( $decoded->is_extensions_tracking_allowed ) ?
17198 $decoded->is_extensions_tracking_allowed :
17199 null ),
17200 ( isset( $decoded->is_diagnostic_tracking_allowed ) && ! is_null( $decoded->is_diagnostic_tracking_allowed ) ?
17201 $decoded->is_diagnostic_tracking_allowed :
17202 null ),
17203 $decoded->install_id,
17204 $decoded->install_public_key,
17205 $decoded->install_secret_key,
17206 false
17207 );
17208 } else if ( is_array( $decoded->installs ) ) {
17209 return $this->install_many_with_new_user(
17210 $decoded->user_id,
17211 $decoded->user_public_key,
17212 $decoded->user_secret_key,
17213 ( isset( $decoded->is_marketing_allowed ) && ! is_null( $decoded->is_marketing_allowed ) ?
17214 $decoded->is_marketing_allowed :
17215 null ),
17216 ( isset( $decoded->is_extensions_tracking_allowed ) && ! is_null( $decoded->is_extensions_tracking_allowed ) ?
17217 $decoded->is_extensions_tracking_allowed :
17218 null ),
17219 ( isset( $decoded->is_diagnostic_tracking_allowed ) && ! is_null( $decoded->is_diagnostic_tracking_allowed ) ?
17220 $decoded->is_diagnostic_tracking_allowed :
17221 null ),
17222 $decoded->installs,
17223 false
17224 );
17225 }
17226
17227 return $decoded;
17228 }
17229
17230 /**
17231 * Set user and site identities.
17232 *
17233 * @author Vova Feldman (@svovaf)
17234 * @since 1.0.9
17235 *
17236 * @param FS_User $user
17237 * @param FS_Site $site
17238 * @param bool $redirect
17239 * @param bool $auto_install Since 1.2.1.7 If `true` and setting up an account with a valid license, will
17240 * redirect (or return a URL) to the account page with a special parameter to
17241 * trigger the auto installation processes.
17242 *
17243 * @return string If redirect is `false`, returns the next page the user should be redirected to.
17244 */
17245 function setup_account(
17246 FS_User $user,
17247 FS_Site $site,
17248 $redirect = true,
17249 $auto_install = false
17250 ) {
17251 return $this->setup_network_account(
17252 $user,
17253 array( $site ),
17254 $redirect,
17255 $auto_install,
17256 false
17257 );
17258 }
17259
17260 /**
17261 * Set user and site identities.
17262 *
17263 * @author Vova Feldman (@svovaf)
17264 * @since 2.0.0
17265 *
17266 * @param FS_User $user
17267 * @param FS_Site[] $installs
17268 * @param bool $redirect
17269 * @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.
17270 * @param bool $is_network_level_opt_in
17271 *
17272 * @return string If redirect is `false`, returns the next page the user should be redirected to.
17273 */
17274 function setup_network_account(
17275 FS_User $user,
17276 array $installs,
17277 $redirect = true,
17278 $auto_install = false,
17279 $is_network_level_opt_in = true
17280 ) {
17281 $first_install = $installs[0];
17282
17283 $this->_user = $user;
17284 $this->_site = $first_install;
17285
17286 $this->_sync_plans();
17287
17288 if ( $this->_storage->handle_gdpr_admin_notice &&
17289 $this->should_handle_gdpr_admin_notice() &&
17290 FS_GDPR_Manager::instance()->should_show_opt_in_notice()
17291 ) {
17292 /**
17293 * Clear user lock after an opt-in.
17294 */
17295 require_once WP_FS__DIR_INCLUDES . '/class-fs-user-lock.php';
17296 FS_User_Lock::instance()->unlock();
17297 }
17298
17299 if ( 1 < count( $installs ) ) {
17300 // Only network level opt-in can have more than one install.
17301 $is_network_level_opt_in = true;
17302 }
17303
17304 $this->update_connectivity_info( true );
17305
17306 // $is_network_level_opt_in = self::is_ajax_action_static( 'network_activate', $this->_module_id );
17307 // If Freemius was OFF before, turn it on.
17308 $this->turn_on();
17309
17310 $this->handle_account_connection(
17311 $installs,
17312 ( ! $this->_is_network_active || ! $is_network_level_opt_in )
17313 );
17314
17315 if ( is_numeric( $first_install->license_id ) ) {
17316 $this->set_license( $this->_get_license_by_id( $first_install->license_id ) );
17317 }
17318
17319 $this->_admin_notices->remove_sticky( 'connect_account' );
17320
17321 if ( $this->is_pending_activation() || ! $this->has_settings_menu() ) {
17322 $this->clear_pending_activation_mode();
17323
17324 if ( ! $this->is_paying_or_trial() ) {
17325 $this->_admin_notices->add_sticky(
17326 sprintf( $this->get_text_inline( '%s opt-in was successfully completed.', 'plugin-x-activation-message' ), '<b>' . $this->get_plugin_name() . '</b>' ),
17327 'activation_complete'
17328 );
17329 }
17330 }
17331
17332 if ( $this->is_paying_or_trial() ) {
17333 if ( ! $this->is_premium() ||
17334 ! $this->has_premium_version() ||
17335 ! $this->has_settings_menu()
17336 ) {
17337 if ( $this->is_paying() ) {
17338 $this->add_complete_upgrade_instructions_notice(
17339 sprintf(
17340 $this->get_text_inline( 'Your account was successfully activated with the %s plan.', 'activation-with-plan-x-message' ),
17341 $this->get_plan_title()
17342 ),
17343 'plan_upgraded'
17344 );
17345 } else {
17346 $trial_plan = $this->get_trial_plan();
17347
17348 $this->add_complete_upgrade_instructions_notice(
17349 sprintf(
17350 $this->get_text_inline( 'Your trial has been successfully started.', 'trial-started-message' ),
17351 '<i>' . $this->get_plugin_name() . '</i>'
17352 ),
17353 'trial_started',
17354 $trial_plan->title
17355 );
17356 }
17357 }
17358
17359 $this->_admin_notices->remove_sticky( array(
17360 'trial_promotion',
17361 ) );
17362 }
17363
17364 $plugin_id = fs_request_get( 'plugin_id', false );
17365
17366 // Store activation time ONLY for plugins & themes (not add-ons).
17367 if ( ! is_numeric( $plugin_id ) || ( $plugin_id == $this->_plugin->id ) ) {
17368 if ( empty( $this->_storage->activation_timestamp ) ) {
17369 $this->_storage->activation_timestamp = WP_FS__SCRIPT_START_TIME;
17370 }
17371 }
17372
17373 $next_page = '';
17374
17375 $extra = array();
17376 if ( $auto_install ) {
17377 $extra['auto_install'] = 'true';
17378 }
17379
17380 if ( is_numeric( $plugin_id ) ) {
17381 /**
17382 * @author Leo Fajardo (@leorw)
17383 * @since 1.2.1.6
17384 *
17385 * Also sync the license after an anonymous user subscribes.
17386 */
17387 if ( $this->is_anonymous() || $plugin_id != $this->_plugin->id ) {
17388 // Add-on was installed - sync license right after install.
17389 $next_page = $this->_get_sync_license_url( $plugin_id, true, $extra );
17390 }
17391 } else {
17392 /**
17393 * @author Vova Feldman (@svovaf)
17394 * @since 1.1.9 If site installed with a valid license, sync license.
17395 */
17396 if ( $this->is_paying() ) {
17397 $this->_sync_plugin_license(
17398 true,
17399 // Installs data is already synced in the beginning of this method directly or via _set_account().
17400 false
17401 );
17402 }
17403
17404 // Reload the page with the keys.
17405 $next_page = $this->is_anonymous() ?
17406 // If user previously skipped, redirect to account page.
17407 $this->get_account_url( false, $extra ) :
17408 $this->get_after_activation_url( 'after_connect_url', array(), $is_network_level_opt_in );
17409 }
17410
17411 if ( ! empty( $next_page ) && $redirect ) {
17412 fs_redirect( $next_page );
17413 }
17414
17415 return $next_page;
17416 }
17417
17418 /**
17419 * Install plugin with new user information after approval.
17420 *
17421 * @author Vova Feldman (@svovaf)
17422 * @since 1.0.7
17423 */
17424 function _install_with_new_user() {
17425 $this->_logger->entrance();
17426
17427 if ( $this->is_registered() ) {
17428 return;
17429 }
17430
17431 $has_pending_activation_confirmation_param = fs_request_has( 'pending_activation' );
17432
17433 $this->update_license_required_permissions_if_anonymous();
17434
17435 if ( ( $this->is_plugin() && fs_request_is_action( $this->get_unique_affix() . '_activate_new' ) ) ||
17436 // @todo This logic should be improved because it's executed on every load of a theme.
17437 $this->is_theme()
17438 ) {
17439 // check_admin_referer( $this->_slug . '_activate_new' );
17440
17441 if ( fs_request_has( 'user_secret_key' ) ) {
17442 if ( fs_is_network_admin() && isset( $this->_storage->pending_sites_info ) ) {
17443 $pending_sites_info = $this->_storage->pending_sites_info;
17444
17445 $this->install_many_pending_with_user(
17446 fs_request_get( 'user_id' ),
17447 fs_request_get_raw( 'user_public_key' ),
17448 fs_request_get_raw( 'user_secret_key' ),
17449 fs_request_get_bool( 'is_marketing_allowed', null ),
17450 fs_request_get_bool( 'is_extensions_tracking_allowed', null ),
17451 fs_request_get_bool( 'is_diagnostic_tracking_allowed', null ),
17452 $pending_sites_info['blog_ids'],
17453 $pending_sites_info['license_key'],
17454 $pending_sites_info['trial_plan_id']
17455 );
17456 } else {
17457 $this->install_with_new_user(
17458 fs_request_get( 'user_id' ),
17459 fs_request_get_raw( 'user_public_key' ),
17460 fs_request_get_raw( 'user_secret_key' ),
17461 fs_request_get_bool( 'is_marketing_allowed', null ),
17462 fs_request_get_bool( 'is_extensions_tracking_allowed', null ),
17463 fs_request_get_bool( 'is_diagnostic_tracking_allowed', null ),
17464 fs_request_get( 'install_id' ),
17465 fs_request_get_raw( 'install_public_key' ),
17466 fs_request_get_raw( 'install_secret_key' ),
17467 true,
17468 fs_request_get_bool( 'auto_install' )
17469 );
17470 }
17471 } else if ( $has_pending_activation_confirmation_param ) {
17472 $this->set_pending_confirmation(
17473 fs_request_get( 'user_email' ),
17474 true,
17475 false,
17476 false,
17477 fs_request_get_bool( 'is_suspicious_email' ),
17478 fs_request_get_bool( 'has_upgrade_context' ),
17479 fs_request_get( 'support_email_address' )
17480 );
17481 }
17482 }
17483 }
17484
17485 /**
17486 * @author Vova Feldman (@svovaf)
17487 * @since 2.0.0
17488 *
17489 * @param number $id
17490 * @param string $public_key
17491 * @param string $secret_key
17492 *
17493 * @return \FS_User
17494 */
17495 private function setup_user( $id, $public_key, $secret_key ) {
17496 $user = self::_get_user_by_id( $id );
17497
17498 if ( is_object( $user ) ) {
17499 $this->_user = $user;
17500 } else {
17501 $user = new FS_User();
17502 $user->id = $id;
17503 $user->public_key = $public_key;
17504 $user->secret_key = $secret_key;
17505
17506 $this->_user = $user;
17507 $user_result = $this->get_api_user_scope()->get();
17508 $user = new FS_User( $user_result );
17509
17510 $this->_user = $user;
17511 $this->_store_user();
17512 }
17513
17514 return $user;
17515 }
17516
17517 /**
17518 * Install plugin with new user.
17519 *
17520 * @author Vova Feldman (@svovaf)
17521 * @since 1.1.7.4
17522 *
17523 * @param number $user_id
17524 * @param string $user_public_key
17525 * @param string $user_secret_key
17526 * @param bool|null $is_marketing_allowed
17527 * @param bool|null $is_extensions_tracking_allowed Since 2.3.2
17528 * @param bool|null $is_diagnostic_tracking_allowed Since 2.5.0.2
17529 * @param number $install_id
17530 * @param string $install_public_key
17531 * @param string $install_secret_key
17532 * @param bool $redirect
17533 * @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.
17534 *
17535 * @return string If redirect is `false`, returns the next page the user should be redirected to.
17536 */
17537 private function install_with_new_user(
17538 $user_id,
17539 $user_public_key,
17540 $user_secret_key,
17541 $is_marketing_allowed,
17542 $is_extensions_tracking_allowed,
17543 $is_diagnostic_tracking_allowed,
17544 $install_id,
17545 $install_public_key,
17546 $install_secret_key,
17547 $redirect = true,
17548 $auto_install = false
17549 ) {
17550 /**
17551 * This method is also executed after opting in with a license key since the
17552 * license can be potentially associated with a different owner.
17553 *
17554 * @since 2.0.0
17555 */
17556 $user = self::_get_user_by_id( $user_id );
17557
17558 if ( ! is_object( $user ) ) {
17559 $user = new FS_User();
17560 $user->id = $user_id;
17561 $user->public_key = $user_public_key;
17562 $user->secret_key = $user_secret_key;
17563
17564 $this->_user = $user;
17565 $user_result = $this->get_api_user_scope()->get();
17566 $user = new FS_User( $user_result );
17567 }
17568
17569 $this->_user = $user;
17570
17571 $site = new FS_Site();
17572 $site->id = $install_id;
17573 $site->public_key = $install_public_key;
17574 $site->secret_key = $install_secret_key;
17575
17576 $this->_site = $site;
17577 $site_result = $this->get_api_site_scope( true )->get();
17578 $site = new FS_Site( $site_result );
17579 $this->_site = $site;
17580
17581 if ( ! is_null( $is_marketing_allowed ) ) {
17582 $this->disable_opt_in_notice_and_lock_user();
17583 }
17584
17585 FS_Permission_Manager::instance( $this )->update_permissions_tracking_flag( array(
17586 FS_Permission_Manager::PERMISSION_DIAGNOSTIC => $is_diagnostic_tracking_allowed,
17587 FS_Permission_Manager::PERMISSION_EXTENSIONS => $is_extensions_tracking_allowed,
17588 ) );
17589
17590 return $this->setup_account(
17591 $this->_user,
17592 $this->_site,
17593 $redirect,
17594 $auto_install
17595 );
17596 }
17597
17598 /**
17599 * Install plugin with user.
17600 *
17601 * @author Leo Fajardo (@leorw)
17602 * @since 2.0.0
17603 *
17604 * @param number $user_id
17605 * @param string $user_public_key
17606 * @param string $user_secret_key
17607 * @param bool|null $is_marketing_allowed
17608 * @param bool|null $is_extensions_tracking_allowed Since 2.3.2
17609 * @param bool|null $is_diagnostic_tracking_allowed Since 2.5.0.2
17610 * @param array $site_ids
17611 * @param bool $license_key
17612 * @param bool $trial_plan_id
17613 * @param bool $redirect
17614 *
17615 * @return void
17616 */
17617 private function install_many_pending_with_user(
17618 $user_id,
17619 $user_public_key,
17620 $user_secret_key,
17621 $is_marketing_allowed,
17622 $is_extensions_tracking_allowed,
17623 $is_diagnostic_tracking_allowed,
17624 $site_ids,
17625 $license_key = false,
17626 $trial_plan_id = false,
17627 $redirect = true
17628 ) {
17629 $user = $this->setup_user( $user_id, $user_public_key, $user_secret_key );
17630
17631 if ( ! is_null( $is_marketing_allowed ) ) {
17632 $this->disable_opt_in_notice_and_lock_user();
17633 }
17634
17635 FS_Permission_Manager::instance( $this )->update_permissions_tracking_flag( array(
17636 FS_Permission_Manager::PERMISSION_DIAGNOSTIC => $is_diagnostic_tracking_allowed,
17637 FS_Permission_Manager::PERMISSION_EXTENSIONS => $is_extensions_tracking_allowed,
17638 ) );
17639
17640 $sites = array();
17641 foreach ( $site_ids as $site_id ) {
17642 $sites[] = $this->get_site_info( array( 'blog_id' => $site_id ) );
17643 }
17644
17645 $this->install_with_user( $user, $license_key, $trial_plan_id, $redirect, true, $sites );
17646 }
17647
17648 /**
17649 * Multi-site install with a new user.
17650 *
17651 * @author Vova Feldman (@svovaf)
17652 * @since 2.0.0
17653 *
17654 * @param number $user_id
17655 * @param string $user_public_key
17656 * @param string $user_secret_key
17657 * @param bool|null $is_marketing_allowed
17658 * @param bool|null $is_extensions_tracking_allowed Since 2.3.2
17659 * @param bool|null $is_diagnostic_tracking_allowed Since 2.5.0.2
17660 * @param object[] $installs
17661 * @param bool $redirect
17662 * @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.
17663 *
17664 * @return string If redirect is `false`, returns the next page the user should be redirected to.
17665 */
17666 private function install_many_with_new_user(
17667 $user_id,
17668 $user_public_key,
17669 $user_secret_key,
17670 $is_marketing_allowed,
17671 $is_extensions_tracking_allowed,
17672 $is_diagnostic_tracking_allowed,
17673 array $installs,
17674 $redirect = true,
17675 $auto_install = false
17676 ) {
17677 $this->setup_user( $user_id, $user_public_key, $user_secret_key );
17678
17679 if ( ! is_null( $is_marketing_allowed ) ) {
17680 $this->disable_opt_in_notice_and_lock_user();
17681 }
17682
17683 FS_Permission_Manager::instance( $this )->update_permissions_tracking_flag( array(
17684 FS_Permission_Manager::PERMISSION_DIAGNOSTIC => $is_diagnostic_tracking_allowed,
17685 FS_Permission_Manager::PERMISSION_EXTENSIONS => $is_extensions_tracking_allowed,
17686 ) );
17687
17688 $install_ids = array();
17689
17690 foreach ( $installs as $install ) {
17691 $install_ids[] = $install->id;
17692 }
17693
17694 $items_per_request = 25;
17695 $left = count( $install_ids );
17696 $offset = 0;
17697
17698 $installs = array();
17699 while ( $left > 0 ) {
17700 $result = $this->get_api_user_scope()->get( "/plugins/{$this->_module_id}/installs.json?ids=" . implode( ',', array_slice( $install_ids, $offset, $items_per_request ) ) );
17701
17702 if ( ! $this->is_api_result_object( $result, 'installs' ) ) {
17703 // @todo Handle API error.
17704 }
17705
17706 $installs = array_merge( $installs, $result->installs );
17707
17708 $left -= $items_per_request;
17709 $offset += $items_per_request;
17710 }
17711
17712 foreach ( $installs as &$install ) {
17713 $install = new FS_Site( $install );
17714 }
17715
17716 return $this->setup_network_account(
17717 $this->_user,
17718 $installs,
17719 $redirect,
17720 $auto_install
17721 );
17722 }
17723
17724 /**
17725 * @author Vova Feldman (@svovaf)
17726 * @since 1.1.7.4
17727 *
17728 * @param string|bool $email
17729 * @param bool $redirect
17730 * @param string|bool $license_key Since 1.2.1.5
17731 * @param bool $is_pending_trial Since 1.2.1.5
17732 * @param bool $is_suspicious_email Since 2.5.0
17733 * @param bool $has_upgrade_context Since 2.5.3
17734 * @param bool|string $support_email_address Since 2.5.3
17735 *
17736 * @return string Since 1.2.1.5 if $redirect is `false`, return the pending activation page.
17737 */
17738 private function set_pending_confirmation(
17739 $email = false,
17740 $redirect = true,
17741 $license_key = false,
17742 $is_pending_trial = false,
17743 $is_suspicious_email = false,
17744 $has_upgrade_context = false,
17745 $support_email_address = false
17746 ) {
17747 $is_network_admin = fs_is_network_admin();
17748
17749 if ( $this->_ignore_pending_mode && ! $has_upgrade_context ) {
17750 /**
17751 * If explicitly asked to ignore pending mode, set to anonymous mode
17752 * 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).
17753 *
17754 * @author Vova Feldman
17755 * @since 1.2.1.6
17756 */
17757 $this->skip_connection( $is_network_admin );
17758 } else {
17759 // Install must be activated via email since
17760 // user with the same email already exist.
17761 $this->_storage->is_pending_activation = true;
17762 $this->_add_pending_activation_notice(
17763 $email,
17764 $is_pending_trial,
17765 $is_suspicious_email,
17766 $has_upgrade_context,
17767 $support_email_address
17768 );
17769 }
17770
17771 if ( ! empty( $license_key ) ) {
17772 $this->_storage->pending_license_key = $license_key;
17773 }
17774
17775 // Remove the opt-in sticky notice.
17776 $this->_admin_notices->remove_sticky( array(
17777 'connect_account',
17778 'trial_promotion',
17779 ) );
17780
17781 $next_page = $this->get_after_activation_url( 'after_pending_connect_url' );
17782
17783 if ( $redirect ) {
17784 // Reload the page with a pending activation message.
17785 fs_redirect( $next_page );
17786 }
17787
17788 return $next_page;
17789 }
17790
17791 /**
17792 * Install plugin with current logged WP user info.
17793 *
17794 * @author Vova Feldman (@svovaf)
17795 * @since 1.0.7
17796 */
17797 function _install_with_current_user() {
17798 $this->_logger->entrance();
17799
17800 if ( $this->is_registered() ) {
17801 return;
17802 }
17803
17804 if ( fs_request_is_action( $this->get_unique_affix() . '_activate_existing' ) && fs_request_is_post() ) {
17805 check_admin_referer( $this->get_unique_affix() . '_activate_existing' );
17806
17807 /**
17808 * @author Vova Feldman (@svovaf)
17809 * @since 1.1.9 Add license key if given.
17810 */
17811 $license_key = fs_request_get_raw( 'license_secret_key' );
17812
17813 FS_Permission_Manager::instance( $this )->update_permissions_tracking_flag( array(
17814 FS_Permission_Manager::PERMISSION_DIAGNOSTIC => fs_request_get_bool( 'is_diagnostic_tracking_allowed', null ),
17815 FS_Permission_Manager::PERMISSION_EXTENSIONS => fs_request_get_bool( 'is_extensions_tracking_allowed', null ),
17816 ) );
17817
17818 $this->install_with_current_user( $license_key );
17819 }
17820 }
17821
17822
17823 /**
17824 * @author Vova Feldman (@svovaf)
17825 * @since 1.1.7.4
17826 *
17827 * @param string|bool $license_key
17828 * @param number|bool $trial_plan_id
17829 * @param array $sites Since 2.0.0
17830 * @param bool $redirect
17831 *
17832 * @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.
17833 */
17834 function install_with_current_user(
17835 $license_key = false,
17836 $trial_plan_id = false,
17837 $sites = array(),
17838 $redirect = true
17839 ) {
17840 // Get current logged WP user.
17841 $current_user = self::_get_current_wp_user();
17842
17843 // Find the relevant FS user by the email.
17844 $user = self::_get_user_by_email( $current_user->user_email );
17845
17846 return $this->install_with_user( $user, $license_key, $trial_plan_id, $redirect, true, $sites );
17847 }
17848
17849 /**
17850 * @author Vova Feldman (@svovaf)
17851 * @since 2.0.0
17852 *
17853 * @param \FS_User $user
17854 * @param string|bool $license_key
17855 * @param number|bool $trial_plan_id
17856 * @param bool $redirect
17857 * @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.
17858 * @param array $sites Since 2.0.0. If not empty, should be a collection of site details for the bulk install API request.
17859 *
17860 * @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.
17861 */
17862 function install_with_user(
17863 FS_User $user,
17864 $license_key = false,
17865 $trial_plan_id = false,
17866 $redirect = true,
17867 $setup_account = true,
17868 $sites = array()
17869 ) {
17870 // We have to set the user before getting user scope API handler.
17871 $this->_user = $user;
17872
17873 // Install the plugin.
17874 $result = $this->create_installs_with_user(
17875 $user,
17876 $license_key,
17877 $trial_plan_id,
17878 $sites,
17879 $redirect
17880 );
17881
17882 if ( ! $this->is_api_result_entity( $result ) &&
17883 ! $this->is_api_result_object( $result, 'installs' )
17884 ) {
17885 // @todo Handler potential API error of the $result
17886 }
17887
17888 if ( empty( $sites ) ) {
17889 $site = new FS_Site( $result );
17890 $this->_site = $site;
17891
17892 if ( ! $setup_account ) {
17893 $this->_store_site();
17894
17895 $this->sync_plan_if_not_exist( $site->plan_id );
17896
17897 if ( ! empty( $license_key ) && FS_Plugin_License::is_valid_id( $site->license_id ) ) {
17898 $this->sync_license_if_not_exist( $site->license_id, $license_key );
17899 }
17900
17901 $this->_admin_notices->remove_sticky( 'connect_account', false );
17902
17903 return $site;
17904 }
17905
17906 return $this->setup_account( $this->_user, $this->_site, $redirect );
17907 } else {
17908 $installs = array();
17909 foreach ( $result->installs as $install ) {
17910 $installs[] = new FS_Site( $install );
17911 }
17912
17913 return $this->setup_network_account(
17914 $user,
17915 $installs,
17916 $redirect
17917 );
17918 }
17919 }
17920
17921 /**
17922 * Initiate an API request to create a collection of installs.
17923 *
17924 * @author Vova Feldman (@svovaf)
17925 * @since 2.0.0
17926 *
17927 * @param \FS_User $user
17928 * @param bool $license_key
17929 * @param bool $trial_plan_id
17930 * @param array $sites
17931 * @param bool $redirect
17932 * @param bool $silent
17933 *
17934 * @return object|mixed
17935 */
17936 private function create_installs_with_user(
17937 FS_User $user,
17938 $license_key = false,
17939 $trial_plan_id = false,
17940 $sites = array(),
17941 $redirect = false,
17942 $silent = false
17943 ) {
17944 $extra_install_params = array(
17945 'uid' => $this->get_anonymous_id(),
17946 'is_disconnected' => false,
17947 );
17948
17949 if ( ! empty( $license_key ) ) {
17950 $extra_install_params['license_key'] = $this->apply_filters( 'license_key', $license_key );
17951
17952 if ( $silent ) {
17953 $extra_install_params['ignore_license_owner'] = true;
17954 }
17955 } else if ( FS_Plugin_Plan::is_valid_id( $trial_plan_id ) ) {
17956 $extra_install_params['trial_plan_id'] = $trial_plan_id;
17957 }
17958
17959 if ( ! empty( $sites ) ) {
17960 $extra_install_params['sites'] = $sites;
17961 }
17962
17963 $args = $this->get_install_data_for_api( $extra_install_params, false, false );
17964
17965 // Install the plugin.
17966 $result = $this->get_api_user_scope_by_user( $user )->call(
17967 "/plugins/{$this->get_id()}/installs.json",
17968 'post',
17969 $args
17970 );
17971
17972 if ( ! $this->is_api_result_entity( $result ) &&
17973 ! $this->is_api_result_object( $result, 'installs' )
17974 ) {
17975 if ( ! empty( $args['license_key'] ) ) {
17976 // Pass the fully entered license key to the failure handler.
17977 $args['license_key'] = $license_key;
17978 }
17979
17980 $result = $this->apply_filters( 'after_install_failure', $result, $args );
17981
17982 if ( ! $silent ) {
17983 $this->_admin_notices->add(
17984 sprintf( $this->get_text_inline( 'Couldn\'t activate %s.', 'could-not-activate-x' ), $this->get_plugin_name() ) . ' ' .
17985 $this->get_text_inline( 'Please contact us with the following message:', 'contact-us-with-error-message' ) . ' ' . '<b>' . $result->error->message . '</b>',
17986 $this->get_text_x_inline( 'Oops', 'exclamation', 'oops' ) . '...',
17987 'error'
17988 );
17989 }
17990
17991 if ( $redirect ) {
17992 /**
17993 * We set the user before getting the user scope API handler, so the user became temporarily
17994 * registered (`is_registered() = true`). Since the API returned an error and we will redirect,
17995 * we have to set the user to `null`, otherwise, the user will be redirected to the wrong
17996 * activation page based on the return value of `is_registered()`. In addition, in case the
17997 * context plugin doesn't have a settings menu and the default page is the `Plugins` page,
17998 * misleading plugin activation errors will be shown on the `Plugins` page.
17999 *
18000 * @author Leo Fajardo (@leorw)
18001 */
18002 $this->_user = null;
18003
18004 fs_redirect( $this->get_activation_url( array( 'error' => $result->error->message ) ) );
18005 }
18006 }
18007
18008 return $result;
18009 }
18010
18011 /**
18012 * Tries to activate add-on account based on parent plugin info.
18013 *
18014 * @author Vova Feldman (@svovaf)
18015 * @since 1.0.6
18016 *
18017 * @param Freemius $parent_fs
18018 * @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.
18019 * @param FS_Plugin_License $bundle_license Since 2.4.0. If provided, this license will be activated for the add-on.
18020 */
18021 private function _activate_addon_account(
18022 Freemius $parent_fs,
18023 $network_level_or_blog_id = null,
18024 FS_Plugin_License $bundle_license = null
18025 ) {
18026 if ( $this->is_registered() ) {
18027 // Already activated.
18028 return;
18029 }
18030
18031 $permission_ids = FS_Permission_Manager::get_all_permission_ids();
18032 $permissions = array();
18033 foreach ( $permission_ids as $permission_id ) {
18034 $permissions[ $permission_id ] = FS_Permission_Manager::instance( $parent_fs )->is_permission( $permission_id, true );
18035 }
18036
18037 FS_Permission_Manager::instance( $this )->update_permissions_tracking_flag( $permissions );
18038
18039 /**
18040 * Do not override the `uid` if network-level opt-in since the call to `get_sites_for_network_level_optin()`
18041 * already returns the data for the current blog.
18042 *
18043 * @author Leo Fajardo (@leorw)
18044 * @since 2.3.0
18045 */
18046 $uid_param_to_override = ( true === $network_level_or_blog_id ) ?
18047 array() :
18048 array( 'uid' => $this->get_anonymous_id() );
18049
18050 $params = $this->get_install_data_for_api(
18051 $uid_param_to_override,
18052 false,
18053 false,
18054 /**
18055 * Do not include the data for the current blog if network-level opt-in since the call to `get_sites_for_network_level_optin`
18056 * already includes the data for it.
18057 *
18058 * @author Leo Fajardo (@leorw)
18059 * @since 2.3.0
18060 */
18061 ( true !== $network_level_or_blog_id )
18062 );
18063
18064 if ( true === $network_level_or_blog_id ) {
18065 $params['sites'] = $this->get_sites_for_network_level_optin();
18066
18067 if ( empty( $params['sites'] ) ) {
18068 return;
18069 }
18070 }
18071
18072 if ( is_object( $bundle_license ) ) {
18073 $params['license_key'] = $bundle_license->secret_key;
18074 }
18075
18076 // Activate add-on with parent plugin credentials.
18077 $result = $parent_fs->get_api_site_scope()->call(
18078 "/addons/{$this->_plugin->id}/installs.json",
18079 'post',
18080 $params
18081 );
18082
18083 if ( ! $this->is_api_result_object( $result, 'installs' ) ) {
18084 if ( is_object( $bundle_license ) ) {
18085 /**
18086 * 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.
18087 *
18088 * @author Leo Fajardo (@leorw)
18089 * @since 2.4.0
18090 */
18091 } else {
18092 $error_message = FS_Api::is_api_error_object( $result ) ?
18093 $result->error->message :
18094 $this->get_text_inline( 'An unknown error has occurred.', 'unknown-error' );
18095
18096 $this->_admin_notices->add(
18097 sprintf( $this->get_text_inline( 'Couldn\'t activate %s.', 'could-not-activate-x' ), $this->get_plugin_name() ) . ' ' .
18098 $this->get_text_inline( 'Please contact us with the following message:', 'contact-us-with-error-message' ) . ' ' . '<b>' . $error_message . '</b>',
18099 $this->get_text_x_inline( 'Oops', 'exclamation', 'oops' ) . '...',
18100 'error'
18101 );
18102 }
18103
18104 return;
18105 }
18106
18107 $addon_installs = $result->installs;
18108 foreach ( $addon_installs as $key => $addon_install ) {
18109 $addon_installs[ $key ] = new FS_Site( $addon_install );
18110 }
18111
18112 $first_install = $addon_installs[0];
18113
18114 // Get user information based on parent's plugin.
18115 $user = $parent_fs->get_user();
18116
18117 // First of all, set site and user info - otherwise we won't
18118 // be able to invoke API calls.
18119 $this->_site = $first_install;
18120 $this->_user = $user;
18121
18122 // Sync add-on plans.
18123 $this->_sync_plans();
18124
18125 $this->handle_account_connection( $addon_installs, ! fs_is_network_admin() );
18126
18127 // Get site's current plan.
18128 //$this->_site->plan = $this->_get_plan_by_id( $this->_site->plan->id );
18129
18130 // Sync licenses.
18131 $this->_sync_licenses();
18132
18133 if ( ! fs_is_network_admin() ) {
18134 // Try to activate premium license.
18135 $this->_activate_license( true, $bundle_license );
18136
18137 if ( is_object( $bundle_license ) ) {
18138 $this->maybe_activate_bundle_license( $bundle_license );
18139 }
18140 } else {
18141 if ( is_object( $bundle_license ) ) {
18142 $premium_license = $bundle_license;
18143 } else {
18144 $license_id = fs_request_get( 'license_id' );
18145
18146 if ( is_object( $this->_site ) &&
18147 FS_Plugin_License::is_valid_id( $license_id ) &&
18148 $license_id == $this->_site->license_id
18149 ) {
18150 // License is already activated.
18151 return;
18152 }
18153
18154 $premium_license = FS_Plugin_License::is_valid_id( $license_id ) ?
18155 $this->_get_license_by_id( $license_id ) :
18156 $this->_get_available_premium_license();
18157 }
18158
18159 if ( is_object( $premium_license ) ) {
18160 $this->maybe_network_activate_addon_license( $premium_license );
18161 }
18162 }
18163 }
18164
18165 /**
18166 * @author Leo Fajardo (@leorw)
18167 * @since 2.3.0
18168 *
18169 * @param FS_Site[] $installs
18170 * @param bool $is_site_level
18171 */
18172 private function handle_account_connection( $installs, $is_site_level ) {
18173 $first_install = $installs[0];
18174
18175 if ( $is_site_level ) {
18176 $this->_set_account( $this->_user, $first_install );
18177
18178 $this->do_action( 'after_account_connection', $this->_user, $first_install );
18179 } else {
18180 $this->_store_user();
18181
18182 // Map site addresses to their blog IDs.
18183 $address_to_blog_map = $this->get_address_to_blog_map();
18184
18185 $first_blog_id = null;
18186 $blog_2_install_map = array();
18187 foreach ( $installs as $install ) {
18188 $address = trailingslashit( fs_strip_url_protocol( $install->url ) );
18189 $blog_id = $address_to_blog_map[ $address ];
18190
18191 $this->_store_site( true, $blog_id, $install );
18192
18193 if ( is_null( $first_blog_id ) ) {
18194 $first_blog_id = $blog_id;
18195 }
18196
18197 $blog_2_install_map[ $blog_id ] = $install;
18198 }
18199
18200 if ( ! FS_User::is_valid_id( $this->_storage->network_user_id ) ||
18201 ! is_object( self::_get_user_by_id( $this->_storage->network_user_id ) )
18202 ) {
18203 // Store network user.
18204 $this->_storage->network_user_id = $this->_user->id;
18205 }
18206
18207 if ( ! FS_Site::is_valid_id( $this->_storage->network_install_blog_id ) ) {
18208 $this->_storage->network_install_blog_id = $first_blog_id;
18209 }
18210
18211 if ( count( $installs ) === count( $address_to_blog_map ) ) {
18212 // Super admin opted in for all sites in the network.
18213 $this->_storage->is_network_connected = true;
18214 }
18215
18216 $this->_store_licenses( false );
18217
18218 self::$_accounts->store();
18219
18220 // Don't sync the installs data on network upgrade
18221 if ( ! $this->network_upgrade_mode_completed() ) {
18222 $this->send_installs_update();
18223 }
18224
18225 $current_blog = get_current_blog_id();
18226
18227 foreach ( $blog_2_install_map as $blog_id => $install ) {
18228 $this->switch_to_blog( $blog_id );
18229
18230 $this->do_action( 'after_account_connection', $this->_user, $install );
18231 }
18232
18233 // Switch install context back to the first install.
18234 $this->switch_to_blog(
18235 $current_blog,
18236 $first_install,
18237 ( $this->_site->id != $first_install->id )
18238 );
18239
18240 $this->do_action( 'after_network_account_connection', $this->_user, $blog_2_install_map );
18241 }
18242 }
18243
18244 /**
18245 * Tries to activate parent account based on add-on's info.
18246 *
18247 * @author Vova Feldman (@svovaf)
18248 * @since 1.2.2.7
18249 *
18250 * @param Freemius $parent_fs
18251 */
18252 private function activate_parent_account( Freemius $parent_fs ) {
18253 if ( ! $this->is_addon() ) {
18254 // This is not an add-on.
18255 return;
18256 }
18257
18258 if ( $parent_fs->is_registered() ) {
18259 // Already activated.
18260 return;
18261 }
18262
18263 // Activate parent with add-on's user credentials.
18264 $parent_install = $this->get_api_user_scope()->call(
18265 "/plugins/{$parent_fs->_plugin->id}/installs.json",
18266 'post',
18267 $parent_fs->get_install_data_for_api( array(
18268 'uid' => $parent_fs->get_anonymous_id(),
18269 ), false, false )
18270 );
18271
18272 if ( isset( $parent_install->error ) ) {
18273 $this->_admin_notices->add(
18274 sprintf( $this->get_text_inline( 'Couldn\'t activate %s.', 'could-not-activate-x' ), $this->get_plugin_name() ) . ' ' .
18275 $this->get_text_inline( 'Please contact us with the following message:', 'contact-us-with-error-message' ) . ' ' . '<b>' . $parent_install->error->message . '</b>',
18276 $this->get_text_x_inline( 'Oops', 'exclamation', 'oops' ) . '...',
18277 'error'
18278 );
18279
18280 return;
18281 }
18282
18283 $parent_fs->_admin_notices->remove_sticky( 'connect_account' );
18284
18285 if ( $parent_fs->is_pending_activation() ) {
18286 $parent_fs->clear_pending_activation_mode();
18287 }
18288
18289 // Get user information based on parent's plugin.
18290 $user = $this->get_user();
18291
18292 // First of all, set site info - otherwise we won't
18293 // be able to invoke API calls.
18294 $parent_fs->_site = new FS_Site( $parent_install );
18295 $parent_fs->_user = $user;
18296
18297 // Sync add-on plans.
18298 $parent_fs->_sync_plans();
18299
18300 $parent_fs->update_license_required_permissions_if_anonymous();
18301
18302 $parent_fs->_set_account( $user, $parent_fs->_site );
18303 }
18304
18305 #endregion
18306
18307 #----------------------------------------------------------------------------------
18308 #region Admin Menu Items
18309 #----------------------------------------------------------------------------------
18310
18311 private $_menu_items = array();
18312
18313 /**
18314 * @author Vova Feldman (@svovaf)
18315 * @since 1.2.1.8
18316 *
18317 * @return array
18318 */
18319 function get_menu_items() {
18320 return $this->_menu_items;
18321 }
18322
18323 /**
18324 * @author Vova Feldman (@svovaf)
18325 * @since 1.0.7
18326 *
18327 * @return string
18328 */
18329 function get_menu_slug() {
18330 return $this->_menu->get_slug();
18331 }
18332
18333 /**
18334 * @author Vova Feldman (@svovaf)
18335 * @since 1.0.9
18336 */
18337 function _prepare_admin_menu() {
18338 // if ( ! $this->is_on() ) {
18339 // return;
18340 // }
18341
18342 if ( is_object( $this->_site ) && ! $this->is_registered() ) {
18343 return;
18344 }
18345
18346 /**
18347 * When running from a site admin with a network activated module and the connection
18348 * was NOT delegated and the user still haven't skipped or opted-in, then hide the
18349 * site level settings.
18350 *
18351 * @author Vova Feldman (@svovaf)
18352 * @since 2.0.0
18353 */
18354 $should_hide_site_admin_settings = (
18355 $this->_is_network_active &&
18356 ! fs_is_network_admin() &&
18357 ! $this->is_delegated_connection() &&
18358 ! $this->is_anonymous() &&
18359 ! $this->is_registered()
18360 );
18361
18362 $should_hide_site_admin_settings = $this->apply_filters( 'should_hide_site_admin_settings_on_network_activation_mode', $should_hide_site_admin_settings );
18363
18364 if ( ( false === $this->has_api_connectivity() && ! $this->is_enable_anonymous() ) ||
18365 $should_hide_site_admin_settings
18366 ) {
18367 $this->_menu->remove_menu_item( $should_hide_site_admin_settings );
18368 } else {
18369 $this->do_action( fs_is_network_admin() ?
18370 'before_network_admin_menu_init' :
18371 'before_admin_menu_init'
18372 );
18373
18374 $this->add_menu_action();
18375
18376 $this->add_network_menu_when_missing();
18377
18378 $this->add_submenu_items();
18379 }
18380 }
18381
18382 /**
18383 * Admin dashboard menu items modifications.
18384 *
18385 * NOTE: admin_menu action executed before admin_init.
18386 *
18387 * @author Vova Feldman (@svovaf)
18388 * @since 1.0.7
18389 *
18390 */
18391 private function add_menu_action() {
18392 if ( $this->is_activation_mode() ) {
18393 if ( $this->show_opt_in_on_setting_page() ) {
18394 $this->override_plugin_menu_with_activation();
18395 } else {
18396 /**
18397 * Handle theme opt-in when the opt-in form shows as a dialog box in the themes page.
18398 */
18399 if ( fs_request_is_action( $this->get_unique_affix() . '_activate_existing' ) ) {
18400 add_action( 'load-themes.php', array( &$this, '_install_with_current_user' ) );
18401 } else if ( fs_request_is_action( $this->get_unique_affix() . '_activate_new' ) ||
18402 fs_request_get_bool( 'pending_activation' )
18403 ) {
18404 add_action( 'load-themes.php', array( &$this, '_install_with_new_user' ) );
18405 }
18406 }
18407 } else {
18408 if ( ! $this->is_registered() ) {
18409 // If not registered try to install user.
18410 if ( fs_request_is_action( $this->get_unique_affix() . '_activate_new' ) ) {
18411 $this->_install_with_new_user();
18412 }
18413 } else if (
18414 fs_request_is_action( 'sync_user' ) &&
18415 ( ! $this->has_settings_menu() || $this->show_opt_in_on_themes_page() )
18416 ) {
18417 $this->_handle_account_user_sync();
18418 }
18419 }
18420 }
18421
18422 /**
18423 * @author Vova Feldman (@svovaf)
18424 * @since 1.0.1
18425 */
18426 function _redirect_on_clicked_menu_link() {
18427 $this->_logger->entrance();
18428
18429 $page = fs_request_get('page');
18430 $page = is_string($page) ? strtolower($page) : '';
18431
18432 $this->_logger->log( 'page = ' . $page );
18433
18434 foreach ( $this->_menu_items as $priority => $items ) {
18435 foreach ( $items as $item ) {
18436 if ( isset( $item['url'] ) ) {
18437 if ( $page === $this->_menu->get_slug( strtolower( $item['menu_slug'] ) ) ) {
18438 $this->_logger->log( 'Redirecting to ' . $item['url'] );
18439
18440 fs_redirect( $item['url'] );
18441 }
18442 }
18443 }
18444 }
18445 }
18446
18447 /**
18448 * Remove plugin's all admin menu items & pages, and replace with activation page.
18449 *
18450 * @author Vova Feldman (@svovaf)
18451 * @since 1.0.1
18452 */
18453 private function override_plugin_menu_with_activation() {
18454 $this->_logger->entrance();
18455
18456 $hook = false;
18457
18458 if ( ! $this->has_settings_menu() ) {
18459 // Add the opt-in page without a menu item.
18460 $hook = FS_Admin_Menu_Manager::add_subpage(
18461 '',
18462 $this->get_plugin_name(),
18463 $this->get_plugin_name(),
18464 'manage_options',
18465 $this->_slug,
18466 array( &$this, '_connect_page_render' )
18467 );
18468 } else if ( $this->_menu->is_top_level() ) {
18469 if ( $this->_menu->is_override_exact() ) {
18470 // Make sure the current page is matching the activation page.
18471 if ( ! $this->is_matching_url( $this->get_activation_url() ) ) {
18472 return;
18473 }
18474 }
18475
18476 $hook = $this->_menu->override_menu_item( array( &$this, '_connect_page_render' ) );
18477
18478 if ( false === $hook ) {
18479 // Create new menu item just for the opt-in.
18480 $hook = FS_Admin_Menu_Manager::add_page(
18481 $this->get_plugin_name(),
18482 $this->get_plugin_name(),
18483 'manage_options',
18484 $this->_menu->get_slug(),
18485 array( &$this, '_connect_page_render' )
18486 );
18487 }
18488 } else {
18489 $menus = array( $this->_menu->get_parent_slug() );
18490
18491 if ( $this->_menu->is_override_exact() ) {
18492 // Make sure the current page is matching the activation page.
18493 if ( ! $this->is_matching_url( $this->get_activation_url() ) ) {
18494 return;
18495 }
18496 }
18497
18498 foreach ( $menus as $parent_slug ) {
18499 $hook = $this->_menu->override_submenu_action(
18500 $parent_slug,
18501 $this->_menu->get_raw_slug(),
18502 array( &$this, '_connect_page_render' )
18503 );
18504
18505 if ( false !== $hook ) {
18506 // Found plugin's submenu item.
18507 break;
18508 }
18509 }
18510 }
18511
18512 if ( $this->is_activation_page() ) {
18513 // Clean admin page from distracting content.
18514 self::_clean_admin_content_section();
18515 }
18516
18517 if ( false !== $hook ) {
18518 if ( fs_request_is_action( $this->get_unique_affix() . '_activate_existing' ) ) {
18519 $this->_install_with_current_user();
18520 } else if ( fs_request_is_action( $this->get_unique_affix() . '_activate_new' ) ) {
18521 $this->_install_with_new_user();
18522 }
18523 }
18524 }
18525
18526 /**
18527 * If a plugin was network activated and connected but don't have a network
18528 * level settings, then add an artificial menu item for the Account and other
18529 * Freemius settings.
18530 *
18531 * @author Vova Feldman (@svovaf)
18532 * @since 2.0.0
18533 */
18534 private function add_network_menu_when_missing() {
18535 $this->_logger->entrance();
18536
18537 if ( ! $this->_is_network_active ) {
18538 // Plugin wasn't activated on the network level.
18539 return;
18540 }
18541
18542 if ( ! fs_is_network_admin() ) {
18543 // The context is not the network admin.
18544 return;
18545 }
18546
18547 if ( $this->_menu->has_network_menu() ) {
18548 // Plugin already has a network level menu.
18549 return;
18550 }
18551
18552 if ( $this->is_network_activation_mode() ) {
18553 /**
18554 * Do not add during activation mode, otherwise, there will be duplicate menus while the opt-in
18555 * screen is being shown.
18556 *
18557 * @author Leo Fajardo (@leorw)
18558 */
18559 return;
18560 }
18561
18562 if ( ! WP_FS__SHOW_NETWORK_EVEN_WHEN_DELEGATED ) {
18563 if ( $this->is_network_delegated_connection() ) {
18564 // Super-admin delegated the connection to the site admins.
18565 return;
18566 }
18567 }
18568
18569 if ( ! $this->_menu->has_menu() || $this->_menu->is_top_level() ) {
18570
18571 if ( $this->_menu->has_menu() ||
18572 ! $this->is_addon() ||
18573 $this->is_activation_mode()
18574 ) {
18575 $this->_dynamically_added_top_level_page_hook_name = $this->_menu->add_page_and_update(
18576 $this->get_plugin_name(),
18577 $this->get_plugin_name(),
18578 'manage_options',
18579 $this->_menu->has_menu() ? $this->_menu->get_slug() : $this->_slug
18580 );
18581 }
18582 } else {
18583 $this->_menu->add_subpage_and_update(
18584 $this->_menu->get_parent_slug(),
18585 $this->get_plugin_name(),
18586 $this->get_plugin_name(),
18587 'manage_options',
18588 $this->_menu->get_slug()
18589 );
18590 }
18591 }
18592
18593 /**
18594 * @author Leo Fajardo (@leorw)
18595 * @since 1.2.1
18596 *
18597 * return string
18598 */
18599 function get_top_level_menu_capability() {
18600 global $menu;
18601
18602 $top_level_menu_slug = $this->get_top_level_menu_slug();
18603
18604 foreach ( $menu as $menu_info ) {
18605 /**
18606 * The second element in the menu info array is the capability/role that has access to the menu and the
18607 * third element is the menu slug.
18608 */
18609 if ( $menu_info[2] === $top_level_menu_slug ) {
18610 return $menu_info[1];
18611 }
18612 }
18613
18614 return 'read';
18615 }
18616
18617 /**
18618 * @author Vova Feldman (@svovaf)
18619 * @since 1.0.0
18620 *
18621 * @return string
18622 */
18623 private function get_top_level_menu_slug() {
18624 return ( $this->is_addon() ?
18625 $this->get_parent_instance()->_menu->get_top_level_menu_slug() :
18626 $this->_menu->get_top_level_menu_slug() );
18627 }
18628
18629 /**
18630 * @author Vova Feldman (@svovaf)
18631 * @since 1.2.2.7
18632 *
18633 * @return string
18634 */
18635 function get_pricing_cta_label() {
18636 $label = $this->get_text_inline( 'Upgrade', 'upgrade' );
18637
18638 if ( $this->is_in_trial_promotion() &&
18639 ! $this->is_paying_or_trial()
18640 ) {
18641 // If running a trial promotion, modify the pricing to load the trial.
18642 $label = $this->get_text_inline( 'Start Trial', 'start-trial' );
18643 } else if ( $this->is_paying() ) {
18644 $label = $this->get_text_inline( 'Pricing', 'pricing' );
18645 }
18646
18647 return $label;
18648 }
18649
18650 /**
18651 * @author Vova Feldman (@svovaf)
18652 * @since 1.2.2.7
18653 *
18654 * @return bool
18655 */
18656 function is_pricing_page_visible() {
18657 return (
18658 // Has at least one paid plan.
18659 $this->has_paid_plan() &&
18660 // Didn't ask to hide the pricing page.
18661 $this->is_page_visible( 'pricing' ) &&
18662 // Don't have a valid active license or has more than one plan.
18663 ( ! $this->is_paying() || ! $this->is_single_plan( true ) )
18664 );
18665 }
18666
18667 /**
18668 * @author Leo Fajardo (@leorw)
18669 * @since 2.3.0
18670 *
18671 * @param bool $is_activation_mode
18672 *
18673 * @return bool
18674 */
18675 private function should_add_submenu_or_action_links( $is_activation_mode ) {
18676 if ( $this->is_addon() ) {
18677 // No submenu items or action links for add-ons.
18678 return false;
18679 }
18680
18681 if ( $this->show_opt_in_on_themes_page() ) {
18682 if ( ! fs_is_network_admin() ) {
18683 // Also add action links or submenu items when running in a free .org theme so the tabs will be visible.
18684 return true;
18685 }
18686 } else if ( $is_activation_mode ) {
18687 // Don't show submenu-items/tabs in activation mode, unless it's a wp.org theme.
18688 return false;
18689 }
18690
18691 if ( fs_is_network_admin() ) {
18692 /**
18693 * Add submenu items or action links to network level when plugin was network activated and the super
18694 * admin did NOT delegate the connection of all sites to site admins.
18695 */
18696 return (
18697 $this->_is_network_active &&
18698 ( WP_FS__SHOW_NETWORK_EVEN_WHEN_DELEGATED ||
18699 ! $this->is_network_delegated_connection() )
18700 );
18701 }
18702
18703 return ( ! $this->_is_network_active || $this->is_delegated_connection() );
18704 }
18705
18706 /**
18707 * Add default Freemius menu items.
18708 *
18709 * @author Vova Feldman (@svovaf)
18710 * @since 1.0.0
18711 * @since 1.2.2.7 Also add submenu items when running in a free .org theme so the tabs will be visible.
18712 */
18713 private function add_submenu_items() {
18714 $this->_logger->entrance();
18715
18716 $is_activation_mode = $this->is_activation_mode();
18717
18718 $add_submenu_items = $this->should_add_submenu_or_action_links( $is_activation_mode );
18719
18720 if ( $add_submenu_items ) {
18721 if ( $this->has_affiliate_program() ) {
18722 // Add affiliation page.
18723 $this->add_submenu_item(
18724 $this->get_text_inline( 'Affiliation', 'affiliation' ),
18725 array( &$this, '_affiliation_page_render' ),
18726 $this->get_plugin_name() . ' &ndash; ' . $this->get_text_inline( 'Affiliation', 'affiliation' ),
18727 'manage_options',
18728 'affiliation',
18729 'Freemius::_clean_admin_content_section',
18730 WP_FS__DEFAULT_PRIORITY,
18731 $this->is_submenu_item_visible( 'affiliation' )
18732 );
18733 }
18734 }
18735
18736 if ( $add_submenu_items ||
18737 ( $is_activation_mode &&
18738 $this->is_only_premium() &&
18739 $this->is_admin_page( 'account' ) &&
18740 fs_request_is_action( $this->get_unique_affix() . '_sync_license' )
18741 )
18742 ) {
18743 if ( ! WP_FS__DEMO_MODE && $this->is_registered() ) {
18744 $show_account = (
18745 $this->is_submenu_item_visible( 'account' ) &&
18746 /**
18747 * @since 1.2.2.7 Don't show the Account for free WP.org themes without any paid plans.
18748 */
18749 ( ! $this->is_free_wp_org_theme() || $this->has_paid_plan() )
18750 );
18751
18752 // Add user account page.
18753 $this->add_submenu_item(
18754 $this->get_text_inline( 'Account', 'account' ),
18755 array( &$this, '_account_page_render' ),
18756 $this->get_plugin_name() . ' &ndash; ' . $this->get_text_inline( 'Account', 'account' ),
18757 'manage_options',
18758 'account',
18759 array( &$this, '_account_page_load' ),
18760 WP_FS__DEFAULT_PRIORITY,
18761 ( $add_submenu_items && $show_account )
18762 );
18763 }
18764 }
18765
18766 if ( $add_submenu_items ) {
18767 if (! WP_FS__DEMO_MODE && ! $this->is_whitelabeled() ) {
18768 // Add contact page.
18769 $this->add_submenu_item(
18770 $this->get_text_inline( 'Contact Us', 'contact-us' ),
18771 array( &$this, '_contact_page_render' ),
18772 $this->get_plugin_name() . ' &ndash; ' . $this->get_text_inline( 'Contact Us', 'contact-us' ),
18773 'manage_options',
18774 'contact',
18775 'Freemius::_clean_admin_content_section',
18776 WP_FS__DEFAULT_PRIORITY,
18777 $this->is_submenu_item_visible( 'contact' )
18778 );
18779 }
18780
18781 if ( $this->has_addons() ) {
18782 $this->add_submenu_item(
18783 $this->get_text_inline( 'Add-Ons', 'add-ons' ),
18784 array( &$this, '_addons_page_render' ),
18785 $this->get_plugin_name() . ' &ndash; ' . $this->get_text_inline( 'Add-Ons', 'add-ons' ),
18786 'manage_options',
18787 'addons',
18788 array( &$this, '_addons_page_load' ),
18789 WP_FS__LOWEST_PRIORITY - 1,
18790 $this->is_submenu_item_visible( 'addons' )
18791 );
18792 }
18793 }
18794
18795 if ( $add_submenu_items ||
18796 ( $is_activation_mode && $this->is_only_premium() && $this->is_admin_page( 'pricing' ) )
18797 ) {
18798 if (! WP_FS__DEMO_MODE && ! $this->is_whitelabeled() ) {
18799 $show_pricing = (
18800 $this->is_submenu_item_visible( 'pricing' ) &&
18801 $this->is_pricing_page_visible()
18802 );
18803
18804 $pricing_cta_text = $this->get_pricing_cta_label();
18805 $pricing_class = 'upgrade-mode';
18806 if ( $show_pricing ) {
18807 if ( $this->is_in_trial_promotion() &&
18808 ! $this->is_paying_or_trial()
18809 ) {
18810 // If running a trial promotion, modify the pricing to load the trial.
18811 $pricing_class = 'trial-mode';
18812 } else if ( $this->is_paying() ) {
18813 $pricing_class = '';
18814 }
18815 }
18816
18817 $custom_pricing_url = $this->get_pricing_url_with_filter( null );
18818 $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' ) );
18819 $show_pricing_submenu_item = ( $add_submenu_items && $show_pricing );
18820
18821 // Add upgrade/pricing submenu item.
18822 if ( ! is_null( $custom_pricing_url ) ) {
18823 $this->add_submenu_link_item(
18824 $pricing_menu_title,
18825 $custom_pricing_url,
18826 'pricing',
18827 'manage_options',
18828 WP_FS__LOWEST_PRIORITY,
18829 $show_pricing_submenu_item,
18830 $pricing_class
18831 );
18832 } else {
18833 $this->add_submenu_item(
18834 $pricing_menu_title,
18835 array( &$this, '_pricing_page_render' ),
18836 $this->get_plugin_name() . ' &ndash; ' . $this->get_text_x_inline( 'Pricing', 'noun', 'pricing' ),
18837 'manage_options',
18838 'pricing',
18839 'Freemius::_clean_admin_content_section',
18840 WP_FS__LOWEST_PRIORITY,
18841 $show_pricing_submenu_item,
18842 $pricing_class
18843 );
18844 }
18845 }
18846 }
18847
18848 if ( ! $is_activation_mode || ( true !== $this->_storage->require_license_activation ) ) {
18849 /**
18850 * Add the other menu items if there are any when not in activation mode or license activation is not
18851 * required (license activation is required for registered or anonymous users after activating the
18852 * premium version when the site is not in trial mode or there's no active valid license).
18853 *
18854 * @author Leo Fajardo (@leorw)
18855 * @since 2.2.1
18856 */
18857 if ( 0 < count( $this->_menu_items ) ) {
18858 if ( ! $this->_menu->is_top_level() ) {
18859 fs_enqueue_local_style( 'fs_common', '/admin/common.css' );
18860
18861 // Append submenu items right after the plugin's submenu item.
18862 $this->order_sub_submenu_items();
18863 } else {
18864 // Append submenu items.
18865 $this->embed_submenu_items();
18866 }
18867 }
18868 }
18869 }
18870
18871 /**
18872 * Moved the actual submenu item additions to a separated function,
18873 * in order to support sub-submenu items when the plugin's settings
18874 * only have a submenu and not top-level menu item.
18875 *
18876 * @author Vova Feldman (@svovaf)
18877 * @since 1.1.4
18878 */
18879 private function embed_submenu_items() {
18880 $item_template = $this->_menu->is_top_level() ?
18881 '<span class="fs-submenu-item %s %s %s">%s</span>' :
18882 '<span class="fs-submenu-item fs-sub %s %s %s">%s</span>';
18883
18884 $top_level_menu_capability = $this->get_top_level_menu_capability();
18885
18886 ksort( $this->_menu_items );
18887
18888 $is_first_submenu_item = true;
18889
18890 foreach ( $this->_menu_items as $priority => $items ) {
18891 foreach ( $items as $item ) {
18892 $capability = ( ! empty( $item['capability'] ) ? $item['capability'] : $top_level_menu_capability );
18893
18894 $menu_item = sprintf(
18895 $item_template,
18896 $this->get_unique_affix(),
18897 $item['menu_slug'],
18898 ! empty( $item['class'] ) ? $item['class'] : '',
18899 $item['menu_title']
18900 );
18901
18902 $top_level_menu_slug = $this->get_top_level_menu_slug();
18903 $menu_slug = $this->_menu->get_slug( $item['menu_slug'] );
18904
18905 if ( ! isset( $item['url'] ) ) {
18906 $hook = FS_Admin_Menu_Manager::add_subpage(
18907 $item['show_submenu'] ?
18908 $top_level_menu_slug :
18909 '',
18910 $item['page_title'],
18911 $menu_item,
18912 $capability,
18913 $menu_slug,
18914 $item['render_function']
18915 );
18916
18917 if ( false !== $item['before_render_function'] ) {
18918 add_action( "load-$hook", $item['before_render_function'] );
18919 }
18920 } else {
18921 FS_Admin_Menu_Manager::add_subpage(
18922 $item['show_submenu'] ?
18923 $top_level_menu_slug :
18924 '',
18925 $item['page_title'],
18926 $menu_item,
18927 $capability,
18928 $menu_slug,
18929 array( $this, '' )
18930 );
18931 }
18932
18933 if ( $item['show_submenu'] && $is_first_submenu_item ) {
18934 if ( $this->_is_network_active && ! empty( $this->_dynamically_added_top_level_page_hook_name ) ) {
18935 /**
18936 * If the top-level menu has been dynamically created, remove the first submenu item that
18937 * WordPress automatically creates when there's no submenu item whose slug matches the
18938 * parent's. In the following example, the `Awesome Plugin` submenu item will be removed.
18939 *
18940 * Awesome Plugin
18941 * - Awesome Plugin <-- we want to remove this since there's no real setting page for the top-level
18942 *
18943 * @author Leo Fajardo (@leorw)
18944 */
18945 remove_submenu_page( $top_level_menu_slug, $top_level_menu_slug );
18946 }
18947
18948 $is_first_submenu_item = false;
18949 }
18950 }
18951 }
18952 }
18953
18954 /**
18955 * Re-order the submenu items so all Freemius added new submenu items
18956 * are added right after the plugin's settings submenu item.
18957 *
18958 * @author Vova Feldman (@svovaf)
18959 * @since 1.1.4
18960 */
18961 private function order_sub_submenu_items() {
18962 global $submenu;
18963
18964 $menu_slug = $this->_menu->get_top_level_menu_slug();
18965
18966 /**
18967 * Before "admin_menu" fires, WordPress will loop over the default submenus and remove pages for which the user
18968 * does not have permissions. So in case a plugin does not have top-level menu but does have submenus under any
18969 * of the default menus, only users that have the right role can access its sub-submenus (Account, Contact Us,
18970 * Support Forum, etc.) since $submenu[ $menu_slug ] will be empty if the user doesn't have permission.
18971 *
18972 * In case a plugin does not have submenus under any of the default menus but does have submenus under the menu
18973 * of another plugin, only users that have the right role can access its sub-submenus since we will use the
18974 * capability needed to access the parent menu as the capability for the submenus that we will add.
18975 */
18976 if ( empty( $submenu[ $menu_slug ] ) ) {
18977 return;
18978 }
18979
18980 $top_level_menu = &$submenu[ $menu_slug ];
18981
18982 $all_submenu_items_after = array();
18983
18984 $found_submenu_item = false;
18985
18986 foreach ( $top_level_menu as $submenu_id => $meta ) {
18987 if ( $found_submenu_item ) {
18988 // Remove all submenu items after the plugin's submenu item.
18989 $all_submenu_items_after[] = $meta;
18990 unset( $top_level_menu[ $submenu_id ] );
18991 }
18992
18993 if ( $this->_menu->get_raw_slug() === $meta[2] ) {
18994 // Found the submenu item, put all below.
18995 $found_submenu_item = true;
18996 continue;
18997 }
18998 }
18999
19000 // Embed all plugin's new submenu items.
19001 $this->embed_submenu_items();
19002
19003 // Start with specially high number to make sure it's appended.
19004 $i = max( 10000, max( array_keys( $top_level_menu ) ) + 1 );
19005 foreach ( $all_submenu_items_after as $meta ) {
19006 $top_level_menu[ $i ] = $meta;
19007 $i ++;
19008 }
19009
19010 // Sort submenu items.
19011 ksort( $top_level_menu );
19012 }
19013
19014 /**
19015 * Helper method to return the module's support forum URL.
19016 *
19017 * @author Vova Feldman (@svovaf)
19018 * @since 1.2.2.7
19019 *
19020 * @return string
19021 */
19022 function get_support_forum_url() {
19023 return $this->apply_filters( 'support_forum_url', "https://wordpress.org/support/{$this->_module_type}/{$this->_slug}" );
19024 }
19025
19026 /**
19027 * Displays the Support Forum link when enabled.
19028 *
19029 * Can be filtered like so:
19030 *
19031 * function _fs_show_support_menu( $is_visible, $menu_id ) {
19032 * if ( 'support' === $menu_id ) {
19033 * return _fs->is_registered();
19034 * }
19035 * return $is_visible;
19036 * }
19037 * _fs()->add_filter('is_submenu_visible', '_fs_show_support_menu', 10, 2);
19038 *
19039 */
19040 function _add_default_submenu_items() {
19041 if ( ! $this->is_on() ) {
19042 return;
19043 }
19044
19045 if ( ! $this->is_activation_mode() &&
19046 ( ( $this->_is_network_active && fs_is_network_admin() ) ||
19047 ( ! $this->_is_network_active && is_admin() ) )
19048 ) {
19049 $this->add_submenu_link_item(
19050 $this->apply_filters( 'support_forum_submenu', $this->get_text_inline( 'Support Forum', 'support-forum' ) ),
19051 $this->get_support_forum_url(),
19052 'wp-support-forum',
19053 null,
19054 50,
19055 $this->is_submenu_item_visible( 'support' )
19056 );
19057 }
19058 }
19059
19060 /**
19061 * @author Vova Feldman (@svovaf)
19062 * @since 1.0.1
19063 *
19064 * @param string $menu_title
19065 * @param callable $render_function
19066 * @param bool|string $page_title
19067 * @param string $capability
19068 * @param bool|string $menu_slug
19069 * @param bool|callable $before_render_function
19070 * @param int $priority
19071 * @param bool $show_submenu
19072 * @param string $class Since 1.2.1.5 can add custom classes to menu items.
19073 */
19074 function add_submenu_item(
19075 $menu_title,
19076 $render_function,
19077 $page_title = false,
19078 $capability = 'manage_options',
19079 $menu_slug = false,
19080 $before_render_function = false,
19081 $priority = WP_FS__DEFAULT_PRIORITY,
19082 $show_submenu = true,
19083 $class = ''
19084 ) {
19085 $this->_logger->entrance( 'Title = ' . $menu_title );
19086
19087 if ( $this->is_addon() ) {
19088 $parent_fs = $this->get_parent_instance();
19089
19090 if ( is_object( $parent_fs ) ) {
19091 $parent_fs->add_submenu_item(
19092 $menu_title,
19093 $render_function,
19094 $page_title,
19095 $capability,
19096 $menu_slug,
19097 $before_render_function,
19098 $priority,
19099 $show_submenu,
19100 $class
19101 );
19102
19103 return;
19104 }
19105 }
19106
19107 if ( ! isset( $this->_menu_items[ $priority ] ) ) {
19108 $this->_menu_items[ $priority ] = array();
19109 }
19110
19111 $this->_menu_items[ $priority ][] = array(
19112 'page_title' => is_string( $page_title ) ? $page_title : $menu_title,
19113 'menu_title' => $menu_title,
19114 'capability' => $capability,
19115 'menu_slug' => is_string( $menu_slug ) ? $menu_slug : strtolower( $menu_title ),
19116 'render_function' => $render_function,
19117 'before_render_function' => $before_render_function,
19118 'show_submenu' => $show_submenu,
19119 'class' => $class,
19120 );
19121 }
19122
19123 /**
19124 * @author Vova Feldman (@svovaf)
19125 * @since 1.0.1
19126 *
19127 * @param string $menu_title
19128 * @param string $url
19129 * @param bool $menu_slug
19130 * @param string $capability
19131 * @param int $priority
19132 * @param bool $show_submenu
19133 * @param string $class
19134 */
19135 function add_submenu_link_item(
19136 $menu_title,
19137 $url,
19138 $menu_slug = false,
19139 $capability = 'read',
19140 $priority = WP_FS__DEFAULT_PRIORITY,
19141 $show_submenu = true,
19142 $class = ''
19143 ) {
19144 $this->_logger->entrance( 'Title = ' . $menu_title . '; Url = ' . $url );
19145
19146 if ( $this->is_addon() ) {
19147 $parent_fs = $this->get_parent_instance();
19148
19149 if ( is_object( $parent_fs ) ) {
19150 $parent_fs->add_submenu_link_item(
19151 $menu_title,
19152 $url,
19153 $menu_slug,
19154 $capability,
19155 $priority,
19156 $show_submenu,
19157 $class
19158 );
19159
19160 return;
19161 }
19162 }
19163
19164 if ( ! isset( $this->_menu_items[ $priority ] ) ) {
19165 $this->_menu_items[ $priority ] = array();
19166 }
19167
19168 $this->_menu_items[ $priority ][] = array(
19169 'menu_title' => $menu_title,
19170 'capability' => $capability,
19171 'menu_slug' => is_string( $menu_slug ) ? $menu_slug : strtolower( $menu_title ),
19172 'url' => $url,
19173 'page_title' => $menu_title,
19174 'render_function' => 'fs_dummy',
19175 'before_render_function' => '',
19176 'show_submenu' => $show_submenu,
19177 'class' => $class,
19178 );
19179 }
19180
19181 #endregion ------------------------------------------------------------------
19182
19183 #--------------------------------------------------------------------------------
19184 #region Admin Notices
19185 #--------------------------------------------------------------------------------
19186
19187 /**
19188 * @author Vova Feldman (@svovaf)
19189 * @since 2.3.1
19190 *
19191 * @param string|string[] $ids
19192 * @param int|null $network_level_or_blog_id
19193 *
19194 * @uses FS_Admin_Notices::remove_sticky()
19195 */
19196 function remove_sticky( $ids, $network_level_or_blog_id = null ) {
19197 $this->_admin_notices->remove_sticky( $ids, $network_level_or_blog_id );
19198 }
19199
19200 #endregion
19201
19202 #--------------------------------------------------------------------------------
19203 #region Actions / Hooks / Filters
19204 #--------------------------------------------------------------------------------
19205
19206 /**
19207 * @author Vova Feldman (@svovaf)
19208 * @since 1.1.7
19209 *
19210 * @param string $tag
19211 *
19212 * @return string
19213 */
19214 public function get_action_tag( $tag ) {
19215 return self::get_action_tag_static( $tag, $this->_slug, $this->is_plugin() );
19216 }
19217
19218 /**
19219 * @author Vova Feldman (@svovaf)
19220 * @since 1.2.1.6
19221 *
19222 * @param string $tag
19223 * @param string $slug
19224 * @param bool $is_plugin
19225 *
19226 * @return string
19227 */
19228 static function get_action_tag_static( $tag, $slug = '', $is_plugin = true ) {
19229 $action = "fs_{$tag}";
19230
19231 if ( ! empty( $slug ) ) {
19232 $action .= '_' . self::get_module_unique_affix( $slug, $is_plugin );
19233 }
19234
19235 return $action;
19236 }
19237
19238 /**
19239 * Returns a string that can be used to generate a unique action name,
19240 * option name, HTML element ID, or HTML element class.
19241 *
19242 * @author Leo Fajardo (@leorw)
19243 * @since 1.2.2
19244 *
19245 * @return string
19246 */
19247 public function get_unique_affix() {
19248 return self::get_module_unique_affix( $this->_slug, $this->is_plugin() );
19249 }
19250
19251 /**
19252 * Returns a string that can be used to generate a unique action name,
19253 * option name, HTML element ID, or HTML element class.
19254 *
19255 * @author Vova Feldman (@svovaf)
19256 * @since 1.2.2.5
19257 *
19258 * @param string $slug
19259 * @param bool $is_plugin
19260 *
19261 * @return string
19262 */
19263 static function get_module_unique_affix( $slug, $is_plugin = true ) {
19264 $affix = $slug;
19265
19266 if ( ! $is_plugin ) {
19267 $affix .= '-' . WP_FS__MODULE_TYPE_THEME;
19268 }
19269
19270 return $affix;
19271 }
19272
19273 /**
19274 * @author Vova Feldman (@svovaf)
19275 * @since 1.2.1
19276 * @since 1.2.2.5 The AJAX action names are based on the module ID, not like the non-AJAX actions that are
19277 * based on the slug for backward compatibility.
19278 *
19279 * @param string $tag
19280 *
19281 * @return string
19282 */
19283 function get_ajax_action( $tag ) {
19284 return self::get_ajax_action_static( $tag, $this->_module_id );
19285 }
19286
19287 /**
19288 * @author Vova Feldman (@svovaf)
19289 * @since 1.2.1.7
19290 *
19291 * @param string $tag
19292 *
19293 * @return string
19294 */
19295 function get_ajax_security( $tag ) {
19296 return wp_create_nonce( $this->get_ajax_action( $tag ) );
19297 }
19298
19299 /**
19300 * @author Vova Feldman (@svovaf)
19301 * @since 1.2.1.7
19302 *
19303 * @param string $tag
19304 */
19305 function check_ajax_referer( $tag ) {
19306 check_ajax_referer( $this->get_ajax_action( $tag ), 'security' );
19307 }
19308
19309 /**
19310 * @author Vova Feldman (@svovaf)
19311 * @since 1.2.1.6
19312 * @since 1.2.2.5 The AJAX action names are based on the module ID, not like the non-AJAX actions that are
19313 * based on the slug for backward compatibility.
19314 *
19315 * @param string $tag
19316 * @param number|null $module_id
19317 *
19318 * @return string
19319 */
19320 static function get_ajax_action_static( $tag, $module_id = null ) {
19321 $action = "fs_{$tag}";
19322
19323 if ( ! empty( $module_id ) ) {
19324 $action .= "_{$module_id}";
19325 }
19326
19327 return $action;
19328 }
19329
19330 /**
19331 * Do action, specific for the current context plugin.
19332 *
19333 * @author Vova Feldman (@svovaf)
19334 * @since 1.0.1
19335 *
19336 * @param string $tag The name of the action to be executed.
19337 * @param mixed $arg,... Optional. Additional arguments which are passed on to the
19338 * functions hooked to the action. Default empty.
19339 *
19340 * @uses do_action()
19341 */
19342 function do_action( $tag, $arg = '' ) {
19343 $args = func_get_args();
19344
19345 $this->_logger->entrance( $tag );
19346
19347 call_user_func_array( 'do_action', array_merge(
19348 array( $this->get_action_tag( $tag ) ),
19349 array_slice( $args, 1 ) )
19350 );
19351 }
19352
19353 /**
19354 * Add action, specific for the current context plugin.
19355 *
19356 * @author Vova Feldman (@svovaf)
19357 * @since 1.0.1
19358 *
19359 * @param string $tag
19360 * @param callable $function_to_add
19361 * @param int $priority
19362 * @param int $accepted_args
19363 *
19364 * @uses add_action()
19365 */
19366 function add_action(
19367 $tag,
19368 $function_to_add,
19369 $priority = WP_FS__DEFAULT_PRIORITY,
19370 $accepted_args = 1
19371 ) {
19372 $this->_logger->entrance( $tag );
19373
19374 add_action( $this->get_action_tag( $tag ), $function_to_add, $priority, $accepted_args );
19375 }
19376
19377 /**
19378 * Add AJAX action, specific for the current context plugin.
19379 *
19380 * @author Vova Feldman (@svovaf)
19381 * @since 1.2.1
19382 *
19383 * @param string $tag
19384 * @param callable $function_to_add
19385 * @param int $priority
19386 *
19387 * @uses add_action()
19388 *
19389 * @return bool True if action added, false if no need to add the action since the AJAX call isn't matching.
19390 */
19391 function add_ajax_action(
19392 $tag,
19393 $function_to_add,
19394 $priority = WP_FS__DEFAULT_PRIORITY
19395 ) {
19396 $this->_logger->entrance( $tag );
19397
19398 return self::add_ajax_action_static(
19399 $tag,
19400 $function_to_add,
19401 $priority,
19402 $this->_module_id
19403 );
19404 }
19405
19406 /**
19407 * Add AJAX action.
19408 *
19409 * @author Vova Feldman (@svovaf)
19410 * @since 1.2.1.6
19411 *
19412 * @param string $tag
19413 * @param callable $function_to_add
19414 * @param int $priority
19415 * @param number|null $module_id
19416 *
19417 * @return bool True if action added, false if no need to add the action since the AJAX call isn't matching.
19418 * @uses add_action()
19419 *
19420 */
19421 static function add_ajax_action_static(
19422 $tag,
19423 $function_to_add,
19424 $priority = WP_FS__DEFAULT_PRIORITY,
19425 $module_id = null
19426 ) {
19427 self::$_static_logger->entrance( $tag );
19428
19429 if ( ! self::is_ajax_action_static( $tag, $module_id ) ) {
19430 return false;
19431 }
19432
19433 add_action(
19434 'wp_ajax_' . self::get_ajax_action_static( $tag, $module_id ),
19435 $function_to_add,
19436 $priority,
19437 0
19438 );
19439
19440 self::$_static_logger->info( "$tag AJAX callback action added." );
19441
19442 return true;
19443 }
19444
19445 /**
19446 * Send a JSON response back to an Ajax request.
19447 *
19448 * @author Vova Feldman (@svovaf)
19449 * @since 1.2.1.5
19450 *
19451 * @param mixed $response
19452 */
19453 static function shoot_ajax_response( $response ) {
19454 wp_send_json( $response );
19455 }
19456
19457 /**
19458 * Send a JSON response back to an Ajax request, indicating success.
19459 *
19460 * @author Vova Feldman (@svovaf)
19461 * @since 1.2.1.5
19462 *
19463 * @param mixed $data Data to encode as JSON, then print and exit.
19464 */
19465 static function shoot_ajax_success( $data = null ) {
19466 wp_send_json_success( $data );
19467 }
19468
19469 /**
19470 * Send a JSON response back to an Ajax request, indicating failure.
19471 *
19472 * @author Vova Feldman (@svovaf)
19473 * @since 1.2.1.5
19474 *
19475 * @param mixed $error Optional error message.
19476 */
19477 static function shoot_ajax_failure( $error = '' ) {
19478 $result = array( 'success' => false );
19479 if ( ! empty( $error ) ) {
19480 $result['error'] = $error;
19481 }
19482
19483 wp_send_json( $result );
19484 }
19485
19486 /**
19487 * Returns an AJAX URL with a special extra param to indicate whether the request was triggered from the network admin or blog admin.
19488 *
19489 * @author Vova Feldman (@svovaf)
19490 * @since 2.5.1
19491 *
19492 * @param string $wrap_with By default, returns the AJAX URL wrapped with single quotes.
19493 *
19494 * @return string
19495 */
19496 static function ajax_url( $wrap_with = "'") {
19497 if ( fs_is_network_admin() ) {
19498 $param_name = '_fs_network_admin';
19499 } else {
19500 $param_name = '_fs_blog_admin';
19501 }
19502
19503 $url = admin_url( 'admin-ajax.php', 'relative' );
19504 $url .= ( false === strpos( $url, '?' ) ) ? '?' : '&';
19505 $url .= "{$param_name}=true";
19506
19507 return "{$wrap_with}{$url}{$wrap_with}";
19508 }
19509
19510 /**
19511 * Apply filter, specific for the current context plugin.
19512 *
19513 * @author Vova Feldman (@svovaf)
19514 * @since 1.0.9
19515 *
19516 * @param string $tag The name of the filter hook.
19517 * @param mixed $value The value on which the filters hooked to `$tag` are applied on.
19518 *
19519 * @return mixed The filtered value after all hooked functions are applied to it.
19520 *
19521 * @uses apply_filters()
19522 */
19523 function apply_filters( $tag, $value ) {
19524 $args = func_get_args();
19525
19526 $this->_logger->entrance( $tag );
19527
19528 array_unshift( $args, $this->get_unique_affix() );
19529
19530 return call_user_func_array( 'fs_apply_filter', $args );
19531 }
19532
19533 /**
19534 * Add filter, specific for the current context plugin.
19535 *
19536 * @author Vova Feldman (@svovaf)
19537 * @since 1.0.9
19538 *
19539 * @param string $tag
19540 * @param callable $function_to_add
19541 * @param int $priority
19542 * @param int $accepted_args
19543 *
19544 * @uses add_filter()
19545 */
19546 function add_filter( $tag, $function_to_add, $priority = WP_FS__DEFAULT_PRIORITY, $accepted_args = 1 ) {
19547 $this->_logger->entrance( $tag );
19548
19549 add_filter( $this->get_action_tag( $tag ), $function_to_add, $priority, $accepted_args );
19550 }
19551
19552 /**
19553 * Check if has filter.
19554 *
19555 * @author Vova Feldman (@svovaf)
19556 * @since 1.1.4
19557 *
19558 * @param string $tag
19559 * @param callable|bool $function_to_check Optional. The callback to check for. Default false.
19560 *
19561 * @return false|int
19562 *
19563 * @uses has_filter()
19564 */
19565 function has_filter( $tag, $function_to_check = false ) {
19566 $this->_logger->entrance( $tag );
19567
19568 return has_filter( $this->get_action_tag( $tag ), $function_to_check );
19569 }
19570
19571 #endregion
19572
19573 /**
19574 * Override default i18n text phrases.
19575 *
19576 * @author Vova Feldman (@svovaf)
19577 * @since 1.1.6
19578 *
19579 * @param string[] string $key_value
19580 *
19581 * @uses fs_override_i18n()
19582 */
19583 function override_i18n( $key_value ) {
19584 fs_override_i18n( $key_value, $this->_slug );
19585 }
19586
19587 /* Account Page
19588 ------------------------------------------------------------------------------------------------------------------*/
19589 /**
19590 * Update site information.
19591 *
19592 * @author Vova Feldman (@svovaf)
19593 * @since 1.0.1
19594 *
19595 * @param bool $store Flush to Database if true.
19596 * @param null|int $network_level_or_blog_id Since 2.0.0
19597 * @param \FS_Site $site Since 2.0.0
19598 */
19599 private function _store_site( $store = true, $network_level_or_blog_id = null, FS_Site $site = null, $is_backup = false ) {
19600 $this->_logger->entrance();
19601
19602 if ( is_null( $site ) ) {
19603 $site = $this->_site;
19604 }
19605
19606 if ( !isset( $site ) || !is_object($site) || empty( $site->id ) ) {
19607 $this->_logger->error( "Empty install ID, can't store site." );
19608
19609 return;
19610 }
19611
19612 $site_clone = clone $site;
19613
19614 $sites = self::get_all_sites( $this->_module_type, $network_level_or_blog_id, $is_backup );
19615
19616 if (
19617 ! $is_backup &&
19618 is_object( $this->_user ) && $this->_user->id != $site->user_id
19619 ) {
19620 $this->sync_user_by_current_install( $site->user_id );
19621
19622 $prev_stored_user_id = $this->_storage->get( 'prev_user_id', false, $network_level_or_blog_id );
19623
19624 if ( empty( $prev_stored_user_id ) &&
19625 is_object($this->_user) && $this->_user->id != $site->user_id
19626 ) {
19627 /**
19628 * Store the current user ID as the previous user ID so that the previous user can be used
19629 * as the install's owner while the new owner's details are not yet available.
19630 *
19631 * This will be executed only in the `replica` site. For example, there are 2 sites, namely `original`
19632 * and `replica`, then an ownership change was initiated and completed in the `original`, the `replica`
19633 * will be using the previous user until it is updated again (e.g.: until the next clone of `original`
19634 * into `replica`.
19635 *
19636 * @author Leo Fajardo (@leorw)
19637 */
19638 $this->_storage->store( 'prev_user_id', $sites[ $this->_slug ]->user_id, $network_level_or_blog_id );
19639 }
19640 }
19641
19642 $sites[ $this->_slug ] = $site_clone;
19643
19644 $this->set_account_option(
19645 ( $is_backup ? 'prev_' : '' ) . 'sites',
19646 $sites,
19647 $store,
19648 $network_level_or_blog_id
19649 );
19650 }
19651
19652 /**
19653 * 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).
19654 *
19655 * @author Leo Fajardo (@leorw)
19656 * @since 2.5.0
19657 */
19658 private function back_up_site() {
19659 $this->_logger->entrance();
19660
19661 $site_clone = clone $this->_site;
19662
19663 $this->_store_site( true, null, $site_clone, true );
19664 }
19665
19666 /**
19667 * Update plugin's plans information.
19668 *
19669 * @author Vova Feldman (@svovaf)
19670 * @since 1.0.2
19671 *
19672 * @param bool $store Flush to Database if true.
19673 */
19674 private function _store_plans( $store = true ) {
19675 $this->_logger->entrance();
19676
19677 $plans = self::get_all_plans( $this->_module_type );
19678
19679 // Copy plans.
19680 $encrypted_plans = array();
19681 for ( $i = 0, $len = count( $this->_plans ); $i < $len; $i ++ ) {
19682 $encrypted_plans[] = self::_encrypt_entity( $this->_plans[ $i ] );
19683 }
19684
19685 $plans[ $this->_slug ] = $encrypted_plans;
19686
19687 $this->set_account_option( 'plans', $plans, $store );
19688 }
19689
19690 /**
19691 * Update user's plugin licenses.
19692 *
19693 * @author Vova Feldman (@svovaf)
19694 * @since 1.0.5
19695 *
19696 * @param bool $store
19697 * @param number|bool $module_id
19698 * @param FS_Plugin_License[] $licenses
19699 */
19700 private function _store_licenses( $store = true, $module_id = false, $licenses = array() ) {
19701 $this->_logger->entrance();
19702
19703 $all_licenses = self::get_all_licenses();
19704
19705 if ( ! FS_Plugin::is_valid_id( $module_id ) ) {
19706 $module_id = $this->_module_id;
19707
19708 $user_licenses = is_array( $this->_licenses ) ?
19709 $this->_licenses :
19710 array();
19711
19712 if ( empty( $user_licenses ) ) {
19713 // If the context user doesn't have any license, don't update the licenses collection.
19714 return;
19715 }
19716
19717 $new_user_licenses_map = array();
19718 foreach ( $user_licenses as $user_license ) {
19719 $new_user_licenses_map[ $user_license->id ] = $user_license;
19720 }
19721
19722 self::store_user_id_license_ids_map( array_keys( $new_user_licenses_map ), $this->_module_id, $this->_user->id );
19723
19724 // Update user licenses.
19725 $licenses_to_update_count = count( $new_user_licenses_map );
19726 foreach ( $all_licenses[ $module_id ] as $key => $license ) {
19727 if ( 0 === $licenses_to_update_count ) {
19728 break;
19729 }
19730
19731 if ( isset( $new_user_licenses_map[ $license->id ] ) ) {
19732 // Update license.
19733 $all_licenses[ $module_id ][ $key ] = $new_user_licenses_map[ $license->id ];
19734 unset( $new_user_licenses_map[ $license->id ] );
19735
19736 $licenses_to_update_count --;
19737 }
19738 }
19739
19740 if ( ! empty( $new_user_licenses_map ) ) {
19741 // Add new licenses.
19742 $all_licenses[ $module_id ] = array_merge( array_values( $new_user_licenses_map ), $all_licenses[ $module_id ] );
19743 }
19744
19745 $licenses = $all_licenses[ $module_id ];
19746 }
19747
19748 if ( ! isset( $all_licenses[ $module_id ] ) ) {
19749 $all_licenses[ $module_id ] = array();
19750 }
19751
19752 $all_licenses[ $module_id ] = $licenses;
19753
19754 self::$_accounts->set_option( 'all_licenses', $all_licenses, $store );
19755 }
19756
19757 /**
19758 * Update user information.
19759 *
19760 * @author Vova Feldman (@svovaf)
19761 * @since 1.0.1
19762 *
19763 * @param bool $store Flush to Database if true.
19764 */
19765 private function _store_user( $store = true ) {
19766 $this->_logger->entrance();
19767
19768 if ( empty( $this->_user->id ) ) {
19769 $this->_logger->error( "Empty user ID, can't store user." );
19770
19771 return;
19772 }
19773
19774 $users = self::get_all_users();
19775 $users[ $this->_user->id ] = $this->_user;
19776 self::$_accounts->set_option( 'users', $users, $store );
19777 }
19778
19779 /**
19780 * Update new updates information.
19781 *
19782 * @author Vova Feldman (@svovaf)
19783 * @since 1.0.4
19784 *
19785 * @param FS_Plugin_Tag|null $update
19786 * @param bool $store Flush to Database if true.
19787 * @param bool|number $plugin_id
19788 */
19789 private function _store_update( $update, $store = true, $plugin_id = false ) {
19790 $this->_logger->entrance();
19791
19792 if ( $update instanceof FS_Plugin_Tag ) {
19793 $update->updated = time();
19794 }
19795
19796 if ( ! is_numeric( $plugin_id ) ) {
19797 $plugin_id = $this->_plugin->id;
19798 }
19799
19800 $updates = self::get_all_updates();
19801 $updates[ $plugin_id ] = $update;
19802 self::$_accounts->set_option( 'updates', $updates, $store );
19803 }
19804
19805 /**
19806 * Update new updates information.
19807 *
19808 * @author Vova Feldman (@svovaf)
19809 * @since 1.0.6
19810 *
19811 * @param FS_Plugin[] $plugin_addons
19812 * @param bool $store Flush to Database if true.
19813 */
19814 private function _store_addons( $plugin_addons, $store = true ) {
19815 $this->_logger->entrance();
19816
19817 $addons = self::get_all_addons();
19818 $addons[ $this->_plugin->id ] = $plugin_addons;
19819 self::$_accounts->set_option( 'addons', $addons, $store );
19820 }
19821
19822 /**
19823 * Delete plugin's associated add-ons.
19824 *
19825 * @author Vova Feldman (@svovaf)
19826 * @since 1.0.8
19827 *
19828 * @param bool $store
19829 *
19830 * @return bool
19831 */
19832 private function _delete_account_addons( $store = true ) {
19833 $all_addons = self::get_all_account_addons();
19834
19835 if ( ! isset( $all_addons[ $this->_plugin->id ] ) ) {
19836 return false;
19837 }
19838
19839 unset( $all_addons[ $this->_plugin->id ] );
19840
19841 self::$_accounts->set_option( 'account_addons', $all_addons, $store );
19842
19843 return true;
19844 }
19845
19846 /**
19847 * Update account add-ons list.
19848 *
19849 * @author Vova Feldman (@svovaf)
19850 * @since 1.0.6
19851 *
19852 * @param FS_Plugin[] $addons
19853 * @param bool $store Flush to Database if true.
19854 */
19855 private function _store_account_addons( $addons, $store = true ) {
19856 $this->_logger->entrance();
19857
19858 $all_addons = self::get_all_account_addons();
19859 $all_addons[ $this->_plugin->id ] = $addons;
19860 self::$_accounts->set_option( 'account_addons', $all_addons, $store );
19861 }
19862
19863 /**
19864 * Purges the cache for the valid user licenses API call so that when the `Account` or `Add-Ons` page is loaded,
19865 * the valid user licenses will be fetched again and the account add-ons may be updated.
19866 *
19867 * @author Leo Fajardo (@leorw)
19868 * @since 2.2.4
19869 */
19870 private function purge_valid_user_licenses_cache() {
19871 if ( ! $this->is_registered() ) {
19872 return;
19873 }
19874
19875 $this->get_api_user_scope()->purge_cache( $this->get_valid_user_licenses_endpoint() );
19876 }
19877
19878 /**
19879 * @author Leo Fajardo (@leorw)
19880 * @since 2.3.0
19881 *
19882 * @param array $all_licenses
19883 * @param number|null $site_license_id
19884 * @param bool $include_parent_licenses
19885 *
19886 * @return array
19887 */
19888 private function get_foreign_licenses_info( $all_licenses, $site_license_id = null, $include_parent_licenses = false ) {
19889 $foreign_licenses = array(
19890 'ids' => array(),
19891 'license_keys' => array()
19892 );
19893
19894 $parent_license_ids_map = array();
19895
19896 foreach ( $all_licenses as $license ) {
19897 if ( $license->user_id == $this->_user->id || $license->id == $site_license_id ) {
19898 continue;
19899 }
19900
19901 $foreign_licenses['ids'][] = $license->id;
19902 $foreign_licenses['license_keys'][] = $license->secret_key;
19903
19904 if (
19905 $include_parent_licenses &&
19906 is_object( $this->_license ) &&
19907 FS_Plugin_License::is_valid_id( $this->_license->parent_license_id ) &&
19908 ! isset( $parent_license_ids_map[ $this->_license->parent_license_id ] )
19909 ) {
19910 /**
19911 * Include the parent license's info only if it has not been included before since child licenses
19912 * can have the same parent license.
19913 */
19914 $foreign_licenses['ids'][] = $this->_license->parent_license_id;
19915 $foreign_licenses['license_keys'][] = $license->secret_key;
19916
19917 $parent_license_ids_map[ $this->_license->parent_license_id ] = true;
19918 }
19919 }
19920
19921 if ( empty( $foreign_licenses['ids'] ) ) {
19922 $foreign_licenses = array();
19923 }
19924
19925 return $foreign_licenses;
19926 }
19927
19928 /**
19929 * @author Leo Fajardo (@leorw)
19930 * @since 2.3.0
19931 *
19932 * @return string
19933 */
19934 private function get_valid_user_licenses_endpoint() {
19935 $user_licenses_endpoint = '/licenses.json?type=active' .
19936 ( FS_Plugin::is_valid_id( $this->get_bundle_id() ) ? '&is_enriched=true' : '' );
19937
19938 $foreign_licenses = $this->get_foreign_licenses_info( self::get_all_licenses( $this->_module_id ), null, true );
19939
19940 if ( ! empty ( $foreign_licenses ) ) {
19941 $foreign_licenses = array(
19942 // Prefix with `+` to tell the server to include foreign licenses in the licenses collection.
19943 'ids' => ( urlencode( '+' ) . implode( ',', $foreign_licenses['ids'] ) ),
19944 'license_keys' => implode( ',', array_map( 'urlencode', $foreign_licenses['license_keys'] ) )
19945 );
19946
19947 $user_licenses_endpoint = add_query_arg( $foreign_licenses, $user_licenses_endpoint );
19948 }
19949
19950 return $user_licenses_endpoint;
19951 }
19952
19953 /**
19954 * Fetches active licenses that are enriched with product type if there's a context `bundle_id` and bundle
19955 * licenses enriched with product IDs if there are any. From the licenses, the `get_updated_account_addons`
19956 * method filters out non–add-on product IDs and stores the add-on IDs.
19957 *
19958 * @author Leo Fajardo (@leorw)
19959 * @since 2.2.4
19960 *
19961 * @return stdClass[] array
19962 */
19963 private function fetch_valid_user_licenses() {
19964 $this->_logger->entrance();
19965
19966 $result = $this->get_api_user_scope()->get( $this->get_valid_user_licenses_endpoint() );
19967
19968 if ( ! $this->is_api_result_object( $result, 'licenses' ) ||
19969 ! is_array( $result->licenses )
19970 ) {
19971 return array();
19972 }
19973
19974 return $result->licenses;
19975 }
19976
19977 /**
19978 * @author Leo Fajardo (@leorw)
19979 * @since 2.2.4
19980 *
19981 * @return number[] Account add-on IDs.
19982 */
19983 function get_updated_account_addons() {
19984 $addons = $this->get_addons();
19985 if ( empty( $addons ) ) {
19986 return array();
19987 }
19988
19989 $account_addons = $this->get_account_addons();
19990 if ( ! is_array( $account_addons ) ) {
19991 $account_addons = array();
19992 }
19993
19994 $user_licenses = $this->is_registered() ?
19995 $this->fetch_valid_user_licenses() :
19996 array();
19997
19998 if ( empty( $user_licenses ) ) {
19999 return $account_addons;
20000 }
20001
20002 $addon_ids = array();
20003 foreach ( $addons as $addon ) {
20004 $addon_ids[] = $addon->id;
20005 }
20006
20007 $license_product_ids = array();
20008
20009 foreach ( $user_licenses as $license ) {
20010 if ( isset( $license->plugin_type ) && 'bundle' === $license->plugin_type ) {
20011 $license_product_ids = array_merge( $license_product_ids, $license->products );
20012 } else {
20013 $license_product_ids[] = $license->plugin_id;
20014 }
20015 }
20016
20017 // Filter out non–add-on IDs.
20018 $new_account_addons = array_intersect( $addon_ids, $license_product_ids );
20019 if ( count( $new_account_addons ) !== count( $account_addons ) ) {
20020 $this->_store_account_addons( array_unique( $new_account_addons ) );
20021 }
20022
20023 return $new_account_addons;
20024 }
20025
20026 /**
20027 * Store account params in the Database.
20028 *
20029 * @author Vova Feldman (@svovaf)
20030 * @since 1.0.1
20031 *
20032 * @param null|int $blog_id Since 2.0.0
20033 */
20034 private function _store_account( $blog_id = null ) {
20035 $this->_logger->entrance();
20036
20037 $this->_store_site( false, $blog_id );
20038 $this->_store_user( false );
20039 $this->_store_plans( false );
20040 $this->_store_licenses( false );
20041
20042 self::$_accounts->store( $blog_id );
20043 }
20044
20045 /**
20046 * Sync user's information.
20047 *
20048 * @author Vova Feldman (@svovaf)
20049 * @since 1.0.3
20050 * @uses FS_Api
20051 */
20052 private function _handle_account_user_sync() {
20053 $this->_logger->entrance();
20054
20055 $api = $this->get_api_user_scope();
20056
20057 // Get user's information.
20058 $user = $api->get( '/', true );
20059
20060 if ( isset( $user->id ) ) {
20061 $this->_user->first = $user->first;
20062 $this->_user->last = $user->last;
20063 $this->_user->email = $user->email;
20064
20065 $is_menu_item_account_visible = $this->is_submenu_item_visible( 'account' );
20066
20067 if ( $user->is_verified &&
20068 ( ! isset( $this->_user->is_verified ) || false === $this->_user->is_verified )
20069 ) {
20070 $this->_user->is_verified = true;
20071
20072 $this->do_action( 'account_email_verified', $user->email );
20073
20074 $this->_admin_notices->add(
20075 $this->get_text_inline( 'Your email has been successfully verified - you are AWESOME!', 'email-verified-message' ),
20076 $this->get_text_x_inline( 'Right on', 'a positive response', 'right-on' ) . '!',
20077 'success',
20078 // Make admin sticky if account menu item is invisible,
20079 // since the page will be auto redirected to the plugin's
20080 // main settings page, and the non-sticky message
20081 // will disappear.
20082 ! $is_menu_item_account_visible,
20083 'email_verified'
20084 );
20085 }
20086
20087 // Flush user details to DB.
20088 $this->_store_user();
20089
20090 $this->do_action( 'after_account_user_sync', $user );
20091
20092 /**
20093 * If account menu item is hidden, redirect to plugin's main settings page.
20094 *
20095 * @author Vova Feldman (@svovaf)
20096 * @since 1.1.6
20097 *
20098 * @link https://github.com/Freemius/wordpress-sdk/issues/6
20099 */
20100 if ( ! $is_menu_item_account_visible ) {
20101 fs_redirect( $this->_get_admin_page_url() );
20102 }
20103 }
20104 }
20105
20106 /**
20107 * @author Vova Feldman (@svovaf)
20108 * @since 1.0.9
20109 * @uses FS_Api
20110 *
20111 * @param number|bool $license_id
20112 *
20113 * @return FS_Subscription|object|bool
20114 */
20115 private function _fetch_site_license_subscription( $license_id = false ) {
20116 $this->_logger->entrance();
20117 $api = $this->get_api_site_scope();
20118
20119 if ( ! is_numeric( $license_id ) ) {
20120 $license_id = FS_Plugin_License::is_valid_id( $this->_license->parent_license_id ) ?
20121 $this->_license->parent_license_id :
20122 $this->_license->id;
20123 }
20124
20125 $result = $api->get( "/licenses/{$license_id}/subscriptions.json", true );
20126
20127 return ! isset( $result->error ) ?
20128 ( ( is_array( $result->subscriptions ) && 0 < count( $result->subscriptions ) ) ?
20129 new FS_Subscription( $result->subscriptions[0] ) :
20130 false
20131 ) :
20132 $result;
20133 }
20134
20135 /**
20136 * @author Vova Feldman (@svovaf)
20137 * @since 1.0.4
20138 * @uses FS_Api
20139 *
20140 * @param number|bool $plan_id
20141 *
20142 * @return FS_Plugin_Plan|object
20143 */
20144 private function _fetch_site_plan( $plan_id = false ) {
20145 $this->_logger->entrance();
20146 $api = $this->get_api_site_scope();
20147
20148 if ( ! is_numeric( $plan_id ) ) {
20149 $plan_id = $this->_site->plan_id;
20150 }
20151
20152 $plan = $api->get( "/plans/{$plan_id}.json", true );
20153
20154 return ! isset( $plan->error ) ? new FS_Plugin_Plan( $plan ) : $plan;
20155 }
20156
20157 /**
20158 * @author Vova Feldman (@svovaf)
20159 * @since 1.0.5
20160 * @uses FS_Api
20161 *
20162 * @return FS_Plugin_Plan[]|object
20163 */
20164 private function _fetch_plugin_plans() {
20165 $this->_logger->entrance();
20166 $api = $this->get_current_or_network_user_api_scope();
20167
20168 /**
20169 * @since 1.2.3 When running in DEV mode, retrieve pending plans as well.
20170 */
20171 $result = $api->get( $this->add_show_pending( "/plugins/{$this->_module_id}/plans.json" ), true );
20172
20173 if ( $this->is_api_result_object( $result, 'plans' ) && is_array( $result->plans ) ) {
20174 for ( $i = 0, $len = count( $result->plans ); $i < $len; $i ++ ) {
20175 $result->plans[ $i ] = new FS_Plugin_Plan( $result->plans[ $i ] );
20176 }
20177
20178 $result = $result->plans;
20179 }
20180
20181 return $result;
20182 }
20183
20184 /**
20185 * @author Vova Feldman (@svovaf)
20186 * @since 2.0.0
20187 *
20188 * @param number $plan_id
20189 *
20190 * @return \FS_Plugin_Plan|object
20191 */
20192 private function fetch_plan_by_id( $plan_id ) {
20193 $this->_logger->entrance();
20194 $api = $this->get_current_or_network_user_api_scope();
20195
20196 $result = $api->get( "/plugins/{$this->_module_id}/plans/{$plan_id}.json", true );
20197
20198 return $this->is_api_result_entity( $result ) ?
20199 new FS_Plugin_Plan( $result ) :
20200 $result;
20201 }
20202
20203 /**
20204 * @author Vova Feldman (@svovaf)
20205 * @since 1.0.5
20206 * @uses FS_Api
20207 *
20208 * @param number|bool $plugin_id
20209 * @param number|bool $site_license_id
20210 * @param array $foreign_licenses @since 2.0.0. This is used by network-activated plugins.
20211 * @param number|null $blog_id
20212 *
20213 * @return FS_Plugin_License[]|object
20214 */
20215 private function _fetch_licenses(
20216 $plugin_id = false,
20217 $site_license_id = false,
20218 $foreign_licenses = array(),
20219 $blog_id = null
20220 ) {
20221 $this->_logger->entrance();
20222
20223 $api = $this->get_api_user_scope();
20224
20225 if ( ! is_numeric( $plugin_id ) ) {
20226 $plugin_id = $this->_plugin->id;
20227 }
20228
20229 $user_licenses_endpoint = "/plugins/{$plugin_id}/licenses.json?is_enriched=true";
20230 if ( ! empty ( $foreign_licenses ) ) {
20231 $foreign_licenses = array(
20232 // Prefix with `+` to tell the server to include foreign licenses in the licenses collection.
20233 'ids' => ( urlencode( '+' ) . implode( ',', $foreign_licenses['ids'] ) ),
20234 'license_keys' => implode( ',', array_map( 'urlencode', $foreign_licenses['license_keys'] ) )
20235 );
20236
20237 $user_licenses_endpoint = add_query_arg( $foreign_licenses, $user_licenses_endpoint );
20238 }
20239
20240 $result = $api->get( $user_licenses_endpoint, true );
20241
20242 $is_site_license_synced = false;
20243
20244 $api_errors = array();
20245
20246 if ( $this->is_api_result_object( $result, 'licenses' ) &&
20247 is_array( $result->licenses )
20248 ) {
20249 for ( $i = 0, $len = count( $result->licenses ); $i < $len; $i ++ ) {
20250 $result->licenses[ $i ] = new FS_Plugin_License( $result->licenses[ $i ] );
20251
20252 if ( ( ! $is_site_license_synced ) && is_numeric( $site_license_id ) ) {
20253 $is_site_license_synced = ( $site_license_id == $result->licenses[ $i ]->id );
20254 }
20255 }
20256
20257 $result = $result->licenses;
20258 } else {
20259 $api_errors[] = $result;
20260 $result = array();
20261 }
20262
20263 if ( ! $is_site_license_synced ) {
20264 if ( ! is_null( $blog_id ) ) {
20265 /**
20266 * If blog ID is not null, the request is for syncing of the license of a single site via the
20267 * network-level "Account" page.
20268 *
20269 * @author Leo Fajardo (@leorw)
20270 */
20271 $this->switch_to_blog( $blog_id );
20272 }
20273
20274 $api = $this->get_api_site_scope();
20275
20276 if ( is_numeric( $site_license_id ) ) {
20277 // Try to retrieve a foreign license that is linked to the install.
20278 $api_result = $api->call( '/licenses.json?is_enriched=true' );
20279
20280 if ( $this->is_api_result_object( $api_result, 'licenses' ) &&
20281 is_array( $api_result->licenses )
20282 ) {
20283 $licenses = $api_result->licenses;
20284
20285 if ( ! empty( $licenses ) ) {
20286 $result[] = new FS_Plugin_License( $licenses[0] );
20287 }
20288 } else {
20289 $api_errors[] = $api_result;
20290 }
20291 } else if (
20292 is_object( $this->_license ) &&
20293 /**
20294 * Sync only if the license belongs to the context plugin. `$plugin_id` can be an add-on ID while
20295 * the FS instance that does the syncing is the parent FS instance.
20296 *
20297 * @author Leo Fajardo (@leorw)
20298 * @since 2.3.0
20299 */
20300 $this->_license->plugin_id == $plugin_id
20301 ) {
20302 $is_license_in_result = false;
20303 if ( ! empty( $result ) ) {
20304 foreach ( $result as $license ) {
20305 if ( $license->id == $this->_license->id ) {
20306 $is_license_in_result = true;
20307 break;
20308 }
20309 }
20310 }
20311
20312 if ( ! $is_license_in_result ) {
20313 // Fetch foreign license by ID and license key.
20314 $license = $api->get( "/licenses/{$this->_license->id}.json?license_key=" .
20315 urlencode( $this->_license->secret_key ) . '&is_enriched=true' );
20316
20317 if ( $this->is_api_result_entity( $license ) ) {
20318 $result[] = new FS_Plugin_License( $license );
20319 } else {
20320 $api_errors[] = $license;
20321 }
20322 }
20323 }
20324
20325 if ( ! is_null( $blog_id ) ) {
20326 $this->switch_to_blog( $this->_storage->network_install_blog_id );
20327 }
20328 }
20329
20330 if ( is_array( $result ) && 0 < count( $result ) ) {
20331 // If found at least one license, return license collection even if there are errors.
20332 return $result;
20333 }
20334
20335 if ( ! empty( $api_errors ) ) {
20336 // If found any errors and no licenses, return first error.
20337 return $api_errors[0];
20338 }
20339
20340 // Fallback to empty licenses list.
20341 return $result;
20342 }
20343
20344 /**
20345 * @author Vova Feldman (@svovaf)
20346 * @since 2.0.0
20347 *
20348 * @param number $license_id
20349 * @param string $license_key
20350 *
20351 * @return \FS_Plugin_License|object
20352 */
20353 private function fetch_license_by_key( $license_id, $license_key ) {
20354 $this->_logger->entrance();
20355
20356 $api = $this->get_current_or_network_user_api_scope();
20357
20358 $result = $api->get( "/licenses/{$license_id}.json?license_key=" . urlencode( $license_key ) );
20359
20360 return $this->is_api_result_entity( $result ) ?
20361 new FS_Plugin_License( $result ) :
20362 $result;
20363 }
20364
20365 /**
20366 * @author Vova Feldman (@svovaf)
20367 * @since 1.2.0
20368 * @uses FS_Api
20369 *
20370 * @param number|bool $plugin_id
20371 * @param bool $flush
20372 *
20373 * @return FS_Payment[]|object
20374 */
20375 function _fetch_payments( $plugin_id = false, $flush = false ) {
20376 $this->_logger->entrance();
20377
20378 $api = $this->get_api_user_scope();
20379
20380 if ( ! is_numeric( $plugin_id ) ) {
20381 $plugin_id = $this->_plugin->id;
20382 }
20383
20384 $include_bundles = (
20385 is_object( $this->_plugin ) &&
20386 FS_Plugin::is_valid_id( $this->_plugin->bundle_id )
20387 );
20388
20389 $result = $api->get(
20390 "/plugins/{$plugin_id}/payments.json?include_addons=true" . ($include_bundles ? '&include_bundles=true' : ''),
20391 $flush
20392 );
20393
20394 if ( ! isset( $result->error ) ) {
20395 for ( $i = 0, $len = count( $result->payments ); $i < $len; $i ++ ) {
20396 $result->payments[ $i ] = new FS_Payment( $result->payments[ $i ] );
20397 }
20398 $result = $result->payments;
20399 }
20400
20401 return $result;
20402 }
20403
20404 /**
20405 * @author Vova Feldman (@svovaf)
20406 * @since 1.2.1.5
20407 * @uses FS_Api
20408 *
20409 * @param bool $flush
20410 *
20411 * @return \FS_Billing|mixed
20412 */
20413 function _fetch_billing( $flush = false ) {
20414 require_once WP_FS__DIR_INCLUDES . '/entities/class-fs-billing.php';
20415
20416 $billing = $this->get_api_user_scope()->get( 'billing.json', $flush );
20417
20418 if ( $this->is_api_result_entity( $billing ) ) {
20419 $billing = new FS_Billing( $billing );
20420 }
20421
20422 return $billing;
20423 }
20424
20425 /**
20426 * @author Vova Feldman (@svovaf)
20427 * @since 1.0.5
20428 *
20429 * @param FS_Plugin_License[] $licenses
20430 * @param number $module_id
20431 */
20432 private function _update_licenses( $licenses, $module_id ) {
20433 $this->_logger->entrance();
20434
20435 if ( is_array( $licenses ) ) {
20436 for ( $i = 0, $len = count( $licenses ); $i < $len; $i ++ ) {
20437 $licenses[ $i ]->updated = time();
20438 }
20439 }
20440
20441 $this->_store_licenses( true, $module_id, $licenses );
20442 }
20443
20444 /**
20445 * @author Vova Feldman (@svovaf)
20446 * @since 1.0.4
20447 *
20448 * @param bool|number $plugin_id
20449 * @param bool $flush Since 1.1.7.3
20450 * @param int $expiration Since 1.2.2.7
20451 * @param bool|string $newer_than Since 2.2.1
20452 *
20453 * @return object|false New plugin tag info if exist.
20454 */
20455 private function _fetch_newer_version( $plugin_id = false, $flush = true, $expiration = WP_FS__TIME_24_HOURS_IN_SEC, $newer_than = false ) {
20456 $latest_tag = $this->_fetch_latest_version( $plugin_id, $flush, $expiration, $newer_than );
20457
20458 if ( ! is_object( $latest_tag ) ) {
20459 return false;
20460 }
20461
20462 $plugin_version = $this->get_plugin_version();
20463
20464 // Check if version is actually newer.
20465 $has_new_version =
20466 // If it's an non-installed add-on then always return latest.
20467 ( $this->_is_addon_id( $plugin_id ) && ! $this->is_addon_activated( $plugin_id ) ) ||
20468 // Compare versions.
20469 version_compare( $plugin_version, $latest_tag->version, '<' );
20470
20471 $this->_logger->departure( $has_new_version ? 'Found newer plugin version ' . $latest_tag->version : 'No new version' );
20472
20473 $is_latest_version_beta = ( 'beta' === $latest_tag->release_mode );
20474
20475 $this->_storage->beta_data = array(
20476 'is_beta' => $is_latest_version_beta,
20477 'version' => $latest_tag->version
20478 );
20479
20480 return $has_new_version ? $latest_tag : false;
20481 }
20482
20483 /**
20484 * @author Vova Feldman (@svovaf)
20485 * @since 1.0.5
20486 *
20487 * @param bool|number $plugin_id
20488 * @param bool $flush Since 1.1.7.3
20489 * @param int $expiration Since 1.2.2.7
20490 * @param bool|string $newer_than Since 2.2.1
20491 *
20492 * @return bool|FS_Plugin_Tag
20493 */
20494 function get_update( $plugin_id = false, $flush = true, $expiration = FS_Plugin_Updater::UPDATES_CHECK_CACHE_EXPIRATION, $newer_than = false ) {
20495 $this->_logger->entrance();
20496
20497 if ( ! is_numeric( $plugin_id ) ) {
20498 $plugin_id = $this->_plugin->id;
20499 }
20500
20501 $this->check_updates( true, $plugin_id, $flush, $expiration, $newer_than );
20502 $updates = $this->get_all_updates();
20503
20504 return isset( $updates[ $plugin_id ] ) && is_object( $updates[ $plugin_id ] ) ? $updates[ $plugin_id ] : false;
20505 }
20506
20507 /**
20508 * Check if site assigned with active license.
20509 *
20510 * @author Vova Feldman (@svovaf)
20511 * @since 1.0.6
20512 *
20513 * @deprecated Please use has_active_valid_license() instead because license can be cancelled.
20514 */
20515 function has_active_license() {
20516 return (
20517 is_object( $this->_license ) &&
20518 is_numeric( $this->_license->id ) &&
20519 ! $this->_license->is_expired()
20520 );
20521 }
20522
20523 /**
20524 * Check if site assigned with active & valid (not expired) license.
20525 *
20526 * @author Vova Feldman (@svovaf)
20527 * @since 1.2.1
20528 *
20529 * @param bool $check_expiration
20530 */
20531 function has_active_valid_license( $check_expiration = true ) {
20532 return self::is_active_valid_license( $this->_license, $check_expiration );
20533 }
20534
20535 /**
20536 * @author Leo Fajardo (@leorw)
20537 * @since 2.3.1
20538 */
20539 function is_data_debug_mode() {
20540 if ( is_null( $this->is_whitelabeled ) || ! $this->is_whitelabeled ) {
20541 return false;
20542 }
20543
20544 $fs = $this->is_addon() ?
20545 $this->get_parent_instance() :
20546 $this;
20547
20548 if ( $fs->is_network_active() && fs_is_network_admin() ) {
20549 $is_developer_license_debug_mode = get_site_transient( "fs_{$this->get_id()}_data_debug_mode" );
20550 } else {
20551 $is_developer_license_debug_mode = get_transient( "fs_{$this->get_id()}_data_debug_mode" );
20552 }
20553
20554 return ( 'true' === $is_developer_license_debug_mode );
20555 }
20556
20557 /**
20558 * @author Leo Fajardo (@leorw)
20559 * @since 2.3.1
20560 */
20561 function _set_data_debug_mode() {
20562 if ( ! $this->is_whitelabeled( true ) ) {
20563 return;
20564 }
20565
20566 $license_or_user_key = fs_request_get_raw( 'license_or_user_key' );
20567
20568 $transient_value = ( ! empty( $license_or_user_key ) ) ?
20569 'true' :
20570 'false';
20571
20572 if ( 'true' === $transient_value ) {
20573 $stored_key = $this->_storage->get( ! FS_User::is_valid_id( $this->_storage->last_license_user_id ) ?
20574 'last_license_key' :
20575 'last_license_user_key'
20576 );
20577
20578 if ( md5( $license_or_user_key ) !== $stored_key ) {
20579 $this->shoot_ajax_failure( sprintf(
20580 '%s... %s',
20581 $this->get_text_x_inline( 'Oops', 'exclamation', 'oops' ),
20582 $this->get_text_inline(
20583 'seems like the key you entered doesn\'t match our records.',
20584 'developer-or-license-not-found'
20585 )
20586 ) );
20587 }
20588 }
20589
20590 if ( $this->is_network_active() && fs_is_network_admin() ) {
20591 set_site_transient(
20592 "fs_{$this->get_id()}_data_debug_mode",
20593 $transient_value,
20594 WP_FS__TIME_24_HOURS_IN_SEC / 24
20595 );
20596 } else {
20597 set_transient(
20598 "fs_{$this->get_id()}_data_debug_mode",
20599 $transient_value,
20600 WP_FS__TIME_24_HOURS_IN_SEC / 24
20601 );
20602 }
20603
20604 if ( 'true' === $transient_value ) {
20605 $this->_admin_notices->add_sticky(
20606 $this->get_text_inline(
20607 '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.',
20608 'data_debug_mode_enabled'
20609 ),
20610 'data_debug_mode_enabled'
20611 );
20612 }
20613
20614 $this->shoot_ajax_success();
20615 }
20616
20617 /**
20618 * Check if a given license is active & valid (not expired).
20619 *
20620 * @author Vova Feldman (@svovaf)
20621 * @since 2.1.3
20622 *
20623 * @param FS_Plugin_License $license
20624 * @param bool $check_expiration
20625 *
20626 * @return bool
20627 */
20628 private static function is_active_valid_license( $license, $check_expiration = true ) {
20629 return (
20630 is_object( $license ) &&
20631 FS_Plugin_License::is_valid_id( $license->id ) &&
20632 $license->is_active() &&
20633 ( ! $check_expiration || $license->is_valid() )
20634 );
20635 }
20636
20637 /**
20638 * Checks if there's any site that is associated with an active & valid license.
20639 * This logic is used to determine if the admin can download the premium code base from a network level admin.
20640 *
20641 * @author Vova Feldman (@svovaf)
20642 * @since 2.1.3
20643 *
20644 * @return bool
20645 */
20646 function has_any_active_valid_license() {
20647 if ( ! fs_is_network_admin() ) {
20648 return $this->has_active_valid_license();
20649 }
20650
20651 $installs = $this->get_blog_install_map();
20652 $all_plugin_licenses = self::get_all_licenses( $this->_module_id );
20653
20654 foreach ( $installs as $blog_id => $install ) {
20655 if ( ! FS_Plugin_License::is_valid_id( $install->license_id ) ) {
20656 continue;
20657 }
20658
20659 foreach ( $all_plugin_licenses as $license ) {
20660 if ( $license->id == $install->license_id ) {
20661 if ( self::is_active_valid_license( $license ) ) {
20662 return true;
20663 }
20664 }
20665 }
20666 }
20667
20668 return false;
20669 }
20670
20671 /**
20672 * Check if site assigned with license with enabled features.
20673 *
20674 * @author Vova Feldman (@svovaf)
20675 * @since 1.0.6
20676 *
20677 * @return bool
20678 */
20679 function has_features_enabled_license() {
20680 return (
20681 is_object( $this->_license ) &&
20682 is_numeric( $this->_license->id ) &&
20683 $this->_license->is_features_enabled()
20684 );
20685 }
20686
20687 /**
20688 * Checks if the product is activated with a bundle license.
20689 *
20690 * @author Leo Fajardo (@leorw)
20691 * @since 2.4.0
20692 *
20693 * @return bool
20694 */
20695 function is_activated_with_bundle_license() {
20696 if ( ! $this->has_features_enabled_license() ) {
20697 return false;
20698 }
20699
20700 return FS_Plugin_License::is_valid_id( $this->_license->parent_license_id );
20701 }
20702
20703 /**
20704 * Check if user is a trial or have feature enabled license.
20705 *
20706 * @author Vova Feldman (@svovaf)
20707 * @since 1.1.7
20708 *
20709 * @return bool
20710 */
20711 function can_use_premium_code() {
20712 return $this->is_trial() || $this->has_features_enabled_license();
20713 }
20714
20715 /**
20716 * Checks if the current user can activate plugins or switch themes. Note that this method should only be used
20717 * after the `init` action is triggered because it is using `current_user_can()` which is only functional after
20718 * the context user is authenticated.
20719 *
20720 * @author Leo Fajardo (@leorw)
20721 * @since 1.2.2
20722 *
20723 * @return bool
20724 */
20725 function is_user_admin() {
20726 /**
20727 * Require a super-admin when network activated, running from the network level OR if
20728 * running from the site level but not delegated the opt-in.
20729 *
20730 * @author Vova Feldman (@svovaf)
20731 * @since 2.0.0
20732 */
20733 if ( $this->_is_network_active &&
20734 ( fs_is_network_admin() || ! $this->is_delegated_connection() )
20735 ) {
20736 return is_super_admin();
20737 }
20738
20739 return ( $this->is_plugin() && current_user_can( is_multisite() ? 'manage_options' : 'activate_plugins' ) )
20740 || ( $this->is_theme() && current_user_can( 'switch_themes' ) );
20741 }
20742
20743 /**
20744 * Sync site's plan.
20745 *
20746 * @author Vova Feldman (@svovaf)
20747 * @since 1.0.3
20748 *
20749 * @uses FS_Api
20750 *
20751 * @param bool $background Hints the method if it's a background sync. If false, it means that was initiated by
20752 * the admin.
20753 * @param bool $is_context_single_site @since 2.0.0. This is used when syncing a license for a single install from the
20754 * network-level "Account" page.
20755 * @param int|null $current_blog_id @since 2.2.3. This is passed from the `execute_cron` method and used by the
20756 * `_sync_plugin_license` method in order to switch to the previous blog when sending
20757 * updates for a single site in case `execute_cron` has switched to a different blog.
20758 */
20759 private function _sync_license( $background = false, $is_context_single_site = false, $current_blog_id = null ) {
20760 $this->_logger->entrance();
20761
20762 $plugin_id = fs_request_get( 'plugin_id', $this->get_id() );
20763
20764 $is_addon_sync = ( ! $this->_plugin->is_addon() && $plugin_id != $this->get_id() );
20765
20766 if ( $is_addon_sync ) {
20767 $this->_sync_addon_license( $plugin_id, $background );
20768 } else {
20769 $this->_sync_plugin_license( $background, true, $is_context_single_site, $current_blog_id );
20770 }
20771
20772 $this->do_action( 'after_account_plan_sync', $this->get_plan_name() );
20773 }
20774
20775 /**
20776 * Sync plugin's add-on license.
20777 *
20778 * @author Vova Feldman (@svovaf)
20779 * @since 1.0.6
20780 * @uses FS_Api
20781 *
20782 * @param number $addon_id
20783 * @param bool $background
20784 */
20785 private function _sync_addon_license( $addon_id, $background ) {
20786 $this->_logger->entrance();
20787
20788 if ( $this->is_addon_activated( $addon_id ) ) {
20789 // If already installed, use add-on sync.
20790 $fs_addon = self::get_instance_by_id( $addon_id );
20791
20792 if (
20793 // Add-on is network activated and network integrated.
20794 $fs_addon->is_network_active() ||
20795 // Background sync cron.
20796 self::is_cron() ||
20797 // Add-on is not network activated or not network integrated.
20798 ! fs_is_network_admin()
20799 ) {
20800 $fs_addon->_sync_license( $background );
20801
20802 return;
20803 }
20804 }
20805
20806 // Validate add-on exists.
20807 $addon = $this->get_addon( $addon_id );
20808
20809 if ( ! is_object( $addon ) ) {
20810 return;
20811 }
20812
20813 // Add add-on into account add-ons.
20814 $account_addons = $this->get_account_addons();
20815 if ( ! is_array( $account_addons ) ) {
20816 $account_addons = array();
20817 }
20818 $account_addons[] = $addon->id;
20819 $account_addons = array_unique( $account_addons );
20820 $this->_store_account_addons( $account_addons );
20821
20822 // Load add-on licenses.
20823 $licenses = $this->_fetch_licenses( $addon->id );
20824
20825 // Sync add-on licenses.
20826 if ( $this->is_array_instanceof( $licenses, 'FS_Plugin_License' ) ) {
20827 $this->_update_licenses( $licenses, $addon->id );
20828
20829 if ( ! $this->is_addon_installed( $addon->id ) && FS_License_Manager::has_premium_license( $licenses ) ) {
20830 $plans_result = $this->get_api_site_or_plugin_scope()->get( $this->add_show_pending( "/addons/{$addon_id}/plans.json" ) );
20831
20832 if ( ! isset( $plans_result->error ) ) {
20833 $plans = array();
20834 foreach ( $plans_result->plans as $plan ) {
20835 $plans[] = new FS_Plugin_Plan( $plan );
20836 }
20837
20838 $this->_admin_notices->add_sticky(
20839 sprintf(
20840 ( FS_Plan_Manager::instance()->has_free_plan( $plans ) ?
20841 $this->get_text_inline( 'Your %s Add-on plan was successfully upgraded.', 'addon-successfully-upgraded-message' ) :
20842 /* translators: %s:product name, e.g. Facebook add-on was successfully... */
20843 $this->get_text_inline( '%s Add-on was successfully purchased.', 'addon-successfully-purchased-message' ) ),
20844 $addon->title
20845 ) . ' ' . $this->get_latest_download_link(
20846 $this->get_text_inline( 'Download the latest version', 'download-latest-version' ),
20847 $addon_id
20848 ),
20849 'addon_plan_upgraded_' . $addon->slug,
20850 $this->get_text_x_inline( 'Yee-haw', 'interjection expressing joy or exuberance', 'yee-haw' ) . '!'
20851 );
20852 }
20853 }
20854 }
20855 }
20856
20857 /**
20858 * Sync site's plugin plan.
20859 *
20860 * @author Vova Feldman (@svovaf)
20861 * @since 1.0.6
20862 * @uses FS_Api
20863 *
20864 * @param bool $background Hints the method if it's a background sync. If false, it means that was initiated by the admin.
20865 * @param bool $send_installs_update Since 2.0.0
20866 * @param bool $is_context_single_site Since 2.0.0. This is used when sending an update for a single install and
20867 * syncing its license from the network-level "Account" page (e.g.: after
20868 * activating a license only for the single install).
20869 * @param int|null $current_blog_id Since 2.2.3. This is passed from the `execute_cron` method so that it
20870 * can be used here to switch to the previous blog in case `execute_cron`
20871 * has switched to a different blog.
20872 */
20873 private function _sync_plugin_license(
20874 $background = false,
20875 $send_installs_update = true,
20876 $is_context_single_site = false,
20877 $current_blog_id = null
20878 ) {
20879 $this->_logger->entrance();
20880
20881 $plan_change = 'none';
20882
20883 $is_site_level_sync = ( $is_context_single_site || fs_is_blog_admin() || ! $this->_is_network_active );
20884
20885 if ( ! $send_installs_update ) {
20886 $site = $this->_site;
20887 } else {
20888 /**
20889 * Sync site info.
20890 *
20891 * @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.
20892 */
20893 if ( $is_site_level_sync ) {
20894 /**
20895 * Switch to the previous blog since `execute_cron` may have switched to a different blog.
20896 *
20897 * @author Leo Fajardo (@leorw)
20898 * @since 2.2.3
20899 */
20900 if ( is_numeric( $current_blog_id ) ) {
20901 $this->switch_to_blog( $current_blog_id );
20902 }
20903
20904 $result = $this->send_install_update( array(), true, true );
20905 $is_valid = $this->is_api_result_entity( $result );
20906 } else {
20907 $result = $this->send_installs_update( array(), true, true );
20908 $is_valid = $this->is_api_result_object( $result, 'installs' );
20909 }
20910
20911 if ( ! $is_valid ) {
20912 if ( $is_context_single_site ) {
20913 // Switch back to the main blog so that the following logic will have the right entities.
20914 $this->switch_to_blog( $this->_storage->network_install_blog_id );
20915 }
20916
20917 // Show API message only if not background sync or if paying customer.
20918 if ( ! $background || $this->is_paying() ) {
20919 // Try to ping API to see if not blocked.
20920 if ( FS_Api::is_blocked( $result ) ) {
20921 /**
20922 * @author Vova Feldman (@svovaf)
20923 * @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.
20924 */
20925 if ( ! self::$_global_admin_notices->has_sticky( 'api_blocked' ) ) {
20926 // Add notice immediately if not a background sync.
20927 $add_notice = ( ! $background );
20928
20929 if ( ! $add_notice ) {
20930 $counter = (int) get_transient( '_fs_api_connection_retry_counter' );
20931
20932 // We only want to add the notice after 3 consecutive failures.
20933 $add_notice = ( 3 <= $counter );
20934
20935 if ( ! $add_notice ) {
20936 /**
20937 * 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.
20938 *
20939 * 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.
20940 */
20941 set_transient( '_fs_api_connection_retry_counter', $counter + 1, WP_FS__TIME_WEEK_IN_SEC );
20942 }
20943 }
20944
20945 // Add notice instantly for not-background sync and only after 3 failed attempts for background sync.
20946 if ( $add_notice ) {
20947 self::$_global_admin_notices->add(
20948 $this->generate_api_blocked_notice_message_from_result( $result ),
20949 '',
20950 'error',
20951 $background,
20952 'api_blocked'
20953 );
20954
20955 add_action( 'admin_footer', array( 'Freemius', '_add_api_connectivity_notice_handler_js' ) );
20956
20957 // Notice was just shown, reset connectivity counter.
20958 delete_transient( '_fs_api_connection_retry_counter' );
20959 }
20960 }
20961 } else if ( is_object( $result ) ) {
20962 // Authentication params are broken.
20963 $this->_admin_notices->add(
20964 $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 ),
20965 '',
20966 'error'
20967 );
20968 }
20969 }
20970
20971 // No reason to continue with license sync while there are API issues.
20972 return;
20973 }
20974
20975 // API is working now. Delete the transient and start afresh.
20976 delete_transient('_fs_api_connection_retry_counter');
20977
20978 if ( $is_site_level_sync ) {
20979 $site = new FS_Site( $result );
20980 } else {
20981 // Map site addresses to their blog IDs.
20982 $address_to_blog_map = $this->get_address_to_blog_map();
20983
20984 // Find the current context install.
20985 $site = null;
20986 foreach ( $result->installs as $install ) {
20987 if ( $install->id == $this->_site->id ) {
20988 $site = new FS_Site( $install );
20989 } else {
20990 $address = trailingslashit( fs_strip_url_protocol( $install->url ) );
20991 $blog_id = $address_to_blog_map[ $address ];
20992
20993 $this->_store_site( true, $blog_id, new FS_Site( $install ) );
20994 }
20995 }
20996 }
20997
20998 // Sync plans.
20999 $this->_sync_plans();
21000 }
21001
21002 // Remove sticky API connectivity message.
21003 self::$_global_admin_notices->remove_sticky( 'api_blocked' );
21004
21005 if ( ! $this->has_paid_plan() ) {
21006 $this->_site = $site;
21007 $this->_store_site(
21008 true,
21009 $is_site_level_sync ?
21010 null :
21011 $this->get_network_install_blog_id()
21012 );
21013 } else {
21014 $context_blog_id = 0;
21015
21016 if ( $is_context_single_site ) {
21017 $context_blog_id = get_current_blog_id();
21018
21019 // Switch back to the main blog in order to properly sync the license.
21020 $this->switch_to_blog( $this->_storage->network_install_blog_id );
21021 }
21022
21023 /**
21024 * Sync licenses. Pass the site's license ID so that the foreign licenses will be fetched if the license
21025 * associated with that ID is not included in the user's licenses collection.
21026 * Save previous value to manage remote license renewals.
21027 */
21028 $was_license_expired_before_sync = is_object( $this->_license ) && $this->_license->is_expired();
21029 $this->_sync_licenses(
21030 $site->license_id,
21031 ( $is_context_single_site ?
21032 $context_blog_id :
21033 null
21034 )
21035 );
21036
21037 if ( $is_context_single_site ) {
21038 $this->switch_to_blog( $context_blog_id );
21039 }
21040
21041 // Check if plan / license changed.
21042 if ( $site->plan_id != $this->_site->plan_id ||
21043 // Check if trial started.
21044 $site->trial_plan_id != $this->_site->trial_plan_id ||
21045 $site->trial_ends != $this->_site->trial_ends ||
21046 // Check if license changed.
21047 $site->license_id != $this->_site->license_id
21048 ) {
21049 if ( $site->is_trial() && ( ! $this->_site->is_trial() || $site->trial_ends != $this->_site->trial_ends ) ) {
21050 // New trial started.
21051 $this->_site = $site;
21052 $plan_change = 'trial_started';
21053
21054 // For trial with subscription use-case.
21055 $new_license = is_null( $site->license_id ) ? null : $this->_get_license_by_id( $site->license_id );
21056
21057 if ( is_object( $new_license ) && $new_license->is_valid() ) {
21058 $this->_site = $site;
21059 $this->_update_site_license( $new_license );
21060 $this->_store_licenses();
21061
21062 $this->_sync_site_subscription( $this->_license );
21063 }
21064 } else if ( $this->_site->is_trial() && ! $site->is_trial() && ! is_numeric( $site->license_id ) ) {
21065 // Was in trial, but now trial expired and no license ID.
21066 // New trial started.
21067 $this->_site = $site;
21068 $plan_change = 'trial_expired';
21069 } else {
21070 $is_free = $this->is_free_plan();
21071
21072 // Make sure license exist and not expired.
21073 $new_license = is_null( $site->license_id ) ?
21074 null :
21075 $this->_get_license_by_id( $site->license_id );
21076
21077 if ( $is_free && is_null( $new_license ) && $this->has_any_license() && $this->_license->is_cancelled ) {
21078 // License cancelled.
21079 $this->_site = $site;
21080 $this->_update_site_license( $new_license );
21081 $this->_store_licenses();
21082
21083 $plan_change = 'cancelled';
21084 } else if ( $is_free && ( ( ! is_object( $new_license ) || $new_license->is_expired() ) ) ) {
21085 // The license is expired, so ignore upgrade method.
21086 $this->_site = $site;
21087 } else {
21088 // License changed.
21089 $this->_site = $site;
21090
21091 /**
21092 * IMPORTANT:
21093 * 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.
21094 *
21095 * @author Vova Feldman (@svovaf)
21096 * @since 2.0.0
21097 */
21098 $this->_update_site_license( $new_license );
21099
21100 if ( ! $is_context_single_site &&
21101 fs_is_network_admin() &&
21102 $this->_is_network_active &&
21103 $new_license->quota > 1 &&
21104 get_blog_count() > 1
21105 ) {
21106 // See if license can activated on all sites.
21107 if ( ! $this->try_activate_license_on_network( $this->_user, $new_license ) ) {
21108 if ( ! fs_request_get_bool( 'auto_install' ) ) {
21109 // Open the license activation dialog box on the account page.
21110 add_action( 'admin_footer', array(
21111 &$this,
21112 '_open_license_activation_dialog_box'
21113 ) );
21114 }
21115 }
21116 }
21117
21118 $this->_store_licenses();
21119
21120 $plan_change = $is_free ?
21121 ( $this->is_only_premium() ? 'activated' : 'upgraded' ) :
21122 ( is_object( $new_license ) ?
21123 'changed' :
21124 'downgraded' );
21125 }
21126 }
21127
21128 // Store updated site info.
21129 $this->_store_site(
21130 true,
21131 $is_site_level_sync ?
21132 null :
21133 $this->get_network_install_blog_id()
21134 );
21135 } else {
21136 if ( ! is_object( $this->_license ) ) {
21137 $this->maybe_update_whitelabel_flag(
21138 FS_Plugin_License::is_valid_id( $site->license_id ) ?
21139 $this->get_license_by_id( $site->license_id ) :
21140 null
21141 );
21142 } else {
21143 $this->maybe_update_whitelabel_flag( $this->_license );
21144
21145 if ( $this->_license->is_expired() ) {
21146 if ( ! $this->has_features_enabled_license() ) {
21147 $this->_deactivate_license();
21148 $plan_change = 'downgraded';
21149 } else {
21150 $last_time_expired_license_notice_was_shown = $this->_storage->get( 'expired_license_notice_shown', 0 );
21151
21152 if ( time() - ( 14 * WP_FS__TIME_24_HOURS_IN_SEC ) >= $last_time_expired_license_notice_was_shown ) {
21153 /**
21154 * Show the expired license notice every 14 days.
21155 *
21156 * @author Leo Fajardo (@leorw)
21157 * @since 2.3.1
21158 */
21159 $plan_change = 'expired';
21160 }
21161 }
21162 } else if ( $was_license_expired_before_sync ) {
21163 /**
21164 * If license was expired but it is not anymore.
21165 *
21166 *
21167 * @author Daniele Alessandra (@danielealessandra)
21168 */
21169 $plan_change = 'extended';
21170 }
21171 }
21172
21173 if ( is_numeric( $site->license_id ) && is_object( $this->_license ) ) {
21174 $this->_sync_site_subscription( $this->_license );
21175 }
21176 }
21177
21178 if ( ! $this->is_addon() &&
21179 $this->_site->is_beta() !== $site->is_beta()
21180 ) {
21181 // Beta flag updated.
21182 $this->_site = $site;
21183
21184 $this->_store_site(
21185 true,
21186 $is_site_level_sync ?
21187 null :
21188 $this->get_network_install_blog_id()
21189 );
21190 }
21191
21192 if ( $this->is_addon() || $this->has_addons() ) {
21193 /**
21194 * Purge the valid user licenses cache so that when the "Account" or the "Add-Ons" page is loaded,
21195 * an updated valid user licenses collection will be fetched from the server which is used to also
21196 * update the account add-ons (add-ons the user has licenses for).
21197 *
21198 * @author Leo Fajardo (@leorw)
21199 * @since 2.2.4
21200 */
21201 $this->purge_valid_user_licenses_cache();
21202 }
21203 }
21204
21205 $hmm_text = $this->get_text_x_inline( 'Hmm', 'something somebody says when they are thinking about what you have just said.', 'hmm' ) . '...';
21206
21207 if ( $this->apply_filters( 'has_paid_plan_account', $this->has_paid_plan() ) ) {
21208 switch ( $plan_change ) {
21209 case 'none':
21210 if ( ! $background && is_admin() ) {
21211 $plan = $this->is_trial() ?
21212 $this->get_trial_plan() :
21213 $this->get_plan();
21214
21215 if ( $plan->is_free() ) {
21216 $this->_admin_notices->add(
21217 sprintf(
21218 $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' ),
21219 '<i><b>' . $plan->title . ( $this->is_trial() ? ' ' . $this->get_text_x_inline( 'Trial', 'trial period', 'trial' ) : '' ) . '</b></i>'
21220 ) . ' ' . sprintf(
21221 '<a href="%s">%s</a>',
21222 $this->contact_url(
21223 'bug',
21224 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' ),
21225 strtoupper( $plan->name )
21226 )
21227 ),
21228 $this->get_text_inline( 'Please contact us here', 'contact-us-here' )
21229 ),
21230 $hmm_text
21231 );
21232 }
21233 }
21234 break;
21235 case 'upgraded':
21236 case 'activated':
21237 $this->add_after_plan_activation_or_upgrade_instructions_notice( 'upgraded' === $plan_change );
21238
21239 $this->_admin_notices->remove_sticky( array(
21240 'trial_started',
21241 'trial_promotion',
21242 'trial_expired',
21243 'activation_complete',
21244 'license_expired',
21245 ) );
21246 break;
21247 case 'extended':
21248 $this->_admin_notices->remove_sticky( array(
21249 'trial_expired',
21250 'license_expired',
21251 ) );
21252 break;
21253 case 'changed':
21254 $this->_admin_notices->add_sticky(
21255 sprintf(
21256 $this->get_text_inline( 'Your plan was successfully changed to %s.', 'plan-changed-to-x-message' ),
21257 $this->get_plan_title()
21258 ),
21259 'plan_changed'
21260 );
21261
21262 $this->_admin_notices->remove_sticky( array(
21263 'trial_started',
21264 'trial_promotion',
21265 'trial_expired',
21266 'activation_complete',
21267 ) );
21268 break;
21269 case 'downgraded':
21270 $this->_admin_notices->add_sticky(
21271 ($this->has_free_plan() ?
21272 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 ) :
21273 /* translators: %1$s: product title; %2$s, %3$s: wrapping HTML anchor element; %4$s: 'plugin', 'theme', or 'add-on'. */
21274 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) ) ),
21275 'license_expired',
21276 $hmm_text
21277 );
21278 $this->_admin_notices->remove_sticky( 'plan_upgraded' );
21279 break;
21280 case 'cancelled':
21281 $this->_admin_notices->add(
21282 $this->get_text_inline( 'Your license has been cancelled. If you think it\'s a mistake, please contact support.', 'license-cancelled' ) . ' ' .
21283 sprintf(
21284 '<a href="%s">%s</a>',
21285 $this->contact_url( 'bug' ),
21286 $this->get_text_inline( 'Please contact us here', 'contact-us-here' )
21287 ),
21288 $hmm_text,
21289 'error'
21290 );
21291 $this->_admin_notices->remove_sticky( 'plan_upgraded' );
21292 break;
21293 case 'expired':
21294 $this->_admin_notices->add_sticky(
21295 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 ),
21296 'license_expired',
21297 $hmm_text
21298 );
21299
21300 $this->_storage->expired_license_notice_shown = WP_FS__SCRIPT_START_TIME;
21301
21302 $this->_admin_notices->remove_sticky( 'plan_upgraded' );
21303 break;
21304 case 'trial_started':
21305 $this->add_complete_upgrade_instructions_notice(
21306 sprintf(
21307 $this->get_text_inline( 'Your trial has been successfully started.', 'trial-started-message' ),
21308 '<i>' . $this->get_plugin_name() . '</i>'
21309 ),
21310 'trial_started',
21311 $this->get_trial_plan()->title
21312 );
21313
21314 $this->_admin_notices->remove_sticky( array(
21315 'trial_promotion',
21316 ) );
21317 break;
21318 case 'trial_expired':
21319 $this->_admin_notices->add_sticky(
21320 ($this->has_free_plan() ?
21321 $this->get_text_inline( 'Your free trial has expired. You can still continue using all our free features.', 'trial-expired-message' ) :
21322 /* translators: %1$s: product title; %2$s, %3$s: wrapping HTML anchor element; %4$s: 'plugin', 'theme', or 'add-on'. */
21323 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))),
21324 'trial_expired',
21325 $hmm_text
21326 );
21327 $this->_admin_notices->remove_sticky( array(
21328 'trial_started',
21329 'trial_promotion',
21330 'plan_upgraded',
21331 ) );
21332 break;
21333 }
21334 }
21335
21336 if ( 'none' !== $plan_change ) {
21337 if (
21338 ! is_object( $this->_license ) ||
21339 ! $this->_license->is_whitelabeled
21340 ) {
21341 $this->_admin_notices->remove_sticky( 'license_whitelabeled' );
21342 }
21343
21344 $this->do_action( 'after_license_change', $plan_change, $this->get_plan() );
21345 }
21346 }
21347
21348 /**
21349 * @author Leo Fajardo (@leorw)
21350 * @since 2.5.4
21351 *
21352 * @param mixed $result
21353 *
21354 * @return string
21355 */
21356 private function generate_api_blocked_notice_message_from_result( $result ) {
21357 $api_domains = $this->apply_filters( 'api_domains', array(
21358 'api.freemius.com',
21359 'wp.freemius.com',
21360 ) );
21361
21362 $api_domains_list_items = '';
21363
21364 foreach( $api_domains as $api_domain ) {
21365 $api_domains_list_items .= "<li>{$api_domain}</li>";
21366 }
21367
21368 $error_message = sprintf(
21369 $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' ),
21370 $this->get_plugin_name(),
21371 "<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>"
21372 );
21373
21374 $error_message =
21375 "<div>{$error_message}</div>" .
21376 '<div class="fs-api-request-error-details" style="display: none">' .
21377 '<strong>' . $this->get_text_inline( 'Error received from the server:', 'server-error-message' ) . '</strong><br>' .
21378 $result->error->message .
21379 '</div>';
21380
21381 return $error_message;
21382 }
21383
21384 /**
21385 * Include the required JS at the footer of the admin to trigger the license activation dialog box.
21386 *
21387 * @author Vova Feldman (@svovaf)
21388 * @since 2.0.0
21389 */
21390 public function _open_license_activation_dialog_box() {
21391 $vars = array( 'license_id' => $this->_site->license_id );
21392 fs_require_once_template( 'js/open-license-activation.php', $vars );
21393 }
21394
21395 /**
21396 * @author Vova Feldman (@svovaf)
21397 * @since 1.0.5
21398 *
21399 * @param bool $background
21400 * @param FS_Plugin_License|null $premium_license
21401 */
21402 protected function _activate_license( $background = false, $premium_license = null ) {
21403 $this->_logger->entrance();
21404
21405 if ( is_null( $premium_license ) ) {
21406 $license_id = fs_request_get( 'license_id' );
21407
21408 if ( is_object( $this->_site ) &&
21409 FS_Plugin_License::is_valid_id( $license_id ) &&
21410 $license_id == $this->_site->license_id
21411 ) {
21412 // License is already activated.
21413 return;
21414 }
21415
21416 $premium_license = FS_Plugin_License::is_valid_id( $license_id ) ?
21417 $this->_get_license_by_id( $license_id ) :
21418 $this->_get_available_premium_license();
21419 }
21420
21421 if ( ! is_object( $premium_license ) ) {
21422 return;
21423 }
21424
21425 if ( ! is_object( $this->_site ) ) {
21426 // Not yet opted-in.
21427 $user = $this->get_current_or_network_user();
21428 if ( ! is_object( $user ) ) {
21429 $user = self::_get_user_by_id( $premium_license->user_id );
21430 }
21431
21432 if ( is_object( $user ) ) {
21433 $this->install_with_user( $user, $premium_license->secret_key, false, false, false );
21434 } else {
21435 $this->opt_in(
21436 false,
21437 false,
21438 false,
21439 $premium_license->secret_key
21440 );
21441
21442 return;
21443 }
21444 }
21445
21446
21447 /**
21448 * If the premium license is already associated with the install, just
21449 * update the license reference (activation is not required).
21450 *
21451 * @since 1.1.9
21452 */
21453 if ( $premium_license->id == $this->_site->license_id ) {
21454 // License is already activated.
21455 $this->_update_site_license( $premium_license );
21456 $this->_store_account();
21457
21458 return;
21459 }
21460
21461 if ( $this->_site->user_id != $premium_license->user_id ) {
21462 $api_request_params = array( 'license_key' => $premium_license->secret_key );
21463 } else {
21464 $api_request_params = array();
21465 }
21466
21467 $api = $this->get_api_site_scope();
21468 $license = $api->call( "/licenses/{$premium_license->id}.json?is_enriched=true", 'put', $api_request_params );
21469
21470 if ( ! $this->is_api_result_entity( $license ) ) {
21471 if ( ! $background ) {
21472 $this->_admin_notices->add( sprintf(
21473 '%s %s',
21474 $this->get_text_inline( 'It looks like the license could not be activated.', 'license-activation-failed-message' ),
21475 ( is_object( $license ) && isset( $license->error ) ?
21476 $license->error->message :
21477 sprintf( '%s<br><code>%s</code>',
21478 $this->get_text_inline( 'Error received from the server:', 'server-error-message' ),
21479 var_export( $license, true )
21480 )
21481 )
21482 ),
21483 $this->get_text_x_inline( 'Hmm', 'something somebody says when they are thinking about what you have just said.', 'hmm' ) . '...',
21484 'error'
21485 );
21486 }
21487
21488 return;
21489 }
21490
21491 $premium_license = new FS_Plugin_License( $license );
21492
21493 // Updated site plan.
21494 $site = $this->get_api_site_scope()->get( '/', true );
21495 if ( $this->is_api_result_entity( $site ) ) {
21496 $this->_site = new FS_Site( $site );
21497 }
21498 $this->_update_site_license( $premium_license );
21499
21500 $this->_store_account();
21501
21502 if ( $this->is_addon() || $this->has_addons() ) {
21503 /**
21504 * Purge the valid user licenses cache so that when the "Account" or the "Add-Ons" page is loaded,
21505 * an updated valid user licenses collection will be fetched from the server which is used to also
21506 * update the account add-ons (add-ons the user has licenses for).
21507 *
21508 * @author Leo Fajardo (@leorw)
21509 * @since 2.2.4
21510 */
21511 $this->purge_valid_user_licenses_cache();
21512 }
21513
21514 if ( ! $background ) {
21515 $this->add_complete_upgrade_instructions_notice(
21516 $this->get_text_inline( 'Your license was successfully activated.', 'license-activated-message' ),
21517 'license_activated'
21518 );
21519 }
21520
21521 $this->_admin_notices->remove_sticky( array(
21522 'trial_promotion',
21523 'license_expired',
21524 ) );
21525 }
21526
21527 /**
21528 * @author Vova Feldman (@svovaf)
21529 * @since 1.0.5
21530 *
21531 * @param bool $show_notice
21532 */
21533 protected function _deactivate_license( $show_notice = true ) {
21534 $this->_logger->entrance();
21535
21536 $hmm_text = $this->get_text_x_inline( 'Hmm', 'something somebody says when they are thinking about what you have just said.', 'hmm' ) . '...';
21537
21538 if ( ! FS_Plugin_License::is_valid_id( $this->_site->license_id ) ) {
21539 $this->_admin_notices->add(
21540 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() ),
21541 $hmm_text
21542 );
21543
21544 return;
21545 }
21546
21547 $api = $this->get_api_site_scope();
21548 $license = $api->call( "/licenses/{$this->_site->license_id}.json", 'delete' );
21549
21550 $this->handle_license_deactivation_result( $license, $hmm_text, $show_notice );
21551 }
21552
21553 /**
21554 * @author Leo Fajardo (@leorw)
21555 * @since 2.2.1
21556 *
21557 * @param FS_Plugin_License $license
21558 * @param bool|string $hmm_text
21559 * @param bool $show_notice
21560 */
21561 private function handle_license_deactivation_result( $license, $hmm_text = false, $show_notice = true ) {
21562 if ( isset( $license->error ) ) {
21563 $this->_admin_notices->add(
21564 $this->get_text_inline( 'It looks like the license deactivation failed.', 'license-deactivation-failed-message' ) . '<br> ' .
21565 $this->get_text_inline( 'Error received from the server:', 'server-error-message' ) . ' ' . var_export( $license->error, true ),
21566 $hmm_text,
21567 'error'
21568 );
21569
21570 return;
21571 }
21572
21573 // Update license cache.
21574 if ( is_array( $this->_licenses ) ) {
21575 for ( $i = 0, $len = count( $this->_licenses ); $i < $len; $i ++ ) {
21576 if ( $license->id == $this->_licenses[ $i ]->id ) {
21577 $this->_licenses[ $i ] = new FS_Plugin_License( $license );
21578 }
21579 }
21580 }
21581
21582 // Update site plan to default.
21583 $this->_sync_plans();
21584 $this->_site->plan_id = $this->_plans[0]->id;
21585 // Unlink license from site.
21586 $this->_update_site_license( null );
21587
21588 $this->_store_account();
21589
21590 if ( $show_notice ) {
21591 $this->_admin_notices->add(
21592 sprintf( $this->is_only_premium() ?
21593 $this->get_text_inline( 'Your %s license was successfully deactivated.', 'license-deactivation-message_premium-only' ) :
21594 $this->get_text_inline( 'Your license was successfully deactivated, you are back to the %s plan.', 'license-deactivation-message' ),
21595 $this->get_plan_title()
21596 ),
21597 $this->get_text_inline( 'O.K', 'ok' )
21598 );
21599 }
21600
21601 $this->_admin_notices->remove_sticky( array(
21602 'plan_upgraded',
21603 'license_activated',
21604 ) );
21605 }
21606
21607 /**
21608 * Site plan downgrade.
21609 *
21610 * @author Vova Feldman (@svovaf)
21611 * @since 1.0.4
21612 *
21613 * @return object
21614 *
21615 * @uses FS_Api
21616 */
21617 private function _downgrade_site() {
21618 $this->_logger->entrance();
21619
21620 $deactivate_license = fs_request_get_bool( 'deactivate_license' );
21621
21622 $api = $this->get_api_site_scope();
21623 $site = $api->call( 'downgrade.json', 'put', array( 'deactivate_license' => $deactivate_license ) );
21624
21625 $plan_downgraded = false;
21626 $plan = false;
21627 if ( $this->is_api_result_entity( $site ) ) {
21628 $prev_plan_id = $this->_site->plan_id;
21629
21630 // Update new site plan id.
21631 $this->_site->plan_id = $site->plan_id;
21632
21633 $plan = $this->get_plan();
21634 $subscription = $this->_sync_site_subscription( $this->_license );
21635
21636 // Plan downgraded if plan was changed or subscription was cancelled.
21637 $plan_downgraded = ( $plan instanceof FS_Plugin_Plan && $prev_plan_id != $plan->id ) ||
21638 ( is_object( $subscription ) && ! isset( $subscription->error ) && ! $subscription->is_active() );
21639 } else {
21640 // handle different error cases.
21641 $this->handle_license_deactivation_result(
21642 $site,
21643 $this->get_text_x_inline( 'Hmm', 'something somebody says when they are thinking about what you have just said.', 'hmm' ) . '...'
21644 );
21645 }
21646
21647 if ( ! $plan_downgraded ) {
21648 return (object) array(
21649 'error' => (object) array(
21650 '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' )
21651 )
21652 );
21653 }
21654
21655 // Remove previous sticky message about upgrade (if exist).
21656 $this->_admin_notices->remove_sticky( 'plan_upgraded' );
21657
21658 $this->_admin_notices->add(
21659 sprintf( $this->get_text_inline( 'Your subscription was successfully cancelled. Your %s plan license will expire in %s.', 'plan-x-downgraded-message' ),
21660 $plan->title,
21661 human_time_diff( time(), strtotime( $this->_license->expiration ) )
21662 )
21663 );
21664
21665 // Store site updates.
21666 $this->_store_site();
21667
21668 if ( $deactivate_license &&
21669 ! FS_Plugin_License::is_valid_id( $site->license_id )
21670 ) {
21671 if ( $this->_site->is_localhost() ) {
21672 $this->_license->activated_local = max( 0, $this->_license->activated_local - 1 );
21673 } else {
21674 $this->_license->activated = max( 0, $this->_license->activated - 1 );
21675 }
21676
21677 // Handle successful license deactivation result.
21678 $this->handle_license_deactivation_result( $this->_license );
21679 }
21680
21681 return $site;
21682 }
21683
21684 /**
21685 * @author Vova Feldman (@svovaf)
21686 * @since 1.1.8.1
21687 *
21688 * @param bool|string $plan_name
21689 *
21690 * @return bool If trial was successfully started.
21691 */
21692 function start_trial( $plan_name = false ) {
21693 $this->_logger->entrance();
21694
21695 // Alias.
21696 $oops_text = $this->get_text_x_inline( 'Oops', 'exclamation', 'oops' ) . '...';
21697
21698 if ( $this->is_trial() ) {
21699 // Already in trial mode.
21700 $this->_admin_notices->add(
21701 sprintf( $this->get_text_inline( 'You are already running the %s in a trial mode.', 'in-trial-mode' ), $this->_module_type ),
21702 $oops_text,
21703 'error'
21704 );
21705
21706 return false;
21707 }
21708
21709 if ( $this->_site->is_trial_utilized() ) {
21710 // Trial was already utilized.
21711 $this->_admin_notices->add(
21712 $this->get_text_inline( 'You already utilized a trial before.', 'trial-utilized' ),
21713 $oops_text,
21714 'error'
21715 );
21716
21717 return false;
21718 }
21719
21720 if ( false !== $plan_name ) {
21721 $plan = $this->get_plan_by_name( $plan_name );
21722
21723 if ( false === $plan ) {
21724 // Plan doesn't exist.
21725 $this->_admin_notices->add(
21726 sprintf( $this->get_text_inline( 'Plan %s do not exist, therefore, can\'t start a trial.', 'trial-plan-x-not-exist' ), $plan_name ),
21727 $oops_text,
21728 'error'
21729 );
21730
21731 return false;
21732 }
21733
21734 if ( ! $plan->has_trial() ) {
21735 // Plan doesn't exist.
21736 $this->_admin_notices->add(
21737 sprintf( $this->get_text_inline( 'Plan %s does not support a trial period.', 'plan-x-no-trial' ), $plan_name ),
21738 $oops_text,
21739 'error'
21740 );
21741
21742 return false;
21743 }
21744 } else {
21745 if ( ! $this->has_trial_plan() ) {
21746 // None of the plans have a trial.
21747 $this->_admin_notices->add(
21748 sprintf( $this->get_text_inline( 'None of the %s\'s plans supports a trial period.', 'no-trials' ), $this->_module_type ),
21749 $oops_text,
21750 'error'
21751 );
21752
21753 return false;
21754 }
21755
21756 $plans_with_trial = FS_Plan_Manager::instance()->get_trial_plans( $this->_plans );
21757
21758 $plan = $plans_with_trial[0];
21759 }
21760
21761 $api = $this->get_api_site_scope();
21762 $plan = $api->call( "plans/{$plan->id}/trials.json", 'post' );
21763
21764 if ( ! $this->is_api_result_entity( $plan ) ) {
21765 // Some API error while trying to start the trial.
21766 $this->_admin_notices->add(
21767 $this->get_api_error_message( $plan ),
21768 $oops_text,
21769 'error'
21770 );
21771
21772 return false;
21773 }
21774
21775 // Sync license.
21776 $this->_sync_license();
21777
21778 return $this->is_trial();
21779 }
21780
21781 /**
21782 * Cancel site trial.
21783 *
21784 * @author Vova Feldman (@svovaf)
21785 * @since 1.0.9
21786 *
21787 * @return object
21788 *
21789 * @uses FS_Api
21790 */
21791 private function _cancel_trial() {
21792 $this->_logger->entrance();
21793
21794 if ( ! $this->is_trial() ) {
21795 return (object) array(
21796 'error' => (object) array(
21797 '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' )
21798 )
21799 );
21800 }
21801
21802 $trial_plan = $this->get_trial_plan();
21803
21804 $api = $this->get_api_site_scope();
21805 $site = $api->call( 'trials.json', 'delete' );
21806
21807 $trial_cancelled = false;
21808
21809 if ( $this->is_api_result_entity( $site ) ) {
21810 $prev_trial_ends = $this->_site->trial_ends;
21811
21812 if ( $this->is_paid_trial() ) {
21813 $this->_license->expiration = $site->trial_ends;
21814 $this->_license->is_cancelled = true;
21815 $this->_update_site_license( $this->_license );
21816 $this->_store_licenses();
21817
21818 // Clear subscription reference.
21819 $this->_sync_site_subscription( null );
21820 }
21821
21822 // Update site info.
21823 $this->_site = new FS_Site( $site );
21824
21825 $trial_cancelled = ( $prev_trial_ends != $site->trial_ends );
21826 } else {
21827 // @todo handle different error cases.
21828 }
21829
21830 if ( ! $trial_cancelled ) {
21831 return (object) array(
21832 'error' => (object) array(
21833 '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' )
21834 )
21835 );
21836 }
21837
21838 // Remove previous sticky messages about upgrade or trial (if exist).
21839 $this->_admin_notices->remove_sticky( array(
21840 'trial_started',
21841 'trial_promotion',
21842 'plan_upgraded',
21843 ) );
21844
21845 // Store site updates.
21846 $this->_store_site();
21847
21848 if ( ! $this->is_addon() ||
21849 ! $this->deactivate_premium_only_addon_without_license( true )
21850 ) {
21851 $this->_admin_notices->add(
21852 sprintf( $this->get_text_inline( 'Your %s free trial was successfully cancelled.', 'trial-cancel-message' ), $trial_plan->title )
21853 );
21854 }
21855
21856 return $site;
21857 }
21858
21859 /**
21860 * @author Vova Feldman (@svovaf)
21861 * @since 1.0.6
21862 *
21863 * @param bool|number $plugin_id
21864 *
21865 * @return bool
21866 */
21867 private function _is_addon_id( $plugin_id ) {
21868 return is_numeric( $plugin_id ) && ( $this->get_id() != $plugin_id );
21869 }
21870
21871 /**
21872 * Check if user eligible to download premium version updates.
21873 *
21874 * @author Vova Feldman (@svovaf)
21875 * @since 1.0.6
21876 *
21877 * @return bool
21878 */
21879 private function _can_download_premium() {
21880 return $this->has_any_active_valid_license() ||
21881 ( $this->is_trial() && ! $this->get_trial_plan()->is_free() );
21882 }
21883
21884 /**
21885 *
21886 * @author Vova Feldman (@svovaf)
21887 * @since 1.0.6
21888 *
21889 * @param bool|number $addon_id
21890 * @param string $type "json" or "zip"
21891 *
21892 * @return string
21893 */
21894 private function _get_latest_version_endpoint( $addon_id = false, $type = 'json' ) {
21895
21896 $is_addon = $this->_is_addon_id( $addon_id );
21897
21898 $is_premium = null;
21899 if ( ! $is_addon ) {
21900 $is_premium = ( $this->is_premium() || $this->_can_download_premium() );
21901 } else if ( $this->is_addon_activated( $addon_id ) ) {
21902 $fs_addon = self::get_instance_by_id( $addon_id );
21903 $is_premium = ( $fs_addon->is_premium() || $fs_addon->_can_download_premium() );
21904 }
21905
21906 // If add-on, then append add-on ID.
21907 $endpoint = ( $is_addon ? "/addons/$addon_id" : '' ) .
21908 '/updates/latest.' . $type;
21909
21910 // If add-on and not yet activated, try to fetch based on server licensing.
21911 if ( is_bool( $is_premium ) ) {
21912 $endpoint = add_query_arg( 'is_premium', json_encode( $is_premium ), $endpoint );
21913 }
21914
21915 if ( $this->has_secret_key() ) {
21916 $endpoint = add_query_arg( 'type', 'all', $endpoint );
21917 } else if ( is_object( $this->_site ) && $this->_site->is_beta() ) {
21918 $endpoint = add_query_arg( 'type', 'beta', $endpoint );
21919 }
21920
21921 return $endpoint;
21922 }
21923
21924 /**
21925 * @author Vova Feldman (@svovaf)
21926 * @since 1.0.4
21927 *
21928 * @param bool|number $addon_id
21929 * @param bool $flush Since 1.1.7.3
21930 * @param int $expiration Since 1.2.2.7
21931 * @param bool|string $newer_than Since 2.2.1
21932 * @param bool|string $fetch_readme Since 2.2.1
21933 *
21934 * @return object|false Plugin latest tag info.
21935 */
21936 function _fetch_latest_version(
21937 $addon_id = false,
21938 $flush = true,
21939 $expiration = WP_FS__TIME_24_HOURS_IN_SEC,
21940 $newer_than = false,
21941 $fetch_readme = true
21942 ) {
21943 $this->_logger->entrance();
21944
21945 if ( $this->is_unresolved_clone( true ) ) {
21946 return false;
21947 }
21948
21949 $switch_to_blog_id = null;
21950
21951 /**
21952 * @since 1.1.7.3 Check for plugin updates from Freemius only if opted-in.
21953 * @since 1.1.7.4 Also check updates for add-ons.
21954 */
21955 if (
21956 ( ! $this->is_registered() || ! FS_Permission_Manager::instance( $this )->is_essentials_tracking_allowed() ) &&
21957 ! $this->_is_addon_id( $addon_id )
21958 ) {
21959 if ( ! is_multisite() ) {
21960 return false;
21961 }
21962
21963 $installs_map = $this->get_blog_install_map();
21964
21965 foreach ( $installs_map as $blog_id => $install ) {
21966 if ( ! FS_Permission_Manager::instance( $this )->is_essentials_tracking_allowed( $blog_id ) ) {
21967 continue;
21968 }
21969
21970 /**
21971 * @var FS_Site $install
21972 */
21973 if ( $install->is_trial() ) {
21974 $switch_to_blog_id = $blog_id;
21975 break;
21976 }
21977
21978 if ( FS_Plugin_License::is_valid_id( $install->license_id ) ) {
21979 $license = $this->get_license_by_id( $install->license_id );
21980
21981 if ( is_object( $license ) && $license->is_features_enabled() ) {
21982 $switch_to_blog_id = $blog_id;
21983 break;
21984 }
21985 }
21986 }
21987
21988 if ( is_null( $switch_to_blog_id ) ) {
21989 return false;
21990 }
21991 }
21992
21993 $current_blog_id = is_numeric( $switch_to_blog_id ) ?
21994 get_current_blog_id() :
21995 0;
21996
21997 if ( is_numeric( $switch_to_blog_id ) ) {
21998 $this->switch_to_blog( $switch_to_blog_id );
21999 }
22000
22001 $latest_version_endpoint = $this->_get_latest_version_endpoint( $addon_id, 'json' );
22002
22003 if ( ! empty( $newer_than ) ) {
22004 $latest_version_endpoint = add_query_arg( 'newer_than', $newer_than, $latest_version_endpoint );
22005 }
22006
22007 if ( true === $fetch_readme ) {
22008 $latest_version_endpoint = add_query_arg( 'readme', 'true', $latest_version_endpoint );
22009 }
22010
22011 $tag = $this->get_api_site_or_plugin_scope()->get(
22012 $latest_version_endpoint,
22013 $flush,
22014 $expiration
22015 );
22016
22017 if ( is_numeric( $switch_to_blog_id ) ) {
22018 $this->switch_to_blog( $current_blog_id );
22019 }
22020
22021 $latest_version = ( is_object( $tag ) && isset( $tag->version ) ) ? $tag->version : 'couldn\'t get';
22022
22023 $this->_logger->departure( 'Latest version ' . $latest_version );
22024
22025 return ( is_object( $tag ) && isset( $tag->version ) ) ? $tag : false;
22026 }
22027
22028 #----------------------------------------------------------------------------------
22029 #region Download Plugin
22030 #----------------------------------------------------------------------------------
22031
22032 /**
22033 * Download latest plugin version, based on plan.
22034 *
22035 * Not like _download_latest(), this will redirect the page
22036 * to secure download url to prevent dual download (from FS to WP server,
22037 * and then from WP server to the client / browser).
22038 *
22039 * @author Vova Feldman (@svovaf)
22040 * @since 1.0.9
22041 *
22042 * @param bool|number $plugin_id
22043 *
22044 * @uses FS_Api
22045 * @uses wp_redirect()
22046 */
22047 private function download_latest_directly( $plugin_id = false ) {
22048 $this->_logger->entrance();
22049
22050 wp_redirect( $this->get_latest_download_api_url( $plugin_id ) );
22051 }
22052
22053 /**
22054 * Get latest plugin FS API download URL.
22055 *
22056 * @author Vova Feldman (@svovaf)
22057 * @since 1.0.9
22058 *
22059 * @param bool|number $plugin_id
22060 *
22061 * @return string
22062 */
22063 private function get_latest_download_api_url( $plugin_id = false ) {
22064 $this->_logger->entrance();
22065
22066 $download_api_url = $this->get_api_site_scope()->get_signed_url(
22067 $this->_get_latest_version_endpoint( $plugin_id, 'zip' )
22068 );
22069
22070 return str_replace( 'http:', 'https:', $download_api_url );
22071 }
22072
22073 /**
22074 * Get payment invoice URL.
22075 *
22076 * @author Vova Feldman (@svovaf)
22077 * @since 1.2.0
22078 *
22079 * @param bool|number $payment_id
22080 *
22081 * @return string
22082 */
22083 function _get_invoice_api_url( $payment_id = false ) {
22084 $this->_logger->entrance();
22085
22086 $url = $this->get_api_user_scope()->get_signed_url(
22087 "/payments/{$payment_id}/invoice.pdf"
22088 );
22089
22090 if ( ! fs_starts_with( $url, 'https://' ) ) {
22091 // Always use HTTPS for invoices.
22092 $url = 'https' . substr( $url, 4 );
22093 }
22094
22095 return $url;
22096 }
22097
22098 /**
22099 * Get latest plugin download link.
22100 *
22101 * @author Vova Feldman (@svovaf)
22102 * @since 1.0.9
22103 *
22104 * @param string $label
22105 * @param bool|number $plugin_id
22106 *
22107 * @return string
22108 */
22109 private function get_latest_download_link( $label, $plugin_id = false ) {
22110 return sprintf(
22111 '<a target="_blank" rel="noopener" href="%s">%s</a>',
22112 $this->_get_latest_download_local_url( $plugin_id ),
22113 $label
22114 );
22115 }
22116
22117 /**
22118 * Get latest plugin download local URL.
22119 *
22120 * @author Vova Feldman (@svovaf)
22121 * @since 1.0.9
22122 *
22123 * @param bool|number $plugin_id
22124 *
22125 * @return string
22126 */
22127 function _get_latest_download_local_url( $plugin_id = false ) {
22128 // Add timestamp to protect from caching.
22129 $params = array( 'ts' => WP_FS__SCRIPT_START_TIME );
22130
22131 if ( ! empty( $plugin_id ) ) {
22132 $params['plugin_id'] = $plugin_id;
22133 } else if ( $this->is_addon() ) {
22134 $params['plugin_id'] = $this->get_id();
22135 }
22136
22137 $fs = $this->is_addon() ?
22138 $this->get_parent_instance() :
22139 $this;
22140
22141 return $this->apply_filters( 'download_latest_url', $fs->get_account_url( 'download_latest', $params ) );
22142 }
22143
22144 #endregion Download Plugin ------------------------------------------------------------------
22145
22146 /**
22147 * @author Vova Feldman (@svovaf)
22148 * @since 1.0.4
22149 *
22150 * @uses FS_Api
22151 *
22152 * @param bool $background Hints the method if it's a background updates check. If false, it means that
22153 * was initiated by the admin.
22154 * @param bool|number $plugin_id
22155 * @param bool $flush Since 1.1.7.3
22156 * @param int $expiration Since 1.2.2.7
22157 * @param bool|string $newer_than Since 2.2.1
22158 */
22159 private function check_updates(
22160 $background = false,
22161 $plugin_id = false,
22162 $flush = true,
22163 $expiration = FS_Plugin_Updater::UPDATES_CHECK_CACHE_EXPIRATION,
22164 $newer_than = false
22165 ) {
22166 $this->_logger->entrance();
22167
22168 // Check if there's a newer version for download.
22169 $new_version = $this->_fetch_newer_version( $plugin_id, $flush, $expiration, $newer_than );
22170
22171 $update = null;
22172 if ( is_object( $new_version ) ) {
22173 $update = new FS_Plugin_Tag( $new_version );
22174
22175 if ( ! $background ) {
22176 $this->_admin_notices->add(
22177 sprintf(
22178 /* translators: %s: Numeric version number (e.g. '2.1.9' */
22179 $this->get_text_inline( 'Version %s was released.', 'version-x-released' ) . ' ' . $this->get_text_inline( 'Please download %s.', 'please-download-x' ),
22180 $update->version,
22181 sprintf(
22182 '<a href="%s" target="_blank" rel="noopener">%s</a>',
22183 $this->get_account_url( 'download_latest' ),
22184 sprintf(
22185 /* translators: %s: plan name (e.g. latest "Professional" version) */
22186 $this->get_text_inline( 'the latest %s version here', 'latest-x-version' ),
22187 $this->get_plan_title()
22188 )
22189 )
22190 ),
22191 $this->get_text_inline( 'New', 'new' ) . '!'
22192 );
22193 }
22194 } else if ( false === $new_version && ! $background ) {
22195 $this->_admin_notices->add(
22196 $this->get_text_inline( 'Seems like you got the latest release.', 'you-have-latest' ),
22197 $this->get_text_inline( 'You are all good!', 'you-are-good' )
22198 );
22199 }
22200
22201 $this->_store_update( $update, true, $plugin_id );
22202 }
22203
22204 /**
22205 * @author Vova Feldman (@svovaf)
22206 * @since 1.0.4
22207 *
22208 * @param bool $flush Since 1.1.7.3 add 24 hour cache by default.
22209 *
22210 * @return FS_Plugin[]
22211 *
22212 * @uses FS_Api
22213 */
22214 private function sync_addons( $flush = false ) {
22215 $this->_logger->entrance();
22216
22217 $api = $this->get_api_site_or_plugin_scope();
22218
22219 $path = $this->add_show_pending( '/addons.json?enriched=true&count=50' );
22220
22221 /**
22222 * @since 1.2.1
22223 *
22224 * If there's a cached version of the add-ons and not asking
22225 * for a flush, just use the currently stored add-ons.
22226 */
22227 if ( ! $flush && $api->is_cached( $path ) ) {
22228 $addons = self::get_all_addons();
22229
22230 return isset( $addons[ $this->_plugin->id ] ) ?
22231 $addons[ $this->_plugin->id ] :
22232 array();
22233 }
22234
22235 $result = $api->get( $path, $flush );
22236
22237 $addons = array();
22238 if ( $this->is_api_result_object( $result, 'plugins' ) &&
22239 is_array( $result->plugins )
22240 ) {
22241 for ( $i = 0, $len = count( $result->plugins ); $i < $len; $i ++ ) {
22242 $addons[ $i ] = new FS_Plugin( $result->plugins[ $i ] );
22243 }
22244
22245 $this->_store_addons( $addons, true );
22246 }
22247
22248 return $addons;
22249 }
22250
22251 /**
22252 * Handle user email update.
22253 *
22254 * @author Vova Feldman (@svovaf)
22255 * @since 1.0.3
22256 * @uses FS_Api
22257 *
22258 * @param string $new_email
22259 *
22260 * @return object
22261 */
22262 private function update_email( $new_email ) {
22263 $this->_logger->entrance();
22264
22265 $api = $this->get_api_user_scope();
22266 $user = $api->call( "?plugin_id={$this->_plugin->id}&fields=id,email,is_verified", 'put', array(
22267 'email' => $new_email,
22268 'after_email_confirm_url' => $this->_get_admin_page_url(
22269 'account',
22270 array( 'fs_action' => 'sync_user' )
22271 ),
22272 ) );
22273
22274 if ( ! isset( $user->error ) ) {
22275 $this->_user->email = $user->email;
22276 $this->_user->is_verified = $user->is_verified;
22277 $this->_store_user();
22278 } else {
22279 // handle different error cases.
22280 }
22281
22282 return $user;
22283 }
22284
22285 #----------------------------------------------------------------------------------
22286 #region API Error Handling
22287 #----------------------------------------------------------------------------------
22288
22289 /**
22290 * @author Vova Feldman (@svovaf)
22291 * @since 1.1.1
22292 *
22293 * @param mixed $result
22294 *
22295 * @return bool Is API result contains an error.
22296 */
22297 private function is_api_error( $result ) {
22298 return FS_Api::is_api_error( $result );
22299 }
22300
22301 /**
22302 * Checks if given API result is a non-empty and not an error object.
22303 *
22304 * @author Vova Feldman (@svovaf)
22305 * @since 1.2.1.5
22306 *
22307 * @param mixed $result
22308 * @param string|null $required_property Optional property we want to verify that is set.
22309 *
22310 * @return bool
22311 */
22312 function is_api_result_object( $result, $required_property = null ) {
22313 return FS_Api::is_api_result_object( $result, $required_property );
22314 }
22315
22316 /**
22317 * Checks if given API result is a non-empty entity object with non-empty ID.
22318 *
22319 * @author Vova Feldman (@svovaf)
22320 * @since 1.2.1.5
22321 *
22322 * @param mixed $result
22323 *
22324 * @return bool
22325 */
22326 private function is_api_result_entity( $result ) {
22327 return FS_Api::is_api_result_entity( $result );
22328 }
22329
22330 #endregion
22331
22332 /**
22333 * Make sure a given argument is an array of a specific type.
22334 *
22335 * @author Vova Feldman (@svovaf)
22336 * @since 1.2.1.5
22337 *
22338 * @param mixed $array
22339 * @param string $class
22340 *
22341 * @return bool
22342 */
22343 private function is_array_instanceof( $array, $class ) {
22344 return ( is_array( $array ) && ( empty( $array ) || $array[0] instanceof $class ) );
22345 }
22346
22347 /**
22348 * Start install ownership change.
22349 *
22350 * @author Vova Feldman (@svovaf)
22351 * @since 1.1.1
22352 * @uses FS_Api
22353 *
22354 * @param string $candidate_email
22355 * @param string $transfer_type
22356 *
22357 * @return bool Is ownership change successfully initiated.
22358 */
22359 private function init_change_owner( $candidate_email, $transfer_type ) {
22360 $this->_logger->entrance();
22361
22362 $installs_info_by_slug_map = $this->get_parent_and_addons_installs_info();
22363 $install_ids = array();
22364
22365 foreach ( $installs_info_by_slug_map as $slug => $install_info ) {
22366 $install = $install_info['install'];
22367
22368 if ( $this->_user->id != $install->user_id ) {
22369 // Skip add-on installs that are not owned by the parent product's install's owner.
22370 continue;
22371 }
22372
22373 $install_ids[ $slug ] = $install->id;
22374 }
22375
22376 $api = $this->get_api_site_scope();
22377 $result = $api->call( "/users/{$this->_user->id}.json", 'put', array(
22378 'email' => $candidate_email,
22379 'transfer_type' => $transfer_type,
22380 'install_ids' => implode( ',', array_values( $install_ids ) ),
22381 'after_confirm_url' => $this->_get_admin_page_url(
22382 'account',
22383 array( 'fs_action' => 'change_owner' )
22384 ),
22385 ) );
22386
22387 return ! $this->is_api_error( $result );
22388 }
22389
22390 /**
22391 * Handle install ownership change.
22392 *
22393 * @author Vova Feldman (@svovaf)
22394 * @since 1.1.1
22395 * @uses FS_Api
22396 *
22397 * @return bool Was ownership change successfully complete.
22398 */
22399 private function complete_change_owner() {
22400 $this->_logger->entrance();
22401
22402 $install_ids = fs_request_get( 'install_ids' );
22403
22404 if ( ! empty( $install_ids ) ) {
22405 $install_ids = explode( ',', $install_ids );
22406
22407 foreach ( $install_ids as $key => $install_id ) {
22408 if ( ! FS_Site::is_valid_id( $install_id ) ) {
22409 unset( $install_ids[ $key ] );
22410 }
22411 }
22412 }
22413
22414 if ( ! is_array( $install_ids ) ) {
22415 $install_ids = array();
22416 }
22417
22418 $user = new FS_User();
22419 $user->id = fs_request_get( 'user_id' );
22420 $user->public_key = fs_request_get_raw( 'user_public_key' );
22421 $user->secret_key = fs_request_get_raw( 'user_secret_key' );
22422
22423 $prev_user = $this->_user;
22424 $this->_user = $user;
22425
22426 $result = $this->get_api_user_scope( true )->get(
22427 "/installs.json?install_ids=" . implode( ',', $install_ids )
22428 );
22429
22430 $current_blog_sites = self::get_all_sites( $this->get_module_type() );
22431
22432 if ( $this->is_api_result_object( $result, 'installs' ) ) {
22433 $site_id_slug_map = array();
22434
22435 foreach ( $current_blog_sites as $slug => $site ) {
22436 $site_id_slug_map[ $site->id ] = $slug;
22437 }
22438
22439 foreach ( $result->installs as $install ) {
22440 $site = new FS_Site( $install );
22441
22442 if ( ! isset( $site_id_slug_map[ $install->id ] ) ) {
22443 continue;
22444 }
22445
22446 $current_blog_sites[ $site_id_slug_map[ $install->id ] ] = clone $site;
22447
22448 if ( $this->_site->id == $site->id ) {
22449 $this->_site = $site;
22450 }
22451 }
22452 }
22453
22454 // Validate install's user and given user.
22455 if ( $user->id != $this->_site->user_id ) {
22456 $this->_user = $prev_user;
22457
22458 return false;
22459 }
22460
22461 $this->set_account_option( 'sites', $current_blog_sites, true );
22462
22463 // Fetch new user information.
22464 $user_result = $this->get_api_user_scope( true )->get();
22465 $user = new FS_User( $user_result );
22466 $this->_user = $user;
22467
22468 $this->_set_account( $user, $this->_site );
22469
22470 $remove_user = true;
22471 $all_modules_sites = FS_DebugManager::get_all_modules_sites();
22472
22473 foreach ( $all_modules_sites as $sites_by_module_type ) {
22474 foreach ( $sites_by_module_type as $sites_by_slug ) {
22475 foreach ( $sites_by_slug as $site ) {
22476 if ( $prev_user->id == $site->user_id ) {
22477 $remove_user = false;
22478 break;
22479 }
22480 }
22481
22482 if ( ! $remove_user ) {
22483 break;
22484 }
22485 }
22486
22487 if ( ! $remove_user ) {
22488 break;
22489 }
22490 }
22491
22492 if ( $remove_user ) {
22493 $users = self::get_all_users();
22494
22495 if ( isset( $users[ $prev_user->id ] ) ) {
22496 unset( $users[ $prev_user->id ] );
22497 } else {
22498 // If the prev user wasn't found by the key, iterate over the users collection.
22499 foreach ( $users as $key => $user ) {
22500 if ( $user->id == $prev_user->id ) {
22501 unset( $users[ $key ] );
22502 break;
22503 }
22504 }
22505 }
22506
22507 $this->set_account_option( 'users', $users, true );
22508 }
22509
22510 return true;
22511 }
22512
22513 /**
22514 * Completes ownership change by license.
22515 *
22516 * @author Leo Fajardo (@leorw)
22517 * @since 2.3.2
22518 *
22519 * @param number $user_id
22520 * @param array[string]number $install_ids_by_slug_map
22521 *
22522 */
22523 private function complete_ownership_change_by_license( $user_id, $install_ids_by_slug_map ) {
22524 $this->_logger->entrance();
22525
22526 $this->sync_user_by_current_install( $user_id );
22527
22528 $result = $this->get_api_user_scope( true )->get(
22529 "/installs.json?install_ids=" . implode( ',', $install_ids_by_slug_map )
22530 );
22531
22532 if ( $this->is_api_result_object( $result, 'installs' ) ) {
22533 $sites = self::get_all_sites( $this->get_module_type() );
22534 $install_ids_by_slug_map = array_flip( $install_ids_by_slug_map );
22535
22536 foreach ( $result->installs as $install ) {
22537 $site = new FS_Site( $install );
22538
22539 $sites[ $install_ids_by_slug_map[ $site->id ] ] = clone $site;
22540 }
22541
22542 $this->set_account_option( 'sites', $sites, true );
22543 }
22544 }
22545
22546 /**
22547 * Handle user name update.
22548 *
22549 * @author Vova Feldman (@svovaf)
22550 * @since 1.0.9
22551 * @uses FS_Api
22552 *
22553 * @return object
22554 */
22555 private function update_user_name() {
22556 $this->_logger->entrance();
22557 $name = fs_request_get( 'fs_user_name_' . $this->get_unique_affix(), '' );
22558
22559 $api = $this->get_api_user_scope();
22560 $user = $api->call( "?plugin_id={$this->_plugin->id}&fields=id,first,last", 'put', array(
22561 'name' => $name,
22562 ) );
22563
22564 if ( ! isset( $user->error ) ) {
22565 $this->_user->first = $user->first;
22566 $this->_user->last = $user->last;
22567 $this->_store_user();
22568 } else {
22569 // handle different error cases.
22570
22571 }
22572
22573 return $user;
22574 }
22575
22576 /**
22577 * Verify user email.
22578 *
22579 * @author Vova Feldman (@svovaf)
22580 * @since 1.0.3
22581 * @uses FS_Api
22582 */
22583 private function verify_email() {
22584 $this->_handle_account_user_sync();
22585
22586 if ( $this->_user->is_verified() ) {
22587 return;
22588 }
22589
22590 $api = $this->get_api_site_scope();
22591 $result = $api->call( "/users/{$this->_user->id}/verify.json", 'put', array(
22592 'after_email_confirm_url' => $this->_get_admin_page_url(
22593 'account',
22594 array( 'fs_action' => 'sync_user' )
22595 )
22596 ) );
22597
22598 if ( ! isset( $result->error ) ) {
22599 $this->_admin_notices->add( sprintf(
22600 $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' ),
22601 sprintf( '<a href="mailto:%1$s">%2$s</a>', esc_url( $this->_user->email ), $this->_user->email )
22602 ) );
22603 } else {
22604 // handle different error cases.
22605
22606 }
22607 }
22608
22609 /**
22610 * @author Vova Feldman (@svovaf)
22611 * @since 1.1.2
22612 *
22613 * @param array $params
22614 * @param bool|null $network
22615 *
22616 * @return string
22617 */
22618 function get_activation_url( $params = array(), $network = null ) {
22619 if ( $this->is_addon() && $this->has_free_plan() ) {
22620 /**
22621 * @author Vova Feldman (@svovaf)
22622 * @since 1.2.1.7 Add-on's activation is the parent's module activation.
22623 */
22624 return $this->get_parent_instance()->get_activation_url( $params );
22625 }
22626
22627 return $this->apply_filters( 'connect_url', $this->_get_admin_page_url( '', $params, $network ) );
22628 }
22629
22630 /**
22631 * @author Vova Feldman (@svovaf)
22632 * @since 1.2.1.5
22633 *
22634 * @param array $params
22635 *
22636 * @return string
22637 */
22638 function get_reconnect_url( $params = array() ) {
22639 $params['fs_action'] = 'reset_anonymous_mode';
22640 $params['fs_unique_affix'] = $this->get_unique_affix();
22641
22642 return $this->get_activation_url( $params );
22643 }
22644
22645 /**
22646 * Get the URL of the page that should be loaded after the user connect
22647 * or skip in the opt-in screen.
22648 *
22649 * @author Vova Feldman (@svovaf)
22650 * @since 1.1.3
22651 *
22652 * @param string $filter Filter name.
22653 * @param array $params Since 1.2.2.7
22654 * @param bool|null $network
22655 *
22656 * @return string
22657 */
22658 function get_after_activation_url( $filter, $params = array(), $network = null ) {
22659 if ( $this->show_opt_in_on_themes_page() &&
22660 ( fs_request_has( 'pending_activation' ) ||
22661 // For cases when the first time path is set, even though it's a WP.org theme.
22662 fs_request_get_bool( $this->get_unique_affix() . '_show_optin' ) )
22663 ) {
22664 $first_time_path = '';
22665 } else {
22666 $first_time_path = $this->_menu->get_first_time_path(
22667 fs_is_network_admin() && $this->_is_network_active
22668 );
22669 }
22670
22671 if ( $this->_is_network_active &&
22672 fs_is_network_admin() &&
22673 ! $this->_menu->has_network_menu() &&
22674 $this->is_network_registered()
22675 ) {
22676 $target_url = $this->get_account_url();
22677 } else {
22678 // Default plugin's page.
22679 $target_url = $this->_get_admin_page_url( '', array(), $network );
22680 }
22681
22682 return add_query_arg( $params, $this->apply_filters(
22683 $filter,
22684 empty( $first_time_path ) ?
22685 $target_url :
22686 $first_time_path
22687 ) );
22688 }
22689
22690 /**
22691 * Handle account page updates / edits / actions.
22692 *
22693 * @author Vova Feldman (@svovaf)
22694 * @since 1.0.2
22695 *
22696 */
22697 private function _handle_account_edits() {
22698 if ( ! $this->is_user_admin() ) {
22699 return;
22700 }
22701
22702 $action = fs_get_action();
22703
22704 if ( empty( $action ) ) {
22705 return;
22706 }
22707
22708 $plugin_id = fs_request_get( 'plugin_id', $this->get_id() );
22709 $install_id = fs_request_get( 'install_id', '' );
22710
22711 // Alias.
22712 $oops_text = $this->get_text_x_inline( 'Oops', 'exclamation', 'oops' ) . '...';
22713
22714 $is_network_action = $this->is_network_level_action();
22715 $blog_id = $this->is_network_level_site_specific_action();
22716 $is_parent_plugin_action = ( $plugin_id == $this->get_id() );
22717
22718 if ( is_numeric( $blog_id ) ) {
22719 $this->switch_to_blog( $blog_id );
22720 } else {
22721 $blog_id = '';
22722 }
22723
22724 switch ( $action ) {
22725 case 'opt_in':
22726 check_admin_referer( trim( "{$action}:{$blog_id}:{$install_id}", ':' ) );
22727
22728 if ( $is_parent_plugin_action ) {
22729 if ( $is_network_action && ! empty( $blog_id ) ) {
22730 if ( ! $this->is_registered() ) {
22731 $this->install_with_user(
22732 $this->get_network_user(),
22733 false,
22734 false,
22735 false,
22736 false
22737 );
22738
22739 $this->_admin_notices->add(
22740 $this->get_text_inline( 'Site successfully opted in.', 'successful-opt-in' ),
22741 $this->get_text_inline( 'Awesome', 'awesome' )
22742 );
22743 }
22744 }
22745 }
22746 break;
22747
22748 case 'toggle_tracking':
22749 check_admin_referer( trim( "{$action}:{$blog_id}:{$install_id}", ':' ) );
22750
22751 if ( $is_parent_plugin_action ) {
22752 if ( $is_network_action && ! empty( $blog_id ) ) {
22753 if ( $this->is_registered( true ) ) {
22754 if ( $this->is_tracking_prohibited( $blog_id ) ) {
22755 if ( $this->toggle_site_tracking( true, $blog_id ) ) {
22756 $this->_admin_notices->add(
22757 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>" ),
22758 $this->get_text_inline( 'Thank you!', 'thank-you' )
22759 );
22760 }
22761 } else {
22762 if ( $this->toggle_site_tracking( false, $blog_id ) ) {
22763 $install = $this->get_install_by_blog_id( $blog_id );
22764
22765 $this->_admin_notices->add(
22766 sprintf(
22767 $this->get_text_inline( 'Diagnostic data will no longer be sent from %s to %s.', 'opted-out-successfully' ),
22768 self::get_unfiltered_site_url( $blog_id, true ),
22769 "<b>{$this->get_plugin_title()}</b>"
22770 )
22771 );
22772 }
22773 }
22774 }
22775 }
22776 }
22777
22778 break;
22779
22780 case 'delete_account':
22781 check_admin_referer( trim( "{$action}:{$blog_id}:{$install_id}", ':' ) );
22782
22783 $is_network_deletion = $is_network_action && empty( $blog_id );
22784
22785 if ( $is_parent_plugin_action ) {
22786 // Delete add-on installs if have any.
22787 $installed_addons = $this->get_installed_addons();
22788 foreach ( $installed_addons as $fs_addon ) {
22789 if ( $is_network_deletion ) {
22790 $fs_addon->delete_network_account_event();
22791 } else {
22792 $fs_addon->delete_account_event();
22793 }
22794 }
22795
22796 if ( $is_network_deletion ) {
22797 $this->delete_network_account_event();
22798 } else {
22799 $this->delete_account_event();
22800 }
22801
22802 // Clear user and site.
22803 $this->_site = null;
22804 $this->_user = null;
22805
22806 $this->maybe_set_slug_and_network_menu_exists_flag();
22807
22808 fs_redirect( $this->get_activation_url() );
22809 } else {
22810 if ( $this->is_addon_activated( $plugin_id ) ) {
22811 $fs_addon = self::get_instance_by_id( $plugin_id );
22812
22813 if ( $is_network_deletion ) {
22814 $fs_addon->delete_network_account_event();
22815 } else {
22816 $fs_addon->delete_account_event();
22817 }
22818
22819 fs_redirect( $this->_get_admin_page_url( 'account' ) );
22820 }
22821 }
22822
22823 return;
22824
22825 case 'downgrade_account':
22826 if ( is_numeric( $blog_id ) ) {
22827 check_admin_referer( trim( "{$action}:{$blog_id}:{$install_id}", ':' ) );
22828 } else {
22829 check_admin_referer( $action );
22830 }
22831
22832 $switch_to_network_install_blog_after_cancellation = (
22833 is_numeric( $blog_id ) &&
22834 $plugin_id == $this->get_id() &&
22835 ! $this->is_trial()
22836 );
22837
22838 $result = $this->cancel_subscription_or_trial( $plugin_id );
22839 if ( $this->is_api_error( $result ) ) {
22840 $this->_admin_notices->add(
22841 $result->error->message,
22842 $this->get_text_x_inline( 'Oops', 'exclamation', 'oops' ) . '...',
22843 'error'
22844 );
22845 }
22846
22847 if ( $switch_to_network_install_blog_after_cancellation ) {
22848 $this->switch_to_blog( $this->_storage->network_install_blog_id );
22849 }
22850
22851 return;
22852
22853 case 'activate_license':
22854 check_admin_referer( trim( "{$action}:{$blog_id}:{$install_id}", ':' ) );
22855
22856 $fs = $this;
22857 if ( $plugin_id != $this->get_id() ) {
22858 $fs = $this->is_addon_activated( $plugin_id ) ?
22859 self::get_instance_by_id( $plugin_id ) :
22860 null;
22861 }
22862
22863 if ( is_object( $fs ) ) {
22864 $fs->_activate_license();
22865
22866 /**
22867 * Remove the product ID from `$_REQUEST` so that the syncing of the license for the other products will work properly.
22868 *
22869 * @author Leo Fajardo (@leorw)
22870 * @since 2.4.0
22871 */
22872 unset( $_REQUEST['plugin_id'] );
22873
22874 if ( $this->is_bundle_license_auto_activation_enabled() ) {
22875 $fs->maybe_activate_bundle_license( null, array(), is_numeric( $blog_id ) ? $blog_id : 0 );
22876 }
22877 }
22878
22879 return;
22880
22881 case 'deactivate_license':
22882 check_admin_referer( trim( "{$action}:{$blog_id}:{$install_id}", ':' ) );
22883
22884 if ( $plugin_id == $this->get_id() ) {
22885 $this->_deactivate_license();
22886
22887 if ( $this->is_only_premium() ) {
22888 // Clear user and site.
22889 $this->_site = null;
22890 $this->_user = null;
22891
22892 if ( ! $is_network_action ) {
22893 fs_redirect( $this->get_activation_url() );
22894 } else if ( is_numeric( $blog_id ) ) {
22895 $this->switch_to_blog( $this->_storage->network_install_blog_id );
22896 }
22897 }
22898 } else {
22899 if ( $this->is_addon_activated( $plugin_id ) ) {
22900 $fs_addon = self::get_instance_by_id( $plugin_id );
22901 $fs_addon->_deactivate_license();
22902 }
22903 }
22904
22905 return;
22906
22907 case 'check_updates':
22908 check_admin_referer( $action );
22909 $this->check_updates();
22910
22911 return;
22912
22913 case 'change_owner':
22914 $state = fs_request_get( 'state', 'init' );
22915 switch ( $state ) {
22916 case 'init':
22917 // The nonce is injected by the error handler in `_email_address_update_ajax_handler` function.
22918 check_admin_referer( 'change_owner' );
22919
22920 $candidate_email = fs_request_get( 'candidate_email' );
22921 $transfer_type = fs_request_get( 'transfer_type' );
22922
22923 if ( $this->init_change_owner( $candidate_email, $transfer_type ) ) {
22924 if ( 'transfer' === $transfer_type ) {
22925 $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>' ) );
22926 } else {
22927 $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>' ) );
22928 }
22929 }
22930 break;
22931 case 'owner_confirmed':
22932 // We cannot (or need not to) check the nonce and referer here, because the link comes from the email sent by our API.
22933 $candidate_email = fs_request_get( 'candidate_email', '' );
22934
22935 if ( ! is_email($candidate_email ) ) {
22936 return;
22937 }
22938
22939 $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>' ) );
22940 break;
22941 case 'candidate_confirmed':
22942 // We do not need to validate the authenticity of this request here, because the `complete_change_owner` does that for us through API calls.
22943 if ( $this->complete_change_owner() ) {
22944 $this->_admin_notices->add_sticky(
22945 sprintf( $this->get_text_inline( '%s is the new owner of the account.', 'change-owner-request_candidate-confirmed' ), '<b>' . $this->_user->email . '</b>' ),
22946 'ownership_changed',
22947 $this->get_text_x_inline( 'Congrats', 'as congratulations', 'congrats' ) . '!'
22948 );
22949 } else {
22950 // @todo Handle failed ownership change message.
22951 }
22952 break;
22953 }
22954
22955 return;
22956
22957 case 'update_user_name':
22958 check_admin_referer( 'update_user_name' );
22959
22960 $result = $this->update_user_name();
22961
22962 if ( isset( $result->error ) ) {
22963 $this->_admin_notices->add(
22964 $this->get_text_inline( 'Please provide your full name.', 'name-update-failed-message' ),
22965 $oops_text,
22966 'error'
22967 );
22968 } else {
22969 $this->_admin_notices->add( $this->get_text_inline( 'Your name was successfully updated.', 'name-updated-message' ) );
22970 }
22971
22972 return;
22973
22974 #region Actions that might be called from external links (e.g. email)
22975
22976 /**
22977 * !!IMPORTANT!!: We cannot check for a valid nonce in this region, because the links could be coming from emails.
22978 */
22979
22980 case 'cancel_trial':
22981 $result = $this->cancel_subscription_or_trial( $plugin_id );
22982 if ( $this->is_api_error( $result ) ) {
22983 $this->_admin_notices->add(
22984 $result->error->message,
22985 $this->get_text_x_inline( 'Oops', 'exclamation', 'oops' ) . '...',
22986 'error'
22987 );
22988 }
22989
22990 return;
22991
22992 case 'verify_email':
22993 $this->verify_email();
22994
22995 return;
22996
22997 case 'sync_user':
22998 $this->_handle_account_user_sync();
22999
23000 return;
23001
23002 case $this->get_unique_affix() . '_sync_license':
23003 $this->_sync_license();
23004
23005 return;
23006
23007 case 'download_latest':
23008 $this->download_latest_directly( $plugin_id );
23009
23010 return;
23011
23012 #endregion
23013 }
23014
23015 if ( WP_FS__IS_POST_REQUEST ) {
23016 $properties = array( 'site_secret_key', 'site_id', 'site_public_key' );
23017 foreach ( $properties as $p ) {
23018 if ( 'update_' . $p === $action ) {
23019 check_admin_referer( $action );
23020
23021 $this->_logger->log( $action );
23022
23023 $site_property = substr( $p, strlen( 'site_' ) );
23024 $site_property_value = fs_request_get( 'fs_' . $p . '_' . $this->get_unique_affix(), '' );
23025 $this->get_site()->{$site_property} = $site_property_value;
23026
23027 // Store account after modification.
23028 $this->_store_site();
23029
23030 $this->do_action( 'account_property_edit', 'site', $site_property, $site_property_value );
23031
23032 $this->_admin_notices->add( sprintf(
23033 /* translators: %s: User's account property (e.g. email address, name) */
23034 $this->get_text_inline( 'You have successfully updated your %s.', 'x-updated' ),
23035 '<b>' . str_replace( '_', ' ', $p ) . '</b>'
23036 ) );
23037
23038 return;
23039 }
23040 }
23041 }
23042 }
23043
23044 /**
23045 * Adds CSS classes for the body tag in the admin.
23046 *
23047 * @param string $classes Space-separated string of class names.
23048 *
23049 * @return string $classes FS Admin body tag class names.
23050 */
23051 public function fs_addons_body_class( $classes ) {
23052 $classes .= ' plugins-php';
23053 return $classes;
23054 }
23055
23056 /**
23057 * Account page resources load.
23058 *
23059 * @author Vova Feldman (@svovaf)
23060 * @since 1.0.6
23061 */
23062 function _account_page_load() {
23063 $this->_logger->entrance();
23064
23065 $this->_logger->info( var_export( $_REQUEST, true ) );
23066
23067 fs_enqueue_local_style( 'fs_account', '/admin/account.css' );
23068
23069 if ( $this->has_addons() ) {
23070 wp_enqueue_script( 'plugin-install' );
23071 add_thickbox();
23072 add_filter( 'admin_body_class', array( $this, 'fs_addons_body_class' ) );
23073 }
23074
23075 if ( $this->has_paid_plan() &&
23076 ! $this->has_any_license() &&
23077 ! $this->is_sync_executed() &&
23078 $this->is_tracking_allowed()
23079 ) {
23080 /**
23081 * If no licenses found and no sync job was executed during the last 24 hours,
23082 * just execute the sync job right away (blocking execution).
23083 *
23084 * @since 1.1.7.3
23085 */
23086 $this->run_manual_sync();
23087 }
23088
23089 $this->_handle_account_edits();
23090
23091 if (
23092 is_object( $this->_license ) &&
23093 $this->_license->user_id == $this->_user->id &&
23094 ! $this->is_whitelabeled( true )
23095 ) {
23096 $this->_admin_notices->add(
23097 sprintf(
23098 $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' ),
23099 sprintf(
23100 '<a href="#" class="fs-toggle-whitelabel-mode">%s</a>',
23101 $this->get_text_inline( 'Click here', 'click-here' )
23102 )
23103 ),
23104 '',
23105 'success',
23106 false,
23107 'license_not_whitelabeled'
23108 );
23109 }
23110
23111 $this->do_action( 'account_page_load_before_departure' );
23112 }
23113
23114 /**
23115 * Renders the "Affiliation" page.
23116 *
23117 * @author Leo Fajardo (@leorw)
23118 * @since 1.2.3
23119 */
23120 function _affiliation_page_render() {
23121 $this->_logger->entrance();
23122
23123 $this->fetch_affiliate_and_terms();
23124
23125 fs_enqueue_local_style( 'fs_affiliation', '/admin/affiliation.css' );
23126
23127 $is_bundle_context = $this->has_bundle_context();
23128
23129 $plugin_title = $this->get_plugin_title();
23130
23131 if ( $is_bundle_context ) {
23132 $plugin_title = $this->plugin_affiliate_terms->plugin_title;
23133
23134 // Add the suffix "Bundle" only if the word is not present in the title itself.
23135 if ( false === mb_stripos( $plugin_title, fs_text_inline( 'Bundle', 'bundle' ) ) ) {
23136 $plugin_title = $this->apply_filters(
23137 'formatted_bundle_title',
23138 $plugin_title . ' ' . fs_text_inline( 'Bundle', 'bundle' )
23139 );
23140 }
23141 }
23142
23143 $vars = array(
23144 'id' => $this->_module_id,
23145 'plugin_title' => $plugin_title,
23146 );
23147 echo $this->apply_filters( "/forms/affiliation.php", fs_get_template( '/forms/affiliation.php', $vars ) );
23148 }
23149
23150
23151 /**
23152 * Render account page.
23153 *
23154 * @author Vova Feldman (@svovaf)
23155 * @since 1.0.0
23156 */
23157 function _account_page_render() {
23158 $this->_logger->entrance();
23159
23160 $template = 'account.php';
23161 $vars = array( 'id' => $this->_module_id );
23162
23163 /**
23164 * Added filter to the template to allow developers wrapping the template
23165 * in custom HTML (e.g. within a wizard/tabs).
23166 *
23167 * @author Vova Feldman (@svovaf)
23168 * @since 1.2.1.6
23169 */
23170 echo $this->apply_filters( "templates/{$template}", fs_get_template( $template, $vars ) );
23171 }
23172
23173 /**
23174 * Render account connect page.
23175 *
23176 * @author Vova Feldman (@svovaf)
23177 * @since 1.0.7
23178 */
23179 function _connect_page_render() {
23180 $this->_logger->entrance();
23181
23182 $vars = array( 'id' => $this->_module_id );
23183
23184 /**
23185 * Added filter to the template to allow developers wrapping the template
23186 * in custom HTML (e.g. within a wizard/tabs).
23187 *
23188 * @author Vova Feldman (@svovaf)
23189 * @since 1.2.1.6
23190 */
23191 echo $this->apply_filters( 'templates/connect.php', fs_get_template( 'connect.php', $vars ) );
23192 }
23193
23194 /**
23195 * Load required resources before add-ons page render.
23196 *
23197 * @author Vova Feldman (@svovaf)
23198 * @since 1.0.6
23199 */
23200 function _addons_page_load() {
23201 $this->_logger->entrance();
23202
23203 fs_enqueue_local_style( 'fs_addons', '/admin/add-ons.css' );
23204
23205 wp_enqueue_script( 'plugin-install' );
23206 add_thickbox();
23207 add_filter( 'admin_body_class', array( $this, 'fs_addons_body_class' ) );
23208
23209 if ( ! $this->is_registered() && $this->is_org_repo_compliant() ) {
23210 $this->_admin_notices->add(
23211 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>' ),
23212 $this->get_text_x_inline( 'Heads up', 'advance notice of something that will need attention.', 'heads-up' ),
23213 'update-nag'
23214 );
23215 }
23216 }
23217
23218 /**
23219 * Render add-ons page.
23220 *
23221 * @author Vova Feldman (@svovaf)
23222 * @since 1.0.6
23223 */
23224 function _addons_page_render() {
23225 $this->_logger->entrance();
23226
23227 $vars = array( 'id' => $this->_module_id );
23228
23229 /**
23230 * Added filter to the template to allow developers wrapping the template
23231 * in custom HTML (e.g. within a wizard/tabs).
23232 *
23233 * @author Vova Feldman (@svovaf)
23234 * @since 1.2.1.6
23235 */
23236 echo $this->apply_filters( 'templates/add-ons.php', fs_get_template( 'add-ons.php', $vars ) );
23237 }
23238
23239 /* Pricing & Upgrade
23240 ------------------------------------------------------------------------------------------------------------------*/
23241 /**
23242 * Render pricing page.
23243 *
23244 * @author Vova Feldman (@svovaf)
23245 * @since 1.0.0
23246 */
23247 function _pricing_page_render() {
23248 $this->_logger->entrance();
23249
23250 $vars = array( 'id' => $this->_module_id );
23251
23252 if ( 'true' === fs_request_get( 'checkout', false ) ) {
23253 echo $this->apply_filters( 'templates/checkout.php', fs_get_template( 'checkout.php', $vars ) );
23254 } else {
23255 echo $this->apply_filters( 'templates/pricing.php', fs_get_template( 'pricing.php', $vars ) );
23256 }
23257 }
23258
23259 /**
23260 * @author Leo Fajardo (@leorw)
23261 * @since 2.3.1
23262 */
23263 function _maybe_add_pricing_ajax_handler() {
23264 if ( ! $this->should_use_external_pricing() ) {
23265 $this->add_ajax_action( 'pricing_ajax_action', array( &$this, '_fs_pricing_ajax_action_handler' ) );
23266 }
23267 }
23268
23269 /**
23270 * @author Leo Fajardo (@leorw)
23271 * @since 2.3.1
23272 */
23273 function _fs_pricing_ajax_action_handler() {
23274 $this->check_ajax_referer( 'pricing_ajax_action' );
23275
23276 $result = null;
23277 $pricing_action = fs_request_get( 'pricing_action' );
23278
23279 switch ( $pricing_action ) {
23280 case 'fetch_pricing_data':
23281 $params = array(
23282 'is_enriched' => true,
23283 'trial' => fs_request_get_bool( 'trial' ),
23284 'sandbox' => fs_request_get_raw( 'sandbox' ),
23285 's_ctx_type' => fs_request_get_raw( 's_ctx_type' ),
23286 's_ctx_id' => fs_request_get_raw( 's_ctx_id' ),
23287 's_ctx_ts' => fs_request_get_raw( 's_ctx_ts' ),
23288 's_ctx_secure' => fs_request_get_raw( 's_ctx_secure' ),
23289 );
23290
23291 $bundle_id = $this->get_bundle_id();
23292 $bundle_public_key = $this->get_bundle_public_key();
23293
23294 $has_bundle_context = ( FS_Plugin::is_valid_id( $bundle_id ) && ! empty( $bundle_public_key ) );
23295
23296 if ( ! $has_bundle_context ) {
23297 $api = $this->get_api_plugin_scope();
23298 } else {
23299 $api = FS_Api::instance(
23300 $bundle_id,
23301 'plugin',
23302 $bundle_id,
23303 $bundle_public_key,
23304 ! $this->is_live(),
23305 false,
23306 $this->get_sdk_version()
23307 );
23308
23309 $params['plugin_id'] = $this->get_id();
23310 $params['plugin_public_key'] = $this->get_public_key();
23311 }
23312
23313 $result = $api->get( 'pricing.json?' . http_build_query( $params ) );
23314 break;
23315 case 'start_trial':
23316 $result = $this->opt_in(
23317 false,
23318 false,
23319 false,
23320 false,
23321 false,
23322 fs_request_get( 'plan_id' )
23323 );
23324 }
23325
23326 if ( is_object( $result ) && $this->is_api_error( $result ) ) {
23327 $this->_logger->api_error( $result );
23328
23329 self::shoot_ajax_failure(
23330 isset( $result->error ) ?
23331 ( is_string( $result->error ) ? $result->error : $result->error->message ) :
23332 var_export( $result, true )
23333 );
23334 }
23335
23336 $this->shoot_ajax_success( $result );
23337 }
23338
23339 #----------------------------------------------------------------------------------
23340 #region Contact Us
23341 #----------------------------------------------------------------------------------
23342
23343 /**
23344 * Render contact-us page.
23345 *
23346 * @author Vova Feldman (@svovaf)
23347 * @since 1.0.3
23348 */
23349 function _contact_page_render() {
23350 $this->_logger->entrance();
23351
23352 $vars = array( 'id' => $this->_module_id );
23353
23354 /**
23355 * Added filter to the template to allow developers wrapping the template
23356 * in custom HTML (e.g. within a wizard/tabs).
23357 *
23358 * @author Vova Feldman (@svovaf)
23359 * @since 2.1.3
23360 */
23361 echo $this->apply_filters( 'templates/contact.php', fs_get_template( 'contact.php', $vars ) );
23362 }
23363
23364 #endregion ------------------------------------------------------------------------
23365
23366 /**
23367 * Hide all admin notices to prevent distractions.
23368 *
23369 * @author Vova Feldman (@svovaf)
23370 * @since 1.0.3
23371 *
23372 * @uses remove_all_actions()
23373 */
23374 private static function _hide_admin_notices() {
23375 remove_all_actions( 'admin_notices' );
23376 remove_all_actions( 'network_admin_notices' );
23377 remove_all_actions( 'all_admin_notices' );
23378 remove_all_actions( 'user_admin_notices' );
23379 }
23380
23381 static function _clean_admin_content_section_hook() {
23382 $hide_admin_notices = true;
23383
23384 if ( fs_request_is_action( 'allow_clone_resolution_notice' ) ) {
23385 check_admin_referer( 'fs_allow_clone_resolution_notice' );
23386
23387 $hide_admin_notices = false;
23388 }
23389
23390 if ( $hide_admin_notices ) {
23391 self::_hide_admin_notices();
23392 }
23393
23394 // Hide footer.
23395 echo '<style>#wpfooter { display: none !important; }</style>';
23396 }
23397
23398 /**
23399 * Attach to admin_head hook to hide all admin notices.
23400 *
23401 * @author Vova Feldman (@svovaf)
23402 * @since 1.0.3
23403 */
23404 static function _clean_admin_content_section() {
23405 add_action( 'admin_head', 'Freemius::_clean_admin_content_section_hook' );
23406 }
23407
23408 /* CSS & JavaScript
23409 ------------------------------------------------------------------------------------------------------------------*/
23410 /* function _enqueue_script($handle, $src) {
23411 $url = plugins_url( substr( WP_FS__DIR_JS, strlen( $this->_plugin_dir_path ) ) . '/assets/js/' . $src );
23412
23413 $this->_logger->entrance( 'script = ' . $url );
23414
23415 wp_enqueue_script( $handle, $url );
23416 }*/
23417
23418 /* SDK
23419 ------------------------------------------------------------------------------------------------------------------*/
23420 private $_user_api;
23421
23422 /**
23423 *
23424 * @author Vova Feldman (@svovaf)
23425 * @since 1.0.2
23426 *
23427 * @param bool $flush
23428 *
23429 * @return FS_Api
23430 */
23431 function get_api_user_scope( $flush = false ) {
23432 if ( ! isset( $this->_user_api ) || $flush ) {
23433 $this->_user_api = $this->get_api_user_scope_by_user( $this->_user );
23434 }
23435
23436 return $this->_user_api;
23437 }
23438
23439 /**
23440 * @author Vova Feldman (@svovaf)
23441 * @since 2.0.0
23442 *
23443 * @param \FS_User $user
23444 *
23445 * @return \FS_Api
23446 */
23447 private function get_api_user_scope_by_user( FS_User $user ) {
23448 return FS_Api::instance(
23449 $this->_module_id,
23450 'user',
23451 $user->id,
23452 $user->public_key,
23453 ! $this->is_live(),
23454 $user->secret_key,
23455 $this->get_sdk_version()
23456 );
23457 }
23458
23459 /**
23460 *
23461 * @author Leo Fajardo (@leorw)
23462 * @since 2.0.0
23463 *
23464 * @param bool $flush
23465 *
23466 * @return FS_Api
23467 */
23468 private function get_current_or_network_user_api_scope( $flush = false ) {
23469 if ( ! $this->_is_network_active ||
23470 ( isset( $this->_user ) && $this->_user instanceof FS_User )
23471 ) {
23472 return $this->get_api_user_scope( $flush );
23473 }
23474
23475 $user = $this->get_current_or_network_user();
23476
23477 $this->_user_api = FS_Api::instance(
23478 $this->_module_id,
23479 'user',
23480 $user->id,
23481 $user->public_key,
23482 ! $this->is_live(),
23483 $user->secret_key,
23484 $this->get_sdk_version()
23485 );
23486
23487 return $this->_user_api;
23488 }
23489
23490 private $_site_api;
23491
23492 /**
23493 *
23494 * @author Vova Feldman (@svovaf)
23495 * @since 1.0.2
23496 *
23497 * @param bool $flush
23498 *
23499 * @return FS_Api
23500 */
23501 private function get_api_site_scope( $flush = false ) {
23502 if ( ! isset( $this->_site_api ) || $flush ) {
23503 $this->_site_api = FS_Api::instance(
23504 $this->_module_id,
23505 'install',
23506 $this->_site->id,
23507 $this->_site->public_key,
23508 ! $this->is_live(),
23509 $this->_site->secret_key,
23510 $this->get_sdk_version(),
23511 self::get_unfiltered_site_url()
23512 );
23513 }
23514
23515 return $this->_site_api;
23516 }
23517
23518 /**
23519 * @author Leo Fajardo (@leorw)
23520 * @since 2.5.0
23521 *
23522 * @param string $path
23523 * @param string $method
23524 * @param array $params
23525 * @param bool $flush_instance
23526 *
23527 * @return array|mixed|string|void
23528 * @throws Freemius_Exception
23529 */
23530 private function api_site_call( $path, $method = 'GET', $params = array(), $flush_instance = false ) {
23531 $result = $this->get_api_site_scope( $flush_instance )->call( $path, $method, $params );
23532
23533 /**
23534 * 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.
23535 *
23536 * @author Leo Fajardo (@leorw)
23537 * @since 2.5.0
23538 */
23539 if (
23540 $this->is_registered() &&
23541 FS_Api::is_api_result_entity( $result ) &&
23542 isset( $result->url )
23543 ) {
23544 $stored_local_url = trailingslashit( $this->_site->url );
23545 $stored_remote_url = trailingslashit( $result->url );
23546
23547 if ( $stored_local_url !== $stored_remote_url ) {
23548 $this->_site->url = $result->url;
23549 $this->_store_site();
23550 }
23551
23552 if ( fs_strip_url_protocol( $stored_remote_url ) !== self::get_unfiltered_site_url( null, true, true ) ) {
23553 FS_Clone_Manager::instance()->maybe_run_clone_resolution();
23554 }
23555 }
23556
23557 return $result;
23558 }
23559
23560 private $_plugin_api;
23561
23562 /**
23563 * Get plugin public API scope.
23564 *
23565 * @author Vova Feldman (@svovaf)
23566 * @since 1.0.7
23567 *
23568 * @return FS_Api
23569 */
23570 function get_api_plugin_scope() {
23571 if ( ! isset( $this->_plugin_api ) ) {
23572 $this->_plugin_api = FS_Api::instance(
23573 $this->_module_id,
23574 'plugin',
23575 $this->_plugin->id,
23576 $this->_plugin->public_key,
23577 ! $this->is_live(),
23578 false,
23579 $this->get_sdk_version()
23580 );
23581 }
23582
23583 return $this->_plugin_api;
23584 }
23585
23586 /**
23587 * Get bundle public API scope.
23588 *
23589 * @author Vova Feldman (@svovaf)
23590 * @since 2.3.1
23591 *
23592 * @return FS_Api
23593 */
23594 function get_api_bundle_scope() {
23595 return FS_Api::instance(
23596 $this->get_bundle_id(),
23597 'plugin',
23598 $this->get_bundle_id(),
23599 $this->get_bundle_public_key(),
23600 ! $this->is_live(),
23601 false,
23602 $this->get_sdk_version()
23603 );
23604 }
23605
23606 /**
23607 * Get site API scope object (fallback to public plugin scope when not registered).
23608 *
23609 * @author Vova Feldman (@svovaf)
23610 * @since 1.0.7
23611 *
23612 * @return FS_Api
23613 */
23614 function get_api_site_or_plugin_scope() {
23615 return $this->is_registered() ?
23616 $this->get_api_site_scope() :
23617 $this->get_api_plugin_scope();
23618 }
23619
23620 /**
23621 * @author Leo Fajardo (@leorw)
23622 * @since 2.2.3.1
23623 *
23624 * @param object $result
23625 */
23626 private function maybe_modify_api_curl_error_message( $result ) {
23627 if (
23628 'cUrlMissing' !== $result->error->type &&
23629 ( 'CurlException' !== $result->error->type || CURLE_COULDNT_CONNECT != $result->error->code ) &&
23630 ( 'HttpRequestFailed' !== $result->error->type || false === strpos( $result->error->message, 'cURL error ' . CURLE_COULDNT_CONNECT ) )
23631 ) {
23632 return;
23633 }
23634
23635 $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' ) .
23636 ' ' .
23637 $this->esc_html_inline(
23638 sprintf(
23639 'Please contact your hosting provider and ask them to whitelist %s for external connection.',
23640 implode(
23641 ', ',
23642 $this->apply_filters( 'api_domains', array(
23643 'api.freemius.com',
23644 'wp.freemius.com'
23645 ) )
23646 )
23647 ),
23648 'connectivity-whitelist'
23649 ) .
23650 ' ' .
23651 sprintf(
23652 $this->esc_html_inline( 'Once you are done, deactivate the %s and activate it again.', 'connectivity-reactivate-module' ),
23653 $this->get_module_type()
23654 );
23655 }
23656
23657 /**
23658 * Show trial promotional notice (if any trial exist).
23659 *
23660 * @author Vova Feldman (@svovaf)
23661 * @since 1.0.9
23662 *
23663 * @param FS_Plugin_Plan[] $plans
23664 */
23665 function _check_for_trial_plans( $plans ) {
23666 /**
23667 * 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.
23668 *
23669 * @author Vova Feldman (@svovaf)
23670 * @since 2.1.2
23671 */
23672 if ( ! is_array( $plans ) && is_object( $plans ) ) {
23673 $plans = array( $plans );
23674 }
23675
23676 if ( ! $this->is_array_instanceof( $plans, 'FS_Plugin_Plan' ) ) {
23677 $plans = array();
23678 }
23679
23680 $this->_storage->has_trial_plan = FS_Plan_Manager::instance()->has_trial_plan( $plans );
23681 }
23682
23683 /**
23684 * During trial promotion the "upgrade" submenu item turns to
23685 * "start trial" to encourage the trial. Since we want to keep
23686 * the same menu item handler and there's no robust way to
23687 * add new arguments to the menu item link's querystring,
23688 * use JavaScript to find the menu item and update the href of
23689 * the link.
23690 *
23691 * @author Vova Feldman (@svovaf)
23692 * @since 1.2.1.5
23693 */
23694 function _fix_start_trial_menu_item_url() {
23695 $template_args = array( 'id' => $this->_module_id );
23696 fs_require_template( 'add-trial-to-pricing.php', $template_args );
23697 }
23698
23699 /**
23700 * Check if module is currently in a trial promotion mode.
23701 *
23702 * @author Vova Feldman (@svovaf)
23703 * @since 1.2.2.7
23704 *
23705 * @return bool
23706 */
23707 function is_in_trial_promotion() {
23708 return $this->_admin_notices->has_sticky( 'trial_promotion' );
23709 }
23710
23711 /**
23712 * Show trial promotional notice (if any trial exist).
23713 *
23714 * @author Vova Feldman (@svovaf)
23715 * @since 1.0.9
23716 *
23717 * @return bool If trial notice added.
23718 */
23719 function _add_trial_notice() {
23720 if ( ! $this->is_user_admin() ) {
23721 return false;
23722 }
23723
23724 if ( ! $this->is_user_in_admin() ) {
23725 return false;
23726 }
23727
23728 if ( $this->_is_network_active ) {
23729 if ( fs_is_network_admin() ) {
23730 // Network level trial is disabled at the moment.
23731 return false;
23732 }
23733
23734 if ( ! $this->is_delegated_connection() ) {
23735 // Only delegated sites should support trials.
23736 return false;
23737 }
23738 }
23739
23740 // Check if trial message is already shown.
23741 if ( $this->is_in_trial_promotion() ) {
23742 add_action( 'admin_footer', array( &$this, '_fix_start_trial_menu_item_url' ) );
23743
23744 $this->_menu->add_counter_to_menu_item( 1, 'fs-trial' );
23745
23746 return false;
23747 }
23748
23749 if ( $this->is_premium() && ! WP_FS__DEV_MODE ) {
23750 // Don't show trial if running the premium code, unless running in DEV mode.
23751 return false;
23752 }
23753
23754 if ( ! $this->has_trial_plan() ) {
23755 // No plans with trial.
23756 return false;
23757 }
23758
23759 if ( ! $this->apply_filters( 'show_trial', true ) ) {
23760 // Developer explicitly asked not to show the trial promo.
23761 return false;
23762 }
23763
23764 if ( $this->is_registered() ) {
23765 // Check if trial already utilized.
23766 if ( $this->_site->is_trial_utilized() ) {
23767 return false;
23768 }
23769
23770 if ( $this->is_paying_or_trial() ) {
23771 // Don't show trial if paying or already in trial.
23772 return false;
23773 }
23774 }
23775
23776 if ( $this->is_activation_mode() || $this->is_pending_activation() ) {
23777 // If not yet opted-in/skipped, or pending activation, don't show trial.
23778 return false;
23779 }
23780
23781 $last_time_trial_promotion_shown = $this->_storage->get( 'trial_promotion_shown', false );
23782 $was_promotion_shown_before = ( false !== $last_time_trial_promotion_shown );
23783
23784 // Show promotion if never shown before and 24 hours after initial activation with FS.
23785 if ( ! $was_promotion_shown_before &&
23786 $this->_storage->install_timestamp > ( time() - $this->apply_filters( 'show_first_trial_after_n_sec', WP_FS__TIME_24_HOURS_IN_SEC ) )
23787 ) {
23788 return false;
23789 }
23790
23791 // OR if promotion was shown before, try showing it every 30 days.
23792 if ( $was_promotion_shown_before &&
23793 $this->apply_filters( 'reshow_trial_after_every_n_sec', 30 * WP_FS__TIME_24_HOURS_IN_SEC ) > time() - $last_time_trial_promotion_shown
23794 ) {
23795 return false;
23796 }
23797
23798 $trial_period = $this->_trial_days;
23799 $require_payment = $this->_is_trial_require_payment;
23800 $trial_url = $this->get_trial_url();
23801 $plans_string = strtolower( $this->get_text_inline( 'Awesome', 'awesome' ) );
23802
23803 if ( $this->is_registered() ) {
23804 // If opted-in, override trial with up to date data from API.
23805 $trial_plans = FS_Plan_Manager::instance()->get_visible_trial_plans( $this->_plans );
23806 $trial_plans_count = count( $trial_plans );
23807
23808 if ( 0 === $trial_plans_count ) {
23809 // If there's no plans with a trial just exit.
23810 return false;
23811 }
23812
23813 /**
23814 * @var FS_Plugin_Plan $paid_plan
23815 */
23816 $paid_plan = $trial_plans[0];
23817 $require_payment = $paid_plan->is_require_subscription;
23818 $trial_period = $paid_plan->trial_period;
23819
23820 $total_paid_plans = count( $this->_plans ) - ( FS_Plan_Manager::instance()->has_free_plan( $this->_plans ) ? 1 : 0 );
23821
23822 if ( $total_paid_plans !== $trial_plans_count ) {
23823 // Not all paid plans have a trial - generate a string of those that have it.
23824 for ( $i = 0; $i < $trial_plans_count; $i ++ ) {
23825 $plans_string .= sprintf(
23826 ' <a href="%s">%s</a>',
23827 $trial_url,
23828 $trial_plans[ $i ]->title
23829 );
23830
23831 if ( $i < $trial_plans_count - 2 ) {
23832 $plans_string .= ', ';
23833 } else if ( $i == $trial_plans_count - 2 ) {
23834 $plans_string .= ' and ';
23835 }
23836 }
23837 }
23838 }
23839
23840 $message = sprintf(
23841 $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' ),
23842 sprintf( '<b>%s</b>', $this->get_plugin_name() ),
23843 $plans_string,
23844 $trial_period
23845 );
23846
23847 // "No Credit-Card Required" or "No Commitment for N Days".
23848 $cc_string = $require_payment ?
23849 sprintf( $this->get_text_inline( 'No commitment for %s days - cancel anytime!', 'no-commitment-for-x-days' ), $trial_period ) :
23850 $this->get_text_inline( 'No credit card required', 'no-cc-required' ) . '!';
23851
23852
23853 // Start trial button.
23854 $button = ' ' . sprintf(
23855 '<a style="margin-left: 10px; vertical-align: super;" href="%s"><button class="button button-primary">%s &nbsp;&#10140;</button></a>',
23856 $trial_url,
23857 $this->get_text_x_inline( 'Start free trial', 'call to action', 'start-free-trial' )
23858 );
23859
23860 $this->_admin_notices->add_sticky(
23861 $this->apply_filters( 'trial_promotion_message', "{$message} {$cc_string} {$button}" ),
23862 'trial_promotion',
23863 '',
23864 'promotion'
23865 );
23866
23867 $this->_storage->trial_promotion_shown = WP_FS__SCRIPT_START_TIME;
23868
23869 return true;
23870 }
23871
23872 /**
23873 * Lets users/customers know that the product has an affiliate program.
23874 *
23875 * @author Leo Fajardo (@leorw)
23876 * @since 1.2.2.11
23877 *
23878 * @return bool Returns true if the notice has been added.
23879 */
23880 function _add_affiliate_program_notice() {
23881 if ( ! $this->is_user_admin() ) {
23882 return false;
23883 }
23884
23885 if ( ! $this->is_user_in_admin() ) {
23886 return false;
23887 }
23888
23889 // Check if the notice is already shown.
23890 if ( $this->_admin_notices->has_sticky( 'affiliate_program' ) ) {
23891 return false;
23892 }
23893
23894 if (
23895 // Product has no affiliate program.
23896 ! $this->has_affiliate_program() ||
23897 // User has applied for an affiliate account.
23898 ! empty( $this->_storage->affiliate_application_data )
23899 ) {
23900 return false;
23901 }
23902
23903 if ( ! $this->apply_filters( 'show_affiliate_program_notice', true ) ) {
23904 // Developer explicitly asked not to show the notice about the affiliate program.
23905 return false;
23906 }
23907
23908 if ( $this->is_activation_mode() || $this->is_pending_activation() ) {
23909 // If not yet opted in/skipped, or pending activation, don't show the notice.
23910 return false;
23911 }
23912
23913 $last_time_notice_was_shown = $this->_storage->get( 'affiliate_program_notice_shown', false );
23914 $was_notice_shown_before = ( false !== $last_time_notice_was_shown );
23915
23916 /**
23917 * Do not show the notice if it was already shown before or less than 30 days have passed since the initial
23918 * activation with FS.
23919 */
23920 if ( $was_notice_shown_before ||
23921 $this->_storage->install_timestamp > ( time() - ( WP_FS__TIME_24_HOURS_IN_SEC * 30 ) )
23922 ) {
23923 return false;
23924 }
23925
23926 if ( ! $this->is_paying() &&
23927 FS_Plugin::AFFILIATE_MODERATION_CUSTOMERS == $this->_plugin->affiliate_moderation
23928 ) {
23929 // If the user is not a customer and the affiliate program is only for customers, don't show the notice.
23930 return false;
23931 }
23932
23933 $message = sprintf(
23934 $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' ),
23935 sprintf( '<strong>%s</strong>', $this->get_plugin_name() ),
23936 $this->get_module_label( true )
23937 );
23938
23939 // HTML code for the "Learn more..." button.
23940 $button = ' ' . sprintf(
23941 '<a style="display: block; margin-top: 10px;" href="%s"><button class="button button-primary">%s &nbsp;&#10140;</button></a>',
23942 $this->_get_admin_page_url( 'affiliation' ),
23943 $this->get_text_inline( 'Learn more', 'learn-more' ) . '...'
23944 );
23945
23946 $this->_admin_notices->add_sticky(
23947 $this->apply_filters( 'affiliate_program_notice', "{$message} {$button}" ),
23948 'affiliate_program',
23949 '',
23950 'promotion'
23951 );
23952
23953 $this->_storage->affiliate_program_notice_shown = WP_FS__SCRIPT_START_TIME;
23954
23955 return true;
23956 }
23957
23958 /**
23959 * @author Vova Feldman (@svovaf)
23960 * @since 1.2.1.5
23961 */
23962 function _enqueue_common_css() {
23963 if ( $this->has_paid_plan() && ! $this->is_paying() ) {
23964 // Add basic CSS for admin-notices and menu-item colors.
23965 fs_enqueue_local_style( 'fs_common', '/admin/common.css' );
23966 }
23967 }
23968
23969 /**
23970 * @author Leo Fajardo (@leorw)
23971 * @since 1.2.2
23972 */
23973 function _show_theme_activation_optin_dialog() {
23974 fs_enqueue_local_style( 'fs_connect', '/admin/connect.css' );
23975
23976 add_action( 'admin_footer', array( &$this, '_add_fs_theme_activation_dialog' ) );
23977 }
23978
23979 /**
23980 * @author Leo Fajardo (@leorw)
23981 * @since 1.2.2
23982 */
23983 function _add_fs_theme_activation_dialog() {
23984 global $pagenow;
23985
23986 if ( 'themes.php' !== $pagenow ) {
23987 return;
23988 }
23989
23990 $vars = array( 'id' => $this->_module_id );
23991 fs_require_once_template( 'connect.php', $vars );
23992 }
23993
23994 /* Action Links
23995 ------------------------------------------------------------------------------------------------------------------*/
23996 private $_action_links_hooked = false;
23997 private $_action_links = array();
23998
23999 /**
24000 * Hook to plugin action links filter.
24001 *
24002 * @author Vova Feldman (@svovaf)
24003 * @since 1.0.0
24004 */
24005 private function hook_plugin_action_links() {
24006 $this->_logger->entrance();
24007
24008 $this->_action_links_hooked = true;
24009
24010 $this->_logger->log( 'Adding action links hooks.' );
24011
24012 // Add action link to settings page.
24013 add_filter( 'plugin_action_links_' . $this->_plugin_basename, array(
24014 &$this,
24015 '_modify_plugin_action_links_hook'
24016 ), WP_FS__DEFAULT_PRIORITY, 2 );
24017 add_filter( 'network_admin_plugin_action_links_' . $this->_plugin_basename, array(
24018 &$this,
24019 '_modify_plugin_action_links_hook'
24020 ), WP_FS__DEFAULT_PRIORITY, 2 );
24021 }
24022
24023 /**
24024 * Add plugin action link.
24025 *
24026 * @author Vova Feldman (@svovaf)
24027 * @since 1.0.0
24028 *
24029 * @param $label
24030 * @param $url
24031 * @param bool $external
24032 * @param int $priority
24033 * @param bool $key
24034 */
24035 function add_plugin_action_link( $label, $url, $external = false, $priority = WP_FS__DEFAULT_PRIORITY, $key = false ) {
24036 $this->_logger->entrance();
24037
24038 if ( ! isset( $this->_action_links[ $priority ] ) ) {
24039 $this->_action_links[ $priority ] = array();
24040 }
24041
24042 if ( false === $key ) {
24043 $key = preg_replace( "/[^A-Za-z0-9 ]/", '', strtolower( $label ) );
24044 }
24045
24046 $this->_action_links[ $priority ][] = array(
24047 'label' => $label,
24048 'href' => $url,
24049 'key' => $key,
24050 'external' => $external
24051 );
24052 }
24053
24054 /**
24055 * Adds Upgrade and Add-Ons links to the main Plugins page link actions collection.
24056 *
24057 * @author Vova Feldman (@svovaf)
24058 * @since 1.0.0
24059 */
24060 function _add_upgrade_action_link() {
24061 $this->_logger->entrance();
24062
24063 $is_activation_mode = $this->is_activation_mode();
24064
24065 $add_action_links = $this->should_add_submenu_or_action_links( $is_activation_mode );
24066
24067 /**
24068 * The following logic is based on the logic in `add_submenu_items()` method that decides when the "Upgrade"
24069 * and "Add-Ons" menus should be added.
24070 *
24071 * @author Leo Fajardo (@leorw)
24072 * @since 2.3.0
24073 */
24074 $add_upgrade_link = (
24075 $add_action_links ||
24076 ( $is_activation_mode && $this->is_only_premium() )
24077 ) && ! WP_FS__DEMO_MODE && ( ! $this->is_whitelabeled() );
24078
24079 $add_addons_link = ( $add_action_links && $this->has_addons() );
24080
24081 if ( ! $add_upgrade_link && ! $add_addons_link ) {
24082 return;
24083 }
24084
24085 if (
24086 $add_upgrade_link &&
24087 $this->is_pricing_page_visible() &&
24088 $this->is_submenu_item_visible( 'pricing' )
24089 ) {
24090 $this->add_plugin_action_link(
24091 $this->get_text_inline( 'Upgrade', 'upgrade' ),
24092 $this->get_upgrade_url(),
24093 false,
24094 7,
24095 'upgrade'
24096 );
24097 }
24098
24099 if (
24100 $add_addons_link &&
24101 $this->has_addons() &&
24102 $this->is_submenu_item_visible( 'addons' )
24103 ) {
24104 $this->add_plugin_action_link(
24105 $this->get_text_inline( 'Add-Ons', 'add-ons' ),
24106 $this->_get_admin_page_url( 'addons' ),
24107 false,
24108 9,
24109 'addons'
24110 );
24111 }
24112 }
24113
24114 /**
24115 * Adds "Activate License" or "Change License" link to the main Plugins page link actions collection.
24116 *
24117 * @author Leo Fajardo (@leorw)
24118 * @since 1.1.9
24119 */
24120 function _add_license_action_link() {
24121 $this->_logger->entrance();
24122
24123 if ( ! self::is_ajax() ) {
24124 // Inject license activation dialog UI and client side code.
24125 add_action( 'admin_footer', array( &$this, '_add_license_activation_dialog_box' ) );
24126 }
24127
24128 $link_text = $this->is_free_plan() ?
24129 $this->get_text_inline( 'Activate License', 'activate-license' ) :
24130 $this->get_text_inline( 'Change License', 'change-license' );
24131
24132 $this->add_plugin_action_link(
24133 $link_text,
24134 '#',
24135 false,
24136 11,
24137 ( 'activate-license ' . $this->get_unique_affix() )
24138 );
24139 }
24140
24141 /**
24142 * @author Leo Fajardo (@leorw)
24143 * @since 2.0.2
24144 */
24145 function _add_premium_version_upgrade_selection_action() {
24146 $this->_logger->entrance();
24147
24148 if ( ! self::is_ajax() ) {
24149 add_action( 'admin_footer', array( &$this, '_add_premium_version_upgrade_selection_dialog_box' ) );
24150 }
24151 }
24152
24153 /**
24154 * Adds "Opt In" or "Opt Out" link to the main "Plugins" page link actions collection.
24155 *
24156 * @author Leo Fajardo (@leorw)
24157 * @since 1.2.1.5
24158 */
24159 function _add_tracking_links() {
24160 if ( ! current_user_can( 'manage_options' ) ) {
24161 return;
24162 }
24163
24164 $this->_logger->entrance();
24165
24166 if ( $this->is_only_premium() && $this->is_free_plan() ) {
24167 // 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.
24168 return;
24169 }
24170
24171 if (
24172 $this->is_addon() &&
24173 ! $this->is_only_premium()
24174 ) {
24175 $parent = $this->get_parent_instance();
24176
24177 if ( is_object( $parent ) && $parent->is_anonymous() ) {
24178 return;
24179 }
24180 }
24181
24182 if ( fs_is_network_admin() ) {
24183 if ( ! $this->_is_network_active ) {
24184 // Don't add tracking links when browsing the network WP Admin and the plugin is not network active.
24185 return;
24186 } else if ( $this->is_network_delegated_connection() ) {
24187 // Don't add tracking links when browsing the network WP Admin and the activation has been delegated to site admins.
24188 return;
24189 }
24190 } else {
24191 if ( $this->_is_network_active && ! $this->is_delegated_connection() ) {
24192 // Don't add tracking links when browsing the sub-site WP Admin, the plugin is network active, and the connection was not delegated.
24193 return;
24194 }
24195 }
24196
24197 if ( fs_request_is_action_secure( $this->get_unique_affix() . '_reconnect' ) ) {
24198 if ( ! $this->is_registered() && $this->is_anonymous() ) {
24199 $this->connect_again();
24200
24201 return;
24202 }
24203 }
24204
24205 if ( ( $this->is_plugin() && ! self::is_plugins_page() ) ||
24206 ( $this->is_theme() && ! self::is_themes_page() )
24207 ) {
24208 // Only show tracking links on the plugins and themes pages.
24209 return;
24210 }
24211
24212 if (
24213 $this->is_activation_mode() &&
24214 $this->is_premium() &&
24215 ! $this->is_registered()
24216 ) {
24217 // If not yet registered and running the premium code base, a license activation link will already be shown.
24218 return;
24219 }
24220
24221 if ( $this->is_registered() && $this->is_tracking_allowed() ) {
24222 if ( ! $this->is_premium() && ! $this->is_enable_anonymous() ) {
24223 // If opted in and tracking is allowed, don't allow to opt out if not premium and anonymous mode is disabled.
24224 return;
24225 }
24226 }
24227
24228 if ( $this->add_ajax_action( 'toggle_permission_tracking', array( &$this, '_toggle_permission_tracking_callback' ) ) ) {
24229 return;
24230 }
24231
24232 $link_text_id = '';
24233 $url = '#';
24234
24235 if ( $this->is_registered( true ) ) {
24236 if ( $this->is_registered() && $this->is_tracking_allowed() ) {
24237 $link_text_id = $this->get_text_inline( 'Opt Out', 'opt-out' );
24238 } else {
24239 $link_text_id = $this->get_text_inline( 'Opt In', 'opt-in' );
24240 }
24241 } else if ( $this->is_anonymous() || $this->is_activation_mode() ) {
24242 /**
24243 * Show opt-in link only if skipped or in activation mode.
24244 */
24245 $link_text_id = $this->get_text_inline( 'Opt In', 'opt-in' );
24246
24247 $params = ! $this->is_anonymous() ?
24248 array() :
24249 array(
24250 'nonce' => wp_create_nonce( $this->get_unique_affix() . '_reconnect' ),
24251 'fs_action' => ( $this->get_unique_affix() . '_reconnect' ),
24252 );
24253
24254 $url = $this->get_activation_url( $params );
24255 }
24256
24257 add_action( 'admin_footer', array( &$this, '_add_optout_dialog' ) );
24258
24259 if ( ! empty( $link_text_id ) && $this->is_plugin() && self::is_plugins_page() ) {
24260 $this->add_plugin_action_link(
24261 $link_text_id,
24262 $url,
24263 false,
24264 13,
24265 "opt-in-or-opt-out {$this->_slug}"
24266 );
24267 }
24268 }
24269
24270 /**
24271 * Get the URL of the page that should be loaded right after the plugin activation.
24272 *
24273 * @author Vova Feldman (@svovaf)
24274 * @since 1.1.7.4
24275 *
24276 * @return string
24277 */
24278 function get_after_plugin_activation_redirect_url() {
24279 $url = false;
24280
24281 if ( ! $this->is_addon() || ! $this->has_free_plan() ) {
24282 $first_time_path = $this->_menu->get_first_time_path(
24283 fs_is_network_admin() && $this->_is_network_active
24284 );
24285
24286 if ( $this->is_activation_mode() ) {
24287 $url = $this->get_activation_url();
24288 } else if ( ! empty( $first_time_path ) ) {
24289 $url = $first_time_path;
24290 } else {
24291 $page = '';
24292 if ( ! empty( $this->_dynamically_added_top_level_page_hook_name ) ) {
24293 if ( $this->is_network_registered() ) {
24294 $page = 'account';
24295 } else if ( $this->is_pending_activation() || $this->is_network_anonymous() ) {
24296 $this->maybe_set_slug_and_network_menu_exists_flag();
24297 }
24298 }
24299
24300 $url = $this->_get_admin_page_url( $page );
24301 }
24302 } else {
24303 $plugin_fs = false;
24304
24305 if ( $this->is_parent_plugin_installed() ) {
24306 $plugin_fs = self::get_parent_instance();
24307 }
24308
24309 if ( is_object( $plugin_fs ) ) {
24310 if ( ! $plugin_fs->is_registered() ) {
24311 // Forward to parent plugin connect when parent not registered.
24312 $url = $plugin_fs->get_activation_url();
24313 } else {
24314 // Forward to account page.
24315 $url = $plugin_fs->_get_admin_page_url( 'account' );
24316 }
24317 }
24318 }
24319
24320 return $url;
24321 }
24322
24323 /**
24324 * Forward page to activation page.
24325 *
24326 * @author Vova Feldman (@svovaf)
24327 * @since 1.0.3
24328 */
24329 function _redirect_on_activation_hook() {
24330 if ( $this->apply_filters( 'redirect_on_activation', true ) ) {
24331 $url = $this->get_after_plugin_activation_redirect_url();
24332
24333 if ( is_string( $url ) ) {
24334 fs_redirect( $url );
24335 }
24336 }
24337 }
24338
24339 /**
24340 * Modify plugin's page action links collection.
24341 *
24342 * @author Vova Feldman (@svovaf)
24343 * @since 1.0.0
24344 *
24345 * @param array $links
24346 * @param $file
24347 *
24348 * @return array
24349 */
24350 function _modify_plugin_action_links_hook( $links, $file ) {
24351 $this->_logger->entrance();
24352
24353 $passed_deactivate = false;
24354 $deactivate_link = '';
24355 $before_deactivate = array();
24356 $after_deactivate = array();
24357 foreach ( $links as $key => $link ) {
24358 if ( 'deactivate' === $key ) {
24359 $deactivate_link = $link;
24360 $passed_deactivate = true;
24361 continue;
24362 }
24363
24364 if ( ! $passed_deactivate ) {
24365 $before_deactivate[ $key ] = $link;
24366 } else {
24367 $after_deactivate[ $key ] = $link;
24368 }
24369 }
24370
24371 ksort( $this->_action_links );
24372
24373 foreach ( $this->_action_links as $new_links ) {
24374 foreach ( $new_links as $link ) {
24375 $before_deactivate[ $link['key'] ] = '<a href="' . $link['href'] . '"' . ( $link['external'] ? ' target="_blank" rel="noopener"' : '' ) . '>' . $link['label'] . '</a>';
24376 }
24377 }
24378
24379 if ( ! empty( $deactivate_link ) ) {
24380 /**
24381 * This HTML element is used to identify the correct plugin when attaching an event to its Deactivate link.
24382 *
24383 * @since 1.2.1.6 Always show the deactivation feedback form since we added automatic free version deactivation upon premium code activation.
24384 */
24385 $deactivate_link .= '<i class="fs-module-id" data-module-id="' . $this->_module_id . '"></i>';
24386
24387 // Append deactivation link.
24388 $before_deactivate['deactivate'] = $deactivate_link;
24389 }
24390
24391 return array_merge( $before_deactivate, $after_deactivate );
24392 }
24393
24394 /**
24395 * Adds admin message.
24396 *
24397 * @author Vova Feldman (@svovaf)
24398 * @since 1.0.4
24399 *
24400 * @param string $message
24401 * @param string $title
24402 * @param string $type
24403 */
24404 function add_admin_message( $message, $title = '', $type = 'success' ) {
24405 $this->_admin_notices->add( $message, $title, $type );
24406 }
24407
24408 /**
24409 * Adds sticky admin message.
24410 *
24411 * @author Vova Feldman (@svovaf)
24412 * @since 1.1.0
24413 *
24414 * @param string $message
24415 * @param string $id
24416 * @param string $title
24417 * @param string $type
24418 */
24419 function add_sticky_admin_message( $message, $id, $title = '', $type = 'success' ) {
24420 $this->_admin_notices->add_sticky( $message, $id, $title, $type );
24421 }
24422
24423 /**
24424 * Check if the paid version of the module is installed.
24425 *
24426 * @author Vova Feldman (@svovaf)
24427 * @since 2.2.0
24428 *
24429 * @return bool
24430 */
24431 private function is_premium_version_installed() {
24432 $premium_plugin_basename = $this->premium_plugin_basename();
24433
24434 if ( $this->is_theme() ) {
24435 return $this->can_activate_theme( $this->get_premium_slug() );
24436 }
24437
24438 return file_exists( fs_normalize_path( WP_PLUGIN_DIR . '/' . $premium_plugin_basename ) );
24439 }
24440
24441 /**
24442 * Helper function that returns the final steps for the upgrade completion.
24443 *
24444 * If the module is already running the premium code, returns an empty string.
24445 *
24446 * @author Vova Feldman (@svovaf)
24447 * @since 1.2.1
24448 *
24449 * @param string $plan_title
24450 *
24451 * @return string
24452 */
24453 private function get_complete_upgrade_instructions( $plan_title = '' ) {
24454 $this->_logger->entrance();
24455
24456 $activate_license_string = $this->get_license_network_activation_notice();
24457
24458 if ( ! $this->has_premium_version() || $this->is_premium() ) {
24459 return '' . $activate_license_string;
24460 }
24461
24462 if ( empty( $plan_title ) ) {
24463 $plan_title = $this->get_plan_title();
24464 }
24465
24466 if ( $this->is_premium_version_installed() ) {
24467 /**
24468 * If the premium version is already installed, instead of showing the installation instructions,
24469 * tell the current user to activate it.
24470 *
24471 * @author Leo Fajardo (@leorw)
24472 * @since 2.2.1
24473 */
24474 $premium_theme_slug_or_plugin_basename = $this->is_theme() ?
24475 $this->get_premium_slug() :
24476 $this->premium_plugin_basename();
24477
24478 return sprintf(
24479 /* translators: %1$s: Product title; %2$s: Plan title */
24480 $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' ),
24481 sprintf( '<em>%s</em>', esc_html( $this->get_plugin_title() ) ),
24482 $plan_title,
24483 sprintf(
24484 '<a style="margin-left: 10px;" href="%s"><button class="button button-primary">%s</button></a>',
24485 ( $this->is_theme() ?
24486 wp_nonce_url( 'themes.php?action=activate&amp;stylesheet=' . $premium_theme_slug_or_plugin_basename, 'switch-theme_' . $premium_theme_slug_or_plugin_basename ) :
24487 wp_nonce_url( 'plugins.php?action=activate&amp;plugin=' . $premium_theme_slug_or_plugin_basename, 'activate-plugin_' . $premium_theme_slug_or_plugin_basename ) ),
24488 esc_html( sprintf(
24489 /* translators: %s: Plan title */
24490 $this->get_text_inline( 'Activate %s features', 'activate-x-features' ),
24491 $plan_title
24492 ) )
24493 )
24494 );
24495 } else {
24496 // @since 1.2.1.5 The free version is auto deactivated.
24497 $deactivation_step = version_compare( $this->version, '1.2.1.5', '<' ) ?
24498 ( '<li>' . $this->esc_html_inline( 'Deactivate the free version', 'deactivate-free-version' ) . '.</li>' ) :
24499 '';
24500
24501 return sprintf(
24502 ' %s: <ol><li>%s.</li>%s<li>%s (<a href="%s" target="_blank" rel="noopener">%s</a>).</li></ol>',
24503 $this->get_text_inline( 'Please follow these steps to complete the upgrade', 'follow-steps-to-complete-upgrade' ),
24504 ( empty( $activate_license_string ) ? '' : $activate_license_string . '</li><li>' ) .
24505 $this->get_latest_download_link( sprintf(
24506 /* translators: %s: Plan title */
24507 $this->get_text_inline( 'Download the latest %s version', 'download-latest-x-version' ),
24508 $plan_title
24509 ) ),
24510 $deactivation_step,
24511 $this->get_text_inline( 'Upload and activate the downloaded version', 'upload-and-activate' ),
24512 $this->apply_filters( 'upload_and_install_video_url', '//bit.ly/wp-' . $this->_module_type . '-upload' ),
24513 $this->get_text_inline( 'How to upload and activate?', 'howto-upload-activate' )
24514 );
24515 }
24516 }
24517
24518 /**
24519 * @author Leo Fajardo (@leorw)
24520 * @since 2.5.3
24521 *
24522 * @param string $message_before_the_instructions
24523 * @param string $message_id
24524 * @param string $plan_title
24525 */
24526 private function add_complete_upgrade_instructions_notice(
24527 $message_before_the_instructions,
24528 $message_id,
24529 $plan_title = ''
24530 ) {
24531 $this->_admin_notices->add_sticky(
24532 $message_before_the_instructions .
24533 $this->get_complete_upgrade_instructions( $plan_title ),
24534 $message_id,
24535 $this->get_text_x_inline( 'Yee-haw', 'interjection expressing joy or exuberance', 'yee-haw' ) . '!'
24536 );
24537 }
24538
24539 /**
24540 * @author Leo Fajardo (@leorw)
24541 * @since 2.5.3
24542 *
24543 * @param bool $is_upgrade
24544 */
24545 private function add_after_plan_activation_or_upgrade_instructions_notice( $is_upgrade = true ) {
24546 $this->add_complete_upgrade_instructions_notice(
24547 $is_upgrade ?
24548 $this->get_text_inline( 'Your plan was successfully upgraded.', 'plan-upgraded-message' ) :
24549 $this->get_text_inline( 'Your plan was successfully activated.', 'plan-activated-message' ),
24550 'plan_upgraded'
24551 );
24552 }
24553
24554 /**
24555 * @author Leo Fajardo (@leorw)
24556 * @since 2.1.0
24557 *
24558 * @param string $url
24559 * @param array $request
24560 * @param int $success_cache_expiration
24561 * @param int $failure_cache_expiration
24562 * @param bool $maybe_enrich_request_for_debug
24563 *
24564 * @return WP_Error|array
24565 */
24566 static function safe_remote_post(
24567 &$url,
24568 $request,
24569 $success_cache_expiration = 0,
24570 $failure_cache_expiration = 0,
24571 $maybe_enrich_request_for_debug = true
24572 ) {
24573 $should_cache = ($success_cache_expiration + $failure_cache_expiration > 0);
24574
24575 $cache_key = $should_cache ? md5( fs_strip_url_protocol($url) . json_encode( $request ) ) : false;
24576
24577 $response = (!WP_FS__DEBUG_SDK && ( false !== $cache_key )) ?
24578 get_transient( $cache_key ) :
24579 false;
24580
24581 if ( false === $response ) {
24582 if ( $maybe_enrich_request_for_debug ) {
24583 FS_DebugManager::enrich_request_for_debug( $url, $request );
24584 }
24585
24586 if ( ! isset( $request['method'] ) ) {
24587 $request['method'] = 'POST';
24588 }
24589
24590 $response = FS_Api::remote_request( $url, $request );
24591
24592 if (
24593 'https://' === substr( $url, 0, 8 ) &&
24594 FS_Api::is_ssl_error_response( $response )
24595 ) {
24596 // Failed due to old version of cURL or Open SSL (SSLv3 is not supported by CloudFlare).
24597 $url = 'http://' . substr( $url, 8 );
24598
24599 $request['timeout'] = 15;
24600 $response = FS_Api::remote_request( $url, $request );
24601 }
24602
24603 if ( false !== $cache_key ) {
24604 set_transient(
24605 $cache_key,
24606 $response,
24607 ( ( $response instanceof WP_Error ) ?
24608 $failure_cache_expiration :
24609 $success_cache_expiration )
24610 );
24611 }
24612 }
24613
24614 return $response;
24615 }
24616
24617 /**
24618 * This method is used to enrich the after upgrade notice instructions when the upgraded
24619 * license cannot be activated network wide (license quota isn't large enough).
24620 *
24621 * @author Vova Feldman (@svovaf)
24622 * @since 2.0.0
24623 *
24624 * @return string
24625 */
24626 private function get_license_network_activation_notice() {
24627 if ( ! $this->_is_network_active ) {
24628 // Module isn't network level activated.
24629 return '';
24630 }
24631
24632 if ( ! fs_is_network_admin() ) {
24633 // Not network level admin.
24634 return '';
24635 }
24636
24637 if ( get_blog_count() == 1 ) {
24638 // There's only a single site in the network so if there's a context license it was already activated.
24639 return '';
24640 }
24641
24642 if ( ! is_object( $this->_license ) ) {
24643 // No context license.
24644 return '';
24645 }
24646
24647 if ( $this->_license->is_single_site() && 0 < $this->_license->activated ) {
24648 // 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).
24649 return '';
24650 }
24651
24652 if ( $this->can_activate_license_on_network( $this->_license ) ) {
24653 // 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).
24654 return '';
24655 }
24656
24657 return sprintf(
24658 $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' ),
24659 '<a href="' . $this->get_account_url( false, array( 'activate_license' => 'true' ) ) . '">',
24660 '</a>'
24661 );
24662 }
24663
24664 /**
24665 * @author Vova Feldman (@svovaf)
24666 * @since 1.2.1.7
24667 *
24668 * @param string $key
24669 *
24670 * @return string
24671 */
24672 function get_text( $key ) {
24673 return fs_text( $key, $this->_slug );
24674 }
24675
24676 /**
24677 * @author Vova Feldman (@svovaf)
24678 * @since 1.2.3
24679 *
24680 * @param string $text Translatable string.
24681 * @param string $key String key for overrides.
24682 *
24683 * @return string
24684 */
24685 function get_text_inline( $text, $key = '' ) {
24686 return _fs_text_inline( $text, $key, $this->_slug );
24687 }
24688
24689 /**
24690 * @author Vova Feldman (@svovaf)
24691 * @since 1.2.3
24692 *
24693 * @param string $text Translatable string.
24694 * @param string $context Context information for the translators.
24695 * @param string $key String key for overrides.
24696 *
24697 * @return string
24698 */
24699 function get_text_x_inline( $text, $context, $key ) {
24700 return _fs_text_x_inline( $text, $context, $key, $this->_slug );
24701 }
24702
24703 /**
24704 * @author Vova Feldman (@svovaf)
24705 * @since 1.2.3
24706 *
24707 * @param string $text Translatable string.
24708 * @param string $key String key for overrides.
24709 *
24710 * @return string
24711 */
24712 function esc_html_inline( $text, $key ) {
24713 return esc_html( _fs_text_inline( $text, $key, $this->_slug ) );
24714 }
24715
24716 #----------------------------------------------------------------------------------
24717 #region Versioning
24718 #----------------------------------------------------------------------------------
24719
24720 /**
24721 * Check if Freemius in SDK upgrade mode.
24722 *
24723 * @author Vova Feldman (@svovaf)
24724 * @since 1.0.9
24725 *
24726 * @return bool
24727 */
24728 function is_sdk_upgrade_mode() {
24729 return isset( $this->_storage->sdk_upgrade_mode ) ?
24730 $this->_storage->sdk_upgrade_mode :
24731 false;
24732 }
24733
24734 /**
24735 * Turn SDK upgrade mode off.
24736 *
24737 * @author Vova Feldman (@svovaf)
24738 * @since 1.0.9
24739 */
24740 function set_sdk_upgrade_complete() {
24741 $this->_storage->sdk_upgrade_mode = false;
24742 }
24743
24744 /**
24745 * Check if plugin upgrade mode.
24746 *
24747 * @author Vova Feldman (@svovaf)
24748 * @since 1.0.9
24749 *
24750 * @return bool
24751 */
24752 function is_plugin_upgrade_mode() {
24753 return isset( $this->_storage->plugin_upgrade_mode ) ?
24754 $this->_storage->plugin_upgrade_mode :
24755 false;
24756 }
24757
24758 /**
24759 * Turn plugin upgrade mode off.
24760 *
24761 * @author Vova Feldman (@svovaf)
24762 * @since 1.0.9
24763 */
24764 function set_plugin_upgrade_complete() {
24765 $this->_storage->plugin_upgrade_mode = false;
24766
24767 $license_migration = ! empty( $this->_storage->license_migration ) ?
24768 $this->_storage->license_migration :
24769 array();
24770
24771 $license_migration['is_migrating'] = false;
24772
24773 $this->_storage->license_migration = $license_migration;
24774 }
24775
24776 #endregion
24777
24778 #----------------------------------------------------------------------------------
24779 #region Permissions
24780 #----------------------------------------------------------------------------------
24781
24782 /**
24783 * Check if specific permission requested.
24784 *
24785 * @author Vova Feldman (@svovaf)
24786 * @since 1.1.6
24787 *
24788 * @param string $permission
24789 *
24790 * @return bool
24791 */
24792 function is_permission_requested( $permission ) {
24793 return isset( $this->_permissions[ $permission ] ) && ( true === $this->_permissions[ $permission ] );
24794 }
24795
24796 #endregion
24797
24798 #----------------------------------------------------------------------------------
24799 #region Auto Activation
24800 #----------------------------------------------------------------------------------
24801
24802 /**
24803 * Hints the SDK if running an auto-installation.
24804 *
24805 * @var bool
24806 */
24807 private $_isAutoInstall = false;
24808
24809 /**
24810 * After upgrade callback to install and auto activate a plugin.
24811 * This code will only be executed on explicit request from the user,
24812 * following the practice Jetpack are using with their theme installations.
24813 *
24814 * @link https://make.wordpress.org/plugins/2017/03/16/clarification-of-guideline-8-executable-code-and-installs/
24815 *
24816 * @author Vova Feldman (@svovaf)
24817 * @since 1.2.1.7
24818 */
24819 function _install_premium_version_ajax_action() {
24820 $this->_logger->entrance();
24821
24822 $this->check_ajax_referer( 'install_premium_version' );
24823
24824 if ( ! $this->is_registered() ) {
24825 // Not registered.
24826 self::shoot_ajax_failure( array(
24827 'message' => $this->get_text_inline( 'Auto installation only works for opted-in users.', 'auto-install-error-not-opted-in' ),
24828 'code' => 'premium_installed',
24829 ) );
24830 }
24831
24832 $plugin_id = fs_request_get( 'target_module_id', $this->get_id() );
24833
24834 if ( ! FS_Plugin::is_valid_id( $plugin_id ) ) {
24835 // Invalid ID.
24836 self::shoot_ajax_failure( array(
24837 'message' => $this->get_text_inline( 'Invalid module ID.', 'auto-install-error-invalid-id' ),
24838 'code' => 'invalid_module_id',
24839 ) );
24840 }
24841
24842 if ( $plugin_id == $this->get_id() ) {
24843 if ( $this->is_premium() ) {
24844 // Already using the premium code version.
24845 self::shoot_ajax_failure( array(
24846 'message' => $this->get_text_inline( 'Premium version already active.', 'auto-install-error-premium-activated' ),
24847 'code' => 'premium_installed',
24848 ) );
24849 }
24850 if ( ! $this->can_use_premium_code() ) {
24851 // Don't have access to the premium code.
24852 self::shoot_ajax_failure( array(
24853 'message' => $this->get_text_inline( 'You do not have a valid license to access the premium version.', 'auto-install-error-invalid-license' ),
24854 'code' => 'invalid_license',
24855 ) );
24856 }
24857 if ( ! $this->has_release_on_freemius() ) {
24858 // Plugin is a serviceware, no premium code version.
24859 self::shoot_ajax_failure( array(
24860 'message' => $this->get_text_inline( 'Plugin is a "Serviceware" which means it does not have a premium code version.', 'auto-install-error-serviceware' ),
24861 'code' => 'premium_version_missing',
24862 ) );
24863 }
24864 } else {
24865 $addon = $this->get_addon( $plugin_id );
24866
24867 if ( ! is_object( $addon ) ) {
24868 // Invalid add-on ID.
24869 self::shoot_ajax_failure( array(
24870 'message' => $this->get_text_inline( 'Invalid module ID.', 'auto-install-error-invalid-id' ),
24871 'code' => 'invalid_module_id',
24872 ) );
24873 }
24874
24875 if ( $this->is_addon_activated( $plugin_id, true ) ) {
24876 // Premium add-on version is already activated.
24877 self::shoot_ajax_failure( array(
24878 'message' => $this->get_text_inline( 'Premium add-on version already installed.', 'auto-install-error-premium-addon-activated' ),
24879 'code' => 'premium_installed',
24880 ) );
24881 }
24882 }
24883
24884 $this->_isAutoInstall = true;
24885
24886 // Try to install and activate.
24887 $updater = FS_Plugin_Updater::instance( $this );
24888 $result = $updater->install_and_activate_plugin( $plugin_id );
24889
24890 if ( is_array( $result ) && ! empty( $result['message'] ) ) {
24891 self::shoot_ajax_failure( array(
24892 'message' => $result['message'],
24893 'code' => $result['code'],
24894 ) );
24895 }
24896
24897 self::shoot_ajax_success( $result );
24898 }
24899
24900 /**
24901 * Displays module activation dialog box after a successful upgrade
24902 * where the user explicitly requested to auto download and install
24903 * the premium version.
24904 *
24905 * @author Vova Feldman (@svovaf)
24906 * @since 1.2.1.7
24907 */
24908 function _add_auto_installation_dialog_box() {
24909 $this->_logger->entrance();
24910
24911 if ( ! $this->is_registered() ) {
24912 // Not registered.
24913 return;
24914 }
24915
24916 $plugin_id = fs_request_get( 'plugin_id', $this->get_id() );
24917
24918 if ( ! FS_Plugin::is_valid_id( $plugin_id ) ) {
24919 // Invalid module ID.
24920 return;
24921 }
24922
24923 if ( $plugin_id == $this->get_id() ) {
24924 if ( $this->is_premium() ) {
24925 // Already using the premium code version.
24926 return;
24927 }
24928 if ( ! $this->can_use_premium_code() ) {
24929 // Don't have access to the premium code.
24930 return;
24931 }
24932 if ( ! $this->has_release_on_freemius() ) {
24933 // Plugin is a serviceware, no premium code version.
24934 return;
24935 }
24936 } else {
24937 $addon = $this->get_addon( $plugin_id );
24938
24939 if ( ! is_object( $addon ) ) {
24940 // Invalid add-on ID.
24941 return;
24942 }
24943
24944 if ( $this->is_addon_activated( $plugin_id, true ) ) {
24945 // Premium add-on version is already activated.
24946 return;
24947 }
24948 }
24949
24950 $vars = array(
24951 'id' => $this->_module_id,
24952 'target_module_id' => $plugin_id,
24953 'slug' => $this->_slug,
24954 );
24955
24956 fs_require_template( 'auto-installation.php', $vars );
24957 }
24958
24959 #endregion
24960
24961 #--------------------------------------------------------------------------------
24962 #region Tabs Integration
24963 #--------------------------------------------------------------------------------
24964
24965 #region Module's Original Tabs
24966
24967 /**
24968 * Inject a JavaScript logic to capture the theme tabs HTML.
24969 *
24970 * @author Vova Feldman (@svovaf)
24971 * @since 1.2.2.7
24972 */
24973 function _tabs_capture() {
24974 $this->_logger->entrance();
24975
24976 if (
24977 ! $this->is_product_settings_page() ||
24978 ! $this->should_page_include_tabs() ||
24979 ! $this->is_matching_url( $this->main_menu_url() )
24980 ) {
24981 return;
24982 }
24983
24984 $params = array(
24985 'id' => $this->_module_id,
24986 );
24987
24988 fs_require_once_template( 'tabs-capture-js.php', $params );
24989 }
24990
24991 /**
24992 * Cache theme's tabs HTML for a week. The cache will also be set as expired
24993 * after version and type (free/premium) changes, in addition to the week period.
24994 *
24995 * @author Vova Feldman (@svovaf)
24996 * @since 1.2.2.7
24997 */
24998 function _store_tabs_ajax_action() {
24999 $this->_logger->entrance();
25000
25001 $this->check_ajax_referer( 'store_tabs' );
25002
25003 // Init filesystem if not yet initiated.
25004 WP_Filesystem();
25005
25006 // Get POST body HTML data.
25007 global $wp_filesystem;
25008 $tabs_html = $wp_filesystem->get_contents( "php://input" );
25009
25010 if ( is_string( $tabs_html ) ) {
25011 $tabs_html = trim( $tabs_html );
25012 }
25013
25014 if ( ! is_string( $tabs_html ) || empty( $tabs_html ) ) {
25015 self::shoot_ajax_failure();
25016 }
25017
25018 $this->_cache->set( 'tabs', $tabs_html, 7 * WP_FS__TIME_24_HOURS_IN_SEC );
25019
25020 self::shoot_ajax_success();
25021 }
25022
25023 /**
25024 * Cache theme's settings page custom styles. The cache will also be set as expired
25025 * after version and type (free/premium) changes, in addition to the week period.
25026 *
25027 * @author Vova Feldman (@svovaf)
25028 * @since 1.2.2.7
25029 */
25030 function _store_tabs_styles() {
25031 $this->_logger->entrance();
25032
25033 if (
25034 ! $this->is_product_settings_page() ||
25035 ! $this->should_page_include_tabs() ||
25036 ! $this->is_matching_url( $this->main_menu_url() )
25037 ) {
25038 return;
25039 }
25040
25041 $wp_styles = wp_styles();
25042
25043 $theme_styles_url = get_template_directory_uri();
25044
25045 $stylesheets = array();
25046 foreach ( $wp_styles->queue as $handler ) {
25047 if ( fs_starts_with( $handler, 'fs_' ) ) {
25048 // Assume that stylesheets that their handler starts with "fs_" belong to the SDK.
25049 continue;
25050 }
25051
25052 /**
25053 * @var _WP_Dependency $stylesheet
25054 */
25055 $stylesheet = $wp_styles->registered[ $handler ];
25056
25057 if ( fs_starts_with( $stylesheet->src, $theme_styles_url ) ) {
25058 $stylesheets[] = $stylesheet->src;
25059 }
25060 }
25061
25062 if ( ! empty( $stylesheets ) ) {
25063 $this->_cache->set( 'tabs_stylesheets', $stylesheets, 7 * WP_FS__TIME_24_HOURS_IN_SEC );
25064 }
25065 }
25066
25067 /**
25068 * Check if module's original settings page has any tabs.
25069 *
25070 * @author Vova Feldman (@svovaf)
25071 * @since 1.2.2.7
25072 *
25073 * @return bool
25074 */
25075 private function has_tabs() {
25076 return $this->_cache->has( 'tabs' );
25077 }
25078
25079 /**
25080 * Get module's settings page HTML content, starting
25081 * from the beginning of the <div class="wrap"> element,
25082 * until the tabs HTML (including).
25083 *
25084 * @author Vova Feldman (@svovaf)
25085 * @since 1.2.2.7
25086 *
25087 * @return string
25088 */
25089 private function get_tabs_html() {
25090 $this->_logger->entrance();
25091
25092 return $this->_cache->get( 'tabs' );
25093 }
25094
25095 /**
25096 * Check if page should include tabs.
25097 *
25098 * @author Vova Feldman (@svovaf)
25099 * @since 1.2.2.7
25100 *
25101 * @return bool
25102 */
25103 private function should_page_include_tabs() {
25104 if ( ! $this->has_settings_menu() ) {
25105 // Don't add tabs if no settings at all.
25106 return false;
25107 }
25108
25109 if ( self::NAVIGATION_TABS !== $this->_navigation ) {
25110 // Only add tabs to themes for now.
25111 return false;
25112 }
25113
25114 if ( $this->is_theme() && ! $this->has_paid_plan() && ! $this->has_addons() ) {
25115 // Only add tabs to monetizing themes.
25116 return false;
25117 }
25118
25119 if ( ! $this->is_product_settings_page() ) {
25120 // Only add tabs if browsing one of the product's setting pages.
25121 return false;
25122 }
25123
25124 if ( $this->is_activation_mode() && $this->is_activation_page() ) {
25125 // Don't include tabs in the activation page.
25126 return false;
25127 }
25128
25129 if ( $this->is_admin_page( 'pricing' ) && fs_request_get_bool( 'checkout' ) ) {
25130 // Don't add tabs on checkout page, we want to reduce distractions
25131 // as much as possible.
25132 return false;
25133 }
25134
25135 return true;
25136 }
25137
25138 /**
25139 * Add the tabs HTML before the setting's page content and
25140 * enqueue any required stylesheets.
25141 *
25142 * @author Vova Feldman (@svovaf)
25143 * @since 1.2.2.7
25144 *
25145 * @return bool If tabs were included.
25146 */
25147 function _add_tabs_before_content() {
25148 $this->_logger->entrance();
25149
25150 if ( ! $this->should_page_include_tabs() ) {
25151 return false;
25152 }
25153
25154 $tabs_html = $this->get_tabs_html();
25155
25156 if ( empty( $tabs_html ) ) {
25157 return false;
25158 }
25159
25160 /**
25161 * Enqueue the original stylesheets that are included in the
25162 * theme settings page. That way, if the theme settings has
25163 * some custom _styled_ content above the tabs UI, this
25164 * will make sure that the styling is preserved.
25165 */
25166 $stylesheets = $this->_cache->get( 'tabs_stylesheets', array() );
25167 if ( is_array( $stylesheets ) ) {
25168 for ( $i = 0, $len = count( $stylesheets ); $i < $len; $i ++ ) {
25169 wp_enqueue_style( "fs_{$this->_module_id}_tabs_{$i}", $stylesheets[ $i ] );
25170 }
25171 }
25172
25173 // Cut closing </div> tag.
25174 echo substr( trim( $tabs_html ), 0, - 6 );
25175
25176 return true;
25177 }
25178
25179 /**
25180 * Add the tabs closing HTML after the setting's page content.
25181 *
25182 * @author Vova Feldman (@svovaf)
25183 * @since 1.2.2.7
25184 *
25185 * @return bool If tabs closing HTML was included.
25186 */
25187 function _add_tabs_after_content() {
25188 $this->_logger->entrance();
25189
25190 if ( ! $this->should_page_include_tabs() ) {
25191 return false;
25192 }
25193
25194 echo '</div>';
25195
25196 return true;
25197 }
25198
25199 #endregion
25200
25201 /**
25202 * Add in-page JavaScript to inject the Freemius tabs into
25203 * the module's setting tabs section.
25204 *
25205 * @author Vova Feldman (@svovaf)
25206 * @since 1.2.2.7
25207 */
25208 function _add_freemius_tabs() {
25209 $this->_logger->entrance();
25210
25211 if ( ! $this->should_page_include_tabs() ) {
25212 return;
25213 }
25214
25215 $params = array( 'id' => $this->_module_id );
25216 fs_require_once_template( 'tabs.php', $params );
25217 }
25218
25219 #endregion
25220
25221 #--------------------------------------------------------------------------------
25222 #region Customizer Integration for Themes
25223 #--------------------------------------------------------------------------------
25224
25225 /**
25226 * @author Vova Feldman (@svovaf)
25227 * @since 1.2.2.7
25228 *
25229 * @param WP_Customize_Manager $customizer
25230 */
25231 function _customizer_register( $customizer ) {
25232 $this->_logger->entrance();
25233
25234 if ( $this->is_pricing_page_visible() ) {
25235 require_once WP_FS__DIR_INCLUDES . '/customizer/class-fs-customizer-upsell-control.php';
25236
25237 $customizer->add_section( 'freemius_upsell', array(
25238 'title' => '&#9733; ' . $this->get_text_inline( 'View paid features', 'view-paid-features' ),
25239 'priority' => 1,
25240 ) );
25241 $customizer->add_setting( 'freemius_upsell', array(
25242 'sanitize_callback' => 'esc_html',
25243 ) );
25244
25245 $customizer->add_control( new FS_Customizer_Upsell_Control( $customizer, 'freemius_upsell', array(
25246 'fs' => $this,
25247 'section' => 'freemius_upsell',
25248 'priority' => 100,
25249 ) ) );
25250 }
25251
25252 if ( $this->is_page_visible( 'contact' ) || $this->is_page_visible( 'support' ) ) {
25253 require_once WP_FS__DIR_INCLUDES . '/customizer/class-fs-customizer-support-section.php';
25254
25255 // Main Documentation Link In Customizer Root.
25256 $customizer->add_section( new FS_Customizer_Support_Section( $customizer, 'freemius_support', array(
25257 'fs' => $this,
25258 'priority' => 1000,
25259 ) ) );
25260 }
25261 }
25262
25263 #endregion
25264
25265 /**
25266 * If the theme has a paid version, add some custom
25267 * styling to the theme's premium version (if exists)
25268 * to highlight that it's the premium version of the
25269 * same theme, making it easier for identification
25270 * after the user upgrades and upload it to the site.
25271 *
25272 * @author Vova Feldman (@svovaf)
25273 * @since 1.2.2.7
25274 */
25275 function _style_premium_theme() {
25276 $this->_logger->entrance();
25277
25278 if ( ! self::is_themes_page() ) {
25279 // Only include in the themes page.
25280 return;
25281 }
25282
25283 if ( ! $this->has_paid_plan() ) {
25284 // Only include if has any paid plans.
25285 return;
25286 }
25287
25288 $params = null;
25289 fs_require_once_template( '/js/jquery.content-change.php', $params );
25290
25291 $params = array(
25292 'slug' => $this->_slug,
25293 'id' => $this->_module_id,
25294 );
25295
25296 fs_require_template( '/js/style-premium-theme.php', $params );
25297 }
25298
25299 /**
25300 * This method will return the absolute URL of the module's local icon.
25301 *
25302 * When you are running your plugin or theme on a **localhost** environment, if the icon
25303 * is not found in the local assets folder, try to fetch the icon URL from Freemius. If not set and
25304 * it's a plugin hosted on WordPress.org, try fetching the icon URL from wordpress.org.
25305 * If an icon is found, this method will automatically attempt to download the icon and store it
25306 * in /freemius/assets/img/{slug}.{png|jpg|gif|svg}.
25307 *
25308 * It's important to mention that this method is NOT phoning home since the developer will deploy
25309 * the product with the local icon in the assets folder. The download process just simplifies
25310 * the process for the developer.
25311 *
25312 * @author Vova Feldman (@svovaf)
25313 * @since 2.0.0
25314 *
25315 * @return string
25316 */
25317 function get_local_icon_url() {
25318 global $fs_active_plugins;
25319
25320 /**
25321 * @since 1.1.7.5
25322 */
25323 $local_path = $this->apply_filters( 'plugin_icon', false );
25324
25325 if ( is_string( $local_path ) ) {
25326 $icons = array( $local_path );
25327 } else {
25328 $img_dir = WP_FS__DIR_IMG;
25329
25330 // Locate the main assets folder.
25331 if ( 1 < count( $fs_active_plugins->plugins ) ) {
25332 $plugin_or_theme_img_dir = ( $this->is_plugin() ? WP_PLUGIN_DIR : get_theme_root( get_stylesheet() ) );
25333
25334 foreach ( $fs_active_plugins->plugins as $sdk_path => &$data ) {
25335 if ( $data->plugin_path == $this->get_plugin_basename() ) {
25336 $img_dir = $plugin_or_theme_img_dir
25337 . '/'
25338 /**
25339 * The basename will be `themes` or the basename of a custom themes directory.
25340 *
25341 * @author Leo Fajardo (@leorw)
25342 * @since 2.2.3
25343 */
25344 . str_replace( '../' . basename( $plugin_or_theme_img_dir ) . '/', '', $sdk_path )
25345 . '/assets/img';
25346
25347 break;
25348 }
25349 }
25350 }
25351
25352 // Try to locate the icon in the assets folder.
25353 $icons = glob( fs_normalize_path( $img_dir . "/{$this->_slug}.*" ) );
25354
25355 if ( ! is_array( $icons ) || 0 === count( $icons ) ) {
25356 if ( ! WP_FS__IS_LOCALHOST && $this->is_theme() ) {
25357 $icons = array(
25358 fs_normalize_path( $img_dir . '/theme-icon.png' )
25359 );
25360 } else {
25361 $icon_found = false;
25362 $local_path = fs_normalize_path( "{$img_dir}/{$this->_slug}.png" );
25363
25364 if ( ! function_exists( 'get_filesystem_method' ) ) {
25365 require_once ABSPATH . 'wp-admin/includes/file.php';
25366 }
25367
25368 $have_write_permissions = ( 'direct' === get_filesystem_method( array(), fs_normalize_path( $img_dir ) ) );
25369
25370 /**
25371 * IMPORTANT: THIS CODE WILL NEVER RUN AFTER THE PLUGIN IS IN THE REPO.
25372 *
25373 * This code will only be executed once during the testing
25374 * of the plugin in a local environment. The plugin icon file WILL
25375 * already exist in the assets folder when the plugin is deployed to
25376 * the repository.
25377 */
25378 if ( WP_FS__IS_LOCALHOST && $have_write_permissions ) {
25379 // Fetch icon from Freemius.
25380 $icon = $this->fetch_remote_icon_url();
25381
25382 // Fetch icon from WordPress.org.
25383 if ( empty( $icon ) && $this->is_plugin() && $this->is_org_repo_compliant() ) {
25384 if ( ! function_exists( 'plugins_api' ) ) {
25385 require_once ABSPATH . 'wp-admin/includes/plugin-install.php';
25386 }
25387
25388 $plugin_information = plugins_api( 'plugin_information', array(
25389 'slug' => $this->_slug,
25390 'fields' => array(
25391 'sections' => false,
25392 'tags' => false,
25393 'icons' => true
25394 )
25395 ) );
25396
25397 if (
25398 ! is_wp_error( $plugin_information )
25399 && isset( $plugin_information->icons )
25400 && ! empty( $plugin_information->icons )
25401 ) {
25402 /**
25403 * Get the smallest icon.
25404 *
25405 * @author Leo Fajardo (@leorw)
25406 * @since 1.2.2
25407 */
25408 $icon = end( $plugin_information->icons );
25409 }
25410 }
25411
25412 if ( ! empty( $icon ) ) {
25413 if ( 0 !== strpos( $icon, 'http' ) ) {
25414 $icon = 'http:' . $icon;
25415 }
25416
25417 /**
25418 * Get a clean file extension, e.g.: "jpg" and not "jpg?rev=1305765".
25419 *
25420 * @author Leo Fajardo (@leorw)
25421 * @since 1.2.2
25422 */
25423 $ext = pathinfo( strtok( $icon, '?' ), PATHINFO_EXTENSION );
25424
25425 $local_path = fs_normalize_path( "{$img_dir}/{$this->_slug}.{$ext}" );
25426
25427 // Try to download the icon.
25428 $icon_found = fs_download_image( $icon, $local_path );
25429 }
25430 }
25431
25432 if ( ! $icon_found ) {
25433 // No icons found, fallback to default icon.
25434 if ( $have_write_permissions ) {
25435 // If have write permissions, copy default icon.
25436 copy( fs_normalize_path( $img_dir . "/{$this->_module_type}-icon.png" ), $local_path );
25437 } else {
25438 // If doesn't have write permissions, use default icon path.
25439 $local_path = fs_normalize_path( $img_dir . "/{$this->_module_type}-icon.png" );
25440 }
25441 }
25442
25443 $icons = array( $local_path );
25444 }
25445 }
25446 }
25447
25448 $icon_dir = dirname( $icons[0] );
25449
25450 return fs_img_url( substr( $icons[0], strlen( $icon_dir ) ), $icon_dir );
25451 }
25452
25453 /**
25454 * Fetch module's extended info.
25455 *
25456 * @author Vova Feldman (@svovaf)
25457 * @since 2.0.0
25458 *
25459 * @return object|mixed
25460 */
25461 private function fetch_module_info() {
25462 return $this->get_api_plugin_scope()->get( 'info.json', false, WP_FS__TIME_WEEK_IN_SEC );
25463 }
25464
25465 /**
25466 * Fetch module's remote icon URL.
25467 *
25468 * @author Vova Feldman (@svovaf)
25469 * @since 2.0.0
25470 *
25471 * @return string
25472 */
25473 function fetch_remote_icon_url() {
25474 $info = $this->fetch_module_info();
25475
25476 return ( $this->is_api_result_object( $info, 'icon' ) && is_string( $info->icon ) ) ?
25477 $info->icon :
25478 '';
25479 }
25480
25481 #--------------------------------------------------------------------------------
25482 #region GDPR
25483 #--------------------------------------------------------------------------------
25484
25485 /**
25486 * @author Leo Fajardo (@leorw)
25487 * @since 2.1.0
25488 *
25489 * @param array $user_plugins
25490 *
25491 * @return string
25492 */
25493 private function get_gdpr_admin_notice_string( $user_plugins ) {
25494 $this->_logger->entrance();
25495
25496 $addons = self::get_all_addons();
25497
25498 foreach ( $user_plugins as $user_plugin ) {
25499 $has_addons = isset( $addons[ $user_plugin->id ] );
25500
25501 if ( WP_FS__MODULE_TYPE_PLUGIN === $user_plugin->type && ! $has_addons ) {
25502 if ( $this->_module_id == $user_plugin->id ) {
25503 $addons = $this->get_addons();
25504 $has_addons = ( ! empty( $addons ) );
25505 } else {
25506 $plugin_api = FS_Api::instance(
25507 $user_plugin->id,
25508 'plugin',
25509 $user_plugin->id,
25510 $user_plugin->public_key,
25511 ! $user_plugin->is_live,
25512 false,
25513 $this->get_sdk_version()
25514 );
25515
25516 $addons_result = $plugin_api->get( '/addons.json?enriched=true', true );
25517
25518 if ( $this->is_api_result_object( $addons_result, 'plugins' ) &&
25519 is_array( $addons_result->plugins ) &&
25520 ! empty( $addons_result->plugins )
25521 ) {
25522 $has_addons = true;
25523 }
25524 }
25525 }
25526
25527 $user_plugin->has_addons = $has_addons;
25528 }
25529
25530 $is_single_parent_product = ( 1 === count( $user_plugins ) );
25531
25532 $multiple_products_text = '';
25533
25534 if ( $is_single_parent_product ) {
25535 $single_parent_product = reset( $user_plugins );
25536
25537 $thank_you = sprintf(
25538 "<span data-plugin-id='%d'>%s</span>",
25539 $single_parent_product->id,
25540 sprintf(
25541 $single_parent_product->has_addons ?
25542 $this->get_text_inline( 'Thank you so much for using %s and its add-ons!', 'thank-you-for-using-product-and-its-addons' ) :
25543 $this->get_text_inline( 'Thank you so much for using %s!', 'thank-you-for-using-product' ),
25544 sprintf('<b><i>%s</i></b>', $single_parent_product->title)
25545 )
25546 );
25547
25548 $already_opted_in = sprintf(
25549 $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' ),
25550 ( WP_FS__MODULE_TYPE_THEME === $single_parent_product->type ) ? WP_FS__MODULE_TYPE_THEME : WP_FS__MODULE_TYPE_PLUGIN
25551 );
25552 } else {
25553 $thank_you = $this->get_text_inline( 'Thank you so much for using our products!', 'thank-you-for-using-products' );
25554 $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' );
25555
25556 $products_and_add_ons = '';
25557 foreach ( $user_plugins as $user_plugin ) {
25558 if ( ! empty( $products_and_add_ons ) ) {
25559 $products_and_add_ons .= ', ';
25560 }
25561
25562 if ( ! $user_plugin->has_addons ) {
25563 $products_and_add_ons .= sprintf(
25564 "<span data-plugin-id='%d'>%s</span>",
25565 $user_plugin->id,
25566 $user_plugin->title
25567 );
25568 } else {
25569 $products_and_add_ons .= sprintf(
25570 "<span data-plugin-id='%d'>%s</span>",
25571 $user_plugin->id,
25572 sprintf(
25573 $this->get_text_inline( '%s and its add-ons', 'product-and-its-addons' ),
25574 $user_plugin->title
25575 )
25576 );
25577 }
25578 }
25579
25580 $multiple_products_text = sprintf(
25581 "<small class='products'><strong>%s:</strong> %s</small>",
25582 $this->get_text_inline( 'Products', 'products' ),
25583 $products_and_add_ons
25584 );
25585 }
25586
25587 $actions = sprintf(
25588 '<ul><li>%s<span class="action-description"> - %s</span></li><li>%s<span class="action-description"> - %s</span></li></ul>',
25589 sprintf('<button class="button button-primary allow-marketing">%s</button>', $this->get_text_inline( 'Yes', 'yes' ) ),
25590 $this->get_text_inline( 'send me security & feature updates, educational content and offers.', 'send-updates' ),
25591 sprintf('<button class="button button-secondary">%s</button>', $this->get_text_inline( 'No', 'no' ) ),
25592 sprintf(
25593 $this->get_text_inline( 'do %sNOT%s send me security & feature updates, educational content and offers.', 'do-not-send-updates' ),
25594 '<span class="underlined">',
25595 '</span>'
25596 )
25597 );
25598
25599 return sprintf(
25600 '%s %s %s',
25601 $thank_you,
25602 $already_opted_in,
25603 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>' ) .
25604 '<br><br>' .
25605 '<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>' .
25606 $actions .
25607 ( $is_single_parent_product ? '' : $multiple_products_text )
25608 );
25609 }
25610
25611 /**
25612 * This method is called for opted-in users to fetch the is_marketing_allowed flag of the user for all the
25613 * plugins and themes they've opted in to.
25614 *
25615 * @author Leo Fajardo (@leorw)
25616 * @since 2.1.0
25617 *
25618 * @param string $user_email
25619 * @param string $license_key
25620 * @param array $plugin_ids
25621 * @param string|null $license_key
25622 *
25623 * @return array|false
25624 */
25625 private function fetch_user_marketing_flag_status_by_plugins( $user_email, $license_key, $plugin_ids ) {
25626 $request = array(
25627 'method' => 'POST',
25628 'body' => array(),
25629 'timeout' => WP_FS__DEBUG_SDK ? 60 : 30,
25630 );
25631
25632 if ( is_string( $user_email ) ) {
25633 $request['body']['email'] = $user_email;
25634 } else {
25635 $request['body']['license_key'] = $license_key;
25636 }
25637
25638 $result = array();
25639
25640 $url = WP_FS__ADDRESS . '/action/service/user_plugin/';
25641 $total_plugin_ids = count( $plugin_ids );
25642
25643 $plugin_ids_count_per_request = 10;
25644 for ( $i = 1; $i <= $total_plugin_ids; $i += $plugin_ids_count_per_request ) {
25645 $plugin_ids_set = array_slice( $plugin_ids, $i - 1, $plugin_ids_count_per_request );
25646
25647 $request['body']['plugin_ids'] = $plugin_ids_set;
25648
25649 $response = self::safe_remote_post(
25650 $url,
25651 $request,
25652 WP_FS__TIME_24_HOURS_IN_SEC,
25653 WP_FS__TIME_12_HOURS_IN_SEC
25654 );
25655
25656 if ( ! is_wp_error( $response ) ) {
25657 $decoded = is_string( $response['body'] ) ?
25658 json_decode( $response['body'] ) :
25659 null;
25660
25661 if (
25662 !is_object($decoded) ||
25663 !isset($decoded->success) ||
25664 true !== $decoded->success ||
25665 !isset( $decoded->data ) ||
25666 !is_array( $decoded->data )
25667 ) {
25668 return false;
25669 }
25670
25671 $result = array_merge( $result, $decoded->data );
25672 }
25673 }
25674
25675 return $result;
25676 }
25677
25678 /**
25679 * @author Leo Fajardo (@leorw)
25680 * @since 2.1.0
25681 */
25682 function _maybe_show_gdpr_admin_notice() {
25683 if ( ! $this->is_user_in_admin() ) {
25684 return;
25685 }
25686
25687 if ( ! $this->should_handle_gdpr_admin_notice() ) {
25688 return;
25689 }
25690
25691 if ( ! $this->is_user_admin() ) {
25692 return;
25693 }
25694
25695 require_once WP_FS__DIR_INCLUDES . '/class-fs-user-lock.php';
25696
25697 $lock = FS_User_Lock::instance();
25698
25699 /**
25700 * Try to acquire a 60-sec lock based on the WP user and thread/process ID.
25701 */
25702 if ( ! $lock->try_lock( 60 ) ) {
25703 return;
25704 }
25705
25706 /**
25707 * @var $current_wp_user WP_User
25708 */
25709 $current_wp_user = self::_get_current_wp_user();
25710
25711 /**
25712 * @var FS_User $current_fs_user
25713 */
25714 $current_fs_user = Freemius::_get_user_by_email( $current_wp_user->user_email );
25715
25716 $ten_years_in_sec = 10 * 365 * WP_FS__TIME_24_HOURS_IN_SEC;
25717
25718 if ( ! is_object( $current_fs_user ) ) {
25719 // 10-year lock.
25720 $lock->lock( $ten_years_in_sec );
25721
25722 return;
25723 }
25724
25725 $gdpr = FS_GDPR_Manager::instance();
25726
25727 if ( $gdpr->is_opt_in_notice_shown() ) {
25728 // 30-day lock.
25729 $lock->lock( 30 * WP_FS__TIME_24_HOURS_IN_SEC );
25730
25731 return;
25732 }
25733
25734 if ( ! $gdpr->should_show_opt_in_notice() ) {
25735 // 10-year lock.
25736 $lock->lock( $ten_years_in_sec );
25737
25738 return;
25739 }
25740
25741 $last_time_notice_shown = $gdpr->last_time_notice_was_shown();
25742 $was_notice_shown_before = ( false !== $last_time_notice_shown );
25743
25744 if ( $was_notice_shown_before &&
25745 30 * WP_FS__TIME_24_HOURS_IN_SEC > time() - $last_time_notice_shown
25746 ) {
25747 // If the notice was shown before, show it again after 30 days from the last time it was shown.
25748 return;
25749 }
25750
25751 /**
25752 * Find all plugin IDs that were installed by the current admin.
25753 */
25754 $plugin_ids_map = self::get_user_opted_in_module_ids_map( $current_fs_user->id );
25755
25756 if ( empty( $plugin_ids_map )) {
25757 $lock->lock( $ten_years_in_sec );
25758
25759 return;
25760 }
25761
25762 $user_plugins = $this->fetch_user_marketing_flag_status_by_plugins(
25763 $current_fs_user->email,
25764 null,
25765 array_keys( $plugin_ids_map )
25766 );
25767
25768 if ( empty( $user_plugins ) ) {
25769 $lock->lock(
25770 is_array($user_plugins) ?
25771 $ten_years_in_sec :
25772 // Lock for 24-hours on errors.
25773 WP_FS__TIME_24_HOURS_IN_SEC
25774 );
25775
25776 return;
25777 }
25778
25779 $has_unset_marketing_optin = false;
25780
25781 foreach ( $user_plugins as $user_plugin ) {
25782 if ( true == $user_plugin->is_marketing_allowed ) {
25783 unset( $plugin_ids_map[ $user_plugin->plugin_id ] );
25784 }
25785
25786 if ( ! $has_unset_marketing_optin && is_null( $user_plugin->is_marketing_allowed ) ) {
25787 $has_unset_marketing_optin = true;
25788 }
25789 }
25790
25791 if ( empty( $plugin_ids_map ) ||
25792 ( $was_notice_shown_before && ! $has_unset_marketing_optin )
25793 ) {
25794 $lock->lock( $ten_years_in_sec );
25795
25796 return;
25797 }
25798
25799 $modules = array_merge(
25800 array_values( self::maybe_get_entities_account_option( 'plugins', array() ) ),
25801 array_values( self::maybe_get_entities_account_option( 'themes', array() ) )
25802 );
25803
25804 foreach ( $modules as $module ) {
25805 if ( ! FS_Plugin::is_valid_id( $module->parent_plugin_id ) && isset( $plugin_ids_map[ $module->id ] ) ) {
25806 $plugin_ids_map[ $module->id ] = $module;
25807 }
25808 }
25809
25810 $plugin_title = null;
25811 if ( 1 === count( $plugin_ids_map ) ) {
25812 $module = reset( $plugin_ids_map );
25813 $plugin_title = $module->title;
25814 }
25815
25816 $gdpr->add_opt_in_sticky_notice(
25817 $this->get_gdpr_admin_notice_string( $plugin_ids_map ),
25818 $plugin_title
25819 );
25820
25821 $this->add_gdpr_optin_ajax_handler_and_style();
25822
25823 $gdpr->notice_was_just_shown();
25824
25825 // 30-day lock.
25826 $lock->lock( 30 * WP_FS__TIME_24_HOURS_IN_SEC );
25827 }
25828
25829 /**
25830 * Prevents the GDPR opt-in admin notice from being added if the user has already chosen to allow or not allow
25831 * marketing.
25832 *
25833 * @author Leo Fajardo (@leorw)
25834 * @since 2.1.0
25835 */
25836 private function disable_opt_in_notice_and_lock_user() {
25837 FS_GDPR_Manager::instance()->disable_opt_in_notice();
25838
25839 require_once WP_FS__DIR_INCLUDES . '/class-fs-user-lock.php';
25840
25841 // 10-year lock.
25842 FS_User_Lock::instance()->lock( 10 * 365 * WP_FS__TIME_24_HOURS_IN_SEC );
25843 }
25844
25845 /**
25846 * @author Leo Fajardo (@leorw)
25847 * @since 2.5.4
25848 */
25849 static function _add_api_connectivity_notice_handler_js() {
25850 fs_require_once_template( 'api-connectivity-message-js.php' );
25851 }
25852
25853 /**
25854 * @author Leo Fajardo (@leorw)
25855 * @since 2.1.0
25856 */
25857 function _add_gdpr_optin_js() {
25858 $vars = array( 'id' => $this->_module_id );
25859
25860 fs_require_once_template( 'gdpr-optin-js.php', $vars );
25861 }
25862
25863 /**
25864 * @author Leo Fajardo (@leorw)
25865 * @since 2.1.0
25866 */
25867 function enqueue_gdpr_optin_notice_style() {
25868 fs_enqueue_local_style( 'fs_gdpr_optin_notice', '/admin/gdpr-optin-notice.css' );
25869 }
25870
25871 /**
25872 * @author Leo Fajardo (@leorw)
25873 * @since 2.1.0
25874 */
25875 function _maybe_add_gdpr_optin_ajax_handler() {
25876 $this->add_ajax_action( 'fetch_is_marketing_required_flag_value', array( &$this, '_fetch_is_marketing_required_flag_value_ajax_action' ) );
25877
25878 if ( FS_GDPR_Manager::instance()->is_opt_in_notice_shown() ) {
25879 $this->add_gdpr_optin_ajax_handler_and_style();
25880 }
25881 }
25882
25883 /**
25884 * @author Leo Fajardo (@leorw)
25885 * @since 2.1.0
25886 */
25887 function _fetch_is_marketing_required_flag_value_ajax_action() {
25888 $this->_logger->entrance();
25889
25890 $this->check_ajax_referer( 'fetch_is_marketing_required_flag_value' );
25891
25892 $license_key = fs_request_get_raw( 'license_key' );
25893
25894 if ( empty($license_key) ) {
25895 self::shoot_ajax_failure( $this->get_text_inline( 'License key is empty.', 'empty-license-key' ) );
25896 }
25897
25898 $user_plugins = $this->fetch_user_marketing_flag_status_by_plugins(
25899 null,
25900 $license_key,
25901 array( $this->_module_id )
25902 );
25903
25904 if ( ! is_array( $user_plugins ) ||
25905 empty($user_plugins) ||
25906 !isset($user_plugins[0]->plugin_id) ||
25907 $user_plugins[0]->plugin_id != $this->_module_id
25908 ) {
25909 /**
25910 * If faced an error or if the module ID do not match to the current module, ask for GDPR opt-in.
25911 *
25912 * @author Vova Feldman (@svovaf)
25913 */
25914 self::shoot_ajax_success( array(
25915 'is_marketing_allowed' => null,
25916 'license_owner_id' => null
25917 ) );
25918 }
25919
25920 self::shoot_ajax_success( array(
25921 'is_marketing_allowed' => $user_plugins[0]->is_marketing_allowed,
25922 'license_owner_id' => ( isset( $user_plugins[0]->license_owner_id ) ? $user_plugins[0]->license_owner_id : null )
25923 ) );
25924 }
25925
25926 /**
25927 * @author Leo Fajardo (@leorw)
25928 * @since 2.3.2
25929 *
25930 * @param number[] $install_ids
25931 *
25932 * @return array {
25933 * An array of objects containing the installs' licenses owners data.
25934 *
25935 * @property number $id User ID.
25936 * @property string $email User email (can be masked email).
25937 * }
25938 */
25939 private function fetch_installs_licenses_owners_data( $install_ids ) {
25940 $this->_logger->entrance();
25941
25942 $response = $this->get_api_user_scope()->get(
25943 '/licenses_owners.json?install_ids=' . implode( ',', $install_ids )
25944 );
25945
25946 $license_owners = array();
25947
25948 if ( $this->is_api_result_object( $response, 'owners' ) ) {
25949 $license_owners = $response->owners;
25950 }
25951
25952 return $license_owners;
25953 }
25954
25955 /**
25956 * @author Leo Fajardo (@leorw)
25957 * @since 2.1.0
25958 */
25959 private function add_gdpr_optin_ajax_handler_and_style() {
25960 // Add GDPR action AJAX callback.
25961 $this->add_ajax_action( 'gdpr_optin_action', array( &$this, '_gdpr_optin_ajax_action' ) );
25962
25963 add_action( 'admin_footer', array( &$this, '_add_gdpr_optin_js' ) );
25964 add_action( 'admin_enqueue_scripts', array( &$this, 'enqueue_gdpr_optin_notice_style' ) );
25965 }
25966
25967 /**
25968 * @author Leo Fajardo (@leorw)
25969 * @since 2.1.0
25970 */
25971 function _gdpr_optin_ajax_action() {
25972 $this->_logger->entrance();
25973
25974 $this->check_ajax_referer( 'gdpr_optin_action' );
25975
25976 if ( ! fs_request_has( 'is_marketing_allowed' ) || ! fs_request_has( 'plugin_ids' ) ) {
25977 self::shoot_ajax_failure();
25978 }
25979
25980 $current_wp_user = self::_get_current_wp_user();
25981
25982 $plugin_ids = fs_request_get( 'plugin_ids', array() );
25983 if ( ! is_array( $plugin_ids ) || empty( $plugin_ids ) ) {
25984 self::shoot_ajax_failure();
25985 }
25986
25987 $modules = array_merge(
25988 array_values( self::maybe_get_entities_account_option( 'plugins', array() ) ),
25989 array_values( self::maybe_get_entities_account_option( 'themes', array() ) )
25990 );
25991
25992 foreach ( $modules as $key => $module ) {
25993 if ( ! in_array( $module->id, $plugin_ids ) ) {
25994 unset( $modules[ $key ] );
25995 }
25996 }
25997
25998 if ( empty( $modules ) ) {
25999 self::shoot_ajax_failure();
26000 }
26001
26002 $user_api = $this->get_api_user_scope_by_user( Freemius::_get_user_by_email( $current_wp_user->user_email ) );
26003
26004 foreach ( $modules as $module ) {
26005 $user_api->call( "?plugin_id={$module->id}", 'put', array(
26006 'is_marketing_allowed' => ( true == fs_request_get_bool( 'is_marketing_allowed' ) )
26007 ) );
26008 }
26009
26010 FS_GDPR_Manager::instance()->remove_opt_in_notice();
26011
26012 require_once WP_FS__DIR_INCLUDES . '/class-fs-user-lock.php';
26013
26014 // 10-year lock.
26015 FS_User_Lock::instance()->lock( 10 * 365 * WP_FS__TIME_24_HOURS_IN_SEC );
26016
26017 self::shoot_ajax_success();
26018 }
26019
26020 /**
26021 * 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.
26022 *
26023 * @author Vova Feldman (@svovaf)
26024 * @since 2.1.0
26025 *
26026 * @return bool
26027 */
26028 private function should_handle_gdpr_admin_notice() {
26029 return $this->apply_filters(
26030 'handle_gdpr_admin_notice',
26031 // Default to false.
26032 false
26033 );
26034 }
26035
26036 #endregion
26037
26038 #----------------------------------------------------------------------------------
26039 #region Marketing
26040 #----------------------------------------------------------------------------------
26041
26042 /**
26043 * Check if current user purchased any other plugins before.
26044 *
26045 * @author Vova Feldman (@svovaf)
26046 * @since 1.0.9
26047 *
26048 * @return bool
26049 */
26050 function has_purchased_before() {
26051 // TODO: Implement has_purchased_before() method.
26052 throw new Exception( 'not implemented' );
26053 }
26054
26055 /**
26056 * Check if current user classified as an agency.
26057 *
26058 * @author Vova Feldman (@svovaf)
26059 * @since 1.0.9
26060 *
26061 * @return bool
26062 */
26063 function is_agency() {
26064 // TODO: Implement is_agency() method.
26065 throw new Exception( 'not implemented' );
26066 }
26067
26068 /**
26069 * Check if current user classified as a developer.
26070 *
26071 * @author Vova Feldman (@svovaf)
26072 * @since 1.0.9
26073 *
26074 * @return bool
26075 */
26076 function is_developer() {
26077 // TODO: Implement is_developer() method.
26078 throw new Exception( 'not implemented' );
26079 }
26080
26081 /**
26082 * Check if current user classified as a business.
26083 *
26084 * @author Vova Feldman (@svovaf)
26085 * @since 1.0.9
26086 *
26087 * @return bool
26088 */
26089 function is_business() {
26090 // TODO: Implement is_business() method.
26091 throw new Exception( 'not implemented' );
26092 }
26093
26094 #endregion
26095
26096 #----------------------------------------------------------------------------------
26097 #region Helper
26098 #----------------------------------------------------------------------------------
26099
26100 /**
26101 * If running with a secret key, assume it's the developer and show pending plans as well.
26102 *
26103 * @author Vova Feldman (@svovaf)
26104 * @since 2.1.2
26105 *
26106 * @param string $path
26107 *
26108 * @return string
26109 */
26110 function add_show_pending( $path ) {
26111 if ( ! $this->has_secret_key() ) {
26112 return $path;
26113 }
26114
26115 return $path . ( false !== strpos( $path, '?' ) ? '&' : '?' ) . 'show_pending=true';
26116 }
26117
26118 #endregion
26119 }
26120