Completed
Push — add/install-theme-api-endpoint ( e754d2 )
by
unknown
195:58 queued 187:50
created

validate_input()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 3
nc 1
nop 1
dl 0
loc 4
rs 10
c 0
b 0
f 0
1
<?php
2
3
include_once ABSPATH . 'wp-admin/includes/class-wp-upgrader.php';
4
include_once ABSPATH . 'wp-admin/includes/file.php';
5
6
class Jetpack_JSON_API_Themes_New_Endpoint extends Jetpack_JSON_API_Themes_Endpoint {
7
8
	// POST  /sites/%s/themes/%s/install
9
	protected $needed_capabilities = 'install_themes';
10
	protected $action              = 'install';
11
	protected $download_links      = array();
12
13
	protected function validate_call( $_blog_id, $capability, $check_manage_active = true ) {
14
		$validate = parent::validate_call( $_blog_id, $capability, $check_manage_active );
15
		if ( is_wp_error( $validate ) ) {
16
			// Lets delete the attachment... if the user doesn't have the right permissions to do things.
17
			$args = $this->input();
18
			if ( isset( $args['zip'][0]['id'] ) ) {
19
				wp_delete_attachment( $args['zip'][0]['id'], true );
20
			}
21
		}
22
23
		return $validate;
24
	}
25
26
	protected function validate_input( $theme ) {
27
		$this->bulk    = false;
28
		$this->themes = array();
29
	}
30
31
	function install() {
32
		$args = $this->input();
33
34
		if ( isset( $args['zip'][0]['id'] ) ) {
35
			$attachment_id = $args['zip'][0]['id'];
36
			$local_file           = get_attached_file( $attachment_id );
37
			if ( ! $local_file ) {
38
				return new WP_Error( 'local-file-does-not-exist' );
39
			}
40
			$skin      = new Jetpack_Automatic_Install_Skin();
41
			$upgrader  = new Theme_Upgrader( $skin );
42
43
			$pre_install_list = wp_get_themes();
44
			$result           = $upgrader->install( $local_file );
45
46
			// clean up.
47
			wp_delete_attachment( $attachment_id, true );
48
49
			if ( is_wp_error( $result ) ) {
50
				return $result;
51
			}
52
53
			$after_install_list = wp_get_themes();
54
			$plugin             = array_values( array_diff( array_keys( $after_install_list ), array_keys( $pre_install_list ) ) );
55
56
			if ( ! $result ) {
57
				$error_code = $upgrader->skin->get_main_error_code();
58
				$message    = $upgrader->skin->get_main_error_message();
59
				if ( empty( $message ) ) {
60
					$message = __( 'An unknown error occurred during installation', 'jetpack' );
61
				}
62
63
				if ( 'download_failed' === $error_code ) {
64
					$error_code = 'no_package';
65
				}
66
67
				return new WP_Error( $error_code, $message, 400 );
68
			}
69
70
			if ( empty( $plugin ) ) {
71
				return new WP_Error( 'theme_already_installed' );
72
			}
73
74
			$this->themes            = $plugin;
75
			$this->log[ $plugin[0] ] = $upgrader->skin->get_upgrade_messages();
76
77
			return true;
78
		}
79
80
		return new WP_Error( 'no_theme_installed' );
81
	}
82
}
83