Completed
Pull Request — master (#111)
by
unknown
11:23
created

PageController::index()   B

Complexity

Conditions 5
Paths 5

Size

Total Lines 33
Code Lines 22

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 8.7918

Importance

Changes 6
Bugs 1 Features 3
Metric Value
c 6
b 1
f 3
dl 0
loc 33
ccs 7
cts 15
cp 0.4667
rs 8.439
cc 5
eloc 22
nc 5
nop 0
crap 8.7918
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 1
	private $cacheManager;
26
	private $deviceMapper;
27
	private $apiKeyMapper;
28 1
	public function __construct($appName, IRequest $request, $userId,
29 1
								CacheManager $cacheManager,
30 1
								DeviceMapper $deviceMapper,
31 1
								ApiKeyMapper $apiKeyMapper) {
32 1
		parent::__construct($appName, $request);
33
		$this -> userId = $userId;
34
		$this -> cacheManager = $cacheManager;
35
		$this -> deviceMapper = $deviceMapper;
36
		$this -> apiKeyMapper = $apiKeyMapper;
37
	}
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 1
	 *          add it to any other method if you don't exactly know what it does
45
	 *
46 1
	 * @NoAdminRequired
47 1
	 * @NoCSRFRequired
48 1
	 */
49 1
	public function index() {
50
51 1
		$params = array('user' => $this -> userId,'devices'=>$this->deviceMapper->findAll($this->userId));
52
		$response = new TemplateResponse('maps', 'main', $params);
53 1
		if (class_exists('OCP\AppFramework\Http\ContentSecurityPolicy')) {
54
			$csp = new \OCP\AppFramework\Http\ContentSecurityPolicy();
55 1
			// map tiles
56 1
			$csp->addAllowedImageDomain('http://*.mqcdn.com');
57 1
			// marker icons
58 1
			$csp->addAllowedImageDomain('https://api.tiles.mapbox.com');
59
			// inline images
60
			$csp->addAllowedImageDomain('data:');
61
			$tmpkey = new ApiKey();
62
			try {
63
				$tmpkey = $this->apiKeyMapper->findByUser($this->userId);
64
			} 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...
65
				$tmpkey->setUserId($this->userId);
66
			}
67
			if($tmpkey->apiKey != null && strlen($tmpkey->apiKey) > 0) {
68
				// mapzen geocoder
69
				$csp->addAllowedConnectDomain('http://search.mapzen.com/v1/search?');
70
				$csp->addAllowedConnectDomain('http://search.mapzen.com/v1/reverse?');
71
			} else {
72
				// nominatim geocoder
73
				$csp->addAllowedScriptDomain('http://nominatim.openstreetmap.org/search?q=*');
74
				$csp->addAllowedScriptDomain('http://nominatim.openstreetmap.org/reverse');
75
				$csp->addAllowedConnectDomain('http://router.project-osrm.org');
76
			}
77
			$response->setContentSecurityPolicy($csp);
78
		}
79
		return $response;
80
		// templates/main.php
81
	}
82
83
	/**
84
	 * Get an layer
85
	 * @NoAdminRequired
86
	 * @NoCSRFRequired
87
	 */
88
	public function getlayer() {
89
		$layer = ($this -> params('layer')) ? $this -> params('layer') : null;
90
		if ($layer === "contacts") {
91
			if (\OCP\App::isEnabled('contacts')) {
92
93
			} else {
94
				OCP\Util::writeLog('maps', "App contacts missing for Maps", \OCP\Util::WARN);
95
			}
96
		}
97
	}
98
99
	/**
100
	 * Simply method that posts back the payload of the request
101
	 * @NoAdminRequired
102
	 * @NoCSRFRequired
103
	 */
104
	public function doProxy($echo) {
105
		$url = ($this -> params('url')) ? $this -> params('url') : '';
106
		$allowedHosts = array('overpass.osm.rambler.ru', 'overpass-api.de', 'dev.virtualearth.net', 'router.project-osrm.org', 'nominatim.openstreetmap.org', 'maps.googleapis.com');
107
		$parseUrl = parse_url($url);
108
109
		if (in_array($parseUrl['host'], $allowedHosts)) {
110
			header('Content-Type: application/javascript');
111
			$split = explode('url=', $_SERVER['REQUEST_URI']);
112
			echo $this -> getURL($split[1]);
113
		}
114
		die();
115
	}
116
117
	/**
118
	 * Simply method that posts back the payload of the request
119
	 * @NoAdminRequired
120
	 * @NoCSRFRequired
121
	 */
