Completed
Pull Request — master (#112)
by
unknown
08:21
created

PageController::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 1

Importance

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