Completed
Push — master ( 3b5393...310e09 )
by Mark
14s
created

createKMLSitemap()   B

Complexity

Conditions 7
Paths 8

Size

Total Lines 64
Code Lines 41

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 64
rs 7.2058
c 0
b 0
f 0
cc 7
eloc 41
nc 8
nop 1

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/*
3
 * Copyright (c) 2014-2016 Mark C. Prins <[email protected]>
4
 *
5
 * Permission to use, copy, modify, and distribute this software for any
6
 * purpose with or without fee is hereby granted, provided that the above
7
 * copyright notice and this permission notice appear in all copies.
8
 *
9
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
10
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
11
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
12
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
13
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
14
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
15
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
16
 */
17
if (!defined('DOKU_INC')) {
18
	die ();
19
}
20
if (!defined('DOKU_PLUGIN')) {
21
	define('DOKU_PLUGIN', DOKU_INC . 'lib/plugins/');
22
}
23
if (!defined('DOKU_LF')) {
24
	define('DOKU_LF', "\n");
25
}
26
27
/**
28
 * DokuWiki Plugin spatialhelper (sitemap Component).
29
 *
30
 * @license BSD license
31
 * @author Mark Prins
32
 */
33
class helper_plugin_spatialhelper_sitemap extends DokuWiki_Plugin {
34
	/**
35
	 * spatial index.
36
	 */
37
	var $spatial_idx = array();
38
39
	/**
40
	 * constructor, load spatial index.
41
	 */
42
	public function __construct() {
43
		global $conf;
44
		$idx_dir = $conf['indexdir'];
45
		if (!@file_exists($idx_dir . '/spatial.idx')) {
46
			$indexer = plugin_load('helper', 'spatialhelper_index');
47
			$indexer->generateSpatialIndex();
48
		}
49
		$this->spatial_idx = unserialize(io_readFile($fn = $idx_dir . '/spatial.idx', false));
50
	}
51
52
	public function getMethods() {
53
		$result[] = array(
0 ignored issues
show
Coding Style Comprehensibility introduced by
$result was never initialized. Although not strictly required by PHP, it is generally a good practice to add $result = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
54
				'name' => 'createGeoRSSSitemap',
55
				'desc' => 'create a spatial sitemap in GeoRSS format.',
56
				'params' => array(
57
						'path' => 'string'
58
				),
59
				'return' => array(
60
						'success' => 'boolean'
61
				)
62
		);
63
		$result[] = array(
64
				'name' => 'createKMLSitemap',
65
				'desc' => 'create a spatial sitemap in KML format.',
66
				'params' => array(
67
						'path' => 'string'
68
				),
69
				'return' => array(
70
						'success' => 'boolean'
71
				)
72
		);
73
		return $result;
74
	}
75
76
	/**
77
	 * Create a GeoRSS Simple sitemap (Atom).
78
	 *
79
	 * @param $mediaID id
80
	 *        	for the GeoRSS file
81
	 */
82
	public function createGeoRSSSitemap($mediaID) {
83
		global $conf;
84
		$namespace = getNS($mediaID);
85
86
		$idTag = 'tag:' . parse_url(DOKU_URL, PHP_URL_HOST) . ',';
87
88
		$RSSstart = '<?xml version="1.0" encoding="UTF-8"?>' . DOKU_LF;
89
		$RSSstart .= '<feed xmlns="http://www.w3.org/2005/Atom" xmlns:georss="http://www.georss.org/georss" xmlns:dc="http://purl.org/dc/elements/1.1/">' . DOKU_LF;
90
		$RSSstart .= '<title>' . $conf['title'] . ' spatial feed</title>' . DOKU_LF;
91
		if (!empty($conf['tagline'])) {
92
			$RSSstart .= '<subtitle>' . $conf['tagline'] . '</subtitle>' . DOKU_LF;
93
		}
94
		$RSSstart .= '<dc:publisher>' . $conf['title'] . '</dc:publisher>' . DOKU_LF;
95
		$RSSstart .= '<link href="' . DOKU_URL . '" />' . DOKU_LF;
96
		$RSSstart .= '<link href="' . ml($mediaID, '', true, '&amp;', true) . '" rel="self" />' . DOKU_LF;
97
		$RSSstart .= '<updated>' . date(DATE_ATOM) . '</updated>' . DOKU_LF;
98
		$RSSstart .= '<id>' . $idTag . date("Y-m-d") . ':' . parse_url(ml($mediaID), PHP_URL_PATH) . '</id>' . DOKU_LF;
99
		$RSSstart .= '<rights>' . $conf['license'] . '</rights>' . DOKU_LF;
100
101
		$RSSend = '</feed>' . DOKU_LF;
102
103
		io_createNamespace($mediaID, 'media');
104
		@touch(mediaFN($mediaID));
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
105
		@chmod(mediaFN($mediaID), $conf['fmode']);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
106
		$fh = fopen(mediaFN($mediaID), 'w');
107
		fwrite($fh, $RSSstart);
108
109
		foreach ($this->spatial_idx as $idxEntry) {
110
			// get list of id's
111
			foreach ($idxEntry as $id) {
112
				// for document item in the index
113
				if (strpos($id, 'media__', 0) !== 0) {
114
					if ($this->_skipPage($id, $namespace)) {
115
						continue;
116
					}
117
118
					$meta = p_get_metadata($id);
119
120
					// $desc = p_render('xhtmlsummary', p_get_instructions($meta['description']['abstract']), $info);
0 ignored issues
show
Unused Code Comprehensibility introduced by
68% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
121
					$desc = strip_tags($meta['description']['abstract']);
122
123
					$entry = '<entry>' . DOKU_LF;
124
					$entry .= '  <title>' . $meta['title'] . '</title>' . DOKU_LF;
125
					$entry .= '  <summary>' . $desc . '</summary>' . DOKU_LF;
126
					$entry .= '  <georss:point>' . $meta['geo']['lat'] . ' ' . $meta['geo']['lon'] . '</georss:point>' . DOKU_LF;
127
					if ($meta['geo']['alt']) {
128
						$entry .= '  <georss:elev>' . $meta['geo']['alt'] . '</georss:elev>' . DOKU_LF;
129
					}
130
					$entry .= '  <link href="' . wl($id) . '" rel="alternate" type="text/html" />' . DOKU_LF;
131
					if (empty($meta['creator'])) {
132
						$meta['creator'] = $conf['title'];
133
					}
134
					$entry .= '  <author><name>' . $meta['creator'] . '</name></author>' . DOKU_LF;
135
					$entry .= '  <updated>' . date_iso8601($meta['date']['modified']) . '</updated>' . DOKU_LF;
136
					$entry .= '  <published>' . date_iso8601($meta['date']['created']) . '</published>' . DOKU_LF;
137
					$entry .= '  <id>' . $idTag . date("Y-m-d", $meta['date']['modified']) . ':' . parse_url(wl($id), PHP_URL_PATH) . '</id>' . DOKU_LF;
138
					$entry .= '</entry>' . DOKU_LF;
139
					fwrite($fh, $entry);
140
				}
141
			}
142
		}
143
144
		fwrite($fh, $RSSend);
145
		return fclose($fh);
146
	}
147
148
	/**
149
	 * Create a KML sitemap.
150
	 *
151
	 * @param $mediaID id
152
	 *        	for the KML file
153
	 */
154
	public function createKMLSitemap($mediaID) {
155
		global $conf;
156
		$namespace = getNS($mediaID);
157
158
		$KMLstart = '<?xml version="1.0" encoding="UTF-8"?>' . DOKU_LF;
159
		$KMLstart .= '<kml xmlns="http://www.opengis.net/kml/2.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:atom="http://www.w3.org/2005/Atom"';
160
		$KMLstart .= ' xsi:schemaLocation="http://www.opengis.net/kml/2.2 http://schemas.opengis.net/kml/2.2.0/ogckml22.xsd">' . DOKU_LF;
161
		$KMLstart .= '<Document id="root_doc">' . DOKU_LF;
162
		$KMLstart .= '<name>' . $conf['title'] . ' spatial sitemap</name>' . DOKU_LF;
163
		$KMLstart .= '<atom:link href="' . DOKU_URL . '" rel="related" type="text/html" />' . DOKU_LF;
164
		$KMLstart .= '<!-- atom:updated>' . date(DATE_ATOM) . '</atom:updated -->' . DOKU_LF;
165
		$KMLstart .= '<Style id="icon"><IconStyle><color>ffffffff</color><scale>1</scale>';
166
		$KMLstart .= '<Icon><href>' . DOKU_BASE . 'lib/plugins/spatialhelper/wikiitem.png</href></Icon></IconStyle></Style>' . DOKU_LF;
167
168
		$KMLend = '</Document>' . DOKU_LF . '</kml>';
169
170
		io_createNamespace($mediaID, 'media');
171
		@touch(mediaFN($mediaID));
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
172
		@chmod(mediaFN($mediaID), $conf['fmode']);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
173
174
		$fh = fopen(mediaFN($mediaID), 'w');
175
		fwrite($fh, $KMLstart);
176
177
		foreach ($this->spatial_idx as $idxEntry) {
178
			// get list of id's
179
			foreach ($idxEntry as $id) {
180
				// for document item in the index
181
				if (strpos($id, 'media__', 0) !== 0) {
182
					if ($this->_skipPage($id, $namespace)) {
183
						continue;
184
					}
185
186
					$meta = p_get_metadata($id);
187
188
					// $desc = p_render('xhtmlsummary', p_get_instructions($meta['description']['abstract']), $info);
0 ignored issues
show
Unused Code Comprehensibility introduced by
68% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
189
					$desc = '<p>' . strip_tags($meta['description']['abstract']) . '</p>';
190
					$desc .= '<p><a href="' . wl($id, '', true) . '">' . $meta['title'] . '</a></p>';
191
192
					// create an entry and store it
193
					$plcm = '<Placemark id="crc32-' . hash('crc32', $id) . '">' . DOKU_LF;
194
					$plcm .= '  <name>' . $meta['title'] . '</name>' . DOKU_LF;
195
					// TODO escape quotes in: title="' . $meta['title'] . '"
196
					$plcm .= '  <atom:link href="' . wl($id, '' . true) . '" rel="alternate" type="text/html" />' . DOKU_LF;
197
					if (!empty($meta['creator'])) {
198
						$entry .= '  <atom:author><atom:name>' . $meta['creator'] . '</atom:name></atom:author>' . DOKU_LF;
0 ignored issues
show
Bug introduced by
The variable $entry does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
199
					}
200
201
					$plcm .= '  <description><![CDATA[' . $desc . ']]></description>' . DOKU_LF;
202
					$plcm .= '  <styleUrl>#icon</styleUrl>' . DOKU_LF;
203
204
					$plcm .= '  <Point><coordinates>' . $meta['geo']['lon'] . ',' . $meta['geo']['lat'];
205
					if ($meta['geo']['alt']) {
206
						$plcm .= ',' . $meta['geo']['alt'];
207
					}
208
					$plcm .= '</coordinates></Point>' . DOKU_LF;
209
					$plcm .= '</Placemark>' . DOKU_LF;
210
211
					fwrite($fh, $plcm);
212
				}
213
			}
214
		}
215
		fwrite($fh, $KMLend);
216
		return fclose($fh);
217
	}
218
	/**
219
	 * will return true for non-public or hidden pages or pages that are not below or in the namespace.
220
	 */
221
	private function _skipPage($id, $namespace) {
222
		dbglog("helper_plugin_spatialhelper_sitemap::_skipPage, check for $id in $namespace");
223
		if (isHiddenPage($id)) {
224
			return true;
225
		}
226
		if (auth_aclcheck($id, '', '') < AUTH_READ) {
227
			return true;
228
		}
229
230
		if (!empty($namespace)) {
231
			// only if id is in or below namespace
232
			if (0 !== strpos(getNS($id), $namespace)) {
233
				dbglog("helper_plugin_spatialhelper_sitemap::_skipPage, skipping $id, not in $namespace");
234
				return true;
235
			}
236
		}
237
		return false;
238
	}
239
}
240