ninja-forms.php 34.1 KB
Newer Older
1
<?php
Kevin Stover's avatar
Kevin Stover committed
2 3
/*
Plugin Name: Ninja Forms
4
Plugin URI: http://ninjaforms.com/
Kevin Stover's avatar
Kevin Stover committed
5
Description: Ninja Forms is a webform builder with unparalleled ease of use and features.
Eric Windham's avatar
Eric Windham committed
6
Version: 3.3.15
Kevin Stover's avatar
Kevin Stover committed
7
Author: The WP Ninjas
8
Author URI: http://ninjaforms.com
9 10
Text Domain: ninja-forms
Domain Path: /lang/
11

Kevin Stover's avatar
Kevin Stover committed
12
Copyright 2016 WP Ninjas.
Kevin Stover's avatar
Kevin Stover committed
13
*/
Kathy's avatar
Kathy committed
14

15
require_once dirname( __FILE__ ) . '/lib/NF_VersionSwitcher.php';
16
require_once dirname( __FILE__ ) . '/lib/NF_Tracking.php';
17
require_once dirname( __FILE__ ) . '/lib/NF_Conversion.php';
18
require_once dirname( __FILE__ ) . '/lib/NF_ExceptionHandlerJS.php';
19
require_once dirname( __FILE__ ) . '/lib/Conversion/Calculations.php';
Dwarve's avatar
Dwarve committed
20

21
// Services require PHP v5.6+
22
if( version_compare( PHP_VERSION, '5.6', '>=' ) ) {
23 24
  include_once dirname( __FILE__ ) . '/services/bootstrap.php';
}
25

26 27 28 29 30 31
function ninja_forms_three_table_exists(){
    global $wpdb;
    $table_name = $wpdb->prefix . 'nf3_forms';
    return ( $wpdb->get_var("SHOW TABLES LIKE '$table_name'") == $table_name );
}