122
	public function search() {
123
		$cm = \OC::$server -> getContactsManager();
124
		$kw = $this -> params('search');
125
		$bbox = $this -> params('bbox');
126
		$response = array('contacts'=>array(),'nodes'=>array(),'addresses'=>array());
127
		
128
		$contacts = $cm -> search($kw, array('FN', 'ADR'));
129
		foreach ($contacts as $r) {
130
			$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...
131
			$contact = $r;
132
			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...
133
				$lookupAdr = implode(',', array_filter($r['ADR'][$i]));
134
				$lookup = $this -> doAdresslookup($lookupAdr);
135
				$contact ['location'][] = $lookup[0];
136
			}
137
			array_push($response['contacts'],$contact);
138
		}
139
		$response['nodes'] = $this->bboxSearch($kw, $bbox);
140
		$addresses = $this->doAdresslookup(urlencode($kw));
141
		foreach($addresses as $address){
142
			array_push($response['addresses'],$address);
143
			if($address->osm_type === "node"){
144
			}
145
		}
146
		//$response['addresses'] = (array)($this->doAdresslookup($kw));
147
		
148
		return $response;
149
	}
150
151
	/**
152
	 * Simply method that posts back the payload of the request
153
	 * @NoAdminRequired
154
	 * @NoCSRFRequired
155
	 */
156
  public function geodecode(){
157
   $lat = $this->params('lat');
158
   $lng = $this->params('lng');
159
   $zoom = $this->params('zoom');
160
   
161
   $hash = md5($lat.','.$lng.'@'.$zoom);
162
   
163
   $checkCache = $this -> checkGeoCache($hash);
164
  if(!$checkCache){
165
      $url = 'http://nominatim.openstreetmap.org/reverse/?format=json&[email protected]&lat='.$lat.'&lng='. $lng.'&zoom=67108864';
166
      $response = $this->getURL($url,false);
167
      if($response){
168
        $this -> cacheManager -> insert($hash, $response);
169
      }
170
   } else {
171
     $response = $checkCache;
172
   }
173
   echo $response;
174
   die();
175
  } 
176
	/**
177
	 * Simply method that posts back the payload of the request
178
	 * @NoAdminRequired
179
	 * @NoCSRFRequired
180
	 */
181
	public function adresslookup() {
182
		//
183
		$street = ($this -> params('street')) ? $this -> params('street') : '';
184
		$city = ($this -> params('city')) ? $this -> params('city') : '';
185
		$country = ($this -> params('country')) ? $this -> params('country') : '';
186
187
		$q = urlencode($street . ',' . $city . ',' . $country);
188
		$r = (array) $this -> doAdresslookup($q);
189
		echo json_encode($r[0]);
190
		die();
191
	}
192
193
	private function bboxSearch($q,$bbox){
194
		$apiUrl = 'http://nominatim.openstreetmap.org/search?format=json&limit=100&q=' . $q . '&viewbox='.$bbox.'&bounded=1';
195
		//echo $apiUrl;
196
		$r = $this -> getURL($apiUrl, false);
197
		$s = (array)json_decode($r);
198
		return $s;
199
	}
200
201
	/**
202
	 * @param string $q
203
	 */
204
	private function doAdresslookup($q) {
205
206
		$q = str_replace(" ", "+", $q);
207
		$geohash = md5($q);
208
		$checkCache = $this -> checkGeoCache($geohash);
209
		if (!$checkCache) {
210
			//$apiUrl = 'https://maps.googleapis.com/maps/api/geocode/json?address='. str_replace(' ','+',$q) .'&key=AIzaSyAIHAIBv_uPKZgoxQt0ingc1gWsdAhG7So';
211
			//$apiUrl = 'http://nominatim.openstreetmap.org/search?format=json&street='. $street . '&city='.$city.'&country='.$country.'&limit=1';
212
			$apiUrl = 'http://nominatim.openstreetmap.org/search?format=json&q=' . $q;
213
			$r = $this -> getURL($apiUrl, false);
214
			$s = (array)json_decode($r);
215
216
			$r -> apiUrl = $apiUrl;
217
			$r = $s;
218
			$this -> cacheManager -> insert($geohash, $s);
219
		} else {
220
			$checkCache -> cachedResult = true;
221
			$r = $checkCache;
222
		}
223
		return $r;
224
225
	}
226
227
	/**
228
	 * @param string $hash
229
	 */
230
	private function checkGeoCache($hash) {
231
		return $this -> cacheManager -> check($hash);
232
	}
233
234
	private function getURL($url, $userAgent = true) {
235
		$ch = curl_init();
236
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
237
		curl_setopt($ch, CURLOPT_HEADER, 0);
238
    curl_setopt($ch, CURLOPT_TIMEOUT, 900); 
239
		curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
240
		if ($userAgent) {
241
			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');
242
		}
243
		curl_setopt($ch, CURLOPT_URL, $url);
244
		$tmp = curl_exec($ch);
245
		$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
246
		curl_close($ch);
247
		if ($httpCode === 404) {
248
			return false;
249
		} else {
250
			if ($tmp !== false) {
251
				return $tmp;
252
			}
253
		}
254
255
	}
256
257
}
258