Completed
Pull Request — master (#111)
by
unknown
08:18
created

PageController::index()   B

Complexity

Conditions 4
Paths 3

Size

Total Lines 28
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 5.6264

Importance

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