PageController   A
last analyzed

Complexity

Total Complexity 33

Size/Duplication

Total Lines 238
Duplicated Lines 0 %

Coupling/Cohesion

Components 2
Dependencies 4

Test Coverage

Coverage 19.85%

Importance

Changes 0
Metric Value
wmc 33
lcom 2
cbo 4
dl 0
loc 238
ccs 27
cts 136
cp 0.1985
rs 9.76
c 0
b 0
f 0

11 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 10 1
A index() 0 35 5
A getlayer() 0 10 4
A doProxy() 0 12 3
A search() 0 28 5
A geodecode() 0 20 3
A adresslookup() 0 11 4
A bboxSearch() 0 7 1
A doAdresslookup() 0 22 2
A checkGeoCache() 0 3 1
A getURL() 0 22 4
1
<?php
2
/**
3
 * ownCloud - maps
4
 *
5
 * This file is licensed under the Affero General Public License version 3 or
6
 * later. See the COPYING file.
7
 *
8
 * @author Sander Brand <[email protected]>
9
 * @copyright Sander Brand 2014
10
 */
11
12
namespace OCA\Maps\Controller;
13
14
use \OCA\Maps\Db\ApiKey;
15
use \OCA\Maps\Db\DeviceMapper;
16
use \OCA\Maps\Db\ApiKeyMapper;
17
use \OCP\IRequest;
18
use \OCP\AppFramework\Http\TemplateResponse;
19
use \OCP\AppFramework\Controller;
20
use \OCA\Maps\Db\CacheManager;
21
22
class PageController extends Controller {
23
24
	private $userId;
25
	private $cacheManager;
26
	private $deviceMapper;
27
	private $apiKeyMapper;
28 1
	public function __construct($appName, IRequest $request, $userId,
29
								CacheManager $cacheManager,
30
								DeviceMapper $deviceMapper,
31
								ApiKeyMapper $apiKeyMapper) {
32 1
		parent::__construct($appName, $request);
33 1
		$this -> userId = $userId;
34 1
		$this -> cacheManager = $cacheManager;
35 1
		$this -> deviceMapper = $deviceMapper;
36 1
		$this -> apiKeyMapper = $apiKeyMapper;
37 1
	}
38
39
	/**
40
	 * CAUTION: the @Stuff turn off security checks, for this page no admin is
41
	 *          required and no CSRF check. If you don't know what CSRF is, read
42
	 *          it up in the docs or you might create a security hole. This is
43
	 *          basically the only required method to add this exemption, don't
44
	 *          add it to any other method if you don't exactly know what it does
45
	 *
46
	 * @NoAdminRequired
47
	 * @NoCSRFRequired
48
	 */
49 1
	public function index() {
50
51 1
		$params = array('user' => $this -> userId,'devices'=>$this->deviceMapper->findAll($this->userId));
52 1
		$response = new TemplateResponse('maps', 'main', $params);
53 1
		if (class_exists('OCP\AppFramework\Http\ContentSecurityPolicy')) {
54 1
			$csp = new \OCP\AppFramework\Http\ContentSecurityPolicy();
55
			// map tiles
56 1
			$csp->addAllowedImageDomain('http://*.mqcdn.com');
57
			// marker icons
58 1
			$csp->addAllowedImageDomain('https://api.tiles.mapbox.com');
59
			// inline images
60 1
			$csp->addAllowedImageDomain('data:');
61
			//overpasslayer api
62 1
			$csp->addAllowedConnectDomain('http://overpass-api.de/api/interpreter?');
63 1
			$tmpkey = new ApiKey();
64
			try {
65 1
				$tmpkey = $this->apiKeyMapper->findByUser($this->userId);
66 1
			} catch(\OCP\AppFramework\Db\DoesNotExistException $e) {
0 ignored issues
show
Bug introduced by
The class OCP\AppFramework\Db\DoesNotExistException does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
67 1
				$tmpkey->setUserId($this->userId);
68
			}
69 1
			if($tmpkey->apiKey != null && strlen($tmpkey->apiKey) > 0) {
70
				// mapzen geocoder
71
				$csp->addAllowedConnectDomain('http://search.mapzen.com/v1/search?');
72
				$csp->addAllowedConnectDomain('http://search.mapzen.com/v1/reverse?');
73
			} else {
74
				// nominatim geocoder
75 1
				$csp->addAllowedScriptDomain('http://nominatim.openstreetmap.org/search?q=*');
76 1
				$csp->addAllowedScriptDomain('http://nominatim.openstreetmap.org/reverse');
77 1
				$csp->addAllowedConnectDomain('http://router.project-osrm.org');
78
			}
79 1
			$response->setContentSecurityPolicy($csp);
80 1
		}
81 1
		return $response;
82
		// templates/main.php
83
	}
84
85
	/**
86
	 * Get an layer
87
	 * @NoAdminRequired
88
	 * @NoCSRFRequired
89
	 */
90
	public function getlayer() {
91
		$layer = ($this -> params('layer')) ? $this -> params('layer') : null;
92
		if ($layer === "contacts") {
93
			if (\OCP\App::isEnabled('contacts')) {
94
95
			} else {
96
				OCP\Util::writeLog('maps', "App contacts missing for Maps", \OCP\Util::WARN);
97
			}
98
		}
99
	}
100
101
	/**
102
	 * Simply method that posts back the payload of the request
103
	 * @NoAdminRequired
104
	 * @NoCSRFRequired
105
	 */
106
	public function doProxy($echo) {
107
		$url = ($this -> params('url')) ? $this -> params('url') : '';
108
		$allowedHosts = array('overpass.osm.rambler.ru', 'overpass-api.de', 'dev.virtualearth.net', 'router.project-osrm.org', 'nominatim.openstreetmap.org', 'maps.googleapis.com');
109
		$parseUrl = parse_url($url);
110
111
		if (in_array($parseUrl['host'], $allowedHosts)) {
112
			header('Content-Type: application/javascript');
113
			$split = explode('url=', $_SERVER['REQUEST_URI']);
114
			echo $this -> getURL($split[1]);
115
		}
116
		die();
117
	}
118
119
	/**
120
	 * Simply method that posts back the payload of the request
121
	 * @NoAdminRequired
122
	 * @NoCSRFRequired
123
	 */
124
	public function search() {
125
		$cm = \OC::$server -> getContactsManager();
126
		$kw = $this -> params('search');
127
		$bbox = $this -> params('bbox');
128
		$response = array('contacts'=>array(),'nodes'=>array(),'addresses'=>array());
129
130
		$contacts = $cm -> search($kw, array('FN', 'ADR'));
131
		foreach ($contacts as $r) {
132
			$data = array();
0 ignored issues
show
Unused Code introduced by
$data is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
133
			$contact = $r;
134
			for($i=0; $i<count($r['ADR']); $i++){
0 ignored issues
show
Performance Best Practice introduced by
It seems like you are calling the size function count() as part of the test condition. You might want to compute the size beforehand, and not on each iteration.

If the size of the collection does not change during the iteration, it is generally a good practice to compute it beforehand, and not on each iteration:

for ($i=0; $i<count($array); $i++) { // calls count() on each iteration
}

// Better
for ($i=0, $c=count($array); $i<$c; $i++) { // calls count() just once
}
Loading history...
135
				$lookupAdr = implode(',', array_filter($r['ADR'][$i]));
136
				$lookup = $this -> doAdresslookup($lookupAdr);
137
				$contact ['location'][] = $lookup[0];
138
			}
139
			array_push($response['contacts'],$contact);
140
		}
141
		$response['nodes'] = $this->bboxSearch($kw, $bbox);
142
		$addresses = $this->doAdresslookup(urlencode($kw));
143
		foreach($addresses as $address){
144
			array_push($response['addresses'],$address);
145
			if($address->osm_type === "node"){
146
			}
147
		}
148
		//$response['addresses'] = (array)($this->doAdresslookup($kw));
149
150
		return $response;
151
	}
152
153
	/**
154
	 * Simply method that posts back the payload of the request
155
	 * @NoAdminRequired
156
	 * @NoCSRFRequired
157
	 */
158
  public function geodecode(){
159
   $lat = $this->params('lat');
160
   $lng = $this->params('lng');
161
   $zoom = $this->params('zoom');
162
163
   $hash = md5($lat.','.$lng.'@'.$zoom);
164
165
   $checkCache = $this -> checkGeoCache($hash);
166
  if(!$checkCache){
167
      $url = 'http://nominatim.openstreetmap.org/reverse/?format=json&[email protected]&lat='.$lat.'&lng='. $lng.'&zoom=67108864';
168
      $response = $this->getURL($url,false);
169
      if($response){
170
        $this -> cacheManager -> insert($hash, $response);
171
      }
172
   } else {
173
     $response = $checkCache;
174
   }
175
   echo $response;
176
   die();
177
  }
178
	/**
179
	 * Simply method that posts back the payload of the request
180
	 * @NoAdminRequired
181
	 * @NoCSRFRequired
182
	 */
183
	public function adresslookup() {
184
		//
185
		$street = ($this -> params('street')) ? $this -> params('street') : '';
186
		$city = ($this -> params('city')) ? $this -> params('city') : '';
187
		$country = ($this -> params('country')) ? $this -> params('country') : '';
188
189
		$q = urlencode($street . ',' . $city . ',' . $country);
190
		$r = (array) $this -> doAdresslookup($q);
191
		echo json_encode($r[0]);
192
		die();
193
	}
194
195
	private function bboxSearch($q,$bbox){
196
		$apiUrl = 'http://nominatim.openstreetmap.org/search?format=json&limit=100&q=' . $q . '&viewbox='.$bbox.'&bounded=1';
197
		//echo $apiUrl;
198
		$r = $this -> getURL($apiUrl, false);
199
		$s = (array)json_decode($r);
200
		return $s;
201
	}
202
203
	/**
204
	 * @param string $q
205
	 */
206
	private function doAdresslookup($q) {
207
208
		$q = str_replace(" ", "+", $q);
209
		$geohash = md5($q);
210
		$checkCache = $this -> checkGeoCache($geohash);
211
		if (!$checkCache) {
212
			//$apiUrl = 'https://maps.googleapis.com/maps/api/geocode/json?address='. str_replace(' ','+',$q) .'&key=AIzaSyAIHAIBv_uPKZgoxQt0ingc1gWsdAhG7So';
213
			//$apiUrl = 'http://nominatim.openstreetmap.org/search?format=json&street='. $street . '&city='.$city.'&country='.$country.'&limit=1';
214
			$apiUrl = 'http://nominatim.openstreetmap.org/search?format=json&q=' . $q;
215
			$r = $this -> getURL($apiUrl, false);
216
			$s = (array)json_decode($r);
217
218
			$r -> apiUrl = $apiUrl;
219
			$r = $s;
220
			$this -> cacheManager -> insert($geohash, $s);
221
		} else {
222
			$checkCache -> cachedResult = true;
223
			$r = $checkCache;
224
		}
225
		return $r;
226
227
	}
228
229
	/**
230
	 * @param string $hash
231
	 */
232
	private function checkGeoCache($hash) {
233
		return $this -> cacheManager -> check($hash);
234
	}
235
236
	private function getURL($url, $userAgent = true) {
237
		$ch = curl_init();
238
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
239
		curl_setopt($ch, CURLOPT_HEADER, 0);
240
    curl_setopt($ch, CURLOPT_TIMEOUT, 900);
241
		curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
242
		if ($userAgent) {
243
			curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.2) Gecko/20090729 Firefox/3.5.2 GTB5');
244
		}
245
		curl_setopt($ch, CURLOPT_URL, $url);
246
		$tmp = curl_exec($ch);
247
		$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
248
		curl_close($ch);
249
		if ($httpCode === 404) {
250
			return false;
251
		} else {
252
			if ($tmp !== false) {
253
				return $tmp;
254
			}
255
		}
256
257
	}
258
259
}
260