opentools-update-checker.php 9.86 KB
Newer Older
1
<?php
2 3 4 5 6 7 8
/**
 * OpenTools Plugin Update Checker Library
 * 
 * Copyright 2016 Reinhold Kainhofer
 * Extends the plugin-update-checker by Janis Elsts
 * Released under the MIT license. 
 */
9 10 11


// *****************************************************************
12
// * PLUGIN UPDATES (using plugin-update-checker and a self-written update server script)
13 14 15 16 17 18 19 20
// * http://w-shadow.com/blog/2010/09/02/automatic-updates-for-any-plugin/
// *****************************************************************

if (!class_exists('OpenToolsPluginUpdateChecker')):

require 'plugin-update-checker/plugin-update-checker.php';

class OpenToolsPluginUpdateChecker extends PluginUpdateChecker_2_1 {
21 22
	protected $credvars = array();
	protected $ajaxurl = '';
23 24 25 26 27
	public function __construct($metadataUrl, $pluginFile, $slug = '', $checkPeriod = 12, $optionName = '', $muPluginFile = '')
	{
		parent::__construct($metadataUrl, $pluginFile, $slug, $checkPeriod, $optionName, $muPluginFile);
		$this->installOTHooks();
	}
28 29
	public function declareCredentials($credential_def) {
		$this->credvars = $credential_def;
30 31 32
		// Append the update credentials to the update server link
		$this->addQueryArgFilter(array($this, 'appendQueryArgsCredentials'));
		
33
	}
34 35 36
	
	protected function installOTHooks() 
	{
37 38
		$this->ajaxurl = is_network_admin()?network_admin_url( 'admin-ajax.php' ): admin_url( 'admin-ajax.php' );
		
39 40 41
		add_action('admin_print_scripts-plugins.php', array($this, 'addCredentialCheckScripts'));
		add_action('admin_print_styles-plugins.php',  array($this, 'addCredentialCheckStyles'));

42 43 44
// 		add_filter('plugin_row_meta', array($this, 'displayUpdateCredentialsLink'), 9, 2);
		add_filter('plugin_action_links_'.$this->pluginFile, array($this, 'displayUpdateCredentialsLink'), 9, 2);

45 46
		add_action( 'wp_ajax_getUpdateCredentialsRow_'.$this->slug,		array( &$this, 'getUpdateCredentialsRow') );
		add_action( 'wp_ajax_submitUpdateCredentials_'.$this->slug,		array( &$this, 'submitUpdateCredentials') );
47 48 49 50 51
	}

	protected function getCredentials($slug) 
	{
		$credentials = array('validated' => FALSE);
52 53 54
		foreach ($this->credvars as $credkey => $credname) {
			$credentials[$credkey] = get_option('otup_credentials_'.$slug.'_'.$credkey);
		}
55 56 57 58
		$credentials['validated']    = get_option('otup_credentials_validated_'.$slug);
		return $credentials;
	}
	
59
	protected function setCredentials($slug, $credentials, $validated = false) 
60
	{
61 62 63
		foreach ($credentials as $credkey => $credvalue) {
			update_option('otup_credentials_'.$slug.'_'.$credkey, $credvalue, false);
		}
64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
		update_option('otup_credentials_validated_'.$slug,    $validated,   false);
	}


	public function addCredentialCheckScripts() {
		wp_register_script( 'opentools-updatecheck', plugins_url('assets/js/opentools-updatecheck.js', __FILE__), array('jquery'));
		wp_enqueue_script( 'opentools-updatecheck');
	}
	
	public function addCredentialCheckStyles() {
		wp_register_style( 'opentools-updatecheck', plugins_url('assets/css/opentools-updatecheck.css', __FILE__));
		wp_enqueue_style( 'opentools-updatecheck');
	}
	
	/** Append the ordernumber and order password to the update server URL 
	 */
	public function appendQueryArgsCredentials($queryArgs) {
		$credentials = $this->getCredentials($this->slug);
82 83
		foreach ($credentials as $credkey => $credvalue) {
			$queryArgs[$credkey] = $credvalue;
84 85 86 87 88 89 90 91 92 93 94 95 96 97 98
		}
		return $queryArgs;
	}

