Completed
Pull Request — stable10 (#1340)
by Lukas
39:16 queued 22:03
created

ImageExportPlugin::getPhoto()   C

Complexity

Conditions 7
Paths 21

Size

Total Lines 44
Code Lines 27

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 7
eloc 27
c 1
b 0
f 0
nc 21
nop 1
dl 0
loc 44
rs 6.7272
1
<?php
2
/**
3
 * @copyright Copyright (c) 2016, ownCloud, Inc.
4
 *
5
 * @author Georg Ehrke <[email protected]>
6
 *
7
 * @license AGPL-3.0
8
 *
9
 * This code is free software: you can redistribute it and/or modify
10
 * it under the terms of the GNU Affero General Public License, version 3,
11
 * as published by the Free Software Foundation.
12
 *
13
 * This program is distributed in the hope that it will be useful,
14
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16
 * GNU Affero General Public License for more details.
17
 *
18
 * You should have received a copy of the GNU Affero General Public License, version 3,
19
 * along with this program.  If not, see <http://www.gnu.org/licenses/>
20
 *
21
 */
22
23
namespace OCA\DAV\CardDAV;
24
25
use OCP\ILogger;
26
use Sabre\CardDAV\Card;
27
use Sabre\DAV\Server;
28
use Sabre\DAV\ServerPlugin;
29
use Sabre\HTTP\RequestInterface;
30
use Sabre\HTTP\ResponseInterface;
31
use Sabre\VObject\Parameter;
32
use Sabre\VObject\Property\Binary;
33
use Sabre\VObject\Reader;
34
35
class ImageExportPlugin extends ServerPlugin {
36
37
	/** @var Server */
38
	protected $server;
39
	/** @var ILogger */
40
	private $logger;
41
42
	public function __construct(ILogger $logger) {
43
		$this->logger = $logger;
44
	}
45
46
	/**
47
	 * Initializes the plugin and registers event handlers
48
	 *
49
	 * @param Server $server
50
	 * @return void
51
	 */
52
	function initialize(Server $server) {
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
53
54
		$this->server = $server;
55
		$this->server->on('method:GET', [$this, 'httpGet'], 90);
56
	}
57
58
	/**
59
	 * Intercepts GET requests on addressbook urls ending with ?photo.
60
	 *
61
	 * @param RequestInterface $request
62
	 * @param ResponseInterface $response
63
	 * @return bool|void
64
	 */
65
	function httpGet(RequestInterface $request, ResponseInterface $response) {
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
66
67
		$queryParams = $request->getQueryParameters();
68
		// TODO: in addition to photo we should also add logo some point in time
69
		if (!array_key_exists('photo', $queryParams)) {
70
			return true;
71
		}
72
73
		$path = $request->getPath();
74
		$node = $this->server->tree->getNodeForPath($path);
75
76
		if (!($node instanceof Card)) {
0 ignored issues
show
Bug introduced by
The class Sabre\CardDAV\Card does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
77
			return true;
78
		}
79
80
		$this->server->transactionType = 'carddav-image-export';
81
82
		// Checking ACL, if available.
83
		if ($aclPlugin = $this->server->getPlugin('acl')) {
84
			/** @var \Sabre\DAVACL\Plugin $aclPlugin */
85
			$aclPlugin->checkPrivileges($path, '{DAV:}read');
86
		}
87
88
		if ($result = $this->getPhoto($node)) {
89
			$response->setHeader('Content-Type', $result['Content-Type']);
90
			$response->setHeader('Content-Disposition', 'attachment');
91
			$response->setStatus(200);
92
93
			$response->setBody($result['body']);
94
95
			// Returning false to break the event chain
96
			return false;
97
		}
98
		return true;
99
	}
100
101
	function getPhoto(Card $node) {
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
102
		// TODO: this is kind of expensive - load carddav data from database and parse it
103
		//       we might want to build up a cache one day
104
		try {
105
			$vObject = $this->readCard($node->get());
106
			if (!$vObject->PHOTO) {
107
				return false;
108
			}
109
110
			$photo = $vObject->PHOTO;
111
			$type = $this->getType($photo);
112
113
			$val = $photo->getValue();
114
			if ($photo->getValueType() === 'URI') {
115
				$parsed = \Sabre\URI\parse($val);
116
				//only allow data://
117
				if ($parsed['scheme'] !== 'data') {
118
					return false;
119
				}
120
				if (substr_count($parsed['path'], ';') === 1) {
121
					list($type,) = explode(';', $parsed['path']);
122
				}
123
				$val = file_get_contents($val);
124
			}
125
126
			$allowedContentTypes = [
127
				'image/png',
128
				'image/jpeg',
129
				'image/gif',
130
			];
131
132
			if(!in_array($type, $allowedContentTypes, true)) {
133
				$type = 'application/octet-stream';
134
			}
135
136
			return [
137
				'Content-Type' => $type,
138
				'body' => $val
139
			];
140
		} catch(\Exception $ex) {
141
			$this->logger->logException($ex);
142
		}
143
		return false;
144
	}
145
146
	private function readCard($cardData) {
147
		return Reader::read($cardData);
148
	}
149
150
	/**
151
	 * @param Binary $photo
152
	 * @return Parameter
153
	 */
154
	private function getType($photo) {
155
		$params = $photo->parameters();
156
		if (isset($params['TYPE']) || isset($params['MEDIATYPE'])) {
157
			/** @var Parameter $typeParam */
158
			$typeParam = isset($params['TYPE']) ? $params['TYPE'] : $params['MEDIATYPE'];
159
			$type = $typeParam->getValue();
160
161
			if (strpos($type, 'image/') === 0) {
162
				return $type;
163
			} else {
164
				return 'image/' . strtolower($type);
0 ignored issues
show
Bug Best Practice introduced by
The return type of return 'image/' . strtolower($type); (string) is incompatible with the return type documented by OCA\DAV\CardDAV\ImageExportPlugin::getType of type Sabre\VObject\Parameter.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

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

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
165
			}
166
		}
167
		return '';
0 ignored issues
show
Bug Best Practice introduced by
The return type of return ''; (string) is incompatible with the return type documented by OCA\DAV\CardDAV\ImageExportPlugin::getType of type Sabre\VObject\Parameter.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

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

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
168
	}
169
}
170