Completed
Push — master ( 00fa07...61a47e )
by Mark
21s queued 13s
created
helper/sitemap.php 2 patches
Indentation   +217 added lines, -217 removed lines patch added patch discarded remove patch
@@ -16,7 +16,7 @@  discard block
 block discarded – undo
16 16
  */
17 17
 
18 18
 if(!defined('DOKU_LF')) {
19
-    define('DOKU_LF', "\n");
19
+	define('DOKU_LF', "\n");
20 20
 }
21 21
 
22 22
 /**
@@ -26,220 +26,220 @@  discard block
 block discarded – undo
26 26
  * @author  Mark Prins
27 27
  */
28 28
 class helper_plugin_spatialhelper_sitemap extends DokuWiki_Plugin {
29
-    /**
30
-     * spatial index.
31
-     */
32
-    private $spatial_idx;
33
-
34
-    /**
35
-     * constructor, load spatial index.
36
-     */
37
-    public function __construct() {
38
-        global $conf;
39
-        $idx_dir = $conf['indexdir'];
40
-        if(!@file_exists($idx_dir . '/spatial.idx')) {
41
-            $indexer = plugin_load('helper', 'spatialhelper_index');
42
-            $indexer->generateSpatialIndex();
43
-        }
44
-        $this->spatial_idx = unserialize(io_readFile($fn = $idx_dir . '/spatial.idx', false));
45
-    }
46
-
47
-    public function getMethods() {
48
-        $result[] = array(
49
-            'name'   => 'createGeoRSSSitemap',
50
-            'desc'   => 'create a spatial sitemap in GeoRSS format.',
51
-            'params' => array(
52
-                'path' => 'string'
53
-            ),
54
-            'return' => array(
55
-                'success' => 'boolean'
56
-            )
57
-        );
58
-        $result[] = array(
59
-            'name'   => 'createKMLSitemap',
60
-            'desc'   => 'create a spatial sitemap in KML format.',
61
-            'params' => array(
62
-                'path' => 'string'
63
-            ),
64
-            'return' => array(
65
-                'success' => 'boolean'
66
-            )
67
-        );
68
-        return $result;
69
-    }
70
-
71
-    /**
72
-     * Create a GeoRSS Simple sitemap (Atom).
73
-     *
74
-     * @param $mediaID id
75
-     *                 for the GeoRSS file
76
-     */
77
-    public function createGeoRSSSitemap($mediaID) {
78
-        global $conf;
79
-        $namespace = getNS($mediaID);
80
-
81
-        $idTag = 'tag:' . parse_url(DOKU_URL, PHP_URL_HOST) . ',';
82
-
83
-        $RSSstart = '<?xml version="1.0" encoding="UTF-8"?>' . DOKU_LF;
84
-        $RSSstart .= '<feed xmlns="http://www.w3.org/2005/Atom" xmlns:georss="http://www.georss.org/georss" ';
85
-        $RSSstart .= 'xmlns:dc="http://purl.org/dc/elements/1.1/">' . DOKU_LF;
86
-        $RSSstart .= '<title>' . $conf['title'] . ' spatial feed</title>' . DOKU_LF;
87
-        if(!empty($conf['tagline'])) {
88
-            $RSSstart .= '<subtitle>' . $conf['tagline'] . '</subtitle>' . DOKU_LF;
89
-        }
90
-        $RSSstart .= '<dc:publisher>' . $conf['title'] . '</dc:publisher>' . DOKU_LF;
91
-        $RSSstart .= '<link href="' . DOKU_URL . '" />' . DOKU_LF;
92
-        $RSSstart .= '<link href="' . ml($mediaID, '', true, '&amp;', true) . '" rel="self" />' . DOKU_LF;
93
-        $RSSstart .= '<updated>' . date(DATE_ATOM) . '</updated>' . DOKU_LF;
94
-        $RSSstart .= '<id>' . $idTag . date("Y-m-d") . ':' . parse_url(ml($mediaID), PHP_URL_PATH)
95
-            . '</id>' . DOKU_LF;
96
-        $RSSstart .= '<rights>' . $conf['license'] . '</rights>' . DOKU_LF;
97
-
98
-        $RSSend = '</feed>' . DOKU_LF;
99
-
100
-        io_createNamespace($mediaID, 'media');
101
-        @touch(mediaFN($mediaID));
102
-        @chmod(mediaFN($mediaID), $conf['fmode']);
103
-        $fh = fopen(mediaFN($mediaID), 'w');
104
-        fwrite($fh, $RSSstart);
105
-
106
-        foreach($this->spatial_idx as $idxEntry) {
107
-            // get list of id's
108
-            foreach($idxEntry as $id) {
109
-                // for document item in the index
110
-                if(strpos($id, 'media__', 0) !== 0) {
111
-                    if($this->skipPage($id, $namespace)) {
112
-                        continue;
113
-                    }
114
-
115
-                    $meta = p_get_metadata($id);
116
-
117
-                    // $desc = p_render('xhtmlsummary', p_get_instructions($meta['description']['abstract']), $info);
118
-                    $desc = strip_tags($meta['description']['abstract']);
119
-
120
-                    $entry = '<entry>' . DOKU_LF;
121
-                    $entry .= '  <title>' . $meta['title'] . '</title>' . DOKU_LF;
122
-                    $entry .= '  <summary>' . $desc . '</summary>' . DOKU_LF;
123
-                    $entry .= '  <georss:point>' . $meta['geo']['lat'] . ' ' . $meta['geo']['lon']
124
-                        . '</georss:point>' . DOKU_LF;
125
-                    if($meta['geo']['alt']) {
126
-                        $entry .= '  <georss:elev>' . $meta['geo']['alt'] . '</georss:elev>' . DOKU_LF;
127
-                    }
128
-                    $entry .= '  <link href="' . wl($id) . '" rel="alternate" type="text/html" />' . DOKU_LF;
129
-                    if(empty($meta['creator'])) {
130
-                        $meta['creator'] = $conf['title'];
131
-                    }
132
-                    $entry .= '  <author><name>' . $meta['creator'] . '</name></author>' . DOKU_LF;
133
-                    $entry .= '  <updated>' . date_iso8601($meta['date']['modified']) . '</updated>' . DOKU_LF;
134
-                    $entry .= '  <published>' . date_iso8601($meta['date']['created']) . '</published>' . DOKU_LF;
135
-                    $entry .= '  <id>' . $idTag . date("Y-m-d", $meta['date']['modified']) . ':'
136
-                        . parse_url(wl($id), PHP_URL_PATH) . '</id>' . DOKU_LF;
137
-                    $entry .= '</entry>' . DOKU_LF;
138
-                    fwrite($fh, $entry);
139
-                }
140
-            }
141
-        }
142
-
143
-        fwrite($fh, $RSSend);
144
-        return fclose($fh);
145
-    }
146
-
147
-    /**
148
-     * will return true for non-public or hidden pages or pages that are not below or in the namespace.
149
-     */
150
-    private function skipPage($id, $namespace) {
151
-        dbglog("helper_plugin_spatialhelper_sitemap::skipPage, check for $id in $namespace");
152
-        if(isHiddenPage($id)) {
153
-            return true;
154
-        }
155
-        if(auth_aclcheck($id, '', '') < AUTH_READ) {
156
-            return true;
157
-        }
158
-
159
-        if(!empty($namespace)) {
160
-            // only if id is in or below namespace
161
-            if(0 !== strpos(getNS($id), $namespace)) {
162
-                // dbglog("helper_plugin_spatialhelper_sitemap::skipPage, skipping $id, not in $namespace");
163
-                return true;
164
-            }
165
-        }
166
-        return false;
167
-    }
168
-
169
-    /**
170
-     * Create a KML sitemap.
171
-     *
172
-     * @param $mediaID id
173
-     *                 for the KML file
174
-     */
175
-    public function createKMLSitemap($mediaID) {
176
-        global $conf;
177
-        $namespace = getNS($mediaID);
178
-
179
-        $KMLstart = '<?xml version="1.0" encoding="UTF-8"?>' . DOKU_LF;
180
-        $KMLstart .= '<kml xmlns="http://www.opengis.net/kml/2.2" ';
181
-        $KMLstart .= 'xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" ';
182
-        $KMLstart .= 'xmlns:atom="http://www.w3.org/2005/Atom"';
183
-        $KMLstart .= ' xsi:schemaLocation="http://www.opengis.net/kml/2.2 ';
184
-        $KMLstart .= 'http://schemas.opengis.net/kml/2.2.0/ogckml22.xsd">' . DOKU_LF;
185
-        $KMLstart .= '<Document id="root_doc">' . DOKU_LF;
186
-        $KMLstart .= '<name>' . $conf['title'] . ' spatial sitemap</name>' . DOKU_LF;
187
-        $KMLstart .= '<atom:link href="' . DOKU_URL . '" rel="related" type="text/html" />' . DOKU_LF;
188
-        $KMLstart .= '<!-- atom:updated>' . date(DATE_ATOM) . '</atom:updated -->' . DOKU_LF;
189
-        $KMLstart .= '<Style id="icon"><IconStyle><color>ffffffff</color><scale>1</scale>';
190
-        $KMLstart .= '<Icon><href>'
191
-            . DOKU_BASE . 'lib/plugins/spatialhelper/wikiitem.png</href></Icon></IconStyle></Style>' . DOKU_LF;
192
-
193
-        $KMLend = '</Document>' . DOKU_LF . '</kml>';
194
-
195
-        io_createNamespace($mediaID, 'media');
196
-        @touch(mediaFN($mediaID));
197
-        @chmod(mediaFN($mediaID), $conf['fmode']);
198
-
199
-        $fh = fopen(mediaFN($mediaID), 'w');
200
-        fwrite($fh, $KMLstart);
201
-
202
-        foreach($this->spatial_idx as $idxEntry) {
203
-            // get list of id's
204
-            foreach($idxEntry as $id) {
205
-                // for document item in the index
206
-                if(strpos($id, 'media__', 0) !== 0) {
207
-                    if($this->skipPage($id, $namespace)) {
208
-                        continue;
209
-                    }
210
-
211
-                    $meta = p_get_metadata($id);
212
-
213
-                    // $desc = p_render('xhtmlsummary', p_get_instructions($meta['description']['abstract']), $info);
214
-                    $desc = '<p>' . strip_tags($meta['description']['abstract']) . '</p>';
215
-                    $desc .= '<p><a href="' . wl($id, '', true) . '">' . $meta['title'] . '</a></p>';
216
-
217
-                    // create an entry and store it
218
-                    $plcm = '<Placemark id="crc32-' . hash('crc32', $id) . '">' . DOKU_LF;
219
-                    $plcm .= '  <name>' . $meta['title'] . '</name>' . DOKU_LF;
220
-                    // TODO escape quotes in: title="' . $meta['title'] . '"
221
-                    $plcm .= '  <atom:link href="' . wl($id, '' . true) . '" rel="alternate" type="text/html" />'
222
-                        . DOKU_LF;
223
-                    if(!empty($meta['creator'])) {
224
-                        $entry .= '  <atom:author><atom:name>' . $meta['creator'] . '</atom:name></atom:author>'
225
-                            . DOKU_LF;
226
-                    }
227
-
228
-                    $plcm .= '  <description><![CDATA[' . $desc . ']]></description>' . DOKU_LF;
229
-                    $plcm .= '  <styleUrl>#icon</styleUrl>' . DOKU_LF;
230
-
231
-                    $plcm .= '  <Point><coordinates>' . $meta['geo']['lon'] . ',' . $meta['geo']['lat'];
232
-                    if($meta['geo']['alt']) {
233
-                        $plcm .= ',' . $meta['geo']['alt'];
234
-                    }
235
-                    $plcm .= '</coordinates></Point>' . DOKU_LF;
236
-                    $plcm .= '</Placemark>' . DOKU_LF;
237
-
238
-                    fwrite($fh, $plcm);
239
-                }
240
-            }
241
-        }
242
-        fwrite($fh, $KMLend);
243
-        return fclose($fh);
244
-    }
29
+	/**
30
+	 * spatial index.
31
+	 */
32
+	private $spatial_idx;
33
+
34
+	/**
35
+	 * constructor, load spatial index.
36
+	 */
37
+	public function __construct() {
38
+		global $conf;
39
+		$idx_dir = $conf['indexdir'];
40
+		if(!@file_exists($idx_dir . '/spatial.idx')) {
41
+			$indexer = plugin_load('helper', 'spatialhelper_index');
42
+			$indexer->generateSpatialIndex();
43
+		}
44
+		$this->spatial_idx = unserialize(io_readFile($fn = $idx_dir . '/spatial.idx', false));
45
+	}
46
+
47
+	public function getMethods() {
48
+		$result[] = array(
49
+			'name'   => 'createGeoRSSSitemap',
50
+			'desc'   => 'create a spatial sitemap in GeoRSS format.',
51
+			'params' => array(
52
+				'path' => 'string'
53
+			),
54
+			'return' => array(
55
+				'success' => 'boolean'
56
+			)
57
+		);
58
+		$result[] = array(
59
+			'name'   => 'createKMLSitemap',
60
+			'desc'   => 'create a spatial sitemap in KML format.',
61
+			'params' => array(
62
+				'path' => 'string'
63
+			),
64
+			'return' => array(
65
+				'success' => 'boolean'
66
+			)
67
+		);
68
+		return $result;
69
+	}
70
+
71
+	/**
72
+	 * Create a GeoRSS Simple sitemap (Atom).
73
+	 *
74
+	 * @param $mediaID id
75
+	 *                 for the GeoRSS file
76
+	 */
77
+	public function createGeoRSSSitemap($mediaID) {
78
+		global $conf;
79
+		$namespace = getNS($mediaID);
80
+
81
+		$idTag = 'tag:' . parse_url(DOKU_URL, PHP_URL_HOST) . ',';
82
+
83
+		$RSSstart = '<?xml version="1.0" encoding="UTF-8"?>' . DOKU_LF;
84
+		$RSSstart .= '<feed xmlns="http://www.w3.org/2005/Atom" xmlns:georss="http://www.georss.org/georss" ';
85
+		$RSSstart .= 'xmlns:dc="http://purl.org/dc/elements/1.1/">' . DOKU_LF;
86
+		$RSSstart .= '<title>' . $conf['title'] . ' spatial feed</title>' . DOKU_LF;
87
+		if(!empty($conf['tagline'])) {
88
+			$RSSstart .= '<subtitle>' . $conf['tagline'] . '</subtitle>' . DOKU_LF;
89
+		}
90
+		$RSSstart .= '<dc:publisher>' . $conf['title'] . '</dc:publisher>' . DOKU_LF;
91
+		$RSSstart .= '<link href="' . DOKU_URL . '" />' . DOKU_LF;
92
+		$RSSstart .= '<link href="' . ml($mediaID, '', true, '&amp;', true) . '" rel="self" />' . DOKU_LF;
93
+		$RSSstart .= '<updated>' . date(DATE_ATOM) . '</updated>' . DOKU_LF;
94
+		$RSSstart .= '<id>' . $idTag . date("Y-m-d") . ':' . parse_url(ml($mediaID), PHP_URL_PATH)
95
+			. '</id>' . DOKU_LF;
96
+		$RSSstart .= '<rights>' . $conf['license'] . '</rights>' . DOKU_LF;
97
+
98
+		$RSSend = '</feed>' . DOKU_LF;
99
+
100
+		io_createNamespace($mediaID, 'media');
101
+		@touch(mediaFN($mediaID));
102
+		@chmod(mediaFN($mediaID), $conf['fmode']);
103
+		$fh = fopen(mediaFN($mediaID), 'w');
104
+		fwrite($fh, $RSSstart);
105
+
106
+		foreach($this->spatial_idx as $idxEntry) {
107
+			// get list of id's
108
+			foreach($idxEntry as $id) {
109
+				// for document item in the index
110
+				if(strpos($id, 'media__', 0) !== 0) {
111
+					if($this->skipPage($id, $namespace)) {
112
+						continue;
113
+					}
114
+
115
+					$meta = p_get_metadata($id);
116
+
117
+					// $desc = p_render('xhtmlsummary', p_get_instructions($meta['description']['abstract']), $info);
118
+					$desc = strip_tags($meta['description']['abstract']);
119
+
120
+					$entry = '<entry>' . DOKU_LF;
121
+					$entry .= '  <title>' . $meta['title'] . '</title>' . DOKU_LF;
122
+					$entry .= '  <summary>' . $desc . '</summary>' . DOKU_LF;
123
+					$entry .= '  <georss:point>' . $meta['geo']['lat'] . ' ' . $meta['geo']['lon']
124
+						. '</georss:point>' . DOKU_LF;
125
+					if($meta['geo']['alt']) {
126
+						$entry .= '  <georss:elev>' . $meta['geo']['alt'] . '</georss:elev>' . DOKU_LF;
127
+					}
128
+					$entry .= '  <link href="' . wl($id) . '" rel="alternate" type="text/html" />' . DOKU_LF;
129
+					if(empty($meta['creator'])) {
130
+						$meta['creator'] = $conf['title'];
131
+					}
132
+					$entry .= '  <author><name>' . $meta['creator'] . '</name></author>' . DOKU_LF;
133
+					$entry .= '  <updated>' . date_iso8601($meta['date']['modified']) . '</updated>' . DOKU_LF;
134
+					$entry .= '  <published>' . date_iso8601($meta['date']['created']) . '</published>' . DOKU_LF;
135
+					$entry .= '  <id>' . $idTag . date("Y-m-d", $meta['date']['modified']) . ':'
136
+						. parse_url(wl($id), PHP_URL_PATH) . '</id>' . DOKU_LF;
137
+					$entry .= '</entry>' . DOKU_LF;
138
+					fwrite($fh, $entry);
139
+				}
140
+			}
141
+		}
142
+
143
+		fwrite($fh, $RSSend);
144
+		return fclose($fh);
145
+	}
146
+
147
+	/**
148
+	 * will return true for non-public or hidden pages or pages that are not below or in the namespace.
149
+	 */
150
+	private function skipPage($id, $namespace) {
151
+		dbglog("helper_plugin_spatialhelper_sitemap::skipPage, check for $id in $namespace");
152
+		if(isHiddenPage($id)) {
153
+			return true;
154
+		}
155
+		if(auth_aclcheck($id, '', '') < AUTH_READ) {
156
+			return true;
157
+		}
158
+
159
+		if(!empty($namespace)) {
160
+			// only if id is in or below namespace
161
+			if(0 !== strpos(getNS($id), $namespace)) {
162
+				// dbglog("helper_plugin_spatialhelper_sitemap::skipPage, skipping $id, not in $namespace");
163
+				return true;
164
+			}
165
+		}
166
+		return false;
167
+	}
168
+
169
+	/**
170
+	 * Create a KML sitemap.
171
+	 *
172
+	 * @param $mediaID id
173
+	 *                 for the KML file
174
+	 */
175
+	public function createKMLSitemap($mediaID) {
176
+		global $conf;
177
+		$namespace = getNS($mediaID);
178
+
179
+		$KMLstart = '<?xml version="1.0" encoding="UTF-8"?>' . DOKU_LF;
180
+		$KMLstart .= '<kml xmlns="http://www.opengis.net/kml/2.2" ';
181
+		$KMLstart .= 'xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" ';
182
+		$KMLstart .= 'xmlns:atom="http://www.w3.org/2005/Atom"';
183
+		$KMLstart .= ' xsi:schemaLocation="http://www.opengis.net/kml/2.2 ';
184
+		$KMLstart .= 'http://schemas.opengis.net/kml/2.2.0/ogckml22.xsd">' . DOKU_LF;
185
+		$KMLstart .= '<Document id="root_doc">' . DOKU_LF;
186
+		$KMLstart .= '<name>' . $conf['title'] . ' spatial sitemap</name>' . DOKU_LF;
187
+		$KMLstart .= '<atom:link href="' . DOKU_URL . '" rel="related" type="text/html" />' . DOKU_LF;
188
+		$KMLstart .= '<!-- atom:updated>' . date(DATE_ATOM) . '</atom:updated -->' . DOKU_LF;
189
+		$KMLstart .= '<Style id="icon"><IconStyle><color>ffffffff</color><scale>1</scale>';
190
+		$KMLstart .= '<Icon><href>'
191
+			. DOKU_BASE . 'lib/plugins/spatialhelper/wikiitem.png</href></Icon></IconStyle></Style>' . DOKU_LF;
192
+
193
+		$KMLend = '</Document>' . DOKU_LF . '</kml>';
194
+
195
+		io_createNamespace($mediaID, 'media');
196
+		@touch(mediaFN($mediaID));
197
+		@chmod(mediaFN($mediaID), $conf['fmode']);
198
+
199
+		$fh = fopen(mediaFN($mediaID), 'w');
200
+		fwrite($fh, $KMLstart);
201
+
202
+		foreach($this->spatial_idx as $idxEntry) {
203
+			// get list of id's
204
+			foreach($idxEntry as $id) {
205
+				// for document item in the index
206
+				if(strpos($id, 'media__', 0) !== 0) {
207
+					if($this->skipPage($id, $namespace)) {
208
+						continue;
209
+					}
210
+
211
+					$meta = p_get_metadata($id);
212
+
213
+					// $desc = p_render('xhtmlsummary', p_get_instructions($meta['description']['abstract']), $info);
214
+					$desc = '<p>' . strip_tags($meta['description']['abstract']) . '</p>';
215
+					$desc .= '<p><a href="' . wl($id, '', true) . '">' . $meta['title'] . '</a></p>';
216
+
217
+					// create an entry and store it
218
+					$plcm = '<Placemark id="crc32-' . hash('crc32', $id) . '">' . DOKU_LF;
219
+					$plcm .= '  <name>' . $meta['title'] . '</name>' . DOKU_LF;
220
+					// TODO escape quotes in: title="' . $meta['title'] . '"
221
+					$plcm .= '  <atom:link href="' . wl($id, '' . true) . '" rel="alternate" type="text/html" />'
222
+						. DOKU_LF;
223
+					if(!empty($meta['creator'])) {
224
+						$entry .= '  <atom:author><atom:name>' . $meta['creator'] . '</atom:name></atom:author>'
225
+							. DOKU_LF;
226
+					}
227
+
228
+					$plcm .= '  <description><![CDATA[' . $desc . ']]></description>' . DOKU_LF;
229
+					$plcm .= '  <styleUrl>#icon</styleUrl>' . DOKU_LF;
230
+
231
+					$plcm .= '  <Point><coordinates>' . $meta['geo']['lon'] . ',' . $meta['geo']['lat'];
232
+					if($meta['geo']['alt']) {
233
+						$plcm .= ',' . $meta['geo']['alt'];
234
+					}
235
+					$plcm .= '</coordinates></Point>' . DOKU_LF;
236
+					$plcm .= '</Placemark>' . DOKU_LF;
237
+
238
+					fwrite($fh, $plcm);
239
+				}
240
+			}
241
+		}
242
+		fwrite($fh, $KMLend);
243
+		return fclose($fh);
244
+	}
245 245
 }