32
if( get_option( 'ninja_forms_load_deprecated', FALSE ) && ! ( isset( $_POST[ 'nf2to3' ] ) && ( defined( 'DOING_AJAX' ) && DOING_AJAX ) ) ){
33 34 35 36

    include 'deprecated/ninja-forms.php';

    register_activation_hook( __FILE__, 'ninja_forms_activation_deprecated' );
37

38 39
    function ninja_forms_activation_deprecated( $network_wide ){
        include_once 'deprecated/includes/activation.php';
40

41 42 43 44 45
        ninja_forms_activation( $network_wide );
    }

} else {

46
    include_once 'lib/NF_Upgrade.php';
47
    include_once 'lib/NF_AddonChecker.php';
48

49
    include_once plugin_dir_path( __FILE__ ) . 'includes/deprecated.php';
50 51 52 53 54 55 56 57 58 59

    /**
     * Class Ninja_Forms
     */
    final class Ninja_Forms
    {

        /**
         * @since 3.0
         */
Eric Windham's avatar
Eric Windham committed
60
        const VERSION = '3.3.15';
61

62
        const WP_MIN_VERSION = '4.7';
63

64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117
        /**
         * @var Ninja_Forms
         * @since 2.7
         */
        private static $instance;

        /**
         * Plugin Directory
         *
         * @since 3.0
         * @var string $dir
         */
        public static $dir = '';

        /**
         * Plugin URL
         *
         * @since 3.0
         * @var string $url
         */
        public static $url = '';

        /**
         * Admin Menus
         *
         * @since 3.0
         * @var array
         */
        public $menus = array();

        /**
         * AJAX Controllers
         *
         * @since 3.0
         * @var array
         */
        public $controllers = array();

        /**
         * Form Fields
         *
         * @since 3.0
         * @var array
         */
        public $fields = array();

        /**
         * Form Actions
         *
         * @since 3.0
         * @var array
         */
        public $actions = array();

Kyle B. Johnson's avatar
Kyle B. Johnson committed
118 119 120 121 122 123 124 125
        /**
         * Merge Tags
         *
         * @since 3.0
         * @var array
         */
        public $merge_tags = array();

126 127 128 129 130 131 132 133
        /**
         * Metaboxes
         *
         * @since 3.0
         * @var array
         */
        public $metaboxes = array();

134 135 136 137 138 139 140 141 142 143 144 145 146 147
        /**
         * Model Factory
         *
         * @var object
         */
        public $factory = '';

        /**
         * Logger
         *
         * @var string
         */
        protected $_logger = '';

148 149 150 151 152 153 154
        /**
         * Dispatcher
         *
         * @var string
         */
        protected $_dispatcher = '';

155 156 157 158 159
        /**
         * @var NF_Session
         */
        protected $session = '';

160 161 162 163 164
        /**
         * @var NF_Tracking
         */
        public $tracking;

165 166 167 168 169 170 171 172
        /**
         * Plugin Settings
         *
         * @since 3.0
         * @var array
         */
        protected $settings = array();

173 174
        protected $requests = array();

175 176
        protected $processes = array();

177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193
        /**
         * Main Ninja_Forms Instance
         *
         * Insures that only one instance of Ninja_Forms exists in memory at any one
         * time. Also prevents needing to define globals all over the place.
         *
         * @since 2.7
         * @static
         * @staticvar array $instance
         * @return Ninja_Forms Highlander Instance
         */
        public static function instance()
        {
            if ( ! isset( self::$instance ) && ! ( self::$instance instanceof Ninja_Forms ) ) {
                self::$instance = new Ninja_Forms;

                self::$dir = plugin_dir_path( __FILE__ );
194 195

                // Define old constants for backwards compatibility.
196 197
                if( ! defined( 'NF_PLUGIN_DIR' ) ){
                    define( 'NF_PLUGIN_DIR', self::$dir );
198
                    define( 'NINJA_FORMS_DIR', self::$dir . 'deprecated' );
199 200 201 202 203 204 205
                }

                self::$url = plugin_dir_url( __FILE__ );
                if( ! defined( 'NF_PLUGIN_URL' ) ){
                    define( 'NF_PLUGIN_URL', self::$url );
                }

206
                $saved_version = get_option( 'ninja_forms_version' );
207 208 209 210 211
                // If this is a fresh install... (The version has never been saved.)
                if ( ! $saved_version ) {
                    // Assume we have clean data.
                    update_option( 'ninja_forms_data_is_clean', 'true' );
                }
212 213 214
                // If we have a recorded version...
                // AND that version is less than our current version...
                if ( $saved_version && version_compare( $saved_version, self::VERSION, '<' ) ) {
215 216 217 218 219
                    // *IMPORTANT: Filter to delete old bad data.
                    // Leave this here until at least 3.4.0.
                    if ( version_compare( $saved_version, '3.3.7', '<' ) && version_compare( $saved_version, '3.3.4', '>' ) ) {
                        delete_option( 'nf_sub_expiration' );
                    }
220 221 222 223 224
                    // We just upgraded the plugin.
                    $plugin_upgrade = true;
                } else {
                    $plugin_upgrade = false;
                }
225
                update_option( 'ninja_forms_version', self::VERSION );
226 227
                // If we've not recorded our db version...
                if ( ! get_option( 'ninja_forms_db_version' ) ) {
228 229 230 231 232 233 234 235 236 237
					// If this isn't a fresh install...
					// AND If we're upgrading from a version before 3.3.0...
					if ( $saved_version && version_compare( $saved_version, '3.3.0', '<' ) ) {
                    	// Set it to the baseline (1.0) so that our upgrade process will run properly.
						add_option( 'ninja_forms_db_version', '1.0', '', 'no' );
					}
					else {
						// Set it to 1.1.
						add_option( 'ninja_forms_db_version', '1.1', '', 'no' );
					}
238
                }
239 240 241 242 243 244 245 246 247 248

                /*
                 * Register our autoloader
                 */
                spl_autoload_register( array( self::$instance, 'autoloader' ) );

                /*
                 * Admin Menus
                 */
                self::$instance->menus[ 'forms' ]           = new NF_Admin_Menus_Forms();
249
                self::$instance->menus[ 'dashboard' ]       = new NF_Admin_Menus_Dashboard();
250 251 252
                self::$instance->menus[ 'add-new' ]         = new NF_Admin_Menus_AddNew();
                self::$instance->menus[ 'submissions']      = new NF_Admin_Menus_Submissions();
                self::$instance->menus[ 'import-export']    = new NF_Admin_Menus_ImportExport();
Kyle B. Johnson's avatar
Kyle B. Johnson committed
253
                self::$instance->menus[ 'settings' ]        = new NF_Admin_Menus_Settings();
254
                self::$instance->menus[ 'licenses']         = new NF_Admin_Menus_Licenses();
Kyle B. Johnson's avatar
Kyle B. Johnson committed
255 256
                self::$instance->menus[ 'system_status']    = new NF_Admin_Menus_SystemStatus();
                self::$instance->menus[ 'add-ons' ]         = new NF_Admin_Menus_Addons();
257
                self::$instance->menus[ 'divider']          = new NF_Admin_Menus_Divider();
258 259 260 261 262
                self::$instance->menus[ 'mock-data']        = new NF_Admin_Menus_MockData();

                /*
                 * AJAX Controllers
                 */
263
                self::$instance->controllers[ 'form' ]          = new NF_AJAX_Controllers_Form();
264
                self::$instance->controllers[ 'fields' ]    = new NF_AJAX_Controllers_Fields();
Eric Windham's avatar
Eric Windham committed
265
                self::$instance->controllers[ 'batch_process' ] = new NF_AJAX_REST_BatchProcess();
266 267 268
                self::$instance->controllers[ 'preview' ]       = new NF_AJAX_Controllers_Preview();
                self::$instance->controllers[ 'submission' ]    = new NF_AJAX_Controllers_Submission();
                self::$instance->controllers[ 'savedfields' ]   = new NF_AJAX_Controllers_SavedFields();
Eric Windham's avatar
Eric Windham committed
269
                self::$instance->controllers[ 'deletealldata' ] = new NF_AJAX_Controllers_DeleteAllData();
270
                self::$instance->controllers[ 'jserror' ]       = new NF_AJAX_Controllers_JSError();
271
                self::$instance->controllers[ 'dispatchpoints' ] = new NF_AJAX_Controllers_DispatchPoints();
272

273 274 275 276 277 278
                /*
                 * REST Controllers
                 */
                self::$instance->controllers[ 'REST' ][ 'forms' ] = new NF_AJAX_REST_Forms();
                self::$instance->controllers[ 'REST' ][ 'new-form-templates' ] = new NF_AJAX_REST_NewFormTemplates();

279 280 281 282 283 284
                /*
                 * Async Requests
                 */
                require_once Ninja_Forms::$dir . 'includes/Libraries/BackgroundProcessing/classes/wp-async-request.php';
                self::$instance->requests[ 'delete-field' ] = new NF_AJAX_Requests_DeleteField();

285 286 287 288 289 290
                /*
                 * Background Processes
                 */
                require_once Ninja_Forms::$dir . 'includes/Libraries/BackgroundProcessing/wp-background-processing.php';
                self::$instance->requests[ 'update-fields' ] = new NF_AJAX_Processes_UpdateFields();

291

292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312
                /*
                 * WP-CLI Commands
                 */
                if( class_exists( 'WP_CLI_Command' ) ) {
                    WP_CLI::add_command('ninja-forms', 'NF_WPCLI_NinjaFormsCommand');
                }

                /*
                 * Preview Page
                 */
                self::$instance->preview = new NF_Display_Preview();

                /*
                 * Shortcodes
                 */
                self::$instance->shortcodes = new NF_Display_Shortcodes();

                /*
                 * Submission CPT
                 */
                new NF_Admin_CPT_Submission();
313 314
                new NF_Admin_CPT_DownloadAllSubmissions();
                require_once Ninja_Forms::$dir . 'lib/StepProcessing/menu.php';
315

KR Moorhouse's avatar
KR Moorhouse committed
316 317 318 319
                /*
                 * Submission Metabox
                 */
                new NF_Admin_Metaboxes_Calculations();
320

321 322 323 324 325
                /*
                 * User data requests ( GDPR actions )
                 */
                new NF_Admin_UserDataRequests();

326 327 328 329 330
                /*
                 * Logger
                 */
                self::$instance->_logger = new NF_Database_Logger();

331 332 333 334 335
                /*
                 * Dispatcher
                 */
                self::$instance->_dispatcher = new NF_Dispatcher();

336 337 338
                /*
                 * Merge Tags
                 */
Kevin Stover's avatar
Kevin Stover committed
339
                self::$instance->merge_tags[ 'wp' ] = new NF_MergeTags_WP();
340 341
                self::$instance->merge_tags[ 'fields' ] = new NF_MergeTags_Fields();
                self::$instance->merge_tags[ 'calcs' ] = new NF_MergeTags_Calcs();
Kyle B. Johnson's avatar
Kyle B. Johnson committed
342
                self::$instance->merge_tags[ 'form' ] = new NF_MergeTags_Form();
343
                self::$instance->merge_tags[ 'other' ] = new NF_MergeTags_Other();
Kevin Stover's avatar
Kevin Stover committed
344
                self::$instance->merge_tags[ 'deprecated' ] = new NF_MergeTags_Deprecated();
345 346 347 348 349 350 351 352 353 354 355 356 357 358

                /*
                 * Add Form Modal
                 */
                self::$instance->add_form_modal = new NF_Admin_AddFormModal();

                /*
                 * EOS Parser
                 */
                self::$instance->_eos[ 'parser' ] = require_once 'includes/Libraries/EOS/Parser.php';

                /*
                 * Plugin Settings
                 */
359
                self::$instance->settings = apply_filters( 'ninja_forms_settings', get_option( 'ninja_forms_settings' ) );
360 361 362 363 364 365

                /*
                 * Admin Notices System
                 */
                self::$instance->notices = new NF_Admin_Notices();

Kyle B. Johnson's avatar
Kyle B. Johnson committed
366 367
                self::$instance->widgets[] = new NF_Widget();

368 369 370 371 372
                /*
                 * Gutenberg
                 */
                self::$instance->gutenblock = new NF_FormBlock();

373 374 375 376 377
                /*
                 * Opt-In Tracking
                 */
                self::$instance->tracking = new NF_Tracking();

378

379
                self::$instance->submission_expiration_cron = new NF_Database_SubmissionExpirationCron();
380

381 382
                /*
                 * JS Exception Handler
383 384
                 *
                 * TODO: Review PR#2492 for improvements.
385
                 */
386
                // self::$instance->exception_handler_js = new NF_ExceptionHandlerJS();
387

388 389 390 391 392 393
                /*
                 * Activation Hook
                 * TODO: Move to a permanent home.
                 */
                register_activation_hook( __FILE__, array( self::$instance, 'activation' ) );

394
                self::$instance->metaboxes[ 'append-form' ] = new NF_Admin_Metaboxes_AppendAForm();
395 396 397 398 399 400 401 402 403

                /*
                 * Require EDD auto-update file
                 */
                if( ! class_exists( 'EDD_SL_Plugin_Updater' ) ) {
                    // Load our custom updater if it doesn't already exist
                    require_once( self::$dir . 'includes/Integrations/EDD/EDD_SL_Plugin_Updater.php');
                }
                require_once self::$dir . 'includes/Integrations/EDD/class-extension-updater.php';
404 405 406 407 408 409
                
                // If Ninja Forms was just upgraded...
                if ( $plugin_upgrade ) {
                    // Ensure all of our tables have been defined.
                    $migrations = new NF_Database_Migrations();
                    $migrations->migrate();
410 411 412 413 414 415 416
                    // If our db version is below 1.1...
                    if ( version_compare( get_option( 'ninja_forms_db_version' ), '1.1', '<' ) ) {
                        // Do our stage 1 updates.
                        $migrations->do_stage_one();
                        // Update our db version.
                        update_option( 'ninja_forms_db_version', '1.1' );
                    }
417 418 419 420 421 422 423 424 425 426 427 428 429 430
					// Fix for legacy versions that upgraded without a set DB version.
					// If our version is exactly 1.1...
					if ( version_compare( get_option( 'ninja_forms_db_version' ), '1.1', '==' ) ) {
						global $wpdb;
						// Fetch the form_title column from the fields table.
						$sql = "SHOW FULL COLUMNS FROM `{$wpdb->prefix}nf3_forms` WHERE Field = 'form_title'";
						$result = $wpdb->get_results( $sql, 'ARRAY_A' );
						// If we didn't get a result...
						if ( empty( $result ) ) {
							// Do our stage 1 updates, even though they should have already run.
							$migrations->do_stage_one();
						}
					}
					
431
                }
432 433 434 435 436 437
            }

            add_action( 'admin_notices', array( self::$instance, 'admin_notices' ) );

            add_action( 'plugins_loaded', array( self::$instance, 'plugins_loaded' ) );

438 439
            add_action( 'ninja_forms_available_actions', array( self::$instance, 'scrub_available_actions' ) );

440 441 442
            add_action( 'init', array( self::$instance, 'init' ), 5 );
            add_action( 'admin_init', array( self::$instance, 'admin_init' ), 5 );

Kenny Hall's avatar
Kenny Hall committed
443
            // Checks php version and..
Kenny Hall's avatar
Kenny Hall committed
444
            if( PHP_VERSION < 5.6 ) {
Kenny Hall's avatar
Kenny Hall committed
445
                // Pulls in the whip notice if the user is.
446 447
                add_action( 'admin_init', array( self::$instance, 'nf_whip_notice' ) );
            }
448 449
            
            add_action( 'admin_init', array( self::$instance, 'nf_do_telemetry' ) );
450
            add_action( 'admin_init', array( self::$instance, 'nf_plugin_add_suggested_privacy_content' ), 20 );
451

452 453 454
            return self::$instance;
        }

455 456 457 458 459 460 461 462
        public function init()
        {
            do_action( 'nf_init', self::$instance );
        }

        public function admin_init()
        {
            do_action( 'nf_admin_init', self::$instance );
463 464 465
            if ( isset ( $_GET[ 'nf-upgrade' ] ) && 'complete' == $_GET[ 'nf-upgrade' ] ) {
                Ninja_Forms()->dispatcher()->send( 'upgrade' );
            }
466 467

            add_filter( 'ninja_forms_dashboard_menu_items', array( $this, 'maybe_hide_dashboard_items' ) );
468 469 470 471 472 473
            
            // If we don't have clean data...
            if ( ! get_option( 'ninja_forms_data_is_clean' ) ) {
                // Register a new notice.
                add_filter( 'ninja_forms_admin_notices', array( $this, 'data_cleanup_notice' ) );
            }
474
        }
475

476 477 478 479
	    /**
	     * Privacy policy suggested content for Ninja Forms
	     */
        function nf_plugin_add_suggested_privacy_content() {
480
            if ( ! function_exists( 'wp_add_privacy_policy_content' ) ) return;
481 482 483 484 485 486 487
			$content = $this->plugin_get_default_privacy_content();
	        wp_add_privacy_policy_content(
	        	__( 'Ninja Forms' ),
		        wp_kses_post( wpautop( $content, false) ) );

        }

488

489 490 491 492 493 494 495 496 497 498 499
	    /**
	     * Return the default suggested privacy policy content.
	     *
	     * @return string The default policy content.
	     */
	    function plugin_get_default_privacy_content() {
		    return
			    '<h2>' . __( 'Ninja Forms allows you to collect personal information' ) . '</h2>' .
			    '<p>' . __( 'If you are using Ninja Forms to collect personal information, you should consult a legal professional for your use case.' ) . '</p>';
	    }

Kenny Hall's avatar
Kenny Hall committed
500 501 502 503 504 505 506
        /**
         * NF Whip Notice
         * If the user is on a version below PHP 5.6 then we get an instance of the
         * NF Whip class which will add a non-dismissible admin notice.
         *
         * @return NF_Whip
         */
507 508 509 510 511
        public function nf_whip_notice()
        {
            require_once self::$dir . '/includes/Libraries/Whip/NF_Whip.php';
            return new NF_Whip();
        }
512 513 514 515 516
        
        /**
         * Function to launch our various telemetry calls on admin_init.
         */
        public function nf_do_telemetry() {
517 518 519
            if ( ! has_filter( 'ninja_forms_settings_licenses_addons' ) && ( ! Ninja_Forms()->tracking->is_opted_in() || Ninja_Forms()->tracking->is_opted_out() ) ) {
                return false;
            }
520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537
            global $wpdb;
            // If we've not already sent table collation...
            if ( ! get_option( 'nf_tel_collate' ) ) {
                $collate = array();
                // Get the collation of the wp_options table.
                $sql = "SHOW FULL COLUMNS FROM `" . $wpdb->prefix . "options` WHERE Field = 'option_value'";
                $result = $wpdb->get_results( $sql, 'ARRAY_A' );
                $collate[ 'cache' ] = $result[ 0 ][ 'Collation' ];
                // Get the collation of the nf3_forms table.
                $sql = "SHOW FULL COLUMNS FROM `" . $wpdb->prefix . "nf3_forms` WHERE Field = 'title'";
                $result = $wpdb->get_results( $sql, 'ARRAY_A' );
                $collate[ 'forms' ] = $result[ 0 ][ 'Collation' ];
                // Send our data to api.ninjaforms.com.
                Ninja_Forms()->dispatcher()->send( 'table_collate', $collate );
                // Record an option so that we don't run this again.
                add_option( 'nf_tel_collate', '1', '', 'no' );
            }
        }
538

539 540 541 542 543 544
        public function maybe_hide_dashboard_items( $items )
        {
            $disable_marketing = false;
            if ( apply_filters( 'ninja_forms_disable_marketing', $disable_marketing ) ) {
                unset(
                    $items[ 'apps' ],
545 546
                    $items[ 'memberships' ],
                    $items[ 'services' ]
547 548 549
                );
            }
            return $items;
550 551
        }

552 553 554 555 556 557 558 559 560
        public function scrub_available_actions( $actions )
        {
            foreach( $actions as $key => $action ){
                if ( ! is_plugin_active( $action[ 'plugin_path' ] ) )  continue;
                unset( $actions[ $key ] );
            }
            return $actions;
        }

561 562 563 564 565 566 567 568 569
        public function admin_notices()
        {
            // Notices filter and run the notices function.
            $admin_notices = Ninja_Forms()->config( 'AdminNotices' );
            self::$instance->notices->admin_notice( apply_filters( 'nf_admin_notices', $admin_notices ) );
        }

        public function plugins_loaded()
        {
570 571
            load_plugin_textdomain( 'ninja-forms', false, basename( dirname( __FILE__ ) ) . '/lang' );

572 573 574 575 576
            /*
             * Field Class Registration
             */
            self::$instance->fields = apply_filters( 'ninja_forms_register_fields', self::load_classes( 'Fields' ) );

577 578 579 580 581 582 583 584 585
            if( ! apply_filters( 'ninja_forms_enable_credit_card_fields', false ) ){
                unset( self::$instance->fields[ 'creditcard' ] );
                unset( self::$instance->fields[ 'creditcardcvc' ] );
                unset( self::$instance->fields[ 'creditcardexpiration' ] );
                unset( self::$instance->fields[ 'creditcardfullname' ] );
                unset( self::$instance->fields[ 'creditcardnumber' ] );
                unset( self::$instance->fields[ 'creditcardzip' ] );
            }

586 587 588 589 590
            /*
             * Form Action Registration
             */
            self::$instance->actions = apply_filters( 'ninja_forms_register_actions', self::load_classes( 'Actions' ) );

Kyle B. Johnson's avatar
Kyle B. Johnson committed
591 592 593 594 595
            /*
             * Merge Tag Registration
             */
            self::$instance->merge_tags = apply_filters( 'ninja_forms_register_merge_tags', self::$instance->merge_tags );

596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647
            /*
             * It's Ninja Time: Hook for Extensions
             */
            do_action( 'ninja_forms_loaded' );

        }

        /**
         * Autoloader
         *
         * Autoload Ninja Forms classes
         *
         * @param $class_name
         */
        public function autoloader( $class_name )
        {
            if( class_exists( $class_name ) ) return;

            /* Ninja Forms Prefix */
            if (false !== strpos($class_name, 'NF_')) {
                $class_name = str_replace('NF_', '', $class_name);
                $classes_dir = realpath(plugin_dir_path(__FILE__)) . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR;
                $class_file = str_replace('_', DIRECTORY_SEPARATOR, $class_name) . '.php';
                if (file_exists($classes_dir . $class_file)) {
                    require_once $classes_dir . $class_file;
                }
            }

            /* WP Ninjas Prefix */
            if (false !== strpos($class_name, 'WPN_')) {
                $class_name = str_replace('WPN_', '', $class_name);
                $classes_dir = realpath(plugin_dir_path(__FILE__)) . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR;
                $class_file = str_replace('_', DIRECTORY_SEPARATOR, $class_name) . '.php';
                if (file_exists($classes_dir . $class_file)) {
                    require_once $classes_dir . $class_file;
                }
            }
        }

        /*
         * PUBLIC API WRAPPERS
         */

        /**
         * Form Model Factory Wrapper
         *
         * @param $id
         * @return NF_Abstracts_ModelFactory
         */
        public function form( $id = '' )
        {
            global $wpdb;
648

Kevin Stover's avatar
Kevin Stover committed
649 650 651 652
            static $forms;
            if ( isset ( $forms[ $id ] ) ) {
                return $forms[ $id ];
            }
653

Kevin Stover's avatar
Kevin Stover committed
654 655
            $forms[ $id ] = new NF_Abstracts_ModelFactory( $wpdb, $id );
            return $forms[ $id ];
656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671
        }

        /**
         * Logger Class Wrapper
         *
         * Example Use:
         * Ninja_Forms()->logger()->log( 'debug', "Hello, {name}!", array( 'name' => 'world' ) );
         * Ninja_Forms()->logger()->debug( "Hello, {name}!", array( 'name' => 'world' ) );
         *
         * @return string
         */
        public function logger()
        {
            return $this->_logger;
        }

672 673 674 675 676
        public function dispatcher()
        {
            return $this->_dispatcher;
        }

677 678
        public function eos()
        {
679
            return new NF_EOS_Parser();
680 681 682 683
        }

        public function session()
        {
684 685 686 687
            if( ! $this->session ){
                $this->session = new NF_Session();
                $this->session->init();
            }
688 689 690
            return $this->session;
        }

691 692 693 694 695 696 697
        public function request( $action )
        {
            if( ! isset( $this->requests[ $action ] ) ) return new NF_AJAX_Requests_NullRequest();

            return $this->requests[ $action ];
        }

698 699 700 701 702 703 704
        public function background_process( $action )
        {
            if( ! isset( $this->requests[ $action ] ) ) return new NF_AJAX_Processes_NullProcess();

            return $this->requests[ $action ];
        }

705 706 707 708 709 710 711 712
	    /**
	     * Get a setting
	     *
	     * @param string     $key
	     * @param bool|false $default
	     * @return bool
	     */
        public function get_setting( $key = '', $default = false )
713
        {
714
            if( empty( $key ) || ! isset( $this->settings[ $key ] ) || empty( $this->settings[ $key ] ) ) return $default;
715 716 717 718

            return $this->settings[ $key ];
        }

719 720 721 722 723
	    /**
	     * Get all the settings
	     *
	     * @return array
	     */
724 725 726 727 728
        public function get_settings()
        {
            return ( is_array( $this->settings ) ) ? $this->settings : array();
        }

729 730 731 732 733 734 735 736
	    /**
	     * Update a setting
	     *
	     * @param string           $key
	     * @param mixed           $value
	     * @param bool|false $defer_update Defer the database update of all settings
	     */
        public function update_setting( $key, $value, $defer_update = false )
737
        {
738 739 740 741
	        $this->settings[ $key ] = $value;
	        if ( ! $defer_update ) {
		        $this->update_settings();
	        }
742 743
        }

744 745 746 747 748
	    /**
	     * Save settings to database
	     *
	     * @param array $settings
	     */
749 750
        public function update_settings( $settings = array() )
        {
751
            if( ! is_array( $this->settings ) ) $this->settings = array();
752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826

            if( $settings && is_array( $settings ) ) {
                $this->settings = array_merge($this->settings, $settings);
            }

            update_option( 'ninja_forms_settings', $this->settings );
        }


        /**
         * Display Wrapper
         *
         * @param $form_id
         */
        public function display( $form_id, $preview = FALSE )
        {
            if( ! $form_id ) return;

            $noscript_message = __( 'Notice: JavaScript is required for this content.', 'ninja-forms' );
            $noscript_message = apply_filters( 'ninja_forms_noscript_message', $noscript_message );

            Ninja_Forms()->template( 'display-noscript-message.html.php', array( 'message' => $noscript_message ) );

            if( ! $preview ) {
                NF_Display_Render::localize($form_id);
            } else {
                NF_Display_Render::localize_preview($form_id);
            }
        }

        /*
         * PRIVATE METHODS
         */

        /**
         * Load Classes from Directory
         *
         * @param string $prefix
         * @return array
         */
        private static function load_classes( $prefix = '' )
        {
            $return = array();

            $subdirectory = str_replace( '_', DIRECTORY_SEPARATOR, str_replace( 'NF_', '', $prefix ) );

            $directory = 'includes/' . $subdirectory;

            foreach (scandir( self::$dir . $directory ) as $path) {

                $path = explode( DIRECTORY_SEPARATOR, str_replace( self::$dir, '', $path ) );
                $filename = str_replace( '.php', '', end( $path ) );

                $class_name = 'NF_' . $prefix . '_' . $filename;

                if( ! class_exists( $class_name ) ) continue;

                $return[ strtolower( $filename ) ] = new $class_name;
            }

            return $return;
        }



        /*
         * STATIC METHODS
         */

        /**
         * Template
         *
         * @param string $file_name
         * @param array $data
         */
827
        public static function template( $file_name = '', array $data = array(), $return = FALSE )
828
        {
829
            if( ! $file_name ) return FALSE;
830 831 832

            extract( $data );

833 834 835 836 837 838 839
            $path = self::$dir . 'includes/Templates/' . $file_name;

            if( ! file_exists( $path ) ) return FALSE;

            if( $return ) return file_get_contents( $path );

            include $path;
840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858
        }

        /**
         * Config
         *
         * @param $file_name
         * @return mixed
         */
        public static function config( $file_name )
        {
            return include self::$dir . 'includes/Config/' . $file_name . '.php';
        }

        /**
         * Activation
         */
        public function activation() {
            $migrations = new NF_Database_Migrations();
            $migrations->migrate();
859

860 861
            if( Ninja_Forms()->form()->get_forms() ) return;

862 863
            // Assume we're on a clean installation.
            update_option( 'ninja_forms_data_is_clean', 'true' );
864 865
            $form = Ninja_Forms::template( 'formtemplate-contactform.nff', array(), TRUE );
            Ninja_Forms()->form()->import_form( $form );
866 867
        }

868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896
        /**
         * Deprecated Notice
         *
         * Example: Ninja_Forms::deprecated_hook( 'ninja_forms_old', '3.0', 'ninja_forms_new', debug_backtrace() );
         *
         * @param $deprecated
         * @param $version
         * @param null $replacement
         * @param null $backtrace
         */
        public static function deprecated_notice( $deprecated, $version, $replacement = null, $backtrace = null )
        {
            do_action( 'ninja_forms_deprecated_call', $deprecated, $replacement, $version );

            $show_errors = current_user_can( 'manage_options' );

            // Allow plugin to filter the output error trigger
            if ( WP_DEBUG && apply_filters( 'ninja_forms_deprecated_function_trigger_error', $show_errors ) ) {
                if ( ! is_null( $replacement ) ) {
                    trigger_error( sprintf( __( '%1$s is <strong>deprecated</strong> since Ninja Forms version %2$s! Use %3$s instead.', 'ninja-forms' ), $deprecated, $version, $replacement ) );
                    // trigger_error(  print_r( $backtrace, 1 ) ); // Limited to previous 1028 characters, but since we only need to move back 1 in stack that should be fine.
                    // Alternatively we could dump this to a file.
                } else {
                    trigger_error( sprintf( __( '%1$s is <strong>deprecated</strong> since Ninja Forms version %2$s.', 'ninja-forms' ), $deprecated, $version ) );
                    // trigger_error( print_r( $backtrace, 1 ) );// Limited to previous 1028 characters, but since we only need to move back 1 in stack that should be fine.
                    // Alternatively we could dump this to a file.
                }
            }
        }
897
        
898 899 900 901 902 903 904 905
        /**
         * Function to register an admin notice if we detect that this installation has "unclean" Ninja Forms data.
         * 
         * @since 3.3.1
         * 
         * @param $notices (Array) Our array of admin notices.
         * @return $notices (Array) Our array of admin notices.
         */
906 907 908
        public function data_cleanup_notice( $notices ) {
            $notices[ 'data_cleanup' ] = array(
                'title' => __( 'Data Cleanup', 'ninja-forms' ),
909
                'msg' => sprintf( __( 'Ninja Forms has detected data on your site leftover from old forms or Ninja Forms versions.%sWe would like to run a quick cleanup process to remove this old data. Your forms will not be impacted by this process, but it may take several minutes to complete.%sPlease %sclick here%s to begin.', 'ninja-forms' ), '<br />', '<br /><br />', '<a href="' . admin_url( 'admin.php?page=ninja-forms&action=cleanup' ) . '">', '</a>' ),
910 911
                'int' => 0,
                'ignore_spam' => true,
912
                'dismiss' => 0
913 914 915
            );
            return $notices;
        }
916

917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939
    } // End Class Ninja_Forms



    /**
     * The main function responsible for returning The Highlander Ninja_Forms
     * Instance to functions everywhere.
     *
     * Use this function like you would a global variable, except without needing
     * to declare the global.
     *
     * Example: <?php $nf = Ninja_Forms(); ?>
     *
     * @since 2.7
     * @return Ninja_Forms Highlander Instance
     */
    function Ninja_Forms()
    {
        return Ninja_Forms::instance();
    }

    Ninja_Forms();

940 941 942 943 944 945
    /*
    |--------------------------------------------------------------------------
    | Uninstall Hook
    |--------------------------------------------------------------------------
    */

Kyle B. Johnson's avatar
Kyle B. Johnson committed
946
    register_uninstall_hook( __FILE__, 'ninja_forms_uninstall' );
947 948

    function ninja_forms_uninstall(){
949

Kyle B. Johnson's avatar
Kyle B. Johnson committed
950
        if( Ninja_Forms()->get_setting( 'delete_on_uninstall' ) ) {
951 952 953
            require_once plugin_dir_path(__FILE__) . '/includes/Database/Migrations.php';
            $migrations = new NF_Database_Migrations();
            $migrations->nuke(TRUE, TRUE);
Kyle Johnson's avatar
Kyle Johnson committed
954
            $migrations->nuke_settings(TRUE, TRUE);
955
            $migrations->nuke_deprecated(TRUE, TRUE);
956 957
        }
    }
958

959
    // Scheduled Action Hook
960 961 962
    function nf_optin_update_environment_vars() {
        /**
         * Send updated environment variables.
963
         */
964
        Ninja_Forms()->dispatcher()->update_environment_vars();
965 966 967 968 969

        /**
         * Make sure that we've reported our opt-in.
         */
        if( get_option( 'ninja_forms_optin_reported', 0 ) ) return;
970

971 972 973
        Ninja_Forms()->dispatcher()->send( 'optin', array( 'send_email' => 1 ) );
        // Debounce opt-in dispatch.
        update_option( 'ninja_forms_optin_reported', 1 );
974
    }
975
    add_action( 'nf_optin_cron', 'nf_optin_update_environment_vars' );
976

977 978
    // Custom Cron Recurrences
    function nf_custom_cron_job_recurrence( $schedules ) {
979 980
        $schedules[ 'nf-monthly' ] = array(
            'display' => __( 'Once per month', 'ninja-forms' ),
981 982 983 984 985
            'interval' => 2678400,
        );
        return $schedules;
    }
    add_filter( 'cron_schedules', 'nf_custom_cron_job_recurrence' );
986

987 988 989 990 991
    // Schedule Cron Job Event
    function nf_optin_send_admin_email_cron_job() {
        if ( ! wp_next_scheduled( 'nf_optin_cron' ) ) {
            wp_schedule_event( current_time( 'timestamp' ), 'nf-monthly', 'nf_optin_cron' );
        }
992
    }
993 994

    add_action( 'wp', 'nf_optin_send_admin_email_cron_job' );
Kyle Johnson's avatar
Kyle Johnson committed
995
}