	/**
	 * Add a "Update Credentials" link to the plugin row in the "Plugins" page. By default,
	 * the new link will appear after the "Visit plugin site" link. 
	 *
	 * You can change the link text by using the "otup_enter_update_credentials-$slug" filter.
	 * Returning an empty string from the filter will disable the link.
	 *
	 * @param array $pluginMeta Array of meta links.
	 * @param string $pluginFile
	 * @return array
	 */
99
	public function displayUpdateCredentialsLink($links, $pluginFile) {
100 101
		$isRelevant = ($pluginFile == $this->pluginFile)
		              || (!empty($this->muPluginFile) && $pluginFile == $this->muPluginFile);
102
		$isRelevant = $isRelevant && !empty($this->credvars);
103 104

		if ( $isRelevant && current_user_can('update_plugins') ) {
105
			$credentials = $this->getCredentials($this->slug);
106 107
			$linkText = apply_filters('otup_enter_update_credentials-' . $this->slug, __('Update Credentials', 'oton-updates'));
			if ( !empty($linkText) ) {
108
				$iconyesno = $credentials['validated']?'yes':'no';
109
				$link = sprintf('<a href="#" onClick=\'return showUpdateCredentialsRow(this);\' class="dashicons-before dashicons-'.$iconyesno.' otup_credentials_link_'.$this->slug.'" data-slug="%s" data-nonce="%s" data-ajaxurl="%s" >%s</a>', esc_attr($this->slug), esc_attr(wp_create_nonce( 'otup_enter_update_credentials' )), esc_attr($this->ajaxurl), $linkText);
110
				array_unshift($links, $link);
111 112
			}
		}
113
		return $links;
114 115 116 117 118 119 120 121 122 123 124 125
	}
	
	
	/**
	* If the user has clicked on the "Update Credentials" link, display the input boxes after the plugin row.
	*
	* @param string $file
	* @param array  $plugin_data
	* @return false|void
	*/
	public function getUpdateCredentialsRow() {
		$json = array('row' => '', 'message'=>'Unsuccessful');
126 127 128 129
		if (isset($_REQUEST['slug']) && $_REQUEST['slug'] != $this->slug) {
			// This update checker is not responsible. Action is for another plugin
			return;
		}
130
		
131 132 133 134 135 136 137 138 139
 $json['showCredentials'] = $showCredentials;
 $json['issetSLUG'] = isset($_REQUEST['slug']);
 $json['SLUGmatches'] = $_REQUEST['slug'] == $this->slug;
 $json['userCanUpdatePlugins'] = current_user_can('update_plugins');
 $json['checkAjax'] = check_ajax_referer('otup_enter_update_credentials');
 $json['NotEmptyCredVars'] = !empty($this->credvars);

 $json['IsNetworkAdmin'] = is_network_admin();
 $json['isMultisite'] = is_multisite();
140 141 142
		$showCredentials = isset($_REQUEST['slug'])
			&& $_REQUEST['slug'] == $this->slug
			&& current_user_can('update_plugins')
143 144 145
			&& check_ajax_referer('otup_enter_update_credentials')
			&& !empty($this->credvars);
		
146 147 148 149 150 151 152 153 154 155
		if ( $showCredentials && (is_network_admin() || !is_multisite() )) {
			$slug = $this->slug;
			if ( is_network_admin() ) {
				$active_class = is_plugin_active_for_network( $this->pluginFile ) ? 'active': '';
			} else {
				$active_class = is_plugin_active( $this->pluginFile ) ? 'active' : '';
			}
			
			$current_credentials = $this->getCredentials($slug);
			
156
			$tr = '<tr class="' . $active_class . ' otup_update_credentials" id="' . esc_attr( $slug . '-credentials' ) . '" >';
157 158 159 160 161 162
			$tr .= '<th colspan="3" class="check-column colspanchange">';
			$tr .= '<div class="update-credentials">';
			$tr .= '<div class="update-credentials-message">';
			$tr .= '</div>';
			$tr .= '<div class="update-credentials-form">';
			
163 164 165 166 167 168 169 170 171 172
			foreach ($this->credvars as $credkey => $credname) {
				$tr .= $credname    . " <input type=\"text\" name=\"otup_update_credentials[$slug][$credkey]\" value=\"" . esc_attr($current_credentials[$credkey]) . "\">&nbsp;&nbsp;&nbsp;";
			}

			$tr .= sprintf('<input type="submit" class="button otup_update_credentials_submit" onclick="return submitUpdateCredentials(this);" data-slug="%s" data-nonce="%s" data-ajaxurl="%s" data-credentialvars=\'%s\'>',
				esc_attr($this->slug),
				esc_attr(wp_create_nonce( 'otup_enter_update_credentials_'.$slug )),
				esc_attr($this->ajaxurl),
				esc_attr(json_encode(array_keys($this->credvars)))
			);
173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190

			$tr .= '</div>';
			$tr .= '</div></th></tr>';
			$json['row'] = $tr;
			$json['message'] = '';
		} else {
			$json['message'] = __("No permissions to modify update credentials", "opentools-updatecheck");
		}
		wp_send_json($json);
	}