Please login to merge, or discard this patch.
Spacing   +19 added lines, -19 removed lines patch added patch discarded remove patch
@@ -15,7 +15,7 @@  discard block
 block discarded – undo
15 15
  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
16 16
  */
17 17
 
18
-if(!defined('DOKU_LF')) {
18
+if (!defined('DOKU_LF')) {
19 19
     define('DOKU_LF', "\n");
20 20
 }
21 21
 
@@ -37,7 +37,7 @@  discard block
 block discarded – undo
37 37
     public function __construct() {
38 38
         global $conf;
39 39
         $idx_dir = $conf['indexdir'];
40
-        if(!@file_exists($idx_dir . '/spatial.idx')) {
40
+        if (!@file_exists($idx_dir . '/spatial.idx')) {
41 41
             $indexer = plugin_load('helper', 'spatialhelper_index');
42 42
             $indexer->generateSpatialIndex();
43 43
         }
@@ -84,7 +84,7 @@  discard block
 block discarded – undo
84 84
         $RSSstart .= '<feed xmlns="http://www.w3.org/2005/Atom" xmlns:georss="http://www.georss.org/georss" ';
85 85
         $RSSstart .= 'xmlns:dc="http://purl.org/dc/elements/1.1/">' . DOKU_LF;
86 86
         $RSSstart .= '<title>' . $conf['title'] . ' spatial feed</title>' . DOKU_LF;
87
-        if(!empty($conf['tagline'])) {
87
+        if (!empty($conf['tagline'])) {
88 88
             $RSSstart .= '<subtitle>' . $conf['tagline'] . '</subtitle>' . DOKU_LF;
89 89
         }
90 90
         $RSSstart .= '<dc:publisher>' . $conf['title'] . '</dc:publisher>' . DOKU_LF;
@@ -103,12 +103,12 @@  discard block
 block discarded – undo
103 103
         $fh = fopen(mediaFN($mediaID), 'w');
104 104
         fwrite($fh, $RSSstart);
105 105
 
106
-        foreach($this->spatial_idx as $idxEntry) {
106
+        foreach ($this->spatial_idx as $idxEntry) {
107 107
             // get list of id's
108
-            foreach($idxEntry as $id) {
108
+            foreach ($idxEntry as $id) {
109 109
                 // for document item in the index
110
-                if(strpos($id, 'media__', 0) !== 0) {
111
-                    if($this->skipPage($id, $namespace)) {
110
+                if (strpos($id, 'media__', 0) !== 0) {
111
+                    if ($this->skipPage($id, $namespace)) {
112 112
                         continue;
113 113
                     }
114 114
 
@@ -122,11 +122,11 @@  discard block
 block discarded – undo
122 122
                     $entry .= '  <summary>' . $desc . '</summary>' . DOKU_LF;
123 123
                     $entry .= '  <georss:point>' . $meta['geo']['lat'] . ' ' . $meta['geo']['lon']
124 124
                         . '</georss:point>' . DOKU_LF;
125
-                    if($meta['geo']['alt']) {
125
+                    if ($meta['geo']['alt']) {
126 126
                         $entry .= '  <georss:elev>' . $meta['geo']['alt'] . '</georss:elev>' . DOKU_LF;
127 127
                     }
128 128
                     $entry .= '  <link href="' . wl($id) . '" rel="alternate" type="text/html" />' . DOKU_LF;
129
-                    if(empty($meta['creator'])) {
129
+                    if (empty($meta['creator'])) {
130 130
                         $meta['creator'] = $conf['title'];
131 131
                     }
132 132
                     $entry .= '  <author><name>' . $meta['creator'] . '</name></author>' . DOKU_LF;
@@ -149,16 +149,16 @@  discard block
 block discarded – undo
149 149
      */
150 150
     private function skipPage($id, $namespace) {
151 151
         dbglog("helper_plugin_spatialhelper_sitemap::skipPage, check for $id in $namespace");
152
-        if(isHiddenPage($id)) {
152
+        if (isHiddenPage($id)) {
153 153
             return true;
154 154
         }
155
-        if(auth_aclcheck($id, '', '') < AUTH_READ) {
155
+        if (auth_aclcheck($id, '', '') < AUTH_READ) {
156 156
             return true;
157 157
         }
158 158
 
159
-        if(!empty($namespace)) {
159
+        if (!empty($namespace)) {
160 160
             // only if id is in or below namespace
161
-            if(0 !== strpos(getNS($id), $namespace)) {
161
+            if (0 !== strpos(getNS($id), $namespace)) {
162 162
                 // dbglog("helper_plugin_spatialhelper_sitemap::skipPage, skipping $id, not in $namespace");
163 163
                 return true;
164 164
             }
@@ -199,12 +199,12 @@  discard block
 block discarded – undo
199 199
         $fh = fopen(mediaFN($mediaID), 'w');
200 200
         fwrite($fh, $KMLstart);
201 201
 
202
-        foreach($this->spatial_idx as $idxEntry) {
202
+        foreach ($this->spatial_idx as $idxEntry) {
203 203
             // get list of id's
204
-            foreach($idxEntry as $id) {
204
+            foreach ($idxEntry as $id) {
205 205
                 // for document item in the index
206
-                if(strpos($id, 'media__', 0) !== 0) {
207
-                    if($this->skipPage($id, $namespace)) {
206
+                if (strpos($id, 'media__', 0) !== 0) {
207
+                    if ($this->skipPage($id, $namespace)) {
208 208
                         continue;
209 209
                     }
210 210
 
@@ -220,7 +220,7 @@  discard block
 block discarded – undo
220 220
                     // TODO escape quotes in: title="' . $meta['title'] . '"
221 221
                     $plcm .= '  <atom:link href="' . wl($id, '' . true) . '" rel="alternate" type="text/html" />'
222 222
                         . DOKU_LF;
223
-                    if(!empty($meta['creator'])) {
223
+                    if (!empty($meta['creator'])) {
224 224
                         $entry .= '  <atom:author><atom:name>' . $meta['creator'] . '</atom:name></atom:author>'
225 225
                             . DOKU_LF;
226 226
                     }
@@ -229,7 +229,7 @@  discard block
 block discarded – undo
229 229
                     $plcm .= '  <styleUrl>#icon</styleUrl>' . DOKU_LF;
230 230
 
231 231
                     $plcm .= '  <Point><coordinates>' . $meta['geo']['lon'] . ',' . $meta['geo']['lat'];
232
-                    if($meta['geo']['alt']) {
232
+                    if ($meta['geo']['alt']) {
233 233
                         $plcm .= ',' . $meta['geo']['alt'];
234 234
                     }
235 235
                     $plcm .= '</coordinates></Point>' . DOKU_LF;
Please login to merge, or discard this patch.
helper/index.php 2 patches
Indentation   +258 added lines, -258 removed lines patch added patch discarded remove patch
@@ -22,283 +22,283 @@
 block discarded – undo
22 22
  * @author  Mark Prins
23 23
  */
24 24
 class helper_plugin_spatialhelper_index extends DokuWiki_Plugin {
25
-    /**
26
-     * directory for index files.
27
-     *
28
-     * @var string
29
-     */
30
-    protected $idx_dir = '';
25
+	/**
26
+	 * directory for index files.
27
+	 *
28
+	 * @var string
29
+	 */
30
+	protected $idx_dir = '';
31 31
 
32
-    /**
33
-     * spatial index, well lookup list/array so we can do spatial queries.
34
-     * entries should be: array("geohash" => {"id1","id3",})
35
-     *
36
-     * @var array
37
-     */
38
-    protected $spatial_idx = array();
32
+	/**
33
+	 * spatial index, well lookup list/array so we can do spatial queries.
34
+	 * entries should be: array("geohash" => {"id1","id3",})
35
+	 *
36
+	 * @var array
37
+	 */
38
+	protected $spatial_idx = array();
39 39
 
40
-    /**
41
-     * handle to the geoPHP plugin.
42
-     */
43
-    protected $geophp;
40
+	/**
41
+	 * handle to the geoPHP plugin.
42
+	 */
43
+	protected $geophp;
44 44
 
45
-    /**
46
-     * Constructor, initialises the spatial index.
47
-     */
48
-    public function __construct() {
49
-        if(!$geophp = &plugin_load('helper', 'geophp')) {
50
-            $message = 'helper_plugin_spatialhelper_index::spatialhelper_index: geophp plugin is not available.';
51
-            msg($message, -1);
52
-            return "";
53
-        }
45
+	/**
46
+	 * Constructor, initialises the spatial index.
47
+	 */
48
+	public function __construct() {
49
+		if(!$geophp = &plugin_load('helper', 'geophp')) {
50
+			$message = 'helper_plugin_spatialhelper_index::spatialhelper_index: geophp plugin is not available.';
51
+			msg($message, -1);
52
+			return "";
53
+		}
54 54
 
55
-        global $conf;
56
-        $this->idx_dir = $conf ['indexdir'];
57
-        // test if there is a spatialindex, if not build one for the wiki
58
-        if(!@file_exists($this->idx_dir . '/spatial.idx')) {
59
-            // creates and stores the index
60
-            $this->generateSpatialIndex();
61
-        } else {
62
-            $this->spatial_idx = unserialize(io_readFile($this->idx_dir . '/spatial.idx', false));
63
-            dbglog($this->spatial_idx, 'done loading spatial index');
64
-        }
65
-    }
55
+		global $conf;
56
+		$this->idx_dir = $conf ['indexdir'];
57
+		// test if there is a spatialindex, if not build one for the wiki
58
+		if(!@file_exists($this->idx_dir . '/spatial.idx')) {
59
+			// creates and stores the index
60
+			$this->generateSpatialIndex();
61
+		} else {
62
+			$this->spatial_idx = unserialize(io_readFile($this->idx_dir . '/spatial.idx', false));
63
+			dbglog($this->spatial_idx, 'done loading spatial index');
64
+		}
65
+	}
66 66
 
67
-    /**
68
-     * (re-)Generates the spatial index by running through all the pages in the wiki.
69
-     *
70
-     * @todo add an option to erase the old index
71
-     */
72
-    public function generateSpatialIndex() {
73
-        global $conf;
74
-        require_once(DOKU_INC . 'inc/search.php');
75
-        $pages = array();
76
-        search($pages, $conf ['datadir'], 'search_allpages', array());
77
-        foreach($pages as $page) {
78
-            $this->updateSpatialIndex($page ['id']);
79
-        }
80
-        // media
81
-        $media = array();
82
-        search($media, $conf ['mediadir'], 'search_media', array());
83
-        foreach($media as $medium) {
84
-            if($medium ['isimg']) {
85
-                $this->indexImage($medium);
86
-            }
87
-        }
88
-        return true;
89
-    }
67
+	/**
68
+	 * (re-)Generates the spatial index by running through all the pages in the wiki.
69
+	 *
70
+	 * @todo add an option to erase the old index
71
+	 */
72
+	public function generateSpatialIndex() {
73
+		global $conf;
74
+		require_once(DOKU_INC . 'inc/search.php');
75
+		$pages = array();
76
+		search($pages, $conf ['datadir'], 'search_allpages', array());
77
+		foreach($pages as $page) {
78
+			$this->updateSpatialIndex($page ['id']);
79
+		}
80
+		// media
81
+		$media = array();
82
+		search($media, $conf ['mediadir'], 'search_media', array());
83
+		foreach($media as $medium) {
84
+			if($medium ['isimg']) {
85
+				$this->indexImage($medium);
86
+			}
87
+		}
88
+		return true;
89
+	}
90 90
 
91
-    /**
92
-     * Update the spatial index for the page.
93
-     *
94
-     * @param string $id
95
-     *          the document ID
96
-     */
97
-    public function updateSpatialIndex($id) {
98
-        $geotags = p_get_metadata($id, 'geo');
99
-        if(empty ($geotags)) {
100
-            return false;
101
-        }
102
-        if(empty ($geotags ['lon']) || empty ($geotags ['lat'])) {
103
-            return false;
104
-        }
105
-        dbglog($geotags, "Geo metadata found for page $id");
106
-        $geometry = new Point($geotags ['lon'], $geotags ['lat']);
107
-        $geohash  = $geometry->out('geohash');
108
-        dbglog('Update index for geohash: ' . $geohash);
109
-        $succes = $this->addToIndex($geohash, $id);
110
-    }
91
+	/**
92
+	 * Update the spatial index for the page.
93
+	 *
94
+	 * @param string $id
95
+	 *          the document ID
96
+	 */
97
+	public function updateSpatialIndex($id) {
98
+		$geotags = p_get_metadata($id, 'geo');
99
+		if(empty ($geotags)) {
100
+			return false;
101
+		}
102
+		if(empty ($geotags ['lon']) || empty ($geotags ['lat'])) {
103
+			return false;
104
+		}
105
+		dbglog($geotags, "Geo metadata found for page $id");
106
+		$geometry = new Point($geotags ['lon'], $geotags ['lat']);
107
+		$geohash  = $geometry->out('geohash');
108
+		dbglog('Update index for geohash: ' . $geohash);
109
+		$succes = $this->addToIndex($geohash, $id);
110
+	}
111 111
 
112
-    /**
113
-     * Store the hash/id entry in the index.
114
-     *
115
-     * @param string $geohash
116
-     * @param string $id
117
-     *          page or media id
118
-     * @return boolean true when succesful
119
-     */
120
-    private function addToIndex($geohash, $id) {
121
-        $pageIds = array();
122
-        // check index for key/geohash
123
-        if(!array_key_exists($geohash, $this->spatial_idx)) {
124
-            dbglog("Geohash $geohash not in index, just add $id.");
125
-            $pageIds [] = $id;
126
-        } else {
127
-            dbglog('Geohash for document is in index, find it.');
128
-            // check the index for document
129
-            $knownHashes = $this->findHashesForId($id, $this->spatial_idx);
130
-            if(empty ($knownHashes)) {
131
-                dbglog("No index record found for document $id, just add");
132
-                $pageIds    = $this->spatial_idx [$geohash];
133
-                $pageIds [] = $id;
134
-            }
135
-            // TODO shortcut, need to make sure there is only one element, if not the index is corrupt
136
-            $knownHash = $knownHashes [0];
112
+	/**
113
+	 * Store the hash/id entry in the index.
114
+	 *
115
+	 * @param string $geohash
116
+	 * @param string $id
117
+	 *          page or media id
118
+	 * @return boolean true when succesful
119
+	 */
120
+	private function addToIndex($geohash, $id) {
121
+		$pageIds = array();
122
+		// check index for key/geohash
123
+		if(!array_key_exists($geohash, $this->spatial_idx)) {
124
+			dbglog("Geohash $geohash not in index, just add $id.");
125
+			$pageIds [] = $id;
126
+		} else {
127
+			dbglog('Geohash for document is in index, find it.');
128
+			// check the index for document
129
+			$knownHashes = $this->findHashesForId($id, $this->spatial_idx);
130
+			if(empty ($knownHashes)) {
131
+				dbglog("No index record found for document $id, just add");
132
+				$pageIds    = $this->spatial_idx [$geohash];
133
+				$pageIds [] = $id;
134
+			}
135
+			// TODO shortcut, need to make sure there is only one element, if not the index is corrupt
136
+			$knownHash = $knownHashes [0];
137 137
 
138
-            if($knownHash == $geohash) {
139
-                dbglog("Document $id was found in index and has the same geohash, nothing to do.");
140
-                return true;
141
-            }
138
+			if($knownHash == $geohash) {
139
+				dbglog("Document $id was found in index and has the same geohash, nothing to do.");
140
+				return true;
141
+			}
142 142
 
143
-            if(!empty ($knownHash)) {
144
-                dbglog("Document/media $id was found in index but has different geohash (it moved).");
145
-                $knownIds = $this->spatial_idx [$knownHash];
146
-                dbglog($knownIds, "Known id's for this hash:");
147
-                // remove it from the old geohash element
148
-                $i = array_search($id, $knownIds);
149
-                dbglog('Unsetting:' . $knownIds [$i]);
150
-                unset ($knownIds [$i]);
151
-                $this->spatial_idx [$knownHash] = $knownIds;
152
-                // set on new geohash element
153
-                $pageIds    = $this->spatial_idx [$geohash];
154
-                $pageIds [] = $id;
155
-            }
156
-        }
157
-        // store and save
158
-        $this->spatial_idx [$geohash] = $pageIds;
159
-        return $this->saveIndex();
160
-    }
143
+			if(!empty ($knownHash)) {
144
+				dbglog("Document/media $id was found in index but has different geohash (it moved).");
145
+				$knownIds = $this->spatial_idx [$knownHash];
146
+				dbglog($knownIds, "Known id's for this hash:");
147
+				// remove it from the old geohash element
148
+				$i = array_search($id, $knownIds);
149
+				dbglog('Unsetting:' . $knownIds [$i]);
150
+				unset ($knownIds [$i]);
151
+				$this->spatial_idx [$knownHash] = $knownIds;
152
+				// set on new geohash element
153
+				$pageIds    = $this->spatial_idx [$geohash];
154
+				$pageIds [] = $id;
155
+			}
156
+		}
157
+		// store and save
158
+		$this->spatial_idx [$geohash] = $pageIds;
159
+		return $this->saveIndex();
160
+	}
161 161
 
162
-    /**
163
-     * Looks up the geohash(es) for the document in the index.
164
-     *
165
-     * @param String $id
166
-     *          document ID
167
-     * @param array  $index
168
-     *          spatial index
169
-     */
170
-    public function findHashesForId($id, $index) {
171
-        $hashes = array();
172
-        foreach($index as $hash => $docIds) {
173
-            if(in_array($id, $docIds, false)) {
174
-                $hashes [] = $hash;
175
-            }
176
-        }
177
-        dbglog($hashes, "Found the following hashes for $id (should only be 1)");
178
-        return $hashes;
179
-    }
162
+	/**
163
+	 * Looks up the geohash(es) for the document in the index.
164
+	 *
165
+	 * @param String $id
166
+	 *          document ID
167
+	 * @param array  $index
168
+	 *          spatial index
169
+	 */
170
+	public function findHashesForId($id, $index) {
171
+		$hashes = array();
172
+		foreach($index as $hash => $docIds) {
173
+			if(in_array($id, $docIds, false)) {
174
+				$hashes [] = $hash;
175
+			}
176
+		}
177
+		dbglog($hashes, "Found the following hashes for $id (should only be 1)");
178
+		return $hashes;
179
+	}
180 180
 
181
-    /**
182
-     * Save spatial index.
183
-     */
184
-    private function saveIndex() {
185
-        return io_saveFile($this->idx_dir . '/spatial.idx', serialize($this->spatial_idx));
186
-    }
181
+	/**
182
+	 * Save spatial index.
183
+	 */
184
+	private function saveIndex() {
185
+		return io_saveFile($this->idx_dir . '/spatial.idx', serialize($this->spatial_idx));
186
+	}
187 187
 
188
-    /**
189
-     * Add an index entry for this file having EXIF / IPTC data.
190
-     *
191
-     * @param unknown_type $img Dokuwiki image
192
-     * @return boolean true when image was succesfully added to the index.
193
-     * @see http://php.net/manual/en/function.exif-read-data.php
194
-     *
195
-     * @see http://www.php.net/manual/en/function.iptcparse.php
196
-     */
197
-    public function indexImage($img) {
198
-        // test for supported files (jpeg only)
199
-        if(
200
-            (substr($img ['file'], -strlen('.jpg')) !== '.jpg') and
201
-            (substr($img ['file'], -strlen('.jpeg')) !== '.jpeg')) {
202
-            return false;
203
-        }
188
+	/**
189
+	 * Add an index entry for this file having EXIF / IPTC data.
190
+	 *
191
+	 * @param unknown_type $img Dokuwiki image
192
+	 * @return boolean true when image was succesfully added to the index.
193
+	 * @see http://php.net/manual/en/function.exif-read-data.php
194
+	 *
195
+	 * @see http://www.php.net/manual/en/function.iptcparse.php
196
+	 */
197
+	public function indexImage($img) {
198
+		// test for supported files (jpeg only)
199
+		if(
200
+			(substr($img ['file'], -strlen('.jpg')) !== '.jpg') and
201
+			(substr($img ['file'], -strlen('.jpeg')) !== '.jpeg')) {
202
+			return false;
203
+		}
204 204
 
205
-        $geometry = $this->getCoordsFromExif($img ['id']);
206
-        if(!$geometry) {
207
-            return false;
208
-        }
209
-        $geohash = $geometry->out('geohash');
210
-        // TODO truncate the geohash to something reasonable, otherwise they are
211
-        // useless as an indexing mechanism eg. u1h73weckdrmskdqec3c9 is far too
212
-        // precise, limit at ~9 as most GPS are not submeter accurate
213
-        return $this->addToIndex($geohash, 'media__' . $img ['id']);
214
-    }
205
+		$geometry = $this->getCoordsFromExif($img ['id']);
206
+		if(!$geometry) {
207
+			return false;
208
+		}
209
+		$geohash = $geometry->out('geohash');
210
+		// TODO truncate the geohash to something reasonable, otherwise they are
211
+		// useless as an indexing mechanism eg. u1h73weckdrmskdqec3c9 is far too
212
+		// precise, limit at ~9 as most GPS are not submeter accurate
213
+		return $this->addToIndex($geohash, 'media__' . $img ['id']);
214
+	}
215 215
 
216
-    /**
217
-     * retrieve GPS decimal coordinates from exif.
218
-     *
219
-     * @param
220
-     *          $id
221
-     * @return Point or false
222
-     */
223
-    public function getCoordsFromExif($id) {
224
-        $exif = exif_read_data(mediaFN($id), 0, true);
225
-        if(empty ($exif ['GPS'])) {
226
-            return false;
227
-        }
216
+	/**
217
+	 * retrieve GPS decimal coordinates from exif.
218
+	 *
219
+	 * @param
220
+	 *          $id
221
+	 * @return Point or false
222
+	 */
223
+	public function getCoordsFromExif($id) {
224
+		$exif = exif_read_data(mediaFN($id), 0, true);
225
+		if(empty ($exif ['GPS'])) {
226
+			return false;
227
+		}
228 228
 
229
-        $lat = $this->convertDMStoD(
230
-            array(
231
-                $exif ['GPS'] ['GPSLatitude'] [0],
232
-                $exif ['GPS'] ['GPSLatitude'] [1],
233
-                $exif ['GPS'] ['GPSLatitude'] [2],
234
-                $exif ['GPS'] ['GPSLatitudeRef']
235
-            )
236
-        );
229
+		$lat = $this->convertDMStoD(
230
+			array(
231
+				$exif ['GPS'] ['GPSLatitude'] [0],
232
+				$exif ['GPS'] ['GPSLatitude'] [1],
233
+				$exif ['GPS'] ['GPSLatitude'] [2],
234
+				$exif ['GPS'] ['GPSLatitudeRef']
235
+			)
236
+		);
237 237
 
238
-        $lon = $this->convertDMStoD(
239
-            array(
240
-                $exif ['GPS'] ['GPSLongitude'] [0],
241
-                $exif ['GPS'] ['GPSLongitude'] [1],
242
-                $exif ['GPS'] ['GPSLongitude'] [2],
243
-                $exif ['GPS'] ['GPSLongitudeRef']
244
-            )
245
-        );
238
+		$lon = $this->convertDMStoD(
239
+			array(
240
+				$exif ['GPS'] ['GPSLongitude'] [0],
241
+				$exif ['GPS'] ['GPSLongitude'] [1],
242
+				$exif ['GPS'] ['GPSLongitude'] [2],
243
+				$exif ['GPS'] ['GPSLongitudeRef']
244
+			)
245
+		);
246 246
 
247
-        return new Point($lon, $lat);
248
-    }
247
+		return new Point($lon, $lat);
248
+	}
249 249
 
250
-    /**
251
-     * convert DegreesMinutesSeconds to Decimal degrees.
252
-     *
253
-     * @param array $param array of rational DMS
254
-     * @return number
255
-     */
256
-    public function convertDMStoD($param) {
257
-        if(!is_array($param)) {
258
-            $param = array($param);
259
-        }
260
-        $deg = $this->convertRationaltoFloat($param [0]);
261
-        $min = $this->convertRationaltoFloat($param [1]) / 60;
262
-        $sec = $this->convertRationaltoFloat($param [2]) / 60 / 60;
263
-        // Hemisphere (N, S, W or E)
264
-        $hem = ($param [3] === 'N' || $param [3] === 'E') ? 1 : -1;
265
-        return $hem * ($deg + $min + $sec);
266
-    }
250
+	/**
251
+	 * convert DegreesMinutesSeconds to Decimal degrees.
252
+	 *
253
+	 * @param array $param array of rational DMS
254
+	 * @return number
255
+	 */
256
+	public function convertDMStoD($param) {
257
+		if(!is_array($param)) {
258
+			$param = array($param);
259
+		}
260
+		$deg = $this->convertRationaltoFloat($param [0]);
261
+		$min = $this->convertRationaltoFloat($param [1]) / 60;
262
+		$sec = $this->convertRationaltoFloat($param [2]) / 60 / 60;
263
+		// Hemisphere (N, S, W or E)
264
+		$hem = ($param [3] === 'N' || $param [3] === 'E') ? 1 : -1;
265
+		return $hem * ($deg + $min + $sec);
266
+	}
267 267
 
268
-    public function convertRationaltoFloat($param) {
269
-        // rational64u
270
-        $nums = explode('/', $param);
271
-        if(intval($nums[1]) > 0) {
272
-            return intval($nums[0]) / intval($nums[1]);
273
-        } else {
274
-            return intval($nums[0]);
275
-        }
276
-    }
268
+	public function convertRationaltoFloat($param) {
269
+		// rational64u
270
+		$nums = explode('/', $param);
271
+		if(intval($nums[1]) > 0) {
272
+			return intval($nums[0]) / intval($nums[1]);
273
+		} else {
274
+			return intval($nums[0]);
275
+		}
276
+	}
277 277
 
278
-    /**
279
-     * Deletes the page from the index.
280
-     *
281
-     * @param String $id
282
-     *          document ID
283
-     */
284
-    public function deleteFromIndex($id) {
285
-        // check the index for document
286
-        $knownHashes = $this->findHashesForId($id, $this->spatial_idx);
287
-        if(empty ($knownHashes)) {
288
-            return;
289
-        }
278
+	/**
279
+	 * Deletes the page from the index.
280
+	 *
281
+	 * @param String $id
282
+	 *          document ID
283
+	 */
284
+	public function deleteFromIndex($id) {
285
+		// check the index for document
286
+		$knownHashes = $this->findHashesForId($id, $this->spatial_idx);
287
+		if(empty ($knownHashes)) {
288
+			return;
289
+		}
290 290
 
291
-        // TODO shortcut, need to make sure there is only one element, if not the index is corrupt
292
-        $knownHash = $knownHashes [0];
293
-        $knownIds  = $this->spatial_idx [$knownHash];
294
-        $i         = array_search($id, $knownIds);
295
-        dbglog("removing: $knownIds[$i] from the index.");
296
-        unset ($knownIds [$i]);
297
-        $this->spatial_idx [$knownHash] = $knownIds;
298
-        if(empty ($this->spatial_idx [$knownHash])) {
299
-            // dbglog ( "removing key: $knownHash from the index." );
300
-            unset ($this->spatial_idx [$knownHash]);
301
-        }
302
-        $succes = $this->saveIndex();
303
-    }
291
+		// TODO shortcut, need to make sure there is only one element, if not the index is corrupt
292
+		$knownHash = $knownHashes [0];
293
+		$knownIds  = $this->spatial_idx [$knownHash];
294
+		$i         = array_search($id, $knownIds);
295
+		dbglog("removing: $knownIds[$i] from the index.");
296
+		unset ($knownIds [$i]);
297
+		$this->spatial_idx [$knownHash] = $knownIds;
298
+		if(empty ($this->spatial_idx [$knownHash])) {
299
+			// dbglog ( "removing key: $knownHash from the index." );
300
+			unset ($this->spatial_idx [$knownHash]);
301
+		}
302
+		$succes = $this->saveIndex();
303
+	}
304 304
 }
Please login to merge, or discard this patch.
Spacing   +20 added lines, -20 removed lines patch added patch discarded remove patch
@@ -46,7 +46,7 @@  discard block
 block discarded – undo
46 46
      * Constructor, initialises the spatial index.
47 47
      */
48 48
     public function __construct() {
49
-        if(!$geophp = &plugin_load('helper', 'geophp')) {
49
+        if (!$geophp = &plugin_load('helper', 'geophp')) {
50 50
             $message = 'helper_plugin_spatialhelper_index::spatialhelper_index: geophp plugin is not available.';
51 51
             msg($message, -1);
52 52
             return "";
@@ -55,7 +55,7 @@  discard block
 block discarded – undo
55 55
         global $conf;
56 56
         $this->idx_dir = $conf ['indexdir'];
57 57
         // test if there is a spatialindex, if not build one for the wiki
58
-        if(!@file_exists($this->idx_dir . '/spatial.idx')) {
58
+        if (!@file_exists($this->idx_dir . '/spatial.idx')) {
59 59
             // creates and stores the index
60 60
             $this->generateSpatialIndex();
61 61
         } else {
@@ -74,14 +74,14 @@  discard block
 block discarded – undo
74 74
         require_once(DOKU_INC . 'inc/search.php');
75 75
         $pages = array();
76 76
         search($pages, $conf ['datadir'], 'search_allpages', array());
77
-        foreach($pages as $page) {
77
+        foreach ($pages as $page) {
78 78
             $this->updateSpatialIndex($page ['id']);
79 79
         }
80 80
         // media
81 81
         $media = array();
82 82
         search($media, $conf ['mediadir'], 'search_media', array());
83
-        foreach($media as $medium) {
84
-            if($medium ['isimg']) {
83
+        foreach ($media as $medium) {
84
+            if ($medium ['isimg']) {
85 85
                 $this->indexImage($medium);
86 86
             }
87 87
         }
@@ -96,10 +96,10 @@  discard block
 block discarded – undo
96 96
      */
97 97
     public function updateSpatialIndex($id) {
98 98
         $geotags = p_get_metadata($id, 'geo');
99
-        if(empty ($geotags)) {
99
+        if (empty ($geotags)) {
100 100
             return false;
101 101
         }
102
-        if(empty ($geotags ['lon']) || empty ($geotags ['lat'])) {
102
+        if (empty ($geotags ['lon']) || empty ($geotags ['lat'])) {
103 103
             return false;
104 104
         }
105 105
         dbglog($geotags, "Geo metadata found for page $id");
@@ -120,14 +120,14 @@  discard block
 block discarded – undo
120 120
     private function addToIndex($geohash, $id) {
121 121
         $pageIds = array();
122 122
         // check index for key/geohash
123
-        if(!array_key_exists($geohash, $this->spatial_idx)) {
123
+        if (!array_key_exists($geohash, $this->spatial_idx)) {
124 124
             dbglog("Geohash $geohash not in index, just add $id.");
125 125
             $pageIds [] = $id;
126 126
         } else {
127 127
             dbglog('Geohash for document is in index, find it.');
128 128
             // check the index for document
129 129
             $knownHashes = $this->findHashesForId($id, $this->spatial_idx);
130
-            if(empty ($knownHashes)) {
130
+            if (empty ($knownHashes)) {
131 131
                 dbglog("No index record found for document $id, just add");
132 132
                 $pageIds    = $this->spatial_idx [$geohash];
133 133
                 $pageIds [] = $id;
@@ -135,12 +135,12 @@  discard block
 block discarded – undo
135 135
             // TODO shortcut, need to make sure there is only one element, if not the index is corrupt
136 136
             $knownHash = $knownHashes [0];
137 137
 
138
-            if($knownHash == $geohash) {
138
+            if ($knownHash == $geohash) {
139 139
                 dbglog("Document $id was found in index and has the same geohash, nothing to do.");
140 140
                 return true;
141 141
             }
142 142
 
143
-            if(!empty ($knownHash)) {
143
+            if (!empty ($knownHash)) {
144 144
                 dbglog("Document/media $id was found in index but has different geohash (it moved).");
145 145
                 $knownIds = $this->spatial_idx [$knownHash];
146 146
                 dbglog($knownIds, "Known id's for this hash:");
@@ -169,8 +169,8 @@  discard block
 block discarded – undo
169 169
      */
170 170
     public function findHashesForId($id, $index) {
171 171
         $hashes = array();
172
-        foreach($index as $hash => $docIds) {
173
-            if(in_array($id, $docIds, false)) {
172
+        foreach ($index as $hash => $docIds) {
173
+            if (in_array($id, $docIds, false)) {
174 174
                 $hashes [] = $hash;
175 175
             }
176 176
         }
@@ -196,14 +196,14 @@  discard block
 block discarded – undo
196 196
      */
197 197
     public function indexImage($img) {
198 198
         // test for supported files (jpeg only)
199
-        if(
199
+        if (
200 200
             (substr($img ['file'], -strlen('.jpg')) !== '.jpg') and
201 201
             (substr($img ['file'], -strlen('.jpeg')) !== '.jpeg')) {
202 202
             return false;
203 203
         }
204 204
 
205 205
         $geometry = $this->getCoordsFromExif($img ['id']);
206
-        if(!$geometry) {
206
+        if (!$geometry) {
207 207
             return false;
208 208
         }
209 209
         $geohash = $geometry->out('geohash');
@@ -222,7 +222,7 @@  discard block
 block discarded – undo
222 222
      */
223 223
     public function getCoordsFromExif($id) {
224 224
         $exif = exif_read_data(mediaFN($id), 0, true);
225
-        if(empty ($exif ['GPS'])) {
225
+        if (empty ($exif ['GPS'])) {
226 226
             return false;
227 227
         }
228 228
 
@@ -254,7 +254,7 @@  discard block
 block discarded – undo
254 254
      * @return number
255 255
      */
256 256
     public function convertDMStoD($param) {
257
-        if(!is_array($param)) {
257
+        if (!is_array($param)) {
258 258
             $param = array($param);
259 259
         }
260 260
         $deg = $this->convertRationaltoFloat($param [0]);
@@ -268,7 +268,7 @@  discard block
 block discarded – undo
268 268
     public function convertRationaltoFloat($param) {
269 269
         // rational64u
270 270
         $nums = explode('/', $param);
271
-        if(intval($nums[1]) > 0) {
271
+        if (intval($nums[1]) > 0) {
272 272
             return intval($nums[0]) / intval($nums[1]);
273 273
         } else {
274 274
             return intval($nums[0]);
@@ -284,7 +284,7 @@  discard block
 block discarded – undo
284 284
     public function deleteFromIndex($id) {
285 285
         // check the index for document
286 286
         $knownHashes = $this->findHashesForId($id, $this->spatial_idx);
287
-        if(empty ($knownHashes)) {
287
+        if (empty ($knownHashes)) {
288 288
             return;
289 289
         }
290 290
 
@@ -295,7 +295,7 @@  discard block
 block discarded – undo
295 295
         dbglog("removing: $knownIds[$i] from the index.");
296 296
         unset ($knownIds [$i]);
297 297
         $this->spatial_idx [$knownHash] = $knownIds;
298
-        if(empty ($this->spatial_idx [$knownHash])) {
298
+        if (empty ($this->spatial_idx [$knownHash])) {
299 299
             // dbglog ( "removing key: $knownHash from the index." );
300 300
             unset ($this->spatial_idx [$knownHash]);
301 301
         }
Please login to merge, or discard this patch.
action.php 2 patches
Indentation   +398 added lines, -398 removed lines patch added patch discarded remove patch
@@ -25,402 +25,402 @@
 block discarded – undo
25 25
  */
26 26
 class action_plugin_spatialhelper extends DokuWiki_Action_Plugin {
27 27
 
28
-    /**
29
-     * Register for events.
30
-     *
31
-     * @param Doku_Event_Handler $controller
32
-     *          DokuWiki's event controller object. Also available as global $EVENT_HANDLER
33
-     */
34
-    public function register(Doku_Event_Handler $controller) {
35
-        // listen for page add / delete events
36
-        // http://www.dokuwiki.org/devel:event:indexer_page_add
37
-        $controller->register_hook('INDEXER_PAGE_ADD', 'BEFORE', $this, 'handleIndexerPageAdd');
38
-        $controller->register_hook('IO_WIKIPAGE_WRITE', 'BEFORE', $this, 'removeFromIndex');
39
-
40
-        // http://www.dokuwiki.org/devel:event:sitemap_generate
41
-        $controller->register_hook('SITEMAP_GENERATE', 'BEFORE', $this, 'handleSitemapGenerateBefore');
42
-        // using after will only trigger us if a sitemap was actually created
43
-        $controller->register_hook('SITEMAP_GENERATE', 'AFTER', $this, 'handleSitemapGenerateAfter');
44
-
45
-        // handle actions we know of
46
-        $controller->register_hook('ACTION_ACT_PREPROCESS', 'BEFORE', $this, 'handleActionActPreprocess', array());
47
-        // handle HTML eg. /dokuwiki/doku.php?id=start&do=findnearby&geohash=u15vk4
48
-        $controller->register_hook(
49
-            'TPL_ACT_UNKNOWN', 'BEFORE', $this, 'findnearby', array(
50
-            'format' => 'HTML'
51
-        )
52
-        );
53
-        // handles AJAX/json eg: jQuery.post("/dokuwiki/lib/exe/ajax.php?id=start&call=findnearby&geohash=u15vk4");
54
-        $controller->register_hook(
55
-            'AJAX_CALL_UNKNOWN', 'BEFORE', $this, 'findnearby', array(
56
-            'format' => 'JSON'
57
-        )
58
-        );
59
-
60
-        // listen for media uploads and deletes
61
-        $controller->register_hook('MEDIA_UPLOAD_FINISH', 'BEFORE', $this, 'handleMediaUploaded', array());
62
-        $controller->register_hook('MEDIA_DELETE_FILE', 'BEFORE', $this, 'handleMediaDeleted', array());
63
-
64
-        $controller->register_hook('TPL_METAHEADER_OUTPUT', 'BEFORE', $this, 'handleMetaheaderOutput');
65
-    }
66
-
67
-    /**
68
-     * Update the spatial index for the page.
69
-     *
70
-     * @param Doku_Event $event
71
-     *          event object by reference
72
-     * @param object     $param
73
-     *          the parameters passed to register_hook when this handler was registered
74
-     */
75
-    public function handleIndexerPageAdd(Doku_Event $event, $param) {
76
-        // $event→data['page'] – the page id
77
-        // $event→data['body'] – empty, can be filled by additional content to index by your plugin
78
-        // $event→data['metadata'] – the metadata that shall be indexed. This is an array where the keys are the
79
-        //    metadata indexes and the value a string or an array of strings with the values.
80
-        //    title and relation_references will already be set.
81
-        $id      = $event->data ['page'];
82
-        $indexer = &plugin_load('helper', 'spatialhelper_index');
83
-        $entries = $indexer->updateSpatialIndex($id);
84
-    }
85
-
86
-    /**
87
-     * Update the spatial index, removing the page.
88
-     *
89
-     * @param Doku_Event $event
90
-     *          event object by reference
91
-     * @param object     $param
92
-     *          the parameters passed to register_hook when this handler was registered
93
-     */
94
-    public function removeFromIndex(Doku_Event &$event, $param) {
95
-        // event data:
96
-        // $data[0] – The raw arguments for io_saveFile as an array. Do not change file path.
97
-        // $data[0][0] – the file path.
98
-        // $data[0][1] – the content to be saved, and may be modified.
99
-        // $data[1] – ns: The colon separated namespace path minus the trailing page name. (false if root ns)
100
-        // $data[2] – page_name: The wiki page name.
101
-        // $data[3] – rev: The page revision, false for current wiki pages.
102
-
103
-        dbglog($event->data, "Event data in removeFromIndex.");
104
-        if(@file_exists($event->data [0] [0])) {
105
-            // file not new
106
-            if(!$event->data [0] [1]) {
107
-                // file is empty, page is being deleted
108
-                if(empty ($event->data [1])) {
109
-                    // root namespace
110
-                    $id = $event->data [2];
111
-                } else {
112
-                    $id = $event->data [1] . ":" . $event->data [2];
113
-                }
114
-                $indexer = &plugin_load('helper', 'spatialhelper_index');
115
-                if($indexer) {
116
-                    $indexer->deleteFromIndex($id);
117
-                }
118
-            }
119
-        }
120
-    }
121
-
122
-    /**
123
-     * Add a new SitemapItem object that points to the KML of public geocoded pages.
124
-     *
125
-     * @param Doku_Event $event
126
-     * @param unknown    $param
127
-     */
128
-    public function handleSitemapGenerateBefore(Doku_Event $event, $param) {
129
-        $path                     = mediaFN($this->getConf('media_kml'));
130
-        $lastmod                  = @filemtime($path);
131
-        $event->data ['items'] [] = new Item(ml($this->getConf('media_kml'), '', true, '&amp;', true), $lastmod);
132
-        //dbglog($event->data ['items'],
133
-        //  "Added a new SitemapItem object that points to the KML of public geocoded pages.");
134
-    }
135
-
136
-    /**
137
-     * Create a spatial sitemap or attach the geo/kml map to the sitemap.
138
-     *
139
-     * @param Doku_Event $event
140
-     *          event object by reference, not used
141
-     * @param mixed      $param
142
-     *          parameter array, not used
143
-     */
144
-    public function handleSitemapGenerateAfter(Doku_Event $event, $param) {
145
-        // $event→data['items']: Array of SitemapItem instances, the array of sitemap items that already
146
-        //      contains all public pages of the wiki
147
-        // $event→data['sitemap']: The path of the file the sitemap will be saved to.
148
-        if($helper = &plugin_load('helper', 'spatialhelper_sitemap')) {
149
-            // dbglog($helper, "createSpatialSitemap loaded helper.");
150
-
151
-            $kml = $helper->createKMLSitemap($this->getConf('media_kml'));
152
-            $rss = $helper->createGeoRSSSitemap($this->getConf('media_georss'));
153
-
154
-            if(!empty ($this->getConf('sitemap_namespaces'))) {
155
-                $namespaces = array_map('trim', explode("\n", $this->getConf('sitemap_namespaces')));
156
-                foreach($namespaces as $namespace) {
157
-                    $kmlN = $helper->createKMLSitemap($namespace . $this->getConf('media_kml'));
158
-                    $rssN = $helper->createGeoRSSSitemap($namespace . $this->getConf('media_georss'));
159
-                    dbglog(
160
-                        $kmlN && $rssN,
161
-                        "handleSitemapGenerateAfter, created KML / GeoRSS sitemap in $namespace, succes: "
162
-                    );
163
-                }
164
-            }
165
-            return $kml && $rss;
166
-        } else {
167
-            dbglog($helper, "createSpatialSitemap NOT loaded helper.");
168
-        }
169
-    }
170
-
171
-    /**
172
-     * trap findnearby action.
173
-     * This addional handler is required as described at: https://www.dokuwiki.org/devel:event:tpl_act_unknown
174
-     *
175
-     * @param Doku_Event $event
176
-     *          event object by reference
177
-     * @param mixed      $param
178
-     *          not used
179
-     */
180
-    public function handleActionActPreprocess(Doku_Event $event, $param) {
181
-        if($event->data != 'findnearby') {
182
-            return;
183
-        }
184
-        $event->preventDefault();
185
-    }
186
-
187
-    /**
188
-     * handle findnearby action.
189
-     *
190
-     * @param Doku_Event $event
191
-     *          event object by reference
192
-     * @param mixed      $param
193
-     *          associative array with keys
194
-     *          'format'=> HTML | JSON
195
-     */
196
-    public function findnearby(Doku_Event &$event, $param) {
197
-        if($event->data != 'findnearby') {
198
-            return;
199
-        }
200
-        $event->preventDefault();
201
-
202
-        global $INPUT;
203
-        if($helper = &plugin_load('helper', 'spatialhelper_search')) {
204
-            if($INPUT->has('lat') && $INPUT->has('lon')) {
205
-                $results = $helper->findNearbyLatLon($INPUT->param('lat'), $INPUT->param('lon'));
206
-            } elseif($INPUT->has('geohash')) {
207
-                $results = $helper->findNearby($INPUT->str('geohash'));
208
-            } else {
209
-                $results = array(
210
-                    'error' => hsc($this->getLang('invalidinput'))
211
-                );
212
-            }
213
-        }
214
-
215
-        $showMedia = $INPUT->bool('showMedia', true);
216
-
217
-        switch($param['format']) {
218
-            case 'JSON' :
219
-                $this->printJSON($results);
220
-                break;
221
-            case 'HTML' :
222
-                // fall through to default
223
-            default :
224
-                $this->printHTML($results, $showMedia);
225
-                break;
226
-        }
227
-    }
228
-
229
-    /**
230
-     * Print seachresults as HTML lists.
231
-     *
232
-     * @param array $searchresults
233
-     */
234
-    private function printJSON($searchresults) {
235
-        require_once DOKU_INC . 'inc/JSON.php';
236
-        $json = new JSON();
237
-        header('Content-Type: application/json');
238
-        print $json->encode($searchresults);
239
-    }
240
-
241
-    /**
242
-     * Print seachresults as HTML lists.
243
-     *
244
-     * @param array   $searchresults
245
-     * @param boolean $showMedia
246
-     */
247
-    private function printHTML($searchresults, $showMedia = true) {
248
-        $pages   = (array) ($searchresults ['pages']);
249
-        $media   = (array) $searchresults ['media'];
250
-        $lat     = (float) $searchresults ['lat'];
251
-        $lon     = (float) $searchresults ['lon'];
252
-        $geohash = (string) $searchresults ['geohash'];
253
-
254
-        if(isset ($searchresults ['error'])) {
255
-            print '<div class="level1"><p>' . hsc($results ['error']) . '</p></div>';
256
-            return;
257
-        }
258
-
259
-        // print a HTML list
260
-        print '<h1>' . $this->getLang('results_header') . '</h1>' . DOKU_LF;
261
-        print '<div class="level1">' . DOKU_LF;
262
-        if(!empty ($pages)) {
263
-            $pagelist = '<ol>' . DOKU_LF;
264
-            foreach($pages as $page) {
265
-                $pagelist .= '<li>' . html_wikilink(
266
-                        ':' . $page ['id'], useHeading('navigation') ? null :
267
-                        noNS($page ['id'])
268
-                    ) . ' (' . $this->getLang('results_distance_prefix')
269
-                    . $page ['distance'] . '&nbsp;m) ' . $page ['description'] . '</li>' . DOKU_LF;
270
-            }
271
-            $pagelist .= '</ol>' . DOKU_LF;
272
-
273
-            print '<h2>' . $this->getLang('results_pages') . hsc(
274
-                    ' lat;lon: ' . $lat . ';' . $lon
275
-                    . ' (geohash: ' . $geohash . ')'
276
-                ) . '</h2>';
277
-            print '<div class="level2">' . DOKU_LF;
278
-            print $pagelist;
279
-            print '</div>' . DOKU_LF;
280
-        } else {
281
-            print '<p>' . hsc($this->getLang('nothingfound')) . '</p>';
282
-        }
283
-
284
-        if(!empty ($media) && $showMedia) {
285
-            $pagelist = '<ol>' . DOKU_LF;
286
-            foreach($media as $m) {
287
-                $opts       = array();
288
-                $link       = ml($m ['id'], $opts, false, '&amp;', false);
289
-                $opts ['w'] = '100';
290
-                $src        = ml($m ['id'], $opts);
291
-                $pagelist   .= '<li><a href="' . $link . '"><img src="' . $src . '"></a> ('
292
-                    . $this->getLang('results_distance_prefix') . $page ['distance'] . '&nbsp;m) ' . hsc($desc)
293
-                    . '</li>' . DOKU_LF;
294
-            }
295
-            $pagelist .= '</ol>' . DOKU_LF;
296
-
297
-            print '<h2>' . $this->getLang('results_media') . hsc(
298
-                    ' lat;lon: ' . $lat . ';' . $lon
299
-                    . ' (geohash: ' . $geohash . ')'
300
-                ) . '</h2>' . DOKU_LF;
301
-            print '<div class="level2">' . DOKU_LF;
302
-            print $pagelist;
303
-            print '</div>' . DOKU_LF;
304
-        }
305
-        print '<p>' . $this->getLang('results_precision') . $searchresults ['precision'] . ' m. ';
306
-        if(strlen($geohash) > 1) {
307
-            $url = wl(
308
-                getID(), array(
309
-                'do'      => 'findnearby',
310
-                'geohash' => substr($geohash, 0, -1)
311
-            )
312
-            );
313
-            print '<a href="' . $url . '" class="findnearby">' . $this->getLang('search_largerarea') . '</a>.</p>'
314
-                . DOKU_LF;
315
-        }
316
-        print '</div>' . DOKU_LF;
317
-    }
318
-
319
-    /**
320
-     * add media to spatial index.
321
-     *
322
-     * @param Doku_Event $event
323
-     *          event object by reference
324
-     * @param unknown    $param
325
-     */
326
-    public function handleMediaUploaded(Doku_Event &$event, $param) {
327
-        // data[0] temporary file name (read from $_FILES)
328
-        // data[1] file name of the file being uploaded
329
-        // data[2] future directory id of the file being uploaded
330
-        // data[3] the mime type of the file being uploaded
331
-        // data[4] true if the uploaded file exists already
332
-        // data[5] (since 2011-02-06) the PHP function used to move the file to the correct location
333
-
334
-        dbglog($event->data, "handleMediaUploaded::event data");
335
-
336
-        // check the list of mimetypes
337
-        // if it's a supported type call appropriate index function
338
-        if(substr_compare($event->data [3], 'image/jpeg', 0)) {
339
-            $indexer = plugin_load('helper', 'spatialhelper_index');
340
-            if($indexer) {
341
-                $indexer->indexImage($event->data [2], $event->data [1]);
342
-            }
343
-        }
344
-        // TODO add image/tiff
345
-        // TODO kml, gpx, geojson...
346
-    }
347
-
348
-    /**
349
-     * removes the media from the index.
350
-     */
351
-    public function handleMediaDeleted(Doku_Event &$event, $param) {
352
-        // data['id'] ID data['unl'] unlink return code
353
-        // data['del'] Namespace directory unlink return code
354
-        // data['name'] file name data['path'] full path to the file
355
-        // data['size'] file size
356
-
357
-        dbglog($event->data, "handleMediaDeleted::event data");
358
-
359
-        // remove the media id from the index
360
-        $indexer = &plugin_load('helper', 'spatialhelper_index');
361
-        if($indexer) {
362
-            $indexer->deleteFromIndex('media__' . $event->data ['id']);
363
-        }
364
-    }
365
-
366
-    /**
367
-     * add a link to the spatial sitemap files in the header.
368
-     *
369
-     * @param Doku_Event   $event
370
-     *          the DokuWiki event. $event->data is a two-dimensional
371
-     *          array of all meta headers. The keys are meta, link and script.
372
-     * @param unknown_type $param
373
-     *
374
-     * @see http://www.dokuwiki.org/devel:event:tpl_metaheader_output
375
-     */
376
-    public function handleMetaheaderOutput(Doku_Event $event, $param) {
377
-        // TODO maybe test for exist
378
-        $event->data ["link"] [] = array(
379
-            "type"  => "application/atom+xml",
380
-            "rel"   => "alternate",
381
-            "href"  => ml($this->getConf('media_georss')),
382
-            "title" => "Spatial ATOM Feed"
383
-        );
384
-        $event->data ["link"] [] = array(
385
-            "type"  => "application/vnd.google-earth.kml+xml",
386
-            "rel"   => "alternate",
387
-            "href"  => ml($this->getConf('media_kml')),
388
-            "title" => "KML Sitemap"
389
-        );
390
-    }
391
-
392
-    /**
393
-     * Calculate a new coordinate based on start, distance and bearing
394
-     *
395
-     * @param $start array
396
-     *               - start coordinate as decimal lat/lon pair
397
-     * @param $dist  float
398
-     *               - distance in kilometers
399
-     * @param $brng  float
400
-     *               - bearing in degrees (compass direction)
401
-     */
402
-    private function geoDestination($start, $dist, $brng) {
403
-        $lat1 = toRad($start [0]);
404
-        $lon1 = toRad($start [1]);
405
-        // http://en.wikipedia.org/wiki/Earth_radius
406
-        // average earth radius in km
407
-        $dist = $dist / 6371.01;
408
-        $brng = toRad($brng);
409
-
410
-        $lon2 = $lon1 + atan2(sin($brng) * sin($dist) * cos($lat1), cos($dist) - sin($lat1) * sin($lat2));
411
-        $lon2 = fmod(($lon2 + 3 * pi()), (2 * pi())) - pi();
412
-
413
-        return array(
414
-            toDeg($lat2),
415
-            toDeg($lon2)
416
-        );
417
-    }
418
-
419
-    private function toRad($deg) {
420
-        return $deg * pi() / 180;
421
-    }
422
-
423
-    private function toDeg($rad) {
424
-        return $rad * 180 / pi();
425
-    }
28
+	/**
29
+	 * Register for events.
30
+	 *
31
+	 * @param Doku_Event_Handler $controller
32
+	 *          DokuWiki's event controller object. Also available as global $EVENT_HANDLER
33
+	 */
34
+	public function register(Doku_Event_Handler $controller) {
35
+		// listen for page add / delete events
36
+		// http://www.dokuwiki.org/devel:event:indexer_page_add
37
+		$controller->register_hook('INDEXER_PAGE_ADD', 'BEFORE', $this, 'handleIndexerPageAdd');
38
+		$controller->register_hook('IO_WIKIPAGE_WRITE', 'BEFORE', $this, 'removeFromIndex');
39
+
40
+		// http://www.dokuwiki.org/devel:event:sitemap_generate
41
+		$controller->register_hook('SITEMAP_GENERATE', 'BEFORE', $this, 'handleSitemapGenerateBefore');
42
+		// using after will only trigger us if a sitemap was actually created
43
+		$controller->register_hook('SITEMAP_GENERATE', 'AFTER', $this, 'handleSitemapGenerateAfter');
44
+
45
+		// handle actions we know of
46
+		$controller->register_hook('ACTION_ACT_PREPROCESS', 'BEFORE', $this, 'handleActionActPreprocess', array());
47
+		// handle HTML eg. /dokuwiki/doku.php?id=start&do=findnearby&geohash=u15vk4
48
+		$controller->register_hook(
49
+			'TPL_ACT_UNKNOWN', 'BEFORE', $this, 'findnearby', array(
50
+			'format' => 'HTML'
51
+		)
52
+		);
53
+		// handles AJAX/json eg: jQuery.post("/dokuwiki/lib/exe/ajax.php?id=start&call=findnearby&geohash=u15vk4");
54
+		$controller->register_hook(
55
+			'AJAX_CALL_UNKNOWN', 'BEFORE', $this, 'findnearby', array(
56
+			'format' => 'JSON'
57
+		)
58
+		);
59
+
60
+		// listen for media uploads and deletes
61
+		$controller->register_hook('MEDIA_UPLOAD_FINISH', 'BEFORE', $this, 'handleMediaUploaded', array());
62
+		$controller->register_hook('MEDIA_DELETE_FILE', 'BEFORE', $this, 'handleMediaDeleted', array());
63
+
64
+		$controller->register_hook('TPL_METAHEADER_OUTPUT', 'BEFORE', $this, 'handleMetaheaderOutput');
65
+	}
66
+
67
+	/**
68
+	 * Update the spatial index for the page.
69
+	 *
70
+	 * @param Doku_Event $event
71
+	 *          event object by reference
72
+	 * @param object     $param
73
+	 *          the parameters passed to register_hook when this handler was registered
74
+	 */
75
+	public function handleIndexerPageAdd(Doku_Event $event, $param) {
76
+		// $event→data['page'] – the page id
77
+		// $event→data['body'] – empty, can be filled by additional content to index by your plugin
78
+		// $event→data['metadata'] – the metadata that shall be indexed. This is an array where the keys are the
79
+		//    metadata indexes and the value a string or an array of strings with the values.
80
+		//    title and relation_references will already be set.
81
+		$id      = $event->data ['page'];
82
+		$indexer = &plugin_load('helper', 'spatialhelper_index');
83
+		$entries = $indexer->updateSpatialIndex($id);
84
+	}
85
+
86
+	/**
87
+	 * Update the spatial index, removing the page.
88
+	 *
89
+	 * @param Doku_Event $event
90
+	 *          event object by reference
91
+	 * @param object     $param
92
+	 *          the parameters passed to register_hook when this handler was registered
93
+	 */
94
+	public function removeFromIndex(Doku_Event &$event, $param) {
95
+		// event data:
96
+		// $data[0] – The raw arguments for io_saveFile as an array. Do not change file path.
97
+		// $data[0][0] – the file path.
98
+		// $data[0][1] – the content to be saved, and may be modified.
99
+		// $data[1] – ns: The colon separated namespace path minus the trailing page name. (false if root ns)
100
+		// $data[2] – page_name: The wiki page name.
101
+		// $data[3] – rev: The page revision, false for current wiki pages.
102
+
103
+		dbglog($event->data, "Event data in removeFromIndex.");
104
+		if(@file_exists($event->data [0] [0])) {
105
+			// file not new
106
+			if(!$event->data [0] [1]) {
107
+				// file is empty, page is being deleted
108
+				if(empty ($event->data [1])) {
109
+					// root namespace
110
+					$id = $event->data [2];
111
+				} else {
112
+					$id = $event->data [1] . ":" . $event->data [2];
113
+				}
114
+				$indexer = &plugin_load('helper', 'spatialhelper_index');
115
+				if($indexer) {
116
+					$indexer->deleteFromIndex($id);
117
+				}
118
+			}
119
+		}
120
+	}
121
+
122
+	/**
123
+	 * Add a new SitemapItem object that points to the KML of public geocoded pages.
124
+	 *
125
+	 * @param Doku_Event $event
126
+	 * @param unknown    $param
127
+	 */
128
+	public function handleSitemapGenerateBefore(Doku_Event $event, $param) {
129
+		$path                     = mediaFN($this->getConf('media_kml'));
130
+		$lastmod                  = @filemtime($path);
131
+		$event->data ['items'] [] = new Item(ml($this->getConf('media_kml'), '', true, '&amp;', true), $lastmod);
132
+		//dbglog($event->data ['items'],
133
+		//  "Added a new SitemapItem object that points to the KML of public geocoded pages.");
134
+	}
135
+
136
+	/**
137
+	 * Create a spatial sitemap or attach the geo/kml map to the sitemap.
138
+	 *
139
+	 * @param Doku_Event $event
140
+	 *          event object by reference, not used
141
+	 * @param mixed      $param
142
+	 *          parameter array, not used
143
+	 */
144
+	public function handleSitemapGenerateAfter(Doku_Event $event, $param) {
145
+		// $event→data['items']: Array of SitemapItem instances, the array of sitemap items that already
146
+		//      contains all public pages of the wiki
147
+		// $event→data['sitemap']: The path of the file the sitemap will be saved to.
148
+		if($helper = &plugin_load('helper', 'spatialhelper_sitemap')) {
149
+			// dbglog($helper, "createSpatialSitemap loaded helper.");
150
+
151
+			$kml = $helper->createKMLSitemap($this->getConf('media_kml'));
152
+			$rss = $helper->createGeoRSSSitemap($this->getConf('media_georss'));
153
+
154
+			if(!empty ($this->getConf('sitemap_namespaces'))) {
155
+				$namespaces = array_map('trim', explode("\n", $this->getConf('sitemap_namespaces')));
156
+				foreach($namespaces as $namespace) {
157
+					$kmlN = $helper->createKMLSitemap($namespace . $this->getConf('media_kml'));
158
+					$rssN = $helper->createGeoRSSSitemap($namespace . $this->getConf('media_georss'));
159
+					dbglog(
160
+						$kmlN && $rssN,
161
+						"handleSitemapGenerateAfter, created KML / GeoRSS sitemap in $namespace, succes: "
162
+					);
163
+				}
164
+			}
165
+			return $kml && $rss;
166
+		} else {
167
+			dbglog($helper, "createSpatialSitemap NOT loaded helper.");
168
+		}
169
+	}
170
+
171
+	/**
172
+	 * trap findnearby action.
173
+	 * This addional handler is required as described at: https://www.dokuwiki.org/devel:event:tpl_act_unknown
174
+	 *
175
+	 * @param Doku_Event $event
176
+	 *          event object by reference
177
+	 * @param mixed      $param
178
+	 *          not used
179
+	 */
180
+	public function handleActionActPreprocess(Doku_Event $event, $param) {
181
+		if($event->data != 'findnearby') {
182
+			return;
183
+		}
184
+		$event->preventDefault();
185
+	}
186
+
187
+	/**
188
+	 * handle findnearby action.
189
+	 *
190
+	 * @param Doku_Event $event
191
+	 *          event object by reference
192
+	 * @param mixed      $param
193
+	 *          associative array with keys
194
+	 *          'format'=> HTML | JSON
195
+	 */
196
+	public function findnearby(Doku_Event &$event, $param) {
197
+		if($event->data != 'findnearby') {
198
+			return;
199
+		}
200
+		$event->preventDefault();
201
+
202
+		global $INPUT;
203
+		if($helper = &plugin_load('helper', 'spatialhelper_search')) {
204
+			if($INPUT->has('lat') && $INPUT->has('lon')) {
205
+				$results = $helper->findNearbyLatLon($INPUT->param('lat'), $INPUT->param('lon'));
206
+			} elseif($INPUT->has('geohash')) {
207
+				$results = $helper->findNearby($INPUT->str('geohash'));
208
+			} else {
209
+				$results = array(
210
+					'error' => hsc($this->getLang('invalidinput'))
211
+				);
212
+			}
213
+		}
214
+
215
+		$showMedia = $INPUT->bool('showMedia', true);
216
+
217
+		switch($param['format']) {
218
+			case 'JSON' :
219
+				$this->printJSON($results);
220
+				break;
221
+			case 'HTML' :
222
+				// fall through to default
223
+			default :
224
+				$this->printHTML($results, $showMedia);
225
+				break;
226
+		}
227
+	}
228
+
229
+	/**
230
+	 * Print seachresults as HTML lists.
231
+	 *
232
+	 * @param array $searchresults
233
+	 */
234
+	private function printJSON($searchresults) {
235
+		require_once DOKU_INC . 'inc/JSON.php';
236
+		$json = new JSON();
237
+		header('Content-Type: application/json');
238
+		print $json->encode($searchresults);
239
+	}
240
+
241
+	/**
242
+	 * Print seachresults as HTML lists.
243
+	 *
244
+	 * @param array   $searchresults
245
+	 * @param boolean $showMedia
246
+	 */
247
+	private function printHTML($searchresults, $showMedia = true) {
248
+		$pages   = (array) ($searchresults ['pages']);
249
+		$media   = (array) $searchresults ['media'];
250
+		$lat     = (float) $searchresults ['lat'];
251
+		$lon     = (float) $searchresults ['lon'];
252
+		$geohash = (string) $searchresults ['geohash'];
253
+
254
+		if(isset ($searchresults ['error'])) {
255
+			print '<div class="level1"><p>' . hsc($results ['error']) . '</p></div>';
256
+			return;
257
+		}
258
+
259
+		// print a HTML list
260
+		print '<h1>' . $this->getLang('results_header') . '</h1>' . DOKU_LF;
261
+		print '<div class="level1">' . DOKU_LF;
262
+		if(!empty ($pages)) {
263
+			$pagelist = '<ol>' . DOKU_LF;
264
+			foreach($pages as $page) {
265
+				$pagelist .= '<li>' . html_wikilink(
266
+						':' . $page ['id'], useHeading('navigation') ? null :
267
+						noNS($page ['id'])
268
+					) . ' (' . $this->getLang('results_distance_prefix')
269
+					. $page ['distance'] . '&nbsp;m) ' . $page ['description'] . '</li>' . DOKU_LF;
270
+			}
271
+			$pagelist .= '</ol>' . DOKU_LF;
272
+
273
+			print '<h2>' . $this->getLang('results_pages') . hsc(
274
+					' lat;lon: ' . $lat . ';' . $lon
275
+					. ' (geohash: ' . $geohash . ')'
276
+				) . '</h2>';
277
+			print '<div class="level2">' . DOKU_LF;
278
+			print $pagelist;
279
+			print '</div>' . DOKU_LF;
280
+		} else {
281
+			print '<p>' . hsc($this->getLang('nothingfound')) . '</p>';
282
+		}
283
+
284
+		if(!empty ($media) && $showMedia) {
285
+			$pagelist = '<ol>' . DOKU_LF;
286
+			foreach($media as $m) {
287
+				$opts       = array();
288
+				$link       = ml($m ['id'], $opts, false, '&amp;', false);
289
+				$opts ['w'] = '100';
290
+				$src        = ml($m ['id'], $opts);
291
+				$pagelist   .= '<li><a href="' . $link . '"><img src="' . $src . '"></a> ('
292
+					. $this->getLang('results_distance_prefix') . $page ['distance'] . '&nbsp;m) ' . hsc($desc)
293
+					. '</li>' . DOKU_LF;
294
+			}
295
+			$pagelist .= '</ol>' . DOKU_LF;
296
+
297
+			print '<h2>' . $this->getLang('results_media') . hsc(
298
+					' lat;lon: ' . $lat . ';' . $lon
299
+					. ' (geohash: ' . $geohash . ')'
300
+				) . '</h2>' . DOKU_LF;
301
+			print '<div class="level2">' . DOKU_LF;
302
+			print $pagelist;
303
+			print '</div>' . DOKU_LF;
304
+		}
305
+		print '<p>' . $this->getLang('results_precision') . $searchresults ['precision'] . ' m. ';
306
+		if(strlen($geohash) > 1) {
307
+			$url = wl(
308
+				getID(), array(
309
+				'do'      => 'findnearby',
310
+				'geohash' => substr($geohash, 0, -1)
311
+			)
312
+			);
313
+			print '<a href="' . $url . '" class="findnearby">' . $this->getLang('search_largerarea') . '</a>.</p>'
314
+				. DOKU_LF;
315
+		}
316
+		print '</div>' . DOKU_LF;
317
+	}
318
+
319
+	/**
320
+	 * add media to spatial index.
321
+	 *
322
+	 * @param Doku_Event $event
323
+	 *          event object by reference
324
+	 * @param unknown    $param
325
+	 */
326
+	public function handleMediaUploaded(Doku_Event &$event, $param) {
327
+		// data[0] temporary file name (read from $_FILES)
328
+		// data[1] file name of the file being uploaded
329
+		// data[2] future directory id of the file being uploaded
330
+		// data[3] the mime type of the file being uploaded
331
+		// data[4] true if the uploaded file exists already
332
+		// data[5] (since 2011-02-06) the PHP function used to move the file to the correct location
333
+
334
+		dbglog($event->data, "handleMediaUploaded::event data");
335
+
336
+		// check the list of mimetypes
337
+		// if it's a supported type call appropriate index function
338
+		if(substr_compare($event->data [3], 'image/jpeg', 0)) {
339
+			$indexer = plugin_load('helper', 'spatialhelper_index');
340
+			if($indexer) {
341
+				$indexer->indexImage($event->data [2], $event->data [1]);
342
+			}
343
+		}
344
+		// TODO add image/tiff
345
+		// TODO kml, gpx, geojson...
346
+	}
347
+
348
+	/**
349
+	 * removes the media from the index.
350
+	 */
351
+	public function handleMediaDeleted(Doku_Event &$event, $param) {
352
+		// data['id'] ID data['unl'] unlink return code
353
+		// data['del'] Namespace directory unlink return code
354
+		// data['name'] file name data['path'] full path to the file
355
+		// data['size'] file size
356
+
357
+		dbglog($event->data, "handleMediaDeleted::event data");
358
+
359
+		// remove the media id from the index
360
+		$indexer = &plugin_load('helper', 'spatialhelper_index');
361
+		if($indexer) {
362
+			$indexer->deleteFromIndex('media__' . $event->data ['id']);
363
+		}
364
+	}
365
+
366
+	/**
367
+	 * add a link to the spatial sitemap files in the header.
368
+	 *
369
+	 * @param Doku_Event   $event
370
+	 *          the DokuWiki event. $event->data is a two-dimensional
371
+	 *          array of all meta headers. The keys are meta, link and script.
372
+	 * @param unknown_type $param
373
+	 *
374
+	 * @see http://www.dokuwiki.org/devel:event:tpl_metaheader_output
375
+	 */
376
+	public function handleMetaheaderOutput(Doku_Event $event, $param) {
377
+		// TODO maybe test for exist
378
+		$event->data ["link"] [] = array(
379
+			"type"  => "application/atom+xml",
380
+			"rel"   => "alternate",
381
+			"href"  => ml($this->getConf('media_georss')),
382
+			"title" => "Spatial ATOM Feed"
383
+		);
384
+		$event->data ["link"] [] = array(
385
+			"type"  => "application/vnd.google-earth.kml+xml",
386
+			"rel"   => "alternate",
387
+			"href"  => ml($this->getConf('media_kml')),
388
+			"title" => "KML Sitemap"
389
+		);
390
+	}
391
+
392
+	/**
393
+	 * Calculate a new coordinate based on start, distance and bearing
394
+	 *
395
+	 * @param $start array
396
+	 *               - start coordinate as decimal lat/lon pair
397
+	 * @param $dist  float
398
+	 *               - distance in kilometers
399
+	 * @param $brng  float
400
+	 *               - bearing in degrees (compass direction)
401
+	 */
402
+	private function geoDestination($start, $dist, $brng) {
403
+		$lat1 = toRad($start [0]);
404
+		$lon1 = toRad($start [1]);
405
+		// http://en.wikipedia.org/wiki/Earth_radius
406
+		// average earth radius in km
407
+		$dist = $dist / 6371.01;
408
+		$brng = toRad($brng);
409
+
410
+		$lon2 = $lon1 + atan2(sin($brng) * sin($dist) * cos($lat1), cos($dist) - sin($lat1) * sin($lat2));
411
+		$lon2 = fmod(($lon2 + 3 * pi()), (2 * pi())) - pi();
412
+
413
+		return array(
414
+			toDeg($lat2),
415
+			toDeg($lon2)
416
+		);
417
+	}
418
+
419
+	private function toRad($deg) {
420
+		return $deg * pi() / 180;
421
+	}
422
+
423
+	private function toDeg($rad) {
424
+		return $rad * 180 / pi();
425
+	}
426 426
 }
Please login to merge, or discard this patch.
Spacing   +28 added lines, -28 removed lines patch added patch discarded remove patch
@@ -101,18 +101,18 @@  discard block
 block discarded – undo
101 101
         // $data[3] – rev: The page revision, false for current wiki pages.
102 102
 
103 103
         dbglog($event->data, "Event data in removeFromIndex.");
104
-        if(@file_exists($event->data [0] [0])) {
104
+        if (@file_exists($event->data [0] [0])) {
105 105
             // file not new
106
-            if(!$event->data [0] [1]) {
106
+            if (!$event->data [0] [1]) {
107 107
                 // file is empty, page is being deleted
108
-                if(empty ($event->data [1])) {
108
+                if (empty ($event->data [1])) {
109 109
                     // root namespace
110 110
                     $id = $event->data [2];
111 111
                 } else {
112 112
                     $id = $event->data [1] . ":" . $event->data [2];
113 113
                 }
114 114
                 $indexer = &plugin_load('helper', 'spatialhelper_index');
115
-                if($indexer) {
115
+                if ($indexer) {
116 116
                     $indexer->deleteFromIndex($id);
117 117
                 }
118 118
             }
@@ -145,15 +145,15 @@  discard block
 block discarded – undo
145 145
         // $event→data['items']: Array of SitemapItem instances, the array of sitemap items that already
146 146
         //      contains all public pages of the wiki
147 147
         // $event→data['sitemap']: The path of the file the sitemap will be saved to.
148
-        if($helper = &plugin_load('helper', 'spatialhelper_sitemap')) {
148
+        if ($helper = &plugin_load('helper', 'spatialhelper_sitemap')) {
149 149
             // dbglog($helper, "createSpatialSitemap loaded helper.");
150 150
 
151 151
             $kml = $helper->createKMLSitemap($this->getConf('media_kml'));
152 152
             $rss = $helper->createGeoRSSSitemap($this->getConf('media_georss'));
153 153
 
154
-            if(!empty ($this->getConf('sitemap_namespaces'))) {
154
+            if (!empty ($this->getConf('sitemap_namespaces'))) {
155 155
                 $namespaces = array_map('trim', explode("\n", $this->getConf('sitemap_namespaces')));
156
-                foreach($namespaces as $namespace) {
156
+                foreach ($namespaces as $namespace) {
157 157
                     $kmlN = $helper->createKMLSitemap($namespace . $this->getConf('media_kml'));
158 158
                     $rssN = $helper->createGeoRSSSitemap($namespace . $this->getConf('media_georss'));
159 159
                     dbglog(
@@ -178,7 +178,7 @@  discard block
 block discarded – undo
178 178
      *          not used
179 179
      */
180 180
     public function handleActionActPreprocess(Doku_Event $event, $param) {
181
-        if($event->data != 'findnearby') {
181
+        if ($event->data != 'findnearby') {
182 182
             return;
183 183
         }
184 184
         $event->preventDefault();
@@ -194,16 +194,16 @@  discard block
 block discarded – undo
194 194
      *          'format'=> HTML | JSON
195 195
      */
196 196
     public function findnearby(Doku_Event &$event, $param) {
197
-        if($event->data != 'findnearby') {
197
+        if ($event->data != 'findnearby') {
198 198
             return;
199 199
         }
200 200
         $event->preventDefault();
201 201
 
202 202
         global $INPUT;
203
-        if($helper = &plugin_load('helper', 'spatialhelper_search')) {
204
-            if($INPUT->has('lat') && $INPUT->has('lon')) {
203
+        if ($helper = &plugin_load('helper', 'spatialhelper_search')) {
204
+            if ($INPUT->has('lat') && $INPUT->has('lon')) {
205 205
                 $results = $helper->findNearbyLatLon($INPUT->param('lat'), $INPUT->param('lon'));
206
-            } elseif($INPUT->has('geohash')) {
206
+            } elseif ($INPUT->has('geohash')) {
207 207
                 $results = $helper->findNearby($INPUT->str('geohash'));
208 208
             } else {
209 209
                 $results = array(
@@ -214,7 +214,7 @@  discard block
 block discarded – undo
214 214
 
215 215
         $showMedia = $INPUT->bool('showMedia', true);
216 216
 
217
-        switch($param['format']) {
217
+        switch ($param['format']) {
218 218
             case 'JSON' :
219 219
                 $this->printJSON($results);
220 220
                 break;
@@ -245,13 +245,13 @@  discard block
 block discarded – undo
245 245
      * @param boolean $showMedia
246 246
      */
247 247
     private function printHTML($searchresults, $showMedia = true) {
248
-        $pages   = (array) ($searchresults ['pages']);
249
-        $media   = (array) $searchresults ['media'];
250
-        $lat     = (float) $searchresults ['lat'];
251
-        $lon     = (float) $searchresults ['lon'];
252
-        $geohash = (string) $searchresults ['geohash'];
248
+        $pages   = ( array ) ($searchresults ['pages']);
249
+        $media   = ( array ) $searchresults ['media'];
250
+        $lat     = ( float ) $searchresults ['lat'];
251
+        $lon     = ( float ) $searchresults ['lon'];
252
+        $geohash = ( string ) $searchresults ['geohash'];
253 253
 
254
-        if(isset ($searchresults ['error'])) {
254
+        if (isset ($searchresults ['error'])) {
255 255
             print '<div class="level1"><p>' . hsc($results ['error']) . '</p></div>';
256 256
             return;
257 257
         }
@@ -259,9 +259,9 @@  discard block
 block discarded – undo
259 259
         // print a HTML list
260 260
         print '<h1>' . $this->getLang('results_header') . '</h1>' . DOKU_LF;
261 261
         print '<div class="level1">' . DOKU_LF;
262
-        if(!empty ($pages)) {
262
+        if (!empty ($pages)) {
263 263
             $pagelist = '<ol>' . DOKU_LF;
264
-            foreach($pages as $page) {
264
+            foreach ($pages as $page) {
265 265
                 $pagelist .= '<li>' . html_wikilink(
266 266
                         ':' . $page ['id'], useHeading('navigation') ? null :
267 267
                         noNS($page ['id'])
@@ -281,14 +281,14 @@  discard block
 block discarded – undo
281 281
             print '<p>' . hsc($this->getLang('nothingfound')) . '</p>';
282 282
         }
283 283
 
284
-        if(!empty ($media) && $showMedia) {
284
+        if (!empty ($media) && $showMedia) {
285 285
             $pagelist = '<ol>' . DOKU_LF;
286
-            foreach($media as $m) {
286
+            foreach ($media as $m) {
287 287
                 $opts       = array();
288 288
                 $link       = ml($m ['id'], $opts, false, '&amp;', false);
289 289
                 $opts ['w'] = '100';
290 290
                 $src        = ml($m ['id'], $opts);
291
-                $pagelist   .= '<li><a href="' . $link . '"><img src="' . $src . '"></a> ('
291
+                $pagelist .= '<li><a href="' . $link . '"><img src="' . $src . '"></a> ('
292 292
                     . $this->getLang('results_distance_prefix') . $page ['distance'] . '&nbsp;m) ' . hsc($desc)
293 293
                     . '</li>' . DOKU_LF;
294 294
             }
@@ -303,7 +303,7 @@  discard block
 block discarded – undo
303 303
             print '</div>' . DOKU_LF;
304 304
         }
305 305
         print '<p>' . $this->getLang('results_precision') . $searchresults ['precision'] . ' m. ';
306
-        if(strlen($geohash) > 1) {
306
+        if (strlen($geohash) > 1) {
307 307
             $url = wl(
308 308
                 getID(), array(
309 309
                 'do'      => 'findnearby',
@@ -335,9 +335,9 @@  discard block
 block discarded – undo
335 335
 
336 336
         // check the list of mimetypes
337 337
         // if it's a supported type call appropriate index function
338
-        if(substr_compare($event->data [3], 'image/jpeg', 0)) {
338
+        if (substr_compare($event->data [3], 'image/jpeg', 0)) {
339 339
             $indexer = plugin_load('helper', 'spatialhelper_index');
340
-            if($indexer) {
340
+            if ($indexer) {
341 341
                 $indexer->indexImage($event->data [2], $event->data [1]);
342 342
             }
343 343
         }
@@ -358,7 +358,7 @@  discard block
 block discarded – undo
358 358
 
359 359
         // remove the media id from the index
360 360
         $indexer = &plugin_load('helper', 'spatialhelper_index');
361
-        if($indexer) {
361
+        if ($indexer) {
362 362
             $indexer->deleteFromIndex('media__' . $event->data ['id']);
363 363
         }
364 364
     }
Please login to merge, or discard this patch.
syntax/findnearby.php 2 patches
Indentation   +79 added lines, -79 removed lines patch added patch discarded remove patch
@@ -22,89 +22,89 @@
 block discarded – undo
22 22
  * @author  Mark C. Prins <[email protected]>
23 23
  */
24 24
 class syntax_plugin_spatialhelper_findnearby extends DokuWiki_Syntax_Plugin {
25
-    /**
26
-     *
27
-     * @see DokuWiki_Syntax_Plugin::getType()
28
-     */
29
-    public function getType() {
30
-        return 'substition';
31
-    }
25
+	/**
26
+	 *
27
+	 * @see DokuWiki_Syntax_Plugin::getType()
28
+	 */
29
+	public function getType() {
30
+		return 'substition';
31
+	}
32 32
 
33
-    /**
34
-     * Return 'normal' so this syntax can be rendered inline.
35
-     *
36
-     * @see DokuWiki_Syntax_Plugin::getPType()
37
-     */
38
-    public function getPType() {
39
-        return 'normal';
40
-    }
33
+	/**
34
+	 * Return 'normal' so this syntax can be rendered inline.
35
+	 *
36
+	 * @see DokuWiki_Syntax_Plugin::getPType()
37
+	 */
38
+	public function getPType() {
39
+		return 'normal';
40
+	}
41 41
 
42
-    /**
43
-     *
44
-     * @see Doku_Parser_Mode::getSort()
45
-     */
46
-    public function getSort() {
47
-        return 307;
48
-    }
42
+	/**
43
+	 *
44
+	 * @see Doku_Parser_Mode::getSort()
45
+	 */
46
+	public function getSort() {
47
+		return 307;
48
+	}
49 49
 
50
-    /**
51
-     * define our special pattern: {{findnearby>Some linkt text or nothing}}.
52
-     *
53
-     * @see Doku_Parser_Mode::connectTo()
54
-     */
55
-    public function connectTo($mode) {
56
-        $this->Lexer->addSpecialPattern('\{\{findnearby>.*?\}\}', $mode, 'plugin_spatialhelper_findnearby');
57
-    }
50
+	/**
51
+	 * define our special pattern: {{findnearby>Some linkt text or nothing}}.
52
+	 *
53
+	 * @see Doku_Parser_Mode::connectTo()
54
+	 */
55
+	public function connectTo($mode) {
56
+		$this->Lexer->addSpecialPattern('\{\{findnearby>.*?\}\}', $mode, 'plugin_spatialhelper_findnearby');
57
+	}
58 58
 
59
-    /**
60
-     * look up the page's geo metadata and pass that on to render.
61
-     *
62
-     * @see DokuWiki_Syntax_Plugin::handle()
63
-     */
64
-    public function handle($match, $state, $pos, Doku_Handler $handler) {
65
-        $data     = array();
66
-        $data [0] = trim(substr($match, strlen('{{findnearby>'), -2));
67
-        if(strlen($data [0]) < 1) {
68
-            $data [0] = $this->getLang('search_findnearby');
69
-        }
70
-        $meta = p_get_metadata(getID(), 'geo');
71
-        if($meta) {
72
-            if($meta ['lat'] && $meta ['lon']) {
73
-                $data [1] = array(
74
-                    'do'  => 'findnearby',
75
-                    'lat' => $meta ['lat'],
76
-                    'lon' => $meta ['lon']
77
-                );
78
-            } elseif($meta ['geohash']) {
79
-                $data [1] = array(
80
-                    'do'      => 'findnearby',
81
-                    'geohash' => $meta ['geohash']
82
-                );
83
-            }
84
-            return $data;
85
-        }
86
-        return false;
87
-    }
59
+	/**
60
+	 * look up the page's geo metadata and pass that on to render.
61
+	 *
62
+	 * @see DokuWiki_Syntax_Plugin::handle()
63
+	 */
64
+	public function handle($match, $state, $pos, Doku_Handler $handler) {
65
+		$data     = array();
66
+		$data [0] = trim(substr($match, strlen('{{findnearby>'), -2));
67
+		if(strlen($data [0]) < 1) {
68
+			$data [0] = $this->getLang('search_findnearby');
69
+		}
70
+		$meta = p_get_metadata(getID(), 'geo');
71
+		if($meta) {
72
+			if($meta ['lat'] && $meta ['lon']) {
73
+				$data [1] = array(
74
+					'do'  => 'findnearby',
75
+					'lat' => $meta ['lat'],
76
+					'lon' => $meta ['lon']
77
+				);
78
+			} elseif($meta ['geohash']) {
79
+				$data [1] = array(
80
+					'do'      => 'findnearby',
81
+					'geohash' => $meta ['geohash']
82
+				);
83
+			}
84
+			return $data;
85
+		}
86
+		return false;
87
+	}
88 88
 
89
-    /**
90
-     * Render a link to a search page.
91
-     *
92
-     * @see DokuWiki_Syntax_Plugin::render()
93
-     */
94
-    public function render($mode, Doku_Renderer $renderer, $data) {
95
-        if($data === false) {
96
-            return false;
97
-        }
89
+	/**
90
+	 * Render a link to a search page.
91
+	 *
92
+	 * @see DokuWiki_Syntax_Plugin::render()
93
+	 */
94
+	public function render($mode, Doku_Renderer $renderer, $data) {
95
+		if($data === false) {
96
+			return false;
97
+		}
98 98
 
99
-        if($mode == 'xhtml') {
100
-            $renderer->doc .= '<a href="' . wl(getID(), $data [1]) . '" class="findnearby">' . hsc($data [0]) . '</a>';
101
-            return true;
102
-        } elseif($mode == 'metadata') {
103
-            return false;
104
-        } elseif($mode == 'odt') {
105
-            // don't render anything in ODT
106
-            return false;
107
-        }
108
-        return false;
109
-    }
99
+		if($mode == 'xhtml') {
100
+			$renderer->doc .= '<a href="' . wl(getID(), $data [1]) . '" class="findnearby">' . hsc($data [0]) . '</a>';
101
+			return true;
102
+		} elseif($mode == 'metadata') {
103
+			return false;
104
+		} elseif($mode == 'odt') {
105
+			// don't render anything in ODT
106
+			return false;
107
+		}
108
+		return false;
109
+	}
110 110
 }
Please login to merge, or discard this patch.
Spacing   +8 added lines, -8 removed lines patch added patch discarded remove patch
@@ -64,18 +64,18 @@  discard block
 block discarded – undo
64 64
     public function handle($match, $state, $pos, Doku_Handler $handler) {
65 65
         $data     = array();
66 66
         $data [0] = trim(substr($match, strlen('{{findnearby>'), -2));
67
-        if(strlen($data [0]) < 1) {
67
+        if (strlen($data [0]) < 1) {
68 68
             $data [0] = $this->getLang('search_findnearby');
69 69
         }
70 70
         $meta = p_get_metadata(getID(), 'geo');
71
-        if($meta) {
72
-            if($meta ['lat'] && $meta ['lon']) {
71
+        if ($meta) {
72
+            if ($meta ['lat'] && $meta ['lon']) {
73 73
                 $data [1] = array(
74 74
                     'do'  => 'findnearby',
75 75
                     'lat' => $meta ['lat'],
76 76
                     'lon' => $meta ['lon']
77 77
                 );
78
-            } elseif($meta ['geohash']) {
78
+            } elseif ($meta ['geohash']) {
79 79
                 $data [1] = array(
80 80
                     'do'      => 'findnearby',
81 81
                     'geohash' => $meta ['geohash']
@@ -92,16 +92,16 @@  discard block
 block discarded – undo
92 92
      * @see DokuWiki_Syntax_Plugin::render()
93 93
      */
94 94
     public function render($mode, Doku_Renderer $renderer, $data) {
95
-        if($data === false) {
95
+        if ($data === false) {
96 96
             return false;
97 97
         }
98 98
 
99
-        if($mode == 'xhtml') {
99
+        if ($mode == 'xhtml') {
100 100
             $renderer->doc .= '<a href="' . wl(getID(), $data [1]) . '" class="findnearby">' . hsc($data [0]) . '</a>';
101 101
             return true;
102
-        } elseif($mode == 'metadata') {
102
+        } elseif ($mode == 'metadata') {
103 103
             return false;
104
-        } elseif($mode == 'odt') {
104
+        } elseif ($mode == 'odt') {
105 105
             // don't render anything in ODT
106 106
             return false;
107 107
         }
Please login to merge, or discard this patch.
_test/index.test.php 1 patch
Indentation   +44 added lines, -44 removed lines patch added patch discarded remove patch
@@ -13,48 +13,48 @@
 block discarded – undo
13 13
  */
14 14
 class index_test extends DokuWikiTest {
15 15
 
16
-    protected $pluginsEnabled = array('spatialhelper');
17
-
18
-    /**
19
-     * Testdata for @return array
20
-     * @see index_test::test_convertDMStoD
21
-     *
22
-     */
23
-    public static function convertDMStoD_testdata(): array {
24
-        return array(
25
-            array(
26
-                array(0 => '52/1', 1 => '31/1', 2 => '2/1', 3 => 'N',),
27
-                52.5172,
28
-                'Latitude in Europe'
29
-            ),
30
-            array(
31
-                array(0 => '13/1', 1 => '30/1', 2 => '38/1', 3 => 'E',),
32
-                13.5105,
33
-                'Longitude in Europe'
34
-            ),
35
-            array(
36
-                array(0 => '50/1', 1 => '34251480/1000000', 2 => '0/1', 3 => 'N',),
37
-                50.5708,
38
-                'Latitude in North America'
39
-            ),
40
-            array(
41
-                array(0 => '109/1', 1 => '28041300/1000000', 2 => '0/1', 3 => 'W',),
42
-                -109.4673,
43
-                'Longitude in North America'
44
-            ),
45
-        );
46
-    }
47
-
48
-    /**
49
-     * @dataProvider convertDMStoD_testdata
50
-     *
51
-     */
52
-    public function test_convertDMStoD($input, $expected_output, $msg): void {
53
-        /** @var helper_plugin_spatialhelper_index $index */
54
-        $index = plugin_load('helper', 'spatialhelper_index');
55
-
56
-        $actual_output = $index->convertDMStoD($input);
57
-
58
-        $this->assertEqualsWithDelta($expected_output, $actual_output, 0.0001, $msg);
59
-    }
16
+	protected $pluginsEnabled = array('spatialhelper');
17
+
18
+	/**
19
+	 * Testdata for @return array
20
+	 * @see index_test::test_convertDMStoD
21
+	 *
22
+	 */
23
+	public static function convertDMStoD_testdata(): array {
24
+		return array(
25
+			array(
26
+				array(0 => '52/1', 1 => '31/1', 2 => '2/1', 3 => 'N',),
27
+				52.5172,
28
+				'Latitude in Europe'
29
+			),
30
+			array(
31
+				array(0 => '13/1', 1 => '30/1', 2 => '38/1', 3 => 'E',),
32
+				13.5105,
33
+				'Longitude in Europe'
34
+			),
35
+			array(
36
+				array(0 => '50/1', 1 => '34251480/1000000', 2 => '0/1', 3 => 'N',),
37
+				50.5708,
38
+				'Latitude in North America'
39
+			),
40
+			array(
41
+				array(0 => '109/1', 1 => '28041300/1000000', 2 => '0/1', 3 => 'W',),
42
+				-109.4673,
43
+				'Longitude in North America'
44
+			),
45
+		);
46
+	}
47
+
48
+	/**
49
+	 * @dataProvider convertDMStoD_testdata
50
+	 *
51
+	 */
52
+	public function test_convertDMStoD($input, $expected_output, $msg): void {
53
+		/** @var helper_plugin_spatialhelper_index $index */
54
+		$index = plugin_load('helper', 'spatialhelper_index');
55
+
56
+		$actual_output = $index->convertDMStoD($input);
57
+
58
+		$this->assertEqualsWithDelta($expected_output, $actual_output, 0.0001, $msg);
59
+	}
60 60
 }
Please login to merge, or discard this patch.
_test/general.test.php 1 patch
Indentation   +30 added lines, -30 removed lines patch added patch discarded remove patch
@@ -23,39 +23,39 @@
 block discarded – undo
23 23
  */
24 24
 class general_plugin_spatialhelper_test extends DokuWikiTest {
25 25
 
26
-    protected $pluginsEnabled = array('spatialhelper');
26
+	protected $pluginsEnabled = array('spatialhelper');
27 27
 
28
-    /**
29
-     * Simple test to make sure the plugin.info.txt is in correct format.
30
-     */
31
-    public function test_plugininfo(): void {
32
-        $file = __DIR__ . '/../plugin.info.txt';
33
-        $this->assertFileExists($file);
28
+	/**
29
+	 * Simple test to make sure the plugin.info.txt is in correct format.
30
+	 */
31
+	public function test_plugininfo(): void {
32
+		$file = __DIR__ . '/../plugin.info.txt';
33
+		$this->assertFileExists($file);
34 34
 
35
-        $info = confToHash($file);
35
+		$info = confToHash($file);
36 36
 
37
-        $this->assertArrayHasKey('base', $info);
38
-        $this->assertArrayHasKey('author', $info);
39
-        $this->assertArrayHasKey('email', $info);
40
-        $this->assertArrayHasKey('date', $info);
41
-        $this->assertArrayHasKey('name', $info);
42
-        $this->assertArrayHasKey('desc', $info);
43
-        $this->assertArrayHasKey('url', $info);
37
+		$this->assertArrayHasKey('base', $info);
38
+		$this->assertArrayHasKey('author', $info);
39
+		$this->assertArrayHasKey('email', $info);
40
+		$this->assertArrayHasKey('date', $info);
41
+		$this->assertArrayHasKey('name', $info);
42
+		$this->assertArrayHasKey('desc', $info);
43
+		$this->assertArrayHasKey('url', $info);
44 44
 
45
-        $this->assertEquals('spatialhelper', $info['base']);
46
-        $this->assertRegExp('/^https?:\/\//', $info['url']);
47
-        $this->assertTrue(mail_isvalid($info['email']));
48
-        $this->assertRegExp('/^\d\d\d\d-\d\d-\d\d$/', $info['date']);
49
-        $this->assertTrue(false !== strtotime($info['date']));
50
-    }
45
+		$this->assertEquals('spatialhelper', $info['base']);
46
+		$this->assertRegExp('/^https?:\/\//', $info['url']);
47
+		$this->assertTrue(mail_isvalid($info['email']));
48
+		$this->assertRegExp('/^\d\d\d\d-\d\d-\d\d$/', $info['date']);
49
+		$this->assertTrue(false !== strtotime($info['date']));
50
+	}
51 51
 
52
-    /**
53
-     * test if plugin is loaded.
54
-     */
55
-    public function test_plugin_spatialhelper_isloaded(): void {
56
-        global $plugin_controller;
57
-        $this->assertContains(
58
-            'spatialhelper', $plugin_controller->getList(), "spatialhelper plugin is loaded"
59
-        );
60
-    }
52
+	/**
53
+	 * test if plugin is loaded.
54
+	 */
55
+	public function test_plugin_spatialhelper_isloaded(): void {
56
+		global $plugin_controller;
57
+		$this->assertContains(
58
+			'spatialhelper', $plugin_controller->getList(), "spatialhelper plugin is loaded"
59
+		);
60
+	}
61 61
 }
Please login to merge, or discard this patch.
admin/purge.php 2 patches
Indentation   +62 added lines, -62 removed lines patch added patch discarded remove patch
@@ -23,73 +23,73 @@
 block discarded – undo
23 23
  */
24 24
 class admin_plugin_spatialhelper_purge extends DokuWiki_Admin_Plugin {
25 25
 
26
-    /**
27
-     *
28
-     * @see DokuWiki_Admin_Plugin::getMenuSort()
29
-     */
30
-    public function getMenuSort() {
31
-        return 801;
32
-    }
26
+	/**
27
+	 *
28
+	 * @see DokuWiki_Admin_Plugin::getMenuSort()
29
+	 */
30
+	public function getMenuSort() {
31
+		return 801;
32
+	}
33 33
 
34
-    /**
35
-     * admin use only.
36
-     *
37
-     * @return true
38
-     *
39
-     * @see DokuWiki_Admin_Plugin::forAdminOnly()
40
-     */
41
-    public function forAdminOnly() {
42
-        return true;
43
-    }
34
+	/**
35
+	 * admin use only.
36
+	 *
37
+	 * @return true
38
+	 *
39
+	 * @see DokuWiki_Admin_Plugin::forAdminOnly()
40
+	 */
41
+	public function forAdminOnly() {
42
+		return true;
43
+	}
44 44
 
45
-    /**
46
-     * purge and regenerate the index and sitemaps.
47
-     *
48
-     * @see DokuWiki_Admin_Plugin::handle()
49
-     */
50
-    public function handle() {
51
-        global $conf;
52
-        if(isset ($_REQUEST ['purgeindex'])) {
53
-            global $conf;
54
-            $path = $conf ['indexdir'] . '/spatial.idx';
55
-            if(file_exists($path)) {
56
-                if(unlink($path)) {
57
-                    msg($this->getLang('admin_purged_tiles'), 0);
58
-                }
59
-            }
60
-        }
45
+	/**
46
+	 * purge and regenerate the index and sitemaps.
47
+	 *
48
+	 * @see DokuWiki_Admin_Plugin::handle()
49
+	 */
50
+	public function handle() {
51
+		global $conf;
52
+		if(isset ($_REQUEST ['purgeindex'])) {
53
+			global $conf;
54
+			$path = $conf ['indexdir'] . '/spatial.idx';
55
+			if(file_exists($path)) {
56
+				if(unlink($path)) {
57
+					msg($this->getLang('admin_purged_tiles'), 0);
58
+				}
59
+			}
60
+		}
61 61
 
62
-        $indexer = plugin_load('helper', 'spatialhelper_index');
63
-        $indexer->generateSpatialIndex();
62
+		$indexer = plugin_load('helper', 'spatialhelper_index');
63
+		$indexer->generateSpatialIndex();
64 64
 
65
-        $sitemapper = plugin_load('helper', 'spatialhelper_sitemap');
66
-        $sitemapper->createKMLSitemap($this->getConf('media_kml'));
67
-        $sitemapper->createGeoRSSSitemap($this->getConf('media_georss'));
68
-    }
65
+		$sitemapper = plugin_load('helper', 'spatialhelper_sitemap');
66
+		$sitemapper->createKMLSitemap($this->getConf('media_kml'));
67
+		$sitemapper->createGeoRSSSitemap($this->getConf('media_georss'));
68
+	}
69 69
 
70
-    /**
71
-     * render the form for this plugin.
72
-     *
73
-     * @see DokuWiki_Admin_Plugin::html()
74
-     */
75
-    public function html() {
76
-        echo $this->locale_xhtml('admin_purge_intro');
70
+	/**
71
+	 * render the form for this plugin.
72
+	 *
73
+	 * @see DokuWiki_Admin_Plugin::html()
74
+	 */
75
+	public function html() {
76
+		echo $this->locale_xhtml('admin_purge_intro');
77 77
 
78
-        $form = new Doku_Form(
79
-            array(
80
-                'id'     => 'spatialhelper__purgeform',
81
-                'method' => 'post'
82
-            )
83
-        );
84
-        $form->addHidden('purgeindex', 'true');
78
+		$form = new Doku_Form(
79
+			array(
80
+				'id'     => 'spatialhelper__purgeform',
81
+				'method' => 'post'
82
+			)
83
+		);
84
+		$form->addHidden('purgeindex', 'true');
85 85
 
86
-        $form->addElement(
87
-            form_makeButton(
88
-                'submit', 'admin', $this->getLang('admin_submit'), array(
89
-                'title' => $this->getLang('admin_submit')
90
-            )
91
-            )
92
-        );
93
-        $form->printForm();
94
-    }
86
+		$form->addElement(
87
+			form_makeButton(
88
+				'submit', 'admin', $this->getLang('admin_submit'), array(
89
+				'title' => $this->getLang('admin_submit')
90
+			)
91
+			)
92
+		);
93
+		$form->printForm();
94
+	}
95 95
 }
Please login to merge, or discard this patch.
Spacing   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -49,11 +49,11 @@
 block discarded – undo
49 49
      */
50 50
     public function handle() {
51 51
         global $conf;
52
-        if(isset ($_REQUEST ['purgeindex'])) {
52
+        if (isset ($_REQUEST ['purgeindex'])) {
53 53
             global $conf;
54 54
             $path = $conf ['indexdir'] . '/spatial.idx';
55
-            if(file_exists($path)) {
56
-                if(unlink($path)) {
55
+            if (file_exists($path)) {
56
+                if (unlink($path)) {
57 57
                     msg($this->getLang('admin_purged_tiles'), 0);
58 58
                 }
59 59
             }
Please login to merge, or discard this patch.
helper/search.php 2 patches
Indentation   +164 added lines, -164 removed lines patch added patch discarded remove patch
@@ -22,180 +22,180 @@
 block discarded – undo
22 22
  * @author  Mark Prins
23 23
  */
24 24
 class helper_plugin_spatialhelper_search extends DokuWiki_Plugin {
25
-    /**
26
-     * spatial index.
27
-     *
28
-     * @var array
29
-     */
30
-    protected $spatial_idx = array();
31
-    /**
32
-     * handle to the geoPHP plugin.
33
-     */
34
-    protected $geophp;
35
-    /**
36
-     * Precision, Distance of Adjacent Cell in Meters.
37
-     *
38
-     * @see https://stackoverflow.com/questions/13836416/geohash-and-max-distance
39
-     *
40
-     * @var float
41
-     */
42
-    private $precision = array(
43
-        5003530,
44
-        625441,
45
-        123264,
46
-        19545,
47
-        3803,
48
-        610,
49
-        118,
50
-        19,
51
-        3.7,
52
-        0.6
53
-    );
25
+	/**
26
+	 * spatial index.
27
+	 *
28
+	 * @var array
29
+	 */
30
+	protected $spatial_idx = array();
31
+	/**
32
+	 * handle to the geoPHP plugin.
33
+	 */
34
+	protected $geophp;
35
+	/**
36
+	 * Precision, Distance of Adjacent Cell in Meters.
37
+	 *
38
+	 * @see https://stackoverflow.com/questions/13836416/geohash-and-max-distance
39
+	 *
40
+	 * @var float
41
+	 */
42
+	private $precision = array(
43
+		5003530,
44
+		625441,
45
+		123264,
46
+		19545,
47
+		3803,
48
+		610,
49
+		118,
50
+		19,
51
+		3.7,
52
+		0.6
53
+	);
54 54
 
55
-    /**
56
-     * constructor; initialize/load spatial index.
57
-     */
58
-    public function __construct() {
59
-        // parent::__construct ();
60
-        global $conf;
55
+	/**
56
+	 * constructor; initialize/load spatial index.
57
+	 */
58
+	public function __construct() {
59
+		// parent::__construct ();
60
+		global $conf;
61 61
 
62
-        if(!$geophp = &plugin_load('helper', 'geophp')) {
63
-            $message = 'helper_plugin_spatialhelper_search::spatialhelper_search: geophp plugin is not available.';
64
-            msg($message, -1);
65
-        }
62
+		if(!$geophp = &plugin_load('helper', 'geophp')) {
63
+			$message = 'helper_plugin_spatialhelper_search::spatialhelper_search: geophp plugin is not available.';
64
+			msg($message, -1);
65
+		}
66 66
 
67
-        $idx_dir = $conf ['indexdir'];
68
-        if(!@file_exists($idx_dir . '/spatial.idx')) {
69
-            $indexer = plugin_load('helper', 'spatialhelper_index');
70
-        }
67
+		$idx_dir = $conf ['indexdir'];
68
+		if(!@file_exists($idx_dir . '/spatial.idx')) {
69
+			$indexer = plugin_load('helper', 'spatialhelper_index');
70
+		}
71 71
 
72
-        $this->spatial_idx = unserialize(io_readFile($fn = $idx_dir . '/spatial.idx', false));
73
-    }
72
+		$this->spatial_idx = unserialize(io_readFile($fn = $idx_dir . '/spatial.idx', false));
73
+	}
74 74
 
75
-    /**
76
-     * Find locations based on the coordinate pair.
77
-     *
78
-     * @param numeric $lat
79
-     *          The y coordinate (or latitude)
80
-     * @param numeric $lon
81
-     *          The x coordinate (or longitude)
82
-     */
83
-    public function findNearbyLatLon($lat, $lon) {
84
-        $geometry = new Point($lon, $lat);
85
-        return $this->findNearby($geometry->out('geohash'), $geometry);
86
-    }
75
+	/**
76
+	 * Find locations based on the coordinate pair.
77
+	 *
78
+	 * @param numeric $lat
79
+	 *          The y coordinate (or latitude)
80
+	 * @param numeric $lon
81
+	 *          The x coordinate (or longitude)
82
+	 */
83
+	public function findNearbyLatLon($lat, $lon) {
84
+		$geometry = new Point($lon, $lat);
85
+		return $this->findNearby($geometry->out('geohash'), $geometry);
86
+	}
87 87
 
88
-    /**
89
-     * finds nearby elements in the index based on the geohash.
90
-     * returns a list of documents and the bunding box.
91
-     *
92
-     * @param string $geohash
93
-     * @param Point  $p
94
-     *          optional point
95
-     * @return array of ...
96
-     */
97
-    public function findNearby($geohash, Point $p = null) {
98
-        $_geohashClass = new Geohash();
99
-        if(!$p) {
100
-            $decodedPoint = $_geohashClass->read($geohash);
101
-        } else {
102
-            $decodedPoint = $p;
103
-        }
88
+	/**
89
+	 * finds nearby elements in the index based on the geohash.
90
+	 * returns a list of documents and the bunding box.
91
+	 *
92
+	 * @param string $geohash
93
+	 * @param Point  $p
94
+	 *          optional point
95
+	 * @return array of ...
96
+	 */
97
+	public function findNearby($geohash, Point $p = null) {
98
+		$_geohashClass = new Geohash();
99
+		if(!$p) {
100
+			$decodedPoint = $_geohashClass->read($geohash);
101
+		} else {
102
+			$decodedPoint = $p;
103
+		}
104 104
 
105
-        // find adjacent blocks
106
-        $adjacent                 = array();
107
-        $adjacent ['center']      = $geohash;
108
-        $adjacent ['top']         = $_geohashClass->adjacent($adjacent ['center'], 'top');
109
-        $adjacent ['bottom']      = $_geohashClass->adjacent($adjacent ['center'], 'bottom');
110
-        $adjacent ['right']       = $_geohashClass->adjacent($adjacent ['center'], 'right');
111
-        $adjacent ['left']        = $_geohashClass->adjacent($adjacent ['center'], 'left');
112
-        $adjacent ['topleft']     = $_geohashClass->adjacent($adjacent ['left'], 'top');
113
-        $adjacent ['topright']    = $_geohashClass->adjacent($adjacent ['right'], 'top');
114
-        $adjacent ['bottomright'] = $_geohashClass->adjacent($adjacent ['right'], 'bottom');
115
-        $adjacent ['bottomleft']  = $_geohashClass->adjacent($adjacent ['left'], 'bottom');
116
-        dbglog($adjacent, "adjacent geo hashes:");
105
+		// find adjacent blocks
106
+		$adjacent                 = array();
107
+		$adjacent ['center']      = $geohash;
108
+		$adjacent ['top']         = $_geohashClass->adjacent($adjacent ['center'], 'top');
109
+		$adjacent ['bottom']      = $_geohashClass->adjacent($adjacent ['center'], 'bottom');
110
+		$adjacent ['right']       = $_geohashClass->adjacent($adjacent ['center'], 'right');
111
+		$adjacent ['left']        = $_geohashClass->adjacent($adjacent ['center'], 'left');
112
+		$adjacent ['topleft']     = $_geohashClass->adjacent($adjacent ['left'], 'top');
113
+		$adjacent ['topright']    = $_geohashClass->adjacent($adjacent ['right'], 'top');
114
+		$adjacent ['bottomright'] = $_geohashClass->adjacent($adjacent ['right'], 'bottom');
115
+		$adjacent ['bottomleft']  = $_geohashClass->adjacent($adjacent ['left'], 'bottom');
116
+		dbglog($adjacent, "adjacent geo hashes:");
117 117
 
118
-        // find all the pages in the index that overlap with the adjacent hashes
119
-        $docIds = array();
120
-        foreach($adjacent as $adjHash) {
121
-            if(is_array($this->spatial_idx)) {
122
-                foreach($this->spatial_idx as $_geohash => $_docIds) {
123
-                    if(strstr($_geohash, $adjHash)) {
124
-                        // dbglog ( "Found adjacent geo hash: $adjHash in $_geohash" );
125
-                        // if $adjHash similar to geohash
126
-                        $docIds = array_merge($docIds, $_docIds);
127
-                    }
128
-                }
129
-            }
130
-        }
131
-        $docIds = array_unique($docIds);
132
-        dbglog($docIds, "found docIDs");
118
+		// find all the pages in the index that overlap with the adjacent hashes
119
+		$docIds = array();
120
+		foreach($adjacent as $adjHash) {
121
+			if(is_array($this->spatial_idx)) {
122
+				foreach($this->spatial_idx as $_geohash => $_docIds) {
123
+					if(strstr($_geohash, $adjHash)) {
124
+						// dbglog ( "Found adjacent geo hash: $adjHash in $_geohash" );
125
+						// if $adjHash similar to geohash
126
+						$docIds = array_merge($docIds, $_docIds);
127
+					}
128
+				}
129
+			}
130
+		}
131
+		$docIds = array_unique($docIds);
132
+		dbglog($docIds, "found docIDs");
133 133
 
134
-        // create associative array of pages + calculate distance
135
-        $pages   = array();
136
-        $media   = array();
137
-        $indexer = plugin_load('helper', 'spatialhelper_index');
134
+		// create associative array of pages + calculate distance
135
+		$pages   = array();
136
+		$media   = array();
137
+		$indexer = plugin_load('helper', 'spatialhelper_index');
138 138
 
139
-        foreach($docIds as $id) {
140
-            if(strpos($id, 'media__', 0) === 0) {
141
-                $id = substr($id, strlen('media__'));
142
-                if(auth_quickaclcheck($id) >= /*AUTH_READ*/ 1) {
143
-                    $point    = $indexer->getCoordsFromExif($id);
144
-                    $line     = new LineString(
145
-                        [
146
-                            $decodedPoint,
147
-                            $point
148
-                        ]
149
-                    );
150
-                    $media [] = array(
151
-                        'id'       => $id,
152
-                        'distance' => (int) ($line->greatCircleLength()),
153
-                        'lat'      => $point->y(),
154
-                        'lon'      => $point->x()
155
-                        // optionally add other meta such as tag, description...
156
-                    );
157
-                }
158
-            } else {
159
-                if(auth_quickaclcheck($id) >= /*AUTH_READ*/ 1) {
160
-                    $geotags  = p_get_metadata($id, 'geo');
161
-                    $point    = new Point($geotags ['lon'], $geotags ['lat']);
162
-                    $line     = new LineString(
163
-                        [
164
-                            $decodedPoint,
165
-                            $point
166
-                        ]
167
-                    );
168
-                    $pages [] = array(
169
-                        'id'          => $id,
170
-                        'distance'    => (int) ($line->greatCircleLength()),
171
-                        'description' => p_get_metadata($id, 'description')['abstract'],
172
-                        'lat'         => $geotags ['lat'],
173
-                        'lon'         => $geotags ['lon']
174
-                        // optionally add other meta such as tag...
175
-                    );
176
-                }
177
-            }
178
-        }
139
+		foreach($docIds as $id) {
140
+			if(strpos($id, 'media__', 0) === 0) {
141
+				$id = substr($id, strlen('media__'));
142
+				if(auth_quickaclcheck($id) >= /*AUTH_READ*/ 1) {
143
+					$point    = $indexer->getCoordsFromExif($id);
144
+					$line     = new LineString(
145
+						[
146
+							$decodedPoint,
147
+							$point
148
+						]
149
+					);
150
+					$media [] = array(
151
+						'id'       => $id,
152
+						'distance' => (int) ($line->greatCircleLength()),
153
+						'lat'      => $point->y(),
154
+						'lon'      => $point->x()
155
+						// optionally add other meta such as tag, description...
156
+					);
157
+				}
158
+			} else {
159
+				if(auth_quickaclcheck($id) >= /*AUTH_READ*/ 1) {
160
+					$geotags  = p_get_metadata($id, 'geo');
161
+					$point    = new Point($geotags ['lon'], $geotags ['lat']);
162
+					$line     = new LineString(
163
+						[
164
+							$decodedPoint,
165
+							$point
166
+						]
167
+					);
168
+					$pages [] = array(
169
+						'id'          => $id,
170
+						'distance'    => (int) ($line->greatCircleLength()),
171
+						'description' => p_get_metadata($id, 'description')['abstract'],
172
+						'lat'         => $geotags ['lat'],
173
+						'lon'         => $geotags ['lon']
174
+						// optionally add other meta such as tag...
175
+					);
176
+				}
177
+			}
178
+		}
179 179
 
180
-        // sort all the pages/media using distance
181
-        usort(
182
-            $pages, function ($a, $b) {
183
-            return strnatcmp($a ['distance'], $b ['distance']);
184
-        }
185
-        );
186
-        usort(
187
-            $media, function ($a, $b) {
188
-            return strnatcmp($a ['distance'], $b ['distance']);
189
-        }
190
-        );
180
+		// sort all the pages/media using distance
181
+		usort(
182
+			$pages, function ($a, $b) {
183
+			return strnatcmp($a ['distance'], $b ['distance']);
184
+		}
185
+		);
186
+		usort(
187
+			$media, function ($a, $b) {
188
+			return strnatcmp($a ['distance'], $b ['distance']);
189
+		}
190
+		);
191 191
 
192
-        return array(
193
-            'pages'     => $pages,
194
-            'media'     => $media,
195
-            'lat'       => $decodedPoint->y(),
196
-            'lon'       => $decodedPoint->x(),
197
-            'geohash'   => $geohash,
198
-            'precision' => $this->precision [strlen($geohash)]
199
-        );
200
-    }
192
+		return array(
193
+			'pages'     => $pages,
194
+			'media'     => $media,
195
+			'lat'       => $decodedPoint->y(),
196
+			'lon'       => $decodedPoint->x(),
197
+			'geohash'   => $geohash,
198
+			'precision' => $this->precision [strlen($geohash)]
199
+		);
200
+	}
201 201
 }
Please login to merge, or discard this patch.
Spacing   +15 added lines, -15 removed lines patch added patch discarded remove patch
@@ -59,13 +59,13 @@  discard block
 block discarded – undo
59 59
         // parent::__construct ();
60 60
         global $conf;
61 61
 
62
-        if(!$geophp = &plugin_load('helper', 'geophp')) {
62
+        if (!$geophp = &plugin_load('helper', 'geophp')) {
63 63
             $message = 'helper_plugin_spatialhelper_search::spatialhelper_search: geophp plugin is not available.';
64 64
             msg($message, -1);
65 65
         }
66 66
 
67 67
         $idx_dir = $conf ['indexdir'];
68
-        if(!@file_exists($idx_dir . '/spatial.idx')) {
68
+        if (!@file_exists($idx_dir . '/spatial.idx')) {
69 69
             $indexer = plugin_load('helper', 'spatialhelper_index');
70 70
         }
71 71
 
@@ -96,7 +96,7 @@  discard block
 block discarded – undo
96 96
      */
97 97
     public function findNearby($geohash, Point $p = null) {
98 98
         $_geohashClass = new Geohash();
99
-        if(!$p) {
99
+        if (!$p) {
100 100
             $decodedPoint = $_geohashClass->read($geohash);
101 101
         } else {
102 102
             $decodedPoint = $p;
@@ -117,10 +117,10 @@  discard block
 block discarded – undo
117 117
 
118 118
         // find all the pages in the index that overlap with the adjacent hashes
119 119
         $docIds = array();
120
-        foreach($adjacent as $adjHash) {
121
-            if(is_array($this->spatial_idx)) {
122
-                foreach($this->spatial_idx as $_geohash => $_docIds) {
123
-                    if(strstr($_geohash, $adjHash)) {
120
+        foreach ($adjacent as $adjHash) {
121
+            if (is_array($this->spatial_idx)) {
122
+                foreach ($this->spatial_idx as $_geohash => $_docIds) {
123
+                    if (strstr($_geohash, $adjHash)) {
124 124
                         // dbglog ( "Found adjacent geo hash: $adjHash in $_geohash" );
125 125
                         // if $adjHash similar to geohash
126 126
                         $docIds = array_merge($docIds, $_docIds);
@@ -136,10 +136,10 @@  discard block
 block discarded – undo
136 136
         $media   = array();
137 137
         $indexer = plugin_load('helper', 'spatialhelper_index');
138 138
 
139
-        foreach($docIds as $id) {
140
-            if(strpos($id, 'media__', 0) === 0) {
139
+        foreach ($docIds as $id) {
140
+            if (strpos($id, 'media__', 0) === 0) {
141 141
                 $id = substr($id, strlen('media__'));
142
-                if(auth_quickaclcheck($id) >= /*AUTH_READ*/ 1) {
142
+                if (auth_quickaclcheck($id) >= /*AUTH_READ*/ 1) {
143 143
                     $point    = $indexer->getCoordsFromExif($id);
144 144
                     $line     = new LineString(
145 145
                         [
@@ -149,14 +149,14 @@  discard block
 block discarded – undo
149 149
                     );
150 150
                     $media [] = array(
151 151
                         'id'       => $id,
152
-                        'distance' => (int) ($line->greatCircleLength()),
152
+                        'distance' => ( int ) ($line->greatCircleLength()),
153 153
                         'lat'      => $point->y(),
154 154
                         'lon'      => $point->x()
155 155
                         // optionally add other meta such as tag, description...
156 156
                     );
157 157
                 }
158 158
             } else {
159
-                if(auth_quickaclcheck($id) >= /*AUTH_READ*/ 1) {
159
+                if (auth_quickaclcheck($id) >= /*AUTH_READ*/ 1) {
160 160
                     $geotags  = p_get_metadata($id, 'geo');
161 161
                     $point    = new Point($geotags ['lon'], $geotags ['lat']);
162 162
                     $line     = new LineString(
@@ -167,7 +167,7 @@  discard block
 block discarded – undo
167 167
                     );
168 168
                     $pages [] = array(
169 169
                         'id'          => $id,
170
-                        'distance'    => (int) ($line->greatCircleLength()),
170
+                        'distance'    => ( int ) ($line->greatCircleLength()),
171 171
                         'description' => p_get_metadata($id, 'description')['abstract'],
172 172
                         'lat'         => $geotags ['lat'],
173 173
                         'lon'         => $geotags ['lon']
@@ -179,12 +179,12 @@  discard block
 block discarded – undo
179 179
 
180 180
         // sort all the pages/media using distance
181 181
         usort(
182
-            $pages, function ($a, $b) {
182
+            $pages, function($a, $b) {
183 183
             return strnatcmp($a ['distance'], $b ['distance']);
184 184
         }
185 185
         );
186 186
         usort(
187
-            $media, function ($a, $b) {
187
+            $media, function($a, $b) {
188 188
             return strnatcmp($a ['distance'], $b ['distance']);
189 189
         }
190 190
         );
Please login to merge, or discard this patch.