Passed
Push — master ( e82094...e2c1d0 )
by Brian
06:14 queued 01:44
created
vendor/ayecode/wp-ayecode-ui/includes/class-aui.php 1 patch
Indentation   +227 added lines, -227 removed lines patch added patch discarded remove patch
@@ -1,7 +1,7 @@  discard block
 block discarded – undo
1 1
 <?php
2 2
 
3 3
 if ( ! defined( 'ABSPATH' ) ) {
4
-	exit; // Exit if accessed directly
4
+    exit; // Exit if accessed directly
5 5
 }
6 6
 
7 7
 /**
@@ -11,231 +11,231 @@  discard block
 block discarded – undo
11 11
  */
12 12
 class AUI {
13 13
 
14
-	/**
15
-	 * Holds the class instance.
16
-	 *
17
-	 * @since 1.0.0
18
-	 * @var null
19
-	 */
20
-	private static $instance = null;
21
-
22
-	/**
23
-	 * Holds the current AUI version number.
24
-	 *
25
-	 * @var string $ver The current version number.
26
-	 */
27
-	public static $ver = '0.1.46';
28
-
29
-	public static $options = null;
30
-
31
-	/**
32
-	 * There can be only one.
33
-	 *
34
-	 * @since 1.0.0
35
-	 * @return AUI|null
36
-	 */
37
-	public static function instance() {
38
-		if ( self::$instance == null ) {
39
-			self::$instance = new AUI();
40
-		}
41
-
42
-		return self::$instance;
43
-	}
44
-
45
-	/**
46
-	 * AUI constructor.
47
-	 *
48
-	 * @since 1.0.0
49
-	 */
50
-	private function __construct() {
51
-		if ( function_exists( "__autoload" ) ) {
52
-			spl_autoload_register( "__autoload" );
53
-		}
54
-		spl_autoload_register( array( $this, 'autoload' ) );
55
-
56
-		// load options
57
-		self::$options = get_option('aui_options');
58
-	}
59
-
60
-	/**
61
-	 * Autoload any components on the fly.
62
-	 *
63
-	 * @since 1.0.0
64
-	 *
65
-	 * @param $classname
66
-	 */
67
-	private function autoload( $classname ) {
68
-		$class     = str_replace( '_', '-', strtolower( $classname ) );
69
-		$file_path = trailingslashit( dirname( __FILE__ ) ) . "components/class-" . $class . '.php';
70
-		if ( $file_path && is_readable( $file_path ) ) {
71
-			include_once( $file_path );
72
-		}
73
-	}
74
-
75
-	/**
76
-	 * Get the AUI options.
77
-	 *
78
-	 * @param $option
79
-	 *
80
-	 * @return string|void
81
-	 */
82
-	public function get_option( $option ){
83
-		$result = isset(self::$options[$option]) ? esc_attr(self::$options[$option]) : '';
84
-
85
-		if ( ! $result && $option) {
86
-			if( $option == 'color_primary' ){
87
-				$result = AUI_PRIMARY_COLOR;
88
-			}elseif( $option == 'color_secondary' ){
89
-				$result = AUI_SECONDARY_COLOR;
90
-			}
91
-		}
92
-		return $result;
93
-	}
94
-
95
-	public function render( $items = array() ) {
96
-		$output = '';
97
-
98
-		if ( ! empty( $items ) ) {
99
-			foreach ( $items as $args ) {
100
-				$render = isset( $args['render'] ) ? $args['render'] : '';
101
-				if ( $render && method_exists( __CLASS__, $render ) ) {
102
-					$output .= $this->$render( $args );
103
-				}
104
-			}
105
-		}
106
-
107
-		return $output;
108
-	}
109
-
110
-	/**
111
-	 * Render and return a bootstrap alert component.
112
-	 *
113
-	 * @since 1.0.0
114
-	 *
115
-	 * @param array $args
116
-	 *
117
-	 * @return string The rendered component.
118
-	 */
119
-	public function alert( $args = array() ) {
120
-		return AUI_Component_Alert::get( $args );
121
-	}
122
-
123
-	/**
124
-	 * Render and return a bootstrap input component.
125
-	 *
126
-	 * @since 1.0.0
127
-	 *
128
-	 * @param array $args
129
-	 *
130
-	 * @return string The rendered component.
131
-	 */
132
-	public function input( $args = array() ) {
133
-		return AUI_Component_Input::input( $args );
134
-	}
135
-
136
-	/**
137
-	 * Render and return a bootstrap textarea component.
138
-	 *
139
-	 * @since 1.0.0
140
-	 *
141
-	 * @param array $args
142
-	 *
143
-	 * @return string The rendered component.
144
-	 */
145
-	public function textarea( $args = array() ) {
146
-		return AUI_Component_Input::textarea( $args );
147
-	}
148
-
149
-	/**
150
-	 * Render and return a bootstrap button component.
151
-	 *
152
-	 * @since 1.0.0
153
-	 *
154
-	 * @param array $args
155
-	 *
156
-	 * @return string The rendered component.
157
-	 */
158
-	public function button( $args = array() ) {
159
-		return AUI_Component_Button::get( $args );
160
-	}
161
-
162
-	/**
163
-	 * Render and return a bootstrap button component.
164
-	 *
165
-	 * @since 1.0.0
166
-	 *
167
-	 * @param array $args
168
-	 *
169
-	 * @return string The rendered component.
170
-	 */
171
-	public function badge( $args = array() ) {
172
-		$defaults = array(
173
-			'class' => 'badge badge-primary align-middle',
174
-		);
175
-
176
-		// maybe set type
177
-		if ( empty( $args['href'] ) ) {
178
-			$defaults['type'] = 'badge';
179
-		}
180
-
181
-		/**
182
-		 * Parse incoming $args into an array and merge it with $defaults
183
-		 */
184
-		$args = wp_parse_args( $args, $defaults );
185
-
186
-		return AUI_Component_Button::get( $args );
187
-	}
188
-
189
-	/**
190
-	 * Render and return a bootstrap dropdown component.
191
-	 *
192
-	 * @since 1.0.0
193
-	 *
194
-	 * @param array $args
195
-	 *
196
-	 * @return string The rendered component.
197
-	 */
198
-	public function dropdown( $args = array() ) {
199
-		return AUI_Component_Dropdown::get( $args );
200
-	}
201
-
202
-	/**
203
-	 * Render and return a bootstrap select component.
204
-	 *
205
-	 * @since 1.0.0
206
-	 *
207
-	 * @param array $args
208
-	 *
209
-	 * @return string The rendered component.
210
-	 */
211
-	public function select( $args = array() ) {
212
-		return AUI_Component_Input::select( $args );
213
-	}
214
-
215
-	/**
216
-	 * Render and return a bootstrap radio component.
217
-	 *
218
-	 * @since 1.0.0
219
-	 *
220
-	 * @param array $args
221
-	 *
222
-	 * @return string The rendered component.
223
-	 */
224
-	public function radio( $args = array() ) {
225
-		return AUI_Component_Input::radio( $args );
226
-	}
227
-
228
-	/**
229
-	 * Render and return a bootstrap pagination component.
230
-	 *
231
-	 * @since 1.0.0
232
-	 *
233
-	 * @param array $args
234
-	 *
235
-	 * @return string The rendered component.
236
-	 */
237
-	public function pagination( $args = array() ) {
238
-		return AUI_Component_Pagination::get( $args );
239
-	}
14
+    /**
15
+     * Holds the class instance.
16
+     *
17
+     * @since 1.0.0
18
+     * @var null
19
+     */
20
+    private static $instance = null;
21
+
22
+    /**
23
+     * Holds the current AUI version number.
24
+     *
25
+     * @var string $ver The current version number.
26
+     */
27
+    public static $ver = '0.1.46';
28
+
29
+    public static $options = null;
30
+
31
+    /**
32
+     * There can be only one.
33
+     *
34
+     * @since 1.0.0
35
+     * @return AUI|null
36
+     */
37
+    public static function instance() {
38
+        if ( self::$instance == null ) {
39
+            self::$instance = new AUI();
40
+        }
41
+
42
+        return self::$instance;
43
+    }
44
+
45
+    /**
46
+     * AUI constructor.
47
+     *
48
+     * @since 1.0.0
49
+     */
50
+    private function __construct() {
51
+        if ( function_exists( "__autoload" ) ) {
52
+            spl_autoload_register( "__autoload" );
53
+        }
54
+        spl_autoload_register( array( $this, 'autoload' ) );
55
+
56
+        // load options
57
+        self::$options = get_option('aui_options');
58
+    }
59
+
60
+    /**
61
+     * Autoload any components on the fly.
62
+     *
63
+     * @since 1.0.0
64
+     *
65
+     * @param $classname
66
+     */
67
+    private function autoload( $classname ) {
68
+        $class     = str_replace( '_', '-', strtolower( $classname ) );
69
+        $file_path = trailingslashit( dirname( __FILE__ ) ) . "components/class-" . $class . '.php';
70
+        if ( $file_path && is_readable( $file_path ) ) {
71
+            include_once( $file_path );
72
+        }
73
+    }
74
+
75
+    /**
76
+     * Get the AUI options.
77
+     *
78
+     * @param $option
79
+     *
80
+     * @return string|void
81
+     */
82
+    public function get_option( $option ){
83
+        $result = isset(self::$options[$option]) ? esc_attr(self::$options[$option]) : '';
84
+
85
+        if ( ! $result && $option) {
86
+            if( $option == 'color_primary' ){
87
+                $result = AUI_PRIMARY_COLOR;
88
+            }elseif( $option == 'color_secondary' ){
89
+                $result = AUI_SECONDARY_COLOR;
90
+            }
91
+        }
92
+        return $result;
93
+    }
94
+
95
+    public function render( $items = array() ) {
96
+        $output = '';
97
+
98
+        if ( ! empty( $items ) ) {
99
+            foreach ( $items as $args ) {
100
+                $render = isset( $args['render'] ) ? $args['render'] : '';
101
+                if ( $render && method_exists( __CLASS__, $render ) ) {
102
+                    $output .= $this->$render( $args );
103
+                }
104
+            }
105
+        }
106
+
107
+        return $output;
108
+    }
109
+
110
+    /**
111
+     * Render and return a bootstrap alert component.
112
+     *
113
+     * @since 1.0.0
114
+     *
115
+     * @param array $args
116
+     *
117
+     * @return string The rendered component.
118
+     */
119
+    public function alert( $args = array() ) {
120
+        return AUI_Component_Alert::get( $args );
121
+    }
122
+
123
+    /**
124
+     * Render and return a bootstrap input component.
125
+     *
126
+     * @since 1.0.0
127
+     *
128
+     * @param array $args
129
+     *
130
+     * @return string The rendered component.
131
+     */
132
+    public function input( $args = array() ) {
133
+        return AUI_Component_Input::input( $args );
134
+    }
135
+
136
+    /**
137
+     * Render and return a bootstrap textarea component.
138
+     *
139
+     * @since 1.0.0
140
+     *
141
+     * @param array $args
142
+     *
143
+     * @return string The rendered component.
144
+     */
145
+    public function textarea( $args = array() ) {
146
+        return AUI_Component_Input::textarea( $args );
147
+    }
148
+
149
+    /**
150
+     * Render and return a bootstrap button component.
151
+     *
152
+     * @since 1.0.0
153
+     *
154
+     * @param array $args
155
+     *
156
+     * @return string The rendered component.
157
+     */
158
+    public function button( $args = array() ) {
159
+        return AUI_Component_Button::get( $args );
160
+    }
161
+
162
+    /**
163
+     * Render and return a bootstrap button component.
164
+     *
165
+     * @since 1.0.0
166
+     *
167
+     * @param array $args
168
+     *
169
+     * @return string The rendered component.
170
+     */
171
+    public function badge( $args = array() ) {
172
+        $defaults = array(
173
+            'class' => 'badge badge-primary align-middle',
174
+        );
175
+
176
+        // maybe set type
177
+        if ( empty( $args['href'] ) ) {
178
+            $defaults['type'] = 'badge';
179
+        }
180
+
181
+        /**
182
+         * Parse incoming $args into an array and merge it with $defaults
183
+         */
184
+        $args = wp_parse_args( $args, $defaults );
185
+
186
+        return AUI_Component_Button::get( $args );
187
+    }
188
+
189
+    /**
190
+     * Render and return a bootstrap dropdown component.
191
+     *
192
+     * @since 1.0.0
193
+     *
194
+     * @param array $args
195
+     *
196
+     * @return string The rendered component.
197
+     */
198
+    public function dropdown( $args = array() ) {
199
+        return AUI_Component_Dropdown::get( $args );
200
+    }
201
+
202
+    /**
203
+     * Render and return a bootstrap select component.
204
+     *
205
+     * @since 1.0.0
206
+     *
207
+     * @param array $args
208
+     *
209
+     * @return string The rendered component.
210
+     */
211
+    public function select( $args = array() ) {
212
+        return AUI_Component_Input::select( $args );
213
+    }
214
+
215
+    /**
216
+     * Render and return a bootstrap radio component.
217
+     *
218
+     * @since 1.0.0
219
+     *
220
+     * @param array $args
221
+     *
222
+     * @return string The rendered component.
223
+     */
224
+    public function radio( $args = array() ) {
225
+        return AUI_Component_Input::radio( $args );
226
+    }
227
+
228
+    /**
229
+     * Render and return a bootstrap pagination component.
230
+     *
231
+     * @since 1.0.0
232
+     *
233
+     * @param array $args
234
+     *
235
+     * @return string The rendered component.
236
+     */
237
+    public function pagination( $args = array() ) {
238
+        return AUI_Component_Pagination::get( $args );
239
+    }
240 240
 
241 241
 }
242 242
\ No newline at end of file
Please login to merge, or discard this patch.
vendor/ayecode/wp-ayecode-ui/includes/ayecode-ui-settings.php 1 patch
Indentation   +1099 added lines, -1099 removed lines patch added patch discarded remove patch
@@ -13,7 +13,7 @@  discard block
 block discarded – undo
13 13
  * Bail if we are not in WP.
14 14
  */
15 15
 if ( ! defined( 'ABSPATH' ) ) {
16
-	exit;
16
+    exit;
17 17
 }
18 18
 
19 19
 /**
@@ -21,236 +21,236 @@  discard block
 block discarded – undo
21 21
  */
22 22
 if ( ! class_exists( 'AyeCode_UI_Settings' ) ) {
23 23
 
24
-	/**
25
-	 * A Class to be able to change settings for Font Awesome.
26
-	 *
27
-	 * Class AyeCode_UI_Settings
28
-	 * @ver 1.0.0
29
-	 * @todo decide how to implement textdomain
30
-	 */
31
-	class AyeCode_UI_Settings {
32
-
33
-		/**
34
-		 * Class version version.
35
-		 *
36
-		 * @var string
37
-		 */
38
-		public $version = '0.1.46';
39
-
40
-		/**
41
-		 * Class textdomain.
42
-		 *
43
-		 * @var string
44
-		 */
45
-		public $textdomain = 'aui';
46
-
47
-		/**
48
-		 * Latest version of Bootstrap at time of publish published.
49
-		 *
50
-		 * @var string
51
-		 */
52
-		public $latest = "4.5.3";
53
-
54
-		/**
55
-		 * Current version of select2 being used.
56
-		 *
57
-		 * @var string
58
-		 */
59
-		public $select2_version = "4.0.11";
60
-
61
-		/**
62
-		 * The title.
63
-		 *
64
-		 * @var string
65
-		 */
66
-		public $name = 'AyeCode UI';
67
-
68
-		/**
69
-		 * The relative url to the assets.
70
-		 *
71
-		 * @var string
72
-		 */
73
-		public $url = '';
74
-
75
-		/**
76
-		 * Holds the settings values.
77
-		 *
78
-		 * @var array
79
-		 */
80
-		private $settings;
81
-
82
-		/**
83
-		 * AyeCode_UI_Settings instance.
84
-		 *
85
-		 * @access private
86
-		 * @since  1.0.0
87
-		 * @var    AyeCode_UI_Settings There can be only one!
88
-		 */
89
-		private static $instance = null;
90
-
91
-		/**
92
-		 * Main AyeCode_UI_Settings Instance.
93
-		 *
94
-		 * Ensures only one instance of AyeCode_UI_Settings is loaded or can be loaded.
95
-		 *
96
-		 * @since 1.0.0
97
-		 * @static
98
-		 * @return AyeCode_UI_Settings - Main instance.
99
-		 */
100
-		public static function instance() {
101
-			if ( ! isset( self::$instance ) && ! ( self::$instance instanceof AyeCode_UI_Settings ) ) {
102
-
103
-				self::$instance = new AyeCode_UI_Settings;
104
-
105
-				add_action( 'init', array( self::$instance, 'init' ) ); // set settings
106
-
107
-				if ( is_admin() ) {
108
-					add_action( 'admin_menu', array( self::$instance, 'menu_item' ) );
109
-					add_action( 'admin_init', array( self::$instance, 'register_settings' ) );
110
-
111
-					// Maybe show example page
112
-					add_action( 'template_redirect', array( self::$instance,'maybe_show_examples' ) );
113
-				}
114
-
115
-				add_action( 'customize_register', array( self::$instance, 'customizer_settings' ));
116
-
117
-				do_action( 'ayecode_ui_settings_loaded' );
118
-			}
119
-
120
-			return self::$instance;
121
-		}
122
-
123
-		/**
124
-		 * Setup some constants.
125
-		 */
126
-		public function constants(){
127
-			define('AUI_PRIMARY_COLOR_ORIGINAL', "#1e73be");
128
-			define('AUI_SECONDARY_COLOR_ORIGINAL', '#6c757d');
129
-			if (!defined('AUI_PRIMARY_COLOR')) define('AUI_PRIMARY_COLOR', AUI_PRIMARY_COLOR_ORIGINAL);
130
-			if (!defined('AUI_SECONDARY_COLOR')) define('AUI_SECONDARY_COLOR', AUI_SECONDARY_COLOR_ORIGINAL);
131
-		}
132
-
133
-		/**
134
-		 * Initiate the settings and add the required action hooks.
135
-		 */
136
-		public function init() {
137
-			$this->constants();
138
-			$this->settings = $this->get_settings();
139
-			$this->url = $this->get_url();
140
-
141
-			/**
142
-			 * Maybe load CSS
143
-			 *
144
-			 * We load super early in case there is a theme version that might change the colors
145
-			 */
146
-			if ( $this->settings['css'] ) {
147
-				add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_style' ), 1 );
148
-			}
149
-			if ( $this->settings['css_backend'] && $this->load_admin_scripts() ) {
150
-				add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_style' ), 1 );
151
-			}
152
-
153
-			// maybe load JS
154
-			if ( $this->settings['js'] ) {
155
-				$priority = $this->is_bs3_compat() ? 100 : 1;
156
-				add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_scripts' ), $priority );
157
-			}
158
-			if ( $this->settings['js_backend'] && $this->load_admin_scripts() ) {
159
-				add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_scripts' ), 1 );
160
-			}
161
-
162
-			// Maybe set the HTML font size
163
-			if ( $this->settings['html_font_size'] ) {
164
-				add_action( 'wp_footer', array( $this, 'html_font_size' ), 10 );
165
-			}
166
-
167
-
168
-		}
169
-
170
-		/**
171
-		 * Check if we should load the admin scripts or not.
172
-		 *
173
-		 * @return bool
174
-		 */
175
-		public function load_admin_scripts(){
176
-			$result = true;
177
-
178
-			// check if specifically disabled
179
-			if(!empty($this->settings['disable_admin'])){
180
-				$url_parts = explode("\n",$this->settings['disable_admin']);
181
-				foreach($url_parts as $part){
182
-					if( strpos($_SERVER['REQUEST_URI'], trim($part)) !== false ){
183
-						return false; // return early, no point checking further
184
-					}
185
-				}
186
-			}
187
-
188
-			return $result;
189
-		}
190
-
191
-		/**
192
-		 * Add a html font size to the footer.
193
-		 */
194
-		public function html_font_size(){
195
-			$this->settings = $this->get_settings();
196
-			echo "<style>html{font-size:".absint($this->settings['html_font_size'])."px;}</style>";
197
-		}
24
+    /**
25
+     * A Class to be able to change settings for Font Awesome.
26
+     *
27
+     * Class AyeCode_UI_Settings
28
+     * @ver 1.0.0
29
+     * @todo decide how to implement textdomain
30
+     */
31
+    class AyeCode_UI_Settings {
32
+
33
+        /**
34
+         * Class version version.
35
+         *
36
+         * @var string
37
+         */
38
+        public $version = '0.1.46';
39
+
40
+        /**
41
+         * Class textdomain.
42
+         *
43
+         * @var string
44
+         */
45
+        public $textdomain = 'aui';
46
+
47
+        /**
48
+         * Latest version of Bootstrap at time of publish published.
49
+         *
50
+         * @var string
51
+         */
52
+        public $latest = "4.5.3";
53
+
54
+        /**
55
+         * Current version of select2 being used.
56
+         *
57
+         * @var string
58
+         */
59
+        public $select2_version = "4.0.11";
60
+
61
+        /**
62
+         * The title.
63
+         *
64
+         * @var string
65
+         */
66
+        public $name = 'AyeCode UI';
67
+
68
+        /**
69
+         * The relative url to the assets.
70
+         *
71
+         * @var string
72
+         */
73
+        public $url = '';
74
+
75
+        /**
76
+         * Holds the settings values.
77
+         *
78
+         * @var array
79
+         */
80
+        private $settings;
81
+
82
+        /**
83
+         * AyeCode_UI_Settings instance.
84
+         *
85
+         * @access private
86
+         * @since  1.0.0
87
+         * @var    AyeCode_UI_Settings There can be only one!
88
+         */
89
+        private static $instance = null;
90
+
91
+        /**
92
+         * Main AyeCode_UI_Settings Instance.
93
+         *
94
+         * Ensures only one instance of AyeCode_UI_Settings is loaded or can be loaded.
95
+         *
96
+         * @since 1.0.0
97
+         * @static
98
+         * @return AyeCode_UI_Settings - Main instance.
99
+         */
100
+        public static function instance() {
101
+            if ( ! isset( self::$instance ) && ! ( self::$instance instanceof AyeCode_UI_Settings ) ) {
102
+
103
+                self::$instance = new AyeCode_UI_Settings;
104
+
105
+                add_action( 'init', array( self::$instance, 'init' ) ); // set settings
106
+
107
+                if ( is_admin() ) {
108
+                    add_action( 'admin_menu', array( self::$instance, 'menu_item' ) );
109
+                    add_action( 'admin_init', array( self::$instance, 'register_settings' ) );
110
+
111
+                    // Maybe show example page
112
+                    add_action( 'template_redirect', array( self::$instance,'maybe_show_examples' ) );
113
+                }
198 114
 
199
-		/**
200
-		 * Check if the current admin screen should load scripts.
201
-		 * 
202
-		 * @return bool
203
-		 */
204
-		public function is_aui_screen(){
205
-			$load = false;
206
-			// check if we should load or not
207
-			if ( is_admin() ) {
208
-				// Only enable on set pages
209
-				$aui_screens = array(
210
-					'page',
211
-					'post',
212
-					'settings_page_ayecode-ui-settings',
213
-					'appearance_page_gutenberg-widgets'
214
-				);
215
-				$screen_ids = apply_filters( 'aui_screen_ids', $aui_screens );
216
-
217
-				$screen = get_current_screen();
115
+                add_action( 'customize_register', array( self::$instance, 'customizer_settings' ));
116
+
117
+                do_action( 'ayecode_ui_settings_loaded' );
118
+            }
119
+
120
+            return self::$instance;
121
+        }
122
+
123
+        /**
124
+         * Setup some constants.
125
+         */
126
+        public function constants(){
127
+            define('AUI_PRIMARY_COLOR_ORIGINAL', "#1e73be");
128
+            define('AUI_SECONDARY_COLOR_ORIGINAL', '#6c757d');
129
+            if (!defined('AUI_PRIMARY_COLOR')) define('AUI_PRIMARY_COLOR', AUI_PRIMARY_COLOR_ORIGINAL);
130
+            if (!defined('AUI_SECONDARY_COLOR')) define('AUI_SECONDARY_COLOR', AUI_SECONDARY_COLOR_ORIGINAL);
131
+        }
132
+
133
+        /**
134
+         * Initiate the settings and add the required action hooks.
135
+         */
136
+        public function init() {
137
+            $this->constants();
138
+            $this->settings = $this->get_settings();
139
+            $this->url = $this->get_url();
140
+
141
+            /**
142
+             * Maybe load CSS
143
+             *
144
+             * We load super early in case there is a theme version that might change the colors
145
+             */
146
+            if ( $this->settings['css'] ) {
147
+                add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_style' ), 1 );
148
+            }
149
+            if ( $this->settings['css_backend'] && $this->load_admin_scripts() ) {
150
+                add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_style' ), 1 );
151
+            }
152
+
153
+            // maybe load JS
154
+            if ( $this->settings['js'] ) {
155
+                $priority = $this->is_bs3_compat() ? 100 : 1;
156
+                add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_scripts' ), $priority );
157
+            }
158
+            if ( $this->settings['js_backend'] && $this->load_admin_scripts() ) {
159
+                add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_scripts' ), 1 );
160
+            }
161
+
162
+            // Maybe set the HTML font size
163
+            if ( $this->settings['html_font_size'] ) {
164
+                add_action( 'wp_footer', array( $this, 'html_font_size' ), 10 );
165
+            }
166
+
167
+
168
+        }
169
+
170
+        /**
171
+         * Check if we should load the admin scripts or not.
172
+         *
173
+         * @return bool
174
+         */
175
+        public function load_admin_scripts(){
176
+            $result = true;
177
+
178
+            // check if specifically disabled
179
+            if(!empty($this->settings['disable_admin'])){
180
+                $url_parts = explode("\n",$this->settings['disable_admin']);
181
+                foreach($url_parts as $part){
182
+                    if( strpos($_SERVER['REQUEST_URI'], trim($part)) !== false ){
183
+                        return false; // return early, no point checking further
184
+                    }
185
+                }
186
+            }
187
+
188
+            return $result;
189
+        }
190
+
191
+        /**
192
+         * Add a html font size to the footer.
193
+         */
194
+        public function html_font_size(){
195
+            $this->settings = $this->get_settings();
196
+            echo "<style>html{font-size:".absint($this->settings['html_font_size'])."px;}</style>";
197
+        }
198
+
199
+        /**
200
+         * Check if the current admin screen should load scripts.
201
+         * 
202
+         * @return bool
203
+         */
204
+        public function is_aui_screen(){
205
+            $load = false;
206
+            // check if we should load or not
207
+            if ( is_admin() ) {
208
+                // Only enable on set pages
209
+                $aui_screens = array(
210
+                    'page',
211
+                    'post',
212
+                    'settings_page_ayecode-ui-settings',
213
+                    'appearance_page_gutenberg-widgets'
214
+                );
215
+                $screen_ids = apply_filters( 'aui_screen_ids', $aui_screens );
216
+
217
+                $screen = get_current_screen();
218 218
 
219 219
 //				echo '###'.$screen->id;
220 220
 				
221
-				if ( $screen && in_array( $screen->id, $screen_ids ) ) {
222
-					$load = true;
223
-				}
224
-			}
221
+                if ( $screen && in_array( $screen->id, $screen_ids ) ) {
222
+                    $load = true;
223
+                }
224
+            }
225 225
 
226
-			return $load;
227
-		}
226
+            return $load;
227
+        }
228 228
 
229
-		/**
230
-		 * Adds the styles.
231
-		 */
232
-		public function enqueue_style() {
229
+        /**
230
+         * Adds the styles.
231
+         */
232
+        public function enqueue_style() {
233 233
 
234
-			if( is_admin() && !$this->is_aui_screen()){
235
-				// don't add wp-admin scripts if not requested to
236
-			}else{
237
-				$css_setting = current_action() == 'wp_enqueue_scripts' ? 'css' : 'css_backend';
234
+            if( is_admin() && !$this->is_aui_screen()){
235
+                // don't add wp-admin scripts if not requested to
236
+            }else{
237
+                $css_setting = current_action() == 'wp_enqueue_scripts' ? 'css' : 'css_backend';
238 238
 
239
-				$rtl = is_rtl() ? '-rtl' : '';
239
+                $rtl = is_rtl() ? '-rtl' : '';
240 240
 
241
-				if($this->settings[$css_setting]){
242
-					$compatibility = $this->settings[$css_setting]=='core' ? false : true;
243
-					$url = $this->settings[$css_setting]=='core' ? $this->url.'assets/css/ayecode-ui'.$rtl.'.css' : $this->url.'assets/css/ayecode-ui-compatibility'.$rtl.'.css';
244
-					wp_register_style( 'ayecode-ui', $url, array(), $this->latest );
245
-					wp_enqueue_style( 'ayecode-ui' );
241
+                if($this->settings[$css_setting]){
242
+                    $compatibility = $this->settings[$css_setting]=='core' ? false : true;
243
+                    $url = $this->settings[$css_setting]=='core' ? $this->url.'assets/css/ayecode-ui'.$rtl.'.css' : $this->url.'assets/css/ayecode-ui-compatibility'.$rtl.'.css';
244
+                    wp_register_style( 'ayecode-ui', $url, array(), $this->latest );
245
+                    wp_enqueue_style( 'ayecode-ui' );
246 246
 
247
-					// flatpickr
248
-					wp_register_style( 'flatpickr', $this->url.'assets/css/flatpickr.min.css', array(), $this->latest );
247
+                    // flatpickr
248
+                    wp_register_style( 'flatpickr', $this->url.'assets/css/flatpickr.min.css', array(), $this->latest );
249 249
 
250 250
 
251
-					// fix some wp-admin issues
252
-					if(is_admin()){
253
-						$custom_css = "
251
+                    // fix some wp-admin issues
252
+                    if(is_admin()){
253
+                        $custom_css = "
254 254
                 body{
255 255
                     background-color: #f1f1f1;
256 256
                     font-family: -apple-system,BlinkMacSystemFont,\"Segoe UI\",Roboto,Oxygen-Sans,Ubuntu,Cantarell,\"Helvetica Neue\",sans-serif;
@@ -289,35 +289,35 @@  discard block
 block discarded – undo
289 289
 				}
290 290
                 ";
291 291
 
292
-						// @todo, remove once fixed :: fix for this bug https://github.com/WordPress/gutenberg/issues/14377
293
-						$custom_css .= "
292
+                        // @todo, remove once fixed :: fix for this bug https://github.com/WordPress/gutenberg/issues/14377
293
+                        $custom_css .= "
294 294
 						.edit-post-sidebar input[type=color].components-text-control__input{
295 295
 						    padding: 0;
296 296
 						}
297 297
 					";
298
-						wp_add_inline_style( 'ayecode-ui', $custom_css );
299
-					}
298
+                        wp_add_inline_style( 'ayecode-ui', $custom_css );
299
+                    }
300 300
 
301
-					// custom changes
302
-					wp_add_inline_style( 'ayecode-ui', self::custom_css($compatibility) );
301
+                    // custom changes
302
+                    wp_add_inline_style( 'ayecode-ui', self::custom_css($compatibility) );
303 303
 
304
-				}
305
-			}
304
+                }
305
+            }
306 306
 
307 307
 
308
-		}
308
+        }
309
+
310
+        /**
311
+         * Get inline script used if bootstrap enqueued
312
+         *
313
+         * If this remains small then its best to use this than to add another JS file.
314
+         */
315
+        public function inline_script() {
316
+            // Flatpickr calendar locale
317
+            $flatpickr_locale = self::flatpickr_locale();
309 318
 
310
-		/**
311
-		 * Get inline script used if bootstrap enqueued
312
-		 *
313
-		 * If this remains small then its best to use this than to add another JS file.
314
-		 */
315
-		public function inline_script() {
316
-			// Flatpickr calendar locale
317
-			$flatpickr_locale = self::flatpickr_locale();
318
-
319
-			ob_start();
320
-			?>
319
+            ob_start();
320
+            ?>
321 321
 			<script>
322 322
 				/**
323 323
 				 * An AUI bootstrap adaptation of GreedyNav.js ( by Luke Jackson ).
@@ -981,27 +981,27 @@  discard block
 block discarded – undo
981 981
 
982 982
 			</script>
983 983
 			<?php
984
-			$output = ob_get_clean();
984
+            $output = ob_get_clean();
985 985
 
986
-			/*
986
+            /*
987 987
 			 * We only add the <script> tags for code highlighting, so we strip them from the output.
988 988
 			 */
989
-			return str_replace( array(
990
-				'<script>',
991
-				'</script>'
992
-			), '', $output );
993
-		}
994
-
995
-
996
-		/**
997
-		 * JS to help with conflict issues with other plugins and themes using bootstrap v3.
998
-		 *
999
-		 * @TODO we may need this when other conflicts arrise.
1000
-		 * @return mixed
1001
-		 */
1002
-		public static function bs3_compat_js() {
1003
-			ob_start();
1004
-			?>
989
+            return str_replace( array(
990
+                '<script>',
991
+                '</script>'
992
+            ), '', $output );
993
+        }
994
+
995
+
996
+        /**
997
+         * JS to help with conflict issues with other plugins and themes using bootstrap v3.
998
+         *
999
+         * @TODO we may need this when other conflicts arrise.
1000
+         * @return mixed
1001
+         */
1002
+        public static function bs3_compat_js() {
1003
+            ob_start();
1004
+            ?>
1005 1005
 			<script>
1006 1006
 				<?php if( defined( 'FUSION_BUILDER_VERSION' ) ){ ?>
1007 1007
 				/* With Avada builder */
@@ -1009,20 +1009,20 @@  discard block
 block discarded – undo
1009 1009
 				<?php } ?>
1010 1010
 			</script>
1011 1011
 			<?php
1012
-			return str_replace( array(
1013
-				'<script>',
1014
-				'</script>'
1015
-			), '', ob_get_clean());
1016
-		}
1017
-
1018
-		/**
1019
-		 * Get inline script used if bootstrap file browser enqueued.
1020
-		 *
1021
-		 * If this remains small then its best to use this than to add another JS file.
1022
-		 */
1023
-		public function inline_script_file_browser(){
1024
-			ob_start();
1025
-			?>
1012
+            return str_replace( array(
1013
+                '<script>',
1014
+                '</script>'
1015
+            ), '', ob_get_clean());
1016
+        }
1017
+
1018
+        /**
1019
+         * Get inline script used if bootstrap file browser enqueued.
1020
+         *
1021
+         * If this remains small then its best to use this than to add another JS file.
1022
+         */
1023
+        public function inline_script_file_browser(){
1024
+            ob_start();
1025
+            ?>
1026 1026
 			<script>
1027 1027
 				// run on doc ready
1028 1028
 				jQuery(document).ready(function () {
@@ -1030,192 +1030,192 @@  discard block
 block discarded – undo
1030 1030
 				});
1031 1031
 			</script>
1032 1032
 			<?php
1033
-			$output = ob_get_clean();
1033
+            $output = ob_get_clean();
1034 1034
 
1035
-			/*
1035
+            /*
1036 1036
 			 * We only add the <script> tags for code highlighting, so we strip them from the output.
1037 1037
 			 */
1038
-			return str_replace( array(
1039
-				'<script>',
1040
-				'</script>'
1041
-			), '', $output );
1042
-		}
1043
-
1044
-		/**
1045
-		 * Adds the Font Awesome JS.
1046
-		 */
1047
-		public function enqueue_scripts() {
1048
-
1049
-			if( is_admin() && !$this->is_aui_screen()){
1050
-				// don't add wp-admin scripts if not requested to
1051
-			}else {
1052
-
1053
-				$js_setting = current_action() == 'wp_enqueue_scripts' ? 'js' : 'js_backend';
1054
-
1055
-				// select2
1056
-				wp_register_script( 'select2', $this->url . 'assets/js/select2.min.js', array( 'jquery' ), $this->select2_version );
1057
-
1058
-				// flatpickr
1059
-				wp_register_script( 'flatpickr', $this->url . 'assets/js/flatpickr.min.js', array(), $this->latest );
1060
-
1061
-				// Bootstrap file browser
1062
-				wp_register_script( 'aui-custom-file-input', $url = $this->url . 'assets/js/bs-custom-file-input.min.js', array( 'jquery' ), $this->select2_version );
1063
-				wp_add_inline_script( 'aui-custom-file-input', $this->inline_script_file_browser() );
1064
-
1065
-				$load_inline = false;
1066
-
1067
-				if ( $this->settings[ $js_setting ] == 'core-popper' ) {
1068
-					// Bootstrap bundle
1069
-					$url = $this->url . 'assets/js/bootstrap.bundle.min.js';
1070
-					wp_register_script( 'bootstrap-js-bundle', $url, array(
1071
-						'select2',
1072
-						'jquery'
1073
-					), $this->latest, $this->is_bs3_compat() );
1074
-					// if in admin then add to footer for compatibility.
1075
-					is_admin() ? wp_enqueue_script( 'bootstrap-js-bundle', '', null, null, true ) : wp_enqueue_script( 'bootstrap-js-bundle' );
1076
-					$script = $this->inline_script();
1077
-					wp_add_inline_script( 'bootstrap-js-bundle', $script );
1078
-				} elseif ( $this->settings[ $js_setting ] == 'popper' ) {
1079
-					$url = $this->url . 'assets/js/popper.min.js';
1080
-					wp_register_script( 'bootstrap-js-popper', $url, array( 'select2', 'jquery' ), $this->latest );
1081
-					wp_enqueue_script( 'bootstrap-js-popper' );
1082
-					$load_inline = true;
1083
-				} else {
1084
-					$load_inline = true;
1085
-				}
1086
-
1087
-				// Load needed inline scripts by faking the loading of a script if the main script is not being loaded
1088
-				if ( $load_inline ) {
1089
-					wp_register_script( 'bootstrap-dummy', '', array( 'select2', 'jquery' ) );
1090
-					wp_enqueue_script( 'bootstrap-dummy' );
1091
-					$script = $this->inline_script();
1092
-					wp_add_inline_script( 'bootstrap-dummy', $script );
1093
-				}
1094
-			}
1095
-
1096
-		}
1097
-
1098
-		/**
1099
-		 * Enqueue flatpickr if called.
1100
-		 */
1101
-		public function enqueue_flatpickr(){
1102
-			wp_enqueue_style( 'flatpickr' );
1103
-			wp_enqueue_script( 'flatpickr' );
1104
-		}
1105
-
1106
-		/**
1107
-		 * Get the url path to the current folder.
1108
-		 *
1109
-		 * @return string
1110
-		 */
1111
-		public function get_url() {
1112
-
1113
-			$url = '';
1114
-			// check if we are inside a plugin
1115
-			$file_dir = str_replace( "/includes","", wp_normalize_path( dirname( __FILE__ ) ) );
1116
-
1117
-			// add check in-case user has changed wp-content dir name.
1118
-			$wp_content_folder_name = basename(WP_CONTENT_DIR);
1119
-			$dir_parts = explode("/$wp_content_folder_name/",$file_dir);
1120
-			$url_parts = explode("/$wp_content_folder_name/",plugins_url());
1121
-
1122
-			if(!empty($url_parts[0]) && !empty($dir_parts[1])){
1123
-				$url = trailingslashit( $url_parts[0]."/$wp_content_folder_name/".$dir_parts[1] );
1124
-			}
1125
-
1126
-			return $url;
1127
-		}
1128
-
1129
-		/**
1130
-		 * Register the database settings with WordPress.
1131
-		 */
1132
-		public function register_settings() {
1133
-			register_setting( 'ayecode-ui-settings', 'ayecode-ui-settings' );
1134
-		}
1135
-
1136
-		/**
1137
-		 * Add the WordPress settings menu item.
1138
-		 * @since 1.0.10 Calling function name direct will fail theme check so we don't.
1139
-		 */
1140
-		public function menu_item() {
1141
-			$menu_function = 'add' . '_' . 'options' . '_' . 'page'; // won't pass theme check if function name present in theme
1142
-			call_user_func( $menu_function, $this->name, $this->name, 'manage_options', 'ayecode-ui-settings', array(
1143
-				$this,
1144
-				'settings_page'
1145
-			) );
1146
-		}
1147
-
1148
-		/**
1149
-		 * Get a list of themes and their default JS settings.
1150
-		 *
1151
-		 * @return array
1152
-		 */
1153
-		public function theme_js_settings(){
1154
-			return array(
1155
-				'ayetheme' => 'popper',
1156
-				'listimia' => 'required',
1157
-				'listimia_backend' => 'core-popper',
1158
-				//'avada'    => 'required', // removed as we now add compatibility
1159
-			);
1160
-		}
1161
-
1162
-		/**
1163
-		 * Get the current Font Awesome output settings.
1164
-		 *
1165
-		 * @return array The array of settings.
1166
-		 */
1167
-		public function get_settings() {
1168
-
1169
-			$db_settings = get_option( 'ayecode-ui-settings' );
1170
-			$js_default = 'core-popper';
1171
-			$js_default_backend = $js_default;
1172
-
1173
-			// maybe set defaults (if no settings set)
1174
-			if(empty($db_settings)){
1175
-				$active_theme = strtolower( get_template() ); // active parent theme.
1176
-				$theme_js_settings = self::theme_js_settings();
1177
-				if(isset($theme_js_settings[$active_theme])){
1178
-					$js_default = $theme_js_settings[$active_theme];
1179
-					$js_default_backend = isset($theme_js_settings[$active_theme."_backend"]) ? $theme_js_settings[$active_theme."_backend"] : $js_default;
1180
-				}
1181
-			}
1182
-
1183
-			$defaults = array(
1184
-				'css'       => 'compatibility', // core, compatibility
1185
-				'js'        => $js_default, // js to load, core-popper, popper
1186
-				'html_font_size'        => '16', // js to load, core-popper, popper
1187
-				'css_backend'       => 'compatibility', // core, compatibility
1188
-				'js_backend'        => $js_default_backend, // js to load, core-popper, popper
1189
-				'disable_admin'     =>  '', // URL snippets to disable loading on admin
1190
-			);
1191
-
1192
-			$settings = wp_parse_args( $db_settings, $defaults );
1193
-
1194
-			/**
1195
-			 * Filter the Bootstrap settings.
1196
-			 *
1197
-			 * @todo if we add this filer people might use it and then it defeates the purpose of this class :/
1198
-			 */
1199
-			return $this->settings = apply_filters( 'ayecode-ui-settings', $settings, $db_settings, $defaults );
1200
-		}
1201
-
1038
+            return str_replace( array(
1039
+                '<script>',
1040
+                '</script>'
1041
+            ), '', $output );
1042
+        }
1043
+
1044
+        /**
1045
+         * Adds the Font Awesome JS.
1046
+         */
1047
+        public function enqueue_scripts() {
1048
+
1049
+            if( is_admin() && !$this->is_aui_screen()){
1050
+                // don't add wp-admin scripts if not requested to
1051
+            }else {
1052
+
1053
+                $js_setting = current_action() == 'wp_enqueue_scripts' ? 'js' : 'js_backend';
1054
+
1055
+                // select2
1056
+                wp_register_script( 'select2', $this->url . 'assets/js/select2.min.js', array( 'jquery' ), $this->select2_version );
1057
+
1058
+                // flatpickr
1059
+                wp_register_script( 'flatpickr', $this->url . 'assets/js/flatpickr.min.js', array(), $this->latest );
1060
+
1061
+                // Bootstrap file browser
1062
+                wp_register_script( 'aui-custom-file-input', $url = $this->url . 'assets/js/bs-custom-file-input.min.js', array( 'jquery' ), $this->select2_version );
1063
+                wp_add_inline_script( 'aui-custom-file-input', $this->inline_script_file_browser() );
1064
+
1065
+                $load_inline = false;
1066
+
1067
+                if ( $this->settings[ $js_setting ] == 'core-popper' ) {
1068
+                    // Bootstrap bundle
1069
+                    $url = $this->url . 'assets/js/bootstrap.bundle.min.js';
1070
+                    wp_register_script( 'bootstrap-js-bundle', $url, array(
1071
+                        'select2',
1072
+                        'jquery'
1073
+                    ), $this->latest, $this->is_bs3_compat() );
1074
+                    // if in admin then add to footer for compatibility.
1075
+                    is_admin() ? wp_enqueue_script( 'bootstrap-js-bundle', '', null, null, true ) : wp_enqueue_script( 'bootstrap-js-bundle' );
1076
+                    $script = $this->inline_script();
1077
+                    wp_add_inline_script( 'bootstrap-js-bundle', $script );
1078
+                } elseif ( $this->settings[ $js_setting ] == 'popper' ) {
1079
+                    $url = $this->url . 'assets/js/popper.min.js';
1080
+                    wp_register_script( 'bootstrap-js-popper', $url, array( 'select2', 'jquery' ), $this->latest );
1081
+                    wp_enqueue_script( 'bootstrap-js-popper' );
1082
+                    $load_inline = true;
1083
+                } else {
1084
+                    $load_inline = true;
1085
+                }
1202 1086
 
1203
-		/**
1204
-		 * The settings page html output.
1205
-		 */
1206
-		public function settings_page() {
1207
-			if ( ! current_user_can( 'manage_options' ) ) {
1208
-				wp_die( __( 'You do not have sufficient permissions to access this page.', 'aui' ) );
1209
-			}
1210
-			?>
1087
+                // Load needed inline scripts by faking the loading of a script if the main script is not being loaded
1088
+                if ( $load_inline ) {
1089
+                    wp_register_script( 'bootstrap-dummy', '', array( 'select2', 'jquery' ) );
1090
+                    wp_enqueue_script( 'bootstrap-dummy' );
1091
+                    $script = $this->inline_script();
1092
+                    wp_add_inline_script( 'bootstrap-dummy', $script );
1093
+                }
1094
+            }
1095
+
1096
+        }
1097
+
1098
+        /**
1099
+         * Enqueue flatpickr if called.
1100
+         */
1101
+        public function enqueue_flatpickr(){
1102
+            wp_enqueue_style( 'flatpickr' );
1103
+            wp_enqueue_script( 'flatpickr' );
1104
+        }
1105
+
1106
+        /**
1107
+         * Get the url path to the current folder.
1108
+         *
1109
+         * @return string
1110
+         */
1111
+        public function get_url() {
1112
+
1113
+            $url = '';
1114
+            // check if we are inside a plugin
1115
+            $file_dir = str_replace( "/includes","", wp_normalize_path( dirname( __FILE__ ) ) );
1116
+
1117
+            // add check in-case user has changed wp-content dir name.
1118
+            $wp_content_folder_name = basename(WP_CONTENT_DIR);
1119
+            $dir_parts = explode("/$wp_content_folder_name/",$file_dir);
1120
+            $url_parts = explode("/$wp_content_folder_name/",plugins_url());
1121
+
1122
+            if(!empty($url_parts[0]) && !empty($dir_parts[1])){
1123
+                $url = trailingslashit( $url_parts[0]."/$wp_content_folder_name/".$dir_parts[1] );
1124
+            }
1125
+
1126
+            return $url;
1127
+        }
1128
+
1129
+        /**
1130
+         * Register the database settings with WordPress.
1131
+         */
1132
+        public function register_settings() {
1133
+            register_setting( 'ayecode-ui-settings', 'ayecode-ui-settings' );
1134
+        }
1135
+
1136
+        /**
1137
+         * Add the WordPress settings menu item.
1138
+         * @since 1.0.10 Calling function name direct will fail theme check so we don't.
1139
+         */
1140
+        public function menu_item() {
1141
+            $menu_function = 'add' . '_' . 'options' . '_' . 'page'; // won't pass theme check if function name present in theme
1142
+            call_user_func( $menu_function, $this->name, $this->name, 'manage_options', 'ayecode-ui-settings', array(
1143
+                $this,
1144
+                'settings_page'
1145
+            ) );
1146
+        }
1147
+
1148
+        /**
1149
+         * Get a list of themes and their default JS settings.
1150
+         *
1151
+         * @return array
1152
+         */
1153
+        public function theme_js_settings(){
1154
+            return array(
1155
+                'ayetheme' => 'popper',
1156
+                'listimia' => 'required',
1157
+                'listimia_backend' => 'core-popper',
1158
+                //'avada'    => 'required', // removed as we now add compatibility
1159
+            );
1160
+        }
1161
+
1162
+        /**
1163
+         * Get the current Font Awesome output settings.
1164
+         *
1165
+         * @return array The array of settings.
1166
+         */
1167
+        public function get_settings() {
1168
+
1169
+            $db_settings = get_option( 'ayecode-ui-settings' );
1170
+            $js_default = 'core-popper';
1171
+            $js_default_backend = $js_default;
1172
+
1173
+            // maybe set defaults (if no settings set)
1174
+            if(empty($db_settings)){
1175
+                $active_theme = strtolower( get_template() ); // active parent theme.
1176
+                $theme_js_settings = self::theme_js_settings();
1177
+                if(isset($theme_js_settings[$active_theme])){
1178
+                    $js_default = $theme_js_settings[$active_theme];
1179
+                    $js_default_backend = isset($theme_js_settings[$active_theme."_backend"]) ? $theme_js_settings[$active_theme."_backend"] : $js_default;
1180
+                }
1181
+            }
1182
+
1183
+            $defaults = array(
1184
+                'css'       => 'compatibility', // core, compatibility
1185
+                'js'        => $js_default, // js to load, core-popper, popper
1186
+                'html_font_size'        => '16', // js to load, core-popper, popper
1187
+                'css_backend'       => 'compatibility', // core, compatibility
1188
+                'js_backend'        => $js_default_backend, // js to load, core-popper, popper
1189
+                'disable_admin'     =>  '', // URL snippets to disable loading on admin
1190
+            );
1191
+
1192
+            $settings = wp_parse_args( $db_settings, $defaults );
1193
+
1194
+            /**
1195
+             * Filter the Bootstrap settings.
1196
+             *
1197
+             * @todo if we add this filer people might use it and then it defeates the purpose of this class :/
1198
+             */
1199
+            return $this->settings = apply_filters( 'ayecode-ui-settings', $settings, $db_settings, $defaults );
1200
+        }
1201
+
1202
+
1203
+        /**
1204
+         * The settings page html output.
1205
+         */
1206
+        public function settings_page() {
1207
+            if ( ! current_user_can( 'manage_options' ) ) {
1208
+                wp_die( __( 'You do not have sufficient permissions to access this page.', 'aui' ) );
1209
+            }
1210
+            ?>
1211 1211
 			<div class="wrap">
1212 1212
 				<h1><?php echo $this->name; ?></h1>
1213 1213
 				<p><?php _e("Here you can adjust settings if you are having compatibility issues.",'aui');?></p>
1214 1214
 				<form method="post" action="options.php">
1215 1215
 					<?php
1216
-					settings_fields( 'ayecode-ui-settings' );
1217
-					do_settings_sections( 'ayecode-ui-settings' );
1218
-					?>
1216
+                    settings_fields( 'ayecode-ui-settings' );
1217
+                    do_settings_sections( 'ayecode-ui-settings' );
1218
+                    ?>
1219 1219
 
1220 1220
 					<h2><?php _e( 'Frontend', 'aui' ); ?></h2>
1221 1221
 					<table class="form-table wpbs-table-settings">
@@ -1295,60 +1295,60 @@  discard block
 block discarded – undo
1295 1295
 					</table>
1296 1296
 
1297 1297
 					<?php
1298
-					submit_button();
1299
-					?>
1298
+                    submit_button();
1299
+                    ?>
1300 1300
 				</form>
1301 1301
 
1302 1302
 				<div id="wpbs-version"><?php echo $this->version; ?></div>
1303 1303
 			</div>
1304 1304
 
1305 1305
 			<?php
1306
-		}
1307
-
1308
-		public function customizer_settings($wp_customize){
1309
-			$wp_customize->add_section('aui_settings', array(
1310
-				'title'    => __('AyeCode UI','aui'),
1311
-				'priority' => 120,
1312
-			));
1313
-
1314
-			//  =============================
1315
-			//  = Color Picker              =
1316
-			//  =============================
1317
-			$wp_customize->add_setting('aui_options[color_primary]', array(
1318
-				'default'           => AUI_PRIMARY_COLOR,
1319
-				'sanitize_callback' => 'sanitize_hex_color',
1320
-				'capability'        => 'edit_theme_options',
1321
-				'type'              => 'option',
1322
-				'transport'         => 'refresh',
1323
-			));
1324
-			$wp_customize->add_control( new WP_Customize_Color_Control($wp_customize, 'color_primary', array(
1325
-				'label'    => __('Primary Color','aui'),
1326
-				'section'  => 'aui_settings',
1327
-				'settings' => 'aui_options[color_primary]',
1328
-			)));
1329
-
1330
-			$wp_customize->add_setting('aui_options[color_secondary]', array(
1331
-				'default'           => '#6c757d',
1332
-				'sanitize_callback' => 'sanitize_hex_color',
1333
-				'capability'        => 'edit_theme_options',
1334
-				'type'              => 'option',
1335
-				'transport'         => 'refresh',
1336
-			));
1337
-			$wp_customize->add_control( new WP_Customize_Color_Control($wp_customize, 'color_secondary', array(
1338
-				'label'    => __('Secondary Color','aui'),
1339
-				'section'  => 'aui_settings',
1340
-				'settings' => 'aui_options[color_secondary]',
1341
-			)));
1342
-		}
1343
-
1344
-		/**
1345
-		 * CSS to help with conflict issues with other plugins and themes using bootstrap v3.
1346
-		 *
1347
-		 * @return mixed
1348
-		 */
1349
-		public static function bs3_compat_css() {
1350
-			ob_start();
1351
-			?>
1306
+        }
1307
+
1308
+        public function customizer_settings($wp_customize){
1309
+            $wp_customize->add_section('aui_settings', array(
1310
+                'title'    => __('AyeCode UI','aui'),
1311
+                'priority' => 120,
1312
+            ));
1313
+
1314
+            //  =============================
1315
+            //  = Color Picker              =
1316
+            //  =============================
1317
+            $wp_customize->add_setting('aui_options[color_primary]', array(
1318
+                'default'           => AUI_PRIMARY_COLOR,
1319
+                'sanitize_callback' => 'sanitize_hex_color',
1320
+                'capability'        => 'edit_theme_options',
1321
+                'type'              => 'option',
1322
+                'transport'         => 'refresh',
1323
+            ));
1324
+            $wp_customize->add_control( new WP_Customize_Color_Control($wp_customize, 'color_primary', array(
1325
+                'label'    => __('Primary Color','aui'),
1326
+                'section'  => 'aui_settings',
1327
+                'settings' => 'aui_options[color_primary]',
1328
+            )));
1329
+
1330
+            $wp_customize->add_setting('aui_options[color_secondary]', array(
1331
+                'default'           => '#6c757d',
1332
+                'sanitize_callback' => 'sanitize_hex_color',
1333
+                'capability'        => 'edit_theme_options',
1334
+                'type'              => 'option',
1335
+                'transport'         => 'refresh',
1336
+            ));
1337
+            $wp_customize->add_control( new WP_Customize_Color_Control($wp_customize, 'color_secondary', array(
1338
+                'label'    => __('Secondary Color','aui'),
1339
+                'section'  => 'aui_settings',
1340
+                'settings' => 'aui_options[color_secondary]',
1341
+            )));
1342
+        }
1343
+
1344
+        /**
1345
+         * CSS to help with conflict issues with other plugins and themes using bootstrap v3.
1346
+         *
1347
+         * @return mixed
1348
+         */
1349
+        public static function bs3_compat_css() {
1350
+            ob_start();
1351
+            ?>
1352 1352
 			<style>
1353 1353
 			/* Bootstrap 3 compatibility */
1354 1354
 			body.modal-open .modal-backdrop.show:not(.in) {opacity:0.5;}
@@ -1374,579 +1374,579 @@  discard block
 block discarded – undo
1374 1374
 			<?php } ?>
1375 1375
 			</style>
1376 1376
 			<?php
1377
-			return str_replace( array(
1378
-				'<style>',
1379
-				'</style>'
1380
-			), '', ob_get_clean());
1381
-		}
1377
+            return str_replace( array(
1378
+                '<style>',
1379
+                '</style>'
1380
+            ), '', ob_get_clean());
1381
+        }
1382 1382
 
1383 1383
 
1384
-		public static function custom_css($compatibility = true) {
1385
-			$settings = get_option('aui_options');
1384
+        public static function custom_css($compatibility = true) {
1385
+            $settings = get_option('aui_options');
1386 1386
 
1387
-			ob_start();
1387
+            ob_start();
1388 1388
 
1389
-			$primary_color = !empty($settings['color_primary']) ? $settings['color_primary'] : AUI_PRIMARY_COLOR;
1390
-			$secondary_color = !empty($settings['color_secondary']) ? $settings['color_secondary'] : AUI_SECONDARY_COLOR;
1391
-				//AUI_PRIMARY_COLOR_ORIGINAL
1392
-			?>
1389
+            $primary_color = !empty($settings['color_primary']) ? $settings['color_primary'] : AUI_PRIMARY_COLOR;
1390
+            $secondary_color = !empty($settings['color_secondary']) ? $settings['color_secondary'] : AUI_SECONDARY_COLOR;
1391
+                //AUI_PRIMARY_COLOR_ORIGINAL
1392
+            ?>
1393 1393
 			<style>
1394 1394
 				<?php
1395 1395
 
1396
-					// BS v3 compat
1397
-					if( self::is_bs3_compat() ){
1398
-					    echo self::bs3_compat_css();
1399
-					}
1396
+                    // BS v3 compat
1397
+                    if( self::is_bs3_compat() ){
1398
+                        echo self::bs3_compat_css();
1399
+                    }
1400 1400
 
1401
-					if(!is_admin() && $primary_color != AUI_PRIMARY_COLOR_ORIGINAL){
1402
-						echo self::css_primary($primary_color,$compatibility);
1403
-					}
1401
+                    if(!is_admin() && $primary_color != AUI_PRIMARY_COLOR_ORIGINAL){
1402
+                        echo self::css_primary($primary_color,$compatibility);
1403
+                    }
1404 1404
 
1405
-					if(!is_admin() && $secondary_color != AUI_SECONDARY_COLOR_ORIGINAL){
1406
-						echo self::css_secondary($settings['color_secondary'],$compatibility);
1407
-					}
1405
+                    if(!is_admin() && $secondary_color != AUI_SECONDARY_COLOR_ORIGINAL){
1406
+                        echo self::css_secondary($settings['color_secondary'],$compatibility);
1407
+                    }
1408 1408
 
1409
-					// Set admin bar z-index lower when modal is open.
1410
-					echo ' body.modal-open #wpadminbar{z-index:999}';
1409
+                    // Set admin bar z-index lower when modal is open.
1410
+                    echo ' body.modal-open #wpadminbar{z-index:999}';
1411 1411
                 ?>
1412 1412
 			</style>
1413 1413
 			<?php
1414 1414
 
1415 1415
 
1416
-			/*
1416
+            /*
1417 1417
 			 * We only add the <script> tags for code highlighting, so we strip them from the output.
1418 1418
 			 */
1419
-			return str_replace( array(
1420
-				'<style>',
1421
-				'</style>'
1422
-			), '', ob_get_clean());
1423
-		}
1424
-
1425
-		/**
1426
-		 * Check if we should add booststrap 3 compatibility changes.
1427
-		 *
1428
-		 * @return bool
1429
-		 */
1430
-		public static function is_bs3_compat(){
1431
-			return defined('AYECODE_UI_BS3_COMPAT') || defined('SVQ_THEME_VERSION') || defined('FUSION_BUILDER_VERSION');
1432
-		}
1433
-
1434
-		public static function css_primary($color_code,$compatibility){;
1435
-			$color_code = sanitize_hex_color($color_code);
1436
-			if(!$color_code){return '';}
1437
-			/**
1438
-			 * c = color, b = background color, o = border-color, f = fill
1439
-			 */
1440
-			$selectors = array(
1441
-				'a' => array('c'),
1442
-				'.btn-primary' => array('b','o'),
1443
-				'.btn-primary.disabled' => array('b','o'),
1444
-				'.btn-primary:disabled' => array('b','o'),
1445
-				'.btn-outline-primary' => array('c','o'),
1446
-				'.btn-outline-primary:hover' => array('b','o'),
1447
-				'.btn-outline-primary:not(:disabled):not(.disabled).active' => array('b','o'),
1448
-				'.btn-outline-primary:not(:disabled):not(.disabled):active' => array('b','o'),
1449
-				'.show>.btn-outline-primary.dropdown-toggle' => array('b','o'),
1450
-				'.btn-link' => array('c'),
1451
-				'.dropdown-item.active' => array('b'),
1452
-				'.custom-control-input:checked~.custom-control-label::before' => array('b','o'),
1453
-				'.custom-checkbox .custom-control-input:indeterminate~.custom-control-label::before' => array('b','o'),
1419
+            return str_replace( array(
1420
+                '<style>',
1421
+                '</style>'
1422
+            ), '', ob_get_clean());
1423
+        }
1424
+
1425
+        /**
1426
+         * Check if we should add booststrap 3 compatibility changes.
1427
+         *
1428
+         * @return bool
1429
+         */
1430
+        public static function is_bs3_compat(){
1431
+            return defined('AYECODE_UI_BS3_COMPAT') || defined('SVQ_THEME_VERSION') || defined('FUSION_BUILDER_VERSION');
1432
+        }
1433
+
1434
+        public static function css_primary($color_code,$compatibility){;
1435
+            $color_code = sanitize_hex_color($color_code);
1436
+            if(!$color_code){return '';}
1437
+            /**
1438
+             * c = color, b = background color, o = border-color, f = fill
1439
+             */
1440
+            $selectors = array(
1441
+                'a' => array('c'),
1442
+                '.btn-primary' => array('b','o'),
1443
+                '.btn-primary.disabled' => array('b','o'),
1444
+                '.btn-primary:disabled' => array('b','o'),
1445
+                '.btn-outline-primary' => array('c','o'),
1446
+                '.btn-outline-primary:hover' => array('b','o'),
1447
+                '.btn-outline-primary:not(:disabled):not(.disabled).active' => array('b','o'),
1448
+                '.btn-outline-primary:not(:disabled):not(.disabled):active' => array('b','o'),
1449
+                '.show>.btn-outline-primary.dropdown-toggle' => array('b','o'),
1450
+                '.btn-link' => array('c'),
1451
+                '.dropdown-item.active' => array('b'),
1452
+                '.custom-control-input:checked~.custom-control-label::before' => array('b','o'),
1453
+                '.custom-checkbox .custom-control-input:indeterminate~.custom-control-label::before' => array('b','o'),
1454 1454
 //				'.custom-range::-webkit-slider-thumb' => array('b'), // these break the inline rules...
1455 1455
 //				'.custom-range::-moz-range-thumb' => array('b'),
1456 1456
 //				'.custom-range::-ms-thumb' => array('b'),
1457
-				'.nav-pills .nav-link.active' => array('b'),
1458
-				'.nav-pills .show>.nav-link' => array('b'),
1459
-				'.page-link' => array('c'),
1460
-				'.page-item.active .page-link' => array('b','o'),
1461
-				'.badge-primary' => array('b'),
1462
-				'.alert-primary' => array('b','o'),
1463
-				'.progress-bar' => array('b'),
1464
-				'.list-group-item.active' => array('b','o'),
1465
-				'.bg-primary' => array('b','f'),
1466
-				'.btn-link.btn-primary' => array('c'),
1467
-				'.select2-container .select2-results__option--highlighted.select2-results__option[aria-selected=true]' => array('b'),
1468
-			);
1469
-
1470
-			$important_selectors = array(
1471
-				'.bg-primary' => array('b','f'),
1472
-				'.border-primary' => array('o'),
1473
-				'.text-primary' => array('c'),
1474
-			);
1475
-
1476
-			$color = array();
1477
-			$color_i = array();
1478
-			$background = array();
1479
-			$background_i = array();
1480
-			$border = array();
1481
-			$border_i = array();
1482
-			$fill = array();
1483
-			$fill_i = array();
1484
-
1485
-			$output = '';
1486
-
1487
-			// build rules into each type
1488
-			foreach($selectors as $selector => $types){
1489
-				$selector = $compatibility ? ".bsui ".$selector : $selector;
1490
-				$types = array_combine($types,$types);
1491
-				if(isset($types['c'])){$color[] = $selector;}
1492
-				if(isset($types['b'])){$background[] = $selector;}
1493
-				if(isset($types['o'])){$border[] = $selector;}
1494
-				if(isset($types['f'])){$fill[] = $selector;}
1495
-			}
1496
-
1497
-			// build rules into each type
1498
-			foreach($important_selectors as $selector => $types){
1499
-				$selector = $compatibility ? ".bsui ".$selector : $selector;
1500
-				$types = array_combine($types,$types);
1501
-				if(isset($types['c'])){$color_i[] = $selector;}
1502
-				if(isset($types['b'])){$background_i[] = $selector;}
1503
-				if(isset($types['o'])){$border_i[] = $selector;}
1504
-				if(isset($types['f'])){$fill_i[] = $selector;}
1505
-			}
1506
-
1507
-			// add any color rules
1508
-			if(!empty($color)){
1509
-				$output .= implode(",",$color) . "{color: $color_code;} ";
1510
-			}
1511
-			if(!empty($color_i)){
1512
-				$output .= implode(",",$color_i) . "{color: $color_code !important;} ";
1513
-			}
1514
-
1515
-			// add any background color rules
1516
-			if(!empty($background)){
1517
-				$output .= implode(",",$background) . "{background-color: $color_code;} ";
1518
-			}
1519
-			if(!empty($background_i)){
1520
-				$output .= implode(",",$background_i) . "{background-color: $color_code !important;} ";
1521
-			}
1522
-
1523
-			// add any border color rules
1524
-			if(!empty($border)){
1525
-				$output .= implode(",",$border) . "{border-color: $color_code;} ";
1526
-			}
1527
-			if(!empty($border_i)){
1528
-				$output .= implode(",",$border_i) . "{border-color: $color_code !important;} ";
1529
-			}
1530
-
1531
-			// add any fill color rules
1532
-			if(!empty($fill)){
1533
-				$output .= implode(",",$fill) . "{fill: $color_code;} ";
1534
-			}
1535
-			if(!empty($fill_i)){
1536
-				$output .= implode(",",$fill_i) . "{fill: $color_code !important;} ";
1537
-			}
1538
-
1539
-
1540
-			$prefix = $compatibility ? ".bsui " : "";
1541
-
1542
-			// darken
1543
-			$darker_075 = self::css_hex_lighten_darken($color_code,"-0.075");
1544
-			$darker_10 = self::css_hex_lighten_darken($color_code,"-0.10");
1545
-			$darker_125 = self::css_hex_lighten_darken($color_code,"-0.125");
1546
-
1547
-			// lighten
1548
-			$lighten_25 = self::css_hex_lighten_darken($color_code,"0.25");
1549
-
1550
-			// opacity see https://css-tricks.com/8-digit-hex-codes/
1551
-			$op_25 = $color_code."40"; // 25% opacity
1552
-
1553
-
1554
-			// button states
1555
-			$output .= $prefix ." .btn-primary:hover{background-color: ".$darker_075.";    border-color: ".$darker_10.";} ";
1556
-			$output .= $prefix ." .btn-outline-primary:not(:disabled):not(.disabled):active:focus, $prefix .btn-outline-primary:not(:disabled):not(.disabled).active:focus, .show>$prefix .btn-outline-primary.dropdown-toggle:focus{box-shadow: 0 0 0 0.2rem $op_25;} ";
1557
-			$output .= $prefix ." .btn-primary:not(:disabled):not(.disabled):active, $prefix .btn-primary:not(:disabled):not(.disabled).active, .show>$prefix .btn-primary.dropdown-toggle{background-color: ".$darker_10.";    border-color: ".$darker_125.";} ";
1558
-			$output .= $prefix ." .btn-primary:not(:disabled):not(.disabled):active:focus, $prefix .btn-primary:not(:disabled):not(.disabled).active:focus, .show>$prefix .btn-primary.dropdown-toggle:focus {box-shadow: 0 0 0 0.2rem $op_25;} ";
1559
-
1560
-
1561
-			// dropdown's
1562
-			$output .= $prefix ." .dropdown-item.active, $prefix .dropdown-item:active{background-color: $color_code;} ";
1563
-
1564
-
1565
-			// input states
1566
-			$output .= $prefix ." .form-control:focus{border-color: ".$lighten_25.";box-shadow: 0 0 0 0.2rem $op_25;} ";
1567
-
1568
-			// page link
1569
-			$output .= $prefix ." .page-link:focus{box-shadow: 0 0 0 0.2rem $op_25;} ";
1570
-
1571
-			return $output;
1572
-		}
1573
-
1574
-		public static function css_secondary($color_code,$compatibility){;
1575
-			$color_code = sanitize_hex_color($color_code);
1576
-			if(!$color_code){return '';}
1577
-			/**
1578
-			 * c = color, b = background color, o = border-color, f = fill
1579
-			 */
1580
-			$selectors = array(
1581
-				'.btn-secondary' => array('b','o'),
1582
-				'.btn-secondary.disabled' => array('b','o'),
1583
-				'.btn-secondary:disabled' => array('b','o'),
1584
-				'.btn-outline-secondary' => array('c','o'),
1585
-				'.btn-outline-secondary:hover' => array('b','o'),
1586
-				'.btn-outline-secondary.disabled' => array('c'),
1587
-				'.btn-outline-secondary:disabled' => array('c'),
1588
-				'.btn-outline-secondary:not(:disabled):not(.disabled):active' => array('b','o'),
1589
-				'.btn-outline-secondary:not(:disabled):not(.disabled).active' => array('b','o'),
1590
-				'.btn-outline-secondary.dropdown-toggle' => array('b','o'),
1591
-				'.badge-secondary' => array('b'),
1592
-				'.alert-secondary' => array('b','o'),
1593
-				'.btn-link.btn-secondary' => array('c'),
1594
-			);
1595
-
1596
-			$important_selectors = array(
1597
-				'.bg-secondary' => array('b','f'),
1598
-				'.border-secondary' => array('o'),
1599
-				'.text-secondary' => array('c'),
1600
-			);
1601
-
1602
-			$color = array();
1603
-			$color_i = array();
1604
-			$background = array();
1605
-			$background_i = array();
1606
-			$border = array();
1607
-			$border_i = array();
1608
-			$fill = array();
1609
-			$fill_i = array();
1610
-
1611
-			$output = '';
1612
-
1613
-			// build rules into each type
1614
-			foreach($selectors as $selector => $types){
1615
-				$selector = $compatibility ? ".bsui ".$selector : $selector;
1616
-				$types = array_combine($types,$types);
1617
-				if(isset($types['c'])){$color[] = $selector;}
1618
-				if(isset($types['b'])){$background[] = $selector;}
1619
-				if(isset($types['o'])){$border[] = $selector;}
1620
-				if(isset($types['f'])){$fill[] = $selector;}
1621
-			}
1622
-
1623
-			// build rules into each type
1624
-			foreach($important_selectors as $selector => $types){
1625
-				$selector = $compatibility ? ".bsui ".$selector : $selector;
1626
-				$types = array_combine($types,$types);
1627
-				if(isset($types['c'])){$color_i[] = $selector;}
1628
-				if(isset($types['b'])){$background_i[] = $selector;}
1629
-				if(isset($types['o'])){$border_i[] = $selector;}
1630
-				if(isset($types['f'])){$fill_i[] = $selector;}
1631
-			}
1632
-
1633
-			// add any color rules
1634
-			if(!empty($color)){
1635
-				$output .= implode(",",$color) . "{color: $color_code;} ";
1636
-			}
1637
-			if(!empty($color_i)){
1638
-				$output .= implode(",",$color_i) . "{color: $color_code !important;} ";
1639
-			}
1640
-
1641
-			// add any background color rules
1642
-			if(!empty($background)){
1643
-				$output .= implode(",",$background) . "{background-color: $color_code;} ";
1644
-			}
1645
-			if(!empty($background_i)){
1646
-				$output .= implode(",",$background_i) . "{background-color: $color_code !important;} ";
1647
-			}
1648
-
1649
-			// add any border color rules
1650
-			if(!empty($border)){
1651
-				$output .= implode(",",$border) . "{border-color: $color_code;} ";
1652
-			}
1653
-			if(!empty($border_i)){
1654
-				$output .= implode(",",$border_i) . "{border-color: $color_code !important;} ";
1655
-			}
1656
-
1657
-			// add any fill color rules
1658
-			if(!empty($fill)){
1659
-				$output .= implode(",",$fill) . "{fill: $color_code;} ";
1660
-			}
1661
-			if(!empty($fill_i)){
1662
-				$output .= implode(",",$fill_i) . "{fill: $color_code !important;} ";
1663
-			}
1664
-
1665
-
1666
-			$prefix = $compatibility ? ".bsui " : "";
1667
-
1668
-			// darken
1669
-			$darker_075 = self::css_hex_lighten_darken($color_code,"-0.075");
1670
-			$darker_10 = self::css_hex_lighten_darken($color_code,"-0.10");
1671
-			$darker_125 = self::css_hex_lighten_darken($color_code,"-0.125");
1672
-
1673
-			// lighten
1674
-			$lighten_25 = self::css_hex_lighten_darken($color_code,"0.25");
1675
-
1676
-			// opacity see https://css-tricks.com/8-digit-hex-codes/
1677
-			$op_25 = $color_code."40"; // 25% opacity
1678
-
1679
-
1680
-			// button states
1681
-			$output .= $prefix ." .btn-secondary:hover{background-color: ".$darker_075.";    border-color: ".$darker_10.";} ";
1682
-			$output .= $prefix ." .btn-outline-secondary:not(:disabled):not(.disabled):active:focus, $prefix .btn-outline-secondary:not(:disabled):not(.disabled).active:focus, .show>$prefix .btn-outline-secondary.dropdown-toggle:focus{box-shadow: 0 0 0 0.2rem $op_25;} ";
1683
-			$output .= $prefix ." .btn-secondary:not(:disabled):not(.disabled):active, $prefix .btn-secondary:not(:disabled):not(.disabled).active, .show>$prefix .btn-secondary.dropdown-toggle{background-color: ".$darker_10.";    border-color: ".$darker_125.";} ";
1684
-			$output .= $prefix ." .btn-secondary:not(:disabled):not(.disabled):active:focus, $prefix .btn-secondary:not(:disabled):not(.disabled).active:focus, .show>$prefix .btn-secondary.dropdown-toggle:focus {box-shadow: 0 0 0 0.2rem $op_25;} ";
1685
-
1686
-
1687
-			return $output;
1688
-		}
1689
-
1690
-		/**
1691
-		 * Increases or decreases the brightness of a color by a percentage of the current brightness.
1692
-		 *
1693
-		 * @param   string  $hexCode        Supported formats: `#FFF`, `#FFFFFF`, `FFF`, `FFFFFF`
1694
-		 * @param   float   $adjustPercent  A number between -1 and 1. E.g. 0.3 = 30% lighter; -0.4 = 40% darker.
1695
-		 *
1696
-		 * @return  string
1697
-		 */
1698
-		public static function css_hex_lighten_darken($hexCode, $adjustPercent) {
1699
-			$hexCode = ltrim($hexCode, '#');
1700
-
1701
-			if (strlen($hexCode) == 3) {
1702
-				$hexCode = $hexCode[0] . $hexCode[0] . $hexCode[1] . $hexCode[1] . $hexCode[2] . $hexCode[2];
1703
-			}
1704
-
1705
-			$hexCode = array_map('hexdec', str_split($hexCode, 2));
1706
-
1707
-			foreach ($hexCode as & $color) {
1708
-				$adjustableLimit = $adjustPercent < 0 ? $color : 255 - $color;
1709
-				$adjustAmount = ceil($adjustableLimit * $adjustPercent);
1710
-
1711
-				$color = str_pad(dechex($color + $adjustAmount), 2, '0', STR_PAD_LEFT);
1712
-			}
1713
-
1714
-			return '#' . implode($hexCode);
1715
-		}
1716
-
1717
-		/**
1718
-		 * Check if we should display examples.
1719
-		 */
1720
-		public function maybe_show_examples(){
1721
-			if(current_user_can('manage_options') && isset($_REQUEST['preview-aui'])){
1722
-				echo "<head>";
1723
-				wp_head();
1724
-				echo "</head>";
1725
-				echo "<body>";
1726
-				echo $this->get_examples();
1727
-				echo "</body>";
1728
-				exit;
1729
-			}
1730
-		}
1731
-
1732
-		/**
1733
-		 * Get developer examples.
1734
-		 *
1735
-		 * @return string
1736
-		 */
1737
-		public function get_examples(){
1738
-			$output = '';
1739
-
1740
-
1741
-			// open form
1742
-			$output .= "<form class='p-5 m-5 border rounded'>";
1743
-
1744
-			// input example
1745
-			$output .= aui()->input(array(
1746
-				'type'  =>  'text',
1747
-				'id'    =>  'text-example',
1748
-				'name'    =>  'text-example',
1749
-				'placeholder'   => 'text placeholder',
1750
-				'title'   => 'Text input example',
1751
-				'value' =>  '',
1752
-				'required'  => false,
1753
-				'help_text' => 'help text',
1754
-				'label' => 'Text input example label'
1755
-			));
1756
-
1757
-			// input example
1758
-			$output .= aui()->input(array(
1759
-				'type'  =>  'url',
1760
-				'id'    =>  'text-example2',
1761
-				'name'    =>  'text-example',
1762
-				'placeholder'   => 'url placeholder',
1763
-				'title'   => 'Text input example',
1764
-				'value' =>  '',
1765
-				'required'  => false,
1766
-				'help_text' => 'help text',
1767
-				'label' => 'Text input example label'
1768
-			));
1769
-
1770
-			// checkbox example
1771
-			$output .= aui()->input(array(
1772
-				'type'  =>  'checkbox',
1773
-				'id'    =>  'checkbox-example',
1774
-				'name'    =>  'checkbox-example',
1775
-				'placeholder'   => 'checkbox-example',
1776
-				'title'   => 'Checkbox example',
1777
-				'value' =>  '1',
1778
-				'checked'   => true,
1779
-				'required'  => false,
1780
-				'help_text' => 'help text',
1781
-				'label' => 'Checkbox checked'
1782
-			));
1783
-
1784
-			// checkbox example
1785
-			$output .= aui()->input(array(
1786
-				'type'  =>  'checkbox',
1787
-				'id'    =>  'checkbox-example2',
1788
-				'name'    =>  'checkbox-example2',
1789
-				'placeholder'   => 'checkbox-example',
1790
-				'title'   => 'Checkbox example',
1791
-				'value' =>  '1',
1792
-				'checked'   => false,
1793
-				'required'  => false,
1794
-				'help_text' => 'help text',
1795
-				'label' => 'Checkbox un-checked'
1796
-			));
1797
-
1798
-			// switch example
1799
-			$output .= aui()->input(array(
1800
-				'type'  =>  'checkbox',
1801
-				'id'    =>  'switch-example',
1802
-				'name'    =>  'switch-example',
1803
-				'placeholder'   => 'checkbox-example',
1804
-				'title'   => 'Switch example',
1805
-				'value' =>  '1',
1806
-				'checked'   => true,
1807
-				'switch'    => true,
1808
-				'required'  => false,
1809
-				'help_text' => 'help text',
1810
-				'label' => 'Switch on'
1811
-			));
1812
-
1813
-			// switch example
1814
-			$output .= aui()->input(array(
1815
-				'type'  =>  'checkbox',
1816
-				'id'    =>  'switch-example2',
1817
-				'name'    =>  'switch-example2',
1818
-				'placeholder'   => 'checkbox-example',
1819
-				'title'   => 'Switch example',
1820
-				'value' =>  '1',
1821
-				'checked'   => false,
1822
-				'switch'    => true,
1823
-				'required'  => false,
1824
-				'help_text' => 'help text',
1825
-				'label' => 'Switch off'
1826
-			));
1827
-
1828
-			// close form
1829
-			$output .= "</form>";
1830
-
1831
-			return $output;
1832
-		}
1833
-
1834
-		/**
1835
-		 * Calendar params.
1836
-		 *
1837
-		 * @since 0.1.44
1838
-		 *
1839
-		 * @return array Calendar params.
1840
-		 */
1841
-		public static function calendar_params() {
1842
-			$params = array(
1843
-				'month_long_1' => __( 'January', 'aui' ),
1844
-				'month_long_2' => __( 'February', 'aui' ),
1845
-				'month_long_3' => __( 'March', 'aui' ),
1846
-				'month_long_4' => __( 'April', 'aui' ),
1847
-				'month_long_5' => __( 'May', 'aui' ),
1848
-				'month_long_6' => __( 'June', 'aui' ),
1849
-				'month_long_7' => __( 'July', 'aui' ),
1850
-				'month_long_8' => __( 'August', 'aui' ),
1851
-				'month_long_9' => __( 'September', 'aui' ),
1852
-				'month_long_10' => __( 'October', 'aui' ),
1853
-				'month_long_11' => __( 'November', 'aui' ),
1854
-				'month_long_12' => __( 'December', 'aui' ),
1855
-				'month_s_1' => _x( 'Jan', 'January abbreviation', 'aui' ),
1856
-				'month_s_2' => _x( 'Feb', 'February abbreviation', 'aui' ),
1857
-				'month_s_3' => _x( 'Mar', 'March abbreviation', 'aui' ),
1858
-				'month_s_4' => _x( 'Apr', 'April abbreviation', 'aui' ),
1859
-				'month_s_5' => _x( 'May', 'May abbreviation', 'aui' ),
1860
-				'month_s_6' => _x( 'Jun', 'June abbreviation', 'aui' ),
1861
-				'month_s_7' => _x( 'Jul', 'July abbreviation', 'aui' ),
1862
-				'month_s_8' => _x( 'Aug', 'August abbreviation', 'aui' ),
1863
-				'month_s_9' => _x( 'Sep', 'September abbreviation', 'aui' ),
1864
-				'month_s_10' => _x( 'Oct', 'October abbreviation', 'aui' ),
1865
-				'month_s_11' => _x( 'Nov', 'November abbreviation', 'aui' ),
1866
-				'month_s_12' => _x( 'Dec', 'December abbreviation', 'aui' ),
1867
-				'day_s1_1' => _x( 'S', 'Sunday initial', 'aui' ),
1868
-				'day_s1_2' => _x( 'M', 'Monday initial', 'aui' ),
1869
-				'day_s1_3' => _x( 'T', 'Tuesday initial', 'aui' ),
1870
-				'day_s1_4' => _x( 'W', 'Wednesday initial', 'aui' ),
1871
-				'day_s1_5' => _x( 'T', 'Friday initial', 'aui' ),
1872
-				'day_s1_6' => _x( 'F', 'Thursday initial', 'aui' ),
1873
-				'day_s1_7' => _x( 'S', 'Saturday initial', 'aui' ),
1874
-				'day_s2_1' => __( 'Su', 'aui' ),
1875
-				'day_s2_2' => __( 'Mo', 'aui' ),
1876
-				'day_s2_3' => __( 'Tu', 'aui' ),
1877
-				'day_s2_4' => __( 'We', 'aui' ),
1878
-				'day_s2_5' => __( 'Th', 'aui' ),
1879
-				'day_s2_6' => __( 'Fr', 'aui' ),
1880
-				'day_s2_7' => __( 'Sa', 'aui' ),
1881
-				'day_s3_1' => __( 'Sun', 'aui' ),
1882
-				'day_s3_2' => __( 'Mon', 'aui' ),
1883
-				'day_s3_3' => __( 'Tue', 'aui' ),
1884
-				'day_s3_4' => __( 'Wed', 'aui' ),
1885
-				'day_s3_5' => __( 'Thu', 'aui' ),
1886
-				'day_s3_6' => __( 'Fri', 'aui' ),
1887
-				'day_s3_7' => __( 'Sat', 'aui' ),
1888
-				'day_s5_1' => __( 'Sunday', 'aui' ),
1889
-				'day_s5_2' => __( 'Monday', 'aui' ),
1890
-				'day_s5_3' => __( 'Tuesday', 'aui' ),
1891
-				'day_s5_4' => __( 'Wednesday', 'aui' ),
1892
-				'day_s5_5' => __( 'Thursday', 'aui' ),
1893
-				'day_s5_6' => __( 'Friday', 'aui' ),
1894
-				'day_s5_7' => __( 'Saturday', 'aui' ),
1895
-				'am_lower' => __( 'am', 'aui' ),
1896
-				'pm_lower' => __( 'pm', 'aui' ),
1897
-				'am_upper' => __( 'AM', 'aui' ),
1898
-				'pm_upper' => __( 'PM', 'aui' ),
1899
-				'firstDayOfWeek' => (int) get_option( 'start_of_week' ),
1900
-				'time_24hr' => false,
1901
-				'year' => __( 'Year', 'aui' ),
1902
-				'hour' => __( 'Hour', 'aui' ),
1903
-				'minute' => __( 'Minute', 'aui' ),
1904
-				'weekAbbreviation' => __( 'Wk', 'aui' ),
1905
-				'rangeSeparator' => __( ' to ', 'aui' ),
1906
-				'scrollTitle' => __( 'Scroll to increment', 'aui' ),
1907
-				'toggleTitle' => __( 'Click to toggle', 'aui' )
1908
-			);
1909
-
1910
-			return apply_filters( 'ayecode_ui_calendar_params', $params );
1911
-		}
1912
-
1913
-		/**
1914
-		 * Flatpickr calendar localize.
1915
-		 *
1916
-		 * @since 0.1.44
1917
-		 *
1918
-		 * @return string Calendar locale.
1919
-		 */
1920
-		public static function flatpickr_locale() {
1921
-			$params = self::calendar_params();
1922
-
1923
-			if ( is_string( $params ) ) {
1924
-				$params = html_entity_decode( $params, ENT_QUOTES, 'UTF-8' );
1925
-			} else {
1926
-				foreach ( (array) $params as $key => $value ) {
1927
-					if ( ! is_scalar( $value ) ) {
1928
-						continue;
1929
-					}
1930
-
1931
-					$params[ $key ] = html_entity_decode( (string) $value, ENT_QUOTES, 'UTF-8' );
1932
-				}
1933
-			}
1457
+                '.nav-pills .nav-link.active' => array('b'),
1458
+                '.nav-pills .show>.nav-link' => array('b'),
1459
+                '.page-link' => array('c'),
1460
+                '.page-item.active .page-link' => array('b','o'),
1461
+                '.badge-primary' => array('b'),
1462
+                '.alert-primary' => array('b','o'),
1463
+                '.progress-bar' => array('b'),
1464
+                '.list-group-item.active' => array('b','o'),
1465
+                '.bg-primary' => array('b','f'),
1466
+                '.btn-link.btn-primary' => array('c'),
1467
+                '.select2-container .select2-results__option--highlighted.select2-results__option[aria-selected=true]' => array('b'),
1468
+            );
1469
+
1470
+            $important_selectors = array(
1471
+                '.bg-primary' => array('b','f'),
1472
+                '.border-primary' => array('o'),
1473
+                '.text-primary' => array('c'),
1474
+            );
1475
+
1476
+            $color = array();
1477
+            $color_i = array();
1478
+            $background = array();
1479
+            $background_i = array();
1480
+            $border = array();
1481
+            $border_i = array();
1482
+            $fill = array();
1483
+            $fill_i = array();
1484
+
1485
+            $output = '';
1486
+
1487
+            // build rules into each type
1488
+            foreach($selectors as $selector => $types){
1489
+                $selector = $compatibility ? ".bsui ".$selector : $selector;
1490
+                $types = array_combine($types,$types);
1491
+                if(isset($types['c'])){$color[] = $selector;}
1492
+                if(isset($types['b'])){$background[] = $selector;}
1493
+                if(isset($types['o'])){$border[] = $selector;}
1494
+                if(isset($types['f'])){$fill[] = $selector;}
1495
+            }
1496
+
1497
+            // build rules into each type
1498
+            foreach($important_selectors as $selector => $types){
1499
+                $selector = $compatibility ? ".bsui ".$selector : $selector;
1500
+                $types = array_combine($types,$types);
1501
+                if(isset($types['c'])){$color_i[] = $selector;}
1502
+                if(isset($types['b'])){$background_i[] = $selector;}
1503
+                if(isset($types['o'])){$border_i[] = $selector;}
1504
+                if(isset($types['f'])){$fill_i[] = $selector;}
1505
+            }
1506
+
1507
+            // add any color rules
1508
+            if(!empty($color)){
1509
+                $output .= implode(",",$color) . "{color: $color_code;} ";
1510
+            }
1511
+            if(!empty($color_i)){
1512
+                $output .= implode(",",$color_i) . "{color: $color_code !important;} ";
1513
+            }
1514
+
1515
+            // add any background color rules
1516
+            if(!empty($background)){
1517
+                $output .= implode(",",$background) . "{background-color: $color_code;} ";
1518
+            }
1519
+            if(!empty($background_i)){
1520
+                $output .= implode(",",$background_i) . "{background-color: $color_code !important;} ";
1521
+            }
1522
+
1523
+            // add any border color rules
1524
+            if(!empty($border)){
1525
+                $output .= implode(",",$border) . "{border-color: $color_code;} ";
1526
+            }
1527
+            if(!empty($border_i)){
1528
+                $output .= implode(",",$border_i) . "{border-color: $color_code !important;} ";
1529
+            }
1530
+
1531
+            // add any fill color rules
1532
+            if(!empty($fill)){
1533
+                $output .= implode(",",$fill) . "{fill: $color_code;} ";
1534
+            }
1535
+            if(!empty($fill_i)){
1536
+                $output .= implode(",",$fill_i) . "{fill: $color_code !important;} ";
1537
+            }
1538
+
1539
+
1540
+            $prefix = $compatibility ? ".bsui " : "";
1541
+
1542
+            // darken
1543
+            $darker_075 = self::css_hex_lighten_darken($color_code,"-0.075");
1544
+            $darker_10 = self::css_hex_lighten_darken($color_code,"-0.10");
1545
+            $darker_125 = self::css_hex_lighten_darken($color_code,"-0.125");
1546
+
1547
+            // lighten
1548
+            $lighten_25 = self::css_hex_lighten_darken($color_code,"0.25");
1549
+
1550
+            // opacity see https://css-tricks.com/8-digit-hex-codes/
1551
+            $op_25 = $color_code."40"; // 25% opacity
1552
+
1553
+
1554
+            // button states
1555
+            $output .= $prefix ." .btn-primary:hover{background-color: ".$darker_075.";    border-color: ".$darker_10.";} ";
1556
+            $output .= $prefix ." .btn-outline-primary:not(:disabled):not(.disabled):active:focus, $prefix .btn-outline-primary:not(:disabled):not(.disabled).active:focus, .show>$prefix .btn-outline-primary.dropdown-toggle:focus{box-shadow: 0 0 0 0.2rem $op_25;} ";
1557
+            $output .= $prefix ." .btn-primary:not(:disabled):not(.disabled):active, $prefix .btn-primary:not(:disabled):not(.disabled).active, .show>$prefix .btn-primary.dropdown-toggle{background-color: ".$darker_10.";    border-color: ".$darker_125.";} ";
1558
+            $output .= $prefix ." .btn-primary:not(:disabled):not(.disabled):active:focus, $prefix .btn-primary:not(:disabled):not(.disabled).active:focus, .show>$prefix .btn-primary.dropdown-toggle:focus {box-shadow: 0 0 0 0.2rem $op_25;} ";
1559
+
1560
+
1561
+            // dropdown's
1562
+            $output .= $prefix ." .dropdown-item.active, $prefix .dropdown-item:active{background-color: $color_code;} ";
1563
+
1564
+
1565
+            // input states
1566
+            $output .= $prefix ." .form-control:focus{border-color: ".$lighten_25.";box-shadow: 0 0 0 0.2rem $op_25;} ";
1567
+
1568
+            // page link
1569
+            $output .= $prefix ." .page-link:focus{box-shadow: 0 0 0 0.2rem $op_25;} ";
1570
+
1571
+            return $output;
1572
+        }
1573
+
1574
+        public static function css_secondary($color_code,$compatibility){;
1575
+            $color_code = sanitize_hex_color($color_code);
1576
+            if(!$color_code){return '';}
1577
+            /**
1578
+             * c = color, b = background color, o = border-color, f = fill
1579
+             */
1580
+            $selectors = array(
1581
+                '.btn-secondary' => array('b','o'),
1582
+                '.btn-secondary.disabled' => array('b','o'),
1583
+                '.btn-secondary:disabled' => array('b','o'),
1584
+                '.btn-outline-secondary' => array('c','o'),
1585
+                '.btn-outline-secondary:hover' => array('b','o'),
1586
+                '.btn-outline-secondary.disabled' => array('c'),
1587
+                '.btn-outline-secondary:disabled' => array('c'),
1588
+                '.btn-outline-secondary:not(:disabled):not(.disabled):active' => array('b','o'),
1589
+                '.btn-outline-secondary:not(:disabled):not(.disabled).active' => array('b','o'),
1590
+                '.btn-outline-secondary.dropdown-toggle' => array('b','o'),
1591
+                '.badge-secondary' => array('b'),
1592
+                '.alert-secondary' => array('b','o'),
1593
+                '.btn-link.btn-secondary' => array('c'),
1594
+            );
1595
+
1596
+            $important_selectors = array(
1597
+                '.bg-secondary' => array('b','f'),
1598
+                '.border-secondary' => array('o'),
1599
+                '.text-secondary' => array('c'),
1600
+            );
1601
+
1602
+            $color = array();
1603
+            $color_i = array();
1604
+            $background = array();
1605
+            $background_i = array();
1606
+            $border = array();
1607
+            $border_i = array();
1608
+            $fill = array();
1609
+            $fill_i = array();
1610
+
1611
+            $output = '';
1612
+
1613
+            // build rules into each type
1614
+            foreach($selectors as $selector => $types){
1615
+                $selector = $compatibility ? ".bsui ".$selector : $selector;
1616
+                $types = array_combine($types,$types);
1617
+                if(isset($types['c'])){$color[] = $selector;}
1618
+                if(isset($types['b'])){$background[] = $selector;}
1619
+                if(isset($types['o'])){$border[] = $selector;}
1620
+                if(isset($types['f'])){$fill[] = $selector;}
1621
+            }
1622
+
1623
+            // build rules into each type
1624
+            foreach($important_selectors as $selector => $types){
1625
+                $selector = $compatibility ? ".bsui ".$selector : $selector;
1626
+                $types = array_combine($types,$types);
1627
+                if(isset($types['c'])){$color_i[] = $selector;}
1628
+                if(isset($types['b'])){$background_i[] = $selector;}
1629
+                if(isset($types['o'])){$border_i[] = $selector;}
1630
+                if(isset($types['f'])){$fill_i[] = $selector;}
1631
+            }
1632
+
1633
+            // add any color rules
1634
+            if(!empty($color)){
1635
+                $output .= implode(",",$color) . "{color: $color_code;} ";
1636
+            }
1637
+            if(!empty($color_i)){
1638
+                $output .= implode(",",$color_i) . "{color: $color_code !important;} ";
1639
+            }
1640
+
1641
+            // add any background color rules
1642
+            if(!empty($background)){
1643
+                $output .= implode(",",$background) . "{background-color: $color_code;} ";
1644
+            }
1645
+            if(!empty($background_i)){
1646
+                $output .= implode(",",$background_i) . "{background-color: $color_code !important;} ";
1647
+            }
1648
+
1649
+            // add any border color rules
1650
+            if(!empty($border)){
1651
+                $output .= implode(",",$border) . "{border-color: $color_code;} ";
1652
+            }
1653
+            if(!empty($border_i)){
1654
+                $output .= implode(",",$border_i) . "{border-color: $color_code !important;} ";
1655
+            }
1656
+
1657
+            // add any fill color rules
1658
+            if(!empty($fill)){
1659
+                $output .= implode(",",$fill) . "{fill: $color_code;} ";
1660
+            }
1661
+            if(!empty($fill_i)){
1662
+                $output .= implode(",",$fill_i) . "{fill: $color_code !important;} ";
1663
+            }
1664
+
1665
+
1666
+            $prefix = $compatibility ? ".bsui " : "";
1667
+
1668
+            // darken
1669
+            $darker_075 = self::css_hex_lighten_darken($color_code,"-0.075");
1670
+            $darker_10 = self::css_hex_lighten_darken($color_code,"-0.10");
1671
+            $darker_125 = self::css_hex_lighten_darken($color_code,"-0.125");
1672
+
1673
+            // lighten
1674
+            $lighten_25 = self::css_hex_lighten_darken($color_code,"0.25");
1675
+
1676
+            // opacity see https://css-tricks.com/8-digit-hex-codes/
1677
+            $op_25 = $color_code."40"; // 25% opacity
1678
+
1679
+
1680
+            // button states
1681
+            $output .= $prefix ." .btn-secondary:hover{background-color: ".$darker_075.";    border-color: ".$darker_10.";} ";
1682
+            $output .= $prefix ." .btn-outline-secondary:not(:disabled):not(.disabled):active:focus, $prefix .btn-outline-secondary:not(:disabled):not(.disabled).active:focus, .show>$prefix .btn-outline-secondary.dropdown-toggle:focus{box-shadow: 0 0 0 0.2rem $op_25;} ";
1683
+            $output .= $prefix ." .btn-secondary:not(:disabled):not(.disabled):active, $prefix .btn-secondary:not(:disabled):not(.disabled).active, .show>$prefix .btn-secondary.dropdown-toggle{background-color: ".$darker_10.";    border-color: ".$darker_125.";} ";
1684
+            $output .= $prefix ." .btn-secondary:not(:disabled):not(.disabled):active:focus, $prefix .btn-secondary:not(:disabled):not(.disabled).active:focus, .show>$prefix .btn-secondary.dropdown-toggle:focus {box-shadow: 0 0 0 0.2rem $op_25;} ";
1685
+
1686
+
1687
+            return $output;
1688
+        }
1689
+
1690
+        /**
1691
+         * Increases or decreases the brightness of a color by a percentage of the current brightness.
1692
+         *
1693
+         * @param   string  $hexCode        Supported formats: `#FFF`, `#FFFFFF`, `FFF`, `FFFFFF`
1694
+         * @param   float   $adjustPercent  A number between -1 and 1. E.g. 0.3 = 30% lighter; -0.4 = 40% darker.
1695
+         *
1696
+         * @return  string
1697
+         */
1698
+        public static function css_hex_lighten_darken($hexCode, $adjustPercent) {
1699
+            $hexCode = ltrim($hexCode, '#');
1700
+
1701
+            if (strlen($hexCode) == 3) {
1702
+                $hexCode = $hexCode[0] . $hexCode[0] . $hexCode[1] . $hexCode[1] . $hexCode[2] . $hexCode[2];
1703
+            }
1704
+
1705
+            $hexCode = array_map('hexdec', str_split($hexCode, 2));
1706
+
1707
+            foreach ($hexCode as & $color) {
1708
+                $adjustableLimit = $adjustPercent < 0 ? $color : 255 - $color;
1709
+                $adjustAmount = ceil($adjustableLimit * $adjustPercent);
1710
+
1711
+                $color = str_pad(dechex($color + $adjustAmount), 2, '0', STR_PAD_LEFT);
1712
+            }
1713
+
1714
+            return '#' . implode($hexCode);
1715
+        }
1716
+
1717
+        /**
1718
+         * Check if we should display examples.
1719
+         */
1720
+        public function maybe_show_examples(){
1721
+            if(current_user_can('manage_options') && isset($_REQUEST['preview-aui'])){
1722
+                echo "<head>";
1723
+                wp_head();
1724
+                echo "</head>";
1725
+                echo "<body>";
1726
+                echo $this->get_examples();
1727
+                echo "</body>";
1728
+                exit;
1729
+            }
1730
+        }
1731
+
1732
+        /**
1733
+         * Get developer examples.
1734
+         *
1735
+         * @return string
1736
+         */
1737
+        public function get_examples(){
1738
+            $output = '';
1739
+
1740
+
1741
+            // open form
1742
+            $output .= "<form class='p-5 m-5 border rounded'>";
1743
+
1744
+            // input example
1745
+            $output .= aui()->input(array(
1746
+                'type'  =>  'text',
1747
+                'id'    =>  'text-example',
1748
+                'name'    =>  'text-example',
1749
+                'placeholder'   => 'text placeholder',
1750
+                'title'   => 'Text input example',
1751
+                'value' =>  '',
1752
+                'required'  => false,
1753
+                'help_text' => 'help text',
1754
+                'label' => 'Text input example label'
1755
+            ));
1756
+
1757
+            // input example
1758
+            $output .= aui()->input(array(
1759
+                'type'  =>  'url',
1760
+                'id'    =>  'text-example2',
1761
+                'name'    =>  'text-example',
1762
+                'placeholder'   => 'url placeholder',
1763
+                'title'   => 'Text input example',
1764
+                'value' =>  '',
1765
+                'required'  => false,
1766
+                'help_text' => 'help text',
1767
+                'label' => 'Text input example label'
1768
+            ));
1769
+
1770
+            // checkbox example
1771
+            $output .= aui()->input(array(
1772
+                'type'  =>  'checkbox',
1773
+                'id'    =>  'checkbox-example',
1774
+                'name'    =>  'checkbox-example',
1775
+                'placeholder'   => 'checkbox-example',
1776
+                'title'   => 'Checkbox example',
1777
+                'value' =>  '1',
1778
+                'checked'   => true,
1779
+                'required'  => false,
1780
+                'help_text' => 'help text',
1781
+                'label' => 'Checkbox checked'
1782
+            ));
1783
+
1784
+            // checkbox example
1785
+            $output .= aui()->input(array(
1786
+                'type'  =>  'checkbox',
1787
+                'id'    =>  'checkbox-example2',
1788
+                'name'    =>  'checkbox-example2',
1789
+                'placeholder'   => 'checkbox-example',
1790
+                'title'   => 'Checkbox example',
1791
+                'value' =>  '1',
1792
+                'checked'   => false,
1793
+                'required'  => false,
1794
+                'help_text' => 'help text',
1795
+                'label' => 'Checkbox un-checked'
1796
+            ));
1797
+
1798
+            // switch example
1799
+            $output .= aui()->input(array(
1800
+                'type'  =>  'checkbox',
1801
+                'id'    =>  'switch-example',
1802
+                'name'    =>  'switch-example',
1803
+                'placeholder'   => 'checkbox-example',
1804
+                'title'   => 'Switch example',
1805
+                'value' =>  '1',
1806
+                'checked'   => true,
1807
+                'switch'    => true,
1808
+                'required'  => false,
1809
+                'help_text' => 'help text',
1810
+                'label' => 'Switch on'
1811
+            ));
1812
+
1813
+            // switch example
1814
+            $output .= aui()->input(array(
1815
+                'type'  =>  'checkbox',
1816
+                'id'    =>  'switch-example2',
1817
+                'name'    =>  'switch-example2',
1818
+                'placeholder'   => 'checkbox-example',
1819
+                'title'   => 'Switch example',
1820
+                'value' =>  '1',
1821
+                'checked'   => false,
1822
+                'switch'    => true,
1823
+                'required'  => false,
1824
+                'help_text' => 'help text',
1825
+                'label' => 'Switch off'
1826
+            ));
1827
+
1828
+            // close form
1829
+            $output .= "</form>";
1830
+
1831
+            return $output;
1832
+        }
1833
+
1834
+        /**
1835
+         * Calendar params.
1836
+         *
1837
+         * @since 0.1.44
1838
+         *
1839
+         * @return array Calendar params.
1840
+         */
1841
+        public static function calendar_params() {
1842
+            $params = array(
1843
+                'month_long_1' => __( 'January', 'aui' ),
1844
+                'month_long_2' => __( 'February', 'aui' ),
1845
+                'month_long_3' => __( 'March', 'aui' ),
1846
+                'month_long_4' => __( 'April', 'aui' ),
1847
+                'month_long_5' => __( 'May', 'aui' ),
1848
+                'month_long_6' => __( 'June', 'aui' ),
1849
+                'month_long_7' => __( 'July', 'aui' ),
1850
+                'month_long_8' => __( 'August', 'aui' ),
1851
+                'month_long_9' => __( 'September', 'aui' ),
1852
+                'month_long_10' => __( 'October', 'aui' ),
1853
+                'month_long_11' => __( 'November', 'aui' ),
1854
+                'month_long_12' => __( 'December', 'aui' ),
1855
+                'month_s_1' => _x( 'Jan', 'January abbreviation', 'aui' ),
1856
+                'month_s_2' => _x( 'Feb', 'February abbreviation', 'aui' ),
1857
+                'month_s_3' => _x( 'Mar', 'March abbreviation', 'aui' ),
1858
+                'month_s_4' => _x( 'Apr', 'April abbreviation', 'aui' ),
1859
+                'month_s_5' => _x( 'May', 'May abbreviation', 'aui' ),
1860
+                'month_s_6' => _x( 'Jun', 'June abbreviation', 'aui' ),
1861
+                'month_s_7' => _x( 'Jul', 'July abbreviation', 'aui' ),
1862
+                'month_s_8' => _x( 'Aug', 'August abbreviation', 'aui' ),
1863
+                'month_s_9' => _x( 'Sep', 'September abbreviation', 'aui' ),
1864
+                'month_s_10' => _x( 'Oct', 'October abbreviation', 'aui' ),
1865
+                'month_s_11' => _x( 'Nov', 'November abbreviation', 'aui' ),
1866
+                'month_s_12' => _x( 'Dec', 'December abbreviation', 'aui' ),
1867
+                'day_s1_1' => _x( 'S', 'Sunday initial', 'aui' ),
1868
+                'day_s1_2' => _x( 'M', 'Monday initial', 'aui' ),
1869
+                'day_s1_3' => _x( 'T', 'Tuesday initial', 'aui' ),
1870
+                'day_s1_4' => _x( 'W', 'Wednesday initial', 'aui' ),
1871
+                'day_s1_5' => _x( 'T', 'Friday initial', 'aui' ),
1872
+                'day_s1_6' => _x( 'F', 'Thursday initial', 'aui' ),
1873
+                'day_s1_7' => _x( 'S', 'Saturday initial', 'aui' ),
1874
+                'day_s2_1' => __( 'Su', 'aui' ),
1875
+                'day_s2_2' => __( 'Mo', 'aui' ),
1876
+                'day_s2_3' => __( 'Tu', 'aui' ),
1877
+                'day_s2_4' => __( 'We', 'aui' ),
1878
+                'day_s2_5' => __( 'Th', 'aui' ),
1879
+                'day_s2_6' => __( 'Fr', 'aui' ),
1880
+                'day_s2_7' => __( 'Sa', 'aui' ),
1881
+                'day_s3_1' => __( 'Sun', 'aui' ),
1882
+                'day_s3_2' => __( 'Mon', 'aui' ),
1883
+                'day_s3_3' => __( 'Tue', 'aui' ),
1884
+                'day_s3_4' => __( 'Wed', 'aui' ),
1885
+                'day_s3_5' => __( 'Thu', 'aui' ),
1886
+                'day_s3_6' => __( 'Fri', 'aui' ),
1887
+                'day_s3_7' => __( 'Sat', 'aui' ),
1888
+                'day_s5_1' => __( 'Sunday', 'aui' ),
1889
+                'day_s5_2' => __( 'Monday', 'aui' ),
1890
+                'day_s5_3' => __( 'Tuesday', 'aui' ),
1891
+                'day_s5_4' => __( 'Wednesday', 'aui' ),
1892
+                'day_s5_5' => __( 'Thursday', 'aui' ),
1893
+                'day_s5_6' => __( 'Friday', 'aui' ),
1894
+                'day_s5_7' => __( 'Saturday', 'aui' ),
1895
+                'am_lower' => __( 'am', 'aui' ),
1896
+                'pm_lower' => __( 'pm', 'aui' ),
1897
+                'am_upper' => __( 'AM', 'aui' ),
1898
+                'pm_upper' => __( 'PM', 'aui' ),
1899
+                'firstDayOfWeek' => (int) get_option( 'start_of_week' ),
1900
+                'time_24hr' => false,
1901
+                'year' => __( 'Year', 'aui' ),
1902
+                'hour' => __( 'Hour', 'aui' ),
1903
+                'minute' => __( 'Minute', 'aui' ),
1904
+                'weekAbbreviation' => __( 'Wk', 'aui' ),
1905
+                'rangeSeparator' => __( ' to ', 'aui' ),
1906
+                'scrollTitle' => __( 'Scroll to increment', 'aui' ),
1907
+                'toggleTitle' => __( 'Click to toggle', 'aui' )
1908
+            );
1909
+
1910
+            return apply_filters( 'ayecode_ui_calendar_params', $params );
1911
+        }
1912
+
1913
+        /**
1914
+         * Flatpickr calendar localize.
1915
+         *
1916
+         * @since 0.1.44
1917
+         *
1918
+         * @return string Calendar locale.
1919
+         */
1920
+        public static function flatpickr_locale() {
1921
+            $params = self::calendar_params();
1922
+
1923
+            if ( is_string( $params ) ) {
1924
+                $params = html_entity_decode( $params, ENT_QUOTES, 'UTF-8' );
1925
+            } else {
1926
+                foreach ( (array) $params as $key => $value ) {
1927
+                    if ( ! is_scalar( $value ) ) {
1928
+                        continue;
1929
+                    }
1930
+
1931
+                    $params[ $key ] = html_entity_decode( (string) $value, ENT_QUOTES, 'UTF-8' );
1932
+                }
1933
+            }
1934 1934
 
1935
-			$day_s3 = array();
1936
-			$day_s5 = array();
1935
+            $day_s3 = array();
1936
+            $day_s5 = array();
1937 1937
 
1938
-			for ( $i = 1; $i <= 7; $i ++ ) {
1939
-				$day_s3[] = addslashes( $params[ 'day_s3_' . $i ] );
1940
-				$day_s5[] = addslashes( $params[ 'day_s3_' . $i ] );
1941
-			}
1938
+            for ( $i = 1; $i <= 7; $i ++ ) {
1939
+                $day_s3[] = addslashes( $params[ 'day_s3_' . $i ] );
1940
+                $day_s5[] = addslashes( $params[ 'day_s3_' . $i ] );
1941
+            }
1942 1942
 
1943
-			$month_s = array();
1944
-			$month_long = array();
1943
+            $month_s = array();
1944
+            $month_long = array();
1945 1945
 
1946
-			for ( $i = 1; $i <= 12; $i ++ ) {
1947
-				$month_s[] = addslashes( $params[ 'month_s_' . $i ] );
1948
-				$month_long[] = addslashes( $params[ 'month_long_' . $i ] );
1949
-			}
1946
+            for ( $i = 1; $i <= 12; $i ++ ) {
1947
+                $month_s[] = addslashes( $params[ 'month_s_' . $i ] );
1948
+                $month_long[] = addslashes( $params[ 'month_long_' . $i ] );
1949
+            }
1950 1950
 
1951 1951
 ob_start();
1952 1952
 if ( 0 ) { ?><script><?php } ?>
@@ -1988,62 +1988,62 @@  discard block
 block discarded – undo
1988 1988
 }
1989 1989
 <?php if ( 0 ) { ?></script><?php } ?>
1990 1990
 <?php
1991
-			$locale = ob_get_clean();
1992
-
1993
-			return apply_filters( 'ayecode_ui_flatpickr_locale', trim( $locale ) );
1994
-		}
1995
-
1996
-		/**
1997
-		 * Select2 JS params.
1998
-		 *
1999
-		 * @since 0.1.44
2000
-		 *
2001
-		 * @return array Select2 JS params.
2002
-		 */
2003
-		public static function select2_params() {
2004
-			$params = array(
2005
-				'i18n_select_state_text'    => esc_attr__( 'Select an option&hellip;', 'aui' ),
2006
-				'i18n_no_matches'           => _x( 'No matches found', 'enhanced select', 'aui' ),
2007
-				'i18n_ajax_error'           => _x( 'Loading failed', 'enhanced select', 'aui' ),
2008
-				'i18n_input_too_short_1'    => _x( 'Please enter 1 or more characters', 'enhanced select', 'aui' ),
2009
-				'i18n_input_too_short_n'    => _x( 'Please enter %item% or more characters', 'enhanced select', 'aui' ),
2010
-				'i18n_input_too_long_1'     => _x( 'Please delete 1 character', 'enhanced select', 'aui' ),
2011
-				'i18n_input_too_long_n'     => _x( 'Please delete %item% characters', 'enhanced select', 'aui' ),
2012
-				'i18n_selection_too_long_1' => _x( 'You can only select 1 item', 'enhanced select', 'aui' ),
2013
-				'i18n_selection_too_long_n' => _x( 'You can only select %item% items', 'enhanced select', 'aui' ),
2014
-				'i18n_load_more'            => _x( 'Loading more results&hellip;', 'enhanced select', 'aui' ),
2015
-				'i18n_searching'            => _x( 'Searching&hellip;', 'enhanced select', 'aui' )
2016
-			);
2017
-
2018
-			return apply_filters( 'ayecode_ui_select2_params', $params );
2019
-		}
2020
-
2021
-		/**
2022
-		 * Select2 JS localize.
2023
-		 *
2024
-		 * @since 0.1.44
2025
-		 *
2026
-		 * @return string Select2 JS locale.
2027
-		 */
2028
-		public static function select2_locale() {
2029
-			$params = self::select2_params();
2030
-
2031
-			foreach ( (array) $params as $key => $value ) {
2032
-				if ( ! is_scalar( $value ) ) {
2033
-					continue;
2034
-				}
1991
+            $locale = ob_get_clean();
1992
+
1993
+            return apply_filters( 'ayecode_ui_flatpickr_locale', trim( $locale ) );
1994
+        }
1995
+
1996
+        /**
1997
+         * Select2 JS params.
1998
+         *
1999
+         * @since 0.1.44
2000
+         *
2001
+         * @return array Select2 JS params.
2002
+         */
2003
+        public static function select2_params() {
2004
+            $params = array(
2005
+                'i18n_select_state_text'    => esc_attr__( 'Select an option&hellip;', 'aui' ),
2006
+                'i18n_no_matches'           => _x( 'No matches found', 'enhanced select', 'aui' ),
2007
+                'i18n_ajax_error'           => _x( 'Loading failed', 'enhanced select', 'aui' ),
2008
+                'i18n_input_too_short_1'    => _x( 'Please enter 1 or more characters', 'enhanced select', 'aui' ),
2009
+                'i18n_input_too_short_n'    => _x( 'Please enter %item% or more characters', 'enhanced select', 'aui' ),
2010
+                'i18n_input_too_long_1'     => _x( 'Please delete 1 character', 'enhanced select', 'aui' ),
2011
+                'i18n_input_too_long_n'     => _x( 'Please delete %item% characters', 'enhanced select', 'aui' ),
2012
+                'i18n_selection_too_long_1' => _x( 'You can only select 1 item', 'enhanced select', 'aui' ),
2013
+                'i18n_selection_too_long_n' => _x( 'You can only select %item% items', 'enhanced select', 'aui' ),
2014
+                'i18n_load_more'            => _x( 'Loading more results&hellip;', 'enhanced select', 'aui' ),
2015
+                'i18n_searching'            => _x( 'Searching&hellip;', 'enhanced select', 'aui' )
2016
+            );
2017
+
2018
+            return apply_filters( 'ayecode_ui_select2_params', $params );
2019
+        }
2020
+
2021
+        /**
2022
+         * Select2 JS localize.
2023
+         *
2024
+         * @since 0.1.44
2025
+         *
2026
+         * @return string Select2 JS locale.
2027
+         */
2028
+        public static function select2_locale() {
2029
+            $params = self::select2_params();
2030
+
2031
+            foreach ( (array) $params as $key => $value ) {
2032
+                if ( ! is_scalar( $value ) ) {
2033
+                    continue;
2034
+                }
2035 2035
 
2036
-				$params[ $key ] = html_entity_decode( (string) $value, ENT_QUOTES, 'UTF-8' );
2037
-			}
2036
+                $params[ $key ] = html_entity_decode( (string) $value, ENT_QUOTES, 'UTF-8' );
2037
+            }
2038 2038
 
2039
-			$locale = json_encode( $params );
2039
+            $locale = json_encode( $params );
2040 2040
 
2041
-			return apply_filters( 'ayecode_ui_select2_locale', trim( $locale ) );
2042
-		}
2043
-	}
2041
+            return apply_filters( 'ayecode_ui_select2_locale', trim( $locale ) );
2042
+        }
2043
+    }
2044 2044
 
2045
-	/**
2046
-	 * Run the class if found.
2047
-	 */
2048
-	AyeCode_UI_Settings::instance();
2045
+    /**
2046
+     * Run the class if found.
2047
+     */
2048
+    AyeCode_UI_Settings::instance();
2049 2049
 }
2050 2050
\ No newline at end of file
Please login to merge, or discard this patch.
includes/gateways/class-getpaid-paypal-gateway-ipn-handler.php 1 patch
Indentation   +386 added lines, -386 removed lines patch added patch discarded remove patch
@@ -12,461 +12,461 @@
 block discarded – undo
12 12
  */
13 13
 class GetPaid_Paypal_Gateway_IPN_Handler {
14 14
 
15
-	/**
16
-	 * Payment method id.
17
-	 *
18
-	 * @var string
19
-	 */
20
-	protected $id = 'paypal';
21
-
22
-	/**
23
-	 * Payment method object.
24
-	 *
25
-	 * @var GetPaid_Paypal_Gateway
26
-	 */
27
-	protected $gateway;
28
-
29
-	/**
30
-	 * Class constructor.
31
-	 *
32
-	 * @param GetPaid_Paypal_Gateway $gateway
33
-	 */
34
-	public function __construct( $gateway ) {
35
-		$this->gateway = $gateway;
36
-		$this->verify_ipn();
37
-	}
38
-
39
-	/**
40
-	 * Processes ipns and marks payments as complete.
41
-	 *
42
-	 * @return void
43
-	 */
44
-	public function verify_ipn() {
45
-
46
-		wpinv_error_log( 'GetPaid PayPal IPN Handler', false );
47
-
48
-		// Validate the IPN.
49
-		if ( empty( $_POST ) || ! $this->validate_ipn() ) {
50
-			wp_die( 'PayPal IPN Request Failure', 500 );
51
-		}
52
-
53
-		// Process the IPN.
54
-		$posted  = wp_unslash( $_POST );
55
-		$invoice = $this->get_ipn_invoice( $posted );
56
-
57
-		// Abort if it was not paid by our gateway.
58
-		if ( $this->id != $invoice->get_gateway() ) {
59
-			wpinv_error_log( 'Aborting, Invoice was not paid via PayPal', false );
60
-			wp_die( 'Invoice not paid via PayPal', 200 );
61
-		}
62
-
63
-		$posted['payment_status'] = isset( $posted['payment_status'] ) ? sanitize_key( strtolower( $posted['payment_status'] ) ) : '';
64
-		$posted['txn_type']       = sanitize_key( strtolower( $posted['txn_type'] ) );
65
-
66
-		wpinv_error_log( 'Payment status:' . $posted['payment_status'], false );
67
-		wpinv_error_log( 'IPN Type:' . $posted['txn_type'], false );
68
-
69
-		if ( method_exists( $this, 'ipn_txn_' . $posted['txn_type'] ) ) {
70
-			call_user_func( array( $this, 'ipn_txn_' . $posted['txn_type'] ), $invoice, $posted );
71
-			wpinv_error_log( 'Done processing IPN', false );
72
-			wp_die( 'Processed', 200 );
73
-		}
74
-
75
-		wpinv_error_log( 'Aborting, Unsupported IPN type:' . $posted['txn_type'], false );
76
-		wp_die( 'Unsupported IPN type', 200 );
77
-
78
-	}
79
-
80
-	/**
81
-	 * Retrieves IPN Invoice.
82
-	 *
83
-	 * @param array $posted
84
-	 * @return WPInv_Invoice
85
-	 */
86
-	protected function get_ipn_invoice( $posted ) {
87
-
88
-		wpinv_error_log( 'Retrieving PayPal IPN Response Invoice', false );
89
-
90
-		if ( ! empty( $posted['custom'] ) ) {
91
-			$invoice = new WPInv_Invoice( $posted['custom'] );
92
-
93
-			if ( $invoice->exists() ) {
94
-				wpinv_error_log( 'Found invoice #' . $invoice->get_number(), false );
95
-				return $invoice;
96
-			}
97
-
98
-		}
99
-
100
-		wpinv_error_log( 'Could not retrieve the associated invoice.', false );
101
-		wp_die( 'Could not retrieve the associated invoice.', 200 );
102
-	}
103
-
104
-	/**
105
-	 * Check PayPal IPN validity.
106
-	 */
107
-	protected function validate_ipn() {
108
-
109
-		wpinv_error_log( 'Validating PayPal IPN response', false );
110
-
111
-		// Retrieve the associated invoice.
112
-		$posted  = wp_unslash( $_POST );
113
-		$invoice = $this->get_ipn_invoice( $posted );
114
-
115
-		if ( $this->gateway->is_sandbox( $invoice ) ) {
116
-			wpinv_error_log( $posted, 'Invoice was processed in sandbox hence logging the posted data', false );
117
-		}
118
-
119
-		// Validate the IPN.
120
-		$posted['cmd'] = '_notify-validate';
121
-
122
-		// Send back post vars to paypal.
123
-		$params = array(
124
-			'body'        => $posted,
125
-			'timeout'     => 60,
126
-			'httpversion' => '1.1',
127
-			'compress'    => false,
128
-			'decompress'  => false,
129
-			'user-agent'  => 'GetPaid/' . WPINV_VERSION,
130
-		);
131
-
132
-		// Post back to get a response.
133
-		$response = wp_safe_remote_post( $this->gateway->is_sandbox( $invoice ) ? 'https://www.sandbox.paypal.com/cgi-bin/webscr' : 'https://www.paypal.com/cgi-bin/webscr', $params );
134
-
135
-		// Check to see if the request was valid.
136
-		if ( ! is_wp_error( $response ) && $response['response']['code'] < 300 && strstr( $response['body'], 'VERIFIED' ) ) {
137
-			wpinv_error_log( 'Received valid response from PayPal IPN: ' . $response['body'], false );
138
-			return true;
139
-		}
140
-
141
-		if ( is_wp_error( $response ) ) {
142
-			wpinv_error_log( $response->get_error_message(), 'Received invalid response from PayPal IPN' );
143
-			return false;
144
-		}
15
+    /**
16
+     * Payment method id.
17
+     *
18
+     * @var string
19
+     */
20
+    protected $id = 'paypal';
21
+
22
+    /**
23
+     * Payment method object.
24
+     *
25
+     * @var GetPaid_Paypal_Gateway
26
+     */
27
+    protected $gateway;
28
+
29
+    /**
30
+     * Class constructor.
31
+     *
32
+     * @param GetPaid_Paypal_Gateway $gateway
33
+     */
34
+    public function __construct( $gateway ) {
35
+        $this->gateway = $gateway;
36
+        $this->verify_ipn();
37
+    }
38
+
39
+    /**
40
+     * Processes ipns and marks payments as complete.
41
+     *
42
+     * @return void
43
+     */
44
+    public function verify_ipn() {
45
+
46
+        wpinv_error_log( 'GetPaid PayPal IPN Handler', false );
47
+
48
+        // Validate the IPN.
49
+        if ( empty( $_POST ) || ! $this->validate_ipn() ) {
50
+            wp_die( 'PayPal IPN Request Failure', 500 );
51
+        }
52
+
53
+        // Process the IPN.
54
+        $posted  = wp_unslash( $_POST );
55
+        $invoice = $this->get_ipn_invoice( $posted );
56
+
57
+        // Abort if it was not paid by our gateway.
58
+        if ( $this->id != $invoice->get_gateway() ) {
59
+            wpinv_error_log( 'Aborting, Invoice was not paid via PayPal', false );
60
+            wp_die( 'Invoice not paid via PayPal', 200 );
61
+        }
62
+
63
+        $posted['payment_status'] = isset( $posted['payment_status'] ) ? sanitize_key( strtolower( $posted['payment_status'] ) ) : '';
64
+        $posted['txn_type']       = sanitize_key( strtolower( $posted['txn_type'] ) );
65
+
66
+        wpinv_error_log( 'Payment status:' . $posted['payment_status'], false );
67
+        wpinv_error_log( 'IPN Type:' . $posted['txn_type'], false );
68
+
69
+        if ( method_exists( $this, 'ipn_txn_' . $posted['txn_type'] ) ) {
70
+            call_user_func( array( $this, 'ipn_txn_' . $posted['txn_type'] ), $invoice, $posted );
71
+            wpinv_error_log( 'Done processing IPN', false );
72
+            wp_die( 'Processed', 200 );
73
+        }
74
+
75
+        wpinv_error_log( 'Aborting, Unsupported IPN type:' . $posted['txn_type'], false );
76
+        wp_die( 'Unsupported IPN type', 200 );
77
+
78
+    }
79
+
80
+    /**
81
+     * Retrieves IPN Invoice.
82
+     *
83
+     * @param array $posted
84
+     * @return WPInv_Invoice
85
+     */
86
+    protected function get_ipn_invoice( $posted ) {
87
+
88
+        wpinv_error_log( 'Retrieving PayPal IPN Response Invoice', false );
89
+
90
+        if ( ! empty( $posted['custom'] ) ) {
91
+            $invoice = new WPInv_Invoice( $posted['custom'] );
92
+
93
+            if ( $invoice->exists() ) {
94
+                wpinv_error_log( 'Found invoice #' . $invoice->get_number(), false );
95
+                return $invoice;
96
+            }
97
+
98
+        }
99
+
100
+        wpinv_error_log( 'Could not retrieve the associated invoice.', false );
101
+        wp_die( 'Could not retrieve the associated invoice.', 200 );
102
+    }
103
+
104
+    /**
105
+     * Check PayPal IPN validity.
106
+     */
107
+    protected function validate_ipn() {
108
+
109
+        wpinv_error_log( 'Validating PayPal IPN response', false );
110
+
111
+        // Retrieve the associated invoice.
112
+        $posted  = wp_unslash( $_POST );
113
+        $invoice = $this->get_ipn_invoice( $posted );
114
+
115
+        if ( $this->gateway->is_sandbox( $invoice ) ) {
116
+            wpinv_error_log( $posted, 'Invoice was processed in sandbox hence logging the posted data', false );
117
+        }
118
+
119
+        // Validate the IPN.
120
+        $posted['cmd'] = '_notify-validate';
121
+
122
+        // Send back post vars to paypal.
123
+        $params = array(
124
+            'body'        => $posted,
125
+            'timeout'     => 60,
126
+            'httpversion' => '1.1',
127
+            'compress'    => false,
128
+            'decompress'  => false,
129
+            'user-agent'  => 'GetPaid/' . WPINV_VERSION,
130
+        );
131
+
132
+        // Post back to get a response.
133
+        $response = wp_safe_remote_post( $this->gateway->is_sandbox( $invoice ) ? 'https://www.sandbox.paypal.com/cgi-bin/webscr' : 'https://www.paypal.com/cgi-bin/webscr', $params );
134
+
135
+        // Check to see if the request was valid.
136
+        if ( ! is_wp_error( $response ) && $response['response']['code'] < 300 && strstr( $response['body'], 'VERIFIED' ) ) {
137
+            wpinv_error_log( 'Received valid response from PayPal IPN: ' . $response['body'], false );
138
+            return true;
139
+        }
140
+
141
+        if ( is_wp_error( $response ) ) {
142
+            wpinv_error_log( $response->get_error_message(), 'Received invalid response from PayPal IPN' );
143
+            return false;
144
+        }
145 145
 
146
-		wpinv_error_log( $response['body'], 'Received invalid response from PayPal IPN' );
147
-		return false;
148
-
149
-	}
146
+        wpinv_error_log( $response['body'], 'Received invalid response from PayPal IPN' );
147
+        return false;
148
+
149
+    }
150 150
 
151
-	/**
152
-	 * Check currency from IPN matches the invoice.
153
-	 *
154
-	 * @param WPInv_Invoice $invoice          Invoice object.
155
-	 * @param string   $currency currency to validate.
156
-	 */
157
-	protected function validate_ipn_currency( $invoice, $currency ) {
151
+    /**
152
+     * Check currency from IPN matches the invoice.
153
+     *
154
+     * @param WPInv_Invoice $invoice          Invoice object.
155
+     * @param string   $currency currency to validate.
156
+     */
157
+    protected function validate_ipn_currency( $invoice, $currency ) {
158 158
 
159
-		if ( strtolower( $invoice->get_currency() ) !== strtolower( $currency ) ) {
159
+        if ( strtolower( $invoice->get_currency() ) !== strtolower( $currency ) ) {
160 160
 
161
-			/* translators: %s: currency code. */
162
-			$invoice->update_status( 'wpi-processing', sprintf( __( 'Validation error: PayPal currencies do not match (code %s).', 'invoicing' ), $currency ) );
161
+            /* translators: %s: currency code. */
162
+            $invoice->update_status( 'wpi-processing', sprintf( __( 'Validation error: PayPal currencies do not match (code %s).', 'invoicing' ), $currency ) );
163 163
 
164
-			wpinv_error_log( "Currencies do not match: {$currency} instead of {$invoice->get_currency()}", 'IPN Error', __FILE__, __LINE__, true );
165
-		}
164
+            wpinv_error_log( "Currencies do not match: {$currency} instead of {$invoice->get_currency()}", 'IPN Error', __FILE__, __LINE__, true );
165
+        }
166 166
 
167
-		wpinv_error_log( $currency, 'Validated IPN Currency', false );
168
-	}
167
+        wpinv_error_log( $currency, 'Validated IPN Currency', false );
168
+    }
169 169
 
170
-	/**
171
-	 * Check payment amount from IPN matches the invoice.
172
-	 *
173
-	 * @param WPInv_Invoice $invoice          Invoice object.
174
-	 * @param float   $amount amount to validate.
175
-	 */
176
-	protected function validate_ipn_amount( $invoice, $amount ) {
177
-		if ( number_format( $invoice->get_total(), 2, '.', '' ) !== number_format( $amount, 2, '.', '' ) ) {
170
+    /**
171
+     * Check payment amount from IPN matches the invoice.
172
+     *
173
+     * @param WPInv_Invoice $invoice          Invoice object.
174
+     * @param float   $amount amount to validate.
175
+     */
176
+    protected function validate_ipn_amount( $invoice, $amount ) {
177
+        if ( number_format( $invoice->get_total(), 2, '.', '' ) !== number_format( $amount, 2, '.', '' ) ) {
178 178
 
179
-			/* translators: %s: Amount. */
180
-			$invoice->update_status( 'wpi-processing', sprintf( __( 'Validation error: PayPal amounts do not match (gross %s).', 'invoicing' ), $amount ) );
179
+            /* translators: %s: Amount. */
180
+            $invoice->update_status( 'wpi-processing', sprintf( __( 'Validation error: PayPal amounts do not match (gross %s).', 'invoicing' ), $amount ) );
181 181
 
182
-			wpinv_error_log( "Amounts do not match: {$amount} instead of {$invoice->get_total()}", 'IPN Error', __FILE__, __LINE__, true );
183
-		}
182
+            wpinv_error_log( "Amounts do not match: {$amount} instead of {$invoice->get_total()}", 'IPN Error', __FILE__, __LINE__, true );
183
+        }
184 184
 
185
-		wpinv_error_log( $amount, 'Validated IPN Amount', false );
186
-	}
185
+        wpinv_error_log( $amount, 'Validated IPN Amount', false );
186
+    }
187 187
 
188
-	/**
189
-	 * Verify receiver email from PayPal.
190
-	 *
191
-	 * @param WPInv_Invoice $invoice          Invoice object.
192
-	 * @param string   $receiver_email Email to validate.
193
-	 */
194
-	protected function validate_ipn_receiver_email( $invoice, $receiver_email ) {
195
-		$paypal_email = wpinv_get_option( 'paypal_email' );
188
+    /**
189
+     * Verify receiver email from PayPal.
190
+     *
191
+     * @param WPInv_Invoice $invoice          Invoice object.
192
+     * @param string   $receiver_email Email to validate.
193
+     */
194
+    protected function validate_ipn_receiver_email( $invoice, $receiver_email ) {
195
+        $paypal_email = wpinv_get_option( 'paypal_email' );
196 196
 
197
-		if ( strcasecmp( trim( $receiver_email ), trim( $paypal_email ) ) !== 0 ) {
198
-			wpinv_record_gateway_error( 'IPN Error', "IPN Response is for another account: {$receiver_email}. Your email is {$paypal_email}" );
197
+        if ( strcasecmp( trim( $receiver_email ), trim( $paypal_email ) ) !== 0 ) {
198
+            wpinv_record_gateway_error( 'IPN Error', "IPN Response is for another account: {$receiver_email}. Your email is {$paypal_email}" );
199 199
 
200
-			/* translators: %s: email address . */
201
-			$invoice->update_status( 'wpi-processing', sprintf( __( 'Validation error: PayPal IPN response from a different email address (%s).', 'invoicing' ), $receiver_email ) );
200
+            /* translators: %s: email address . */
201
+            $invoice->update_status( 'wpi-processing', sprintf( __( 'Validation error: PayPal IPN response from a different email address (%s).', 'invoicing' ), $receiver_email ) );
202 202
 
203
-			return wpinv_error_log( "IPN Response is for another account: {$receiver_email}. Your email is {$paypal_email}", 'IPN Error', __FILE__, __LINE__, true );
204
-		}
203
+            return wpinv_error_log( "IPN Response is for another account: {$receiver_email}. Your email is {$paypal_email}", 'IPN Error', __FILE__, __LINE__, true );
204
+        }
205 205
 
206
-		wpinv_error_log( 'Validated PayPal Email', false );
207
-	}
206
+        wpinv_error_log( 'Validated PayPal Email', false );
207
+    }
208 208
 
209
-	/**
210
-	 * Handles one time payments.
211
-	 *
212
-	 * @param WPInv_Invoice $invoice  Invoice object.
213
-	 * @param array    $posted Posted data.
214
-	 */
215
-	protected function ipn_txn_web_accept( $invoice, $posted ) {
209
+    /**
210
+     * Handles one time payments.
211
+     *
212
+     * @param WPInv_Invoice $invoice  Invoice object.
213
+     * @param array    $posted Posted data.
214
+     */
215
+    protected function ipn_txn_web_accept( $invoice, $posted ) {
216 216
 
217
-		// Collect payment details
218
-		$payment_status = strtolower( $posted['payment_status'] );
219
-		$business_email = isset( $posted['business'] ) && is_email( $posted['business'] ) ? trim( $posted['business'] ) : trim( $posted['receiver_email'] );
217
+        // Collect payment details
218
+        $payment_status = strtolower( $posted['payment_status'] );
219
+        $business_email = isset( $posted['business'] ) && is_email( $posted['business'] ) ? trim( $posted['business'] ) : trim( $posted['receiver_email'] );
220 220
 
221
-		$this->validate_ipn_receiver_email( $invoice, $business_email );
222
-		$this->validate_ipn_currency( $invoice, $posted['mc_currency'] );
223
-
224
-		// Update the transaction id.
225
-		if ( ! empty( $posted['txn_id'] ) ) {
226
-			$invoice->set_transaction_id( wpinv_clean( $posted['txn_id'] ) );
227
-			$invoice->save();
228
-		}
221
+        $this->validate_ipn_receiver_email( $invoice, $business_email );
222
+        $this->validate_ipn_currency( $invoice, $posted['mc_currency'] );
223
+
224
+        // Update the transaction id.
225
+        if ( ! empty( $posted['txn_id'] ) ) {
226
+            $invoice->set_transaction_id( wpinv_clean( $posted['txn_id'] ) );
227
+            $invoice->save();
228
+        }
229 229
 
230
-		// Process a refund.
231
-		if ( $payment_status == 'refunded' || $payment_status == 'reversed' ) {
230
+        // Process a refund.
231
+        if ( $payment_status == 'refunded' || $payment_status == 'reversed' ) {
232 232
 
233
-			update_post_meta( $invoice->get_id(), 'refunded_remotely', 1 );
233
+            update_post_meta( $invoice->get_id(), 'refunded_remotely', 1 );
234 234
 
235
-			if ( ! $invoice->is_refunded() ) {
236
-				$invoice->update_status( 'wpi-refunded', $posted['reason_code'] );
237
-			}
235
+            if ( ! $invoice->is_refunded() ) {
236
+                $invoice->update_status( 'wpi-refunded', $posted['reason_code'] );
237
+            }
238 238
 
239
-			return wpinv_error_log( $posted['reason_code'], false );
240
-		}
239
+            return wpinv_error_log( $posted['reason_code'], false );
240
+        }
241 241
 
242
-		// Process payments.
243
-		if ( $payment_status == 'completed' ) {
242
+        // Process payments.
243
+        if ( $payment_status == 'completed' ) {
244 244
 
245
-			if ( $invoice->is_paid() && 'wpi_processing' != $invoice->get_status() ) {
246
-				return wpinv_error_log( 'Aborting, Invoice #' . $invoice->get_number() . ' is already paid.', false );
247
-			}
245
+            if ( $invoice->is_paid() && 'wpi_processing' != $invoice->get_status() ) {
246
+                return wpinv_error_log( 'Aborting, Invoice #' . $invoice->get_number() . ' is already paid.', false );
247
+            }
248 248
 
249
-			$this->validate_ipn_amount( $invoice, $posted['mc_gross'] );
249
+            $this->validate_ipn_amount( $invoice, $posted['mc_gross'] );
250 250
 
251
-			$note = '';
251
+            $note = '';
252 252
 
253
-			if ( ! empty( $posted['mc_fee'] ) ) {
254
-				$note = sprintf( __( 'PayPal Transaction Fee %.', 'invoicing' ), sanitize_text_field( $posted['mc_fee'] ) );
255
-			}
253
+            if ( ! empty( $posted['mc_fee'] ) ) {
254
+                $note = sprintf( __( 'PayPal Transaction Fee %.', 'invoicing' ), sanitize_text_field( $posted['mc_fee'] ) );
255
+            }
256 256
 
257
-			if ( ! empty( $posted['payer_status'] ) ) {
258
-				$note = ' ' . sprintf( __( 'Buyer status %.', 'invoicing' ), sanitize_text_field( $posted['payer_status'] ) );
259
-			}
257
+            if ( ! empty( $posted['payer_status'] ) ) {
258
+                $note = ' ' . sprintf( __( 'Buyer status %.', 'invoicing' ), sanitize_text_field( $posted['payer_status'] ) );
259
+            }
260 260
 
261
-			$invoice->mark_paid( ( ! empty( $posted['txn_id'] ) ? sanitize_text_field( $posted['txn_id'] ) : '' ), trim( $note ) );
262
-			return wpinv_error_log( 'Invoice marked as paid.', false );
261
+            $invoice->mark_paid( ( ! empty( $posted['txn_id'] ) ? sanitize_text_field( $posted['txn_id'] ) : '' ), trim( $note ) );
262
+            return wpinv_error_log( 'Invoice marked as paid.', false );
263 263
 
264
-		}
264
+        }
265 265
 
266
-		// Pending payments.
267
-		if ( $payment_status == 'pending' ) {
266
+        // Pending payments.
267
+        if ( $payment_status == 'pending' ) {
268 268
 
269
-			/* translators: %s: pending reason. */
270
-			$invoice->update_status( 'wpi-onhold', sprintf( __( 'Payment pending (%s).', 'invoicing' ), $posted['pending_reason'] ) );
269
+            /* translators: %s: pending reason. */
270
+            $invoice->update_status( 'wpi-onhold', sprintf( __( 'Payment pending (%s).', 'invoicing' ), $posted['pending_reason'] ) );
271 271
 
272
-			return wpinv_error_log( 'Invoice marked as "payment held".', false );
273
-		}
272
+            return wpinv_error_log( 'Invoice marked as "payment held".', false );
273
+        }
274 274
 
275
-		/* translators: %s: payment status. */
276
-		$invoice->update_status( 'wpi-failed', sprintf( __( 'Payment %s via IPN.', 'invoicing' ), sanitize_text_field( $posted['payment_status'] ) ) );
275
+        /* translators: %s: payment status. */
276
+        $invoice->update_status( 'wpi-failed', sprintf( __( 'Payment %s via IPN.', 'invoicing' ), sanitize_text_field( $posted['payment_status'] ) ) );
277 277
 
278
-	}
278
+    }
279 279
 
280
-	/**
281
-	 * Handles one time payments.
282
-	 *
283
-	 * @param WPInv_Invoice $invoice  Invoice object.
284
-	 * @param array    $posted Posted data.
285
-	 */
286
-	protected function ipn_txn_cart( $invoice, $posted ) {
287
-		$this->ipn_txn_web_accept( $invoice, $posted );
288
-	}
280
+    /**
281
+     * Handles one time payments.
282
+     *
283
+     * @param WPInv_Invoice $invoice  Invoice object.
284
+     * @param array    $posted Posted data.
285
+     */
286
+    protected function ipn_txn_cart( $invoice, $posted ) {
287
+        $this->ipn_txn_web_accept( $invoice, $posted );
288
+    }
289 289
 
290
-	/**
291
-	 * Handles subscription sign ups.
292
-	 *
293
-	 * @param WPInv_Invoice $invoice  Invoice object.
294
-	 * @param array    $posted Posted data.
295
-	 */
296
-	protected function ipn_txn_subscr_signup( $invoice, $posted ) {
290
+    /**
291
+     * Handles subscription sign ups.
292
+     *
293
+     * @param WPInv_Invoice $invoice  Invoice object.
294
+     * @param array    $posted Posted data.
295
+     */
296
+    protected function ipn_txn_subscr_signup( $invoice, $posted ) {
297 297
 
298
-		wpinv_error_log( 'Processing subscription signup', false );
298
+        wpinv_error_log( 'Processing subscription signup', false );
299 299
 
300
-		// Make sure the invoice has a subscription.
301
-		$subscription = getpaid_get_invoice_subscription( $invoice );
300
+        // Make sure the invoice has a subscription.
301
+        $subscription = getpaid_get_invoice_subscription( $invoice );
302 302
 
303
-		if ( empty( $subscription ) ) {
304
-			return wpinv_error_log( 'Aborting, Subscription for the invoice ' . $invoice->get_id() . ' not found', false );
305
-		}
303
+        if ( empty( $subscription ) ) {
304
+            return wpinv_error_log( 'Aborting, Subscription for the invoice ' . $invoice->get_id() . ' not found', false );
305
+        }
306 306
 
307
-		wpinv_error_log( 'Found subscription #' . $subscription->get_id(), false );
307
+        wpinv_error_log( 'Found subscription #' . $subscription->get_id(), false );
308 308
 
309
-		// Validate the IPN.
310
-		$business_email = isset( $posted['business'] ) && is_email( $posted['business'] ) ? trim( $posted['business'] ) : trim( $posted['receiver_email'] );
311
-		$this->validate_ipn_receiver_email( $invoice, $business_email );
312
-		$this->validate_ipn_currency( $invoice, $posted['mc_currency'] );
309
+        // Validate the IPN.
310
+        $business_email = isset( $posted['business'] ) && is_email( $posted['business'] ) ? trim( $posted['business'] ) : trim( $posted['receiver_email'] );
311
+        $this->validate_ipn_receiver_email( $invoice, $business_email );
312
+        $this->validate_ipn_currency( $invoice, $posted['mc_currency'] );
313 313
 
314
-		// Activate the subscription.
315
-		$duration = strtotime( $subscription->get_expiration() ) - strtotime( $subscription->get_date_created() );
316
-		$subscription->set_date_created( current_time( 'mysql' ) );
317
-		$subscription->set_expiration( date( 'Y-m-d H:i:s', ( current_time( 'timestamp' ) + $duration ) ) );
318
-		$subscription->set_profile_id( sanitize_text_field( $posted['subscr_id'] ) );
319
-		$subscription->activate();
314
+        // Activate the subscription.
315
+        $duration = strtotime( $subscription->get_expiration() ) - strtotime( $subscription->get_date_created() );
316
+        $subscription->set_date_created( current_time( 'mysql' ) );
317
+        $subscription->set_expiration( date( 'Y-m-d H:i:s', ( current_time( 'timestamp' ) + $duration ) ) );
318
+        $subscription->set_profile_id( sanitize_text_field( $posted['subscr_id'] ) );
319
+        $subscription->activate();
320 320
 
321
-		// Set the transaction id.
322
-		if ( ! empty( $posted['txn_id'] ) ) {
323
-			$invoice->set_transaction_id( $posted['txn_id'] );
324
-		}
321
+        // Set the transaction id.
322
+        if ( ! empty( $posted['txn_id'] ) ) {
323
+            $invoice->set_transaction_id( $posted['txn_id'] );
324
+        }
325 325
 
326
-		// Update the payment status.
327
-		$invoice->mark_paid();
326
+        // Update the payment status.
327
+        $invoice->mark_paid();
328 328
 
329
-		$invoice->add_note( sprintf( __( 'PayPal Subscription ID: %s', 'invoicing' ) , $posted['subscr_id'] ), false, false, true );
329
+        $invoice->add_note( sprintf( __( 'PayPal Subscription ID: %s', 'invoicing' ) , $posted['subscr_id'] ), false, false, true );
330 330
 
331
-		wpinv_error_log( 'Subscription started.', false );
332
-	}
331
+        wpinv_error_log( 'Subscription started.', false );
332
+    }
333 333
 
334
-	/**
335
-	 * Handles subscription renewals.
336
-	 *
337
-	 * @param WPInv_Invoice $invoice  Invoice object.
338
-	 * @param array    $posted Posted data.
339
-	 */
340
-	protected function ipn_txn_subscr_payment( $invoice, $posted ) {
334
+    /**
335
+     * Handles subscription renewals.
336
+     *
337
+     * @param WPInv_Invoice $invoice  Invoice object.
338
+     * @param array    $posted Posted data.
339
+     */
340
+    protected function ipn_txn_subscr_payment( $invoice, $posted ) {
341 341
 
342
-		// Make sure the invoice has a subscription.
343
-		$subscription = wpinv_get_subscription( $invoice );
342
+        // Make sure the invoice has a subscription.
343
+        $subscription = wpinv_get_subscription( $invoice );
344 344
 
345
-		if ( empty( $subscription ) ) {
346
-			return wpinv_error_log( 'Aborting, Subscription for the invoice ' . $invoice->get_id() . ' not found', false );
347
-		}
345
+        if ( empty( $subscription ) ) {
346
+            return wpinv_error_log( 'Aborting, Subscription for the invoice ' . $invoice->get_id() . ' not found', false );
347
+        }
348 348
 
349
-		wpinv_error_log( 'Found subscription #' . $subscription->get_id(), false );
349
+        wpinv_error_log( 'Found subscription #' . $subscription->get_id(), false );
350 350
 
351
-		// Abort if this is the first payment.
352
-		$invoice_completed = date( 'Ynd', strtotime( $invoice->get_date_completed() ) );
353
-		$payment_date      = date( 'Ynd', strtotime( $posted['payment_date'] ) );
354
-		$subscription_date = date( 'Ynd', $subscription->get_time_created() );
355
-		if ( $invoice_completed == $payment_date || $subscription_date == $payment_date ) {
351
+        // Abort if this is the first payment.
352
+        $invoice_completed = date( 'Ynd', strtotime( $invoice->get_date_completed() ) );
353
+        $payment_date      = date( 'Ynd', strtotime( $posted['payment_date'] ) );
354
+        $subscription_date = date( 'Ynd', $subscription->get_time_created() );
355
+        if ( $invoice_completed == $payment_date || $subscription_date == $payment_date ) {
356 356
 
357
-			if ( ! empty( $posted['txn_id'] ) ) {
358
-				$invoice->set_transaction_id( sanitize_text_field( $posted['txn_id'] ) );	
359
-			}
357
+            if ( ! empty( $posted['txn_id'] ) ) {
358
+                $invoice->set_transaction_id( sanitize_text_field( $posted['txn_id'] ) );	
359
+            }
360 360
 
361
-			return $invoice->mark_paid();
362
-		}
361
+            return $invoice->mark_paid();
362
+        }
363 363
 
364
-		wpinv_error_log( 'Processing subscription renewal payment for the invoice ' . $invoice->get_id(), false );
364
+        wpinv_error_log( 'Processing subscription renewal payment for the invoice ' . $invoice->get_id(), false );
365 365
 
366
-		// Abort if the payment is already recorded.
367
-		if ( wpinv_get_id_by_transaction_id( $posted['txn_id'] ) ) {
368
-			return wpinv_error_log( 'Aborting, Transaction ' . $posted['txn_id'] .' has already been processed', false );
369
-		}
370
-
371
-		$args = array(
372
-			'transaction_id' => $posted['txn_id'],
373
-			'gateway'        => $this->id,
374
-		);
375
-
376
-		$invoice = wpinv_get_invoice( $subscription->add_payment( $args ) );
377
-
378
-		if ( empty( $invoice ) ) {
379
-			return;
380
-		}
381
-
382
-		$invoice->add_note( wp_sprintf( __( 'PayPal Transaction ID: %s', 'invoicing' ) , $posted['txn_id'] ), false, false, true );
383
-		$invoice->add_note( wp_sprintf( __( 'PayPal Subscription ID: %s', 'invoicing' ) , $posted['subscr_id'] ), false, false, true );
384
-
385
-		$subscription->renew();
386
-		wpinv_error_log( 'Subscription renewed.', false );
387
-
388
-	}
366
+        // Abort if the payment is already recorded.
367
+        if ( wpinv_get_id_by_transaction_id( $posted['txn_id'] ) ) {
368
+            return wpinv_error_log( 'Aborting, Transaction ' . $posted['txn_id'] .' has already been processed', false );
369
+        }
370
+
371
+        $args = array(
372
+            'transaction_id' => $posted['txn_id'],
373
+            'gateway'        => $this->id,
374
+        );
375
+
376
+        $invoice = wpinv_get_invoice( $subscription->add_payment( $args ) );
377
+
378
+        if ( empty( $invoice ) ) {
379
+            return;
380
+        }
381
+
382
+        $invoice->add_note( wp_sprintf( __( 'PayPal Transaction ID: %s', 'invoicing' ) , $posted['txn_id'] ), false, false, true );
383
+        $invoice->add_note( wp_sprintf( __( 'PayPal Subscription ID: %s', 'invoicing' ) , $posted['subscr_id'] ), false, false, true );
384
+
385
+        $subscription->renew();
386
+        wpinv_error_log( 'Subscription renewed.', false );
387
+
388
+    }
389 389
 
390
-	/**
391
-	 * Handles subscription cancelations.
392
-	 *
393
-	 * @param WPInv_Invoice $invoice  Invoice object.
394
-	 */
395
-	protected function ipn_txn_subscr_cancel( $invoice ) {
390
+    /**
391
+     * Handles subscription cancelations.
392
+     *
393
+     * @param WPInv_Invoice $invoice  Invoice object.
394
+     */
395
+    protected function ipn_txn_subscr_cancel( $invoice ) {
396 396
 
397
-		// Make sure the invoice has a subscription.
398
-		$subscription = wpinv_get_subscription( $invoice );
397
+        // Make sure the invoice has a subscription.
398
+        $subscription = wpinv_get_subscription( $invoice );
399 399
 
400
-		if ( empty( $subscription ) ) {
401
-			return wpinv_error_log( 'Aborting, Subscription for the invoice ' . $invoice->get_id() . ' not found', false);
402
-		}
403
-
404
-		wpinv_error_log( 'Processing subscription cancellation for the invoice ' . $invoice->get_id(), false );
405
-		$subscription->cancel();
406
-		wpinv_error_log( 'Subscription cancelled.', false );
407
-
408
-	}
409
-
410
-	/**
411
-	 * Handles subscription completions.
412
-	 *
413
-	 * @param WPInv_Invoice $invoice  Invoice object.
414
-	 * @param array    $posted Posted data.
415
-	 */
416
-	protected function ipn_txn_subscr_eot( $invoice ) {
400
+        if ( empty( $subscription ) ) {
401
+            return wpinv_error_log( 'Aborting, Subscription for the invoice ' . $invoice->get_id() . ' not found', false);
402
+        }
403
+
404
+        wpinv_error_log( 'Processing subscription cancellation for the invoice ' . $invoice->get_id(), false );
405
+        $subscription->cancel();
406
+        wpinv_error_log( 'Subscription cancelled.', false );
407
+
408
+    }
409
+
410
+    /**
411
+     * Handles subscription completions.
412
+     *
413
+     * @param WPInv_Invoice $invoice  Invoice object.
414
+     * @param array    $posted Posted data.
415
+     */
416
+    protected function ipn_txn_subscr_eot( $invoice ) {
417 417
 
418
-		// Make sure the invoice has a subscription.
419
-		$subscription = wpinv_get_subscription( $invoice );
418
+        // Make sure the invoice has a subscription.
419
+        $subscription = wpinv_get_subscription( $invoice );
420 420
 
421
-		if ( empty( $subscription ) ) {
422
-			return wpinv_error_log( 'Aborting, Subscription for the invoice ' . $invoice->get_id() . ' not found', false );
423
-		}
421
+        if ( empty( $subscription ) ) {
422
+            return wpinv_error_log( 'Aborting, Subscription for the invoice ' . $invoice->get_id() . ' not found', false );
423
+        }
424 424
 
425
-		wpinv_error_log( 'Processing subscription end of life for the invoice ' . $invoice->get_id(), false );
426
-		$subscription->complete();
427
-		wpinv_error_log( 'Subscription completed.', false );
425
+        wpinv_error_log( 'Processing subscription end of life for the invoice ' . $invoice->get_id(), false );
426
+        $subscription->complete();
427
+        wpinv_error_log( 'Subscription completed.', false );
428 428
 
429
-	}
429
+    }
430 430
 
431
-	/**
432
-	 * Handles subscription fails.
433
-	 *
434
-	 * @param WPInv_Invoice $invoice  Invoice object.
435
-	 * @param array    $posted Posted data.
436
-	 */
437
-	protected function ipn_txn_subscr_failed( $invoice ) {
431
+    /**
432
+     * Handles subscription fails.
433
+     *
434
+     * @param WPInv_Invoice $invoice  Invoice object.
435
+     * @param array    $posted Posted data.
436
+     */
437
+    protected function ipn_txn_subscr_failed( $invoice ) {
438 438
 
439
-		// Make sure the invoice has a subscription.
440
-		$subscription = wpinv_get_subscription( $invoice );
439
+        // Make sure the invoice has a subscription.
440
+        $subscription = wpinv_get_subscription( $invoice );
441 441
 
442
-		if ( empty( $subscription ) ) {
443
-			return wpinv_error_log( 'Aborting, Subscription for the invoice ' . $invoice->get_id() . ' not found', false );
444
-		}
442
+        if ( empty( $subscription ) ) {
443
+            return wpinv_error_log( 'Aborting, Subscription for the invoice ' . $invoice->get_id() . ' not found', false );
444
+        }
445 445
 
446
-		wpinv_error_log( 'Processing subscription payment failure for the invoice ' . $invoice->get_id(), false );
447
-		$subscription->failing();
448
-		wpinv_error_log( 'Subscription marked as failing.', false );
446
+        wpinv_error_log( 'Processing subscription payment failure for the invoice ' . $invoice->get_id(), false );
447
+        $subscription->failing();
448
+        wpinv_error_log( 'Subscription marked as failing.', false );
449 449
 
450
-	}
451
-
452
-	/**
453
-	 * Handles subscription suspensions.
454
-	 *
455
-	 * @param WPInv_Invoice $invoice  Invoice object.
456
-	 * @param array    $posted Posted data.
457
-	 */
458
-	protected function ipn_txn_recurring_payment_suspended_due_to_max_failed_payment( $invoice ) {
450
+    }
451
+
452
+    /**
453
+     * Handles subscription suspensions.
454
+     *
455
+     * @param WPInv_Invoice $invoice  Invoice object.
456
+     * @param array    $posted Posted data.
457
+     */
458
+    protected function ipn_txn_recurring_payment_suspended_due_to_max_failed_payment( $invoice ) {
459 459
 
460
-		// Make sure the invoice has a subscription.
461
-		$subscription = wpinv_get_subscription( $invoice );
460
+        // Make sure the invoice has a subscription.
461
+        $subscription = wpinv_get_subscription( $invoice );
462 462
 
463
-		if ( empty( $subscription ) ) {
464
-			return wpinv_error_log( 'Aborting, Subscription for the invoice ' . $invoice->get_id() . ' not found', false );
465
-		}
466
-
467
-		wpinv_error_log( 'Processing subscription cancellation due to max failed payment for the invoice ' . $invoice->get_id(), false );
468
-		$subscription->cancel();
469
-		wpinv_error_log( 'Subscription cancelled.', false );
470
-	}
463
+        if ( empty( $subscription ) ) {
464
+            return wpinv_error_log( 'Aborting, Subscription for the invoice ' . $invoice->get_id() . ' not found', false );
465
+        }
466
+
467
+        wpinv_error_log( 'Processing subscription cancellation due to max failed payment for the invoice ' . $invoice->get_id(), false );
468
+        $subscription->cancel();
469
+        wpinv_error_log( 'Subscription cancelled.', false );
470
+    }
471 471
 
472 472
 }
Please login to merge, or discard this patch.
includes/class-wpinv.php 1 patch
Indentation   +527 added lines, -527 removed lines patch added patch discarded remove patch
@@ -14,590 +14,590 @@
 block discarded – undo
14 14
  */
15 15
 class WPInv_Plugin {
16 16
 
17
-	/**
18
-	 * GetPaid version.
19
-	 *
20
-	 * @var string
21
-	 */
22
-	public $version;
23
-
24
-	/**
25
-	 * Data container.
26
-	 *
27
-	 * @var array
28
-	 */
29
-	protected $data = array();
30
-
31
-	/**
32
-	 * Form elements instance.
33
-	 *
34
-	 * @var WPInv_Payment_Form_Elements
35
-	 */
36
-	public $form_elements;
37
-
38
-	/**
39
-	 * @param array An array of payment gateways.
40
-	 */
41
-	public $gateways;
42
-
43
-	/**
44
-	 * Class constructor.
45
-	 */
46
-	public function __construct() {
47
-		$this->define_constants();
48
-		$this->includes();
49
-		$this->init_hooks();
50
-		$this->set_properties();
51
-	}
52
-
53
-	/**
54
-	 * Sets a custom data property.
55
-	 * 
56
-	 * @param string $prop The prop to set.
57
-	 * @param mixed $value The value to retrieve.
58
-	 */
59
-	public function set( $prop, $value ) {
60
-		$this->data[ $prop ] = $value;
61
-	}
62
-
63
-	/**
64
-	 * Gets a custom data property.
65
-	 *
66
-	 * @param string $prop The prop to set.
67
-	 * @return mixed The value.
68
-	 */
69
-	public function get( $prop ) {
70
-
71
-		if ( isset( $this->data[ $prop ] ) ) {
72
-			return $this->data[ $prop ];
73
-		}
74
-
75
-		return null;
76
-	}
77
-
78
-	/**
79
-	 * Define class properties.
80
-	 */
81
-	public function set_properties() {
82
-
83
-		// Sessions.
84
-		$this->set( 'session', new WPInv_Session_Handler() );
85
-		$GLOBALS['wpi_session'] = $this->get( 'session' ); // Backwards compatibility.
86
-		$GLOBALS['wpinv_euvat'] = new WPInv_EUVat(); // Backwards compatibility.
87
-
88
-		// Init other objects.
89
-		$this->set( 'session', new WPInv_Session_Handler() );
90
-		$this->set( 'notes', new WPInv_Notes() );
91
-		$this->set( 'api', new WPInv_API() );
92
-		$this->set( 'post_types', new GetPaid_Post_Types() );
93
-		$this->set( 'template', new GetPaid_Template() );
94
-		$this->set( 'admin', new GetPaid_Admin() );
95
-		$this->set( 'subscriptions', new WPInv_Subscriptions() );
96
-		$this->set( 'invoice_emails', new GetPaid_Invoice_Notification_Emails() );
97
-		$this->set( 'subscription_emails', new GetPaid_Subscription_Notification_Emails() );
98
-		$this->set( 'daily_maintenace', new GetPaid_Daily_Maintenance() );
99
-		$this->set( 'payment_forms', new GetPaid_Payment_Forms() );
100
-		$this->set( 'maxmind', new GetPaid_MaxMind_Geolocation() );
101
-
102
-	}
103
-
104
-	 /**
105
-	 * Define plugin constants.
106
-	 */
107
-	public function define_constants() {
108
-		define( 'WPINV_PLUGIN_DIR', plugin_dir_path( WPINV_PLUGIN_FILE ) );
109
-		define( 'WPINV_PLUGIN_URL', plugin_dir_url( WPINV_PLUGIN_FILE ) );
110
-		$this->version = WPINV_VERSION;
111
-	}
112
-
113
-	/**
114
-	 * Hook into actions and filters.
115
-	 *
116
-	 * @since 1.0.19
117
-	 */
118
-	protected function init_hooks() {
119
-		/* Internationalize the text strings used. */
120
-		add_action( 'plugins_loaded', array( &$this, 'plugins_loaded' ) );
121
-
122
-		// Init the plugin after WordPress inits.
123
-		add_action( 'init', array( $this, 'init' ), 1 );
124
-		add_action( 'init', array( $this, 'maybe_process_ipn' ), 10 );
125
-		add_action( 'init', array( $this, 'wpinv_actions' ) );
126
-		add_action( 'init', array( $this, 'maybe_do_authenticated_action' ), 100 );
127
-		add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_scripts' ), 11 );
128
-		add_action( 'wp_footer', array( $this, 'wp_footer' ) );
129
-		add_action( 'wp_head', array( $this, 'wp_head' ) );
130
-		add_action( 'widgets_init', array( &$this, 'register_widgets' ) );
131
-		add_filter( 'wpseo_exclude_from_sitemap_by_post_ids', array( $this, 'wpseo_exclude_from_sitemap_by_post_ids' ) );
132
-		add_filter( 'pre_get_posts', array( &$this, 'pre_get_posts' ) );
133
-
134
-		add_filter( 'query_vars', array( $this, 'custom_query_vars' ) );
17
+    /**
18
+     * GetPaid version.
19
+     *
20
+     * @var string
21
+     */
22
+    public $version;
23
+
24
+    /**
25
+     * Data container.
26
+     *
27
+     * @var array
28
+     */
29
+    protected $data = array();
30
+
31
+    /**
32
+     * Form elements instance.
33
+     *
34
+     * @var WPInv_Payment_Form_Elements
35
+     */
36
+    public $form_elements;
37
+
38
+    /**
39
+     * @param array An array of payment gateways.
40
+     */
41
+    public $gateways;
42
+
43
+    /**
44
+     * Class constructor.
45
+     */
46
+    public function __construct() {
47
+        $this->define_constants();
48
+        $this->includes();
49
+        $this->init_hooks();
50
+        $this->set_properties();
51
+    }
52
+
53
+    /**
54
+     * Sets a custom data property.
55
+     * 
56
+     * @param string $prop The prop to set.
57
+     * @param mixed $value The value to retrieve.
58
+     */
59
+    public function set( $prop, $value ) {
60
+        $this->data[ $prop ] = $value;
61
+    }
62
+
63
+    /**
64
+     * Gets a custom data property.
65
+     *
66
+     * @param string $prop The prop to set.
67
+     * @return mixed The value.
68
+     */
69
+    public function get( $prop ) {
70
+
71
+        if ( isset( $this->data[ $prop ] ) ) {
72
+            return $this->data[ $prop ];
73
+        }
74
+
75
+        return null;
76
+    }
77
+
78
+    /**
79
+     * Define class properties.
80
+     */
81
+    public function set_properties() {
82
+
83
+        // Sessions.
84
+        $this->set( 'session', new WPInv_Session_Handler() );
85
+        $GLOBALS['wpi_session'] = $this->get( 'session' ); // Backwards compatibility.
86
+        $GLOBALS['wpinv_euvat'] = new WPInv_EUVat(); // Backwards compatibility.
87
+
88
+        // Init other objects.
89
+        $this->set( 'session', new WPInv_Session_Handler() );
90
+        $this->set( 'notes', new WPInv_Notes() );
91
+        $this->set( 'api', new WPInv_API() );
92
+        $this->set( 'post_types', new GetPaid_Post_Types() );
93
+        $this->set( 'template', new GetPaid_Template() );
94
+        $this->set( 'admin', new GetPaid_Admin() );
95
+        $this->set( 'subscriptions', new WPInv_Subscriptions() );
96
+        $this->set( 'invoice_emails', new GetPaid_Invoice_Notification_Emails() );
97
+        $this->set( 'subscription_emails', new GetPaid_Subscription_Notification_Emails() );
98
+        $this->set( 'daily_maintenace', new GetPaid_Daily_Maintenance() );
99
+        $this->set( 'payment_forms', new GetPaid_Payment_Forms() );
100
+        $this->set( 'maxmind', new GetPaid_MaxMind_Geolocation() );
101
+
102
+    }
103
+
104
+        /**
105
+         * Define plugin constants.
106
+         */
107
+    public function define_constants() {
108
+        define( 'WPINV_PLUGIN_DIR', plugin_dir_path( WPINV_PLUGIN_FILE ) );
109
+        define( 'WPINV_PLUGIN_URL', plugin_dir_url( WPINV_PLUGIN_FILE ) );
110
+        $this->version = WPINV_VERSION;
111
+    }
112
+
113
+    /**
114
+     * Hook into actions and filters.
115
+     *
116
+     * @since 1.0.19
117
+     */
118
+    protected function init_hooks() {
119
+        /* Internationalize the text strings used. */
120
+        add_action( 'plugins_loaded', array( &$this, 'plugins_loaded' ) );
121
+
122
+        // Init the plugin after WordPress inits.
123
+        add_action( 'init', array( $this, 'init' ), 1 );
124
+        add_action( 'init', array( $this, 'maybe_process_ipn' ), 10 );
125
+        add_action( 'init', array( $this, 'wpinv_actions' ) );
126
+        add_action( 'init', array( $this, 'maybe_do_authenticated_action' ), 100 );
127
+        add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_scripts' ), 11 );
128
+        add_action( 'wp_footer', array( $this, 'wp_footer' ) );
129
+        add_action( 'wp_head', array( $this, 'wp_head' ) );
130
+        add_action( 'widgets_init', array( &$this, 'register_widgets' ) );
131
+        add_filter( 'wpseo_exclude_from_sitemap_by_post_ids', array( $this, 'wpseo_exclude_from_sitemap_by_post_ids' ) );
132
+        add_filter( 'pre_get_posts', array( &$this, 'pre_get_posts' ) );
133
+
134
+        add_filter( 'query_vars', array( $this, 'custom_query_vars' ) );
135 135
         add_action( 'init', array( $this, 'add_rewrite_rule' ), 10, 0 );
136
-		add_action( 'pre_get_posts', array( $this, 'maybe_process_new_ipn' ), 1 );
137
-
138
-		// Fires after registering actions.
139
-		do_action( 'wpinv_actions', $this );
140
-		do_action( 'getpaid_actions', $this );
141
-
142
-	}
143
-
144
-	public function plugins_loaded() {
145
-		/* Internationalize the text strings used. */
146
-		$this->load_textdomain();
147
-
148
-		do_action( 'wpinv_loaded' );
149
-
150
-		// Fix oxygen page builder conflict
151
-		if ( function_exists( 'ct_css_output' ) ) {
152
-			wpinv_oxygen_fix_conflict();
153
-		}
154
-	}
155
-
156
-	/**
157
-	 * Load the translation of the plugin.
158
-	 *
159
-	 * @since 1.0
160
-	 */
161
-	public function load_textdomain( $locale = NULL ) {
162
-		if ( empty( $locale ) ) {
163
-			$locale = is_admin() && function_exists( 'get_user_locale' ) ? get_user_locale() : get_locale();
164
-		}
165
-
166
-		$locale = apply_filters( 'plugin_locale', $locale, 'invoicing' );
167
-
168
-		unload_textdomain( 'invoicing' );
169
-		load_textdomain( 'invoicing', WP_LANG_DIR . '/invoicing/invoicing-' . $locale . '.mo' );
170
-		load_plugin_textdomain( 'invoicing', false, WPINV_PLUGIN_DIR . 'languages' );
171
-
172
-		/**
173
-		 * Define language constants.
174
-		 */
175
-		require_once( WPINV_PLUGIN_DIR . 'language.php' );
176
-	}
177
-
178
-	/**
179
-	 * Include required core files used in admin and on the frontend.
180
-	 */
181
-	public function includes() {
182
-
183
-		// Start with the settings.
184
-		require_once( WPINV_PLUGIN_DIR . 'includes/admin/register-settings.php' );
185
-
186
-		// Packages/libraries.
187
-		require_once( WPINV_PLUGIN_DIR . 'vendor/autoload.php' );
188
-		require_once( WPINV_PLUGIN_DIR . 'vendor/ayecode/wp-ayecode-ui/ayecode-ui-loader.php' );
189
-
190
-		// Load functions.
191
-		require_once( WPINV_PLUGIN_DIR . 'includes/deprecated-functions.php' );
192
-		require_once( WPINV_PLUGIN_DIR . 'includes/wpinv-email-functions.php' );
193
-		require_once( WPINV_PLUGIN_DIR . 'includes/wpinv-general-functions.php' );
194
-		require_once( WPINV_PLUGIN_DIR . 'includes/wpinv-helper-functions.php' );
195
-		require_once( WPINV_PLUGIN_DIR . 'includes/wpinv-tax-functions.php' );
196
-		require_once( WPINV_PLUGIN_DIR . 'includes/wpinv-template-functions.php' );
197
-		require_once( WPINV_PLUGIN_DIR . 'includes/wpinv-address-functions.php' );
198
-		require_once( WPINV_PLUGIN_DIR . 'includes/invoice-functions.php' );
199
-		require_once( WPINV_PLUGIN_DIR . 'includes/subscription-functions.php' );
200
-		require_once( WPINV_PLUGIN_DIR . 'includes/wpinv-item-functions.php' );
201
-		require_once( WPINV_PLUGIN_DIR . 'includes/wpinv-discount-functions.php' );
202
-		require_once( WPINV_PLUGIN_DIR . 'includes/wpinv-gateway-functions.php' );
203
-		require_once( WPINV_PLUGIN_DIR . 'includes/wpinv-payment-functions.php' );
204
-		require_once( WPINV_PLUGIN_DIR . 'includes/user-functions.php' );
205
-		require_once( WPINV_PLUGIN_DIR . 'includes/error-functions.php' );
206
-
207
-		// Register autoloader.
208
-		try {
209
-			spl_autoload_register( array( $this, 'autoload' ), true );
210
-		} catch ( Exception $e ) {
211
-			wpinv_error_log( $e->getMessage(), '', __FILE__, 149, true );
212
-		}
213
-
214
-		require_once( WPINV_PLUGIN_DIR . 'includes/abstracts/abstract-wpinv-session.php' );
215
-		require_once( WPINV_PLUGIN_DIR . 'includes/class-wpinv-session-handler.php' );
216
-		require_once( WPINV_PLUGIN_DIR . 'includes/class-wpinv-ajax.php' );
217
-		require_once( WPINV_PLUGIN_DIR . 'includes/class-wpinv-api.php' );
218
-		require_once( WPINV_PLUGIN_DIR . 'includes/class-wpinv-cache-helper.php' );
219
-		require_once( WPINV_PLUGIN_DIR . 'includes/class-wpinv-db.php' );
220
-		require_once( WPINV_PLUGIN_DIR . 'includes/admin/subscriptions.php' );
221
-		require_once( WPINV_PLUGIN_DIR . 'includes/class-wpinv-subscriptions-db.php' );
222
-		require_once( WPINV_PLUGIN_DIR . 'includes/wpinv-subscription.php' );
223
-		require_once( WPINV_PLUGIN_DIR . 'includes/abstracts/abstract-wpinv-privacy.php' );
224
-		require_once( WPINV_PLUGIN_DIR . 'includes/class-wpinv-privacy.php' );
225
-		require_once( WPINV_PLUGIN_DIR . 'includes/libraries/class-ayecode-addons.php' );
226
-		require_once( WPINV_PLUGIN_DIR . 'includes/class-wpinv-addons.php' );
227
-		require_once( WPINV_PLUGIN_DIR . 'widgets/checkout.php' );
228
-		require_once( WPINV_PLUGIN_DIR . 'widgets/invoice-history.php' );
229
-		require_once( WPINV_PLUGIN_DIR . 'widgets/invoice-receipt.php' );
230
-		require_once( WPINV_PLUGIN_DIR . 'widgets/invoice-messages.php' );
231
-		require_once( WPINV_PLUGIN_DIR . 'widgets/subscriptions.php' );
232
-		require_once( WPINV_PLUGIN_DIR . 'widgets/buy-item.php' );
233
-		require_once( WPINV_PLUGIN_DIR . 'widgets/getpaid.php' );
234
-		require_once( WPINV_PLUGIN_DIR . 'includes/admin/admin-pages.php' );
235
-
236
-		if ( is_admin() || ( defined( 'WP_CLI' ) && WP_CLI ) ) {
237
-			GetPaid_Post_Types_Admin::init();
238
-
239
-			require_once( WPINV_PLUGIN_DIR . 'includes/admin/wpinv-admin-functions.php' );
240
-			require_once( WPINV_PLUGIN_DIR . 'includes/admin/meta-boxes/class-mb-payment-form.php' );
241
-			require_once( WPINV_PLUGIN_DIR . 'includes/admin/meta-boxes/class-mb-invoice-notes.php' );
242
-			require_once( WPINV_PLUGIN_DIR . 'includes/admin/class-wpinv-admin-menus.php' );
243
-			require_once( WPINV_PLUGIN_DIR . 'includes/admin/class-wpinv-users.php' );
244
-			require_once( WPINV_PLUGIN_DIR . 'includes/admin/class-getpaid-admin-profile.php' );
245
-			// load the user class only on the users.php page
246
-			global $pagenow;
247
-			if($pagenow=='users.php'){
248
-				new WPInv_Admin_Users();
249
-			}
250
-		}
251
-
252
-		// Register cli commands
253
-		if ( defined( 'WP_CLI' ) && WP_CLI ) {
254
-			require_once( WPINV_PLUGIN_DIR . 'includes/class-wpinv-cli.php' );
255
-			WP_CLI::add_command( 'invoicing', 'WPInv_CLI' );
256
-		}
257
-
258
-	}
259
-
260
-	/**
261
-	 * Class autoloader
262
-	 *
263
-	 * @param       string $class_name The name of the class to load.
264
-	 * @access      public
265
-	 * @since       1.0.19
266
-	 * @return      void
267
-	 */
268
-	public function autoload( $class_name ) {
269
-
270
-		// Normalize the class name...
271
-		$class_name  = strtolower( $class_name );
272
-
273
-		// ... and make sure it is our class.
274
-		if ( false === strpos( $class_name, 'getpaid_' ) && false === strpos( $class_name, 'wpinv_' ) ) {
275
-			return;
276
-		}
277
-
278
-		// Next, prepare the file name from the class.
279
-		$file_name = 'class-' . str_replace( '_', '-', $class_name ) . '.php';
280
-
281
-		// Base path of the classes.
282
-		$plugin_path = untrailingslashit( WPINV_PLUGIN_DIR );
283
-
284
-		// And an array of possible locations in order of importance.
285
-		$locations = array(
286
-			"$plugin_path/includes",
287
-			"$plugin_path/includes/data-stores",
288
-			"$plugin_path/includes/gateways",
289
-			"$plugin_path/includes/payments",
290
-			"$plugin_path/includes/geolocation",
291
-			"$plugin_path/includes/reports",
292
-			"$plugin_path/includes/api",
293
-			"$plugin_path/includes/admin",
294
-			"$plugin_path/includes/admin/meta-boxes",
295
-		);
296
-
297
-		foreach ( apply_filters( 'getpaid_autoload_locations', $locations ) as $location ) {
298
-
299
-			if ( file_exists( trailingslashit( $location ) . $file_name ) ) {
300
-				include trailingslashit( $location ) . $file_name;
301
-				break;
302
-			}
303
-
304
-		}
305
-
306
-	}
307
-
308
-	/**
309
-	 * Inits hooks etc.
310
-	 */
311
-	public function init() {
312
-
313
-		// Fires before getpaid inits.
314
-		do_action( 'before_getpaid_init', $this );
315
-
316
-		// Maybe upgrade.
317
-		$this->maybe_upgrade_database();
318
-
319
-		// Load default gateways.
320
-		$gateways = apply_filters(
321
-			'getpaid_default_gateways',
322
-			array(
323
-				'manual'        => 'GetPaid_Manual_Gateway',
324
-				'paypal'        => 'GetPaid_Paypal_Gateway',
325
-				'worldpay'      => 'GetPaid_Worldpay_Gateway',
326
-				'bank_transfer' => 'GetPaid_Bank_Transfer_Gateway',
327
-				'authorizenet'  => 'GetPaid_Authorize_Net_Gateway',
328
-			)
329
-		);
330
-
331
-		foreach ( $gateways as $id => $class ) {
332
-			$this->gateways[ $id ] = new $class();
333
-		}
334
-
335
-		if ( 'yes' != get_option( 'wpinv_renamed_gateways' ) ) {
336
-			GetPaid_Installer::rename_gateways_label();
337
-			update_option( 'wpinv_renamed_gateways', 'yes' );
338
-		}
339
-
340
-		// Fires after getpaid inits.
341
-		do_action( 'getpaid_init', $this );
342
-
343
-	}
344
-
345
-	/**
346
-	 * Checks if this is an IPN request and processes it.
347
-	 */
348
-	public function maybe_process_ipn() {
349
-
350
-		// Ensure that this is an IPN request.
351
-		if ( empty( $_GET['wpi-listener'] ) || 'IPN' !== $_GET['wpi-listener'] || empty( $_GET['wpi-gateway'] ) ) {
352
-			return;
353
-		}
354
-
355
-		$gateway = wpinv_clean( $_GET['wpi-gateway'] );
356
-
357
-		do_action( 'wpinv_verify_payment_ipn', $gateway );
358
-		do_action( "wpinv_verify_{$gateway}_ipn" );
359
-		exit;
360
-
361
-	}
362
-
363
-	public function enqueue_scripts() {
364
-
365
-		// Fires before adding scripts.
366
-		do_action( 'getpaid_enqueue_scripts' );
367
-
368
-		$localize                         = array();
369
-		$localize['ajax_url']             = admin_url( 'admin-ajax.php' );
370
-		$localize['nonce']                = wp_create_nonce( 'wpinv-nonce' );
371
-		$localize['txtComplete']          = __( 'Continue', 'invoicing' );
372
-		$localize['UseTaxes']             = wpinv_use_taxes();
373
-		$localize['formNonce']            = wp_create_nonce( 'getpaid_form_nonce' );
374
-		$localize['loading']              = __( 'Loading...', 'invoicing' );
375
-		$localize['connectionError']      = __( 'Could not establish a connection to the server.', 'invoicing' );
376
-
377
-		$localize = apply_filters( 'wpinv_front_js_localize', $localize );
378
-
379
-		$version = filemtime( WPINV_PLUGIN_DIR . 'assets/js/payment-forms.js' );
380
-		wp_enqueue_script( 'wpinv-front-script', WPINV_PLUGIN_URL . 'assets/js/payment-forms.js', array( 'jquery' ),  $version, true );
381
-		wp_localize_script( 'wpinv-front-script', 'WPInv', $localize );
382
-	}
383
-
384
-	public function wpinv_actions() {
385
-		if ( isset( $_REQUEST['wpi_action'] ) ) {
386
-			do_action( 'wpinv_' . wpinv_sanitize_key( $_REQUEST['wpi_action'] ), $_REQUEST );
387
-		}
388
-	}
389
-
390
-	/**
136
+        add_action( 'pre_get_posts', array( $this, 'maybe_process_new_ipn' ), 1 );
137
+
138
+        // Fires after registering actions.
139
+        do_action( 'wpinv_actions', $this );
140
+        do_action( 'getpaid_actions', $this );
141
+
142
+    }
143
+
144
+    public function plugins_loaded() {
145
+        /* Internationalize the text strings used. */
146
+        $this->load_textdomain();
147
+
148
+        do_action( 'wpinv_loaded' );
149
+
150
+        // Fix oxygen page builder conflict
151
+        if ( function_exists( 'ct_css_output' ) ) {
152
+            wpinv_oxygen_fix_conflict();
153
+        }
154
+    }
155
+
156
+    /**
157
+     * Load the translation of the plugin.
158
+     *
159
+     * @since 1.0
160
+     */
161
+    public function load_textdomain( $locale = NULL ) {
162
+        if ( empty( $locale ) ) {
163
+            $locale = is_admin() && function_exists( 'get_user_locale' ) ? get_user_locale() : get_locale();
164
+        }
165
+
166
+        $locale = apply_filters( 'plugin_locale', $locale, 'invoicing' );
167
+
168
+        unload_textdomain( 'invoicing' );
169
+        load_textdomain( 'invoicing', WP_LANG_DIR . '/invoicing/invoicing-' . $locale . '.mo' );
170
+        load_plugin_textdomain( 'invoicing', false, WPINV_PLUGIN_DIR . 'languages' );
171
+
172
+        /**
173
+         * Define language constants.
174
+         */
175
+        require_once( WPINV_PLUGIN_DIR . 'language.php' );
176
+    }
177
+
178
+    /**
179
+     * Include required core files used in admin and on the frontend.
180
+     */
181
+    public function includes() {
182
+
183
+        // Start with the settings.
184
+        require_once( WPINV_PLUGIN_DIR . 'includes/admin/register-settings.php' );
185
+
186
+        // Packages/libraries.
187
+        require_once( WPINV_PLUGIN_DIR . 'vendor/autoload.php' );
188
+        require_once( WPINV_PLUGIN_DIR . 'vendor/ayecode/wp-ayecode-ui/ayecode-ui-loader.php' );
189
+
190
+        // Load functions.
191
+        require_once( WPINV_PLUGIN_DIR . 'includes/deprecated-functions.php' );
192
+        require_once( WPINV_PLUGIN_DIR . 'includes/wpinv-email-functions.php' );
193
+        require_once( WPINV_PLUGIN_DIR . 'includes/wpinv-general-functions.php' );
194
+        require_once( WPINV_PLUGIN_DIR . 'includes/wpinv-helper-functions.php' );
195
+        require_once( WPINV_PLUGIN_DIR . 'includes/wpinv-tax-functions.php' );
196
+        require_once( WPINV_PLUGIN_DIR . 'includes/wpinv-template-functions.php' );
197
+        require_once( WPINV_PLUGIN_DIR . 'includes/wpinv-address-functions.php' );
198
+        require_once( WPINV_PLUGIN_DIR . 'includes/invoice-functions.php' );
199
+        require_once( WPINV_PLUGIN_DIR . 'includes/subscription-functions.php' );
200
+        require_once( WPINV_PLUGIN_DIR . 'includes/wpinv-item-functions.php' );
201
+        require_once( WPINV_PLUGIN_DIR . 'includes/wpinv-discount-functions.php' );
202
+        require_once( WPINV_PLUGIN_DIR . 'includes/wpinv-gateway-functions.php' );
203
+        require_once( WPINV_PLUGIN_DIR . 'includes/wpinv-payment-functions.php' );
204
+        require_once( WPINV_PLUGIN_DIR . 'includes/user-functions.php' );
205
+        require_once( WPINV_PLUGIN_DIR . 'includes/error-functions.php' );
206
+
207
+        // Register autoloader.
208
+        try {
209
+            spl_autoload_register( array( $this, 'autoload' ), true );
210
+        } catch ( Exception $e ) {
211
+            wpinv_error_log( $e->getMessage(), '', __FILE__, 149, true );
212
+        }
213
+
214
+        require_once( WPINV_PLUGIN_DIR . 'includes/abstracts/abstract-wpinv-session.php' );
215
+        require_once( WPINV_PLUGIN_DIR . 'includes/class-wpinv-session-handler.php' );
216
+        require_once( WPINV_PLUGIN_DIR . 'includes/class-wpinv-ajax.php' );
217
+        require_once( WPINV_PLUGIN_DIR . 'includes/class-wpinv-api.php' );
218
+        require_once( WPINV_PLUGIN_DIR . 'includes/class-wpinv-cache-helper.php' );
219
+        require_once( WPINV_PLUGIN_DIR . 'includes/class-wpinv-db.php' );
220
+        require_once( WPINV_PLUGIN_DIR . 'includes/admin/subscriptions.php' );
221
+        require_once( WPINV_PLUGIN_DIR . 'includes/class-wpinv-subscriptions-db.php' );
222
+        require_once( WPINV_PLUGIN_DIR . 'includes/wpinv-subscription.php' );
223
+        require_once( WPINV_PLUGIN_DIR . 'includes/abstracts/abstract-wpinv-privacy.php' );
224
+        require_once( WPINV_PLUGIN_DIR . 'includes/class-wpinv-privacy.php' );
225
+        require_once( WPINV_PLUGIN_DIR . 'includes/libraries/class-ayecode-addons.php' );
226
+        require_once( WPINV_PLUGIN_DIR . 'includes/class-wpinv-addons.php' );
227
+        require_once( WPINV_PLUGIN_DIR . 'widgets/checkout.php' );
228
+        require_once( WPINV_PLUGIN_DIR . 'widgets/invoice-history.php' );
229
+        require_once( WPINV_PLUGIN_DIR . 'widgets/invoice-receipt.php' );
230
+        require_once( WPINV_PLUGIN_DIR . 'widgets/invoice-messages.php' );
231
+        require_once( WPINV_PLUGIN_DIR . 'widgets/subscriptions.php' );
232
+        require_once( WPINV_PLUGIN_DIR . 'widgets/buy-item.php' );
233
+        require_once( WPINV_PLUGIN_DIR . 'widgets/getpaid.php' );
234
+        require_once( WPINV_PLUGIN_DIR . 'includes/admin/admin-pages.php' );
235
+
236
+        if ( is_admin() || ( defined( 'WP_CLI' ) && WP_CLI ) ) {
237
+            GetPaid_Post_Types_Admin::init();
238
+
239
+            require_once( WPINV_PLUGIN_DIR . 'includes/admin/wpinv-admin-functions.php' );
240
+            require_once( WPINV_PLUGIN_DIR . 'includes/admin/meta-boxes/class-mb-payment-form.php' );
241
+            require_once( WPINV_PLUGIN_DIR . 'includes/admin/meta-boxes/class-mb-invoice-notes.php' );
242
+            require_once( WPINV_PLUGIN_DIR . 'includes/admin/class-wpinv-admin-menus.php' );
243
+            require_once( WPINV_PLUGIN_DIR . 'includes/admin/class-wpinv-users.php' );
244
+            require_once( WPINV_PLUGIN_DIR . 'includes/admin/class-getpaid-admin-profile.php' );
245
+            // load the user class only on the users.php page
246
+            global $pagenow;
247
+            if($pagenow=='users.php'){
248
+                new WPInv_Admin_Users();
249
+            }
250
+        }
251
+
252
+        // Register cli commands
253
+        if ( defined( 'WP_CLI' ) && WP_CLI ) {
254
+            require_once( WPINV_PLUGIN_DIR . 'includes/class-wpinv-cli.php' );
255
+            WP_CLI::add_command( 'invoicing', 'WPInv_CLI' );
256
+        }
257
+
258
+    }
259
+
260
+    /**
261
+     * Class autoloader
262
+     *
263
+     * @param       string $class_name The name of the class to load.
264
+     * @access      public
265
+     * @since       1.0.19
266
+     * @return      void
267
+     */
268
+    public function autoload( $class_name ) {
269
+
270
+        // Normalize the class name...
271
+        $class_name  = strtolower( $class_name );
272
+
273
+        // ... and make sure it is our class.
274
+        if ( false === strpos( $class_name, 'getpaid_' ) && false === strpos( $class_name, 'wpinv_' ) ) {
275
+            return;
276
+        }
277
+
278
+        // Next, prepare the file name from the class.
279
+        $file_name = 'class-' . str_replace( '_', '-', $class_name ) . '.php';
280
+
281
+        // Base path of the classes.
282
+        $plugin_path = untrailingslashit( WPINV_PLUGIN_DIR );
283
+
284
+        // And an array of possible locations in order of importance.
285
+        $locations = array(
286
+            "$plugin_path/includes",
287
+            "$plugin_path/includes/data-stores",
288
+            "$plugin_path/includes/gateways",
289
+            "$plugin_path/includes/payments",
290
+            "$plugin_path/includes/geolocation",
291
+            "$plugin_path/includes/reports",
292
+            "$plugin_path/includes/api",
293
+            "$plugin_path/includes/admin",
294
+            "$plugin_path/includes/admin/meta-boxes",
295
+        );
296
+
297
+        foreach ( apply_filters( 'getpaid_autoload_locations', $locations ) as $location ) {
298
+
299
+            if ( file_exists( trailingslashit( $location ) . $file_name ) ) {
300
+                include trailingslashit( $location ) . $file_name;
301
+                break;
302
+            }
303
+
304
+        }
305
+
306
+    }
307
+
308
+    /**
309
+     * Inits hooks etc.
310
+     */
311
+    public function init() {
312
+
313
+        // Fires before getpaid inits.
314
+        do_action( 'before_getpaid_init', $this );
315
+
316
+        // Maybe upgrade.
317
+        $this->maybe_upgrade_database();
318
+
319
+        // Load default gateways.
320
+        $gateways = apply_filters(
321
+            'getpaid_default_gateways',
322
+            array(
323
+                'manual'        => 'GetPaid_Manual_Gateway',
324
+                'paypal'        => 'GetPaid_Paypal_Gateway',
325
+                'worldpay'      => 'GetPaid_Worldpay_Gateway',
326
+                'bank_transfer' => 'GetPaid_Bank_Transfer_Gateway',
327
+                'authorizenet'  => 'GetPaid_Authorize_Net_Gateway',
328
+            )
329
+        );
330
+
331
+        foreach ( $gateways as $id => $class ) {
332
+            $this->gateways[ $id ] = new $class();
333
+        }
334
+
335
+        if ( 'yes' != get_option( 'wpinv_renamed_gateways' ) ) {
336
+            GetPaid_Installer::rename_gateways_label();
337
+            update_option( 'wpinv_renamed_gateways', 'yes' );
338
+        }
339
+
340
+        // Fires after getpaid inits.
341
+        do_action( 'getpaid_init', $this );
342
+
343
+    }
344
+
345
+    /**
346
+     * Checks if this is an IPN request and processes it.
347
+     */
348
+    public function maybe_process_ipn() {
349
+
350
+        // Ensure that this is an IPN request.
351
+        if ( empty( $_GET['wpi-listener'] ) || 'IPN' !== $_GET['wpi-listener'] || empty( $_GET['wpi-gateway'] ) ) {
352
+            return;
353
+        }
354
+
355
+        $gateway = wpinv_clean( $_GET['wpi-gateway'] );
356
+
357
+        do_action( 'wpinv_verify_payment_ipn', $gateway );
358
+        do_action( "wpinv_verify_{$gateway}_ipn" );
359
+        exit;
360
+
361
+    }
362
+
363
+    public function enqueue_scripts() {
364
+
365
+        // Fires before adding scripts.
366
+        do_action( 'getpaid_enqueue_scripts' );
367
+
368
+        $localize                         = array();
369
+        $localize['ajax_url']             = admin_url( 'admin-ajax.php' );
370
+        $localize['nonce']                = wp_create_nonce( 'wpinv-nonce' );
371
+        $localize['txtComplete']          = __( 'Continue', 'invoicing' );
372
+        $localize['UseTaxes']             = wpinv_use_taxes();
373
+        $localize['formNonce']            = wp_create_nonce( 'getpaid_form_nonce' );
374
+        $localize['loading']              = __( 'Loading...', 'invoicing' );
375
+        $localize['connectionError']      = __( 'Could not establish a connection to the server.', 'invoicing' );
376
+
377
+        $localize = apply_filters( 'wpinv_front_js_localize', $localize );
378
+
379
+        $version = filemtime( WPINV_PLUGIN_DIR . 'assets/js/payment-forms.js' );
380
+        wp_enqueue_script( 'wpinv-front-script', WPINV_PLUGIN_URL . 'assets/js/payment-forms.js', array( 'jquery' ),  $version, true );
381
+        wp_localize_script( 'wpinv-front-script', 'WPInv', $localize );
382
+    }
383
+
384
+    public function wpinv_actions() {
385
+        if ( isset( $_REQUEST['wpi_action'] ) ) {
386
+            do_action( 'wpinv_' . wpinv_sanitize_key( $_REQUEST['wpi_action'] ), $_REQUEST );
387
+        }
388
+    }
389
+
390
+    /**
391 391
      * Fires an action after verifying that a user can fire them.
392
-	 *
393
-	 * Note: If the action is on an invoice, subscription etc, esure that the
394
-	 * current user owns the invoice/subscription.
392
+     *
393
+     * Note: If the action is on an invoice, subscription etc, esure that the
394
+     * current user owns the invoice/subscription.
395 395
      */
396 396
     public function maybe_do_authenticated_action() {
397 397
 
398
-		if ( isset( $_REQUEST['getpaid-action'] ) && isset( $_REQUEST['getpaid-nonce'] ) && wp_verify_nonce( $_REQUEST['getpaid-nonce'], 'getpaid-nonce' ) ) {
398
+        if ( isset( $_REQUEST['getpaid-action'] ) && isset( $_REQUEST['getpaid-nonce'] ) && wp_verify_nonce( $_REQUEST['getpaid-nonce'], 'getpaid-nonce' ) ) {
399
+
400
+            $key  = sanitize_key( $_REQUEST['getpaid-action'] );
401
+            $data = wp_unslash( $_REQUEST );
402
+            if ( is_user_logged_in() ) {
403
+                do_action( "getpaid_authenticated_action_$key", $data );
404
+            }
405
+
406
+            do_action( "getpaid_unauthenticated_action_$key", $data );
407
+
408
+        }
399 409
 
400
-			$key  = sanitize_key( $_REQUEST['getpaid-action'] );
401
-			$data = wp_unslash( $_REQUEST );
402
-			if ( is_user_logged_in() ) {
403
-				do_action( "getpaid_authenticated_action_$key", $data );
404
-			}
410
+    }
405 411
 
406
-			do_action( "getpaid_unauthenticated_action_$key", $data );
412
+    public function pre_get_posts( $wp_query ) {
407 413
 
408
-		}
414
+        if ( ! is_admin() && ! empty( $wp_query->query_vars['post_type'] ) && getpaid_is_invoice_post_type( $wp_query->query_vars['post_type'] ) && is_user_logged_in() && is_single() && $wp_query->is_main_query() ) {
415
+            $wp_query->query_vars['post_status'] = array_keys( wpinv_get_invoice_statuses( false, false, $wp_query->query_vars['post_type'] ) );
416
+        }
409 417
 
418
+        return $wp_query;
410 419
     }
411 420
 
412
-	public function pre_get_posts( $wp_query ) {
413
-
414
-		if ( ! is_admin() && ! empty( $wp_query->query_vars['post_type'] ) && getpaid_is_invoice_post_type( $wp_query->query_vars['post_type'] ) && is_user_logged_in() && is_single() && $wp_query->is_main_query() ) {
415
-			$wp_query->query_vars['post_status'] = array_keys( wpinv_get_invoice_statuses( false, false, $wp_query->query_vars['post_type'] ) );
416
-		}
417
-
418
-		return $wp_query;
419
-	}
420
-
421
-	/**
422
-	 * Register widgets
423
-	 *
424
-	 */
425
-	public function register_widgets() {
426
-
427
-		// Currently, UX Builder does not work particulaly well with SuperDuper.
428
-		// So we disable our widgets when editing a page with UX Builder.
429
-		if ( function_exists( 'ux_builder_is_active' ) && ux_builder_is_active() ) {
430
-			return;
431
-		}
432
-
433
-		$widgets = apply_filters(
434
-			'getpaid_widget_classes',
435
-			array(
436
-				'WPInv_Checkout_Widget',
437
-				'WPInv_History_Widget',
438
-				'WPInv_Receipt_Widget',
439
-				'WPInv_Subscriptions_Widget',
440
-				'WPInv_Buy_Item_Widget',
441
-				'WPInv_Messages_Widget',
442
-				'WPInv_GetPaid_Widget'
443
-			)
444
-		);
445
-
446
-		foreach ( $widgets as $widget ) {
447
-			register_widget( $widget );
448
-		}
421
+    /**
422
+     * Register widgets
423
+     *
424
+     */
425
+    public function register_widgets() {
426
+
427
+        // Currently, UX Builder does not work particulaly well with SuperDuper.
428
+        // So we disable our widgets when editing a page with UX Builder.
429
+        if ( function_exists( 'ux_builder_is_active' ) && ux_builder_is_active() ) {
430
+            return;
431
+        }
432
+
433
+        $widgets = apply_filters(
434
+            'getpaid_widget_classes',
435
+            array(
436
+                'WPInv_Checkout_Widget',
437
+                'WPInv_History_Widget',
438
+                'WPInv_Receipt_Widget',
439
+                'WPInv_Subscriptions_Widget',
440
+                'WPInv_Buy_Item_Widget',
441
+                'WPInv_Messages_Widget',
442
+                'WPInv_GetPaid_Widget'
443
+            )
444
+        );
445
+
446
+        foreach ( $widgets as $widget ) {
447
+            register_widget( $widget );
448
+        }
449 449
 		
450
-	}
450
+    }
451 451
 
452
-	/**
453
-	 * Upgrades the database.
454
-	 *
455
-	 * @since 2.0.2
456
-	 */
457
-	public function maybe_upgrade_database() {
452
+    /**
453
+     * Upgrades the database.
454
+     *
455
+     * @since 2.0.2
456
+     */
457
+    public function maybe_upgrade_database() {
458 458
 
459
-		$wpi_version = get_option( 'wpinv_version', 0 );
459
+        $wpi_version = get_option( 'wpinv_version', 0 );
460 460
 
461
-		if ( $wpi_version == WPINV_VERSION ) {
462
-			return;
463
-		}
461
+        if ( $wpi_version == WPINV_VERSION ) {
462
+            return;
463
+        }
464 464
 
465
-		$installer = new GetPaid_Installer();
465
+        $installer = new GetPaid_Installer();
466 466
 
467
-		if ( empty( $wpi_version ) ) {
468
-			return $installer->upgrade_db( 0 );
469
-		}
467
+        if ( empty( $wpi_version ) ) {
468
+            return $installer->upgrade_db( 0 );
469
+        }
470 470
 
471
-		$upgrades  = array(
472
-			'0.0.5' => '004',
473
-			'1.0.3' => '102',
474
-			'2.0.0' => '118',
475
-			'2.0.8' => '207',
476
-		);
471
+        $upgrades  = array(
472
+            '0.0.5' => '004',
473
+            '1.0.3' => '102',
474
+            '2.0.0' => '118',
475
+            '2.0.8' => '207',
476
+        );
477 477
 
478
-		foreach ( $upgrades as $key => $method ) {
478
+        foreach ( $upgrades as $key => $method ) {
479 479
 
480
-			if ( version_compare( $wpi_version, $key, '<' ) ) {
481
-				return $installer->upgrade_db( $method );
482
-			}
480
+            if ( version_compare( $wpi_version, $key, '<' ) ) {
481
+                return $installer->upgrade_db( $method );
482
+            }
483 483
 
484
-		}
484
+        }
485 485
 
486
-	}
486
+    }
487 487
 
488
-	/**
489
-	 * Flushes the permalinks if needed.
490
-	 *
491
-	 * @since 2.0.8
492
-	 */
493
-	public function maybe_flush_permalinks() {
488
+    /**
489
+     * Flushes the permalinks if needed.
490
+     *
491
+     * @since 2.0.8
492
+     */
493
+    public function maybe_flush_permalinks() {
494 494
 
495
-		$flush = get_option( 'wpinv_flush_permalinks', 0 );
495
+        $flush = get_option( 'wpinv_flush_permalinks', 0 );
496 496
 
497
-		if ( ! empty( $flush ) ) {
498
-			flush_rewrite_rules();
499
-			delete_option( 'wpinv_flush_permalinks' );
500
-		}
497
+        if ( ! empty( $flush ) ) {
498
+            flush_rewrite_rules();
499
+            delete_option( 'wpinv_flush_permalinks' );
500
+        }
501 501
 
502
-	}
502
+    }
503 503
 
504
-	/**
505
-	 * Remove our pages from yoast sitemaps.
506
-	 *
507
-	 * @since 1.0.19
508
-	 * @param int[] $excluded_posts_ids
509
-	 */
510
-	public function wpseo_exclude_from_sitemap_by_post_ids( $excluded_posts_ids ){
504
+    /**
505
+     * Remove our pages from yoast sitemaps.
506
+     *
507
+     * @since 1.0.19
508
+     * @param int[] $excluded_posts_ids
509
+     */
510
+    public function wpseo_exclude_from_sitemap_by_post_ids( $excluded_posts_ids ){
511 511
 
512
-		// Ensure that we have an array.
513
-		if ( ! is_array( $excluded_posts_ids ) ) {
514
-			$excluded_posts_ids = array();
515
-		}
512
+        // Ensure that we have an array.
513
+        if ( ! is_array( $excluded_posts_ids ) ) {
514
+            $excluded_posts_ids = array();
515
+        }
516 516
 
517
-		// Prepare our pages.
518
-		$our_pages = array();
517
+        // Prepare our pages.
518
+        $our_pages = array();
519 519
 
520
-		// Checkout page.
521
-		$our_pages[] = wpinv_get_option( 'checkout_page', false );
520
+        // Checkout page.
521
+        $our_pages[] = wpinv_get_option( 'checkout_page', false );
522 522
 
523
-		// Success page.
524
-		$our_pages[] = wpinv_get_option( 'success_page', false );
523
+        // Success page.
524
+        $our_pages[] = wpinv_get_option( 'success_page', false );
525 525
 
526
-		// Failure page.
527
-		$our_pages[] = wpinv_get_option( 'failure_page', false );
526
+        // Failure page.
527
+        $our_pages[] = wpinv_get_option( 'failure_page', false );
528 528
 
529
-		// History page.
530
-		$our_pages[] = wpinv_get_option( 'invoice_history_page', false );
529
+        // History page.
530
+        $our_pages[] = wpinv_get_option( 'invoice_history_page', false );
531 531
 
532
-		// Subscriptions page.
533
-		$our_pages[] = wpinv_get_option( 'invoice_subscription_page', false );
532
+        // Subscriptions page.
533
+        $our_pages[] = wpinv_get_option( 'invoice_subscription_page', false );
534 534
 
535
-		$our_pages   = array_map( 'intval', array_filter( $our_pages ) );
535
+        $our_pages   = array_map( 'intval', array_filter( $our_pages ) );
536 536
 
537
-		$excluded_posts_ids = $excluded_posts_ids + $our_pages;
538
-		return array_unique( $excluded_posts_ids );
537
+        $excluded_posts_ids = $excluded_posts_ids + $our_pages;
538
+        return array_unique( $excluded_posts_ids );
539 539
 
540
-	}
540
+    }
541 541
 
542
-	/**
543
-	 * Displays additional footer code.
544
-	 * 
545
-	 * @since 2.0.0
546
-	 */
547
-	public function wp_footer() {
548
-		wpinv_get_template( 'frontend-footer.php' );
549
-	}
542
+    /**
543
+     * Displays additional footer code.
544
+     * 
545
+     * @since 2.0.0
546
+     */
547
+    public function wp_footer() {
548
+        wpinv_get_template( 'frontend-footer.php' );
549
+    }
550 550
 
551
-	/**
552
-	 * Displays additional header code.
553
-	 * 
554
-	 * @since 2.0.0
555
-	 */
556
-	public function wp_head() {
557
-		wpinv_get_template( 'frontend-head.php' );
558
-	}
551
+    /**
552
+     * Displays additional header code.
553
+     * 
554
+     * @since 2.0.0
555
+     */
556
+    public function wp_head() {
557
+        wpinv_get_template( 'frontend-head.php' );
558
+    }
559 559
 
560
-	/**
561
-	 * Custom query vars.
562
-	 *
563
-	 */
564
-	public function custom_query_vars( $vars ) {
560
+    /**
561
+     * Custom query vars.
562
+     *
563
+     */
564
+    public function custom_query_vars( $vars ) {
565 565
         $vars[] = 'getpaid-ipn';
566 566
         return $vars;
567
-	}
567
+    }
568 568
 
569
-	/**
570
-	 * Add rewrite tags and rules.
571
-	 *
572
-	 */
573
-	public function add_rewrite_rule() {
569
+    /**
570
+     * Add rewrite tags and rules.
571
+     *
572
+     */
573
+    public function add_rewrite_rule() {
574 574
         $tag = 'getpaid-ipn';
575 575
         add_rewrite_tag( "%$tag%", '([^&]+)' );
576 576
         add_rewrite_rule( "^$tag/([^/]*)/?", "index.php?$tag=\$matches[1]",'top' );
577
-	}
577
+    }
578 578
 
579
-	/**
580
-	 * Processes non-query string ipns.
581
-	 *
582
-	 */
583
-	public function maybe_process_new_ipn( $query ) {
579
+    /**
580
+     * Processes non-query string ipns.
581
+     *
582
+     */
583
+    public function maybe_process_new_ipn( $query ) {
584 584
 
585 585
         if ( is_admin() || ! $query->is_main_query() ) {
586 586
             return;
587 587
         }
588 588
 
589
-		$gateway = get_query_var( 'getpaid-ipn' );
589
+        $gateway = get_query_var( 'getpaid-ipn' );
590 590
 
591 591
         if ( ! empty( $gateway ) ){
592 592
 
593
-			$gateway = sanitize_text_field( $gateway );
594
-			nocache_headers();
595
-			do_action( 'wpinv_verify_payment_ipn', $gateway );
596
-			do_action( "wpinv_verify_{$gateway}_ipn" );
597
-			exit;
593
+            $gateway = sanitize_text_field( $gateway );
594
+            nocache_headers();
595
+            do_action( 'wpinv_verify_payment_ipn', $gateway );
596
+            do_action( "wpinv_verify_{$gateway}_ipn" );
597
+            exit;
598 598
 
599 599
         }
600 600
 
601
-	}
601
+    }
602 602
 
603 603
 }
Please login to merge, or discard this patch.
includes/payments/class-getpaid-payment-form-submission.php 1 patch
Indentation   +804 added lines, -804 removed lines patch added patch discarded remove patch
@@ -1,6 +1,6 @@  discard block
 block discarded – undo
1 1
 <?php
2 2
 if ( ! defined( 'ABSPATH' ) ) {
3
-	exit;
3
+    exit;
4 4
 }
5 5
 
6 6
 /**
@@ -10,198 +10,198 @@  discard block
 block discarded – undo
10 10
 class GetPaid_Payment_Form_Submission {
11 11
 
12 12
     /**
13
-	 * Submission ID
14
-	 *
15
-	 * @var string
16
-	 */
17
-	public $id = null;
18
-
19
-	/**
20
-	 * The raw submission data.
21
-	 *
22
-	 * @var array
23
-	 */
24
-	protected $data = null;
25
-
26
-	/**
27
-	 * Submission totals
28
-	 *
29
-	 * @var array
30
-	 */
31
-	protected $totals = array(
32
-
33
-		'subtotal'      => array(
34
-			'initial'   => 0,
35
-			'recurring' => 0,
36
-		),
37
-
38
-		'discount'      => array(
39
-			'initial'   => 0,
40
-			'recurring' => 0,
41
-		),
42
-
43
-		'fees'          => array(
44
-			'initial'   => 0,
45
-			'recurring' => 0,
46
-		),
47
-
48
-		'taxes'         => array(
49
-			'initial'   => 0,
50
-			'recurring' => 0,
51
-		),
52
-
53
-	);
54
-
55
-	/**
56
-	 * Sets the associated payment form.
57
-	 *
58
-	 * @var GetPaid_Payment_Form
59
-	 */
13
+     * Submission ID
14
+     *
15
+     * @var string
16
+     */
17
+    public $id = null;
18
+
19
+    /**
20
+     * The raw submission data.
21
+     *
22
+     * @var array
23
+     */
24
+    protected $data = null;
25
+
26
+    /**
27
+     * Submission totals
28
+     *
29
+     * @var array
30
+     */
31
+    protected $totals = array(
32
+
33
+        'subtotal'      => array(
34
+            'initial'   => 0,
35
+            'recurring' => 0,
36
+        ),
37
+
38
+        'discount'      => array(
39
+            'initial'   => 0,
40
+            'recurring' => 0,
41
+        ),
42
+
43
+        'fees'          => array(
44
+            'initial'   => 0,
45
+            'recurring' => 0,
46
+        ),
47
+
48
+        'taxes'         => array(
49
+            'initial'   => 0,
50
+            'recurring' => 0,
51
+        ),
52
+
53
+    );
54
+
55
+    /**
56
+     * Sets the associated payment form.
57
+     *
58
+     * @var GetPaid_Payment_Form
59
+     */
60 60
     protected $payment_form = null;
61 61
 
62 62
     /**
63
-	 * The country for the submission.
64
-	 *
65
-	 * @var string
66
-	 */
67
-	public $country = null;
68
-
69
-    /**
70
-	 * The state for the submission.
71
-	 *
72
-	 * @since 1.0.19
73
-	 * @var string
74
-	 */
75
-	public $state = null;
76
-
77
-	/**
78
-	 * The invoice associated with the submission.
79
-	 *
80
-	 * @var WPInv_Invoice
81
-	 */
82
-	protected $invoice = null;
83
-
84
-	/**
85
-	 * The recurring item for the submission.
86
-	 *
87
-	 * @var int
88
-	 */
89
-	public $has_recurring = 0;
90
-
91
-	/**
92
-	 * An array of fees for the submission.
93
-	 *
94
-	 * @var array
95
-	 */
96
-	protected $fees = array();
97
-
98
-	/**
99
-	 * An array of discounts for the submission.
100
-	 *
101
-	 * @var array
102
-	 */
103
-	protected $discounts = array();
104
-
105
-	/**
106
-	 * An array of taxes for the submission.
107
-	 *
108
-	 * @var array
109
-	 */
110
-	protected $taxes = array();
111
-
112
-	/**
113
-	 * An array of items for the submission.
114
-	 *
115
-	 * @var GetPaid_Form_Item[]
116
-	 */
117
-	protected $items = array();
118
-
119
-	/**
120
-	 * The last error.
121
-	 *
122
-	 * @var string
123
-	 */
124
-	public $last_error = null;
125
-
126
-	/**
127
-	 * The last error code.
128
-	 *
129
-	 * @var string
130
-	 */
131
-	public $last_error_code = null;
132
-
133
-    /**
134
-	 * Class constructor.
135
-	 *
136
-	 */
137
-	public function __construct() {
138
-
139
-		// Set the state and country to the default state and country.
140
-		$this->country = wpinv_default_billing_country();
141
-		$this->state   = wpinv_get_default_state();
142
-
143
-		// Do we have an actual submission?
144
-		if ( isset( $_POST['getpaid_payment_form_submission'] ) ) {
145
-			$this->load_data( $_POST );
146
-		}
147
-
148
-	}
149
-
150
-	/**
151
-	 * Loads submission data.
152
-	 *
153
-	 * @param array $data
154
-	 */
155
-	public function load_data( $data ) {
156
-
157
-		// Remove slashes from the submitted data...
158
-		$data       = wp_unslash( $data );
159
-
160
-		// Allow plugins to filter the data.
161
-		$data       = apply_filters( 'getpaid_submission_data', $data, $this );
162
-
163
-		// Cache it...
164
-		$this->data = $data;
165
-
166
-		// Then generate a unique id from the data.
167
-		$this->id   = md5( wp_json_encode( $data ) );
168
-
169
-		// Finally, process the submission.
170
-		try {
171
-
172
-			// Each process is passed an instance of the class (with reference)
173
-			// and should throw an Exception whenever it encounters one.
174
-			$processors = apply_filters(
175
-				'getpaid_payment_form_submission_processors',
176
-				array(
177
-					array( $this, 'process_payment_form' ),
178
-					array( $this, 'process_invoice' ),
179
-					array( $this, 'process_fees' ),
180
-					array( $this, 'process_items' ),
181
-					array( $this, 'process_discount' ),
182
-					array( $this, 'process_taxes' ),
183
-				),
184
-				$this		
185
-			);
186
-
187
-			foreach ( $processors as $processor ) {
188
-				call_user_func_array( $processor, array( &$this ) );
189
-			}
190
-
191
-		} catch( GetPaid_Payment_Exception $e ) {
192
-			$this->last_error      = $e->getMessage();
193
-			$this->last_error_code = $e->getErrorCode();
194
-		} catch ( Exception $e ) {
195
-			$this->last_error      = $e->getMessage();
196
-			$this->last_error_code = $e->getCode();
197
-		}
198
-
199
-		// Fired when we are done processing a submission.
200
-		do_action_ref_array( 'getpaid_process_submission', array( &$this ) );
201
-
202
-	}
203
-
204
-	/*
63
+     * The country for the submission.
64
+     *
65
+     * @var string
66
+     */
67
+    public $country = null;
68
+
69
+    /**
70
+     * The state for the submission.
71
+     *
72
+     * @since 1.0.19
73
+     * @var string
74
+     */
75
+    public $state = null;
76
+
77
+    /**
78
+     * The invoice associated with the submission.
79
+     *
80
+     * @var WPInv_Invoice
81
+     */
82
+    protected $invoice = null;
83
+
84
+    /**
85
+     * The recurring item for the submission.
86
+     *
87
+     * @var int
88
+     */
89
+    public $has_recurring = 0;
90
+
91
+    /**
92
+     * An array of fees for the submission.
93
+     *
94
+     * @var array
95
+     */
96
+    protected $fees = array();
97
+
98
+    /**
99
+     * An array of discounts for the submission.
100
+     *
101
+     * @var array
102
+     */
103
+    protected $discounts = array();
104
+
105
+    /**
106
+     * An array of taxes for the submission.
107
+     *
108
+     * @var array
109
+     */
110
+    protected $taxes = array();
111
+
112
+    /**
113
+     * An array of items for the submission.
114
+     *
115
+     * @var GetPaid_Form_Item[]
116
+     */
117
+    protected $items = array();
118
+
119
+    /**
120
+     * The last error.
121
+     *
122
+     * @var string
123
+     */
124
+    public $last_error = null;
125
+
126
+    /**
127
+     * The last error code.
128
+     *
129
+     * @var string
130
+     */
131
+    public $last_error_code = null;
132
+
133
+    /**
134
+     * Class constructor.
135
+     *
136
+     */
137
+    public function __construct() {
138
+
139
+        // Set the state and country to the default state and country.
140
+        $this->country = wpinv_default_billing_country();
141
+        $this->state   = wpinv_get_default_state();
142
+
143
+        // Do we have an actual submission?
144
+        if ( isset( $_POST['getpaid_payment_form_submission'] ) ) {
145
+            $this->load_data( $_POST );
146
+        }
147
+
148
+    }
149
+
150
+    /**
151
+     * Loads submission data.
152
+     *
153
+     * @param array $data
154
+     */
155
+    public function load_data( $data ) {
156
+
157
+        // Remove slashes from the submitted data...
158
+        $data       = wp_unslash( $data );
159
+
160
+        // Allow plugins to filter the data.
161
+        $data       = apply_filters( 'getpaid_submission_data', $data, $this );
162
+
163
+        // Cache it...
164
+        $this->data = $data;
165
+
166
+        // Then generate a unique id from the data.
167
+        $this->id   = md5( wp_json_encode( $data ) );
168
+
169
+        // Finally, process the submission.
170
+        try {
171
+
172
+            // Each process is passed an instance of the class (with reference)
173
+            // and should throw an Exception whenever it encounters one.
174
+            $processors = apply_filters(
175
+                'getpaid_payment_form_submission_processors',
176
+                array(
177
+                    array( $this, 'process_payment_form' ),
178
+                    array( $this, 'process_invoice' ),
179
+                    array( $this, 'process_fees' ),
180
+                    array( $this, 'process_items' ),
181
+                    array( $this, 'process_discount' ),
182
+                    array( $this, 'process_taxes' ),
183
+                ),
184
+                $this		
185
+            );
186
+
187
+            foreach ( $processors as $processor ) {
188
+                call_user_func_array( $processor, array( &$this ) );
189
+            }
190
+
191
+        } catch( GetPaid_Payment_Exception $e ) {
192
+            $this->last_error      = $e->getMessage();
193
+            $this->last_error_code = $e->getErrorCode();
194
+        } catch ( Exception $e ) {
195
+            $this->last_error      = $e->getMessage();
196
+            $this->last_error_code = $e->getCode();
197
+        }
198
+
199
+        // Fired when we are done processing a submission.
200
+        do_action_ref_array( 'getpaid_process_submission', array( &$this ) );
201
+
202
+    }
203
+
204
+    /*
205 205
 	|--------------------------------------------------------------------------
206 206
 	| Payment Forms.
207 207
 	|--------------------------------------------------------------------------
@@ -210,39 +210,39 @@  discard block
 block discarded – undo
210 210
 	| submission has an active payment form etc.
211 211
     */
212 212
 
213
-	/**
214
-	 * Prepares the submission's payment form.
215
-	 *
216
-	 * @since 1.0.19
217
-	 */
218
-	public function process_payment_form() {
213
+    /**
214
+     * Prepares the submission's payment form.
215
+     *
216
+     * @since 1.0.19
217
+     */
218
+    public function process_payment_form() {
219 219
 
220
-		// Every submission needs an active payment form.
221
-		if ( empty( $this->data['form_id'] ) ) {
222
-			throw new Exception( __( 'Missing payment form', 'invoicing' ) );
223
-		}
220
+        // Every submission needs an active payment form.
221
+        if ( empty( $this->data['form_id'] ) ) {
222
+            throw new Exception( __( 'Missing payment form', 'invoicing' ) );
223
+        }
224 224
 
225
-		// Fetch the payment form.
226
-		$this->payment_form = new GetPaid_Payment_Form( $this->data['form_id'] );
225
+        // Fetch the payment form.
226
+        $this->payment_form = new GetPaid_Payment_Form( $this->data['form_id'] );
227 227
 
228
-		if ( ! $this->payment_form->is_active() ) {
229
-			throw new Exception( __( 'Payment form not active', 'invoicing' ) );
230
-		}
228
+        if ( ! $this->payment_form->is_active() ) {
229
+            throw new Exception( __( 'Payment form not active', 'invoicing' ) );
230
+        }
231 231
 
232
-		do_action_ref_array( 'getpaid_submissions_process_payment_form', array( &$this ) );
233
-	}
232
+        do_action_ref_array( 'getpaid_submissions_process_payment_form', array( &$this ) );
233
+    }
234 234
 
235 235
     /**
236
-	 * Returns the payment form.
237
-	 *
238
-	 * @since 1.0.19
239
-	 * @return GetPaid_Payment_Form
240
-	 */
241
-	public function get_payment_form() {
242
-		return $this->payment_form;
243
-	}
236
+     * Returns the payment form.
237
+     *
238
+     * @since 1.0.19
239
+     * @return GetPaid_Payment_Form
240
+     */
241
+    public function get_payment_form() {
242
+        return $this->payment_form;
243
+    }
244 244
 
245
-	/*
245
+    /*
246 246
 	|--------------------------------------------------------------------------
247 247
 	| Invoices.
248 248
 	|--------------------------------------------------------------------------
@@ -251,84 +251,84 @@  discard block
 block discarded – undo
251 251
 	| might be for an existing invoice.
252 252
 	*/
253 253
 
254
-	/**
255
-	 * Prepares the submission's invoice.
256
-	 *
257
-	 * @since 1.0.19
258
-	 */
259
-	public function process_invoice() {
254
+    /**
255
+     * Prepares the submission's invoice.
256
+     *
257
+     * @since 1.0.19
258
+     */
259
+    public function process_invoice() {
260 260
 
261
-		// Abort if there is no invoice.
262
-		if ( empty( $this->data['invoice_id'] ) ) {
263
-			return;
264
-		}
261
+        // Abort if there is no invoice.
262
+        if ( empty( $this->data['invoice_id'] ) ) {
263
+            return;
264
+        }
265 265
 
266
-		// If the submission is for an existing invoice, ensure that it exists
267
-		// and that it is not paid for.
268
-		$invoice = wpinv_get_invoice( $this->data['invoice_id'] );
266
+        // If the submission is for an existing invoice, ensure that it exists
267
+        // and that it is not paid for.
268
+        $invoice = wpinv_get_invoice( $this->data['invoice_id'] );
269 269
 
270 270
         if ( empty( $invoice ) ) {
271
-			throw new Exception( __( 'Invalid invoice', 'invoicing' ) );
272
-		}
271
+            throw new Exception( __( 'Invalid invoice', 'invoicing' ) );
272
+        }
273 273
 
274
-		if ( $invoice->is_paid() ) {
275
-			throw new Exception( __( 'This invoice is already paid for.', 'invoicing' ) );
276
-		}
274
+        if ( $invoice->is_paid() ) {
275
+            throw new Exception( __( 'This invoice is already paid for.', 'invoicing' ) );
276
+        }
277 277
 
278
-		$this->payment_form->invoice = $invoice;
279
-		if ( ! $this->payment_form->is_default() ) {
278
+        $this->payment_form->invoice = $invoice;
279
+        if ( ! $this->payment_form->is_default() ) {
280 280
 
281
-			$items    = array();
282
-			$item_ids = array();
281
+            $items    = array();
282
+            $item_ids = array();
283 283
 	
284
-			foreach ( $invoice->get_items() as $item ) {
285
-				if ( ! in_array( $item->get_id(), $item_ids ) ) {
286
-					$item_ids[] = $item->get_id();
287
-					$items[]    = $item;
288
-				}
289
-			}
284
+            foreach ( $invoice->get_items() as $item ) {
285
+                if ( ! in_array( $item->get_id(), $item_ids ) ) {
286
+                    $item_ids[] = $item->get_id();
287
+                    $items[]    = $item;
288
+                }
289
+            }
290 290
 	
291
-			foreach ( $this->payment_form->get_items() as $item ) {
292
-				if ( ! in_array( $item->get_id(), $item_ids ) ) {
293
-					$item_ids[] = $item->get_id();
294
-					$items[]    = $item;
295
-				}
296
-			}
291
+            foreach ( $this->payment_form->get_items() as $item ) {
292
+                if ( ! in_array( $item->get_id(), $item_ids ) ) {
293
+                    $item_ids[] = $item->get_id();
294
+                    $items[]    = $item;
295
+                }
296
+            }
297 297
 	
298
-			$this->payment_form->set_items( $items );
298
+            $this->payment_form->set_items( $items );
299 299
 	
300
-		} else {
301
-			$this->payment_form->set_items( $invoice->get_items() );
302
-		}
303
-
304
-		$this->country = $invoice->get_country();
305
-		$this->state   = $invoice->get_state();
306
-		$this->invoice = $invoice;
307
-
308
-		do_action_ref_array( 'getpaid_submissions_process_invoice', array( &$this ) );
309
-	}
310
-
311
-	/**
312
-	 * Returns the associated invoice.
313
-	 *
314
-	 * @since 1.0.19
315
-	 * @return WPInv_Invoice
316
-	 */
317
-	public function get_invoice() {
318
-		return $this->invoice;
319
-	}
320
-
321
-	/**
322
-	 * Checks whether there is an invoice associated with this submission.
323
-	 *
324
-	 * @since 1.0.19
325
-	 * @return bool
326
-	 */
327
-	public function has_invoice() {
328
-		return ! empty( $this->invoice );
329
-	}
330
-
331
-	/*
300
+        } else {
301
+            $this->payment_form->set_items( $invoice->get_items() );
302
+        }
303
+
304
+        $this->country = $invoice->get_country();
305
+        $this->state   = $invoice->get_state();
306
+        $this->invoice = $invoice;
307
+
308
+        do_action_ref_array( 'getpaid_submissions_process_invoice', array( &$this ) );
309
+    }
310
+
311
+    /**
312
+     * Returns the associated invoice.
313
+     *
314
+     * @since 1.0.19
315
+     * @return WPInv_Invoice
316
+     */
317
+    public function get_invoice() {
318
+        return $this->invoice;
319
+    }
320
+
321
+    /**
322
+     * Checks whether there is an invoice associated with this submission.
323
+     *
324
+     * @since 1.0.19
325
+     * @return bool
326
+     */
327
+    public function has_invoice() {
328
+        return ! empty( $this->invoice );
329
+    }
330
+
331
+    /*
332 332
 	|--------------------------------------------------------------------------
333 333
 	| Items.
334 334
 	|--------------------------------------------------------------------------
@@ -337,115 +337,115 @@  discard block
 block discarded – undo
337 337
 	| recurring item. But can have an unlimited number of non-recurring items.
338 338
 	*/
339 339
 
340
-	/**
341
-	 * Prepares the submission's items.
342
-	 *
343
-	 * @since 1.0.19
344
-	 */
345
-	public function process_items() {
346
-
347
-		$processor = new GetPaid_Payment_Form_Submission_Items( $this );
348
-
349
-		foreach ( $processor->items as $item ) {
350
-			$this->add_item( $item );
351
-		}
352
-
353
-		do_action_ref_array( 'getpaid_submissions_process_items', array( &$this ) );
354
-	}
355
-
356
-	/**
357
-	 * Adds an item to the submission.
358
-	 *
359
-	 * @since 1.0.19
360
-	 * @param GetPaid_Form_Item $item
361
-	 */
362
-	public function add_item( $item ) {
363
-
364
-		// Make sure that it is available for purchase.
365
-		if ( ! $item->can_purchase() || isset( $this->items[ $item->get_id() ] ) ) {
366
-			return;
367
-		}
368
-
369
-		// Each submission can only contain one recurring item.
370
-		if ( $item->is_recurring() ) {
371
-
372
-			if ( $this->has_recurring != 0 ) {
373
-				throw new Exception( __( 'You can only buy one recurring item at a time.', 'invoicing' ) );
374
-			}
375
-
376
-			$this->has_recurring = $item->get_id();
377
-
378
-		}
379
-
380
-		// Update the items and totals.
381
-		$this->items[ $item->get_id() ]         = $item;
382
-		$this->totals['subtotal']['initial']   += $item->get_sub_total();
383
-		$this->totals['subtotal']['recurring'] += $item->get_recurring_sub_total();
384
-
385
-	}
386
-
387
-	/**
388
-	 * Removes a specific item.
389
-	 * 
390
-	 * You should not call this method after the discounts and taxes
391
-	 * have been calculated.
392
-	 *
393
-	 * @since 1.0.19
394
-	 */
395
-	public function remove_item( $item_id ) {
396
-
397
-		if ( isset( $this->items[ $item_id ] ) ) {
398
-			$this->totals['subtotal']['initial']   -= $this->items[ $item_id ]->get_sub_total();
399
-			$this->totals['subtotal']['recurring'] -= $this->items[ $item_id ]->get_recurring_sub_total();
400
-
401
-			if ( $this->items[ $item_id ]->is_recurring() ) {
402
-				$this->has_recurring = 0;
403
-			}
404
-
405
-			unset( $this->items[ $item_id ] );
406
-		}
407
-
408
-	}
409
-
410
-	/**
411
-	 * Returns the subtotal.
412
-	 *
413
-	 * @since 1.0.19
414
-	 */
415
-	public function get_subtotal() {
416
-
417
-		if ( wpinv_prices_include_tax() ) {
418
-			return $this->totals['subtotal']['initial'] - $this->totals['taxes']['initial'];
419
-		}
420
-
421
-		return $this->totals['subtotal']['initial'];
422
-	}
423
-
424
-	/**
425
-	 * Returns the recurring subtotal.
426
-	 *
427
-	 * @since 1.0.19
428
-	 */
429
-	public function get_recurring_subtotal() {
430
-
431
-		if ( wpinv_prices_include_tax() ) {
432
-			return $this->totals['subtotal']['recurring'] - $this->totals['taxes']['recurring'];
433
-		}
434
-
435
-		return $this->totals['subtotal']['recurring'];
436
-	}
437
-
438
-	/**
439
-	 * Returns all items.
440
-	 *
441
-	 * @since 1.0.19
442
-	 * @return GetPaid_Form_Item[]
443
-	 */
444
-	public function get_items() {
445
-		return $this->items;
446
-	}
447
-
448
-	/*
340
+    /**
341
+     * Prepares the submission's items.
342
+     *
343
+     * @since 1.0.19
344
+     */
345
+    public function process_items() {
346
+
347
+        $processor = new GetPaid_Payment_Form_Submission_Items( $this );
348
+
349
+        foreach ( $processor->items as $item ) {
350
+            $this->add_item( $item );
351
+        }
352
+
353
+        do_action_ref_array( 'getpaid_submissions_process_items', array( &$this ) );
354
+    }
355
+
356
+    /**
357
+     * Adds an item to the submission.
358
+     *
359
+     * @since 1.0.19
360
+     * @param GetPaid_Form_Item $item
361
+     */
362
+    public function add_item( $item ) {
363
+
364
+        // Make sure that it is available for purchase.
365
+        if ( ! $item->can_purchase() || isset( $this->items[ $item->get_id() ] ) ) {
366
+            return;
367
+        }
368
+
369
+        // Each submission can only contain one recurring item.
370
+        if ( $item->is_recurring() ) {
371
+
372
+            if ( $this->has_recurring != 0 ) {
373
+                throw new Exception( __( 'You can only buy one recurring item at a time.', 'invoicing' ) );
374
+            }
375
+
376
+            $this->has_recurring = $item->get_id();
377
+
378
+        }
379
+
380
+        // Update the items and totals.
381
+        $this->items[ $item->get_id() ]         = $item;
382
+        $this->totals['subtotal']['initial']   += $item->get_sub_total();
383
+        $this->totals['subtotal']['recurring'] += $item->get_recurring_sub_total();
384
+
385
+    }
386
+
387
+    /**
388
+     * Removes a specific item.
389
+     * 
390
+     * You should not call this method after the discounts and taxes
391
+     * have been calculated.
392
+     *
393
+     * @since 1.0.19
394
+     */
395
+    public function remove_item( $item_id ) {
396
+
397
+        if ( isset( $this->items[ $item_id ] ) ) {
398
+            $this->totals['subtotal']['initial']   -= $this->items[ $item_id ]->get_sub_total();
399
+            $this->totals['subtotal']['recurring'] -= $this->items[ $item_id ]->get_recurring_sub_total();
400
+
401
+            if ( $this->items[ $item_id ]->is_recurring() ) {
402
+                $this->has_recurring = 0;
403
+            }
404
+
405
+            unset( $this->items[ $item_id ] );
406
+        }
407
+
408
+    }
409
+
410
+    /**
411
+     * Returns the subtotal.
412
+     *
413
+     * @since 1.0.19
414
+     */
415
+    public function get_subtotal() {
416
+
417
+        if ( wpinv_prices_include_tax() ) {
418
+            return $this->totals['subtotal']['initial'] - $this->totals['taxes']['initial'];
419
+        }
420
+
421
+        return $this->totals['subtotal']['initial'];
422
+    }
423
+
424
+    /**
425
+     * Returns the recurring subtotal.
426
+     *
427
+     * @since 1.0.19
428
+     */
429
+    public function get_recurring_subtotal() {
430
+
431
+        if ( wpinv_prices_include_tax() ) {
432
+            return $this->totals['subtotal']['recurring'] - $this->totals['taxes']['recurring'];
433
+        }
434
+
435
+        return $this->totals['subtotal']['recurring'];
436
+    }
437
+
438
+    /**
439
+     * Returns all items.
440
+     *
441
+     * @since 1.0.19
442
+     * @return GetPaid_Form_Item[]
443
+     */
444
+    public function get_items() {
445
+        return $this->items;
446
+    }
447
+
448
+    /*
449 449
 	|--------------------------------------------------------------------------
450 450
 	| Taxes
451 451
 	|--------------------------------------------------------------------------
@@ -454,128 +454,128 @@  discard block
 block discarded – undo
454 454
 	| or only one-time.
455 455
     */
456 456
 
457
-	/**
458
-	 * Prepares the submission's taxes.
459
-	 *
460
-	 * @since 1.0.19
461
-	 */
462
-	public function process_taxes() {
463
-
464
-		// Abort if we're not using taxes.
465
-		if ( ! $this->use_taxes() ) {
466
-			return;
467
-		}
468
-
469
-		// If a custom country && state has been passed in, use it to calculate taxes.
470
-		$country = $this->get_field( 'wpinv_country', 'billing' );
471
-		if ( ! empty( $country ) ) {
472
-			$this->country = $country;
473
-		}
474
-
475
-		$state = $this->get_field( 'wpinv_state', 'billing' );
476
-		if ( ! empty( $state ) ) {
477
-			$this->state = $state;
478
-		}
479
-
480
-		// Confirm if the provided country and the ip country are similar.
481
-		$address_confirmed = $this->get_field( 'confirm-address' );
482
-		if ( wpinv_should_validate_vat_number() && getpaid_get_ip_country() != $this->country && empty( $address_confirmed ) ) {
483
-			throw new Exception( __( 'The country of your current location must be the same as the country of your billing location or you must confirm the billing address is your home country.', 'invoicing' ) );
484
-		}
485
-
486
-		// Abort if the country is not taxable.
487
-		if ( ! wpinv_is_country_taxable( $this->country ) ) {
488
-			return;
489
-		}
490
-
491
-		$processor = new GetPaid_Payment_Form_Submission_Taxes( $this );
492
-
493
-		foreach ( $processor->taxes as $tax ) {
494
-			$this->add_tax( $tax );
495
-		}
496
-
497
-		do_action_ref_array( 'getpaid_submissions_process_taxes', array( &$this ) );
498
-	}
499
-
500
-	/**
501
-	 * Adds a tax to the submission.
502
-	 *
503
-	 * @param array $tax An array of tax details. name, initial_tax, and recurring_tax are required.
504
-	 * @since 1.0.19
505
-	 */
506
-	public function add_tax( $tax ) {
507
-
508
-		if ( wpinv_round_tax_per_tax_rate() ) {
509
-			$tax['initial_tax']   = wpinv_round_amount( $tax['initial_tax'] );
510
-			$tax['recurring_tax'] = wpinv_round_amount( $tax['recurring_tax'] );
511
-		}
512
-
513
-		$this->taxes[ $tax['name'] ]         = $tax;
514
-		$this->totals['taxes']['initial']   += wpinv_sanitize_amount( $tax['initial_tax'] );
515
-		$this->totals['taxes']['recurring'] += wpinv_sanitize_amount( $tax['recurring_tax'] );
516
-
517
-	}
518
-
519
-	/**
520
-	 * Removes a specific tax.
521
-	 *
522
-	 * @since 1.0.19
523
-	 */
524
-	public function remove_tax( $tax_name ) {
525
-
526
-		if ( isset( $this->taxes[ $tax_name ] ) ) {
527
-			$this->totals['taxes']['initial']   -= $this->taxes[ $tax_name ]['initial_tax'];
528
-			$this->totals['taxes']['recurring'] -= $this->taxes[ $tax_name ]['recurring_tax'];
529
-			unset( $this->taxes[ $tax_name ] );
530
-		}
531
-
532
-	}
533
-
534
-	/**
535
-	 * Whether or not we'll use taxes for the submission.
536
-	 *
537
-	 * @since 1.0.19
538
-	 */
539
-	public function use_taxes() {
540
-
541
-		$use_taxes = wpinv_use_taxes();
542
-
543
-		if ( $this->has_invoice() && ! $this->invoice->is_taxable() ) {
544
-			$use_taxes = false;
545
-		}
546
-
547
-		return apply_filters( 'getpaid_submission_use_taxes', $use_taxes, $this );
548
-
549
-	}
550
-
551
-	/**
552
-	 * Returns the tax.
553
-	 *
554
-	 * @since 1.0.19
555
-	 */
556
-	public function get_tax() {
557
-		return $this->totals['taxes']['initial'];
558
-	}
559
-
560
-	/**
561
-	 * Returns the recurring tax.
562
-	 *
563
-	 * @since 1.0.19
564
-	 */
565
-	public function get_recurring_tax() {
566
-		return $this->totals['taxes']['recurring'];
567
-	}
568
-
569
-	/**
570
-	 * Returns all taxes.
571
-	 *
572
-	 * @since 1.0.19
573
-	 */
574
-	public function get_taxes() {
575
-		return $this->taxes;
576
-	}
577
-
578
-	/*
457
+    /**
458
+     * Prepares the submission's taxes.
459
+     *
460
+     * @since 1.0.19
461
+     */
462
+    public function process_taxes() {
463
+
464
+        // Abort if we're not using taxes.
465
+        if ( ! $this->use_taxes() ) {
466
+            return;
467
+        }
468
+
469
+        // If a custom country && state has been passed in, use it to calculate taxes.
470
+        $country = $this->get_field( 'wpinv_country', 'billing' );
471
+        if ( ! empty( $country ) ) {
472
+            $this->country = $country;
473
+        }
474
+
475
+        $state = $this->get_field( 'wpinv_state', 'billing' );
476
+        if ( ! empty( $state ) ) {
477
+            $this->state = $state;
478
+        }
479
+
480
+        // Confirm if the provided country and the ip country are similar.
481
+        $address_confirmed = $this->get_field( 'confirm-address' );
482
+        if ( wpinv_should_validate_vat_number() && getpaid_get_ip_country() != $this->country && empty( $address_confirmed ) ) {
483
+            throw new Exception( __( 'The country of your current location must be the same as the country of your billing location or you must confirm the billing address is your home country.', 'invoicing' ) );
484
+        }
485
+
486
+        // Abort if the country is not taxable.
487
+        if ( ! wpinv_is_country_taxable( $this->country ) ) {
488
+            return;
489
+        }
490
+
491
+        $processor = new GetPaid_Payment_Form_Submission_Taxes( $this );
492
+
493
+        foreach ( $processor->taxes as $tax ) {
494
+            $this->add_tax( $tax );
495
+        }
496
+
497
+        do_action_ref_array( 'getpaid_submissions_process_taxes', array( &$this ) );
498
+    }
499
+
500
+    /**
501
+     * Adds a tax to the submission.
502
+     *
503
+     * @param array $tax An array of tax details. name, initial_tax, and recurring_tax are required.
504
+     * @since 1.0.19
505
+     */
506
+    public function add_tax( $tax ) {
507
+
508
+        if ( wpinv_round_tax_per_tax_rate() ) {
509
+            $tax['initial_tax']   = wpinv_round_amount( $tax['initial_tax'] );
510
+            $tax['recurring_tax'] = wpinv_round_amount( $tax['recurring_tax'] );
511
+        }
512
+
513
+        $this->taxes[ $tax['name'] ]         = $tax;
514
+        $this->totals['taxes']['initial']   += wpinv_sanitize_amount( $tax['initial_tax'] );
515
+        $this->totals['taxes']['recurring'] += wpinv_sanitize_amount( $tax['recurring_tax'] );
516
+
517
+    }
518
+
519
+    /**
520
+     * Removes a specific tax.
521
+     *
522
+     * @since 1.0.19
523
+     */
524
+    public function remove_tax( $tax_name ) {
525
+
526
+        if ( isset( $this->taxes[ $tax_name ] ) ) {
527
+            $this->totals['taxes']['initial']   -= $this->taxes[ $tax_name ]['initial_tax'];
528
+            $this->totals['taxes']['recurring'] -= $this->taxes[ $tax_name ]['recurring_tax'];
529
+            unset( $this->taxes[ $tax_name ] );
530
+        }
531
+
532
+    }
533
+
534
+    /**
535
+     * Whether or not we'll use taxes for the submission.
536
+     *
537
+     * @since 1.0.19
538
+     */
539
+    public function use_taxes() {
540
+
541
+        $use_taxes = wpinv_use_taxes();
542
+
543
+        if ( $this->has_invoice() && ! $this->invoice->is_taxable() ) {
544
+            $use_taxes = false;
545
+        }
546
+
547
+        return apply_filters( 'getpaid_submission_use_taxes', $use_taxes, $this );
548
+
549
+    }
550
+
551
+    /**
552
+     * Returns the tax.
553
+     *
554
+     * @since 1.0.19
555
+     */
556
+    public function get_tax() {
557
+        return $this->totals['taxes']['initial'];
558
+    }
559
+
560
+    /**
561
+     * Returns the recurring tax.
562
+     *
563
+     * @since 1.0.19
564
+     */
565
+    public function get_recurring_tax() {
566
+        return $this->totals['taxes']['recurring'];
567
+    }
568
+
569
+    /**
570
+     * Returns all taxes.
571
+     *
572
+     * @since 1.0.19
573
+     */
574
+    public function get_taxes() {
575
+        return $this->taxes;
576
+    }
577
+
578
+    /*
579 579
 	|--------------------------------------------------------------------------
580 580
 	| Discounts
581 581
 	|--------------------------------------------------------------------------
@@ -584,99 +584,99 @@  discard block
 block discarded – undo
584 584
 	| or only one-time. They also do not have to come from a discount code.
585 585
     */
586 586
 
587
-	/**
588
-	 * Prepares the submission's discount.
589
-	 *
590
-	 * @since 1.0.19
591
-	 */
592
-	public function process_discount() {
593
-
594
-		$initial_total    = $this->get_subtotal() + $this->get_fee() + $this->get_tax();
595
-		$recurring_total  = $this->get_recurring_subtotal() + $this->get_recurring_fee() + $this->get_recurring_tax();
596
-		$processor        = new GetPaid_Payment_Form_Submission_Discount( $this, $initial_total, $recurring_total );
597
-
598
-		foreach ( $processor->discounts as $discount ) {
599
-			$this->add_discount( $discount );
600
-		}
601
-
602
-		do_action_ref_array( 'getpaid_submissions_process_discounts', array( &$this ) );
603
-	}
604
-
605
-	/**
606
-	 * Adds a discount to the submission.
607
-	 *
608
-	 * @param array $discount An array of discount details. name, initial_discount, and recurring_discount are required. Include discount_code if the discount is from a discount code.
609
-	 * @since 1.0.19
610
-	 */
611
-	public function add_discount( $discount ) {
612
-		$this->discounts[ $discount['name'] ]   = $discount;
613
-		$this->totals['discount']['initial']   += wpinv_sanitize_amount( $discount['initial_discount'] );
614
-		$this->totals['discount']['recurring'] += wpinv_sanitize_amount( $discount['recurring_discount'] );
615
-	}
616
-
617
-	/**
618
-	 * Removes a discount from the submission.
619
-	 *
620
-	 * @since 1.0.19
621
-	 */
622
-	public function remove_discount( $name ) {
623
-
624
-		if ( isset( $this->discounts[ $name ] ) ) {
625
-			$this->totals['discount']['initial']   -= $this->discounts[ $name ]['initial_discount'];
626
-			$this->totals['discount']['recurring'] -= $this->discounts[ $name ]['recurring_discount'];
627
-			unset( $this->discounts[ $name ] );
628
-		}
629
-
630
-	}
631
-
632
-	/**
633
-	 * Checks whether there is a discount code associated with this submission.
634
-	 *
635
-	 * @since 1.0.19
636
-	 * @return bool
637
-	 */
638
-	public function has_discount_code() {
639
-		return ! empty( $this->discounts['discount_code'] );
640
-	}
641
-
642
-	/**
643
-	 * Returns the discount code.
644
-	 *
645
-	 * @since 1.0.19
646
-	 * @return string
647
-	 */
648
-	public function get_discount_code() {
649
-		return $this->has_discount_code() ? $this->discounts['discount_code']['discount_code'] : '';
650
-	}
651
-
652
-	/**
653
-	 * Returns the discount.
654
-	 *
655
-	 * @since 1.0.19
656
-	 */
657
-	public function get_discount() {
658
-		return $this->totals['discount']['initial'];
659
-	}
660
-
661
-	/**
662
-	 * Returns the recurring discount.
663
-	 *
664
-	 * @since 1.0.19
665
-	 */
666
-	public function get_recurring_discount() {
667
-		return $this->totals['discount']['recurring'];
668
-	}
669
-
670
-	/**
671
-	 * Returns all discounts.
672
-	 *
673
-	 * @since 1.0.19
674
-	 */
675
-	public function get_discounts() {
676
-		return $this->discounts;
677
-	}
678
-
679
-	/*
587
+    /**
588
+     * Prepares the submission's discount.
589
+     *
590
+     * @since 1.0.19
591
+     */
592
+    public function process_discount() {
593
+
594
+        $initial_total    = $this->get_subtotal() + $this->get_fee() + $this->get_tax();
595
+        $recurring_total  = $this->get_recurring_subtotal() + $this->get_recurring_fee() + $this->get_recurring_tax();
596
+        $processor        = new GetPaid_Payment_Form_Submission_Discount( $this, $initial_total, $recurring_total );
597
+
598
+        foreach ( $processor->discounts as $discount ) {
599
+            $this->add_discount( $discount );
600
+        }
601
+
602
+        do_action_ref_array( 'getpaid_submissions_process_discounts', array( &$this ) );
603
+    }
604
+
605
+    /**
606
+     * Adds a discount to the submission.
607
+     *
608
+     * @param array $discount An array of discount details. name, initial_discount, and recurring_discount are required. Include discount_code if the discount is from a discount code.
609
+     * @since 1.0.19
610
+     */
611
+    public function add_discount( $discount ) {
612
+        $this->discounts[ $discount['name'] ]   = $discount;
613
+        $this->totals['discount']['initial']   += wpinv_sanitize_amount( $discount['initial_discount'] );
614
+        $this->totals['discount']['recurring'] += wpinv_sanitize_amount( $discount['recurring_discount'] );
615
+    }
616
+
617
+    /**
618
+     * Removes a discount from the submission.
619
+     *
620
+     * @since 1.0.19
621
+     */
622
+    public function remove_discount( $name ) {
623
+
624
+        if ( isset( $this->discounts[ $name ] ) ) {
625
+            $this->totals['discount']['initial']   -= $this->discounts[ $name ]['initial_discount'];
626
+            $this->totals['discount']['recurring'] -= $this->discounts[ $name ]['recurring_discount'];
627
+            unset( $this->discounts[ $name ] );
628
+        }
629
+
630
+    }
631
+
632
+    /**
633
+     * Checks whether there is a discount code associated with this submission.
634
+     *
635
+     * @since 1.0.19
636
+     * @return bool
637
+     */
638
+    public function has_discount_code() {
639
+        return ! empty( $this->discounts['discount_code'] );
640
+    }
641
+
642
+    /**
643
+     * Returns the discount code.
644
+     *
645
+     * @since 1.0.19
646
+     * @return string
647
+     */
648
+    public function get_discount_code() {
649
+        return $this->has_discount_code() ? $this->discounts['discount_code']['discount_code'] : '';
650
+    }
651
+
652
+    /**
653
+     * Returns the discount.
654
+     *
655
+     * @since 1.0.19
656
+     */
657
+    public function get_discount() {
658
+        return $this->totals['discount']['initial'];
659
+    }
660
+
661
+    /**
662
+     * Returns the recurring discount.
663
+     *
664
+     * @since 1.0.19
665
+     */
666
+    public function get_recurring_discount() {
667
+        return $this->totals['discount']['recurring'];
668
+    }
669
+
670
+    /**
671
+     * Returns all discounts.
672
+     *
673
+     * @since 1.0.19
674
+     */
675
+    public function get_discounts() {
676
+        return $this->discounts;
677
+    }
678
+
679
+    /*
680 680
 	|--------------------------------------------------------------------------
681 681
 	| Fees
682 682
 	|--------------------------------------------------------------------------
@@ -686,89 +686,89 @@  discard block
 block discarded – undo
686 686
 	| fees.
687 687
     */
688 688
 
689
-	/**
690
-	 * Prepares the submission's fees.
691
-	 *
692
-	 * @since 1.0.19
693
-	 */
694
-	public function process_fees() {
695
-
696
-		$fees_processor = new GetPaid_Payment_Form_Submission_Fees( $this );
697
-
698
-		foreach ( $fees_processor->fees as $fee ) {
699
-			$this->add_fee( $fee );
700
-		}
701
-
702
-		do_action_ref_array( 'getpaid_submissions_process_fees', array( &$this ) );
703
-	}
704
-
705
-	/**
706
-	 * Adds a fee to the submission.
707
-	 *
708
-	 * @param array $fee An array of fee details. name, initial_fee, and recurring_fee are required.
709
-	 * @since 1.0.19
710
-	 */
711
-	public function add_fee( $fee ) {
712
-
713
-		$this->fees[ $fee['name'] ]         = $fee;
714
-		$this->totals['fees']['initial']   += wpinv_sanitize_amount( $fee['initial_fee'] );
715
-		$this->totals['fees']['recurring'] += wpinv_sanitize_amount( $fee['recurring_fee'] );
716
-
717
-	}
718
-
719
-	/**
720
-	 * Removes a fee from the submission.
721
-	 *
722
-	 * @since 1.0.19
723
-	 */
724
-	public function remove_fee( $name ) {
725
-
726
-		if ( isset( $this->fees[ $name ] ) ) {
727
-			$this->totals['fees']['initial']   -= $this->fees[ $name ]['initial_fee'];
728
-			$this->totals['fees']['recurring'] -= $this->fees[ $name ]['recurring_fee'];
729
-			unset( $this->fees[ $name ] );
730
-		}
731
-
732
-	}
733
-
734
-	/**
735
-	 * Returns the fees.
736
-	 *
737
-	 * @since 1.0.19
738
-	 */
739
-	public function get_fee() {
740
-		return $this->totals['fees']['initial'];
741
-	}
742
-
743
-	/**
744
-	 * Returns the recurring fees.
745
-	 *
746
-	 * @since 1.0.19
747
-	 */
748
-	public function get_recurring_fee() {
749
-		return $this->totals['fees']['recurring'];
750
-	}
751
-
752
-	/**
753
-	 * Returns all fees.
754
-	 *
755
-	 * @since 1.0.19
756
-	 */
757
-	public function get_fees() {
758
-		return $this->fees;
759
-	}
760
-
761
-	/**
762
-	 * Checks if there are any fees for the form.
763
-	 *
764
-	 * @return bool
765
-	 * @since 1.0.19
766
-	 */
767
-	public function has_fees() {
768
-		return count( $this->fees ) !== 0;
769
-	}
770
-
771
-	/*
689
+    /**
690
+     * Prepares the submission's fees.
691
+     *
692
+     * @since 1.0.19
693
+     */
694
+    public function process_fees() {
695
+
696
+        $fees_processor = new GetPaid_Payment_Form_Submission_Fees( $this );
697
+
698
+        foreach ( $fees_processor->fees as $fee ) {
699
+            $this->add_fee( $fee );
700
+        }
701
+
702
+        do_action_ref_array( 'getpaid_submissions_process_fees', array( &$this ) );
703
+    }
704
+
705
+    /**
706
+     * Adds a fee to the submission.
707
+     *
708
+     * @param array $fee An array of fee details. name, initial_fee, and recurring_fee are required.
709
+     * @since 1.0.19
710
+     */
711
+    public function add_fee( $fee ) {
712
+
713
+        $this->fees[ $fee['name'] ]         = $fee;
714
+        $this->totals['fees']['initial']   += wpinv_sanitize_amount( $fee['initial_fee'] );
715
+        $this->totals['fees']['recurring'] += wpinv_sanitize_amount( $fee['recurring_fee'] );
716
+
717
+    }
718
+
719
+    /**
720
+     * Removes a fee from the submission.
721
+     *
722
+     * @since 1.0.19
723
+     */
724
+    public function remove_fee( $name ) {
725
+
726
+        if ( isset( $this->fees[ $name ] ) ) {
727
+            $this->totals['fees']['initial']   -= $this->fees[ $name ]['initial_fee'];
728
+            $this->totals['fees']['recurring'] -= $this->fees[ $name ]['recurring_fee'];
729
+            unset( $this->fees[ $name ] );
730
+        }
731
+
732
+    }
733
+
734
+    /**
735
+     * Returns the fees.
736
+     *
737
+     * @since 1.0.19
738
+     */
739
+    public function get_fee() {
740
+        return $this->totals['fees']['initial'];
741
+    }
742
+
743
+    /**
744
+     * Returns the recurring fees.
745
+     *
746
+     * @since 1.0.19
747
+     */
748
+    public function get_recurring_fee() {
749
+        return $this->totals['fees']['recurring'];
750
+    }
751
+
752
+    /**
753
+     * Returns all fees.
754
+     *
755
+     * @since 1.0.19
756
+     */
757
+    public function get_fees() {
758
+        return $this->fees;
759
+    }
760
+
761
+    /**
762
+     * Checks if there are any fees for the form.
763
+     *
764
+     * @return bool
765
+     * @since 1.0.19
766
+     */
767
+    public function has_fees() {
768
+        return count( $this->fees ) !== 0;
769
+    }
770
+
771
+    /*
772 772
 	|--------------------------------------------------------------------------
773 773
 	| MISC
774 774
 	|--------------------------------------------------------------------------
@@ -776,119 +776,119 @@  discard block
 block discarded – undo
776 776
 	| Extra submission functions.
777 777
     */
778 778
 
779
-	/**
780
-	 * Checks if this is the initial fetch.
781
-	 *
782
-	 * @return bool
783
-	 * @since 1.0.19
784
-	 */
785
-	public function is_initial_fetch() {
786
-		return empty( $this->data['initial_state'] );
787
-	}
788
-
789
-	/**
790
-	 * Returns the total amount to collect for this submission.
791
-	 *
792
-	 * @since 1.0.19
793
-	 */
794
-	public function get_total() {
795
-		$total = $this->get_subtotal() + $this->get_fee() + $this->get_tax() - $this->get_discount();
796
-		return max( $total, 0 );
797
-	}
798
-
799
-	/**
800
-	 * Returns the recurring total amount to collect for this submission.
801
-	 *
802
-	 * @since 1.0.19
803
-	 */
804
-	public function get_recurring_total() {
805
-		$total = $this->get_recurring_subtotal() + $this->get_recurring_fee() + $this->get_recurring_tax() - $this->get_recurring_discount();
806
-		return max( $total, 0 );
807
-	}
808
-
809
-	/**
810
-	 * Whether payment details should be collected for this submission.
811
-	 *
812
-	 * @since 1.0.19
813
-	 */
814
-	public function should_collect_payment_details() {
815
-		$initial   = $this->get_total();
816
-		$recurring = $this->get_recurring_total();
817
-
818
-		if ( $this->has_recurring == 0 ) {
819
-			$recurring = 0;
820
-		}
821
-
822
-		$collect = $initial > 0 || $recurring > 0;
823
-		return apply_filters( 'getpaid_submission_should_collect_payment_details', $collect, $this  );
824
-	}
825
-
826
-	/**
827
-	 * Returns the billing email of the user.
828
-	 *
829
-	 * @since 1.0.19
830
-	 */
831
-	public function get_billing_email() {
832
-		return apply_filters( 'getpaid_get_submission_billing_email', $this->get_field( 'billing_email' ), $this  );
833
-	}
834
-
835
-	/**
836
-	 * Checks if the submitter has a billing email.
837
-	 *
838
-	 * @since 1.0.19
839
-	 */
840
-	public function has_billing_email() {
841
-		$billing_email = $this->get_billing_email();
842
-		return ! empty( $billing_email ) && is_email( $billing_email );
843
-	}
844
-
845
-	/**
846
-	 * Returns the appropriate currency for the submission.
847
-	 *
848
-	 * @since 1.0.19
849
-	 * @return string
850
-	 */
851
-	public function get_currency() {
852
-		return $this->has_invoice() ? $this->invoice->get_currency() : wpinv_get_currency();
853
-    }
854
-
855
-    /**
856
-	 * Returns the raw submission data.
857
-	 *
858
-	 * @since 1.0.19
859
-	 * @return array
860
-	 */
861
-	public function get_data() {
862
-		return $this->data;
863
-	}
864
-
865
-	/**
866
-	 * Returns a field from the submission data
867
-	 *
868
-	 * @param string $field
869
-	 * @since 1.0.19
870
-	 * @return mixed|null
871
-	 */
872
-	public function get_field( $field, $sub_array_key = null ) {
873
-		return getpaid_get_array_field( $this->data, $field, $sub_array_key );
874
-	}
875
-
876
-	/**
877
-	 * Checks if a required field is set.
878
-	 *
879
-	 * @since 1.0.19
880
-	 */
881
-	public function is_required_field_set( $field ) {
882
-		return empty( $field['required'] ) || ! empty( $this->data[ $field['id'] ] );
883
-	}
884
-
885
-	/**
886
-	 * Formats an amount
887
-	 *
888
-	 * @since 1.0.19
889
-	 */
890
-	public function format_amount( $amount ) {
891
-		return wpinv_price( $amount, $this->get_currency() );
892
-	}
779
+    /**
780
+     * Checks if this is the initial fetch.
781
+     *
782
+     * @return bool
783
+     * @since 1.0.19
784
+     */
785
+    public function is_initial_fetch() {
786
+        return empty( $this->data['initial_state'] );
787
+    }
788
+
789
+    /**
790
+     * Returns the total amount to collect for this submission.
791
+     *
792
+     * @since 1.0.19
793
+     */
794
+    public function get_total() {
795
+        $total = $this->get_subtotal() + $this->get_fee() + $this->get_tax() - $this->get_discount();
796
+        return max( $total, 0 );
797
+    }
798
+
799
+    /**
800
+     * Returns the recurring total amount to collect for this submission.
801
+     *
802
+     * @since 1.0.19
803
+     */
804
+    public function get_recurring_total() {
805
+        $total = $this->get_recurring_subtotal() + $this->get_recurring_fee() + $this->get_recurring_tax() - $this->get_recurring_discount();
806
+        return max( $total, 0 );
807
+    }
808
+
809
+    /**
810
+     * Whether payment details should be collected for this submission.
811
+     *
812
+     * @since 1.0.19
813
+     */
814
+    public function should_collect_payment_details() {
815
+        $initial   = $this->get_total();
816
+        $recurring = $this->get_recurring_total();
817
+
818
+        if ( $this->has_recurring == 0 ) {
819
+            $recurring = 0;
820
+        }
821
+
822
+        $collect = $initial > 0 || $recurring > 0;
823
+        return apply_filters( 'getpaid_submission_should_collect_payment_details', $collect, $this  );
824
+    }
825
+
826
+    /**
827
+     * Returns the billing email of the user.
828
+     *
829
+     * @since 1.0.19
830
+     */
831
+    public function get_billing_email() {
832
+        return apply_filters( 'getpaid_get_submission_billing_email', $this->get_field( 'billing_email' ), $this  );
833
+    }
834
+
835
+    /**
836
+     * Checks if the submitter has a billing email.
837
+     *
838
+     * @since 1.0.19
839
+     */
840
+    public function has_billing_email() {
841
+        $billing_email = $this->get_billing_email();
842
+        return ! empty( $billing_email ) && is_email( $billing_email );
843
+    }
844
+
845
+    /**
846
+     * Returns the appropriate currency for the submission.
847
+     *
848
+     * @since 1.0.19
849
+     * @return string
850
+     */
851
+    public function get_currency() {
852
+        return $this->has_invoice() ? $this->invoice->get_currency() : wpinv_get_currency();
853
+    }
854
+
855
+    /**
856
+     * Returns the raw submission data.
857
+     *
858
+     * @since 1.0.19
859
+     * @return array
860
+     */
861
+    public function get_data() {
862
+        return $this->data;
863
+    }
864
+
865
+    /**
866
+     * Returns a field from the submission data
867
+     *
868
+     * @param string $field
869
+     * @since 1.0.19
870
+     * @return mixed|null
871
+     */
872
+    public function get_field( $field, $sub_array_key = null ) {
873
+        return getpaid_get_array_field( $this->data, $field, $sub_array_key );
874
+    }
875
+
876
+    /**
877
+     * Checks if a required field is set.
878
+     *
879
+     * @since 1.0.19
880
+     */
881
+    public function is_required_field_set( $field ) {
882
+        return empty( $field['required'] ) || ! empty( $this->data[ $field['id'] ] );
883
+    }
884
+
885
+    /**
886
+     * Formats an amount
887
+     *
888
+     * @since 1.0.19
889
+     */
890
+    public function format_amount( $amount ) {
891
+        return wpinv_price( $amount, $this->get_currency() );
892
+    }
893 893
 
894 894
 }
Please login to merge, or discard this patch.
includes/payments/class-getpaid-payment-exception.php 1 patch
Indentation   +41 added lines, -41 removed lines patch added patch discarded remove patch
@@ -14,51 +14,51 @@
 block discarded – undo
14 14
  */
15 15
 class GetPaid_Payment_Exception extends Exception {
16 16
 
17
-	/**
18
-	 * Sanitized error code.
19
-	 *
20
-	 * @var string
21
-	 */
22
-	protected $error_code;
17
+    /**
18
+     * Sanitized error code.
19
+     *
20
+     * @var string
21
+     */
22
+    protected $error_code;
23 23
 
24
-	/**
25
-	 * Error extra data.
26
-	 *
27
-	 * @var array
28
-	 */
29
-	protected $error_data;
24
+    /**
25
+     * Error extra data.
26
+     *
27
+     * @var array
28
+     */
29
+    protected $error_data;
30 30
 
31
-	/**
32
-	 * Setup exception.
33
-	 *
34
-	 * @param string $code             Machine-readable error code, e.g `getpaid-discount-error`.
35
-	 * @param string $message          User-friendly translated error message, e.g. 'Discount is invalid'.
36
-	 * @param int    $http_status_code Proper HTTP status code to respond with, e.g. 400.
37
-	 * @param array  $data             Extra error data.
38
-	 */
39
-	public function __construct( $code, $message, $http_status_code = 400, $data = array() ) {
40
-		$this->error_code = $code;
41
-		$this->error_data = array_merge( array( 'status' => $http_status_code ), $data );
31
+    /**
32
+     * Setup exception.
33
+     *
34
+     * @param string $code             Machine-readable error code, e.g `getpaid-discount-error`.
35
+     * @param string $message          User-friendly translated error message, e.g. 'Discount is invalid'.
36
+     * @param int    $http_status_code Proper HTTP status code to respond with, e.g. 400.
37
+     * @param array  $data             Extra error data.
38
+     */
39
+    public function __construct( $code, $message, $http_status_code = 400, $data = array() ) {
40
+        $this->error_code = $code;
41
+        $this->error_data = array_merge( array( 'status' => $http_status_code ), $data );
42 42
 
43
-		parent::__construct( $message, $http_status_code );
44
-	}
43
+        parent::__construct( $message, $http_status_code );
44
+    }
45 45
 
46
-	/**
47
-	 * Returns the error code.
48
-	 *
49
-	 * @return string
50
-	 */
51
-	public function getErrorCode() {
52
-		return $this->error_code;
53
-	}
46
+    /**
47
+     * Returns the error code.
48
+     *
49
+     * @return string
50
+     */
51
+    public function getErrorCode() {
52
+        return $this->error_code;
53
+    }
54 54
 
55
-	/**
56
-	 * Returns error data.
57
-	 *
58
-	 * @return array
59
-	 */
60
-	public function getErrorData() {
61
-		return $this->error_data;
62
-	}
55
+    /**
56
+     * Returns error data.
57
+     *
58
+     * @return array
59
+     */
60
+    public function getErrorData() {
61
+        return $this->error_data;
62
+    }
63 63
 
64 64
 }
Please login to merge, or discard this patch.
includes/payments/class-getpaid-payment-form-submission-discount.php 1 patch
Indentation   +154 added lines, -154 removed lines patch added patch discarded remove patch
@@ -12,162 +12,162 @@
 block discarded – undo
12 12
  */
13 13
 class GetPaid_Payment_Form_Submission_Discount {
14 14
 
15
-	/**
16
-	 * Submission discounts.
17
-	 * @var array
18
-	 */
19
-	public $discounts = array();
15
+    /**
16
+     * Submission discounts.
17
+     * @var array
18
+     */
19
+    public $discounts = array();
20
+
21
+    /**
22
+     * Class constructor
23
+     *
24
+     * @param GetPaid_Payment_Form_Submission $submission
25
+     * @param float                           $initial_total
26
+     * @param float                           $recurring_total
27
+     */
28
+    public function __construct( $submission, $initial_total, $recurring_total ) {
29
+
30
+        // Process any existing invoice discounts.
31
+        if ( $submission->has_invoice() ) {
32
+            $this->discounts = $submission->get_invoice()->get_discounts();
33
+        }
34
+
35
+        // Do we have a discount?
36
+        $discount = $submission->get_field( 'discount' );
37
+
38
+        if ( empty( $discount ) ) {
39
+
40
+            if ( isset( $this->discounts['discount_code'] ) ) {
41
+                unset( $this->discounts['discount_code'] );
42
+            }
43
+
44
+            return;
45
+        }
46
+
47
+        // Processes the discount code.
48
+        $amount = max( $initial_total, $recurring_total );
49
+        $this->process_discount( $submission, $discount, $amount );
50
+
51
+    }
20 52
 
21 53
     /**
22
-	 * Class constructor
23
-	 *
24
-	 * @param GetPaid_Payment_Form_Submission $submission
25
-	 * @param float                           $initial_total
26
-	 * @param float                           $recurring_total
27
-	 */
28
-	public function __construct( $submission, $initial_total, $recurring_total ) {
29
-
30
-		// Process any existing invoice discounts.
31
-		if ( $submission->has_invoice() ) {
32
-			$this->discounts = $submission->get_invoice()->get_discounts();
33
-		}
34
-
35
-		// Do we have a discount?
36
-		$discount = $submission->get_field( 'discount' );
37
-
38
-		if ( empty( $discount ) ) {
39
-
40
-			if ( isset( $this->discounts['discount_code'] ) ) {
41
-				unset( $this->discounts['discount_code'] );
42
-			}
43
-
44
-			return;
45
-		}
46
-
47
-		// Processes the discount code.
48
-		$amount = max( $initial_total, $recurring_total );
49
-		$this->process_discount( $submission, $discount, $amount );
50
-
51
-	}
52
-
53
-	/**
54
-	 * Processes a submission discount.
55
-	 *
56
-	 * @param GetPaid_Payment_Form_Submission $submission
57
-	 * @param string                          $discount
58
-	 * @param float                           $amount
59
-	 */
60
-	public function process_discount( $submission, $discount, $amount ) {
61
-
62
-		// Fetch the discount.
63
-		$discount = new WPInv_Discount( $discount );
64
-
65
-		// Ensure it is active.
54
+     * Processes a submission discount.
55
+     *
56
+     * @param GetPaid_Payment_Form_Submission $submission
57
+     * @param string                          $discount
58
+     * @param float                           $amount
59
+     */
60
+    public function process_discount( $submission, $discount, $amount ) {
61
+
62
+        // Fetch the discount.
63
+        $discount = new WPInv_Discount( $discount );
64
+
65
+        // Ensure it is active.
66 66
         if ( ! $this->is_discount_active( $discount ) ) {
67
-			throw new GetPaid_Payment_Exception( '.getpaid-discount-field .getpaid-custom-payment-form-errors', __( 'Invalid or expired discount code', 'invoicing' ) );
68
-		}
69
-
70
-		// Exceeded limit.
71
-		if ( $discount->has_exceeded_limit() ) {
72
-			throw new GetPaid_Payment_Exception( '.getpaid-discount-field .getpaid-custom-payment-form-errors', __( 'This discount code has been used up', 'invoicing' ) );
73
-		}
74
-
75
-		// Validate usages.
76
-		$this->validate_single_use_discount( $submission, $discount );
77
-
78
-		// Validate amount.
79
-		$this->validate_discount_amount( $submission, $discount, $amount );
80
-
81
-		// Save the discount.
82
-		$this->discounts['discount_code'] = $this->calculate_discount( $submission, $discount );
83
-	}
84
-
85
-	/**
86
-	 * Validates a single use discount.
87
-	 *
88
-	 * @param WPInv_Discount                  $discount
89
-	 * @return bool
90
-	 */
91
-	public function is_discount_active(  $discount ) {
92
-		return $discount->exists() && $discount->is_active() && $discount->has_started() && ! $discount->is_expired();
93
-	}
94
-
95
-	/**
96
-	 * Returns a user's id or email.
97
-	 *
98
-	 * @param string $email
99
-	 * @return int|string|false
100
-	 */
101
-	public function get_user_id_or_email( $email ) {
102
-
103
-		if ( is_user_logged_in() ) {
104
-			return get_current_user_id();
105
-		}
106
-
107
-		return empty( $email ) ? false : sanitize_email( $email );
108
-	}
109
-
110
-	/**
111
-	 * Validates a single use discount.
112
-	 *
113
-	 * @param GetPaid_Payment_Form_Submission $submission
114
-	 * @param WPInv_Discount                  $discount
115
-	 */
116
-	public function validate_single_use_discount( $submission, $discount ) {
117
-
118
-		// Abort if it is not a single use discount.
119
-		if ( ! $discount->is_single_use() ) {
120
-			return;
121
-		}
122
-
123
-		// Ensure there is a valid billing email.
124
-		$user = $this->get_user_id_or_email( $submission->get_billing_email() );
125
-
126
-		if ( empty( $user ) ) {
127
-			throw new GetPaid_Payment_Exception( '.getpaid-discount-field .getpaid-custom-payment-form-errors', __( 'You need to either log in or enter your billing email before applying this discount', 'invoicing' ) );
128
-		}
129
-
130
-		// Has the user used this discount code before?
131
-		if ( ! $discount->is_valid_for_user( $user ) ) {
132
-			throw new GetPaid_Payment_Exception( '.getpaid-discount-field .getpaid-custom-payment-form-errors', __( 'You have already used this discount', 'invoicing' ) );
133
-		}
134
-
135
-	}
136
-
137
-	/**
138
-	 * Validates the discount's amount.
139
-	 *
140
-	 * @param GetPaid_Payment_Form_Submission $submission
141
-	 * @param WPInv_Discount         $discount
142
-	 * @param float                  $amount
143
-	 */
144
-	public function validate_discount_amount( $submission, $discount, $amount ) {
145
-
146
-		// Validate minimum amount.
147
-		if ( ! $discount->is_minimum_amount_met( $amount ) ) {
148
-			$min = wpinv_price( $discount->get_minimum_total(), $submission->get_currency() );
149
-			throw new GetPaid_Payment_Exception( '.getpaid-discount-field .getpaid-custom-payment-form-errors', sprintf( __( 'The minimum total for using this discount is %s', 'invoicing' ), $min ) );
150
-		}
151
-
152
-		// Validate the maximum amount.
153
-		if ( ! $discount->is_maximum_amount_met( $amount ) ) {
154
-			$max = wpinv_price( $discount->get_maximum_total(), $submission->get_currency() );
155
-			throw new GetPaid_Payment_Exception( '.getpaid-discount-field .getpaid-custom-payment-form-errors', sprintf( __( 'The maximum total for using this discount is %s', 'invoicing' ), $max ) );
156
-		}
157
-
158
-	}
159
-
160
-	/**
161
-	 * Calculates the discount code's amount.
162
-	 *
163
-	 * Ensure that the discount exists and has been validated before calling this method.
164
-	 *
165
-	 * @param GetPaid_Payment_Form_Submission $submission
166
-	 * @param WPInv_Discount                  $discount
167
-	 * @return array
168
-	 */
169
-	public function calculate_discount( $submission, $discount ) {
170
-		return getpaid_calculate_invoice_discount( $submission, $discount );
171
-	}
67
+            throw new GetPaid_Payment_Exception( '.getpaid-discount-field .getpaid-custom-payment-form-errors', __( 'Invalid or expired discount code', 'invoicing' ) );
68
+        }
69
+
70
+        // Exceeded limit.
71
+        if ( $discount->has_exceeded_limit() ) {
72
+            throw new GetPaid_Payment_Exception( '.getpaid-discount-field .getpaid-custom-payment-form-errors', __( 'This discount code has been used up', 'invoicing' ) );
73
+        }
74
+
75
+        // Validate usages.
76
+        $this->validate_single_use_discount( $submission, $discount );
77
+
78
+        // Validate amount.
79
+        $this->validate_discount_amount( $submission, $discount, $amount );
80
+
81
+        // Save the discount.
82
+        $this->discounts['discount_code'] = $this->calculate_discount( $submission, $discount );
83
+    }
84
+
85
+    /**
86
+     * Validates a single use discount.
87
+     *
88
+     * @param WPInv_Discount                  $discount
89
+     * @return bool
90
+     */
91
+    public function is_discount_active(  $discount ) {
92
+        return $discount->exists() && $discount->is_active() && $discount->has_started() && ! $discount->is_expired();
93
+    }
94
+
95
+    /**
96
+     * Returns a user's id or email.
97
+     *
98
+     * @param string $email
99
+     * @return int|string|false
100
+     */
101
+    public function get_user_id_or_email( $email ) {
102
+
103
+        if ( is_user_logged_in() ) {
104
+            return get_current_user_id();
105
+        }
106
+
107
+        return empty( $email ) ? false : sanitize_email( $email );
108
+    }
109
+
110
+    /**
111
+     * Validates a single use discount.
112
+     *
113
+     * @param GetPaid_Payment_Form_Submission $submission
114
+     * @param WPInv_Discount                  $discount
115
+     */
116
+    public function validate_single_use_discount( $submission, $discount ) {
117
+
118
+        // Abort if it is not a single use discount.
119
+        if ( ! $discount->is_single_use() ) {
120
+            return;
121
+        }
122
+
123
+        // Ensure there is a valid billing email.
124
+        $user = $this->get_user_id_or_email( $submission->get_billing_email() );
125
+
126
+        if ( empty( $user ) ) {
127
+            throw new GetPaid_Payment_Exception( '.getpaid-discount-field .getpaid-custom-payment-form-errors', __( 'You need to either log in or enter your billing email before applying this discount', 'invoicing' ) );
128
+        }
129
+
130
+        // Has the user used this discount code before?
131
+        if ( ! $discount->is_valid_for_user( $user ) ) {
132
+            throw new GetPaid_Payment_Exception( '.getpaid-discount-field .getpaid-custom-payment-form-errors', __( 'You have already used this discount', 'invoicing' ) );
133
+        }
134
+
135
+    }
136
+
137
+    /**
138
+     * Validates the discount's amount.
139
+     *
140
+     * @param GetPaid_Payment_Form_Submission $submission
141
+     * @param WPInv_Discount         $discount
142
+     * @param float                  $amount
143
+     */
144
+    public function validate_discount_amount( $submission, $discount, $amount ) {
145
+
146
+        // Validate minimum amount.
147
+        if ( ! $discount->is_minimum_amount_met( $amount ) ) {
148
+            $min = wpinv_price( $discount->get_minimum_total(), $submission->get_currency() );
149
+            throw new GetPaid_Payment_Exception( '.getpaid-discount-field .getpaid-custom-payment-form-errors', sprintf( __( 'The minimum total for using this discount is %s', 'invoicing' ), $min ) );
150
+        }
151
+
152
+        // Validate the maximum amount.
153
+        if ( ! $discount->is_maximum_amount_met( $amount ) ) {
154
+            $max = wpinv_price( $discount->get_maximum_total(), $submission->get_currency() );
155
+            throw new GetPaid_Payment_Exception( '.getpaid-discount-field .getpaid-custom-payment-form-errors', sprintf( __( 'The maximum total for using this discount is %s', 'invoicing' ), $max ) );
156
+        }
157
+
158
+    }
159
+
160
+    /**
161
+     * Calculates the discount code's amount.
162
+     *
163
+     * Ensure that the discount exists and has been validated before calling this method.
164
+     *
165
+     * @param GetPaid_Payment_Form_Submission $submission
166
+     * @param WPInv_Discount                  $discount
167
+     * @return array
168
+     */
169
+    public function calculate_discount( $submission, $discount ) {
170
+        return getpaid_calculate_invoice_discount( $submission, $discount );
171
+    }
172 172
 
173 173
 }
Please login to merge, or discard this patch.
includes/gateways/class-getpaid-authorize-net-gateway.php 1 patch
Indentation   +237 added lines, -237 removed lines patch added patch discarded remove patch
@@ -13,58 +13,58 @@  discard block
 block discarded – undo
13 13
 class GetPaid_Authorize_Net_Gateway extends GetPaid_Authorize_Net_Legacy_Gateway {
14 14
 
15 15
     /**
16
-	 * Payment method id.
17
-	 *
18
-	 * @var string
19
-	 */
16
+     * Payment method id.
17
+     *
18
+     * @var string
19
+     */
20 20
     public $id = 'authorizenet';
21 21
 
22 22
     /**
23
-	 * An array of features that this gateway supports.
24
-	 *
25
-	 * @var array
26
-	 */
23
+     * An array of features that this gateway supports.
24
+     *
25
+     * @var array
26
+     */
27 27
     protected $supports = array( 'subscription', 'sandbox', 'tokens', 'addons' );
28 28
 
29 29
     /**
30
-	 * Payment method order.
31
-	 *
32
-	 * @var int
33
-	 */
30
+     * Payment method order.
31
+     *
32
+     * @var int
33
+     */
34 34
     public $order = 4;
35 35
 
36 36
     /**
37
-	 * Endpoint for requests from Authorize.net.
38
-	 *
39
-	 * @var string
40
-	 */
41
-	protected $notify_url;
42
-
43
-	/**
44
-	 * Endpoint for requests to Authorize.net.
45
-	 *
46
-	 * @var string
47
-	 */
37
+     * Endpoint for requests from Authorize.net.
38
+     *
39
+     * @var string
40
+     */
41
+    protected $notify_url;
42
+
43
+    /**
44
+     * Endpoint for requests to Authorize.net.
45
+     *
46
+     * @var string
47
+     */
48 48
     protected $endpoint;
49 49
 
50 50
     /**
51
-	 * Currencies this gateway is allowed for.
52
-	 *
53
-	 * @var array
54
-	 */
55
-	public $currencies = array( 'USD', 'CAD', 'GBP', 'DKK', 'NOK', 'PLN', 'SEK', 'AUD', 'EUR', 'NZD' );
51
+     * Currencies this gateway is allowed for.
52
+     *
53
+     * @var array
54
+     */
55
+    public $currencies = array( 'USD', 'CAD', 'GBP', 'DKK', 'NOK', 'PLN', 'SEK', 'AUD', 'EUR', 'NZD' );
56 56
 
57 57
     /**
58
-	 * URL to view a transaction.
59
-	 *
60
-	 * @var string
61
-	 */
58
+     * URL to view a transaction.
59
+     *
60
+     * @var string
61
+     */
62 62
     public $view_transaction_url = 'https://{sandbox}authorize.net/ui/themes/sandbox/Transaction/TransactionReceipt.aspx?transid=%s';
63 63
 
64 64
     /**
65
-	 * Class constructor.
66
-	 */
67
-	public function __construct() {
65
+     * Class constructor.
66
+     */
67
+    public function __construct() {
68 68
 
69 69
         $this->title                = __( 'Credit Card / Debit Card', 'invoicing' );
70 70
         $this->method_title         = __( 'Authorize.Net', 'invoicing' );
@@ -76,11 +76,11 @@  discard block
 block discarded – undo
76 76
     }
77 77
 
78 78
     /**
79
-	 * Displays the payment method select field.
80
-	 *
81
-	 * @param int $invoice_id 0 or invoice id.
82
-	 * @param GetPaid_Payment_Form $form Current payment form.
83
-	 */
79
+     * Displays the payment method select field.
80
+     *
81
+     * @param int $invoice_id 0 or invoice id.
82
+     * @param GetPaid_Payment_Form $form Current payment form.
83
+     */
84 84
     public function payment_fields( $invoice_id, $form ) {
85 85
 
86 86
         // Let the user select a payment method.
@@ -91,16 +91,16 @@  discard block
 block discarded – undo
91 91
     }
92 92
 
93 93
     /**
94
-	 * Creates a customer profile.
95
-	 *
96
-	 *
97
-	 * @param WPInv_Invoice $invoice Invoice.
94
+     * Creates a customer profile.
95
+     *
96
+     *
97
+     * @param WPInv_Invoice $invoice Invoice.
98 98
      * @param array $submission_data Posted checkout fields.
99 99
      * @param bool $save Whether or not to save the payment as a token.
100 100
      * @link https://developer.authorize.net/api/reference/index.html#customer-profiles-create-customer-profile
101
-	 * @return string|WP_Error Payment profile id.
102
-	 */
103
-	public function create_customer_profile( $invoice, $submission_data, $save = true ) {
101
+     * @return string|WP_Error Payment profile id.
102
+     */
103
+    public function create_customer_profile( $invoice, $submission_data, $save = true ) {
104 104
 
105 105
         // Remove non-digits from the number
106 106
         $submission_data['authorizenet']['cc_number'] = preg_replace('/\D/', '', $submission_data['authorizenet']['cc_number'] );
@@ -167,14 +167,14 @@  discard block
 block discarded – undo
167 167
     }
168 168
 
169 169
     /**
170
-	 * Retrieves a customer profile.
171
-	 *
172
-	 *
173
-	 * @param string $profile_id profile id.
174
-	 * @return string|WP_Error Profile id.
170
+     * Retrieves a customer profile.
171
+     *
172
+     *
173
+     * @param string $profile_id profile id.
174
+     * @return string|WP_Error Profile id.
175 175
      * @link https://developer.authorize.net/api/reference/index.html#customer-profiles-get-customer-profile
176
-	 */
177
-	public function get_customer_profile( $profile_id ) {
176
+     */
177
+    public function get_customer_profile( $profile_id ) {
178 178
 
179 179
         // Generate args.
180 180
         $args = array(
@@ -189,17 +189,17 @@  discard block
 block discarded – undo
189 189
     }
190 190
 
191 191
     /**
192
-	 * Creates a customer profile.
193
-	 *
194
-	 *
192
+     * Creates a customer profile.
193
+     *
194
+     *
195 195
      * @param string $profile_id profile id.
196
-	 * @param WPInv_Invoice $invoice Invoice.
196
+     * @param WPInv_Invoice $invoice Invoice.
197 197
      * @param array $submission_data Posted checkout fields.
198 198
      * @param bool $save Whether or not to save the payment as a token.
199 199
      * @link https://developer.authorize.net/api/reference/index.html#customer-profiles-create-customer-profile
200
-	 * @return string|WP_Error Profile id.
201
-	 */
202
-	public function create_customer_payment_profile( $customer_profile, $invoice, $submission_data, $save ) {
200
+     * @return string|WP_Error Profile id.
201
+     */
202
+    public function create_customer_payment_profile( $customer_profile, $invoice, $submission_data, $save ) {
203 203
 
204 204
         // Remove non-digits from the number
205 205
         $submission_data['authorizenet']['cc_number'] = preg_replace('/\D/', '', $submission_data['authorizenet']['cc_number'] );
@@ -272,13 +272,13 @@  discard block
 block discarded – undo
272 272
     }
273 273
 
274 274
     /**
275
-	 * Retrieves payment details from cache.
276
-	 *
277
-	 *
275
+     * Retrieves payment details from cache.
276
+     *
277
+     *
278 278
      * @param array $payment_details.
279
-	 * @return array|false Profile id.
280
-	 */
281
-	public function retrieve_payment_profile_from_cache( $payment_details, $customer_profile, $invoice ) {
279
+     * @return array|false Profile id.
280
+     */
281
+    public function retrieve_payment_profile_from_cache( $payment_details, $customer_profile, $invoice ) {
282 282
 
283 283
         $cached_information = get_option( 'getpaid_authorize_net_cached_profiles', array() );
284 284
         $payment_details    = hash_hmac( 'sha256', json_encode( $payment_details ), SECURE_AUTH_KEY );
@@ -303,13 +303,13 @@  discard block
 block discarded – undo
303 303
     }
304 304
 
305 305
     /**
306
-	 * Securely adds payment details to cache.
307
-	 *
308
-	 *
306
+     * Securely adds payment details to cache.
307
+     *
308
+     *
309 309
      * @param array $payment_details.
310 310
      * @param string $payment_profile_id.
311
-	 */
312
-	public function add_payment_profile_to_cache( $payment_details, $payment_profile_id ) {
311
+     */
312
+    public function add_payment_profile_to_cache( $payment_details, $payment_profile_id ) {
313 313
 
314 314
         $cached_information = get_option( 'getpaid_authorize_net_cached_profiles', array() );
315 315
         $cached_information = is_array( $cached_information ) ? $cached_information : array();
@@ -321,15 +321,15 @@  discard block
 block discarded – undo
321 321
     }
322 322
 
323 323
     /**
324
-	 * Retrieves a customer payment profile.
325
-	 *
326
-	 *
327
-	 * @param string $customer_profile_id customer profile id.
324
+     * Retrieves a customer payment profile.
325
+     *
326
+     *
327
+     * @param string $customer_profile_id customer profile id.
328 328
      * @param string $payment_profile_id payment profile id.
329
-	 * @return string|WP_Error Profile id.
329
+     * @return string|WP_Error Profile id.
330 330
      * @link https://developer.authorize.net/api/reference/index.html#customer-profiles-get-customer-payment-profile
331
-	 */
332
-	public function get_customer_payment_profile( $customer_profile_id, $payment_profile_id ) {
331
+     */
332
+    public function get_customer_payment_profile( $customer_profile_id, $payment_profile_id ) {
333 333
 
334 334
         // Generate args.
335 335
         $args = array(
@@ -345,15 +345,15 @@  discard block
 block discarded – undo
345 345
     }
346 346
 
347 347
     /**
348
-	 * Charges a customer payment profile.
349
-	 *
348
+     * Charges a customer payment profile.
349
+     *
350 350
      * @param string $customer_profile_id customer profile id.
351 351
      * @param string $payment_profile_id payment profile id.
352
-	 * @param WPInv_Invoice $invoice Invoice.
352
+     * @param WPInv_Invoice $invoice Invoice.
353 353
      * @link https://developer.authorize.net/api/reference/index.html#payment-transactions-charge-a-customer-profile
354
-	 * @return WP_Error|object
355
-	 */
356
-	public function charge_customer_payment_profile( $customer_profile_id, $payment_profile_id, $invoice ) {
354
+     * @return WP_Error|object
355
+     */
356
+    public function charge_customer_payment_profile( $customer_profile_id, $payment_profile_id, $invoice ) {
357 357
 
358 358
         // Generate args.
359 359
         $args = array(
@@ -399,41 +399,41 @@  discard block
 block discarded – undo
399 399
     }
400 400
 
401 401
     /**
402
-	 * Processes a customer charge.
403
-	 *
402
+     * Processes a customer charge.
403
+     *
404 404
      * @param stdClass $result Api response.
405
-	 * @param WPInv_Invoice $invoice Invoice.
406
-	 */
407
-	public function process_charge_response( $result, $invoice ) {
405
+     * @param WPInv_Invoice $invoice Invoice.
406
+     */
407
+    public function process_charge_response( $result, $invoice ) {
408 408
 
409 409
         wpinv_clear_errors();
410
-		$response_code = (int) $result->transactionResponse->responseCode;
410
+        $response_code = (int) $result->transactionResponse->responseCode;
411 411
 
412
-		// Succeeded.
413
-		if ( 1 == $response_code || 4 == $response_code ) {
412
+        // Succeeded.
413
+        if ( 1 == $response_code || 4 == $response_code ) {
414 414
 
415
-			// Maybe set a transaction id.
416
-			if ( ! empty( $result->transactionResponse->transId ) ) {
417
-				$invoice->set_transaction_id( $result->transactionResponse->transId );
418
-			}
415
+            // Maybe set a transaction id.
416
+            if ( ! empty( $result->transactionResponse->transId ) ) {
417
+                $invoice->set_transaction_id( $result->transactionResponse->transId );
418
+            }
419 419
 
420
-			$invoice->add_note( sprintf( __( 'Authentication code: %s (%s).', 'invoicing' ), $result->transactionResponse->authCode, $result->transactionResponse->accountNumber ), false, false, true );
420
+            $invoice->add_note( sprintf( __( 'Authentication code: %s (%s).', 'invoicing' ), $result->transactionResponse->authCode, $result->transactionResponse->accountNumber ), false, false, true );
421 421
 
422
-			if ( 1 == $response_code ) {
423
-				return $invoice->mark_paid();
424
-			}
422
+            if ( 1 == $response_code ) {
423
+                return $invoice->mark_paid();
424
+            }
425 425
 
426
-			$invoice->set_status( 'wpi-onhold' );
427
-        	$invoice->add_note(
426
+            $invoice->set_status( 'wpi-onhold' );
427
+            $invoice->add_note(
428 428
                 sprintf(
429 429
                     __( 'Held for review: %s', 'invoicing' ),
430 430
                     $result->transactionResponse->messages->message[0]->description
431 431
                 )
432
-			);
432
+            );
433 433
 
434
-			return $invoice->save();
434
+            return $invoice->save();
435 435
 
436
-		}
436
+        }
437 437
 
438 438
         wpinv_set_error( 'card_declined', __( 'Credit card declined.', 'invoicing' ) );
439 439
 
@@ -445,13 +445,13 @@  discard block
 block discarded – undo
445 445
     }
446 446
 
447 447
     /**
448
-	 * Returns payment information.
449
-	 *
450
-	 *
451
-	 * @param array $card Card details.
452
-	 * @return array
453
-	 */
454
-	public function get_payment_information( $card ) {
448
+     * Returns payment information.
449
+     *
450
+     *
451
+     * @param array $card Card details.
452
+     * @return array
453
+     */
454
+    public function get_payment_information( $card ) {
455 455
         return array(
456 456
 
457 457
             'creditCard'         => array (
@@ -464,25 +464,25 @@  discard block
 block discarded – undo
464 464
     }
465 465
 
466 466
     /**
467
-	 * Returns the customer profile meta name.
468
-	 *
469
-	 *
470
-	 * @param WPInv_Invoice $invoice Invoice.
471
-	 * @return string
472
-	 */
473
-	public function get_customer_profile_meta_name( $invoice ) {
467
+     * Returns the customer profile meta name.
468
+     *
469
+     *
470
+     * @param WPInv_Invoice $invoice Invoice.
471
+     * @return string
472
+     */
473
+    public function get_customer_profile_meta_name( $invoice ) {
474 474
         return $this->is_sandbox( $invoice ) ? 'getpaid_authorizenet_sandbox_customer_profile_id' : 'getpaid_authorizenet_customer_profile_id';
475 475
     }
476 476
 
477 477
     /**
478
-	 * Validates the submitted data.
479
-	 *
480
-	 *
481
-	 * @param array $submission_data Posted checkout fields.
478
+     * Validates the submitted data.
479
+     *
480
+     *
481
+     * @param array $submission_data Posted checkout fields.
482 482
      * @param WPInv_Invoice $invoice
483
-	 * @return WP_Error|string The payment profile id
484
-	 */
485
-	public function validate_submission_data( $submission_data, $invoice ) {
483
+     * @return WP_Error|string The payment profile id
484
+     */
485
+    public function validate_submission_data( $submission_data, $invoice ) {
486 486
 
487 487
         // Validate authentication details.
488 488
         $auth = $this->get_auth_params();
@@ -514,13 +514,13 @@  discard block
 block discarded – undo
514 514
     }
515 515
 
516 516
     /**
517
-	 * Returns invoice line items.
518
-	 *
519
-	 *
520
-	 * @param WPInv_Invoice $invoice Invoice.
521
-	 * @return array
522
-	 */
523
-	public function get_line_items( $invoice ) {
517
+     * Returns invoice line items.
518
+     *
519
+     *
520
+     * @param WPInv_Invoice $invoice Invoice.
521
+     * @return array
522
+     */
523
+    public function get_line_items( $invoice ) {
524 524
         $items = array();
525 525
 
526 526
         foreach ( $invoice->get_items() as $item ) {
@@ -558,15 +558,15 @@  discard block
 block discarded – undo
558 558
     }
559 559
 
560 560
     /**
561
-	 * Process Payment.
562
-	 *
563
-	 *
564
-	 * @param WPInv_Invoice $invoice Invoice.
565
-	 * @param array $submission_data Posted checkout fields.
566
-	 * @param GetPaid_Payment_Form_Submission $submission Checkout submission.
567
-	 * @return array
568
-	 */
569
-	public function process_payment( $invoice, $submission_data, $submission ) {
561
+     * Process Payment.
562
+     *
563
+     *
564
+     * @param WPInv_Invoice $invoice Invoice.
565
+     * @param array $submission_data Posted checkout fields.
566
+     * @param GetPaid_Payment_Form_Submission $submission Checkout submission.
567
+     * @return array
568
+     */
569
+    public function process_payment( $invoice, $submission_data, $submission ) {
570 570
 
571 571
         // Validate the submitted data.
572 572
         $payment_profile_id = $this->validate_submission_data( $submission_data, $invoice );
@@ -599,69 +599,69 @@  discard block
 block discarded – undo
599 599
 
600 600
         exit;
601 601
 
602
-	}
602
+    }
603 603
 	
604
-	/**
605
-	 * Processes the initial payment.
606
-	 *
604
+    /**
605
+     * Processes the initial payment.
606
+     *
607 607
      * @param WPInv_Invoice $invoice Invoice.
608
-	 */
609
-	protected function process_initial_payment( $invoice ) {
608
+     */
609
+    protected function process_initial_payment( $invoice ) {
610 610
 
611
-		$payment_profile_id = get_post_meta( $invoice->get_id(), 'getpaid_authorizenet_profile_id', true );
611
+        $payment_profile_id = get_post_meta( $invoice->get_id(), 'getpaid_authorizenet_profile_id', true );
612 612
         $customer_profile   = get_user_meta( $invoice->get_user_id(), $this->get_customer_profile_meta_name( $invoice ), true );
613
-		$result             = $this->charge_customer_payment_profile( $customer_profile, $payment_profile_id, $invoice );
613
+        $result             = $this->charge_customer_payment_profile( $customer_profile, $payment_profile_id, $invoice );
614 614
 
615
-		// Do we have an error?
616
-		if ( is_wp_error( $result ) ) {
617
-			wpinv_set_error( $result->get_error_code(), $result->get_error_message() );
618
-			wpinv_send_back_to_checkout( $invoice );
619
-		}
615
+        // Do we have an error?
616
+        if ( is_wp_error( $result ) ) {
617
+            wpinv_set_error( $result->get_error_code(), $result->get_error_message() );
618
+            wpinv_send_back_to_checkout( $invoice );
619
+        }
620 620
 
621
-		// Process the response.
622
-		$this->process_charge_response( $result, $invoice );
621
+        // Process the response.
622
+        $this->process_charge_response( $result, $invoice );
623 623
 
624
-		if ( wpinv_get_errors() ) {
625
-			wpinv_send_back_to_checkout( $invoice );
626
-		}
624
+        if ( wpinv_get_errors() ) {
625
+            wpinv_send_back_to_checkout( $invoice );
626
+        }
627 627
 
628
-	}
628
+    }
629 629
 
630 630
     /**
631
-	 * Processes recurring payments.
632
-	 *
631
+     * Processes recurring payments.
632
+     *
633 633
      * @param WPInv_Invoice $invoice Invoice.
634 634
      * @param WPInv_Subscription $subscription Subscription.
635
-	 */
636
-	public function process_subscription( $invoice, $subscription ) {
635
+     */
636
+    public function process_subscription( $invoice, $subscription ) {
637 637
 
638 638
         // Check if there is an initial amount to charge.
639 639
         if ( (float) $invoice->get_total() > 0 ) {
640
-			$this->process_initial_payment( $invoice );
640
+            $this->process_initial_payment( $invoice );
641 641
         }
642 642
 
643 643
         // Activate the subscription.
644 644
         $duration = strtotime( $subscription->get_expiration() ) - strtotime( $subscription->get_date_created() );
645 645
         $expiry   = date( 'Y-m-d H:i:s', ( current_time( 'timestamp' ) + $duration ) );
646 646
 
647
-		$subscription->set_next_renewal_date( $expiry );
648
-		$subscription->set_date_created( current_time( 'mysql' ) );
649
-		$subscription->set_profile_id( $invoice->generate_key() );
650
-		$subscription->activate();
647
+        $subscription->set_next_renewal_date( $expiry );
648
+        $subscription->set_date_created( current_time( 'mysql' ) );
649
+        $subscription->set_profile_id( $invoice->generate_key() );
650
+        $subscription->activate();
651 651
 
652
-		// Redirect to the success page.
652
+        // Redirect to the success page.
653 653
         wpinv_send_to_success_page( array( 'invoice_key' => $invoice->get_key() ) );
654 654
 
655 655
     }
656 656
 
657
-	/**
658
-	 * (Maybe) renews an authorize.net subscription profile.
659
-	 *
660
-	 *
661
-	 * @param bool $should_expire
657
+    /**
658
+     * (Maybe) renews an authorize.net subscription profile.
659
+     *
660
+     *
661
+     * @param bool $should_expire
662 662
      * @param WPInv_Subscription $subscription
663
-	 */
664
-	public function maybe_renew_subscription( $should_expire, $subscription ) {
663
+     */
664
+    public function maybe_renew_subscription( $should_expire, $subscription ) {
665 665
 
666 666
         // Ensure its our subscription && it's active.
667 667
         if ( $this->id != $subscription->get_gateway() || ! $subscription->has_status( 'active trialling' ) ) {
@@ -678,18 +678,18 @@  discard block
 block discarded – undo
678 678
 
679 679
         return false;
680 680
 
681
-	}
681
+    }
682 682
 
683 683
     /**
684
-	 * Renews a subscription.
685
-	 *
684
+     * Renews a subscription.
685
+     *
686 686
      * @param WPInv_Subscription $subscription
687
-	 */
688
-	public function renew_subscription( $subscription ) {
687
+     */
688
+    public function renew_subscription( $subscription ) {
689 689
 
690
-		// Generate the renewal invoice.
691
-		$new_invoice = $subscription->create_payment();
692
-		$old_invoice = $subscription->get_parent_payment();
690
+        // Generate the renewal invoice.
691
+        $new_invoice = $subscription->create_payment();
692
+        $old_invoice = $subscription->get_parent_payment();
693 693
 
694 694
         if ( empty( $new_invoice ) ) {
695 695
             $old_invoice->add_note( __( 'Error generating a renewal invoice.', 'invoicing' ), false, false, false );
@@ -698,37 +698,37 @@  discard block
 block discarded – undo
698 698
         }
699 699
 
700 700
         // Charge the payment method.
701
-		$payment_profile_id = get_post_meta( $old_invoice->get_id(), 'getpaid_authorizenet_profile_id', true );
702
-		$customer_profile   = get_user_meta( $old_invoice->get_user_id(), $this->get_customer_profile_meta_name( $old_invoice ), true );
703
-		$result             = $this->charge_customer_payment_profile( $customer_profile, $payment_profile_id, $new_invoice );
704
-
705
-		// Do we have an error?
706
-		if ( is_wp_error( $result ) ) {
707
-
708
-			$old_invoice->add_note(
709
-				sprintf( __( 'Error renewing subscription : ( %s ).', 'invoicing' ), $result->get_error_message() ),
710
-				true,
711
-				false,
712
-				true
713
-			);
714
-			$subscription->failing();
715
-			return;
716
-
717
-		}
718
-
719
-		// Process the response.
720
-		$this->process_charge_response( $result, $new_invoice );
721
-
722
-		if ( wpinv_get_errors() ) {
723
-
724
-			$old_invoice->add_note(
725
-				sprintf( __( 'Error renewing subscription : ( %s ).', 'invoicing' ), getpaid_get_errors_html() ),
726
-				true,
727
-				false,
728
-				true
729
-			);
730
-			$subscription->failing();
731
-			return;
701
+        $payment_profile_id = get_post_meta( $old_invoice->get_id(), 'getpaid_authorizenet_profile_id', true );
702
+        $customer_profile   = get_user_meta( $old_invoice->get_user_id(), $this->get_customer_profile_meta_name( $old_invoice ), true );
703
+        $result             = $this->charge_customer_payment_profile( $customer_profile, $payment_profile_id, $new_invoice );
704
+
705
+        // Do we have an error?
706
+        if ( is_wp_error( $result ) ) {
707
+
708
+            $old_invoice->add_note(
709
+                sprintf( __( 'Error renewing subscription : ( %s ).', 'invoicing' ), $result->get_error_message() ),
710
+                true,
711
+                false,
712
+                true
713
+            );
714
+            $subscription->failing();
715
+            return;
716
+
717
+        }
718
+
719
+        // Process the response.
720
+        $this->process_charge_response( $result, $new_invoice );
721
+
722
+        if ( wpinv_get_errors() ) {
723
+
724
+            $old_invoice->add_note(
725
+                sprintf( __( 'Error renewing subscription : ( %s ).', 'invoicing' ), getpaid_get_errors_html() ),
726
+                true,
727
+                false,
728
+                true
729
+            );
730
+            $subscription->failing();
731
+            return;
732 732
 
733 733
         }
734 734
 
@@ -737,13 +737,13 @@  discard block
 block discarded – undo
737 737
     }
738 738
 
739 739
     /**
740
-	 * Processes invoice addons.
741
-	 *
742
-	 * @param WPInv_Invoice $invoice
743
-	 * @param GetPaid_Form_Item[] $items
744
-	 * @return WPInv_Invoice
745
-	 */
746
-	public function process_addons( $invoice, $items ) {
740
+     * Processes invoice addons.
741
+     *
742
+     * @param WPInv_Invoice $invoice
743
+     * @param GetPaid_Form_Item[] $items
744
+     * @return WPInv_Invoice
745
+     */
746
+    public function process_addons( $invoice, $items ) {
747 747
 
748 748
         global $getpaid_authorize_addons;
749 749
 
@@ -763,7 +763,7 @@  discard block
 block discarded – undo
763 763
         $invoice->recalculate_total();
764 764
 
765 765
         $payment_profile_id = get_post_meta( $invoice->get_id(), 'getpaid_authorizenet_profile_id', true );
766
-		$customer_profile   = get_user_meta( $invoice->get_user_id(), $this->get_customer_profile_meta_name( $invoice ), true );
766
+        $customer_profile   = get_user_meta( $invoice->get_user_id(), $this->get_customer_profile_meta_name( $invoice ), true );
767 767
 
768 768
         add_filter( 'getpaid_authorizenet_charge_customer_payment_profile_args', array( $this, 'filter_addons_request' ), 10, 2 );
769 769
         $result = $this->charge_customer_payment_profile( $customer_profile, $payment_profile_id, $invoice );
@@ -778,11 +778,11 @@  discard block
 block discarded – undo
778 778
     }
779 779
 
780 780
     /**
781
-	 * Processes invoice addons.
782
-	 *
781
+     * Processes invoice addons.
782
+     *
783 783
      * @param array $args
784
-	 * @return array
785
-	 */
784
+     * @return array
785
+     */
786 786
     public function filter_addons_request( $args ) {
787 787
 
788 788
         global $getpaid_authorize_addons;
@@ -816,11 +816,11 @@  discard block
 block discarded – undo
816 816
     }
817 817
 
818 818
     /**
819
-	 * Filters the gateway settings.
820
-	 *
821
-	 * @param array $admin_settings
822
-	 */
823
-	public function admin_settings( $admin_settings ) {
819
+     * Filters the gateway settings.
820
+     *
821
+     * @param array $admin_settings
822
+     */
823
+    public function admin_settings( $admin_settings ) {
824 824
 
825 825
         $currencies = sprintf(
826 826
             __( 'Supported Currencies: %s', 'invoicing' ),
@@ -860,7 +860,7 @@  discard block
 block discarded – undo
860 860
             'readonly' => true,
861 861
         );
862 862
 
863
-		return $admin_settings;
864
-	}
863
+        return $admin_settings;
864
+    }
865 865
 
866 866
 }
Please login to merge, or discard this patch.
includes/reports/class-getpaid-reports-helper.php 1 patch
Indentation   +276 added lines, -276 removed lines patch added patch discarded remove patch
@@ -12,294 +12,294 @@
 block discarded – undo
12 12
  */
13 13
 class GetPaid_Reports_Helper {
14 14
 
15
-	/**
16
-	 * Get report totals such as invoice totals and discount amounts.
17
-	 *
18
-	 * Data example:
19
-	 *
20
-	 * 'subtotal' => array(
21
-	 *     'type'     => 'invoice_data',
22
-	 *     'function' => 'SUM',
23
-	 *     'name'     => 'subtotal'
24
-	 * )
25
-	 *
26
-	 * @param  array $args
27
-	 * @return mixed depending on query_type
28
-	 */
29
-	public static function get_invoice_report_data( $args = array() ) {
30
-		global $wpdb;
31
-
32
-		$default_args = array(
33
-			'data'                  => array(), // The data to retrieve.
34
-			'where'                 => array(), // An array of where queries.
35
-			'query_type'            => 'get_row', // wpdb query to run.
36
-			'group_by'              => '', // What to group results by.
37
-			'order_by'              => '', // What to order by.
38
-			'limit'                 => '', // Results limit.
39
-			'filter_range'          => array(), // An array of before and after dates to limit results by.
40
-			'invoice_types'         => array( 'wpi_invoice' ), // An array of post types to retrieve.
41
-			'invoice_status'        => array( 'publish', 'wpi-processing', 'wpi-onhold' ),
42
-			'parent_invoice_status' => false, // Optionally filter by parent invoice status.
43
-		);
44
-
45
-		$args         = apply_filters( 'getpaid_reports_get_invoice_report_data_args', $args );
46
-		$args         = wp_parse_args( $args, $default_args );
47
-
48
-		extract( $args );
49
-
50
-		if ( empty( $data ) ) {
51
-			return '';
52
-		}
53
-
54
-		$query           = array();
55
-		$query['select'] = 'SELECT ' . implode( ',', self::prepare_invoice_data( $data ) );
56
-		$query['from']   = "FROM {$wpdb->posts} AS posts";
57
-		$query['join']   = implode( ' ', self::prepare_invoice_joins( $data + $where, ! empty( $parent_invoice_status ) ) );
58
-
59
-		$query['where']  = "
15
+    /**
16
+     * Get report totals such as invoice totals and discount amounts.
17
+     *
18
+     * Data example:
19
+     *
20
+     * 'subtotal' => array(
21
+     *     'type'     => 'invoice_data',
22
+     *     'function' => 'SUM',
23
+     *     'name'     => 'subtotal'
24
+     * )
25
+     *
26
+     * @param  array $args
27
+     * @return mixed depending on query_type
28
+     */
29
+    public static function get_invoice_report_data( $args = array() ) {
30
+        global $wpdb;
31
+
32
+        $default_args = array(
33
+            'data'                  => array(), // The data to retrieve.
34
+            'where'                 => array(), // An array of where queries.
35
+            'query_type'            => 'get_row', // wpdb query to run.
36
+            'group_by'              => '', // What to group results by.
37
+            'order_by'              => '', // What to order by.
38
+            'limit'                 => '', // Results limit.
39
+            'filter_range'          => array(), // An array of before and after dates to limit results by.
40
+            'invoice_types'         => array( 'wpi_invoice' ), // An array of post types to retrieve.
41
+            'invoice_status'        => array( 'publish', 'wpi-processing', 'wpi-onhold' ),
42
+            'parent_invoice_status' => false, // Optionally filter by parent invoice status.
43
+        );
44
+
45
+        $args         = apply_filters( 'getpaid_reports_get_invoice_report_data_args', $args );
46
+        $args         = wp_parse_args( $args, $default_args );
47
+
48
+        extract( $args );
49
+
50
+        if ( empty( $data ) ) {
51
+            return '';
52
+        }
53
+
54
+        $query           = array();
55
+        $query['select'] = 'SELECT ' . implode( ',', self::prepare_invoice_data( $data ) );
56
+        $query['from']   = "FROM {$wpdb->posts} AS posts";
57
+        $query['join']   = implode( ' ', self::prepare_invoice_joins( $data + $where, ! empty( $parent_invoice_status ) ) );
58
+
59
+        $query['where']  = "
60 60
 			WHERE 	posts.post_type 	IN ( '" . implode( "','", $invoice_types ) . "' )
61 61
 			";
62 62
 
63
-		if ( ! empty( $invoice_status ) ) {
64
-			$query['where'] .= "
63
+        if ( ! empty( $invoice_status ) ) {
64
+            $query['where'] .= "
65 65
 				AND 	posts.post_status 	IN ( '" . implode( "','", $invoice_status ) . "' )
66 66
 			";
67
-		}
68
-
69
-		if ( ! empty( $parent_invoice_status ) ) {
70
-			if ( ! empty( $invoice_status ) ) {
71
-				$query['where'] .= " AND ( parent.post_status IN ( '" . implode( "','", $parent_invoice_status ) . "' ) OR parent.ID IS NULL ) ";
72
-			} else {
73
-				$query['where'] .= " AND parent.post_status IN ( '" . implode( "','", $parent_invoice_status ) . "' ) ";
74
-			}
75
-		}
76
-
77
-		if ( ! empty( $filter_range['before'] ) ) {
78
-			$query['where'] .= "
67
+        }
68
+
69
+        if ( ! empty( $parent_invoice_status ) ) {
70
+            if ( ! empty( $invoice_status ) ) {
71
+                $query['where'] .= " AND ( parent.post_status IN ( '" . implode( "','", $parent_invoice_status ) . "' ) OR parent.ID IS NULL ) ";
72
+            } else {
73
+                $query['where'] .= " AND parent.post_status IN ( '" . implode( "','", $parent_invoice_status ) . "' ) ";
74
+            }
75
+        }
76
+
77
+        if ( ! empty( $filter_range['before'] ) ) {
78
+            $query['where'] .= "
79 79
 				AND 	posts.post_date < '" . date( 'Y-m-d H:i:s', strtotime( $filter_range['before'] ) ) . "'
80 80
 			";
81
-		}
81
+        }
82 82
 
83
-		if ( ! empty( $filter_range['after'] ) ) {
84
-			$query['where'] .= "
83
+        if ( ! empty( $filter_range['after'] ) ) {
84
+            $query['where'] .= "
85 85
 				AND 	posts.post_date > '" . date( 'Y-m-d H:i:s', strtotime( $filter_range['after'] ) ) . "'
86 86
 			";
87
-		}
87
+        }
88 88
 
89
-		if ( ! empty( $where ) ) {
89
+        if ( ! empty( $where ) ) {
90 90
 
91
-			foreach ( $where as $value ) {
91
+            foreach ( $where as $value ) {
92 92
 
93
-				if ( strtolower( $value['operator'] ) == 'in' || strtolower( $value['operator'] ) == 'not in' ) {
94
-
95
-					if ( is_array( $value['value'] ) ) {
96
-						$value['value'] = implode( "','", $value['value'] );
97
-					}
98
-
99
-					if ( ! empty( $value['value'] ) ) {
100
-						$where_value = "{$value['operator']} ('{$value['value']}')";
101
-					}
102
-				} else {
103
-					$where_value = "{$value['operator']} '{$value['value']}'";
104
-				}
105
-
106
-				if ( ! empty( $where_value ) ) {
107
-					$query['where'] .= " AND {$value['key']} {$where_value}";
108
-				}
109
-			}
110
-		}
111
-
112
-		if ( $group_by ) {
113
-			$query['group_by'] = "GROUP BY {$group_by}";
114
-		}
115
-
116
-		if ( $order_by ) {
117
-			$query['order_by'] = "ORDER BY {$order_by}";
118
-		}
119
-
120
-		if ( $limit ) {
121
-			$query['limit'] = "LIMIT {$limit}";
122
-		}
123
-
124
-		$query = apply_filters( 'getpaid_reports_get_invoice_report_query', $query, $data );
125
-		$query = implode( ' ', $query );
126
-
127
-		return self::execute( $query_type, $query );
128
-
129
-	}
130
-
131
-	/**
132
-	 * Prepares the data to select.
133
-	 *
134
-	 *
135
-	 * @param  array $data
136
-	 * @return array
137
-	 */
138
-	public static function prepare_invoice_data( $data ) {
139
-
140
-		$prepared = array();
141
-
142
-		foreach ( $data as $raw_key => $value ) {
143
-			$key      = sanitize_key( $raw_key );
144
-			$distinct = '';
145
-
146
-			if ( isset( $value['distinct'] ) ) {
147
-				$distinct = 'DISTINCT';
148
-			}
149
-
150
-			$get_key = self::get_invoice_table_key( $key, $value['type'] );
151
-
152
-			if ( false === $get_key ) {
153
-				// Skip to the next foreach iteration else the query will be invalid.
154
-				continue;
155
-			}
156
-
157
-			if ( ! empty( $value['function'] ) ) {
158
-				$get = "{$value['function']}({$distinct} {$get_key})";
159
-			} else {
160
-				$get = "{$distinct} {$get_key}";
161
-			}
162
-
163
-			$prepared[] = "{$get} as {$value['name']}";
164
-		}
165
-
166
-		return $prepared;
167
-
168
-	}
169
-
170
-	/**
171
-	 * Prepares the joins to use.
172
-	 *
173
-	 *
174
-	 * @param  array $data
175
-	 * @param  bool $with_parent
176
-	 * @return array
177
-	 */
178
-	public static function prepare_invoice_joins( $data, $with_parent ) {
179
-		global $wpdb;
180
-
181
-		$prepared = array();
182
-
183
-		foreach ( $data as $raw_key => $value ) {
184
-			$join_type = isset( $value['join_type'] ) ? $value['join_type'] : 'INNER';
185
-			$type      = isset( $value['type'] ) ? $value['type'] : false;
186
-			$key       = sanitize_key( $raw_key );
187
-
188
-			switch ( $type ) {
189
-				case 'meta':
190
-					$prepared[ "meta_{$key}" ] = "{$join_type} JOIN {$wpdb->postmeta} AS meta_{$key} ON ( posts.ID = meta_{$key}.post_id AND meta_{$key}.meta_key = '{$raw_key}' )";
191
-					break;
192
-				case 'parent_meta':
193
-					$prepared[ "parent_meta_{$key}" ] = "{$join_type} JOIN {$wpdb->postmeta} AS parent_meta_{$key} ON (posts.post_parent = parent_meta_{$key}.post_id) AND (parent_meta_{$key}.meta_key = '{$raw_key}')";
194
-					break;
195
-				case 'invoice_data':
196
-					$prepared['invoices'] = "{$join_type} JOIN {$wpdb->prefix}getpaid_invoices AS invoices ON posts.ID = invoices.post_id";
197
-					break;
198
-				case 'invoice_item':
199
-					$prepared['invoice_items'] = "{$join_type} JOIN {$wpdb->prefix}getpaid_invoice_items AS invoice_items ON posts.ID = invoice_items.post_id";
200
-					break;
201
-			}
202
-		}
203
-
204
-		if ( $with_parent ) {
205
-			$prepared['parent'] = "LEFT JOIN {$wpdb->posts} AS parent ON posts.post_parent = parent.ID";
206
-		}
207
-
208
-		return $prepared;
209
-
210
-	}
211
-
212
-	/**
213
-	 * Retrieves the appropriate table key to use.
214
-	 *
215
-	 *
216
-	 * @param  string $key
217
-	 * @param  string $table
218
-	 * @return string|false
219
-	 */
220
-	public static function get_invoice_table_key( $key, $table ) {
221
-
222
-		$keys = array(
223
-			'meta'         => "meta_{$key}.meta_value",
224
-			'parent_meta'  => "parent_meta_{$key}.meta_value",
225
-			'post_data'    => "posts.{$key}",
226
-			'invoice_data' => "invoices.{$key}",
227
-			'invoice_item' => "invoice_items.{$key}",
228
-		);
229
-
230
-		return isset( $keys[ $table ] ) ? $keys[ $table ] : false;
231
-
232
-	}
233
-
234
-	/**
235
-	 * Executes a query and caches the result for a minute.
236
-	 *
237
-	 *
238
-	 * @param  string $query_type
239
-	 * @param  string $query
240
-	 * @return mixed depending on query_type
241
-	 */
242
-	public static function execute( $query_type, $query ) {
243
-		global $wpdb;
244
-
245
-		$query_hash = md5( $query_type . $query );
246
-		$result     = self::get_cached_query( $query_hash );
247
-		if ( $result === false ) {
248
-			self::enable_big_selects();
249
-
250
-			$result = $wpdb->$query_type( $query );
251
-			self::set_cached_query( $query_hash, $result );
252
-		}
253
-
254
-		return $result;
255
-
256
-	}
257
-
258
-	/**
259
-	 * Enables big mysql selects for reports, just once for this session.
260
-	 */
261
-	protected static function enable_big_selects() {
262
-		static $big_selects = false;
263
-
264
-		global $wpdb;
265
-
266
-		if ( ! $big_selects ) {
267
-			$wpdb->query( 'SET SESSION SQL_BIG_SELECTS=1' );
268
-			$big_selects = true;
269
-		}
270
-	}
271
-
272
-	/**
273
-	 * Get the cached query result or null if it's not in the cache.
274
-	 *
275
-	 * @param string $query_hash The query hash.
276
-	 *
277
-	 * @return mixed|false The cache contents on success, false on failure to retrieve contents.
278
-	 */
279
-	protected static function get_cached_query( $query_hash ) {
280
-
281
-		return wp_cache_get(
282
-			$query_hash,
283
-			strtolower( __CLASS__ )
284
-		);
285
-
286
-	}
287
-
288
-	/**
289
-	 * Set the cached query result.
290
-	 *
291
-	 * @param string $query_hash The query hash.
292
-	 * @param mixed  $data The data to cache.
293
-	 */
294
-	protected static function set_cached_query( $query_hash, $data ) {
295
-
296
-		wp_cache_set(
297
-			$query_hash,
298
-			$data,
299
-			strtolower( __CLASS__ ),
300
-			MINUTE_IN_SECONDS
301
-		);
302
-
303
-	}
93
+                if ( strtolower( $value['operator'] ) == 'in' || strtolower( $value['operator'] ) == 'not in' ) {
94
+
95
+                    if ( is_array( $value['value'] ) ) {
96
+                        $value['value'] = implode( "','", $value['value'] );
97
+                    }
98
+
99
+                    if ( ! empty( $value['value'] ) ) {
100
+                        $where_value = "{$value['operator']} ('{$value['value']}')";
101
+                    }
102
+                } else {
103
+                    $where_value = "{$value['operator']} '{$value['value']}'";
104
+                }
105
+
106
+                if ( ! empty( $where_value ) ) {
107
+                    $query['where'] .= " AND {$value['key']} {$where_value}";
108
+                }
109
+            }
110
+        }
111
+
112
+        if ( $group_by ) {
113
+            $query['group_by'] = "GROUP BY {$group_by}";
114
+        }
115
+
116
+        if ( $order_by ) {
117
+            $query['order_by'] = "ORDER BY {$order_by}";
118
+        }
119
+
120
+        if ( $limit ) {
121
+            $query['limit'] = "LIMIT {$limit}";
122
+        }
123
+
124
+        $query = apply_filters( 'getpaid_reports_get_invoice_report_query', $query, $data );
125
+        $query = implode( ' ', $query );
126
+
127
+        return self::execute( $query_type, $query );
128
+
129
+    }
130
+
131
+    /**
132
+     * Prepares the data to select.
133
+     *
134
+     *
135
+     * @param  array $data
136
+     * @return array
137
+     */
138
+    public static function prepare_invoice_data( $data ) {
139
+
140
+        $prepared = array();
141
+
142
+        foreach ( $data as $raw_key => $value ) {
143
+            $key      = sanitize_key( $raw_key );
144
+            $distinct = '';
145
+
146
+            if ( isset( $value['distinct'] ) ) {
147
+                $distinct = 'DISTINCT';
148
+            }
149
+
150
+            $get_key = self::get_invoice_table_key( $key, $value['type'] );
151
+
152
+            if ( false === $get_key ) {
153
+                // Skip to the next foreach iteration else the query will be invalid.
154
+                continue;
155
+            }
156
+
157
+            if ( ! empty( $value['function'] ) ) {
158
+                $get = "{$value['function']}({$distinct} {$get_key})";
159
+            } else {
160
+                $get = "{$distinct} {$get_key}";
161
+            }
162
+
163
+            $prepared[] = "{$get} as {$value['name']}";
164
+        }
165
+
166
+        return $prepared;
167
+
168
+    }
169
+
170
+    /**
171
+     * Prepares the joins to use.
172
+     *
173
+     *
174
+     * @param  array $data
175
+     * @param  bool $with_parent
176
+     * @return array
177
+     */
178
+    public static function prepare_invoice_joins( $data, $with_parent ) {
179
+        global $wpdb;
180
+
181
+        $prepared = array();
182
+
183
+        foreach ( $data as $raw_key => $value ) {
184
+            $join_type = isset( $value['join_type'] ) ? $value['join_type'] : 'INNER';
185
+            $type      = isset( $value['type'] ) ? $value['type'] : false;
186
+            $key       = sanitize_key( $raw_key );
187
+
188
+            switch ( $type ) {
189
+                case 'meta':
190
+                    $prepared[ "meta_{$key}" ] = "{$join_type} JOIN {$wpdb->postmeta} AS meta_{$key} ON ( posts.ID = meta_{$key}.post_id AND meta_{$key}.meta_key = '{$raw_key}' )";
191
+                    break;
192
+                case 'parent_meta':
193
+                    $prepared[ "parent_meta_{$key}" ] = "{$join_type} JOIN {$wpdb->postmeta} AS parent_meta_{$key} ON (posts.post_parent = parent_meta_{$key}.post_id) AND (parent_meta_{$key}.meta_key = '{$raw_key}')";
194
+                    break;
195
+                case 'invoice_data':
196
+                    $prepared['invoices'] = "{$join_type} JOIN {$wpdb->prefix}getpaid_invoices AS invoices ON posts.ID = invoices.post_id";
197
+                    break;
198
+                case 'invoice_item':
199
+                    $prepared['invoice_items'] = "{$join_type} JOIN {$wpdb->prefix}getpaid_invoice_items AS invoice_items ON posts.ID = invoice_items.post_id";
200
+                    break;
201
+            }
202
+        }
203
+
204
+        if ( $with_parent ) {
205
+            $prepared['parent'] = "LEFT JOIN {$wpdb->posts} AS parent ON posts.post_parent = parent.ID";
206
+        }
207
+
208
+        return $prepared;
209
+
210
+    }
211
+
212
+    /**
213
+     * Retrieves the appropriate table key to use.
214
+     *
215
+     *
216
+     * @param  string $key
217
+     * @param  string $table
218
+     * @return string|false
219
+     */
220
+    public static function get_invoice_table_key( $key, $table ) {
221
+
222
+        $keys = array(
223
+            'meta'         => "meta_{$key}.meta_value",
224
+            'parent_meta'  => "parent_meta_{$key}.meta_value",
225
+            'post_data'    => "posts.{$key}",
226
+            'invoice_data' => "invoices.{$key}",
227
+            'invoice_item' => "invoice_items.{$key}",
228
+        );
229
+
230
+        return isset( $keys[ $table ] ) ? $keys[ $table ] : false;
231
+
232
+    }
233
+
234
+    /**
235
+     * Executes a query and caches the result for a minute.
236
+     *
237
+     *
238
+     * @param  string $query_type
239
+     * @param  string $query
240
+     * @return mixed depending on query_type
241
+     */
242
+    public static function execute( $query_type, $query ) {
243
+        global $wpdb;
244
+
245
+        $query_hash = md5( $query_type . $query );
246
+        $result     = self::get_cached_query( $query_hash );
247
+        if ( $result === false ) {
248
+            self::enable_big_selects();
249
+
250
+            $result = $wpdb->$query_type( $query );
251
+            self::set_cached_query( $query_hash, $result );
252
+        }
253
+
254
+        return $result;
255
+
256
+    }
257
+
258
+    /**
259
+     * Enables big mysql selects for reports, just once for this session.
260
+     */
261
+    protected static function enable_big_selects() {
262
+        static $big_selects = false;
263
+
264
+        global $wpdb;
265
+
266
+        if ( ! $big_selects ) {
267
+            $wpdb->query( 'SET SESSION SQL_BIG_SELECTS=1' );
268
+            $big_selects = true;
269
+        }
270
+    }
271
+
272
+    /**
273
+     * Get the cached query result or null if it's not in the cache.
274
+     *
275
+     * @param string $query_hash The query hash.
276
+     *
277
+     * @return mixed|false The cache contents on success, false on failure to retrieve contents.
278
+     */
279
+    protected static function get_cached_query( $query_hash ) {
280
+
281
+        return wp_cache_get(
282
+            $query_hash,
283
+            strtolower( __CLASS__ )
284
+        );
285
+
286
+    }
287
+
288
+    /**
289
+     * Set the cached query result.
290
+     *
291
+     * @param string $query_hash The query hash.
292
+     * @param mixed  $data The data to cache.
293
+     */
294
+    protected static function set_cached_query( $query_hash, $data ) {
295
+
296
+        wp_cache_set(
297
+            $query_hash,
298
+            $data,
299
+            strtolower( __CLASS__ ),
300
+            MINUTE_IN_SECONDS
301
+        );
302
+
303
+    }
304 304
 
305 305
 }
Please login to merge, or discard this patch.