Completed
Push — 161-improved-credential-encryp... ( fc3bb4 )
by Armando
01:57
created

WP_To_Diaspora::admin_notices()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 17
rs 9.7
c 0
b 0
f 0
cc 3
nc 3
nop 0
1
<?php
2
/**
3
 * Plugin Name:       WP to diaspora*
4
 * Plugin URI:        https://github.com/DiasPHPora/wp-to-diaspora
5
 * Description:       Automatically shares WordPress posts on diaspora*
6
 * Version:           2.1.0
7
 * Author:            Augusto Bennemann, Armando Lüscher
8
 * Author URI:        https://github.com/DiasPHPora
9
 * License:           GPLv2 or later
10
 * License URI:       https://www.gnu.org/licenses/gpl-2.0.html
11
 * Text Domain:       wp-to-diaspora
12
 * Domain Path:       /languages
13
 * GitHub Plugin URI: DiasPHPora/wp-to-diaspora
14
 * GitHub Branch:     master
15
 *
16
 * Copyright 2014-2017 Augusto Bennemann (email: gutobenn at gmail.com)
17
 *
18
 * This program is free software; you can redistribute it and/or modify it under the terms of the GNU
19
 * General Public License as published by the Free Software Foundation; either version 2 of the License,
20
 * or (at your option) any later version.
21
 *
22
 * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
23
 * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
24
 *
25
 * You should have received a copy of the GNU General Public License along with this program; if not, write
26
 * to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
27
 *
28
 * @package   WP_To_Diaspora
29
 * @version   2.1.0
30
 * @author    Augusto Bennemann <[email protected]>
31
 * @copyright Copyright (c) 2017, Augusto Bennemann
32
 * @link      https://github.com/DiasPHPora/wp-to-diaspora
33
 * @license   https://www.gnu.org/licenses/old-licenses/gpl-2.0.html
34
 */
35
36
// Exit if accessed directly.
37
defined( 'ABSPATH' ) || exit;
38
39
// Set the current version.
40
define( 'WP2D_VERSION', '2.1.0' );
41
42
/**
43
 * WP to diaspora* main plugin class.
44
 */