	/**
	 * Check the submitted update credentials for correctness and save them
	 *
	 * @return void
	 */
	public function submitUpdateCredentials() {
191 192 193 194 195
		if (isset($_REQUEST['slug']) && $_REQUEST['slug'] != $this->slug) {
			// This update checker is not responsible. Action is for another plugin
			return;
		}
		
196 197
		$json = array('message' => '', 'success' => FALSE);
		$slug = isset($_REQUEST['slug'])?($_REQUEST['slug']):"INVALIDSLUG";
198 199

		$submitCredentials = ($slug == $this->slug)
200 201
			&& current_user_can('update_plugins')
			&& check_ajax_referer('otup_enter_update_credentials_'.$slug);
202
		$submitCredentials = $submitCredentials && !empty($this->credvars);
203 204

		if ( $submitCredentials ) {
205 206 207 208 209 210
			$credentials = array();
			foreach ($this->credvars as $credkey=>$credname) {
				if (isset($_REQUEST[$credkey])) {
					$credentials[$credkey] = $_REQUEST[$credkey];
				}
			}
211 212
			
			$message = "";
213 214
			$validated = $this->checkUpdateCredentials($credentials, $message);
			$this->setCredentials($this->slug, $credentials, $validated);
215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234
			
			$json['success'] = $validated;
			
			if ($validated) {
				if ( is_network_admin() ) {
					$active_class = is_plugin_active_for_network( $this->pluginFile ) ? 'active': '';
				} else {
					$active_class = is_plugin_active( $this->pluginFile ) ? 'active' : '';
				}

				$json['message'] .= __("Update credentials successfully validated and saved. Automatic updates will be provided.", "opentools-updatecheck");
			} else {
				$json['message'] = $message;
			}
		} else {
			$json['message'] = __("No permissions to modify update credentials", "opentools-updatecheck");
		}
		wp_send_json($json);
	}

235
	public function checkUpdateCredentials($credentials, &$message)
236
	{
237
		$this->setCredentials($this->slug, $credentials);
238 239 240 241
		$success = FALSE;
		$updateinfo = $this->requestInfo(array());
		if ($updateinfo && isset($updateinfo->download_url)) {
			$downloadurl = $updateinfo->download_url;
242
			$downloadurl = apply_filters('puc_check_download_query_args-'.$this->slug, $downloadurl);
243 244 245 246 247 248 249 250 251 252 253 254
		
			$headers = get_headers($downloadurl);
			list($version, $status_code, $msg) = explode(' ',$headers[0], 3);
		
			// Check the HTTP Status code
			$message = $msg;
			$success = ($status_code==200);
		} else {
			$message = __('Unable to access plugin download URL. Please check your credentials.');
		}
		return $success;
	}
255 256 257 258
	
	public function addAccessCheckQueryArgFilter($callback){
		add_filter('puc_check_download_query_args-'.$this->slug, $callback);
	}
259 260 261 262 263 264 265 266

};

endif;



// *****************************************************************