Completed
Push — rework-geocoder ( 78e6d3...74b0e7 )
by
unknown
10:26
created

PageController::index()   B

Complexity

Conditions 2
Paths 2

Size

Total Lines 24
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

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