Passed
Pull Request — master (#136)
by Daniel
06:36 queued 04:43
created
classes/class-algolia-woo-indexer.php 1 patch
Indentation   +464 added lines, -464 removed lines patch added patch discarded remove patch
@@ -23,418 +23,418 @@  discard block
 block discarded – undo
23 23
  * Include plugin file if function is_plugin_active does not exist
24 24
  */
25 25
 if (! function_exists('is_plugin_active')) {
26
-    require_once(ABSPATH . '/wp-admin/includes/plugin.php');
26
+	require_once(ABSPATH . '/wp-admin/includes/plugin.php');
27 27
 }
28 28
 
29 29
 if (! class_exists('Algolia_Woo_Indexer')) {
30
-    /**
31
-     * Algolia WooIndexer main class
32
-     */
33
-    class Algolia_Woo_Indexer
34
-    {
35
-        const PLUGIN_NAME      = 'Algolia Woo Indexer';
36
-        const PLUGIN_TRANSIENT = 'algowoo-plugin-notice';
37
-
38
-        /**
39
-         * Class instance
40
-         *
41
-         * @var object
42
-         */
43
-        private static $instance;
44
-
45
-        /**
46
-         * The plugin URL
47
-         *
48
-         * @var string
49
-         */
50
-        private static $plugin_url = '';
51
-
52
-        /**
53
-         * Class constructor
54
-         *
55
-         * @return void
56
-         */
57
-        public function __construct()
58
-        {
59
-            $this->init();
60
-        }
61
-
62
-        /**
63
-         * Setup sections and fields to store and retrieve values from Settings API
64
-         *
65
-         * @return void
66
-         */
67
-        public static function setup_settings_sections()
68
-        {
69
-            /**
70
-            * Setup arguments for settings sections and fields
71
-            *
72
-            * @see https://developer.wordpress.org/reference/functions/register_setting/
73
-            */
74
-            if (is_admin()) {
75
-                $arguments = array(
76
-                    'type'              => 'string',
77
-                    'sanitize_callback' => 'settings_fields_validate_options',
78
-                    'default'           => null,
79
-                );
80
-                register_setting('algolia_woo_options', 'algolia_woo_options', $arguments);
81
-
82
-                /**
83
-                 * Make sure we reference the instance of the current class by using self::get_instance()
84
-                 * This way we can setup the correct callback function for add_settings_section and add_settings_field
85
-                 */
86
-                $algowooindexer = self::get_instance();
87
-
88
-                /**
89
-                 * Add our necessary settings sections and fields
90
-                 */
91
-                add_settings_section(
92
-                    'algolia_woo_indexer_main',
93
-                    esc_html__('Algolia Woo Plugin Settings', 'algolia-woo-indexer'),
94
-                    array( $algowooindexer, 'algolia_woo_indexer_section_text' ),
95
-                    'algolia_woo_indexer'
96
-                );
97
-                add_settings_field(
98
-                    'algolia_woo_indexer_application_id',
99
-                    esc_html__('Application ID', 'algolia-woo-indexer'),
100
-                    array( $algowooindexer, 'algolia_woo_indexer_application_id_output' ),
101
-                    'algolia_woo_indexer',
102
-                    'algolia_woo_indexer_main'
103
-                );
104
-                add_settings_field(
105
-                    'algolia_woo_indexer_admin_api_key',
106
-                    esc_html__('Admin API Key', 'algolia-woo-indexer'),
107
-                    array( $algowooindexer, 'algolia_woo_indexer_admin_api_key_output' ),
108
-                    'algolia_woo_indexer',
109
-                    'algolia_woo_indexer_main'
110
-                );
111
-                add_settings_field(
112
-                    'algolia_woo_indexer_index_name',
113
-                    esc_html__('Index name (will be created if not existing)', 'algolia-woo-indexer'),
114
-                    array( $algowooindexer, 'algolia_woo_indexer_index_name_output' ),
115
-                    'algolia_woo_indexer',
116
-                    'algolia_woo_indexer_main'
117
-                );
118
-                add_settings_field(
119
-                    'algolia_woo_indexer_automatically_send_new_products',
120
-                    esc_html__('Automatically index new products', 'algolia-woo-indexer'),
121
-                    array( $algowooindexer, 'algolia_woo_indexer_automatically_send_new_products_output' ),
122
-                    'algolia_woo_indexer',
123
-                    'algolia_woo_indexer_main'
124
-                );
125
-            }
126
-        }
127
-
128
-        /**
129
-         * Output for admin API key field
130
-         *
131
-         * @see https://developer.wordpress.org/reference/functions/wp_nonce_field/
132
-         *
133
-         * @return void
134
-         */
135
-        public static function algolia_woo_indexer_admin_api_key_output()
136
-        {
137
-            $api_key = get_option(ALGOWOO_DB_OPTION . ALGOLIA_API_KEY);
138
-            $api_key = is_string($api_key) ? $api_key : CHANGE_ME;
139
-
140
-            wp_nonce_field('algolia_woo_indexer_admin_api_nonce_action', 'algolia_woo_indexer_admin_api_nonce_name');
141
-
142
-            echo "<input id='algolia_woo_indexer_admin_api_key' name='algolia_woo_indexer_admin_api_key[key]'
30
+	/**
31
+	 * Algolia WooIndexer main class
32
+	 */
33
+	class Algolia_Woo_Indexer
34
+	{
35
+		const PLUGIN_NAME      = 'Algolia Woo Indexer';
36
+		const PLUGIN_TRANSIENT = 'algowoo-plugin-notice';
37
+
38
+		/**
39
+		 * Class instance
40
+		 *
41
+		 * @var object
42
+		 */
43
+		private static $instance;
44
+
45
+		/**
46
+		 * The plugin URL
47
+		 *
48
+		 * @var string
49
+		 */
50
+		private static $plugin_url = '';
51
+
52
+		/**
53
+		 * Class constructor
54
+		 *
55
+		 * @return void
56
+		 */
57
+		public function __construct()
58
+		{
59
+			$this->init();
60
+		}
61
+
62
+		/**
63
+		 * Setup sections and fields to store and retrieve values from Settings API
64
+		 *
65
+		 * @return void
66
+		 */
67
+		public static function setup_settings_sections()
68
+		{
69
+			/**
70
+			 * Setup arguments for settings sections and fields
71
+			 *
72
+			 * @see https://developer.wordpress.org/reference/functions/register_setting/
73
+			 */
74
+			if (is_admin()) {
75
+				$arguments = array(
76
+					'type'              => 'string',
77
+					'sanitize_callback' => 'settings_fields_validate_options',
78
+					'default'           => null,
79
+				);
80
+				register_setting('algolia_woo_options', 'algolia_woo_options', $arguments);
81
+
82
+				/**
83
+				 * Make sure we reference the instance of the current class by using self::get_instance()
84
+				 * This way we can setup the correct callback function for add_settings_section and add_settings_field
85
+				 */
86
+				$algowooindexer = self::get_instance();
87
+
88
+				/**
89
+				 * Add our necessary settings sections and fields
90
+				 */
91
+				add_settings_section(
92
+					'algolia_woo_indexer_main',
93
+					esc_html__('Algolia Woo Plugin Settings', 'algolia-woo-indexer'),
94
+					array( $algowooindexer, 'algolia_woo_indexer_section_text' ),
95
+					'algolia_woo_indexer'
96
+				);
97
+				add_settings_field(
98
+					'algolia_woo_indexer_application_id',
99
+					esc_html__('Application ID', 'algolia-woo-indexer'),
100
+					array( $algowooindexer, 'algolia_woo_indexer_application_id_output' ),
101
+					'algolia_woo_indexer',
102
+					'algolia_woo_indexer_main'
103
+				);
104
+				add_settings_field(
105
+					'algolia_woo_indexer_admin_api_key',
106
+					esc_html__('Admin API Key', 'algolia-woo-indexer'),
107
+					array( $algowooindexer, 'algolia_woo_indexer_admin_api_key_output' ),
108
+					'algolia_woo_indexer',
109
+					'algolia_woo_indexer_main'
110
+				);
111
+				add_settings_field(
112
+					'algolia_woo_indexer_index_name',
113
+					esc_html__('Index name (will be created if not existing)', 'algolia-woo-indexer'),
114
+					array( $algowooindexer, 'algolia_woo_indexer_index_name_output' ),
115
+					'algolia_woo_indexer',
116
+					'algolia_woo_indexer_main'
117
+				);
118
+				add_settings_field(
119
+					'algolia_woo_indexer_automatically_send_new_products',
120
+					esc_html__('Automatically index new products', 'algolia-woo-indexer'),
121
+					array( $algowooindexer, 'algolia_woo_indexer_automatically_send_new_products_output' ),
122
+					'algolia_woo_indexer',
123
+					'algolia_woo_indexer_main'
124
+				);
125
+			}
126
+		}
127
+
128
+		/**
129
+		 * Output for admin API key field
130
+		 *
131
+		 * @see https://developer.wordpress.org/reference/functions/wp_nonce_field/
132
+		 *
133
+		 * @return void
134
+		 */
135
+		public static function algolia_woo_indexer_admin_api_key_output()
136
+		{
137
+			$api_key = get_option(ALGOWOO_DB_OPTION . ALGOLIA_API_KEY);
138
+			$api_key = is_string($api_key) ? $api_key : CHANGE_ME;
139
+
140
+			wp_nonce_field('algolia_woo_indexer_admin_api_nonce_action', 'algolia_woo_indexer_admin_api_nonce_name');
141
+
142
+			echo "<input id='algolia_woo_indexer_admin_api_key' name='algolia_woo_indexer_admin_api_key[key]'
143 143
 				type='text' value='" . esc_attr($api_key) . "' />";
144
-        }
145
-
146
-        /**
147
-         * Output for application ID field
148
-         *
149
-         * @return void
150
-         */
151
-        public static function algolia_woo_indexer_application_id_output()
152
-        {
153
-            $application_id = get_option(ALGOWOO_DB_OPTION . ALGOLIA_APPLICATION_ID);
154
-            $application_id = is_string($application_id) ? $application_id : CHANGE_ME;
155
-
156
-            echo "<input id='algolia_woo_indexer_application_id' name='algolia_woo_indexer_application_id[id]'
144
+		}
145
+
146
+		/**
147
+		 * Output for application ID field
148
+		 *
149
+		 * @return void
150
+		 */
151
+		public static function algolia_woo_indexer_application_id_output()
152
+		{
153
+			$application_id = get_option(ALGOWOO_DB_OPTION . ALGOLIA_APPLICATION_ID);
154
+			$application_id = is_string($application_id) ? $application_id : CHANGE_ME;
155
+
156
+			echo "<input id='algolia_woo_indexer_application_id' name='algolia_woo_indexer_application_id[id]'
157 157
 				type='text' value='" . esc_attr($application_id) . "' />";
158
-        }
159
-
160
-        /**
161
-         * Output for index name field
162
-         *
163
-         * @return void
164
-         */
165
-        public static function algolia_woo_indexer_index_name_output()
166
-        {
167
-            $index_name = get_option(ALGOWOO_DB_OPTION . INDEX_NAME);
168
-            $index_name = is_string($index_name) ? $index_name : CHANGE_ME;
169
-
170
-            echo "<input id='algolia_woo_indexer_index_name' name='algolia_woo_indexer_index_name[name]'
158
+		}
159
+
160
+		/**
161
+		 * Output for index name field
162
+		 *
163
+		 * @return void
164
+		 */
165
+		public static function algolia_woo_indexer_index_name_output()
166
+		{
167
+			$index_name = get_option(ALGOWOO_DB_OPTION . INDEX_NAME);
168
+			$index_name = is_string($index_name) ? $index_name : CHANGE_ME;
169
+
170
+			echo "<input id='algolia_woo_indexer_index_name' name='algolia_woo_indexer_index_name[name]'
171 171
 				type='text' value='" . esc_attr($index_name) . "' />";
172
-        }
172
+		}
173 173
         
174
-        /**
175
-         * Output for checkbox to check if we automatically send new products to Algolia
176
-         *
177
-         * @return void
178
-         */
179
-        public static function algolia_woo_indexer_automatically_send_new_products_output()
180
-        {
181
-            /**
182
-             * Sanitization is not really needed as the variable is not directly echoed
183
-             * But I have still done it to be 100% safe
184
-             */
185
-            $automatically_send_new_products = get_option(ALGOWOO_DB_OPTION . AUTOMATICALLY_SEND_NEW_PRODUCTS);
186
-            $automatically_send_new_products = (! empty($automatically_send_new_products)) ? 1 : 0; ?>
174
+		/**
175
+		 * Output for checkbox to check if we automatically send new products to Algolia
176
+		 *
177
+		 * @return void
178
+		 */
179
+		public static function algolia_woo_indexer_automatically_send_new_products_output()
180
+		{
181
+			/**
182
+			 * Sanitization is not really needed as the variable is not directly echoed
183
+			 * But I have still done it to be 100% safe
184
+			 */
185
+			$automatically_send_new_products = get_option(ALGOWOO_DB_OPTION . AUTOMATICALLY_SEND_NEW_PRODUCTS);
186
+			$automatically_send_new_products = (! empty($automatically_send_new_products)) ? 1 : 0; ?>
187 187
 			<input id="algolia_woo_indexer_automatically_send_new_products" name="algolia_woo_indexer_automatically_send_new_products[checked]"
188 188
 			type="checkbox" <?php checked(1, $automatically_send_new_products); ?> />
189 189
 			<?php
190
-        }
191
-
192
-        /**
193
-         * Section text for plugin settings section text
194
-         *
195
-         * @return void
196
-         */
197
-        public static function algolia_woo_indexer_section_text()
198
-        {
199
-            echo esc_html__('Enter your settings here', 'algolia-woo-indexer');
200
-        }
201
-
202
-        /**
203
-         * Check if we are going to send products by verifying send products nonce
204
-         *
205
-         * @return void
206
-         */
207
-        public static function maybe_send_products()
208
-        {
209
-            if (true === Algolia_Verify_Nonces::verify_send_products_nonce()) {
210
-                Algolia_Send_Products::send_products_to_algolia();
211
-            }
212
-        }
213
-
214
-        /**
215
-         * Initialize class, setup settings sections and fields
216
-         *
217
-         * @return void
218
-         */
219
-        public static function init()
220
-        {
221
-
222
-            /**
223
-             * Fetch the option to see if we are going to automatically send new products
224
-             */
225
-            $automatically_send_new_products = get_option(ALGOWOO_DB_OPTION . AUTOMATICALLY_SEND_NEW_PRODUCTS);
226
-
227
-            /**
228
-             * Check that we have the minimum versions required and all of the required PHP extensions
229
-             */
230
-            Algolia_Check_Requirements::check_unmet_requirements();
231
-
232
-            if (! Algolia_Check_Requirements::algolia_wp_version_check() || ! Algolia_Check_Requirements::algolia_php_version_check()) {
233
-                add_action(
234
-                    'admin_notices',
235
-                    function () {
236
-                        echo '<div class="error notice">
190
+		}
191
+
192
+		/**
193
+		 * Section text for plugin settings section text
194
+		 *
195
+		 * @return void
196
+		 */
197
+		public static function algolia_woo_indexer_section_text()
198
+		{
199
+			echo esc_html__('Enter your settings here', 'algolia-woo-indexer');
200
+		}
201
+
202
+		/**
203
+		 * Check if we are going to send products by verifying send products nonce
204
+		 *
205
+		 * @return void
206
+		 */
207
+		public static function maybe_send_products()
208
+		{
209
+			if (true === Algolia_Verify_Nonces::verify_send_products_nonce()) {
210
+				Algolia_Send_Products::send_products_to_algolia();
211
+			}
212
+		}
213
+
214
+		/**
215
+		 * Initialize class, setup settings sections and fields
216
+		 *
217
+		 * @return void
218
+		 */
219
+		public static function init()
220
+		{
221
+
222
+			/**
223
+			 * Fetch the option to see if we are going to automatically send new products
224
+			 */
225
+			$automatically_send_new_products = get_option(ALGOWOO_DB_OPTION . AUTOMATICALLY_SEND_NEW_PRODUCTS);
226
+
227
+			/**
228
+			 * Check that we have the minimum versions required and all of the required PHP extensions
229
+			 */
230
+			Algolia_Check_Requirements::check_unmet_requirements();
231
+
232
+			if (! Algolia_Check_Requirements::algolia_wp_version_check() || ! Algolia_Check_Requirements::algolia_php_version_check()) {
233
+				add_action(
234
+					'admin_notices',
235
+					function () {
236
+						echo '<div class="error notice">
237 237
                                   <p>' . esc_html__('Please check the server requirements for Algolia Woo Indexer. <br/> It requires minimum PHP version 7.2 and WordPress version 5.0', 'algolia-woo-indexer') . '</p>
238 238
                                 </div>';
239
-                    }
240
-                );
241
-            }
242
-
243
-            $ob_class = get_called_class();
244
-
245
-            /**
246
-             * Setup translations
247
-             */
248
-            add_action('plugins_loaded', array( $ob_class, 'load_textdomain' ));
249
-
250
-            /**
251
-             * Add actions to setup admin menu
252
-             */
253
-            if (is_admin()) {
254
-                add_action('admin_menu', array( $ob_class, 'admin_menu' ));
255
-                add_action('admin_init', array( $ob_class, 'setup_settings_sections' ));
256
-                add_action('admin_init', array( $ob_class, 'update_settings_options' ));
257
-                add_action('admin_init', array( $ob_class, 'maybe_send_products' ));
258
-
259
-                /**
260
-                 * Register hook to automatically send new products if the option is set
261
-                 */
262
-
263
-                if ('1' === $automatically_send_new_products) {
264
-                    add_action('save_post', array( $ob_class, 'send_new_product_to_algolia' ), 10, 3);
265
-                }
266
-
267
-                self::$plugin_url = admin_url('options-general.php?page=algolia-woo-indexer-settings');
268
-
269
-                if (! is_plugin_active('woocommerce/woocommerce.php')) {
270
-                    add_action(
271
-                        'admin_notices',
272
-                        function () {
273
-                            echo '<div class="error notice">
239
+					}
240
+				);
241
+			}
242
+
243
+			$ob_class = get_called_class();
244
+
245
+			/**
246
+			 * Setup translations
247
+			 */
248
+			add_action('plugins_loaded', array( $ob_class, 'load_textdomain' ));
249
+
250
+			/**
251
+			 * Add actions to setup admin menu
252
+			 */
253
+			if (is_admin()) {
254
+				add_action('admin_menu', array( $ob_class, 'admin_menu' ));
255
+				add_action('admin_init', array( $ob_class, 'setup_settings_sections' ));
256
+				add_action('admin_init', array( $ob_class, 'update_settings_options' ));
257
+				add_action('admin_init', array( $ob_class, 'maybe_send_products' ));
258
+
259
+				/**
260
+				 * Register hook to automatically send new products if the option is set
261
+				 */
262
+
263
+				if ('1' === $automatically_send_new_products) {
264
+					add_action('save_post', array( $ob_class, 'send_new_product_to_algolia' ), 10, 3);
265
+				}
266
+
267
+				self::$plugin_url = admin_url('options-general.php?page=algolia-woo-indexer-settings');
268
+
269
+				if (! is_plugin_active('woocommerce/woocommerce.php')) {
270
+					add_action(
271
+						'admin_notices',
272
+						function () {
273
+							echo '<div class="error notice">
274 274
 								  <p>' . esc_html__('WooCommerce plugin must be enabled for Algolia Woo Indexer to work.', 'algolia-woo-indexer') . '</p>
275 275
 								</div>';
276
-                        }
277
-                    );
278
-                }
279
-            }
280
-        }
281
-
282
-        /**
283
-         * Send a single product to Algolia once a new product has been published
284
-         *
285
-         * @param int   $post_id ID of the product.
286
-         * @param array $post Post array.
287
-         *
288
-         * @return void
289
-         */
290
-        public static function send_new_product_to_algolia($post_id, $post)
291
-        {
292
-            if ('publish' !== $post->post_status || 'product' !== $post->post_type) {
293
-                return;
294
-            }
295
-            Algolia_Send_Products::send_products_to_algolia($post_id);
296
-        }
297
-
298
-        /**
299
-         * Verify nonces before we update options and settings
300
-         * Also retrieve the value from the send_products_to_algolia hidden field to check if we are sending products to Algolia
301
-         *
302
-         * @return void
303
-         */
304
-        public static function update_settings_options()
305
-        {
306
-            Algolia_Verify_Nonces::verify_settings_nonce();
307
-
308
-            /**
309
-             * Do not proceed if we are going to send products
310
-             */
311
-            if (true === Algolia_Verify_Nonces::verify_send_products_nonce()) {
312
-                return;
313
-            }
314
-
315
-            /**
316
-             * Filter the application id, api key, index name and verify that the input is an array
317
-             *
318
-             * @see https://www.php.net/manual/en/function.filter-input.php
319
-             */
320
-            $post_application_id             = filter_input(INPUT_POST, 'algolia_woo_indexer_application_id', FILTER_DEFAULT, FILTER_REQUIRE_ARRAY);
321
-            $post_api_key                    = filter_input(INPUT_POST, 'algolia_woo_indexer_admin_api_key', FILTER_DEFAULT, FILTER_REQUIRE_ARRAY);
322
-            $post_index_name                 = filter_input(INPUT_POST, 'algolia_woo_indexer_index_name', FILTER_DEFAULT, FILTER_REQUIRE_ARRAY);
323
-            $automatically_send_new_products = filter_input(INPUT_POST, 'algolia_woo_indexer_automatically_send_new_products', FILTER_DEFAULT, FILTER_REQUIRE_ARRAY);
324
-
325
-            /**
326
-             * Properly sanitize text fields before updating data
327
-             *
328
-             * @see https://developer.wordpress.org/reference/functions/sanitize_text_field/
329
-             */
330
-            $filtered_application_id = sanitize_text_field($post_application_id['id']);
331
-            $filtered_api_key        = sanitize_text_field($post_api_key['key']);
332
-            $filtered_index_name     = sanitize_text_field($post_index_name['name']);
333
-
334
-            /**
335
-             * Sanitizing by setting the value to either 1 or 0
336
-             */
337
-            $filtered_automatically_send_new_products = (! empty($automatically_send_new_products)) ? 1 : 0;
338
-
339
-            /**
340
-             * Values have been filtered and sanitized
341
-             * Check if set and not empty and update the database
342
-             *
343
-             * @see https://developer.wordpress.org/reference/functions/update_option/
344
-             */
345
-            if (isset($filtered_application_id) && (! empty($filtered_application_id))) {
346
-                update_option(
347
-                    ALGOWOO_DB_OPTION . ALGOLIA_APPLICATION_ID,
348
-                    $filtered_application_id
349
-                );
350
-            }
351
-
352
-            if (isset($filtered_api_key) && (! empty($filtered_api_key))) {
353
-                update_option(
354
-                    ALGOWOO_DB_OPTION . ALGOLIA_API_KEY,
355
-                    $filtered_api_key
356
-                );
357
-            }
358
-
359
-            if (isset($filtered_index_name) && (! empty($filtered_index_name))) {
360
-                update_option(
361
-                    ALGOWOO_DB_OPTION . INDEX_NAME,
362
-                    $filtered_index_name
363
-                );
364
-            }
365
-
366
-            if (isset($filtered_automatically_send_new_products) && (! empty($filtered_automatically_send_new_products))) {
367
-                update_option(
368
-                    ALGOWOO_DB_OPTION . AUTOMATICALLY_SEND_NEW_PRODUCTS,
369
-                    $filtered_automatically_send_new_products
370
-                );
371
-            }
372
-        }
373
-
374
-        /**
375
-         * Sanitize input in settings fields and filter through regex to accept only a-z and A-Z
376
-         *
377
-         * @param string $input Settings text data
378
-         * @return array
379
-         */
380
-        public static function settings_fields_validate_options($input)
381
-        {
382
-            $valid         = array();
383
-            $valid['name'] = preg_replace(
384
-                '/[^a-zA-Z\s]/',
385
-                '',
386
-                $input['name']
387
-            );
388
-            return $valid;
389
-        }
390
-
391
-        /**
392
-         * Load text domain for translations
393
-         *
394
-         * @return void
395
-         */
396
-        public static function load_textdomain()
397
-        {
398
-            load_plugin_textdomain('algolia-woo-indexer', false, basename(dirname(__FILE__)) . '/languages/');
399
-        }
400
-
401
-        /**
402
-         * Add the new menu to settings section so that we can configure the plugin
403
-         *
404
-         * @return void
405
-         */
406
-        public static function admin_menu()
407
-        {
408
-            add_submenu_page(
409
-                'options-general.php',
410
-                esc_html__('Algolia Woo Indexer Settings', 'algolia-woo-indexer'),
411
-                esc_html__('Algolia Woo Indexer Settings', 'algolia-woo-indexer'),
412
-                'manage_options',
413
-                'algolia-woo-indexer-settings',
414
-                array( get_called_class(), 'algolia_woo_indexer_settings' )
415
-            );
416
-        }
417
-
418
-        /**
419
-         * Display settings and allow user to modify them
420
-         *
421
-         * @return void
422
-         */
423
-        public static function algolia_woo_indexer_settings()
424
-        {
425
-            /**
426
-            * Verify that the user can access the settings page
427
-            */
428
-            if (! current_user_can('manage_options')) {
429
-                wp_die(esc_html__('Action not allowed.', 'algolia_woo_indexer_settings'));
430
-            } ?>
276
+						}
277
+					);
278
+				}
279
+			}
280
+		}
281
+
282
+		/**
283
+		 * Send a single product to Algolia once a new product has been published
284
+		 *
285
+		 * @param int   $post_id ID of the product.
286
+		 * @param array $post Post array.
287
+		 *
288
+		 * @return void
289
+		 */
290
+		public static function send_new_product_to_algolia($post_id, $post)
291
+		{
292
+			if ('publish' !== $post->post_status || 'product' !== $post->post_type) {
293
+				return;
294
+			}
295
+			Algolia_Send_Products::send_products_to_algolia($post_id);
296
+		}
297
+
298
+		/**
299
+		 * Verify nonces before we update options and settings
300
+		 * Also retrieve the value from the send_products_to_algolia hidden field to check if we are sending products to Algolia
301
+		 *
302
+		 * @return void
303
+		 */
304
+		public static function update_settings_options()
305
+		{
306
+			Algolia_Verify_Nonces::verify_settings_nonce();
307
+
308
+			/**
309
+			 * Do not proceed if we are going to send products
310
+			 */
311
+			if (true === Algolia_Verify_Nonces::verify_send_products_nonce()) {
312
+				return;
313
+			}
314
+
315
+			/**
316
+			 * Filter the application id, api key, index name and verify that the input is an array
317
+			 *
318
+			 * @see https://www.php.net/manual/en/function.filter-input.php
319
+			 */
320
+			$post_application_id             = filter_input(INPUT_POST, 'algolia_woo_indexer_application_id', FILTER_DEFAULT, FILTER_REQUIRE_ARRAY);
321
+			$post_api_key                    = filter_input(INPUT_POST, 'algolia_woo_indexer_admin_api_key', FILTER_DEFAULT, FILTER_REQUIRE_ARRAY);
322
+			$post_index_name                 = filter_input(INPUT_POST, 'algolia_woo_indexer_index_name', FILTER_DEFAULT, FILTER_REQUIRE_ARRAY);
323
+			$automatically_send_new_products = filter_input(INPUT_POST, 'algolia_woo_indexer_automatically_send_new_products', FILTER_DEFAULT, FILTER_REQUIRE_ARRAY);
324
+
325
+			/**
326
+			 * Properly sanitize text fields before updating data
327
+			 *
328
+			 * @see https://developer.wordpress.org/reference/functions/sanitize_text_field/
329
+			 */
330
+			$filtered_application_id = sanitize_text_field($post_application_id['id']);
331
+			$filtered_api_key        = sanitize_text_field($post_api_key['key']);
332
+			$filtered_index_name     = sanitize_text_field($post_index_name['name']);
333
+
334
+			/**
335
+			 * Sanitizing by setting the value to either 1 or 0
336
+			 */
337
+			$filtered_automatically_send_new_products = (! empty($automatically_send_new_products)) ? 1 : 0;
338
+
339
+			/**
340
+			 * Values have been filtered and sanitized
341
+			 * Check if set and not empty and update the database
342
+			 *
343
+			 * @see https://developer.wordpress.org/reference/functions/update_option/
344
+			 */
345
+			if (isset($filtered_application_id) && (! empty($filtered_application_id))) {
346
+				update_option(
347
+					ALGOWOO_DB_OPTION . ALGOLIA_APPLICATION_ID,
348
+					$filtered_application_id
349
+				);
350
+			}
351
+
352
+			if (isset($filtered_api_key) && (! empty($filtered_api_key))) {
353
+				update_option(
354
+					ALGOWOO_DB_OPTION . ALGOLIA_API_KEY,
355
+					$filtered_api_key
356
+				);
357
+			}
358
+
359
+			if (isset($filtered_index_name) && (! empty($filtered_index_name))) {
360
+				update_option(
361
+					ALGOWOO_DB_OPTION . INDEX_NAME,
362
+					$filtered_index_name
363
+				);
364
+			}
365
+
366
+			if (isset($filtered_automatically_send_new_products) && (! empty($filtered_automatically_send_new_products))) {
367
+				update_option(
368
+					ALGOWOO_DB_OPTION . AUTOMATICALLY_SEND_NEW_PRODUCTS,
369
+					$filtered_automatically_send_new_products
370
+				);
371
+			}
372
+		}
373
+
374
+		/**
375
+		 * Sanitize input in settings fields and filter through regex to accept only a-z and A-Z
376
+		 *
377
+		 * @param string $input Settings text data
378
+		 * @return array
379
+		 */
380
+		public static function settings_fields_validate_options($input)
381
+		{
382
+			$valid         = array();
383
+			$valid['name'] = preg_replace(
384
+				'/[^a-zA-Z\s]/',
385
+				'',
386
+				$input['name']
387
+			);
388
+			return $valid;
389
+		}
390
+
391
+		/**
392
+		 * Load text domain for translations
393
+		 *
394
+		 * @return void
395
+		 */
396
+		public static function load_textdomain()
397
+		{
398
+			load_plugin_textdomain('algolia-woo-indexer', false, basename(dirname(__FILE__)) . '/languages/');
399
+		}
400
+
401
+		/**
402
+		 * Add the new menu to settings section so that we can configure the plugin
403
+		 *
404
+		 * @return void
405
+		 */
406
+		public static function admin_menu()
407
+		{
408
+			add_submenu_page(
409
+				'options-general.php',
410
+				esc_html__('Algolia Woo Indexer Settings', 'algolia-woo-indexer'),
411
+				esc_html__('Algolia Woo Indexer Settings', 'algolia-woo-indexer'),
412
+				'manage_options',
413
+				'algolia-woo-indexer-settings',
414
+				array( get_called_class(), 'algolia_woo_indexer_settings' )
415
+			);
416
+		}
417
+
418
+		/**
419
+		 * Display settings and allow user to modify them
420
+		 *
421
+		 * @return void
422
+		 */
423
+		public static function algolia_woo_indexer_settings()
424
+		{
425
+			/**
426
+			 * Verify that the user can access the settings page
427
+			 */
428
+			if (! current_user_can('manage_options')) {
429
+				wp_die(esc_html__('Action not allowed.', 'algolia_woo_indexer_settings'));
430
+			} ?>
431 431
 			<div class="wrap">
432 432
 				<h1><?php esc_html__('Algolia Woo Indexer Settings', 'algolia-woo-indexer'); ?></h1>
433 433
 				<form action="<?php echo esc_url(self::$plugin_url); ?>" method="POST">
434 434
 			<?php
435
-            settings_fields('algolia_woo_options');
436
-            do_settings_sections('algolia_woo_indexer');
437
-            submit_button('', 'primary wide'); ?>
435
+			settings_fields('algolia_woo_options');
436
+			do_settings_sections('algolia_woo_indexer');
437
+			submit_button('', 'primary wide'); ?>
438 438
 				</form>
439 439
 				<form action="<?php echo esc_url(self::$plugin_url); ?>" method="POST">
440 440
 					<?php wp_nonce_field('send_products_to_algolia_nonce_action', 'send_products_to_algolia_nonce_name'); ?>
@@ -443,75 +443,75 @@  discard block
 block discarded – undo
443 443
 				</form>
444 444
 			</div>
445 445
 			<?php
446
-        }
447
-
448
-        /**
449
-         * Get active object instance
450
-         *
451
-         * @return object
452
-         */
453
-        public static function get_instance()
454
-        {
455
-            if (! self::$instance) {
456
-                self::$instance = new Algolia_Woo_Indexer();
457
-            }
458
-            return self::$instance;
459
-        }
460
-
461
-        /**
462
-         * The actions to execute when the plugin is activated.
463
-         *
464
-         * @return void
465
-         */
466
-        public static function activate_plugin()
467
-        {
468
-
469
-            /**
470
-             * Set default values for options if not already set
471
-             */
472
-            $automatically_send_new_products = get_option(ALGOWOO_DB_OPTION . AUTOMATICALLY_SEND_NEW_PRODUCTS);
473
-            $algolia_application_id          = get_option(ALGOWOO_DB_OPTION . ALGOLIA_APPLICATION_ID);
474
-            $algolia_api_key                 = get_option(ALGOWOO_DB_OPTION . ALGOLIA_API_KEY);
475
-            $algolia_index_name              = get_option(ALGOWOO_DB_OPTION . INDEX_NAME);
446
+		}
447
+
448
+		/**
449
+		 * Get active object instance
450
+		 *
451
+		 * @return object
452
+		 */
453
+		public static function get_instance()
454
+		{
455
+			if (! self::$instance) {
456
+				self::$instance = new Algolia_Woo_Indexer();
457
+			}
458
+			return self::$instance;
459
+		}
460
+
461
+		/**
462
+		 * The actions to execute when the plugin is activated.
463
+		 *
464
+		 * @return void
465
+		 */
466
+		public static function activate_plugin()
467
+		{
468
+
469
+			/**
470
+			 * Set default values for options if not already set
471
+			 */
472
+			$automatically_send_new_products = get_option(ALGOWOO_DB_OPTION . AUTOMATICALLY_SEND_NEW_PRODUCTS);
473
+			$algolia_application_id          = get_option(ALGOWOO_DB_OPTION . ALGOLIA_APPLICATION_ID);
474
+			$algolia_api_key                 = get_option(ALGOWOO_DB_OPTION . ALGOLIA_API_KEY);
475
+			$algolia_index_name              = get_option(ALGOWOO_DB_OPTION . INDEX_NAME);
476 476
             
477
-            if (empty($automatically_send_new_products)) {
478
-                add_option(
479
-                    ALGOWOO_DB_OPTION . AUTOMATICALLY_SEND_NEW_PRODUCTS,
480
-                    '0'
481
-                );
482
-            }
483
-
484
-            if (empty($algolia_application_id)) {
485
-                add_option(
486
-                    ALGOWOO_DB_OPTION . ALGOLIA_APPLICATION_ID,
487
-                    'Change me'
488
-                );
489
-            }
490
-
491
-            if (empty($algolia_api_key)) {
492
-                add_option(
493
-                    ALGOWOO_DB_OPTION . ALGOLIA_API_KEY,
494
-                    'Change me'
495
-                );
496
-            }
497
-
498
-            if (empty($algolia_index_name)) {
499
-                add_option(
500
-                    ALGOWOO_DB_OPTION . INDEX_NAME,
501
-                    'Change me'
502
-                );
503
-            }
504
-            set_transient(self::PLUGIN_TRANSIENT, true);
505
-        }
506
-
507
-        /**
508
-         * The actions to execute when the plugin is deactivated.
509
-         *
510
-         * @return void
511
-         */
512
-        public static function deactivate_plugin()
513
-        {
514
-            delete_transient(self::PLUGIN_TRANSIENT);
515
-        }
516
-    }
477
+			if (empty($automatically_send_new_products)) {
478
+				add_option(
479
+					ALGOWOO_DB_OPTION . AUTOMATICALLY_SEND_NEW_PRODUCTS,
480
+					'0'
481
+				);
482
+			}
483
+
484
+			if (empty($algolia_application_id)) {
485
+				add_option(
486
+					ALGOWOO_DB_OPTION . ALGOLIA_APPLICATION_ID,
487
+					'Change me'
488
+				);
489
+			}
490
+
491
+			if (empty($algolia_api_key)) {
492
+				add_option(
493
+					ALGOWOO_DB_OPTION . ALGOLIA_API_KEY,
494
+					'Change me'
495
+				);
496
+			}
497
+
498
+			if (empty($algolia_index_name)) {
499
+				add_option(
500
+					ALGOWOO_DB_OPTION . INDEX_NAME,
501
+					'Change me'
502
+				);
503
+			}
504
+			set_transient(self::PLUGIN_TRANSIENT, true);
505
+		}
506
+
507
+		/**
508
+		 * The actions to execute when the plugin is deactivated.
509
+		 *
510
+		 * @return void
511
+		 */
512
+		public static function deactivate_plugin()
513
+		{
514
+			delete_transient(self::PLUGIN_TRANSIENT);
515
+		}
516
+	}
517 517
 }
518 518
\ No newline at end of file
Please login to merge, or discard this patch.
classes/class-check-requirements.php 1 patch
Indentation   +55 added lines, -55 removed lines patch added patch discarded remove patch
@@ -18,28 +18,28 @@  discard block
 block discarded – undo
18 18
  * Abort if this file is called directly
19 19
  */
20 20
 if (! defined('ABSPATH')) {
21
-    exit;
21
+	exit;
22 22
 }
23 23
 
24 24
 if (! class_exists('Algolia_Check_Requirements')) {
25
-    /**
26
-     * Check requirements for Algolia plugin
27
-     */
28
-    class Algolia_Check_Requirements
29
-    {
25
+	/**
26
+	 * Check requirements for Algolia plugin
27
+	 */
28
+	class Algolia_Check_Requirements
29
+	{
30 30
 
31
-        /**
32
-         * Check for required PHP version.
33
-         *
34
-         * @return bool
35
-         */
36
-        public static function algolia_php_version_check()
37
-        {
38
-            if (version_compare(PHP_VERSION, ALGOLIA_MIN_PHP_VERSION, '<')) {
39
-                return false;
40
-            }
41
-            return true;
42
-        }
31
+		/**
32
+		 * Check for required PHP version.
33
+		 *
34
+		 * @return bool
35
+		 */
36
+		public static function algolia_php_version_check()
37
+		{
38
+			if (version_compare(PHP_VERSION, ALGOLIA_MIN_PHP_VERSION, '<')) {
39
+				return false;
40
+			}
41
+			return true;
42
+		}
43 43
 
44 44
 		/**
45 45
 		 * Check if values are empty and display error notice if not all values have been set
@@ -52,52 +52,52 @@  discard block
 block discarded – undo
52 52
 		public static function check_algolia_input_values($algolia_application_id, $algolia_api_key, $algolia_index_name )
53 53
 		{	
54 54
 			if (empty($algolia_application_id) || empty($algolia_api_key || empty($algolia_index_name))) {
55
-                add_action(
56
-                    'admin_notices',
57
-                    function () {
58
-                        echo '<div class="error notice">
55
+				add_action(
56
+					'admin_notices',
57
+					function () {
58
+						echo '<div class="error notice">
59 59
 							  <p>' . esc_html__('All settings need to be set for the plugin to work.', 'algolia-woo-indexer') . '</p>
60 60
 							</div>';
61
-                    }
62
-                );    
63
-            }
64
-        }
61
+					}
62
+				);    
63
+			}
64
+		}
65 65
 
66
-        /**
67
-         * Check for required WordPress version.
68
-         *
69
-         * @return bool
70
-         */
71
-        public static function algolia_wp_version_check()
72
-        {
73
-            if (version_compare($GLOBALS['wp_version'], ALGOLIA_MIN_WP_VERSION, '<')) {
74
-                return false;
75
-            }
76
-            return true;
77
-        }
66
+		/**
67
+		 * Check for required WordPress version.
68
+		 *
69
+		 * @return bool
70
+		 */
71
+		public static function algolia_wp_version_check()
72
+		{
73
+			if (version_compare($GLOBALS['wp_version'], ALGOLIA_MIN_WP_VERSION, '<')) {
74
+				return false;
75
+			}
76
+			return true;
77
+		}
78 78
 
79
-        /**
80
-         * Check that we have all of the required PHP extensions installed
81
-         *
82
-         * @return void
83
-         */
84
-        public static function check_unmet_requirements()
85
-        {
86
-            if (! extension_loaded('mbstring')) {
87
-                echo '<div class="error notice">
79
+		/**
80
+		 * Check that we have all of the required PHP extensions installed
81
+		 *
82
+		 * @return void
83
+		 */
84
+		public static function check_unmet_requirements()
85
+		{
86
+			if (! extension_loaded('mbstring')) {
87
+				echo '<div class="error notice">
88 88
 					  <p>' . esc_html__('Algolia Woo Indexer requires the "mbstring" PHP extension to be enabled. Please contact your hosting provider.', 'algolia-woo-indexer') . '</p>
89 89
 				  </div>';
90
-            } elseif (! function_exists('mb_ereg_replace')) {
91
-                echo '<div class="error notice">
90
+			} elseif (! function_exists('mb_ereg_replace')) {
91
+				echo '<div class="error notice">
92 92
 					  <p>' . esc_html__('Algolia Woo Indexer needs "mbregex" NOT to be disabled. Please contact your hosting provider.', 'algolia-woo-indexer') . '</p>
93 93
 				  </div>';
94
-            }
95
-            if (! extension_loaded('curl')) {
96
-                echo '<div class="error notice">
94
+			}
95
+			if (! extension_loaded('curl')) {
96
+				echo '<div class="error notice">
97 97
 					  <p>' . esc_html__('Algolia Woo Indexer requires the "cURL" PHP extension to be enabled. Please contact your hosting provider.', 'algolia-woo-indexer') . '</p>
98 98
 				  </div>';
99
-                return;
100
-            }
101
-        }
99
+				return;
100
+			}
101
+		}
102 102
 	}
103 103
 }
Please login to merge, or discard this patch.
classes/class-send-products.php 1 patch
Indentation   +168 added lines, -168 removed lines patch added patch discarded remove patch
@@ -15,14 +15,14 @@  discard block
 block discarded – undo
15 15
  * Abort if this file is called directly
16 16
  */
17 17
 if (!defined('ABSPATH')) {
18
-    exit;
18
+	exit;
19 19
 }
20 20
 
21 21
 /**
22 22
  * Include plugin file if function is_plugin_active does not exist
23 23
  */
24 24
 if (!function_exists('is_plugin_active')) {
25
-    require_once(ABSPATH . '/wp-admin/includes/plugin.php');
25
+	require_once(ABSPATH . '/wp-admin/includes/plugin.php');
26 26
 }
27 27
 
28 28
 /**
@@ -45,174 +45,174 @@  discard block
 block discarded – undo
45 45
 define('ALGOLIA_API_KEY', '_admin_api_key');
46 46
 
47 47
 if (!class_exists('Algolia_Send_Products')) {
48
-    /**
49
-     * Algolia WooIndexer main class
50
-     */
51
-    class Algolia_Send_Products
52
-    {
53
-        const PLUGIN_NAME      = 'Algolia Woo Indexer';
54
-        const PLUGIN_TRANSIENT = 'algowoo-plugin-notice';
55
-
56
-        /**
57
-         * The Algolia instance
58
-         *
59
-         * @var \Algolia\AlgoliaSearch\SearchClient
60
-         */
61
-        private static $algolia = null;
62
-
63
-        /**
64
-         * Check if we can connect to Algolia, if not, handle the exception, display an error and then return
65
-         */
66
-        public static function can_connect_to_algolia()
67
-        {
68
-            try {
69
-                self::$algolia->listApiKeys();
70
-            } catch (\Algolia\AlgoliaSearch\Exceptions\UnreachableException $error) {
71
-                add_action(
72
-                    'admin_notices',
73
-                    function () {
74
-                        echo '<div class="error notice">
48
+	/**
49
+	 * Algolia WooIndexer main class
50
+	 */
51
+	class Algolia_Send_Products
52
+	{
53
+		const PLUGIN_NAME      = 'Algolia Woo Indexer';
54
+		const PLUGIN_TRANSIENT = 'algowoo-plugin-notice';
55
+
56
+		/**
57
+		 * The Algolia instance
58
+		 *
59
+		 * @var \Algolia\AlgoliaSearch\SearchClient
60
+		 */
61
+		private static $algolia = null;
62
+
63
+		/**
64
+		 * Check if we can connect to Algolia, if not, handle the exception, display an error and then return
65
+		 */
66
+		public static function can_connect_to_algolia()
67
+		{
68
+			try {
69
+				self::$algolia->listApiKeys();
70
+			} catch (\Algolia\AlgoliaSearch\Exceptions\UnreachableException $error) {
71
+				add_action(
72
+					'admin_notices',
73
+					function () {
74
+						echo '<div class="error notice">
75 75
 							  <p>' . esc_html__('An error has been encountered. Please check your application ID and API key. ', 'algolia-woo-indexer') . '</p>
76 76
 							</div>';
77
-                    }
78
-                );
79
-                return;
80
-            }
81
-        }
82
-
83
-        /**
84
-         * Send WooCommerce products to Algolia
85
-         *
86
-         * @param Int $id Product to send to Algolia if we send only a single product
87
-         * @return void
88
-         */
89
-        public static function send_products_to_algolia($id = '')
90
-        {
91
-            /**
92
-             * Remove classes from plugin URL and autoload Algolia with Composer
93
-             */
94
-
95
-            $base_plugin_directory = str_replace('classes', '', dirname(__FILE__));
96
-            require_once $base_plugin_directory . '/vendor/autoload.php';
97
-
98
-            /**
99
-             * Fetch the required variables from the Settings API
100
-             */
101
-
102
-            $algolia_application_id = get_option(ALGOWOO_DB_OPTION . ALGOLIA_APPLICATION_ID);
103
-            $algolia_application_id = is_string($algolia_application_id) ? $algolia_application_id : CHANGE_ME;
104
-
105
-            $algolia_api_key        = get_option(ALGOWOO_DB_OPTION . ALGOLIA_API_KEY);
106
-            $algolia_api_key        = is_string($algolia_api_key) ? $algolia_api_key : CHANGE_ME;
107
-
108
-            $algolia_index_name     = get_option(ALGOWOO_DB_OPTION . INDEX_NAME);
109
-            $algolia_index_name        = is_string($algolia_index_name) ? $algolia_index_name : CHANGE_ME;
110
-
111
-            /**
112
-             * Display admin notice and return if not all values have been set
113
-             */
114
-
115
-            Algolia_Check_Requirements::check_algolia_input_values($algolia_application_id, $algolia_api_key, $algolia_index_name);
116
-
117
-            /**
118
-             * Initiate the Algolia client
119
-             */
120
-            self::$algolia = \Algolia\AlgoliaSearch\SearchClient::create($algolia_application_id, $algolia_api_key);
121
-
122
-            /**
123
-             * Check if we can connect, if not, handle the exception, display an error and then return
124
-             */
125
-            self::can_connect_to_algolia();
126
-
127
-            /**
128
-             * Initialize the search index and set the name to the option from the database
129
-             */
130
-            $index = self::$algolia->initIndex($algolia_index_name);
131
-
132
-            /**
133
-             * Setup arguments for sending all products to Algolia
134
-             *
135
-             * Limit => -1 means we send all products
136
-             */
137
-            $arguments = array(
138
-                'status'   => 'publish',
139
-                'limit'    => -1,
140
-                'paginate' => false,
141
-            );
142
-
143
-            /**
144
-             * Setup arguments for sending only a single product
145
-             */
146
-            if (isset($id) && '' !== $id) {
147
-                $arguments = array(
148
-                    'status'   => 'publish',
149
-                    'include'  => array($id),
150
-                    'paginate' => false,
151
-                );
152
-            }
153
-
154
-            /**
155
-             * Fetch all products from WooCommerce
156
-             *
157
-             * @see https://docs.woocommerce.com/wc-apidocs/function-wc_get_products.html
158
-             */
159
-            $products =
160
-                /** @scrutinizer ignore-call */
161
-                wc_get_products($arguments);
162
-
163
-            if (empty($products)) {
164
-                return;
165
-            }
166
-            $records = array();
167
-            $record  = array();
168
-
169
-            foreach ($products as $product) {
170
-                /**
171
-                 * Set sale price or regular price based on product type
172
-                 */
173
-                if ($product->is_type('simple')) {
174
-                    $sale_price     =  $product->get_sale_price();
175
-                    $regular_price  =  $product->get_regular_price();
176
-                } elseif ($product->is_type('variable')) {
177
-                    $sale_price     =  $product->get_variation_sale_price('min', true);
178
-                    $regular_price  =  $product->get_variation_regular_price('max', true);
179
-                }
180
-
181
-                /**
182
-                 * Extract image from $product->get_image()
183
-                 */
184
-                preg_match('/<img(.*)src(.*)=(.*)"(.*)"/U', $product->get_image(), $result);
185
-                $product_image = array_pop($result);
186
-                /**
187
-                 * Build the record array using the information from the WooCommerce product
188
-                 */
189
-                $record['objectID']                      = $product->get_id();
190
-                $record['product_name']                  = $product->get_name();
191
-                $record['product_image']                 = $product_image;
192
-                $record['short_description']             = $product->get_short_description();
193
-                $record['regular_price']                 = $regular_price;
194
-                $record['sale_price']                    = $sale_price;
195
-                $record['on_sale']                       = $product->is_on_sale();
196
-                $records[] = $record;
197
-            }
198
-            wp_reset_postdata();
199
-
200
-            /**
201
-             * Send the information to Algolia and save the result
202
-             * If result is NullResponse, print an error message
203
-             */
204
-            $result = $index->saveObjects($records);
205
-
206
-            if ('Algolia\AlgoliaSearch\Response\NullResponse' === get_class($result)) {
207
-                wp_die(esc_html__('No response from the server. Please check your settings and try again', 'algolia_woo_indexer_settings'));
208
-            }
209
-
210
-            /**
211
-             * Display success message
212
-             */
213
-            echo '<div class="notice notice-success is-dismissible">
77
+					}
78
+				);
79
+				return;
80
+			}
81
+		}
82
+
83
+		/**
84
+		 * Send WooCommerce products to Algolia
85
+		 *
86
+		 * @param Int $id Product to send to Algolia if we send only a single product
87
+		 * @return void
88
+		 */
89
+		public static function send_products_to_algolia($id = '')
90
+		{
91
+			/**
92
+			 * Remove classes from plugin URL and autoload Algolia with Composer
93
+			 */
94
+
95
+			$base_plugin_directory = str_replace('classes', '', dirname(__FILE__));
96
+			require_once $base_plugin_directory . '/vendor/autoload.php';
97
+
98
+			/**
99
+			 * Fetch the required variables from the Settings API
100
+			 */
101
+
102
+			$algolia_application_id = get_option(ALGOWOO_DB_OPTION . ALGOLIA_APPLICATION_ID);
103
+			$algolia_application_id = is_string($algolia_application_id) ? $algolia_application_id : CHANGE_ME;
104
+
105
+			$algolia_api_key        = get_option(ALGOWOO_DB_OPTION . ALGOLIA_API_KEY);
106
+			$algolia_api_key        = is_string($algolia_api_key) ? $algolia_api_key : CHANGE_ME;
107
+
108
+			$algolia_index_name     = get_option(ALGOWOO_DB_OPTION . INDEX_NAME);
109
+			$algolia_index_name        = is_string($algolia_index_name) ? $algolia_index_name : CHANGE_ME;
110
+
111
+			/**
112
+			 * Display admin notice and return if not all values have been set
113
+			 */
114
+
115
+			Algolia_Check_Requirements::check_algolia_input_values($algolia_application_id, $algolia_api_key, $algolia_index_name);
116
+
117
+			/**
118
+			 * Initiate the Algolia client
119
+			 */
120
+			self::$algolia = \Algolia\AlgoliaSearch\SearchClient::create($algolia_application_id, $algolia_api_key);
121
+
122
+			/**
123
+			 * Check if we can connect, if not, handle the exception, display an error and then return
124
+			 */
125
+			self::can_connect_to_algolia();
126
+
127
+			/**
128
+			 * Initialize the search index and set the name to the option from the database
129
+			 */
130
+			$index = self::$algolia->initIndex($algolia_index_name);
131
+
132
+			/**
133
+			 * Setup arguments for sending all products to Algolia
134
+			 *
135
+			 * Limit => -1 means we send all products
136
+			 */
137
+			$arguments = array(
138
+				'status'   => 'publish',
139
+				'limit'    => -1,
140
+				'paginate' => false,
141
+			);
142
+
143
+			/**
144
+			 * Setup arguments for sending only a single product
145
+			 */
146
+			if (isset($id) && '' !== $id) {
147
+				$arguments = array(
148
+					'status'   => 'publish',
149
+					'include'  => array($id),
150
+					'paginate' => false,
151
+				);
152
+			}
153
+
154
+			/**
155
+			 * Fetch all products from WooCommerce
156
+			 *
157
+			 * @see https://docs.woocommerce.com/wc-apidocs/function-wc_get_products.html
158
+			 */
159
+			$products =
160
+				/** @scrutinizer ignore-call */
161
+				wc_get_products($arguments);
162
+
163
+			if (empty($products)) {
164
+				return;
165
+			}
166
+			$records = array();
167
+			$record  = array();
168
+
169
+			foreach ($products as $product) {
170
+				/**
171
+				 * Set sale price or regular price based on product type
172
+				 */
173
+				if ($product->is_type('simple')) {
174
+					$sale_price     =  $product->get_sale_price();
175
+					$regular_price  =  $product->get_regular_price();
176
+				} elseif ($product->is_type('variable')) {
177
+					$sale_price     =  $product->get_variation_sale_price('min', true);
178
+					$regular_price  =  $product->get_variation_regular_price('max', true);
179
+				}
180
+
181
+				/**
182
+				 * Extract image from $product->get_image()
183
+				 */
184
+				preg_match('/<img(.*)src(.*)=(.*)"(.*)"/U', $product->get_image(), $result);
185
+				$product_image = array_pop($result);
186
+				/**
187
+				 * Build the record array using the information from the WooCommerce product
188
+				 */
189
+				$record['objectID']                      = $product->get_id();
190
+				$record['product_name']                  = $product->get_name();
191
+				$record['product_image']                 = $product_image;
192
+				$record['short_description']             = $product->get_short_description();
193
+				$record['regular_price']                 = $regular_price;
194
+				$record['sale_price']                    = $sale_price;
195
+				$record['on_sale']                       = $product->is_on_sale();
196
+				$records[] = $record;
197
+			}
198
+			wp_reset_postdata();
199
+
200
+			/**
201
+			 * Send the information to Algolia and save the result
202
+			 * If result is NullResponse, print an error message
203
+			 */
204
+			$result = $index->saveObjects($records);
205
+
206
+			if ('Algolia\AlgoliaSearch\Response\NullResponse' === get_class($result)) {
207
+				wp_die(esc_html__('No response from the server. Please check your settings and try again', 'algolia_woo_indexer_settings'));
208
+			}
209
+
210
+			/**
211
+			 * Display success message
212
+			 */
213
+			echo '<div class="notice notice-success is-dismissible">
214 214
 					 	<p>' . esc_html__('Product(s) sent to Algolia.', 'algolia-woo-indexer') . '</p>
215 215
 				  		</div>';
216
-        }
217
-    }
216
+		}
217
+	}
218 218
 }
Please login to merge, or discard this patch.