45
class WP_To_Diaspora {
46
47
	/**
48
	 * Only instance of this class.
49
	 *
50
	 * @var WP_To_Diaspora
51
	 */
52
	private static $_instance;
53
54
	/**
55
	 * The minimum required WordPress version.
56
	 *
57
	 * @since 1.5.4
58
	 *
59
	 * @var string
60
	 */
61
	private $_min_wp = '3.9.2-src';
62
63
	/**
64
	 * The minimum required PHP version.
65
	 *
66
	 * @since 1.5.4
67
	 *
68
	 * @var string
69
	 */
70
	private $_min_php = '5.4';
71
72
	/**
73
	 * Instance of the API class.
74
	 *
75
	 * @var WP2D_API
76
	 */
77
	private $_api;
78
79
	/**
80
	 * Create / Get the instance of this class.
81
	 *
82
	 * @return WP_To_Diaspora Instance of this class.
83
	 */
84
	public static function instance() {
85
		if ( null === self::$_instance ) {
86
			self::$_instance = new self();
87
			if ( self::$_instance->_version_check() ) {
88
				self::$_instance->_constants();
89
				self::$_instance->_includes();
90
				self::$_instance->_setup();
91
			} else {
92
				self::$_instance = null;
93
			}
94
		}
95
96
		return self::$_instance;
97
	}
98
99
	/**
100
	 * Define all the required constants.
101
	 *
102
	 * @since 1.5.0
103
	 */
104
	private function _constants() {
105
		// Are we in debugging mode?
106
		if ( isset( $_GET['debugging'] ) ) {
107
			define( 'WP2D_DEBUGGING', true );
108
		}
109
110
		define( 'WP2D_DIR', __DIR__ );
111
		define( 'WP2D_LIB_DIR', WP2D_DIR . '/lib' );
112
		define( 'WP2D_VENDOR_DIR', WP2D_DIR . '/vendor' );
113
114
		// Fall back to WordPress AUTH_KEY for password encryption.
115
		defined( 'WP2D_ENC_KEY' ) || define( 'WP2D_ENC_KEY', AUTH_KEY );
116
	}
117
118
	/**
119
	 * Check the minimum WordPress and PHP requirements.
120
	 *
121
	 * @since 1.5.4
122
	 *
123
	 * @return bool If version requirements are met.
124
	 */
125
	private function _version_check() {
0 ignored issues
show
Coding Style introduced by
_version_check uses the super-global variable $GLOBALS which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
126
		// Check for version requirements.
127
		if ( version_compare( PHP_VERSION, $this->_min_php, '<' ) || version_compare( $GLOBALS['wp_version'], $this->_min_wp, '<' ) ) {
128
			add_action( 'admin_notices', [ $this, 'deactivate' ] );
129
130
			return false;
131
		}
132
133
		return true;
134
	}
135
136
	/**
137
	 * Callback to deactivate plugin and display admin notice.
138
	 *
139
	 * @since 1.5.4
140
	 */
141
	public function deactivate() {
0 ignored issues
show
Coding Style introduced by
deactivate uses the super-global variable $GLOBALS which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
142
		// First of all, deactivate the plugin.
143
		deactivate_plugins( plugin_basename( __FILE__ ) );
144
145
		// Get rid of the "Plugin activated" message.
146
		unset( $_GET['activate'] );
147
148
		// Then display the admin notice.
149
		?>
150
		<div class="error">
151
			<p><?php echo esc_html( sprintf( 'WP to diaspora* requires at least WordPress %1$s (you have %2$s) and PHP %3$s (you have %4$s)!', $this->_min_wp, $GLOBALS['wp_version'], $this->_min_php, PHP_VERSION ) ); ?></p>
152
		</div>
153
		<?php
154
	}
155
156
	/**
157
	 * Include all the required files.
158
	 *
159
	 * @since 1.5.0
160
	 */
161
	private function _includes() {
162
		require_once WP2D_VENDOR_DIR . '/autoload.php';
163
		require_once WP2D_LIB_DIR . '/class-api.php';
164
		require_once WP2D_LIB_DIR . '/class-contextual-help.php';
165
		require_once WP2D_LIB_DIR . '/class-helpers.php';
166
		require_once WP2D_LIB_DIR . '/class-options.php';
167
		require_once WP2D_LIB_DIR . '/class-post.php';
168
	}
169
170
	/**
171
	 * Set up the plugin.
172
	 */
173
	private function _setup() {
174
175
		// Load languages.
176
		add_action( 'plugins_loaded', [ $this, 'l10n' ] );
177
178
		// Add "Settings" link to plugin page.
179
		add_filter( 'plugin_action_links_' . plugin_basename( __FILE__ ), [ $this, 'settings_link' ] );
180
181
		// Perform any necessary data upgrades.
182
		add_action( 'admin_init', [ $this, 'upgrade' ] );
183
184
		// Admin notice when the AUTH_KEY has changed and credentials need to be re-saved.
185
		add_action( 'admin_notices', [ $this, 'admin_notices' ] );
186
187
		// Enqueue CSS and JS scripts.
188
		add_action( 'admin_enqueue_scripts', [ $this, 'admin_load_scripts' ] );
189
190
		// Set up the options.
191
		add_action( 'init', [ 'WP2D_Options', 'instance' ] );
192
193
		// WP2D Post.
194
		add_action( 'init', [ 'WP2D_Post', 'setup' ] );
195
196
		// AJAX actions for loading aspects and services.
197
		add_action( 'wp_ajax_wp_to_diaspora_update_aspects_list', [ $this, 'update_aspects_list_callback' ] );
198
		add_action( 'wp_ajax_wp_to_diaspora_update_services_list', [ $this, 'update_services_list_callback' ] );
199
200
		// Check the pod connection status on the options page.
201
		add_action( 'wp_ajax_wp_to_diaspora_check_pod_connection_status', [ $this, 'check_pod_connection_status_callback' ] );
202
	}
203
204
	/**
205
	 * Load the diaspora* API for ease of use.
206
	 *
207
	 * @return WP2D_API The API object.
208
	 */
209
	private function _load_api() {
210
		if ( null === $this->_api ) {
211
			$this->_api = WP2D_Helpers::api_quick_connect();
212
		}
213
214
		return $this->_api;
215
	}
216
217
	/**
218
	 * Initialise upgrade sequence.
219
	 */
220
	public function upgrade() {
221
		// Get the current options, or assign defaults.
222
		$options = WP2D_Options::instance();
223
		$version = $options->get_option( 'version' );
224
225
		// If the versions differ, this is probably an update. Need to save updated options.
226
		if ( WP2D_VERSION !== $version ) {
227
228
			// Password is stored encrypted since version 1.2.7.
229
			// When upgrading to it, the plain text password is encrypted and saved again.
230
			if ( version_compare( $version, '1.2.7', '<' ) ) {
231
				$options->set_option( 'password', WP2D_Helpers::encrypt( (string) $options->get_option( 'password' ) ) );
232
			}
233
234
			if ( version_compare( $version, '1.3.0', '<' ) ) {
235
				// The 'user' setting is renamed to 'username'.
236
				$options->set_option( 'username', $options->get_option( 'user' ) );
237
				$options->set_option( 'user', null );
238
239
				// Save tags as arrays instead of comma seperated values.
240
				$global_tags = $options->get_option( 'global_tags' );
241
				$options->set_option( 'global_tags', $options->validate_tags( $global_tags ) );
242
			}
243
244
			if ( version_compare( $version, '1.4.0', '<' ) ) {
245
				// Turn tags_to_post string into an array.
246
				$tags_to_post_old = $options->get_option( 'tags_to_post' );
247
				$tags_to_post     = array_filter( [
248
					( false !== strpos( $tags_to_post_old, 'g' ) ) ? 'global' : null,
249
					( false !== strpos( $tags_to_post_old, 'c' ) ) ? 'custom' : null,
250
					( false !== strpos( $tags_to_post_old, 'p' ) ) ? 'post' : null,
251
				] );
252
				$options->set_option( 'tags_to_post', $tags_to_post );
253
			}
254
255
			// Encryption key is set in WP2D_ENC_KEY since version 2.2.0.
256
			if ( version_compare( $version, '2.2.0', '<' ) ) {
257
				// Remember AUTH_KEY hash to notice a change.
258
				$options->set_option( 'auth_key_hash', md5( AUTH_KEY ) );
259
260
				// Upgrade encrypted password if new WP2D_ENC_KEY is used.
261
				$options->attempt_password_upgrade();
262
			}
263
264
			// Update version.
265
			$options->set_option( 'version', WP2D_VERSION );
266
			$options->save();
267
		}
268
	}
269
270
	/**
271
	 * Set up i18n.
272
	 */
273
	public function l10n() {
274
		load_plugin_textdomain( 'wp-to-diaspora', false, 'wp-to-diaspora/languages' );
275
	}
276
277
	/**
278
	 * Load scripts and styles for Settings and Post pages of allowed post types.
279
	 */
280
	public function admin_load_scripts() {
281
		// Get the enabled post types to load the script for.
282
		$enabled_post_types = WP2D_Options::instance()->get_option( 'enabled_post_types', [] );
283
284
		// Get the screen to find out where we are.
285
		$screen = get_current_screen();
286
287
		// Only load the styles and scripts on the settings page and the allowed post types.
288
		if ( 'settings_page_wp_to_diaspora' === $screen->id || ( in_array( $screen->post_type, $enabled_post_types, true ) && 'post' === $screen->base ) ) {
289
			wp_enqueue_style( 'tag-it', plugins_url( '/css/jquery.tagit.css', __FILE__ ) );
290
			wp_enqueue_style( 'chosen', plugins_url( '/css/chosen.min.css', __FILE__ ) );
291
			wp_enqueue_style( 'wp-to-diaspora-admin', plugins_url( '/css/wp-to-diaspora.css', __FILE__ ) );
292
			wp_enqueue_script( 'chosen', plugins_url( '/js/chosen.jquery.min.js', __FILE__ ), [ 'jquery' ], false, true );
293
			wp_enqueue_script( 'tag-it', plugins_url( '/js/tag-it.min.js', __FILE__ ), [ 'jquery', 'jquery-ui-autocomplete' ], false, true );
294
			wp_enqueue_script( 'wp-to-diaspora-admin', plugins_url( '/js/wp-to-diaspora.js', __FILE__ ), [ 'jquery' ], false, true );
295
			// Javascript-specific l10n.
296
			wp_localize_script( 'wp-to-diaspora-admin', 'WP2DL10n', [
297
				'resave_credentials'    => __( 'Resave your credentials and try again.', 'wp-to-diaspora' ),
298
				'no_services_connected' => __( 'No services connected yet.', 'wp-to-diaspora' ),
299
				'sure_reset_defaults'   => __( 'Are you sure you want to reset to default values?', 'wp-to-diaspora' ),
300
				'conn_testing'          => __( 'Testing connection...', 'wp-to-diaspora' ),
301
				'conn_successful'       => __( 'Connection successful.', 'wp-to-diaspora' ),
302
				'conn_failed'           => __( 'Connection failed.', 'wp-to-diaspora' ),
303
			] );
304
		}
305
	}
306
307
	/**
308
	 * Add "AUTH_KEY" changed admin notice.
309
	 *
310
	 * @since 2.2.0
311
	 */
312
	public function admin_notices() {
313
		// If a custom WP2D_ENC_KEY is set, it doesn't matter if the AUTH_KEY has changed.
314
		if ( AUTH_KEY !== WP2D_ENC_KEY ) {
315
			return;
316
		}
317
318
		$options = WP2D_Options::instance();
319
		if ( md5( AUTH_KEY ) !== $options->get_option( 'auth_key_hash' ) ) {
320
			printf( '<div class="error notice is-dismissible"><p>%1$s</p></div>',
321
				sprintf(
322
					esc_html_x( 'Looks like your WordPress secret keys have changed! Please %sre-save your login info%s.', 'placeholders are link tags to the settings page.', 'wp-to-diaspora' ),
323
					'<a href="' . admin_url( 'options-general.php?page=wp_to_diaspora' ) . '&amp;tab=setup" target="_blank">',
324
					'</a>'
325
				)
326
			);
327
		}
328
	}
329
330
	/**
331
	 * Add the "Settings" link to the plugins page.
332
	 *
333
	 * @param array $links Links to display for plugin on plugins page.
334
	 *
335
	 * @return array Links to display for plugin on plugins page.
336
	 */
337
	public function settings_link( $links ) {
338
		$links[] = '<a href="' . admin_url( 'options-general.php?page=wp_to_diaspora' ) . '">' . __( 'Settings' ) . '</a>';
339
340
		return $links;
341
	}
342
343
	/**
344
	 * Fetch the list of aspects or services and save them to the settings.
345
	 *
346
	 * NOTE: When updating the lists, always force a fresh fetch.
347
	 *
348
	 * @param string $type Type of list to update.
349
	 *
350
	 * @return array|bool The list of aspects or services, false if an illegal parameter is passed.
351
	 */
352
	private function _update_aspects_services_list( $type ) {
353
		// Check for correct argument value.
354
		if ( ! in_array( $type, [ 'aspects', 'services' ], true ) ) {
355
			return false;
356
		}
357
358
		$options = WP2D_Options::instance();
359
		$list    = $options->get_option( $type . '_list' );
360
361
		// Make sure that we have at least the 'Public' aspect.
362
		if ( 'aspects' === $type && empty( $list ) ) {
363
			$list = [ 'public' => __( 'Public' ) ];
364
		}
365
366
		// Set up the connection to diaspora*.
367
		$api = $this->_load_api();
368
369
		// If there was a problem loading the API, return false.
370
		if ( $api->has_last_error() ) {
371
			return false;
372
		}
373
374
		$list_new = $list;
375
		if ( 'aspects' === $type ) {
376
			$list_new = $api->get_aspects( true );
377
		} elseif ( 'services' === $type ) {
378
			$list_new = $api->get_services( true );
379
		}
380
381
		// If the new list couldn't be fetched successfully, return false.
382
		if ( $api->has_last_error() ) {
383
			return false;
384
		}
385
386
		// We have a new list to save and return!
387
		$options->set_option( $type . '_list', $list_new );
388
		$options->save();
389
390
		return $list_new;
391
	}
392
393
	/**
394
	 * Update the list of aspects and return them for use with AJAX.
395
	 */
396
	public function update_aspects_list_callback() {
397
		wp_send_json( $this->_update_aspects_services_list( 'aspects' ) );
398
	}
399
400
	/**
401
	 * Update the list of services and return them for use with AJAX.
402
	 */
403
	public function update_services_list_callback() {
404
		wp_send_json( $this->_update_aspects_services_list( 'services' ) );
405
	}
406
407
	/**
408
	 * Check the pod connection status.
409
	 *
410
	 * @return bool The status of the connection.
411
	 */
412
	private function _check_pod_connection_status() {
413
		$options = WP2D_Options::instance();
414
415
		$status = null;
416
417
		if ( $options->is_pod_set_up() ) {
418
			$status = ! $this->_load_api()->has_last_error();
419
		}
420
421
		return $status;
422
	}
423
424
	/**
425
	 * Check the connection to the pod and return the status for use with AJAX.
426
	 *
427
	 * @todo esc_html
428
	 */
429
	public function check_pod_connection_status_callback() {
0 ignored issues
show
Coding Style introduced by
check_pod_connection_status_callback uses the super-global variable $_REQUEST which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
430
		if ( ! defined( 'WP2D_DEBUGGING' ) && isset( $_REQUEST['debugging'] ) ) {
431
			define( 'WP2D_DEBUGGING', true );
432
		}
433
434
		$status = $this->_check_pod_connection_status();
435
436
		$data = [
437
			'debug'   => esc_textarea( WP2D_Helpers::get_debugging() ),
438
			'message' => __( 'Connection successful.', 'wp-to-diaspora' ),
439
		];
440
441
		if ( true === $status ) {
442
			wp_send_json_success( $data );
443
		} elseif ( false === $status && $this->_load_api()->has_last_error() ) {
444
			$data['message'] = $this->_load_api()->get_last_error() . ' ' . WP2D_Contextual_Help::get_help_tab_quick_link( $this->_load_api()->get_last_error_object() );
0 ignored issues
show
Bug introduced by
It seems like $this->_load_api()->get_last_error_object() can be null; however, get_help_tab_quick_link() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
445
			wp_send_json_error( $data );
446
		}
447
		// If $status === null, do nothing.
0 ignored issues
show
Unused Code Comprehensibility introduced by
36% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
448
	}
449
}
450
451
// Get the party started!
452
WP_To_Diaspora::instance();
453