Completed
Pull Request — master (#313)
by Thomas
09:55
created
htdocs/okapi/services/caches/map/tiletree.inc.php 5 patches
Doc Comments   +3 added lines patch added patch discarded remove patch
@@ -57,6 +57,9 @@
 block discarded – undo
57 57
      * Note that $pixels can also be negative or >=256 (up to a margin of 32px).
58 58
      * Count is the number of other caches "eclipsed" by this geocache (such
59 59
      * eclipsed geocaches are not included in the result).
60
+     * @param integer $zoom
61
+     * @param integer $x
62
+     * @param integer $y
60 63
      */
61 64
     public static function query_fast($zoom, $x, $y, $set_id)
62 65
     {
Please login to merge, or discard this patch.
Indentation   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -312,7 +312,7 @@
 block discarded – undo
312 312
          * avoid MySQL casting negative values to 0, we'll do an additional
313 313
          * abs on it. */
314 314
 
315
-         return abs(crc32($name));
315
+            return abs(crc32($name));
316 316
     }
317 317
 
318 318
     private static function latlon_to_z21xy($lat, $lon)
Please login to merge, or discard this patch.
Unused Use Statements   +2 added lines, -10 removed lines patch added patch discarded remove patch
@@ -3,20 +3,12 @@
 block discarded – undo
3 3
 namespace okapi\services\caches\map;
4 4
 
5 5
 use Exception;
6
-use okapi\Okapi;
7
-use okapi\Settings;
8 6
 use okapi\Cache;
9 7
 use okapi\Db;
10
-use okapi\OkapiRequest;
11
-use okapi\OkapiHttpResponse;
12
-use okapi\ParamMissing;
13
-use okapi\InvalidParam;
14
-use okapi\BadRequest;
15
-use okapi\DoesNotExist;
16
-use okapi\OkapiInternalRequest;
8
+use okapi\Okapi;
17 9
 use okapi\OkapiInternalConsumer;
10
+use okapi\OkapiInternalRequest;
18 11
 use okapi\OkapiServiceRunner;
19
-use okapi\OkapiLock;
20 12
 
21 13
 
22 14
 class TileTree
Please login to merge, or discard this patch.
Spacing   +4 added lines, -4 removed lines patch added patch discarded remove patch
@@ -135,8 +135,8 @@  discard block
 block discarded – undo
135 135
             # but there is *no need* to - this query is run seldom and is cached.
136 136
 
137 137
             $params = array();
138
-            $params['status'] = "Available|Temporarily unavailable|Archived";  # we want them all
139
-            $params['limit'] = "10000000";  # no limit
138
+            $params['status'] = "Available|Temporarily unavailable|Archived"; # we want them all
139
+            $params['limit'] = "10000000"; # no limit
140 140
 
141 141
             $internal_request = new OkapiInternalRequest(new OkapiInternalConsumer(), null, $params);
142 142
             $internal_request->skip_limits = true;
@@ -244,7 +244,7 @@  discard block
 block discarded – undo
244 244
                     ");
245 245
                     Db::execute("unlock tables;");
246 246
                 } catch (Exception $e) {
247
-                    Db::execute("unlock tables");  // No "finally" in PHP 5.3
247
+                    Db::execute("unlock tables"); // No "finally" in PHP 5.3
248 248
                     throw $e;
249 249
                 }
250 250
                 $test = Db::select_value("
@@ -319,7 +319,7 @@  discard block
 block discarded – undo
319 319
     {
320 320
         $offset = 128 << 21;
321 321
         $x = round($offset + ($offset * $lon / 180));
322
-        $y = round($offset - $offset/pi() * log((1 + sin($lat * pi() / 180)) / (1 - sin($lat * pi() / 180))) / 2);
322
+        $y = round($offset - $offset / pi() * log((1 + sin($lat * pi() / 180)) / (1 - sin($lat * pi() / 180))) / 2);
323 323
         return array($x, $y);
324 324
     }
325 325
 }
326 326
\ No newline at end of file
Please login to merge, or discard this patch.
Braces   +42 added lines, -27 removed lines patch added patch discarded remove patch
@@ -64,19 +64,23 @@  discard block
 block discarded – undo
64 64
         # (and if it was, was it empty).
65 65
 
66 66
         $status = self::get_tile_status($zoom, $x, $y);
67
-        if ($status === null)  # Not yet computed.
67
+        if ($status === null) {
68
+            # Not yet computed.
68 69
         {
69 70
             # Note, that computing the tile does not involve taking any
70 71
             # search parameters.
71 72
 
72 73
             $status = self::compute_tile($zoom, $x, $y);
73 74
         }
75
+        }
74 76
 
75
-        if ($status === 1)  # Computed and empty.
77
+        if ($status === 1) {
78
+            # Computed and empty.
76 79
         {
77 80
             # This tile was already computed and it is empty.
78 81
             return null;
79 82
         }
83
+        }
80 84
 
81 85
         # If we got here, then the tile is computed and not empty (status 2).
82 86
 
@@ -121,11 +125,11 @@  discard block
 block discarded – undo
121 125
         # For low-level tiles, this can be expensive.
122 126
 
123 127
         $status = self::get_tile_status($zoom, $x, $y);
124
-        if ($status !== null)
125
-            return $status;
128
+        if ($status !== null) {
129
+                    return $status;
130
+        }
126 131
 
127
-        if ($zoom === 0)
128
-        {
132
+        if ($zoom === 0) {
129 133
             # When computing zoom zero, we don't have a parent to speed up
130 134
             # the computation. We need to use the caches table. Note, that
131 135
             # zoom level 0 contains *entire world*, so we don't have to use
@@ -150,8 +154,7 @@  discard block
 block discarded – undo
150 154
             $internal_request->skip_limits = true;
151 155
             $caches = OkapiServiceRunner::call("services/caches/geocaches", $internal_request);
152 156
 
153
-            foreach ($caches as $cache)
154
-            {
157
+            foreach ($caches as $cache) {
155 158
                 $row = self::generate_short_row($cache);
156 159
                 if (!$row) {
157 160
                     /* Some caches cannot be included, e.g. the ones near the poles. */
@@ -174,9 +177,7 @@  discard block
 block discarded – undo
174 177
                 ");
175 178
             }
176 179
             $status = 2;
177
-        }
178
-        else
179
-        {
180
+        } else {
180 181
             # We will use the parent tile to compute the contents of this tile.
181 182
 
182 183
             $parent_zoom = $zoom - 1;
@@ -184,19 +185,23 @@  discard block
 block discarded – undo
184 185
             $parent_y = $y >> 1;
185 186
 
186 187
             $status = self::get_tile_status($parent_zoom, $parent_x, $parent_y);
187
-            if ($status === null)  # Not computed.
188
+            if ($status === null) {
189
+                # Not computed.
188 190
             {
189 191
                 $time_started = microtime(true);
192
+            }
190 193
                 $status = self::compute_tile($parent_zoom, $parent_x, $parent_y);
191 194
             }
192 195
 
193
-            if ($status === 1)  # Computed and empty.
196
+            if ($status === 1) {
197
+                # Computed and empty.
194 198
             {
195 199
                 # No need to check.
196 200
             }
197 201
             else  # Computed, not empty.
198 202
             {
199 203
                 $scale = 8 + 21 - $zoom;
204
+            }
200 205
                 $parentcenter_z21x = (($parent_x << 1) | 1) << $scale;
201 206
                 $parentcenter_z21y = (($parent_y << 1) | 1) << $scale;
202 207
                 $margin = 1 << ($scale - 2);
@@ -209,14 +214,20 @@  discard block
 block discarded – undo
209 214
                 # |1 2|
210 215
                 # |3 4|
211 216
 
212
-                if ($x & 1)  # 2 or 4
217
+                if ($x & 1) {
218
+                    # 2 or 4
213 219
                     $left_z21x = $parentcenter_z21x - $margin;
214
-                else  # 1 or 3
220
+                } else {
221
+                    # 1 or 3
215 222
                     $right_z21x = $parentcenter_z21x + $margin;
216
-                if ($y & 1)  # 3 or 4
223
+                }
224
+                if ($y & 1) {
225
+                    # 3 or 4
217 226
                     $top_z21y = $parentcenter_z21y - $margin;
218
-                else  # 1 or 2
227
+                } else {
228
+                    # 1 or 2
219 229
                     $bottom_z21y = $parentcenter_z21y + $margin;
230
+                }
220 231
 
221 232
                 # Cache the result.
222 233
 
@@ -256,10 +267,11 @@  discard block
 block discarded – undo
256 267
                         and y = '".Db::escape_string($y)."'
257 268
                     limit 1;
258 269
                 ");
259
-                if ($test)
260
-                    $status = 2;
261
-                else
262
-                    $status = 1;
270
+                if ($test) {
271
+                                    $status = 2;
272
+                } else {
273
+                                    $status = 1;
274
+                }
263 275
             }
264 276
         }
265 277
 
@@ -294,12 +306,15 @@  discard block
 block discarded – undo
294 306
             return false;
295 307
         }
296 308
         $flags = 0;
297
-        if (($cache['founds'] > 6) && (($cache['recommendations'] / $cache['founds']) > 0.3))
298
-            $flags |= self::$FLAG_STAR;
299
-        if ($cache['trackables_count'] > 0)
300
-            $flags |= self::$FLAG_HAS_TRACKABLES;
301
-        if ($cache['founds'] == 0)
302
-            $flags |= self::$FLAG_NOT_YET_FOUND;
309
+        if (($cache['founds'] > 6) && (($cache['recommendations'] / $cache['founds']) > 0.3)) {
310
+                    $flags |= self::$FLAG_STAR;
311
+        }
312
+        if ($cache['trackables_count'] > 0) {
313
+                    $flags |= self::$FLAG_HAS_TRACKABLES;
314
+        }
315
+        if ($cache['founds'] == 0) {
316
+                    $flags |= self::$FLAG_NOT_YET_FOUND;
317
+        }
303 318
         return array($cache['internal_id'], $z21x, $z21y, Okapi::cache_status_name2id($cache['status']),
304 319
             Okapi::cache_type_name2id($cache['type']), $cache['rating'], $flags,
305 320
             self::compute_name_crc($cache['name']));
Please login to merge, or discard this patch.
htdocs/okapi/services/caches/save_personal_notes.php 4 patches
Doc Comments   +3 added lines patch added patch discarded remove patch
@@ -108,6 +108,9 @@
 block discarded – undo
108 108
         return $str1 == $str2;
109 109
     }
110 110
 
111
+    /**
112
+     * @param string $new_notes
113
+     */
111 114
     private static function update_notes($cache_id, $user_id, $new_notes)
112 115
     {
113 116
         if (Settings::get('OC_BRANCH') == 'oc.de')
Please login to merge, or discard this patch.
Unused Use Statements   +3 added lines, -7 removed lines patch added patch discarded remove patch
@@ -2,16 +2,12 @@
 block discarded – undo
2 2
 
3 3
 namespace okapi\services\caches\save_personal_notes;
4 4
 
5
-use Exception;
6
-use okapi\Okapi;
7 5
 use okapi\Db;
8
-use okapi\OkapiRequest;
9
-use okapi\ParamMissing;
10
-use okapi\InvalidParam;
11
-use okapi\BadRequest;
6
+use okapi\Okapi;
12 7
 use okapi\OkapiInternalRequest;
8
+use okapi\OkapiRequest;
13 9
 use okapi\OkapiServiceRunner;
14
-use okapi\OkapiAccessToken;
10
+use okapi\ParamMissing;
15 11
 use okapi\Settings;
16 12
 
17 13
 
Please login to merge, or discard this patch.
Spacing   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -127,7 +127,7 @@  discard block
 block discarded – undo
127 127
                     and user_id = '".Db::escape_string($user_id)."'
128 128
             ");
129 129
             $id = null;
130
-            if($row = Db::fetch_assoc($rs)) {
130
+            if ($row = Db::fetch_assoc($rs)) {
131 131
                 $id = $row['id'];
132 132
             }
133 133
             if ($id == null) {
@@ -162,7 +162,7 @@  discard block
 block discarded – undo
162 162
                     and user_id = '".Db::escape_string($user_id)."'
163 163
             ");
164 164
             $id = null;
165
-            if($row = Db::fetch_assoc($rs)) {
165
+            if ($row = Db::fetch_assoc($rs)) {
166 166
                 $id = $row['id'];
167 167
             }
168 168
             if ($id == null) {
@@ -202,7 +202,7 @@  discard block
 block discarded – undo
202 202
                     and longitude = 0
203 203
                     and latitude = 0
204 204
             ");
205
-            if (Db::get_affected_row_count() <= 0){
205
+            if (Db::get_affected_row_count() <= 0) {
206 206
                 # no rows deleted - record either doesn't exist, or has coords
207 207
                 # remove only description
208 208
                 Db::execute("
Please login to merge, or discard this patch.
Braces   +20 added lines, -16 removed lines patch added patch discarded remove patch
@@ -29,8 +29,9 @@  discard block
 block discarded – undo
29 29
         # Get current notes, and verify cache_code
30 30
 
31 31
         $cache_code = $request->get_parameter('cache_code');
32
-        if ($cache_code == null)
33
-            throw new ParamMissing('cache_code');
32
+        if ($cache_code == null) {
33
+                    throw new ParamMissing('cache_code');
34
+        }
34 35
         $geocache = OkapiServiceRunner::call(
35 36
             'services/caches/geocache',
36 37
             new OkapiInternalRequest($request->consumer, $request->token, array(
@@ -47,14 +48,16 @@  discard block
 block discarded – undo
47 48
         # old_value
48 49
 
49 50
         $old_value = $request->get_parameter('old_value');
50
-        if ($old_value === null)
51
-            $old_value = '';
51
+        if ($old_value === null) {
52
+                    $old_value = '';
53
+        }
52 54
 
53 55
         # new_value (force "no HTML" policy).
54 56
 
55 57
         $new_value = $request->get_parameter('new_value');
56
-        if ($new_value === null)
57
-            throw new ParamMissing('new_value');
58
+        if ($new_value === null) {
59
+                    throw new ParamMissing('new_value');
60
+        }
58 61
 
59 62
         # Force "no HTML" policy.
60 63
 
@@ -98,10 +101,12 @@  discard block
 block discarded – undo
98 101
 
99 102
     private static function str_equals($str1, $str2)
100 103
     {
101
-        if ($str1 == null)
102
-            $str1 = '';
103
-        if ($str2 == null)
104
-            $str2 = '';
104
+        if ($str1 == null) {
105
+                    $str1 = '';
106
+        }
107
+        if ($str2 == null) {
108
+                    $str2 = '';
109
+        }
105 110
         $str1 = mb_ereg_replace("[ \t\n\r\x0B]+", '', $str1);
106 111
         $str2 = mb_ereg_replace("[ \t\n\r\x0B]+", '', $str2);
107 112
 
@@ -110,8 +115,7 @@  discard block
 block discarded – undo
110 115
 
111 116
     private static function update_notes($cache_id, $user_id, $new_notes)
112 117
     {
113
-        if (Settings::get('OC_BRANCH') == 'oc.de')
114
-        {
118
+        if (Settings::get('OC_BRANCH') == 'oc.de') {
115 119
             /* See:
116 120
              *
117 121
              * - https://github.com/OpencachingDeutschland/oc-server3/tree/master/htdocs/libse/CacheNote
@@ -151,8 +155,7 @@  discard block
 block discarded – undo
151 155
                         and type = 2
152 156
                 ");
153 157
             }
154
-        }
155
-        else  # oc.pl branch
158
+        } else  # oc.pl branch
156 159
         {
157 160
             $rs = Db::query("
158 161
                 select max(note_id) as id
@@ -202,7 +205,7 @@  discard block
 block discarded – undo
202 205
                     and longitude = 0
203 206
                     and latitude = 0
204 207
             ");
205
-            if (Db::get_affected_row_count() <= 0){
208
+            if (Db::get_affected_row_count() <= 0) {
206 209
                 # no rows deleted - record either doesn't exist, or has coords
207 210
                 # remove only description
208 211
                 Db::execute("
@@ -214,7 +217,8 @@  discard block
 block discarded – undo
214 217
                         and user_id = '".Db::escape_string($user_id)."'
215 218
                 ");
216 219
             }
217
-        } else {  # oc.pl branch
220
+        } else {
221
+# oc.pl branch
218 222
             Db::execute("
219 223
                 delete from cache_notes
220 224
                 where
Please login to merge, or discard this patch.
htdocs/okapi/services/caches/search/save.php 4 patches
Doc Comments   +2 added lines patch added patch discarded remove patch
@@ -24,6 +24,7 @@  discard block
 block discarded – undo
24 24
     /**
25 25
      * Get [set_id, date_created, expires] for the given params_hash
26 26
      * (or [null, null, null] if not found).
27
+     * @param string $params_hash
27 28
      */
28 29
     private static function find_param_set($params_hash, $ref_max_age)
29 30
     {
@@ -92,6 +93,7 @@  discard block
 block discarded – undo
92 93
     /**
93 94
      * Important: YOU HAVE TO make sure $tables and $where_conds don't contain
94 95
      * unescaped user-supplied data!
96
+     * @param string[] $tables
95 97
      */
96 98
     public static function get_set($tables, $joins, $where_conds, $min_store, $ref_max_age)
97 99
     {
Please login to merge, or discard this patch.
Unused Use Statements   +3 added lines, -4 removed lines patch added patch discarded remove patch
@@ -4,12 +4,11 @@
 block discarded – undo
4 4
 
5 5
 require_once('searching.inc.php');
6 6
 
7
-use okapi\Okapi;
8
-use okapi\OkapiRequest;
9
-use okapi\ParamMissing;
10
-use okapi\InvalidParam;
11 7
 use okapi\Db;
8
+use okapi\InvalidParam;
9
+use okapi\Okapi;
12 10
 use okapi\OkapiLock;
11
+use okapi\OkapiRequest;
13 12
 use okapi\services\caches\search\SearchAssistant;
14 13
 
15 14
 class WebService
Please login to merge, or discard this patch.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -51,7 +51,7 @@
 block discarded – undo
51 51
         $tmp = $request->get_parameter('min_store');
52 52
         if ($tmp === null) $tmp = "300";
53 53
         $min_store = intval($tmp);
54
-        if (("$min_store" !== $tmp) ||($min_store < 0) || ($min_store > 64800))
54
+        if (("$min_store" !== $tmp) || ($min_store < 0) || ($min_store > 64800))
55 55
             throw new InvalidParam('min_store', "Has to be in the 0..64800 range.");
56 56
 
57 57
         $tmp = $request->get_parameter('ref_max_age');
Please login to merge, or discard this patch.
Braces   +28 added lines, -24 removed lines patch added patch discarded remove patch
@@ -39,8 +39,9 @@  discard block
 block discarded – undo
39 39
             order by id desc
40 40
             limit 1
41 41
         ");
42
-        if ($tmp === null)
43
-            return array(null, null, null);
42
+        if ($tmp === null) {
43
+                    return array(null, null, null);
44
+        }
44 45
         return array($tmp['id'], $tmp['date_created'], $tmp['expires']);
45 46
     }
46 47
 
@@ -49,17 +50,25 @@  discard block
 block discarded – undo
49 50
         # "Cache control" parameters.
50 51
 
51 52
         $tmp = $request->get_parameter('min_store');
52
-        if ($tmp === null) $tmp = "300";
53
+        if ($tmp === null) {
54
+            $tmp = "300";
55
+        }
53 56
         $min_store = intval($tmp);
54
-        if (("$min_store" !== $tmp) ||($min_store < 0) || ($min_store > 64800))
55
-            throw new InvalidParam('min_store', "Has to be in the 0..64800 range.");
57
+        if (("$min_store" !== $tmp) ||($min_store < 0) || ($min_store > 64800)) {
58
+                    throw new InvalidParam('min_store', "Has to be in the 0..64800 range.");
59
+        }
56 60
 
57 61
         $tmp = $request->get_parameter('ref_max_age');
58
-        if ($tmp === null) $tmp = "300";
59
-        if ($tmp == "nolimit") $tmp = "9999999";
62
+        if ($tmp === null) {
63
+            $tmp = "300";
64
+        }
65
+        if ($tmp == "nolimit") {
66
+            $tmp = "9999999";
67
+        }
60 68
         $ref_max_age = intval($tmp);
61
-        if (("$ref_max_age" !== $tmp) || ($ref_max_age < 300))
62
-            throw new InvalidParam('ref_max_age', "Has to be >=300.");
69
+        if (("$ref_max_age" !== $tmp) || ($ref_max_age < 300)) {
70
+                    throw new InvalidParam('ref_max_age', "Has to be >=300.");
71
+        }
63 72
 
64 73
         # Search params.
65 74
 
@@ -75,10 +84,11 @@  discard block
 block discarded – undo
75 84
             $search_params['where_conds']
76 85
         );
77 86
 
78
-        if (isset($search_params['extra_joins']) && is_array($search_params['extra_joins']))
79
-            $joins = $search_params['extra_joins'];
80
-        else
81
-            $joins = array();
87
+        if (isset($search_params['extra_joins']) && is_array($search_params['extra_joins'])) {
88
+                    $joins = $search_params['extra_joins'];
89
+        } else {
90
+                    $joins = array();
91
+        }
82 92
 
83 93
         unset($search_params);
84 94
 
@@ -103,8 +113,7 @@  discard block
 block discarded – undo
103 113
         # given freshness criteria.
104 114
 
105 115
         list($set_id, $date_created, $expires) = self::find_param_set($params_hash, $ref_max_age);
106
-        if ($set_id === null)
107
-        {
116
+        if ($set_id === null) {
108 117
             # To avoid generating the same results by multiple threads at once
109 118
             # (the "tile" method uses the "save" method, so the problem is
110 119
             # quite real!), we will acquire a write-lock here.
@@ -112,13 +121,11 @@  discard block
 block discarded – undo
112 121
             $lock = OkapiLock::get("search-results-writer");
113 122
             $lock->acquire();
114 123
 
115
-            try
116
-            {
124
+            try {
117 125
                 # Make sure we were the first to acquire the lock.
118 126
 
119 127
                 list($set_id, $date_created, $expires) = self::find_param_set($params_hash, $ref_max_age);
120
-                if ($set_id === null)
121
-                {
128
+                if ($set_id === null) {
122 129
                     # We are in the first thread which have acquired the lock.
123 130
                     # We will proceed with result-set creation. Other threads
124 131
                     # will be waiting until we finish.
@@ -161,9 +168,7 @@  discard block
 block discarded – undo
161 168
                     # generated the result set. We don't need to do anything.
162 169
                 }
163 170
                 $lock->release();
164
-            }
165
-            catch (Exception $e)
166
-            {
171
+            } catch (Exception $e) {
167 172
                 # SQL error? Make sure the lock is released and rethrow.
168 173
 
169 174
                 $lock->release();
@@ -174,8 +179,7 @@  discard block
 block discarded – undo
174 179
         # If we got an old set, we may need to expand its lifetime in order to
175 180
         # meet user's "min_store" criterium.
176 181
 
177
-        if (time() + $min_store > $expires)
178
-        {
182
+        if (time() + $min_store > $expires) {
179 183
             Db::execute("
180 184
                 update okapi_search_sets
181 185
                 set expires = date_add(now(), interval '".Db::escape_string($min_store + 60)."' second)
Please login to merge, or discard this patch.
htdocs/okapi/services/logs/images/add.php 4 patches
Doc Comments   +4 added lines patch added patch discarded remove patch
@@ -284,6 +284,10 @@
 block discarded – undo
284 284
     }
285 285
 
286 286
 
287
+    /**
288
+     * @param string $image_uuid
289
+     * @param string $file_ext
290
+     */
287 291
     private static function db_insert_image(
288 292
         $consumer_key, $user_id,
289 293
         $log_internal_id, $image_uuid, $position, $caption, $is_spoiler, $file_ext)
Please login to merge, or discard this patch.
Unused Use Statements   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -3,13 +3,13 @@
 block discarded – undo
3 3
 namespace okapi\services\logs\images\add;
4 4
 
5 5
 use Exception;
6
-use okapi\Okapi;
6
+use okapi\BadRequest;
7 7
 use okapi\Db;
8
+use okapi\InvalidParam;
9
+use okapi\Okapi;
8 10
 use okapi\OkapiRequest;
9 11
 use okapi\ParamMissing;
10
-use okapi\InvalidParam;
11 12
 use okapi\Settings;
12
-use okapi\BadRequest;
13 13
 use okapi\services\logs\images\LogImagesCommon;
14 14
 
15 15
 
Please login to merge, or discard this patch.
Spacing   +7 added lines, -7 removed lines patch added patch discarded remove patch
@@ -116,7 +116,7 @@  discard block
 block discarded – undo
116 116
             throw new InvalidParam('image', "bad base64 encoding");
117 117
 
118 118
         try {
119
-            $image_properties = getimagesizefromstring($image);  # can throw
119
+            $image_properties = getimagesizefromstring($image); # can throw
120 120
             if (!$image_properties)
121 121
                 throw new Exception();
122 122
             list($width, $height, $image_type) = $image_properties;
@@ -148,7 +148,7 @@  discard block
 block discarded – undo
148 148
             ));
149 149
         }
150 150
         try {
151
-            $image = imagecreatefromstring($image);  # can throw
151
+            $image = imagecreatefromstring($image); # can throw
152 152
             if (!$image) throw new Exception();
153 153
         }
154 154
         catch (Exception $e) {
@@ -224,11 +224,11 @@  discard block
 block discarded – undo
224 224
 
225 225
     private static function max_pixels($base64_image)
226 226
     {
227
-        $bytes_per_pixel = 5;   # GD needs 5 bytes per pixel for "true color"
227
+        $bytes_per_pixel = 5; # GD needs 5 bytes per pixel for "true color"
228 228
         $available_memory = Okapi::php_ini_get_bytes('memory_limit') - memory_get_usage();
229
-        $available_memory -= 16 * 1024 * 1024;  # reserve
230
-        $available_memory -= strlen($base64_image);  # will be copied for EXIF processing
231
-        $available_memory -= 3 * $bytes_per_pixel * Settings::get('IMAGE_MAX_PIXEL_COUNT');  # processing buffers
229
+        $available_memory -= 16 * 1024 * 1024; # reserve
230
+        $available_memory -= strlen($base64_image); # will be copied for EXIF processing
231
+        $available_memory -= 3 * $bytes_per_pixel * Settings::get('IMAGE_MAX_PIXEL_COUNT'); # processing buffers
232 232
         return floor($available_memory / $bytes_per_pixel);
233 233
     }
234 234
 
@@ -269,7 +269,7 @@  discard block
 block discarded – undo
269 269
             # The PHP Exif module can read EXIF data only from files. To avoid
270 270
             # disk I/O overhead, we pipe the image string through a pseudo-file:
271 271
 
272
-            $exif_data = exif_read_data("data://image/jpeg;base64," . $base64_image);
272
+            $exif_data = exif_read_data("data://image/jpeg;base64,".$base64_image);
273 273
             if ($exif_data && isset($exif_data['Orientation'])) {
274 274
                 switch ($exif_data['Orientation'])
275 275
                 {
Please login to merge, or discard this patch.
Braces   +51 added lines, -48 removed lines patch added patch discarded remove patch
@@ -19,7 +19,9 @@  discard block
 block discarded – undo
19 19
  * the Consumer did anything wrong (it's the user who did). This exception shouldn't
20 20
  * be used outside of this file.
21 21
  */
22
-class CannotPublishException extends Exception {}
22
+class CannotPublishException extends Exception
23
+{
24
+}
23 25
 
24 26
 class WebService
25 27
 {
@@ -48,8 +50,9 @@  discard block
 block discarded – undo
48 50
         # validate the 'log_uuid' parameter
49 51
 
50 52
         $log_uuid = $request->get_parameter('log_uuid');
51
-        if (!$log_uuid)
52
-            throw new ParamMissing('log_uuid');
53
+        if (!$log_uuid) {
54
+                    throw new ParamMissing('log_uuid');
55
+        }
53 56
         $rs = Db::query("
54 57
             select id, node, user_id
55 58
             from cache_logs
@@ -57,8 +60,9 @@  discard block
 block discarded – undo
57 60
         );
58 61
         $row = Db::fetch_assoc($rs);
59 62
         Db::free_result($rs);
60
-        if (!$row)
61
-            throw new InvalidParam('log_uuid', "There is no log entry with uuid '".$log_uuid."'.");
63
+        if (!$row) {
64
+                    throw new InvalidParam('log_uuid', "There is no log entry with uuid '".$log_uuid."'.");
65
+        }
62 66
         if ($row['node'] != Settings::get('OC_NODE_ID')) {
63 67
             throw new Exception(
64 68
                 "This site's database contains the log entry '$log_uuid' which has been"
@@ -85,21 +89,24 @@  discard block
 block discarded – undo
85 89
         }
86 90
 
87 91
         $is_spoiler = $request->get_parameter('is_spoiler');
88
-        if ($is_spoiler === null) $is_spoiler = 'false';
89
-        if (!in_array($is_spoiler, array('true', 'false')))
90
-            throw new InvalidParam('is_spoiler');
92
+        if ($is_spoiler === null) {
93
+            $is_spoiler = 'false';
94
+        }
95
+        if (!in_array($is_spoiler, array('true', 'false'))) {
96
+                    throw new InvalidParam('is_spoiler');
97
+        }
91 98
 
92 99
         $position = LogImagesCommon::validate_position($request);
93 100
 
94 101
         # validate the 'image' parameter
95 102
 
96 103
         $base64_image = $request->get_parameter('image');
97
-        if (!$base64_image)
98
-            throw new ParamMissing('image');
104
+        if (!$base64_image) {
105
+                    throw new ParamMissing('image');
106
+        }
99 107
 
100 108
         $estimated_decoded_size = strlen($base64_image) / 4 * 3 - 2;
101
-        if ($estimated_decoded_size > Settings::get('IMAGE_MAX_UPLOAD_SIZE'))
102
-        {
109
+        if ($estimated_decoded_size > Settings::get('IMAGE_MAX_UPLOAD_SIZE')) {
103 110
             $estimated_decoded_size_MB = round($estimated_decoded_size / 1024 / 1024, 1);
104 111
             $max_upload_size_MB = round(Settings::get('IMAGE_MAX_UPLOAD_SIZE') / 1024 / 1024, 1);
105 112
 
@@ -112,20 +119,21 @@  discard block
 block discarded – undo
112 119
         }
113 120
 
114 121
         $image = base64_decode($base64_image);
115
-        if (!$image)
116
-            throw new InvalidParam('image', "bad base64 encoding");
122
+        if (!$image) {
123
+                    throw new InvalidParam('image', "bad base64 encoding");
124
+        }
117 125
 
118 126
         try {
119 127
             $image_properties = getimagesizefromstring($image);  # can throw
120
-            if (!$image_properties)
121
-                throw new Exception();
128
+            if (!$image_properties) {
129
+                            throw new Exception();
130
+            }
122 131
             list($width, $height, $image_type) = $image_properties;
123 132
             if (!in_array($image_type, array(IMAGETYPE_JPEG, IMAGETYPE_PNG, IMAGETYPE_GIF))) {
124 133
                 # This will happen e.g. for BMP and XBM images, which are supported by GD.
125 134
                 throw new Exception();
126 135
             }
127
-        }
128
-        catch (Exception $e) {
136
+        } catch (Exception $e) {
129 137
             # Note: There may be *subtypes* which are not accepted by the GD library.
130 138
             # About 1 of 2000 JPEGs at OC.de is not readable by the PHP functions,
131 139
             # though they can be displayed by web browsers.
@@ -149,9 +157,10 @@  discard block
 block discarded – undo
149 157
         }
150 158
         try {
151 159
             $image = imagecreatefromstring($image);  # can throw
152
-            if (!$image) throw new Exception();
153
-        }
154
-        catch (Exception $e) {
160
+            if (!$image) {
161
+                throw new Exception();
162
+            }
163
+        } catch (Exception $e) {
155 164
             throw new CannotPublishException(_("The uploaded image file is broken."));
156 165
         }
157 166
 
@@ -168,8 +177,7 @@  discard block
 block discarded – undo
168 177
 
169 178
         $image_uuid = Okapi::create_uuid();
170 179
         $imagepath = Settings::get('IMAGES_DIR').'/'.$image_uuid;
171
-        switch ($image_type)
172
-        {
180
+        switch ($image_type) {
173 181
             case IMAGETYPE_JPEG:
174 182
                 $file_ext = '.jpg';
175 183
                 $quality = Settings::get('JPEG_QUALITY');
@@ -190,26 +198,23 @@  discard block
 block discarded – undo
190 198
                 $file_ext = '.???';
191 199
                 $result = false;
192 200
         }
193
-        if (!$result)
194
-            throw new Exception("could not save image file '".$imagepath.$file_ext."'");
201
+        if (!$result) {
202
+                    throw new Exception("could not save image file '".$imagepath.$file_ext."'");
203
+        }
195 204
 
196 205
         # insert image into database
197 206
 
198
-        try
199
-        {
207
+        try {
200 208
             $position = self::db_insert_image(
201 209
                 $request->consumer->key, $request->token->user_id,
202 210
                 $log_internal_id, $image_uuid, $position, $caption, $is_spoiler, $file_ext
203 211
             );
204
-        }
205
-        catch (Exception $e)
206
-        {
212
+        } catch (Exception $e) {
207 213
             # TODO: Proper handling of nested exception if the unlink() fails
208 214
             # (which is very unlikely, and will just add a bit more of garbage
209 215
             # to that which is already present in the images directory).
210 216
 
211
-            try { unlink($imagepath.$file_ext); }
212
-            catch (Exception $e2) {}
217
+            try { unlink($imagepath.$file_ext); } catch (Exception $e2) {}
213 218
             throw $e;
214 219
         }
215 220
 
@@ -239,15 +244,15 @@  discard block
 block discarded – undo
239 244
         # and more powerful alternative (e.g. allowing more file types),
240 245
         # but that needs additional and sometimes non-trivial installation.
241 246
 
242
-        if (!extension_loaded('gd'))
243
-            throw new Exception('PHP GD image processing module is disabled');
247
+        if (!extension_loaded('gd')) {
248
+                    throw new Exception('PHP GD image processing module is disabled');
249
+        }
244 250
 
245 251
         # rescale image if necessary
246 252
 
247 253
         $scale_factor = sqrt(Settings::get('IMAGE_MAX_PIXEL_COUNT') / ($width * $height));
248 254
 
249
-        if ($scale_factor < 1)
250
-        {
255
+        if ($scale_factor < 1) {
251 256
             $new_width = $width * $scale_factor;
252 257
             $new_height = $height * $scale_factor;
253 258
             $scaled_image = imagecreatetruecolor($new_width, $new_height);
@@ -261,18 +266,17 @@  discard block
 block discarded – undo
261 266
         #   - GD cannot save EXIF data anyway, and
262 267
         #   - the orientation flag may not be recognized by all image processors.
263 268
 
264
-        if (!extension_loaded('exif'))
265
-            throw new Exception('PHP Exif module is disabled');
269
+        if (!extension_loaded('exif')) {
270
+                    throw new Exception('PHP Exif module is disabled');
271
+        }
266 272
 
267
-        if ($image_type == IMAGETYPE_JPEG)
268
-        {
273
+        if ($image_type == IMAGETYPE_JPEG) {
269 274
             # The PHP Exif module can read EXIF data only from files. To avoid
270 275
             # disk I/O overhead, we pipe the image string through a pseudo-file:
271 276
 
272 277
             $exif_data = exif_read_data("data://image/jpeg;base64," . $base64_image);
273 278
             if ($exif_data && isset($exif_data['Orientation'])) {
274
-                switch ($exif_data['Orientation'])
275
-                {
279
+                switch ($exif_data['Orientation']) {
276 280
                     case 3: $image = imagerotate($image, 180, 0); break;
277 281
                     case 6: $image = imagerotate($image, -90, 0); break;
278 282
                     case 8: $image = imagerotate($image, 90, 0); break;
@@ -393,11 +397,12 @@  discard block
 block discarded – undo
393 397
         # This is the "real" entry point. A wrapper for the _call method.
394 398
 
395 399
         $langpref = $request->get_parameter('langpref');
396
-        if (!$langpref) $langpref = "en";
400
+        if (!$langpref) {
401
+            $langpref = "en";
402
+        }
397 403
         Okapi::gettext_domain_init(explode("|", $langpref));
398 404
 
399
-        try
400
-        {
405
+        try {
401 406
             list($image_uuid, $position) = self::_call($request);
402 407
             $result = array(
403 408
                 'success' => true,
@@ -406,9 +411,7 @@  discard block
 block discarded – undo
406 411
                 'position' => $position
407 412
             );
408 413
             Okapi::gettext_domain_restore();
409
-        }
410
-        catch (CannotPublishException $e)
411
-        {
414
+        } catch (CannotPublishException $e) {
412 415
             Okapi::gettext_domain_restore();
413 416
             $result = array(
414 417
                 'success' => false,
Please login to merge, or discard this patch.
htdocs/okapi/services/logs/images/log_images_common.inc.php 4 patches
Doc Comments   +7 added lines patch added patch discarded remove patch
@@ -17,6 +17,9 @@  discard block
 block discarded – undo
17 17
 
18 18
 class LogImagesCommon
19 19
 {
20
+    /**
21
+     * @param OkapiRequest $request
22
+     */
20 23
     function validate_image_uuid($request)
21 24
     {
22 25
         $image_uuid = $request->get_parameter('image_uuid');
@@ -63,6 +66,9 @@  discard block
 block discarded – undo
63 66
     }
64 67
 
65 68
 
69
+    /**
70
+     * @param OkapiRequest $request
71
+     */
66 72
     function validate_position($request)
67 73
     {
68 74
         $position = $request->get_parameter('position');
@@ -87,6 +93,7 @@  discard block
 block discarded – undo
87 93
      *
88 94
      * This function is always called when adding images. When editing images,
89 95
      * it is called only for OCDE and if the position parameter was supplied.
96
+     * @param integer $end_offset
90 97
      */
91 98
 
92 99
     static function prepare_position($log_internal_id, $position, $end_offset)
Please login to merge, or discard this patch.
Unused Use Statements   -3 removed lines patch added patch discarded remove patch
@@ -7,12 +7,9 @@
 block discarded – undo
7 7
 namespace okapi\services\logs\images;
8 8
 
9 9
 use Exception;
10
-use okapi\Okapi;
11 10
 use okapi\Db;
12
-use okapi\OkapiRequest;
13 11
 use okapi\InvalidParam;
14 12
 use okapi\Settings;
15
-use okapi\BadRequest;
16 13
 
17 14
 
18 15
 class LogImagesCommon
Please login to merge, or discard this patch.
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -101,7 +101,7 @@  discard block
 block discarded – undo
101 101
             Db::execute('lock tables pictures write');
102 102
         }
103 103
 
104
-        $log_images_count =  Db::select_value("
104
+        $log_images_count = Db::select_value("
105 105
             select count(*)
106 106
             from pictures
107 107
             where object_type = 1 and object_id = '".Db::escape_string($log_internal_id)."'
@@ -133,7 +133,7 @@  discard block
 block discarded – undo
133 133
                     from pictures
134 134
                     where object_type = 1 and object_id = '".Db::escape_string($log_internal_id)."'
135 135
                     order by seq
136
-                    limit ".($position+0).", 1
136
+                    limit ".($position + 0).", 1
137 137
                 ");
138 138
             }
139 139
         }
Please login to merge, or discard this patch.
Braces   +6 added lines, -9 removed lines patch added patch discarded remove patch
@@ -20,8 +20,9 @@  discard block
 block discarded – undo
20 20
     function validate_image_uuid($request)
21 21
     {
22 22
         $image_uuid = $request->get_parameter('image_uuid');
23
-        if (!$image_uuid)
24
-            throw new ParamMissing('image_uuid');
23
+        if (!$image_uuid) {
24
+                    throw new ParamMissing('image_uuid');
25
+        }
25 26
 
26 27
         # When uploading images, OCPL stores the user_id of the uploader
27 28
         # in the 'pictures' table. This is redundant to cache_logs.user_id,
@@ -91,8 +92,7 @@  discard block
 block discarded – undo
91 92
 
92 93
     static function prepare_position($log_internal_id, $position, $end_offset)
93 94
     {
94
-        if (Settings::get('OC_BRANCH') == 'oc.de' && $position !== null)
95
-        {
95
+        if (Settings::get('OC_BRANCH') == 'oc.de' && $position !== null) {
96 96
             # Prevent race conditions when creating sequence numbers if a
97 97
             # user tries to upload multiple images simultaneously. With a
98 98
             # few picture uploads per hour - most of them probably witout
@@ -107,16 +107,13 @@  discard block
 block discarded – undo
107 107
             where object_type = 1 and object_id = '".Db::escape_string($log_internal_id)."'
108 108
         ");
109 109
 
110
-        if (Settings::get('OC_BRANCH') == 'oc.pl')
111
-        {
110
+        if (Settings::get('OC_BRANCH') == 'oc.pl') {
112 111
             # Ignore the position parameter, always insert at end.
113 112
             # Remember that this function is NOT called when editing OCPL images.
114 113
 
115 114
             $position = $log_images_count;
116 115
             $seq = 1;
117
-        }
118
-        else
119
-        {
116
+        } else {
120 117
             if ($position === null || $position >= $log_images_count) {
121 118
                 $position = $log_images_count - 1 + $end_offset;
122 119
                 $seq = Db::select_value("
Please login to merge, or discard this patch.
htdocs/okapi/services/logs/submit.php 4 patches
Doc Comments   +7 added lines patch added patch discarded remove patch
@@ -713,6 +713,9 @@  discard block
 block discarded – undo
713 713
         return Okapi::formatted_response($request, $result);
714 714
     }
715 715
 
716
+    /**
717
+     * @param integer $when
718
+     */
716 719
     private static function increment_cache_stats($cache_internal_id, $when, $logtype)
717 720
     {
718 721
         if (Settings::get('OC_BRANCH') == 'oc.de')
@@ -788,6 +791,10 @@  discard block
 block discarded – undo
788 791
         }
789 792
     }
790 793
 
794
+    /**
795
+     * @param integer $when
796
+     * @param integer $text_html
797
+     */
791 798
     private static function insert_log_row(
792 799
         $consumer_key, $cache_internal_id, $user_internal_id, $logtype, $when,
793 800
         $formatted_comment, $text_html, $needs_maintenance2
Please login to merge, or discard this patch.
Unused Use Statements   +4 added lines, -4 removed lines patch added patch discarded remove patch
@@ -3,15 +3,15 @@
 block discarded – undo
3 3
 namespace okapi\services\logs\submit;
4 4
 
5 5
 use Exception;
6
-use okapi\Okapi;
6
+use okapi\BadRequest;
7 7
 use okapi\Db;
8
-use okapi\OkapiRequest;
9
-use okapi\ParamMissing;
10 8
 use okapi\InvalidParam;
9
+use okapi\Okapi;
11 10
 use okapi\OkapiInternalRequest;
11
+use okapi\OkapiRequest;
12 12
 use okapi\OkapiServiceRunner;
13
+use okapi\ParamMissing;
13 14
 use okapi\Settings;
14
-use okapi\BadRequest;
15 15
 
16 16
 
17 17
 /**
Please login to merge, or discard this patch.
Spacing   +4 added lines, -4 removed lines patch added patch discarded remove patch
@@ -70,7 +70,7 @@  discard block
 block discarded – undo
70 70
                     'when', "'$tmp' is not in a valid format or is not a valid date."
71 71
                 );
72 72
             }
73
-            if ($when > time() + 5*60) {
73
+            if ($when > time() + 5 * 60) {
74 74
                 throw new CannotPublishException(_(
75 75
                     "You are trying to publish a log entry with a date in ".
76 76
                     "future. Cache log entries are allowed to be published in ".
@@ -91,7 +91,7 @@  discard block
 block discarded – undo
91 91
         }
92 92
 
93 93
         $rating = $request->get_parameter('rating');
94
-        if ($rating !== null && (!in_array($rating, array(1,2,3,4,5)))) {
94
+        if ($rating !== null && (!in_array($rating, array(1, 2, 3, 4, 5)))) {
95 95
             throw new InvalidParam(
96 96
                 'rating', "If present, it must be an integer in the 1..5 scale."
97 97
             );
@@ -314,7 +314,7 @@  discard block
 block discarded – undo
314 314
 
315 315
                 $opt['rootpath'] = $GLOBALS['rootpath'];
316 316
                 $opt['html_purifier'] = Settings::get('OCDE_HTML_PURIFIER_SETTINGS');
317
-                require_once($GLOBALS['rootpath'] . 'lib2/OcHTMLPurifier.class.php');
317
+                require_once($GLOBALS['rootpath'].'lib2/OcHTMLPurifier.class.php');
318 318
 
319 319
                 $purifier = new \OcHTMLPurifier($opt);
320 320
                 $formatted_comment = $purifier->purify($formatted_comment);
@@ -478,7 +478,7 @@  discard block
 block discarded – undo
478 478
 
479 479
             # Check the number of recommendations.
480 480
 
481
-            $founds = $user['caches_found'] + 1;  // +1, because he'll find THIS ONE in a moment
481
+            $founds = $user['caches_found'] + 1; // +1, because he'll find THIS ONE in a moment
482 482
 
483 483
             # Note: caches_found includes the number of attended events (both on
484 484
             # OCDE and OCPL). OCPL does not allow recommending events, but the
Please login to merge, or discard this patch.
Braces   +78 added lines, -127 removed lines patch added patch discarded remove patch
@@ -20,7 +20,9 @@  discard block
 block discarded – undo
20 20
  * the Consumer did anything wrong (it's the user who did). This exception shouldn't
21 21
  * be used outside of this file.
22 22
  */
23
-class CannotPublishException extends Exception {}
23
+class CannotPublishException extends Exception
24
+{
25
+}
24 26
 
25 27
 class WebService
26 28
 {
@@ -43,10 +45,14 @@  discard block
 block discarded – undo
43 45
         # "call").
44 46
 
45 47
         $cache_code = $request->get_parameter('cache_code');
46
-        if (!$cache_code) throw new ParamMissing('cache_code');
48
+        if (!$cache_code) {
49
+            throw new ParamMissing('cache_code');
50
+        }
47 51
 
48 52
         $logtype = $request->get_parameter('logtype');
49
-        if (!$logtype) throw new ParamMissing('logtype');
53
+        if (!$logtype) {
54
+            throw new ParamMissing('logtype');
55
+        }
50 56
         if (!in_array($logtype, array(
51 57
             'Found it', "Didn't find it", 'Comment', 'Will attend', 'Attended'
52 58
         ))) {
@@ -54,16 +60,20 @@  discard block
 block discarded – undo
54 60
         }
55 61
 
56 62
         $comment = $request->get_parameter('comment');
57
-        if (!$comment) $comment = "";
63
+        if (!$comment) {
64
+            $comment = "";
65
+        }
58 66
 
59 67
         $comment_format = $request->get_parameter('comment_format');
60
-        if (!$comment_format) $comment_format = "auto";
61
-        if (!in_array($comment_format, array('auto', 'html', 'plaintext')))
62
-            throw new InvalidParam('comment_format', $comment_format);
68
+        if (!$comment_format) {
69
+            $comment_format = "auto";
70
+        }
71
+        if (!in_array($comment_format, array('auto', 'html', 'plaintext'))) {
72
+                    throw new InvalidParam('comment_format', $comment_format);
73
+        }
63 74
 
64 75
         $tmp = $request->get_parameter('when');
65
-        if ($tmp)
66
-        {
76
+        if ($tmp) {
67 77
             $when = strtotime($tmp);
68 78
             if ($when < 1) {
69 79
                 throw new InvalidParam(
@@ -77,8 +87,7 @@  discard block
 block discarded – undo
77 87
                     "the past, but NOT in the future."
78 88
                 ));
79 89
             }
80
-        }
81
-        else {
90
+        } else {
82 91
             $when = time();
83 92
         }
84 93
 
@@ -101,8 +110,7 @@  discard block
 block discarded – undo
101 110
                 "Rating is allowed only for 'Found it' and 'Attended' logtypes."
102 111
             );
103 112
         }
104
-        if ($rating !== null && (Settings::get('OC_BRANCH') == 'oc.de'))
105
-        {
113
+        if ($rating !== null && (Settings::get('OC_BRANCH') == 'oc.de')) {
106 114
             # We will remove the rating request and change the success message
107 115
             # (which will be returned IF the rest of the query will meet all the
108 116
             # requirements).
@@ -115,18 +123,19 @@  discard block
 block discarded – undo
115 123
         }
116 124
 
117 125
         $recommend = $request->get_parameter('recommend');
118
-        if (!$recommend) $recommend = 'false';
119
-        if (!in_array($recommend, array('true', 'false')))
120
-            throw new InvalidParam('recommend', "Unknown option: '$recommend'.");
126
+        if (!$recommend) {
127
+            $recommend = 'false';
128
+        }
129
+        if (!in_array($recommend, array('true', 'false'))) {
130
+                    throw new InvalidParam('recommend', "Unknown option: '$recommend'.");
131
+        }
121 132
         $recommend = ($recommend == 'true');
122
-        if ($recommend && $logtype != 'Found it')
123
-        {
133
+        if ($recommend && $logtype != 'Found it') {
124 134
             if ($logtype != 'Attended') {
125 135
                 throw new BadRequest(
126 136
                     "Recommending is allowed only for 'Found it' and 'Attended' logs."
127 137
                 );
128
-            }
129
-            else if (Settings::get('OC_BRANCH') == 'oc.pl') {
138
+            } else if (Settings::get('OC_BRANCH') == 'oc.pl') {
130 139
 
131 140
                 # We will remove the recommendation request and change the success message
132 141
                 # (which will be returned IF the rest of the query will meet all the
@@ -156,9 +165,7 @@  discard block
 block discarded – undo
156 165
         # Parse $needs_maintenance and get rid of it.
157 166
 
158 167
         if ($needs_maintenance) {
159
-            if ($needs_maintenance == 'true') { $needs_maintenance2 = 'true'; }
160
-            else if ($needs_maintenance == 'false') { $needs_maintenance2 = 'null'; }
161
-            else {
168
+            if ($needs_maintenance == 'true') { $needs_maintenance2 = 'true'; } else if ($needs_maintenance == 'false') { $needs_maintenance2 = 'null'; } else {
162 169
                 throw new InvalidParam(
163 170
                     'needs_maintenance', "Unknown option: '$needs_maintenance'."
164 171
                 );
@@ -208,24 +215,21 @@  discard block
 block discarded – undo
208 215
 
209 216
         # Various integrity checks.
210 217
 
211
-        if ($cache['type'] == 'Event')
212
-        {
218
+        if ($cache['type'] == 'Event') {
213 219
             if (!in_array($logtype, array('Will attend', 'Attended', 'Comment'))) {
214 220
                 throw new CannotPublishException(_(
215 221
                     'This cache is an Event cache. You cannot "Find" it (but '.
216 222
                     'you can attend it, or comment on it)!'
217 223
                 ));
218 224
             }
219
-        }
220
-        else  # type != event
225
+        } else  # type != event
221 226
         {
222 227
             if (in_array($logtype, array('Will attend', 'Attended'))) {
223 228
                 throw new CannotPublishException(_(
224 229
                     'This cache is NOT an Event cache. You cannot "Attend" it '.
225 230
                     '(but you can find it, or comment on it)!'
226 231
                 ));
227
-            }
228
-            else if (!in_array($logtype, array('Found it', "Didn't find it", 'Comment'))) {
232
+            } else if (!in_array($logtype, array('Found it', "Didn't find it", 'Comment'))) {
229 233
                 throw new Exception("Unknown log entry - should be documented here.");
230 234
             }
231 235
         }
@@ -237,8 +241,7 @@  discard block
 block discarded – undo
237 241
 
238 242
         # Password check.
239 243
 
240
-        if (($logtype == 'Found it' || $logtype == 'Attended') && $cache['req_passwd'])
241
-        {
244
+        if (($logtype == 'Found it' || $logtype == 'Attended') && $cache['req_passwd']) {
242 245
             $valid_password = Db::select_value("
243 246
                 select logpw
244 247
                 from caches
@@ -264,8 +267,7 @@  discard block
 block discarded – undo
264 267
         # original format, while still being able to re-create the comment in
265 268
         # its original form.
266 269
 
267
-        if ($comment_format == 'plaintext')
268
-        {
270
+        if ($comment_format == 'plaintext') {
269 271
             # This code is identical to the plaintext processing in OC code,
270 272
             # including a space handling bug: Multiple consecutive spaces will
271 273
             # get semantically lost in the generated HTML.
@@ -273,12 +275,9 @@  discard block
 block discarded – undo
273 275
             $formatted_comment = htmlspecialchars($comment, ENT_COMPAT);
274 276
             $formatted_comment = nl2br($formatted_comment);
275 277
 
276
-            if (Settings::get('OC_BRANCH') == 'oc.de')
277
-            {
278
+            if (Settings::get('OC_BRANCH') == 'oc.de') {
278 279
                 $value_for_text_html_field = 0;
279
-            }
280
-            else
281
-            {
280
+            } else {
282 281
                 # 'text_html' = 0 (false) is broken in OCPL code and has been
283 282
                 # deprecated; OCPL code was changed to always set it to 1 (true).
284 283
                 # For OKAPI, the value has been changed from 0 to 1 with commit
@@ -289,26 +288,21 @@  discard block
 block discarded – undo
289 288
 
290 289
                 $value_for_text_html_field = 1;
291 290
             }
292
-        }
293
-        elseif ($comment_format == 'auto')
294
-        {
291
+        } elseif ($comment_format == 'auto') {
295 292
             # 'Auto' is for backward compatibility. Before the "comment_format"
296 293
             # was introduced, OKAPI used a weird format in between (it allowed
297 294
             # HTML, but applied nl2br too).
298 295
 
299 296
             $formatted_comment = nl2br($comment);
300 297
             $value_for_text_html_field = 1;
301
-        }
302
-        else
303
-        {
298
+        } else {
304 299
             $formatted_comment = $comment;
305 300
 
306 301
             # For user-supplied HTML comments, OC sites require us to do
307 302
             # additional HTML purification prior to the insertion into the
308 303
             # database.
309 304
 
310
-            if (Settings::get('OC_BRANCH') == 'oc.de')
311
-            {
305
+            if (Settings::get('OC_BRANCH') == 'oc.de') {
312 306
                 # NOTICE: We are including EXTERNAL OCDE library here! This
313 307
                 # code does not belong to OKAPI!
314 308
 
@@ -318,9 +312,7 @@  discard block
 block discarded – undo
318 312
 
319 313
                 $purifier = new \OcHTMLPurifier($opt);
320 314
                 $formatted_comment = $purifier->purify($formatted_comment);
321
-            }
322
-            else
323
-            {
315
+            } else {
324 316
                 # TODO: Add OCPL HTML filtering.
325 317
                 # See https://github.com/opencaching/okapi/issues/412.
326 318
             }
@@ -328,8 +320,7 @@  discard block
 block discarded – undo
328 320
             $value_for_text_html_field = 1;
329 321
         }
330 322
 
331
-        if (Settings::get('OC_BRANCH') == 'oc.pl')
332
-        {
323
+        if (Settings::get('OC_BRANCH') == 'oc.pl') {
333 324
             # The HTML processing in OCPL code is broken. Effectively, it
334 325
             # will decode &lt; &gt; and &amp; (and maybe other things?)
335 326
             # before display so that text contents may be interpreted as HTML.
@@ -365,8 +356,7 @@  discard block
 block discarded – undo
365 356
 
366 357
         # Duplicate detection.
367 358
 
368
-        if ($on_duplicate != 'continue')
369
-        {
359
+        if ($on_duplicate != 'continue') {
370 360
             # Attempt to find a log entry made by the same user, for the same cache, with
371 361
             # the same date, type, comment, etc. Note, that these are not ALL the fields
372 362
             # we could check, but should work ok in most cases. Also note, that we
@@ -386,15 +376,11 @@  discard block
 block discarded – undo
386 376
                     ".((Settings::get('OC_BRANCH') == 'oc.pl') ? "and deleted = 0" : "")."
387 377
                 limit 1
388 378
             ");
389
-            if ($duplicate_uuid != null)
390
-            {
391
-                if ($on_duplicate == 'silent_success')
392
-                {
379
+            if ($duplicate_uuid != null) {
380
+                if ($on_duplicate == 'silent_success') {
393 381
                     # Act as if the log has been submitted successfully.
394 382
                     return $duplicate_uuid;
395
-                }
396
-                elseif ($on_duplicate == 'user_error')
397
-                {
383
+                } elseif ($on_duplicate == 'user_error') {
398 384
                     throw new CannotPublishException(_(
399 385
                         "You have already submitted a log entry with exactly ".
400 386
                         "the same contents."
@@ -440,8 +426,7 @@  discard block
 block discarded – undo
440 426
         # user submit a rating for it? Anyway, I will stick to the procedure
441 427
         # found in log.php. On the bright side, it's fail-safe.
442 428
 
443
-        if ($rating)
444
-        {
429
+        if ($rating) {
445 430
             $has_already_rated = Db::select_value("
446 431
                 select 1
447 432
                 from scores
@@ -459,8 +444,7 @@  discard block
 block discarded – undo
459 444
 
460 445
         # If user wants to recommend...
461 446
 
462
-        if ($recommend)
463
-        {
447
+        if ($recommend) {
464 448
             # Do the same "fail-safety" check as we did for the rating.
465 449
 
466 450
             $already_recommended = Db::select_value("
@@ -497,32 +481,26 @@  discard block
 block discarded – undo
497 481
         # If user checked the "needs_maintenance(2)" flag for OCPL, we will shuffle things
498 482
         # a little...
499 483
 
500
-        if (Settings::get('OC_BRANCH') == 'oc.pl' && $needs_maintenance2 == 'true')
501
-        {
484
+        if (Settings::get('OC_BRANCH') == 'oc.pl' && $needs_maintenance2 == 'true') {
502 485
             # If we're here, then we also know that the "Needs maintenance" log
503 486
             # type is supported by this OC site. However, it's a separate log
504 487
             # type, so we might have to submit two log types together:
505 488
 
506
-            if ($logtype == 'Comment')
507
-            {
489
+            if ($logtype == 'Comment') {
508 490
                 # If user submits a "Comment", we'll just change its type to
509 491
                 # "Needs maintenance". Only one log entry will be issued.
510 492
 
511 493
                 $logtype = 'Needs maintenance';
512 494
                 $second_logtype = null;
513 495
                 $second_formatted_comment = null;
514
-            }
515
-            elseif ($logtype == 'Found it')
516
-            {
496
+            } elseif ($logtype == 'Found it') {
517 497
                 # If "Found it", then we'll issue two log entries: one "Found
518 498
                 # it" with the original comment, and second one "Needs
519 499
                 # maintenance" with empty comment.
520 500
 
521 501
                 $second_logtype = 'Needs maintenance';
522 502
                 $second_formatted_comment = "";
523
-            }
524
-            elseif ($logtype == "Didn't find it")
525
-            {
503
+            } elseif ($logtype == "Didn't find it") {
526 504
                 # If "Didn't find it", then we'll issue two log entries, but this time
527 505
                 # we'll do this the other way around. The first "Didn't find it" entry
528 506
                 # will have an empty comment. We will move the comment to the second
@@ -532,22 +510,17 @@  discard block
 block discarded – undo
532 510
                 $second_logtype = 'Needs maintenance';
533 511
                 $second_formatted_comment = $formatted_comment;
534 512
                 $formatted_comment = "";
535
-            }
536
-            else if ($logtype == 'Will attend' || $logtype == 'Attended')
537
-            {
513
+            } else if ($logtype == 'Will attend' || $logtype == 'Attended') {
538 514
                 # OC branches which allow maintenance logs, still don't allow them on
539 515
                 # event caches.
540 516
 
541 517
                 throw new CannotPublishException(_(
542 518
                     "Event caches cannot \"need maintenance\"."
543 519
                 ));
544
-            }
545
-            else {
520
+            } else {
546 521
                 throw new Exception();
547 522
             }
548
-        }
549
-        else
550
-        {
523
+        } else {
551 524
             # User didn't check the "Needs maintenance" flag OR "Needs maintenance"
552 525
             # log type isn't supported by this server.
553 526
 
@@ -567,8 +540,7 @@  discard block
 block discarded – undo
567 540
         );
568 541
         self::increment_cache_stats($cache['internal_id'], $when, $logtype);
569 542
         self::increment_user_stats($user['internal_id'], $logtype);
570
-        if ($second_logtype != null)
571
-        {
543
+        if ($second_logtype != null) {
572 544
             # Reminder: This will only be called for OCPL branch.
573 545
 
574 546
             $log_uuids[] = self::insert_log_row(
@@ -587,8 +559,7 @@  discard block
 block discarded – undo
587 559
 
588 560
         # Save the rating.
589 561
 
590
-        if ($rating)
591
-        {
562
+        if ($rating) {
592 563
             # This code will be called for OCPL branch only. Earlier, we made sure,
593 564
             # to set $rating to null, if we're running on OCDE.
594 565
 
@@ -602,8 +573,7 @@  discard block
 block discarded – undo
602 573
             # but presumably has some deep logic into it. See also here (Polish):
603 574
             # http://wiki.opencaching.pl/index.php/Oceny_skrzynek
604 575
 
605
-            switch ($rating)
606
-            {
576
+            switch ($rating) {
607 577
                 case 1: $db_score = -2.0; break;
608 578
                 case 2: $db_score = -0.5; break;
609 579
                 case 3: $db_score = 0.7; break;
@@ -632,10 +602,8 @@  discard block
 block discarded – undo
632 602
 
633 603
         # Save recommendation.
634 604
 
635
-        if ($recommend)
636
-        {
637
-            if (Db::field_exists('cache_rating', 'rating_date'))
638
-            {
605
+        if ($recommend) {
606
+            if (Db::field_exists('cache_rating', 'rating_date')) {
639 607
                 Db::execute("
640 608
                     insert into cache_rating (user_id, cache_id, rating_date)
641 609
                     values (
@@ -644,9 +612,7 @@  discard block
 block discarded – undo
644 612
                         from_unixtime('".Db::escape_string($when)."')
645 613
                     );
646 614
                 ");
647
-            }
648
-            else
649
-            {
615
+            } else {
650 616
                 Db::execute("
651 617
                     insert into cache_rating (user_id, cache_id)
652 618
                     values (
@@ -680,14 +646,15 @@  discard block
 block discarded – undo
680 646
         # This is the "real" entry point. A wrapper for the _call method.
681 647
 
682 648
         $langpref = $request->get_parameter('langpref');
683
-        if (!$langpref) $langpref = "en";
649
+        if (!$langpref) {
650
+            $langpref = "en";
651
+        }
684 652
 
685 653
         # Error messages thrown via CannotPublishException exceptions should be localized.
686 654
         # They will be delivered for end user to display in his language.
687 655
 
688 656
         Okapi::gettext_domain_init(explode("|", $langpref));
689
-        try
690
-        {
657
+        try {
691 658
             # If appropriate, $success_message might be changed inside the _call.
692 659
             self::$success_message = _("Your cache log entry was posted successfully.");
693 660
             $log_uuids = self::_call($request);
@@ -698,9 +665,7 @@  discard block
 block discarded – undo
698 665
                 'log_uuids' => $log_uuids
699 666
             );
700 667
             Okapi::gettext_domain_restore();
701
-        }
702
-        catch (CannotPublishException $e)
703
-        {
668
+        } catch (CannotPublishException $e) {
704 669
             Okapi::gettext_domain_restore();
705 670
             $result = array(
706 671
                 'success' => false,
@@ -715,17 +680,13 @@  discard block
 block discarded – undo
715 680
 
716 681
     private static function increment_cache_stats($cache_internal_id, $when, $logtype)
717 682
     {
718
-        if (Settings::get('OC_BRANCH') == 'oc.de')
719
-        {
683
+        if (Settings::get('OC_BRANCH') == 'oc.de') {
720 684
             # OCDE handles cache stats updates using triggers. So, they are already
721 685
             # incremented properly.
722
-        }
723
-        else
724
-        {
686
+        } else {
725 687
             # OCPL doesn't use triggers for this. We need to update manually.
726 688
 
727
-            if ($logtype == 'Found it')
728
-            {
689
+            if ($logtype == 'Found it') {
729 690
                 Db::execute("
730 691
                     update caches
731 692
                     set
@@ -736,25 +697,19 @@  discard block
 block discarded – undo
736 697
                         )
737 698
                     where cache_id = '".Db::escape_string($cache_internal_id)."'
738 699
                 ");
739
-            }
740
-            elseif ($logtype == "Didn't find it")
741
-            {
700
+            } elseif ($logtype == "Didn't find it") {
742 701
                 Db::execute("
743 702
                     update caches
744 703
                     set notfounds = notfounds + 1
745 704
                     where cache_id = '".Db::escape_string($cache_internal_id)."'
746 705
                 ");
747
-            }
748
-            elseif ($logtype == 'Comment')
749
-            {
706
+            } elseif ($logtype == 'Comment') {
750 707
                 Db::execute("
751 708
                     update caches
752 709
                     set notes = notes + 1
753 710
                     where cache_id = '".Db::escape_string($cache_internal_id)."'
754 711
                 ");
755
-            }
756
-            else
757
-            {
712
+            } else {
758 713
                 # This log type is not represented in cache stats.
759 714
             }
760 715
         }
@@ -762,17 +717,13 @@  discard block
 block discarded – undo
762 717
 
763 718
     private static function increment_user_stats($user_internal_id, $logtype)
764 719
     {
765
-        if (Settings::get('OC_BRANCH') == 'oc.de')
766
-        {
720
+        if (Settings::get('OC_BRANCH') == 'oc.de') {
767 721
             # OCDE handles cache stats updates using triggers. So, they are already
768 722
             # incremented properly.
769
-        }
770
-        else
771
-        {
723
+        } else {
772 724
             # OCPL doesn't have triggers for this. We need to update manually.
773 725
 
774
-            switch ($logtype)
775
-            {
726
+            switch ($logtype) {
776 727
                 case 'Found it': $field_to_increment = 'founds_count'; break;
777 728
                 case "Didn't find it": $field_to_increment = 'notfounds_count'; break;
778 729
                 case 'Comment': $field_to_increment = 'log_notes_count'; break;
@@ -791,15 +742,15 @@  discard block
 block discarded – undo
791 742
     private static function insert_log_row(
792 743
         $consumer_key, $cache_internal_id, $user_internal_id, $logtype, $when,
793 744
         $formatted_comment, $text_html, $needs_maintenance2
794
-    )
795
-    {
745
+    ) {
796 746
         if (Settings::get('OC_BRANCH') == 'oc.de') {
797 747
             $needs_maintenance_field_SQL = ', needs_maintenance';
798 748
             if ($needs_maintenance2 == 'true') {
799 749
                 $needs_maintenance_SQL = ',2';
800 750
             } else if ($needs_maintenance2 == 'false') {
801 751
                 $needs_maintenance_SQL = ',1';
802
-            } else {  // 'null'
752
+            } else {
753
+// 'null'
803 754
                 $needs_maintenance_SQL = ',0';
804 755
             }
805 756
         } else {
Please login to merge, or discard this patch.
htdocs/okapi/services/replicate/replicate_common.inc.php 4 patches
Doc Comments   +8 added lines patch added patch discarded remove patch
@@ -165,6 +165,7 @@  discard block
 block discarded – undo
165 165
      * well as long as only log entry fields are replicated which update
166 166
      * some cache_logs column when changed (by OKAPI or OC code). See
167 167
      * https://github.com/opencaching/okapi/issues/382 for further discussion.
168
+     * @param string[] $geocache_ignored_fields
168 169
      */
169 170
     public static function verify_clog_consistency(
170 171
         $force_all=false, $geocache_ignored_fields = null
@@ -269,6 +270,13 @@  discard block
 block discarded – undo
269 270
      * In normal mode, update the changelog and don't return anything.
270 271
      * In fulldump mode, return the generated changelog entries *instead* of
271 272
      * updating it.
273
+     * @param string $feeder_method
274
+     * @param string $object_type
275
+     * @param string $feeder_keys_param
276
+     * @param string $key_name
277
+     * @param string $fields
278
+     * @param boolean $fulldump_mode
279
+     * @param boolean $use_cache
272 280
      */
273 281
     private static function generate_changelog_entries($feeder_method, $object_type, $feeder_keys_param,
274 282
         $key_name, $key_values, $fields, $fulldump_mode, $use_cache, $cache_timeout = 86400)
Please login to merge, or discard this patch.
Unused Use Statements   +3 added lines, -8 removed lines patch added patch discarded remove patch
@@ -3,17 +3,12 @@
 block discarded – undo
3 3
 namespace okapi\services\replicate;
4 4
 
5 5
 use Exception;
6
-use okapi\Okapi;
6
+use okapi\Cache;
7 7
 use okapi\Db;
8
-use okapi\OkapiRequest;
9
-use okapi\ParamMissing;
10
-use okapi\InvalidParam;
11
-use okapi\BadRequest;
12
-use okapi\DoesNotExist;
13
-use okapi\OkapiInternalRequest;
8
+use okapi\Okapi;
14 9
 use okapi\OkapiInternalConsumer;
10
+use okapi\OkapiInternalRequest;
15 11
 use okapi\OkapiServiceRunner;
16
-use okapi\Cache;
17 12
 use okapi\Settings;
18 13
 
19 14
 class ReplicateCommon
Please login to merge, or discard this patch.
Spacing   +6 added lines, -6 removed lines patch added patch discarded remove patch
@@ -73,7 +73,7 @@  discard block
 block discarded – undo
73 73
     /** Check for modifications in the database and update the changelog table accordingly. */
74 74
     public static function update_clog_table()
75 75
     {
76
-        $now = Db::select_value("select date_add(now(), interval -1 minute)");  # See issue 157.
76
+        $now = Db::select_value("select date_add(now(), interval -1 minute)"); # See issue 157.
77 77
         $last_update = Okapi::get_var('last_clog_update');
78 78
         if ($last_update === null)
79 79
             $last_update = Db::select_value("select date_add(now(), interval -1 day)");
@@ -167,7 +167,7 @@  discard block
 block discarded – undo
167 167
      * https://github.com/opencaching/okapi/issues/382 for further discussion.
168 168
      */
169 169
     public static function verify_clog_consistency(
170
-        $force_all=false, $geocache_ignored_fields = null
170
+        $force_all = false, $geocache_ignored_fields = null
171 171
     )
172 172
     {
173 173
         set_time_limit(0);
@@ -228,8 +228,8 @@  discard block
 block discarded – undo
228 228
                 # vars which is to be emailed to OKAPI developers.
229 229
 
230 230
                 if (count($two_examples) == 0)
231
-                    $two_examples[0] = $entry;  /* The first entry */
232
-                $two_examples[1] = $entry;  /* The last entry */
231
+                    $two_examples[0] = $entry; /* The first entry */
232
+                $two_examples[1] = $entry; /* The last entry */
233 233
 
234 234
                 Db::execute("
235 235
                     update caches
@@ -389,7 +389,7 @@  discard block
 block discarded – undo
389 389
             if ($use_cache)
390 390
             {
391 391
                 Cache::set_many($cached_values1, $cache_timeout);
392
-                Cache::set_many($cached_values2, null);  # make it persistent
392
+                Cache::set_many($cached_values2, null); # make it persistent
393 393
             }
394 394
         }
395 395
     }
@@ -589,7 +589,7 @@  discard block
 block discarded – undo
589 589
 
590 590
         $use_bzip2 = true;
591 591
         $dumpfilename = "okapi-dump.tar.".($use_bzip2 ? "bz2" : "gz");
592
-        shell_exec("tar --directory $dir -c".($use_bzip2 ? "j" : "z")."f $dir/$dumpfilename index.json ".implode(" ", $json_files). " 2>&1");
592
+        shell_exec("tar --directory $dir -c".($use_bzip2 ? "j" : "z")."f $dir/$dumpfilename index.json ".implode(" ", $json_files)." 2>&1");
593 593
 
594 594
         # Delete temporary files.
595 595
 
Please login to merge, or discard this patch.
Braces   +103 added lines, -112 removed lines patch added patch discarded remove patch
@@ -37,11 +37,11 @@  discard block
 block discarded – undo
37 37
     public static function get_min_since()
38 38
     {
39 39
         static $cache = null;
40
-        if ($cache == null)
41
-        {
40
+        if ($cache == null) {
42 41
             $cache = Db::select_value("select min(id) from okapi_clog");
43
-            if ($cache === null)
44
-                $cache = 1;
42
+            if ($cache === null) {
43
+                            $cache = 1;
44
+            }
45 45
             $cache -= 1;
46 46
         }
47 47
         return $cache;
@@ -54,19 +54,21 @@  discard block
 block discarded – undo
54 54
      */
55 55
     private static function get_diff($old, $new)
56 56
     {
57
-        if (!$old)
58
-            return $new;
57
+        if (!$old) {
58
+                    return $new;
59
+        }
59 60
         $changed_keys = array();
60
-        foreach ($new as $key => $value)
61
-        {
62
-            if (!array_key_exists($key, $old))
63
-                $changed_keys[] = $key;
64
-            elseif ($old[$key] != $new[$key])
65
-                $changed_keys[] = $key;
61
+        foreach ($new as $key => $value) {
62
+            if (!array_key_exists($key, $old)) {
63
+                            $changed_keys[] = $key;
64
+            } elseif ($old[$key] != $new[$key]) {
65
+                            $changed_keys[] = $key;
66
+            }
66 67
         }
67 68
         $changed = array();
68
-        foreach ($changed_keys as $key)
69
-            $changed[$key] = $new[$key];
69
+        foreach ($changed_keys as $key) {
70
+                    $changed[$key] = $new[$key];
71
+        }
70 72
         return $changed;
71 73
     }
72 74
 
@@ -75,8 +77,9 @@  discard block
 block discarded – undo
75 77
     {
76 78
         $now = Db::select_value("select date_add(now(), interval -1 minute)");  # See issue 157.
77 79
         $last_update = Okapi::get_var('last_clog_update');
78
-        if ($last_update === null)
79
-            $last_update = Db::select_value("select date_add(now(), interval -1 day)");
80
+        if ($last_update === null) {
81
+                    $last_update = Db::select_value("select date_add(now(), interval -1 day)");
82
+        }
80 83
 
81 84
         # Usually this will be fast. But, for example, if admin changes ALL the
82 85
         # caches, this will take forever. But we still want it to finish properly
@@ -100,8 +103,7 @@  discard block
 block discarded – undo
100 103
 
101 104
         # For each group, update the changelog table accordingly.
102 105
 
103
-        foreach ($cache_code_groups as $cache_codes)
104
-        {
106
+        foreach ($cache_code_groups as $cache_codes) {
105 107
             self::generate_changelog_entries('services/caches/geocaches', 'geocache', 'cache_codes',
106 108
                 'code', $cache_codes, self::$logged_cache_fields, false, true, null);
107 109
         }
@@ -109,27 +111,25 @@  discard block
 block discarded – undo
109 111
         # Same as above, for log entries.
110 112
 
111 113
         $offset = 0;
112
-        while (true)
113
-        {
114
+        while (true) {
114 115
             $log_uuids = Db::select_column("
115 116
                 select uuid
116 117
                 from cache_logs
117 118
                 where okapi_syncbase > '".Db::escape_string($last_update)."'
118 119
                 limit $offset, 10000;
119 120
             ");
120
-            if (count($log_uuids) == 0)
121
-                break;
121
+            if (count($log_uuids) == 0) {
122
+                            break;
123
+            }
122 124
             $offset += 10000;
123 125
             $log_uuid_groups = Okapi::make_groups($log_uuids, 100);
124 126
             unset($log_uuids);
125
-            foreach ($log_uuid_groups as $log_uuids)
126
-            {
127
+            foreach ($log_uuid_groups as $log_uuids) {
127 128
                 self::generate_changelog_entries('services/logs/entries', 'log', 'log_uuids',
128 129
                     'uuid', $log_uuids, self::$logged_log_entry_fields, false, true, 3600);
129 130
             }
130 131
         }
131
-        if (Settings::get('OC_BRANCH') == 'oc.de')
132
-        {
132
+        if (Settings::get('OC_BRANCH') == 'oc.de') {
133 133
             # On OCDE branch, deleted log entries are MOVED to another table.
134 134
             # So the above queries won't detect them. We need to run one more.
135 135
             # We will assume there are not so many of them and we don't have to
@@ -142,8 +142,7 @@  discard block
 block discarded – undo
142 142
             ");
143 143
             $deleted_uuid_groups = Okapi::make_groups($DELETED_uuids, 100);
144 144
             unset($DELETED_uuids);
145
-            foreach ($deleted_uuid_groups as $deleted_uuids)
146
-            {
145
+            foreach ($deleted_uuid_groups as $deleted_uuids) {
147 146
                 self::generate_changelog_entries('services/logs/entries', 'log', 'log_uuids',
148 147
                     'uuid', $deleted_uuids, self::$logged_log_entry_fields, false, true, 3600);
149 148
             }
@@ -168,8 +167,7 @@  discard block
 block discarded – undo
168 167
      */
169 168
     public static function verify_clog_consistency(
170 169
         $force_all=false, $geocache_ignored_fields = null
171
-    )
172
-    {
170
+    ) {
173 171
         set_time_limit(0);
174 172
         ignore_user_abort(true);
175 173
 
@@ -194,16 +192,15 @@  discard block
 block discarded – undo
194 192
 
195 193
         $sum = 0;
196 194
         $two_examples = array();
197
-        foreach ($cache_code_groups as $cache_codes)
198
-        {
195
+        foreach ($cache_code_groups as $cache_codes) {
199 196
             $entries = self::generate_changelog_entries(
200 197
                 'services/caches/geocaches', 'geocache', 'cache_codes',
201 198
                 'code', $cache_codes, self::$logged_cache_fields, true, true, null
202 199
             );
203
-            foreach ($entries as $entry)
204
-            {
205
-                if ($entry['object_type'] != 'geocache')
206
-                    continue;
200
+            foreach ($entries as $entry) {
201
+                if ($entry['object_type'] != 'geocache') {
202
+                                    continue;
203
+                }
207 204
                 $cache_code = $entry['object_key']['code'];
208 205
 
209 206
                 if (($entry['change_type'] == 'replace') && ($geocache_ignored_fields != null)) {
@@ -227,8 +224,10 @@  discard block
 block discarded – undo
227 224
                 # We will story the first and the last entry in the $two_examples
228 225
                 # vars which is to be emailed to OKAPI developers.
229 226
 
230
-                if (count($two_examples) == 0)
231
-                    $two_examples[0] = $entry;  /* The first entry */
227
+                if (count($two_examples) == 0) {
228
+                                    $two_examples[0] = $entry;
229
+                }
230
+                /* The first entry */
232 231
                 $two_examples[1] = $entry;  /* The last entry */
233 232
 
234 233
                 Db::execute("
@@ -275,18 +274,18 @@  discard block
 block discarded – undo
275 274
     {
276 275
         # Retrieve the previous versions of all objects from OKAPI cache.
277 276
 
278
-        if ($use_cache)
279
-        {
277
+        if ($use_cache) {
280 278
             $cache_keys1 = array();
281 279
             $cache_keys2 = array();
282
-            foreach ($key_values as $key)
283
-                $cache_keys1[] = 'clog#'.$object_type.'#'.$key;
284
-            foreach ($key_values as $key)
285
-                $cache_keys2[] = 'clogmd5#'.$object_type.'#'.$key;
280
+            foreach ($key_values as $key) {
281
+                            $cache_keys1[] = 'clog#'.$object_type.'#'.$key;
282
+            }
283
+            foreach ($key_values as $key) {
284
+                            $cache_keys2[] = 'clogmd5#'.$object_type.'#'.$key;
285
+            }
286 286
             $cached_values1 = Cache::get_many($cache_keys1);
287 287
             $cached_values2 = Cache::get_many($cache_keys2);
288
-            if (!$fulldump_mode)
289
-            {
288
+            if (!$fulldump_mode) {
290 289
                 Cache::delete_many($cache_keys1);
291 290
                 Cache::delete_many($cache_keys2);
292 291
             }
@@ -305,25 +304,20 @@  discard block
 block discarded – undo
305 304
                 'attribution_append' => 'static'  # currently, this is for the "geocaches" method only
306 305
             )));
307 306
         $entries = array();
308
-        foreach ($current_values as $key => $object)
309
-        {
310
-            if ($object !== null)
311
-            {
307
+        foreach ($current_values as $key => $object) {
308
+            if ($object !== null) {
312 309
                 # Currently, the object exists.
313
-                if ($use_cache)
314
-                {
310
+                if ($use_cache) {
315 311
                     # First, compare the cached hash. The hash has much longer lifetime
316 312
                     # than the actual cached object.
317 313
                     $cached_md5 = $cached_values2['clogmd5#'.$object_type.'#'.$key];
318 314
                     $current_md5 = md5(serialize($object));
319
-                    if ($cached_md5 == $current_md5)
320
-                    {
315
+                    if ($cached_md5 == $current_md5) {
321 316
                         # The object was not changed since it was last replaced.
322 317
                         continue;
323 318
                     }
324 319
                     $diff = self::get_diff($cached_values1['clog#'.$object_type.'#'.$key], $object);
325
-                    if (count($diff) == 0)
326
-                    {
320
+                    if (count($diff) == 0) {
327 321
                         # Md5 differs, but diff does not. Weird, but it can happen
328 322
                         # (e.g. just after the md5 extension was introduced, or if
329 323
                         # md5 somehow expired before the actual object did).
@@ -336,18 +330,14 @@  discard block
 block discarded – undo
336 330
                     'change_type' => 'replace',
337 331
                     'data' => ($use_cache ? $diff : $object),
338 332
                 );
339
-                if ($use_cache)
340
-                {
333
+                if ($use_cache) {
341 334
                     # Save the last-published state of the object, for future comparison.
342 335
                     $cached_values2['clogmd5#'.$object_type.'#'.$key] = $current_md5;
343 336
                     $cached_values1['clog#'.$object_type.'#'.$key] = $object;
344 337
                 }
345
-            }
346
-            else
347
-            {
338
+            } else {
348 339
                 # Currently, the object does not exist.
349
-                if ($use_cache && ($cached_values1['clog#'.$object_type.'#'.$key] === false))
350
-                {
340
+                if ($use_cache && ($cached_values1['clog#'.$object_type.'#'.$key] === false)) {
351 341
                     # No need to delete, we have already published its deletion.
352 342
                     continue;
353 343
                 }
@@ -356,8 +346,7 @@  discard block
 block discarded – undo
356 346
                     'object_key' => array($key_name => $key),
357 347
                     'change_type' => 'delete',
358 348
                 );
359
-                if ($use_cache)
360
-                {
349
+                if ($use_cache) {
361 350
                     # Cache the fact, that the object was deleted.
362 351
                     $cached_values2['clogmd5#'.$object_type.'#'.$key] = false;
363 352
                     $cached_values1['clog#'.$object_type.'#'.$key] = false;
@@ -365,19 +354,16 @@  discard block
 block discarded – undo
365 354
             }
366 355
         }
367 356
 
368
-        if ($fulldump_mode)
369
-        {
357
+        if ($fulldump_mode) {
370 358
             return $entries;
371
-        }
372
-        else
373
-        {
359
+        } else {
374 360
             # Save the entries to the clog table.
375 361
 
376
-            if (count($entries) > 0)
377
-            {
362
+            if (count($entries) > 0) {
378 363
                 $data_values = array();
379
-                foreach ($entries as $entry)
380
-                    $data_values[] = gzdeflate(serialize($entry));
364
+                foreach ($entries as $entry) {
365
+                                    $data_values[] = gzdeflate(serialize($entry));
366
+                }
381 367
                 Db::execute("
382 368
                     insert into okapi_clog (data)
383 369
                     values ('".implode("'),('", array_map('\okapi\Db::escape_string', $data_values))."');
@@ -386,8 +372,7 @@  discard block
 block discarded – undo
386 372
 
387 373
             # Update the values kept in OKAPI cache.
388 374
 
389
-            if ($use_cache)
390
-            {
375
+            if ($use_cache) {
391 376
                 Cache::set_many($cached_values1, $cache_timeout);
392 377
                 Cache::set_many($cached_values2, null);  # make it persistent
393 378
             }
@@ -403,10 +388,14 @@  discard block
 block discarded – undo
403 388
         $first_id = Db::select_value("
404 389
             select id from okapi_clog where id > '".Db::escape_string($since)."' limit 1
405 390
         ");
406
-        if ($first_id === null)
407
-            return true; # okay, since points to the newest revision
408
-        if ($first_id == $since + 1)
409
-            return true; # okay, revision $since + 1 is present
391
+        if ($first_id === null) {
392
+                    return true;
393
+        }
394
+        # okay, since points to the newest revision
395
+        if ($first_id == $since + 1) {
396
+                    return true;
397
+        }
398
+        # okay, revision $since + 1 is present
410 399
 
411 400
         # If we're here, then this means that $first_id > $since + 1.
412 401
         # Revision $since + 1 is already deleted, $since must be too old!
@@ -425,17 +414,17 @@  discard block
 block discarded – undo
425 414
     {
426 415
         $current_revision = self::get_revision();
427 416
         $last_chunk_cut = $current_revision - ($current_revision % self::$chunk_size);
428
-        if ($since >= $last_chunk_cut)
429
-        {
417
+        if ($since >= $last_chunk_cut) {
430 418
             # If, for example, we have a choice to give user 50 items he wants, or 80 items
431 419
             # which we probably already have in cache (and this includes the 50 which the
432 420
             # user wants), then we'll give him 80. If user wants less than half of what we
433 421
             # have (ex. 30), then we'll give him only his 30.
434 422
 
435
-            if ($current_revision - $since > $since - $last_chunk_cut)
436
-                return array($last_chunk_cut + 1, $current_revision);
437
-            else
438
-                return array($since + 1, $current_revision);
423
+            if ($current_revision - $since > $since - $last_chunk_cut) {
424
+                            return array($last_chunk_cut + 1, $current_revision);
425
+            } else {
426
+                            return array($since + 1, $current_revision);
427
+            }
439 428
         }
440 429
         $prev_chunk_cut = $since - ($since % self::$chunk_size);
441 430
         return array($prev_chunk_cut + 1, $prev_chunk_cut + self::$chunk_size);
@@ -446,17 +435,18 @@  discard block
 block discarded – undo
446 435
      */
447 436
     public static function get_chunk($from, $to)
448 437
     {
449
-        if ($to < $from)
450
-            return array();
451
-        if ($to - $from > self::$chunk_size)
452
-            throw new Exception("You should not get chunksize bigger than ".self::$chunk_size." entries at one time.");
438
+        if ($to < $from) {
439
+                    return array();
440
+        }
441
+        if ($to - $from > self::$chunk_size) {
442
+                    throw new Exception("You should not get chunksize bigger than ".self::$chunk_size." entries at one time.");
443
+        }
453 444
 
454 445
         # Check if we already have this chunk in cache.
455 446
 
456 447
         $cache_key = 'clog_chunk#'.$from.'-'.$to;
457 448
         $chunk = Cache::get($cache_key);
458
-        if ($chunk === null)
459
-        {
449
+        if ($chunk === null) {
460 450
             $rs = Db::query("
461 451
                 select id, data
462 452
                 from okapi_clog
@@ -464,8 +454,7 @@  discard block
 block discarded – undo
464 454
                 order by id
465 455
             ");
466 456
             $chunk = array();
467
-            while ($row = Db::fetch_assoc($rs))
468
-            {
457
+            while ($row = Db::fetch_assoc($rs)) {
469 458
                 $chunk[] = unserialize(gzinflate($row['data']));
470 459
             }
471 460
 
@@ -475,10 +464,11 @@  discard block
 block discarded – undo
475 464
             # be ever accessed after the next revision appears, so there is not point
476 465
             # in storing them that long.
477 466
 
478
-            if (($from % self::$chunk_size === 0) && ($to % self::$chunk_size === 0))
479
-                $timeout = 10 * 86400;
480
-            else
481
-                $timeout = 86400;
467
+            if (($from % self::$chunk_size === 0) && ($to % self::$chunk_size === 0)) {
468
+                            $timeout = 10 * 86400;
469
+            } else {
470
+                            $timeout = 86400;
471
+            }
482 472
             Cache::set($cache_key, $chunk, $timeout);
483 473
         }
484 474
 
@@ -511,16 +501,16 @@  discard block
 block discarded – undo
511 501
         $cache_codes = Db::select_column("select wp_oc from caches");
512 502
         $cache_code_groups = Okapi::make_groups($cache_codes, self::$chunk_size);
513 503
         unset($cache_codes);
514
-        foreach ($cache_code_groups as $cache_codes)
515
-        {
504
+        foreach ($cache_code_groups as $cache_codes) {
516 505
             $basename = "part".str_pad($i, 5, "0", STR_PAD_LEFT);
517 506
             $json_files[] = $basename.".json";
518 507
             $entries = self::generate_changelog_entries('services/caches/geocaches', 'geocache', 'cache_codes',
519 508
                 'code', $cache_codes, self::$logged_cache_fields, true, false);
520 509
             $filtered = array();
521
-            foreach ($entries as $entry)
522
-                if ($entry['change_type'] == 'replace')
510
+            foreach ($entries as $entry) {
511
+                            if ($entry['change_type'] == 'replace')
523 512
                     $filtered[] = $entry;
513
+            }
524 514
             unset($entries);
525 515
             file_put_contents("$dir/$basename.json", json_encode($filtered));
526 516
             unset($filtered);
@@ -532,8 +522,7 @@  discard block
 block discarded – undo
532 522
         # too much memory. Hence the offset/limit loop.
533 523
 
534 524
         $offset = 0;
535
-        while (true)
536
-        {
525
+        while (true) {
537 526
             $log_uuids = Db::select_column("
538 527
                 select uuid
539 528
                 from cache_logs
@@ -541,21 +530,22 @@  discard block
 block discarded – undo
541 530
                 order by uuid
542 531
                 limit $offset, 10000
543 532
             ");
544
-            if (count($log_uuids) == 0)
545
-                break;
533
+            if (count($log_uuids) == 0) {
534
+                            break;
535
+            }
546 536
             $offset += 10000;
547 537
             $log_uuid_groups = Okapi::make_groups($log_uuids, 500);
548 538
             unset($log_uuids);
549
-            foreach ($log_uuid_groups as $log_uuids)
550
-            {
539
+            foreach ($log_uuid_groups as $log_uuids) {
551 540
                 $basename = "part".str_pad($i, 5, "0", STR_PAD_LEFT);
552 541
                 $json_files[] = $basename.".json";
553 542
                 $entries = self::generate_changelog_entries('services/logs/entries', 'log', 'log_uuids',
554 543
                     'uuid', $log_uuids, self::$logged_log_entry_fields, true, false);
555 544
                 $filtered = array();
556
-                foreach ($entries as $entry)
557
-                    if ($entry['change_type'] == 'replace')
545
+                foreach ($entries as $entry) {
546
+                                    if ($entry['change_type'] == 'replace')
558 547
                         $filtered[] = $entry;
548
+                }
559 549
                 unset($entries);
560 550
                 file_put_contents("$dir/$basename.json", json_encode($filtered));
561 551
                 unset($filtered);
@@ -581,8 +571,9 @@  discard block
 block discarded – undo
581 571
         # Compute uncompressed size.
582 572
 
583 573
         $size = filesize("$dir/index.json");
584
-        foreach ($json_files as $filename)
585
-            $size += filesize("$dir/$filename");
574
+        foreach ($json_files as $filename) {
575
+                    $size += filesize("$dir/$filename");
576
+        }
586 577
 
587 578
         # Create JSON archive. We use tar options: -j for bzip2, -z for gzip
588 579
         # (bzip2 is MUCH slower).
Please login to merge, or discard this patch.
htdocs/okapi/views/devel/comparator.inc.php 4 patches
Doc Comments   +4 added lines, -2 removed lines patch added patch discarded remove patch
@@ -215,6 +215,7 @@  discard block
 block discarded – undo
215 215
     * Makes comparison of the given database structures, support some options
216 216
     * @access private
217 217
     * @param string $source and $dest are strings - database tables structures
218
+    * @param string $dest
218 219
     * @return array
219 220
     * - table (array)
220 221
     *       - destOrphan (boolean)
@@ -376,8 +377,8 @@  discard block
 block discarded – undo
376 377
     /**
377 378
     * returns array of fields or keys definitions that differs in the given tables structure
378 379
     * @access private
379
-    * @param sring $sourceSql table structure
380
-    * @param sring $destSql right table structure
380
+    * @param string $sourceSql table structure
381
+    * @param string $destSql right table structure
381 382
     * supports some $options
382 383
     * @return array
383 384
     *   - [0]
@@ -734,6 +735,7 @@  discard block
 block discarded – undo
734 735
     /**
735 736
     * works the same as getDelimPos except returns position of the first occurence of the delimiter starting from
736 737
     * the end of the string
738
+    * @param string $string
737 739
     */
738 740
     function getDelimRpos($string, $offset=0, $delim=';', $skipInBrackets=false)
739 741
     {
Please login to merge, or discard this patch.
Indentation   +86 added lines, -86 removed lines patch added patch discarded remove patch
@@ -57,9 +57,9 @@  discard block
 block discarded – undo
57 57
     var $config = array();//updater configuration
58 58
 
59 59
     /**
60
-    * Constructor
61
-    * @access public
62
-    */
60
+     * Constructor
61
+     * @access public
62
+     */
63 63
     function __construct()
64 64
     {
65 65
         $this->init();
@@ -82,9 +82,9 @@  discard block
 block discarded – undo
82 82
     }
83 83
 
84 84
     /**
85
-    * merges current updater config with the given one
86
-    * @param assoc_array $config new configuration values
87
-    */
85
+     * merges current updater config with the given one
86
+     * @param assoc_array $config new configuration values
87
+     */
88 88
     function setConfig($config=array())
89 89
     {
90 90
         if (is_array($config))
@@ -94,13 +94,13 @@  discard block
 block discarded – undo
94 94
     }
95 95
 
96 96
     /**
97
-    * Returns array of update SQL with default options, $source, $dest - database structures
98
-    * @access public
99
-    * @param string $source structure dump of database to update
100
-    * @param string $dest structure dump of the reference database
101
-    * @param bool $asString if true - result will be a string, otherwise - array
102
-    * @return array|string update sql statements - in array or string (separated with ';')
103
-    */
97
+     * Returns array of update SQL with default options, $source, $dest - database structures
98
+     * @access public
99
+     * @param string $source structure dump of database to update
100
+     * @param string $dest structure dump of the reference database
101
+     * @param bool $asString if true - result will be a string, otherwise - array
102
+     * @return array|string update sql statements - in array or string (separated with ';')
103
+     */
104 104
     function getUpdates($source, $dest, $asString=false)
105 105
     {
106 106
         $result = $asString?'':array();
@@ -123,8 +123,8 @@  discard block
 block discarded – undo
123 123
     }
124 124
 
125 125
     /**
126
-    * Filters comparison result and lefts only sync actions allowed by 'updateTypes' option
127
-    */
126
+     * Filters comparison result and lefts only sync actions allowed by 'updateTypes' option
127
+     */
128 128
     function filterDiffs($compRes)
129 129
     {
130 130
         $result = array();
@@ -183,9 +183,9 @@  discard block
 block discarded – undo
183 183
     }
184 184
 
185 185
     /**
186
-    * Gets structured general info about the databases diff :
187
-    * array(sourceOrphans=>array(...), destOrphans=>array(...), different=>array(...))
188
-    */
186
+     * Gets structured general info about the databases diff :
187
+     * array(sourceOrphans=>array(...), destOrphans=>array(...), different=>array(...))
188
+     */
189 189
     function getDiffInfo($compRes)
190 190
     {
191 191
         if (!is_array($compRes))
@@ -212,19 +212,19 @@  discard block
 block discarded – undo
212 212
     }
213 213
 
214 214
     /**
215
-    * Makes comparison of the given database structures, support some options
216
-    * @access private
217
-    * @param string $source and $dest are strings - database tables structures
218
-    * @return array
219
-    * - table (array)
220
-    *       - destOrphan (boolean)
221
-    *       - sourceOrphan (boolean)
222
-    *       - differs (array) OR (boolean) false if no diffs
223
-    *           - [0](array)
224
-    *               - source (string) structure definition line in the out-of-date table
225
-    *               - dest (string) structure definition line in the reference table
226
-    *           - [1](array) ...
227
-    */
215
+     * Makes comparison of the given database structures, support some options
216
+     * @access private
217
+     * @param string $source and $dest are strings - database tables structures
218
+     * @return array
219
+     * - table (array)
220
+     *       - destOrphan (boolean)
221
+     *       - sourceOrphan (boolean)
222
+     *       - differs (array) OR (boolean) false if no diffs
223
+     *           - [0](array)
224
+     *               - source (string) structure definition line in the out-of-date table
225
+     *               - dest (string) structure definition line in the reference table
226
+     *           - [1](array) ...
227
+     */
228 228
     function compare($source, $dest)
229 229
     {
230 230
         $this->sourceStruct = $source;
@@ -272,10 +272,10 @@  discard block
 block discarded – undo
272 272
     }
273 273
 
274 274
     /**
275
-    * Retrieves list of table names from the database structure dump
276
-    * @access private
277
-    * @param string $struct database structure listing
278
-    */
275
+     * Retrieves list of table names from the database structure dump
276
+     * @access private
277
+     * @param string $struct database structure listing
278
+     */
279 279
     function getTableList($struct)
280 280
     {
281 281
         $result = array();
@@ -290,13 +290,13 @@  discard block
 block discarded – undo
290 290
     }
291 291
 
292 292
     /**
293
-    * Retrieves table structure definition from the database structure dump
294
-    * @access private
295
-    * @param string $struct database structure listing
296
-    * @param string $tab table name
297
-    * @param bool $removeDatabase - either to remove database name in "CREATE TABLE database.tab"-like declarations
298
-    * @return string table structure definition
299
-    */
293
+     * Retrieves table structure definition from the database structure dump
294
+     * @access private
295
+     * @param string $struct database structure listing
296
+     * @param string $tab table name
297
+     * @param bool $removeDatabase - either to remove database name in "CREATE TABLE database.tab"-like declarations
298
+     * @return string table structure definition
299
+     */
300 300
     function getTabSql($struct, $tab, $removeDatabase=true)
301 301
     {
302 302
         $result = '';
@@ -327,9 +327,9 @@  discard block
 block discarded – undo
327 327
     }
328 328
 
329 329
     /**
330
-    * Splits table sql into indexed array
331
-    *
332
-    */
330
+     * Splits table sql into indexed array
331
+     *
332
+     */
333 333
     function splitTabSql($sql)
334 334
     {
335 335
         $result = array();
@@ -374,17 +374,17 @@  discard block
 block discarded – undo
374 374
     }
375 375
 
376 376
     /**
377
-    * returns array of fields or keys definitions that differs in the given tables structure
378
-    * @access private
379
-    * @param sring $sourceSql table structure
380
-    * @param sring $destSql right table structure
381
-    * supports some $options
382
-    * @return array
383
-    *   - [0]
384
-    *       - source (string) out-of-date table field definition
385
-    *       - dest (string) reference table field definition
386
-    *   - [1]...
387
-    */
377
+     * returns array of fields or keys definitions that differs in the given tables structure
378
+     * @access private
379
+     * @param sring $sourceSql table structure
380
+     * @param sring $destSql right table structure
381
+     * supports some $options
382
+     * @return array
383
+     *   - [0]
384
+     *       - source (string) out-of-date table field definition
385
+     *       - dest (string) reference table field definition
386
+     *   - [1]...
387
+     */
388 388
     function compareSql($sourceSql, $destSql)//$sourceSql, $destSql
389 389
     {
390 390
         $result = array();
@@ -449,13 +449,13 @@  discard block
 block discarded – undo
449 449
     }
450 450
 
451 451
     /**
452
-    * Transforms table structure defnition line into key=>value pair where the key is a string that uniquely
453
-    * defines field or key desribed
454
-    * @access private
455
-    * @param string $line field definition string
456
-    * @return array array with single key=>value pair as described in the description
457
-    * implements some options
458
-    */
452
+     * Transforms table structure defnition line into key=>value pair where the key is a string that uniquely
453
+     * defines field or key desribed
454
+     * @access private
455
+     * @param string $line field definition string
456
+     * @return array array with single key=>value pair as described in the description
457
+     * implements some options
458
+     */
459 459
     function processLine($line)
460 460
     {
461 461
         $options = $this->config;
@@ -497,13 +497,13 @@  discard block
 block discarded – undo
497 497
     }
498 498
 
499 499
     /**
500
-    * Takes an output of compare() method to generate the set of sql needed to update source table to make it
501
-    * look as a destination one
502
-    * @access private
503
-    * @param array $diff compare() method output
504
-    * @return array list of sql statements
505
-    * supports query generation options
506
-    */
500
+     * Takes an output of compare() method to generate the set of sql needed to update source table to make it
501
+     * look as a destination one
502
+     * @access private
503
+     * @param array $diff compare() method output
504
+     * @return array list of sql statements
505
+     * supports query generation options
506
+     */
507 507
     function getDiffSql($diff)//maybe add option to ommit or force 'IF NOT EXISTS', skip autoincrement
508 508
     {
509 509
         $options = $this->config;
@@ -566,13 +566,13 @@  discard block
 block discarded – undo
566 566
     }
567 567
 
568 568
     /**
569
-    * Compiles update sql
570
-    * @access private
571
-    * @param string $action - 'drop', 'add' or 'modify'
572
-    * @param string $tab table name
573
-    * @param string $sql definition of the element to change
574
-    * @return string update sql
575
-    */
569
+     * Compiles update sql
570
+     * @access private
571
+     * @param string $action - 'drop', 'add' or 'modify'
572
+     * @param string $tab table name
573
+     * @param string $sql definition of the element to change
574
+     * @return string update sql
575
+     */
576 576
     function getActionSql($action, $tab, $sql)
577 577
     {
578 578
         $result = 'ALTER TABLE `'.$tab.'` ';
@@ -645,12 +645,12 @@  discard block
 block discarded – undo
645 645
     }
646 646
 
647 647
     /**
648
-    * Searches for the position of the next delimiter which is not inside string literal like 'this ; ' or
649
-    * like "this ; ".
650
-    *
651
-    * Handles escaped \" and \'. Also handles sql comments.
652
-    * Actualy it is regex-based Finit State Machine (FSN)
653
-    */
648
+     * Searches for the position of the next delimiter which is not inside string literal like 'this ; ' or
649
+     * like "this ; ".
650
+     *
651
+     * Handles escaped \" and \'. Also handles sql comments.
652
+     * Actualy it is regex-based Finit State Machine (FSN)
653
+     */
654 654
     function getDelimPos($string, $offset=0, $delim=';', $skipInBrackets=false)
655 655
     {
656 656
         $stack = array();
@@ -732,9 +732,9 @@  discard block
 block discarded – undo
732 732
     }
733 733
 
734 734
     /**
735
-    * works the same as getDelimPos except returns position of the first occurence of the delimiter starting from
736
-    * the end of the string
737
-    */
735
+     * works the same as getDelimPos except returns position of the first occurence of the delimiter starting from
736
+     * the end of the string
737
+     */
738 738
     function getDelimRpos($string, $offset=0, $delim=';', $skipInBrackets=false)
739 739
     {
740 740
         $pos = $this->getDelimPos($string, $offset, $delim, $skipInBrackets);
Please login to merge, or discard this patch.
Spacing   +74 added lines, -74 removed lines patch added patch discarded remove patch
@@ -52,9 +52,9 @@  discard block
 block discarded – undo
52 52
 */
53 53
 class dbStructUpdater
54 54
 {
55
-    var $sourceStruct = '';//structure dump of the reference database
56
-    var $destStruct = '';//structure dump of database to update
57
-    var $config = array();//updater configuration
55
+    var $sourceStruct = ''; //structure dump of the reference database
56
+    var $destStruct = ''; //structure dump of database to update
57
+    var $config = array(); //updater configuration
58 58
 
59 59
     /**
60 60
     * Constructor
@@ -85,7 +85,7 @@  discard block
 block discarded – undo
85 85
     * merges current updater config with the given one
86 86
     * @param assoc_array $config new configuration values
87 87
     */
88
-    function setConfig($config=array())
88
+    function setConfig($config = array())
89 89
     {
90 90
         if (is_array($config))
91 91
         {
@@ -101,9 +101,9 @@  discard block
 block discarded – undo
101 101
     * @param bool $asString if true - result will be a string, otherwise - array
102 102
     * @return array|string update sql statements - in array or string (separated with ';')
103 103
     */
104
-    function getUpdates($source, $dest, $asString=false)
104
+    function getUpdates($source, $dest, $asString = false)
105 105
     {
106
-        $result = $asString?'':array();
106
+        $result = $asString ? '' : array();
107 107
         $compRes = $this->compare($source, $dest);
108 108
         if (empty($compRes))
109 109
         {
@@ -138,7 +138,7 @@  discard block
 block discarded – undo
138 138
         }
139 139
         $allowedActions = array('create', 'drop', 'add', 'remove', 'modify');
140 140
         $updateActions = array_intersect($updateActions, $allowedActions);
141
-        foreach($compRes as $table=>$info)
141
+        foreach ($compRes as $table=>$info)
142 142
         {
143 143
             if ($info['sourceOrphan'])
144 144
             {
@@ -154,7 +154,7 @@  discard block
 block discarded – undo
154 154
                     $result[$table] = $info;
155 155
                 }
156 156
             }
157
-            elseif($info['differs'])
157
+            elseif ($info['differs'])
158 158
             {
159 159
                 $resultInfo = $info;
160 160
                 unset($resultInfo['differs']);
@@ -168,7 +168,7 @@  discard block
 block discarded – undo
168 168
                     {
169 169
                         $resultInfo['differs'][] = $diff;
170 170
                     }
171
-                    elseif(in_array('modify', $updateActions))
171
+                    elseif (in_array('modify', $updateActions))
172 172
                     {
173 173
                         $resultInfo['differs'][] = $diff;
174 174
                     }
@@ -193,7 +193,7 @@  discard block
 block discarded – undo
193 193
             return false;
194 194
         }
195 195
         $result = array('sourceOrphans'=>array(), 'destOrphans'=>array(), 'different'=>array());
196
-        foreach($compRes as $table=>$info)
196
+        foreach ($compRes as $table=>$info)
197 197
         {
198 198
             if ($info['sourceOrphan'])
199 199
             {
@@ -242,7 +242,7 @@  discard block
 block discarded – undo
242 242
         foreach ($all as $tab)
243 243
         {
244 244
             $info = array('destOrphan'=>false, 'sourceOrphan'=>false, 'differs'=>false);
245
-            if(in_array($tab, $destOrphans))
245
+            if (in_array($tab, $destOrphans))
246 246
             {
247 247
                 $info['destOrphan'] = true;
248 248
             }
@@ -255,7 +255,7 @@  discard block
 block discarded – undo
255 255
                 $destSql = $this->getTabSql($this->destStruct, $tab, true);
256 256
                 $sourceSql = $this->getTabSql($this->sourceStruct, $tab, true);
257 257
                 $diffs = $this->compareSql($sourceSql, $destSql);
258
-                if ($diffs===false)
258
+                if ($diffs === false)
259 259
                 {
260 260
                     trigger_error('[WARNING] error parsing definition of table "'.$tab.'" - skipped');
261 261
                     continue;
@@ -264,7 +264,7 @@  discard block
 block discarded – undo
264 264
                 {
265 265
                     $info['differs'] = $diffs;
266 266
                 }
267
-                else continue;//empty array
267
+                else continue; //empty array
268 268
             }
269 269
             $result[$tab] = $info;
270 270
         }
@@ -281,7 +281,7 @@  discard block
 block discarded – undo
281 281
         $result = array();
282 282
         if (preg_match_all('/CREATE(?:\s*TEMPORARY)?\s*TABLE\s*(?:IF NOT EXISTS\s*)?(?:`?(\w+)`?\.)?`?(\w+)`?/i', $struct, $m))
283 283
         {
284
-            foreach($m[2] as $match)//m[1] is a database name if any
284
+            foreach ($m[2] as $match)//m[1] is a database name if any
285 285
             {
286 286
                 $result[] = $match;
287 287
             }
@@ -297,7 +297,7 @@  discard block
 block discarded – undo
297 297
     * @param bool $removeDatabase - either to remove database name in "CREATE TABLE database.tab"-like declarations
298 298
     * @return string table structure definition
299 299
     */
300
-    function getTabSql($struct, $tab, $removeDatabase=true)
300
+    function getTabSql($struct, $tab, $removeDatabase = true)
301 301
     {
302 302
         $result = '';
303 303
         /* create table should be single line in this case*/
@@ -307,7 +307,7 @@  discard block
 block discarded – undo
307 307
             $tableDef = $m[0][0];
308 308
             $start = $m[0][1];
309 309
             $database = $m[2][0];
310
-            $offset = $start+strlen($m[0][0]);
310
+            $offset = $start + strlen($m[0][0]);
311 311
             $end = $this->getDelimPos($struct, $offset);
312 312
             if ($end === false)
313 313
             {
@@ -315,7 +315,7 @@  discard block
 block discarded – undo
315 315
             }
316 316
             else
317 317
             {
318
-                $result = substr($struct, $start, $end-$start);//already without ';'
318
+                $result = substr($struct, $start, $end - $start); //already without ';'
319 319
             }
320 320
         }
321 321
         $result = trim($result);
@@ -335,27 +335,27 @@  discard block
 block discarded – undo
335 335
         $result = array();
336 336
         //find opening bracket, get the prefix along with it
337 337
         $openBracketPos = $this->getDelimPos($sql, 0, '(');
338
-        if ($openBracketPos===false)
338
+        if ($openBracketPos === false)
339 339
         {
340 340
             trigger_error('[WARNING] can not find opening bracket in table definition');
341 341
             return false;
342 342
         }
343
-        $prefix = substr($sql, 0, $openBracketPos+1);//prefix can not be empty, so do not check it, just trim
343
+        $prefix = substr($sql, 0, $openBracketPos + 1); //prefix can not be empty, so do not check it, just trim
344 344
         $result[] = trim($prefix);
345
-        $body = substr($sql, strlen($prefix));//fields, indexes and part after closing bracket
345
+        $body = substr($sql, strlen($prefix)); //fields, indexes and part after closing bracket
346 346
         //split by commas, get part by part
347
-        while(($commaPos = $this->getDelimPos($body, 0, ',', true))!==false)
347
+        while (($commaPos = $this->getDelimPos($body, 0, ',', true)) !== false)
348 348
         {
349
-            $part = trim(substr($body, 0, $commaPos+1));//read another part and shorten $body
349
+            $part = trim(substr($body, 0, $commaPos + 1)); //read another part and shorten $body
350 350
             if ($part)
351 351
             {
352 352
                 $result[] = $part;
353 353
             }
354
-            $body = substr($body, $commaPos+1);
354
+            $body = substr($body, $commaPos + 1);
355 355
         }
356 356
         //here we have last field (or index) definition + part after closing bracket (ENGINE, ect)
357 357
         $closeBracketPos = $this->getDelimRpos($body, 0, ')');
358
-        if ($closeBracketPos===false)
358
+        if ($closeBracketPos === false)
359 359
         {
360 360
             trigger_error('[WARNING] can not find closing bracket in table definition');
361 361
             return false;
@@ -389,27 +389,27 @@  discard block
 block discarded – undo
389 389
     {
390 390
         $result = array();
391 391
         //split with comma delimiter, not line breaks
392
-        $sourceParts =  $this->splitTabSql($sourceSql);
393
-        if ($sourceParts===false)//error parsing sql
392
+        $sourceParts = $this->splitTabSql($sourceSql);
393
+        if ($sourceParts === false)//error parsing sql
394 394
         {
395 395
             trigger_error('[WARNING] error parsing source sql');
396 396
             return false;
397 397
         }
398 398
         $destParts = $this->splitTabSql($destSql);
399
-        if ($destParts===false)
399
+        if ($destParts === false)
400 400
         {
401 401
             trigger_error('[WARNING] error parsing destination sql');
402 402
             return false;
403 403
         }
404 404
         $sourcePartsIndexed = array();
405 405
         $destPartsIndexed = array();
406
-        foreach($sourceParts as $line)
406
+        foreach ($sourceParts as $line)
407 407
         {
408 408
             $lineInfo = $this->processLine($line);
409 409
             if (!$lineInfo) continue;
410 410
             $sourcePartsIndexed[$lineInfo['key']] = $lineInfo['line'];
411 411
         }
412
-        foreach($destParts as $line)
412
+        foreach ($destParts as $line)
413 413
         {
414 414
             $lineInfo = $this->processLine($line);
415 415
             if (!$lineInfo) continue;
@@ -418,16 +418,16 @@  discard block
 block discarded – undo
418 418
         $sourceKeys = array_keys($sourcePartsIndexed);
419 419
         $destKeys = array_keys($destPartsIndexed);
420 420
         $all = array_unique(array_merge($sourceKeys, $destKeys));
421
-        sort($all);//fields first, then indexes - because fields are prefixed with '!'
421
+        sort($all); //fields first, then indexes - because fields are prefixed with '!'
422 422
 
423 423
         foreach ($all as $key)
424 424
         {
425 425
             $info = array('source'=>'', 'dest'=>'');
426
-            $inSource= in_array($key, $sourceKeys);
427
-            $inDest= in_array($key, $destKeys);
426
+            $inSource = in_array($key, $sourceKeys);
427
+            $inDest = in_array($key, $destKeys);
428 428
             $sourceOrphan = $inSource && !$inDest;
429 429
             $destOrphan = $inDest && !$inSource;
430
-            $different =  $inSource && $inDest &&
430
+            $different = $inSource && $inDest &&
431 431
             strcasecmp($this->normalizeString($destPartsIndexed[$key]), $this->normalizeString($sourcePartsIndexed[$key]));
432 432
             if ($sourceOrphan)
433 433
             {
@@ -472,11 +472,11 @@  discard block
 block discarded – undo
472 472
         }
473 473
         elseif (preg_match('/^`?\w+`?/i', $line, $m))//field definition
474 474
         {
475
-            $key = '!'.$m[0];//to make sure fields will be synchronised before the keys
475
+            $key = '!'.$m[0]; //to make sure fields will be synchronised before the keys
476 476
         }
477 477
         else
478 478
         {
479
-            return false;//line has no valuable info (empty or comment)
479
+            return false; //line has no valuable info (empty or comment)
480 480
         }
481 481
         //$key = str_replace('`', '', $key);
482 482
         if (!empty($options['varcharDefaultIgnore']))
@@ -492,7 +492,7 @@  discard block
 block discarded – undo
492 492
             $line = preg_replace("/ AUTO_INCREMENT=[0-9]+/i", '', $line);
493 493
         }
494 494
         $result['key'] = $this->normalizeString($key);
495
-        $result['line']= $line;
495
+        $result['line'] = $line;
496 496
         return $result;
497 497
     }
498 498
 
@@ -512,7 +512,7 @@  discard block
 block discarded – undo
512 512
         {
513 513
             return $sqls;
514 514
         }
515
-        foreach($diff as $tab=>$info)
515
+        foreach ($diff as $tab=>$info)
516 516
         {
517 517
             if ($info['sourceOrphan'])//delete it
518 518
             {
@@ -538,7 +538,7 @@  discard block
 block discarded – undo
538 538
             }
539 539
             else
540 540
             {
541
-                foreach($info['differs'] as $finfo)
541
+                foreach ($info['differs'] as $finfo)
542 542
                 {
543 543
                     $inDest = !empty($finfo['dest']);
544 544
                     $inSource = !empty($finfo['source']);
@@ -577,51 +577,51 @@  discard block
 block discarded – undo
577 577
     {
578 578
         $result = 'ALTER TABLE `'.$tab.'` ';
579 579
         $action = strtolower($action);
580
-        $keyField = '`?\w`?(?:\(\d+\))?';//matches `name`(10)
581
-        $keyFieldList = '(?:'.$keyField.'(?:,\s?)?)+';//matches `name`(10),`desc`(255)
580
+        $keyField = '`?\w`?(?:\(\d+\))?'; //matches `name`(10)
581
+        $keyFieldList = '(?:'.$keyField.'(?:,\s?)?)+'; //matches `name`(10),`desc`(255)
582 582
         if (preg_match('/((?:PRIMARY )|(?:UNIQUE )|(?:FULLTEXT ))?KEY `?(\w+)?`?\s(\('.$keyFieldList.'\))/i', $sql, $m))
583 583
         {   //key and index operations
584 584
             $type = strtolower(trim($m[1]));
585 585
             $name = trim($m[2]);
586 586
             $fields = trim($m[3]);
587
-            switch($action)
587
+            switch ($action)
588 588
             {
589 589
                 case 'drop':
590
-                    if ($type=='primary')
590
+                    if ($type == 'primary')
591 591
                     {
592
-                        $result.= 'DROP PRIMARY KEY';
592
+                        $result .= 'DROP PRIMARY KEY';
593 593
                     }
594 594
                     else
595 595
                     {
596
-                        $result.= 'DROP INDEX `'.$name.'`';
596
+                        $result .= 'DROP INDEX `'.$name.'`';
597 597
                     }
598 598
                 break;
599 599
                 case 'add':
600
-                    if ($type=='primary')
600
+                    if ($type == 'primary')
601 601
                     {
602
-                        $result.= 'ADD PRIMARY KEY '.$fields;
602
+                        $result .= 'ADD PRIMARY KEY '.$fields;
603 603
                     }
604
-                    elseif ($type=='')
604
+                    elseif ($type == '')
605 605
                     {
606
-                        $result.= 'ADD INDEX `'.$name.'` '.$fields;
606
+                        $result .= 'ADD INDEX `'.$name.'` '.$fields;
607 607
                     }
608 608
                     else
609 609
                     {
610
-                        $result .='ADD '.strtoupper($type).' `'.$name.'` '.$fields;//fulltext or unique
610
+                        $result .= 'ADD '.strtoupper($type).' `'.$name.'` '.$fields; //fulltext or unique
611 611
                     }
612 612
                 break;
613 613
                 case 'modify':
614
-                    if ($type=='primary')
614
+                    if ($type == 'primary')
615 615
                     {
616
-                        $result.='DROP PRIMARY KEY, ADD PRIMARY KEY '.$fields;
616
+                        $result .= 'DROP PRIMARY KEY, ADD PRIMARY KEY '.$fields;
617 617
                     }
618
-                    elseif ($type=='')
618
+                    elseif ($type == '')
619 619
                     {
620
-                        $result.='DROP INDEX `'.$name.'`, ADD INDEX `'.$name.'` '.$fields;
620
+                        $result .= 'DROP INDEX `'.$name.'`, ADD INDEX `'.$name.'` '.$fields;
621 621
                     }
622 622
                     else
623 623
                     {
624
-                        $result.='DROP INDEX `'.$name.'`, ADD '.strtoupper($type).' `'.$name.'` '.$fields;//fulltext or unique
624
+                        $result .= 'DROP INDEX `'.$name.'`, ADD '.strtoupper($type).' `'.$name.'` '.$fields; //fulltext or unique
625 625
                     }
626 626
                 break;
627 627
 
@@ -630,15 +630,15 @@  discard block
 block discarded – undo
630 630
         else //fields operations
631 631
         {
632 632
             $sql = rtrim(trim($sql), ',');
633
-            $result.= strtoupper($action);
634
-            if ($action=='drop')
633
+            $result .= strtoupper($action);
634
+            if ($action == 'drop')
635 635
             {
636 636
                 $spacePos = strpos($sql, ' ');
637
-                $result.= ' '.substr($sql, 0, $spacePos);
637
+                $result .= ' '.substr($sql, 0, $spacePos);
638 638
             }
639 639
             else
640 640
             {
641
-                $result.= ' '.$sql;
641
+                $result .= ' '.$sql;
642 642
             }
643 643
         }
644 644
         return $result;
@@ -651,39 +651,39 @@  discard block
 block discarded – undo
651 651
     * Handles escaped \" and \'. Also handles sql comments.
652 652
     * Actualy it is regex-based Finit State Machine (FSN)
653 653
     */
654
-    function getDelimPos($string, $offset=0, $delim=';', $skipInBrackets=false)
654
+    function getDelimPos($string, $offset = 0, $delim = ';', $skipInBrackets = false)
655 655
     {
656 656
         $stack = array();
657
-        $rbs = '\\\\';  //reg - escaped backslash
657
+        $rbs = '\\\\'; //reg - escaped backslash
658 658
         $regPrefix = "(?<!$rbs)(?:$rbs{2})*";
659 659
         $reg = $regPrefix.'("|\')|(/\\*)|(\\*/)|(-- )|(\r\n|\r|\n)|';
660 660
         if ($skipInBrackets)
661 661
         {
662
-            $reg.='(\(|\))|';
662
+            $reg .= '(\(|\))|';
663 663
         }
664 664
         else
665 665
         {
666
-            $reg.='()';
666
+            $reg .= '()';
667 667
         }
668 668
         $reg .= '('.preg_quote($delim).')';
669 669
         while (preg_match('%'.$reg.'%', $string, $m, PREG_OFFSET_CAPTURE, $offset))
670 670
         {
671
-            $offset = $m[0][1]+strlen($m[0][0]);
672
-            if (end($stack)=='/*')
671
+            $offset = $m[0][1] + strlen($m[0][0]);
672
+            if (end($stack) == '/*')
673 673
             {
674 674
                 if (!empty($m[3][0]))
675 675
                 {
676 676
                     array_pop($stack);
677 677
                 }
678
-                continue;//here we could also simplify regexp
678
+                continue; //here we could also simplify regexp
679 679
             }
680
-            if (end($stack)=='-- ')
680
+            if (end($stack) == '-- ')
681 681
             {
682 682
                 if (!empty($m[5][0]))
683 683
                 {
684 684
                     array_pop($stack);
685 685
                 }
686
-                continue;//here we could also simplify regexp
686
+                continue; //here we could also simplify regexp
687 687
             }
688 688
 
689 689
             if (!empty($m[7][0]))// ';' found
@@ -699,18 +699,18 @@  discard block
 block discarded – undo
699 699
             }
700 700
             if (!empty($m[6][0]))// '(' or ')' found
701 701
             {
702
-                if (empty($stack) && $m[6][0]=='(')
702
+                if (empty($stack) && $m[6][0] == '(')
703 703
                 {
704 704
                     array_push($stack, $m[6][0]);
705 705
                 }
706
-                elseif($m[6][0]==')' && end($stack)=='(')
706
+                elseif ($m[6][0] == ')' && end($stack) == '(')
707 707
                 {
708 708
                     array_pop($stack);
709 709
                 }
710 710
             }
711 711
             elseif (!empty($m[1][0]))// ' or " found
712 712
             {
713
-                if (end($stack)==$m[1][0])
713
+                if (end($stack) == $m[1][0])
714 714
                 {
715 715
                     array_pop($stack);
716 716
                 }
@@ -735,22 +735,22 @@  discard block
 block discarded – undo
735 735
     * works the same as getDelimPos except returns position of the first occurence of the delimiter starting from
736 736
     * the end of the string
737 737
     */
738
-    function getDelimRpos($string, $offset=0, $delim=';', $skipInBrackets=false)
738
+    function getDelimRpos($string, $offset = 0, $delim = ';', $skipInBrackets = false)
739 739
     {
740 740
         $pos = $this->getDelimPos($string, $offset, $delim, $skipInBrackets);
741
-        if ($pos===false)
741
+        if ($pos === false)
742 742
         {
743 743
             return false;
744 744
         }
745 745
         do
746 746
         {
747
-            $newPos=$this->getDelimPos($string, $pos+1, $delim, $skipInBrackets);
747
+            $newPos = $this->getDelimPos($string, $pos + 1, $delim, $skipInBrackets);
748 748
             if ($newPos !== false)
749 749
             {
750 750
                 $pos = $newPos;
751 751
             }
752 752
         }
753
-        while($newPos!==false);
753
+        while ($newPos !== false);
754 754
         return $pos;
755 755
     }
756 756
 
Please login to merge, or discard this patch.
Braces   +133 added lines, -214 removed lines patch added patch discarded remove patch
@@ -87,8 +87,7 @@  discard block
 block discarded – undo
87 87
     */
88 88
     function setConfig($config=array())
89 89
     {
90
-        if (is_array($config))
91
-        {
90
+        if (is_array($config)) {
92 91
             $this->config = array_merge($this->config, $config);
93 92
         }
94 93
     }
@@ -105,18 +104,15 @@  discard block
 block discarded – undo
105 104
     {
106 105
         $result = $asString?'':array();
107 106
         $compRes = $this->compare($source, $dest);
108
-        if (empty($compRes))
109
-        {
107
+        if (empty($compRes)) {
110 108
             return $result;
111 109
         }
112 110
         $compRes = $this->filterDiffs($compRes);
113
-        if (empty($compRes))
114
-        {
111
+        if (empty($compRes)) {
115 112
             return $result;
116 113
         }
117 114
         $result = $this->getDiffSql($compRes);
118
-        if ($asString)
119
-        {
115
+        if ($asString) {
120 116
             $result = implode(";\r\n", $result).';';
121 117
         }
122 118
         return $result;
@@ -128,53 +124,35 @@  discard block
 block discarded – undo
128 124
     function filterDiffs($compRes)
129 125
     {
130 126
         $result = array();
131
-        if (is_array($this->config['updateTypes']))
132
-        {
127
+        if (is_array($this->config['updateTypes'])) {
133 128
             $updateActions = $this->config['updateTypes'];
134
-        }
135
-        else
136
-        {
129
+        } else {
137 130
             $updateActions = array_map('trim', explode(',', $this->config['updateTypes']));
138 131
         }
139 132
         $allowedActions = array('create', 'drop', 'add', 'remove', 'modify');
140 133
         $updateActions = array_intersect($updateActions, $allowedActions);
141
-        foreach($compRes as $table=>$info)
142
-        {
143
-            if ($info['sourceOrphan'])
144
-            {
145
-                if (in_array('create', $updateActions))
146
-                {
134
+        foreach($compRes as $table=>$info) {
135
+            if ($info['sourceOrphan']) {
136
+                if (in_array('create', $updateActions)) {
147 137
                     $result[$table] = $info;
148 138
                 }
149
-            }
150
-            elseif ($info['destOrphan'])
151
-            {
152
-                if (in_array('drop', $updateActions))
153
-                {
139
+            } elseif ($info['destOrphan']) {
140
+                if (in_array('drop', $updateActions)) {
154 141
                     $result[$table] = $info;
155 142
                 }
156
-            }
157
-            elseif($info['differs'])
158
-            {
143
+            } elseif($info['differs']) {
159 144
                 $resultInfo = $info;
160 145
                 unset($resultInfo['differs']);
161
-                foreach ($info['differs'] as $diff)
162
-                {
163
-                    if (empty($diff['dest']) && in_array('add', $updateActions))
164
-                    {
146
+                foreach ($info['differs'] as $diff) {
147
+                    if (empty($diff['dest']) && in_array('add', $updateActions)) {
165 148
                         $resultInfo['differs'][] = $diff;
166
-                    }
167
-                    elseif (empty($diff['source']) && in_array('remove', $updateActions))
168
-                    {
149
+                    } elseif (empty($diff['source']) && in_array('remove', $updateActions)) {
169 150
                         $resultInfo['differs'][] = $diff;
170
-                    }
171
-                    elseif(in_array('modify', $updateActions))
172
-                    {
151
+                    } elseif(in_array('modify', $updateActions)) {
173 152
                         $resultInfo['differs'][] = $diff;
174 153
                     }
175 154
                 }
176
-                if (!empty($resultInfo['differs']))
177
-                {
155
+                if (!empty($resultInfo['differs'])) {
178 156
                     $result[$table] = $resultInfo;
179 157
                 }
180 158
             }
@@ -188,23 +166,16 @@  discard block
 block discarded – undo
188 166
     */
189 167
     function getDiffInfo($compRes)
190 168
     {
191
-        if (!is_array($compRes))
192
-        {
169
+        if (!is_array($compRes)) {
193 170
             return false;
194 171
         }
195 172
         $result = array('sourceOrphans'=>array(), 'destOrphans'=>array(), 'different'=>array());
196
-        foreach($compRes as $table=>$info)
197
-        {
198
-            if ($info['sourceOrphan'])
199
-            {
173
+        foreach($compRes as $table=>$info) {
174
+            if ($info['sourceOrphan']) {
200 175
                 $result['sourceOrphans'][] = $table;
201
-            }
202
-            elseif ($info['destOrphan'])
203
-            {
176
+            } elseif ($info['destOrphan']) {
204 177
                 $result['destOrphans'][] = $table;
205
-            }
206
-            else
207
-            {
178
+            } else {
208 179
                 $result['different'][] = $table;
209 180
             }
210 181
         }
@@ -239,32 +210,28 @@  discard block
 block discarded – undo
239 210
         $sourceOrphans = array_diff($sourceTabNames, $common);
240 211
         $all = array_unique(array_merge($destTabNames, $sourceTabNames));
241 212
         sort($all);
242
-        foreach ($all as $tab)
243
-        {
213
+        foreach ($all as $tab) {
244 214
             $info = array('destOrphan'=>false, 'sourceOrphan'=>false, 'differs'=>false);
245
-            if(in_array($tab, $destOrphans))
246
-            {
215
+            if(in_array($tab, $destOrphans)) {
247 216
                 $info['destOrphan'] = true;
248
-            }
249
-            elseif (in_array($tab, $sourceOrphans))
250
-            {
217
+            } elseif (in_array($tab, $sourceOrphans)) {
251 218
                 $info['sourceOrphan'] = true;
252
-            }
253
-            else
254
-            {
219
+            } else {
255 220
                 $destSql = $this->getTabSql($this->destStruct, $tab, true);
256 221
                 $sourceSql = $this->getTabSql($this->sourceStruct, $tab, true);
257 222
                 $diffs = $this->compareSql($sourceSql, $destSql);
258
-                if ($diffs===false)
259
-                {
223
+                if ($diffs===false) {
260 224
                     trigger_error('[WARNING] error parsing definition of table "'.$tab.'" - skipped');
261 225
                     continue;
262
-                }
263
-                elseif (!empty($diffs))//not empty array
226
+                } elseif (!empty($diffs)) {
227
+                    //not empty array
264 228
                 {
265 229
                     $info['differs'] = $diffs;
266 230
                 }
267
-                else continue;//empty array
231
+                } else {
232
+                    continue;
233
+                }
234
+                //empty array
268 235
             }
269 236
             $result[$tab] = $info;
270 237
         }
@@ -279,12 +246,13 @@  discard block
 block discarded – undo
279 246
     function getTableList($struct)
280 247
     {
281 248
         $result = array();
282
-        if (preg_match_all('/CREATE(?:\s*TEMPORARY)?\s*TABLE\s*(?:IF NOT EXISTS\s*)?(?:`?(\w+)`?\.)?`?(\w+)`?/i', $struct, $m))
283
-        {
284
-            foreach($m[2] as $match)//m[1] is a database name if any
249
+        if (preg_match_all('/CREATE(?:\s*TEMPORARY)?\s*TABLE\s*(?:IF NOT EXISTS\s*)?(?:`?(\w+)`?\.)?`?(\w+)`?/i', $struct, $m)) {
250
+            foreach($m[2] as $match) {
251
+                //m[1] is a database name if any
285 252
             {
286 253
                 $result[] = $match;
287 254
             }
255
+            }
288 256
         }
289 257
         return $result;
290 258
     }
@@ -302,25 +270,20 @@  discard block
 block discarded – undo
302 270
         $result = '';
303 271
         /* create table should be single line in this case*/
304 272
         //1 - part before database, 2-database name, 3 - part after database
305
-        if (preg_match('/(CREATE(?:\s*TEMPORARY)?\s*TABLE\s*(?:IF NOT EXISTS\s*)?)(?:`?(\w+)`?\.)?(`?('.$tab.')`?(\W|$))/i', $struct, $m, PREG_OFFSET_CAPTURE))
306
-        {
273
+        if (preg_match('/(CREATE(?:\s*TEMPORARY)?\s*TABLE\s*(?:IF NOT EXISTS\s*)?)(?:`?(\w+)`?\.)?(`?('.$tab.')`?(\W|$))/i', $struct, $m, PREG_OFFSET_CAPTURE)) {
307 274
             $tableDef = $m[0][0];
308 275
             $start = $m[0][1];
309 276
             $database = $m[2][0];
310 277
             $offset = $start+strlen($m[0][0]);
311 278
             $end = $this->getDelimPos($struct, $offset);
312
-            if ($end === false)
313
-            {
279
+            if ($end === false) {
314 280
                 $result = substr($struct, $start);
315
-            }
316
-            else
317
-            {
281
+            } else {
318 282
                 $result = substr($struct, $start, $end-$start);//already without ';'
319 283
             }
320 284
         }
321 285
         $result = trim($result);
322
-        if ($database && $removeDatabase)
323
-        {
286
+        if ($database && $removeDatabase) {
324 287
             $result = str_replace($tableDef, $m[1][0].$m[3][0], $result);
325 288
         }
326 289
         return $result;
@@ -335,8 +298,7 @@  discard block
 block discarded – undo
335 298
         $result = array();
336 299
         //find opening bracket, get the prefix along with it
337 300
         $openBracketPos = $this->getDelimPos($sql, 0, '(');
338
-        if ($openBracketPos===false)
339
-        {
301
+        if ($openBracketPos===false) {
340 302
             trigger_error('[WARNING] can not find opening bracket in table definition');
341 303
             return false;
342 304
         }
@@ -344,19 +306,16 @@  discard block
 block discarded – undo
344 306
         $result[] = trim($prefix);
345 307
         $body = substr($sql, strlen($prefix));//fields, indexes and part after closing bracket
346 308
         //split by commas, get part by part
347
-        while(($commaPos = $this->getDelimPos($body, 0, ',', true))!==false)
348
-        {
309
+        while(($commaPos = $this->getDelimPos($body, 0, ',', true))!==false) {
349 310
             $part = trim(substr($body, 0, $commaPos+1));//read another part and shorten $body
350
-            if ($part)
351
-            {
311
+            if ($part) {
352 312
                 $result[] = $part;
353 313
             }
354 314
             $body = substr($body, $commaPos+1);
355 315
         }
356 316
         //here we have last field (or index) definition + part after closing bracket (ENGINE, ect)
357 317
         $closeBracketPos = $this->getDelimRpos($body, 0, ')');
358
-        if ($closeBracketPos===false)
359
-        {
318
+        if ($closeBracketPos===false) {
360 319
             trigger_error('[WARNING] can not find closing bracket in table definition');
361 320
             return false;
362 321
         }
@@ -366,8 +325,7 @@  discard block
 block discarded – undo
366 325
         //get the suffix part along with the closing bracket
367 326
         $suffix = substr($body, $closeBracketPos);
368 327
         $suffix = trim($suffix);
369
-        if ($suffix)
370
-        {
328
+        if ($suffix) {
371 329
             $result[] = $suffix;
372 330
         }
373 331
         return $result;
@@ -390,29 +348,32 @@  discard block
 block discarded – undo
390 348
         $result = array();
391 349
         //split with comma delimiter, not line breaks
392 350
         $sourceParts =  $this->splitTabSql($sourceSql);
393
-        if ($sourceParts===false)//error parsing sql
351
+        if ($sourceParts===false) {
352
+            //error parsing sql
394 353
         {
395 354
             trigger_error('[WARNING] error parsing source sql');
355
+        }
396 356
             return false;
397 357
         }
398 358
         $destParts = $this->splitTabSql($destSql);
399
-        if ($destParts===false)
400
-        {
359
+        if ($destParts===false) {
401 360
             trigger_error('[WARNING] error parsing destination sql');
402 361
             return false;
403 362
         }
404 363
         $sourcePartsIndexed = array();
405 364
         $destPartsIndexed = array();
406
-        foreach($sourceParts as $line)
407
-        {
365
+        foreach($sourceParts as $line) {
408 366
             $lineInfo = $this->processLine($line);
409
-            if (!$lineInfo) continue;
367
+            if (!$lineInfo) {
368
+                continue;
369
+            }
410 370
             $sourcePartsIndexed[$lineInfo['key']] = $lineInfo['line'];
411 371
         }
412
-        foreach($destParts as $line)
413
-        {
372
+        foreach($destParts as $line) {
414 373
             $lineInfo = $this->processLine($line);
415
-            if (!$lineInfo) continue;
374
+            if (!$lineInfo) {
375
+                continue;
376
+            }
416 377
             $destPartsIndexed[$lineInfo['key']] = $lineInfo['line'];
417 378
         }
418 379
         $sourceKeys = array_keys($sourcePartsIndexed);
@@ -420,8 +381,7 @@  discard block
 block discarded – undo
420 381
         $all = array_unique(array_merge($sourceKeys, $destKeys));
421 382
         sort($all);//fields first, then indexes - because fields are prefixed with '!'
422 383
 
423
-        foreach ($all as $key)
424
-        {
384
+        foreach ($all as $key) {
425 385
             $info = array('source'=>'', 'dest'=>'');
426 386
             $inSource= in_array($key, $sourceKeys);
427 387
             $inDest= in_array($key, $destKeys);
@@ -429,20 +389,16 @@  discard block
 block discarded – undo
429 389
             $destOrphan = $inDest && !$inSource;
430 390
             $different =  $inSource && $inDest &&
431 391
             strcasecmp($this->normalizeString($destPartsIndexed[$key]), $this->normalizeString($sourcePartsIndexed[$key]));
432
-            if ($sourceOrphan)
433
-            {
392
+            if ($sourceOrphan) {
434 393
                 $info['source'] = $sourcePartsIndexed[$key];
435
-            }
436
-            elseif ($destOrphan)
437
-            {
394
+            } elseif ($destOrphan) {
438 395
                 $info['dest'] = $destPartsIndexed[$key];
439
-            }
440
-            elseif ($different)
441
-            {
396
+            } elseif ($different) {
442 397
                 $info['source'] = $sourcePartsIndexed[$key];
443 398
                 $info['dest'] = $destPartsIndexed[$key];
399
+            } else {
400
+                continue;
444 401
             }
445
-            else continue;
446 402
             $result[] = $info;
447 403
         }
448 404
         return $result;
@@ -461,34 +417,35 @@  discard block
 block discarded – undo
461 417
         $options = $this->config;
462 418
         $result = array('key'=>'', 'line'=>'');
463 419
         $line = rtrim(trim($line), ',');
464
-        if (preg_match('/^(CREATE\s+TABLE)|(\) ENGINE=)/i', $line))//first or last table definition line
420
+        if (preg_match('/^(CREATE\s+TABLE)|(\) ENGINE=)/i', $line)) {
421
+            //first or last table definition line
465 422
         {
466 423
             return false;
467 424
         }
425
+        }
468 426
         //if (preg_match('/^(PRIMARY KEY)|(((UNIQUE )|(FULLTEXT ))?KEY `?\w+`?)/i', $line, $m))//key definition
469
-        if (preg_match('/^(PRIMARY\s+KEY)|(((UNIQUE\s+)|(FULLTEXT\s+))?KEY\s+`?\w+`?)/i', $line, $m))//key definition
427
+        if (preg_match('/^(PRIMARY\s+KEY)|(((UNIQUE\s+)|(FULLTEXT\s+))?KEY\s+`?\w+`?)/i', $line, $m)) {
428
+            //key definition
470 429
         {
471 430
             $key = $m[0];
472 431
         }
473
-        elseif (preg_match('/^`?\w+`?/i', $line, $m))//field definition
432
+        } elseif (preg_match('/^`?\w+`?/i', $line, $m)) {
433
+            //field definition
474 434
         {
475
-            $key = '!'.$m[0];//to make sure fields will be synchronised before the keys
435
+            $key = '!'.$m[0];
476 436
         }
477
-        else
478
-        {
437
+        //to make sure fields will be synchronised before the keys
438
+        } else {
479 439
             return false;//line has no valuable info (empty or comment)
480 440
         }
481 441
         //$key = str_replace('`', '', $key);
482
-        if (!empty($options['varcharDefaultIgnore']))
483
-        {
442
+        if (!empty($options['varcharDefaultIgnore'])) {
484 443
             $line = preg_replace("/(var)?char\(([0-9]+)\)\s+NOT\s+NULL\s+default\s+''/i", '$1char($2) NOT NULL', $line);
485 444
         }
486
-        if (!empty($options['intDefaultIgnore']))
487
-        {
445
+        if (!empty($options['intDefaultIgnore'])) {
488 446
             $line = preg_replace("/((?:big)|(?:tiny))?int\(([0-9]+)\)\s+NOT\s+NULL\s+default\s+'0'/i", '$1int($2) NOT NULL', $line);
489 447
         }
490
-        if (!empty($options['ignoreIncrement']))
491
-        {
448
+        if (!empty($options['ignoreIncrement'])) {
492 449
             $line = preg_replace("/ AUTO_INCREMENT=[0-9]+/i", '', $line);
493 450
         }
494 451
         $result['key'] = $this->normalizeString($key);
@@ -508,52 +465,42 @@  discard block
 block discarded – undo
508 465
     {
509 466
         $options = $this->config;
510 467
         $sqls = array();
511
-        if (!is_array($diff) || empty($diff))
512
-        {
468
+        if (!is_array($diff) || empty($diff)) {
513 469
             return $sqls;
514 470
         }
515
-        foreach($diff as $tab=>$info)
516
-        {
517
-            if ($info['sourceOrphan'])//delete it
471
+        foreach($diff as $tab=>$info) {
472
+            if ($info['sourceOrphan']) {
473
+                //delete it
518 474
             {
519 475
                 $sqls[] = 'DROP TABLE `'.$tab.'`';
520 476
             }
521
-            elseif ($info['destOrphan'])//create destination table in source
477
+            } elseif ($info['destOrphan']) {
478
+                //create destination table in source
522 479
             {
523 480
                 $database = '';
481
+            }
524 482
                 $destSql = $this->getTabSql($this->destStruct, $tab, $database);
525
-                if (!empty($options['ignoreIncrement']))
526
-                {
483
+                if (!empty($options['ignoreIncrement'])) {
527 484
                     $destSql = preg_replace("/\s*AUTO_INCREMENT=[0-9]+/i", '', $destSql);
528 485
                 }
529
-                if (!empty($options['ingoreIfNotExists']))
530
-                {
486
+                if (!empty($options['ingoreIfNotExists'])) {
531 487
                     $destSql = preg_replace("/IF NOT EXISTS\s*/i", '', $destSql);
532 488
                 }
533
-                if (!empty($options['forceIfNotExists']))
534
-                {
489
+                if (!empty($options['forceIfNotExists'])) {
535 490
                     $destSql = preg_replace('/(CREATE(?:\s*TEMPORARY)?\s*TABLE\s*)(?:IF\sNOT\sEXISTS\s*)?(`?\w+`?)/i', '$1IF NOT EXISTS $2', $destSql);
536 491
                 }
537 492
                 $sqls[] = $destSql;
538
-            }
539
-            else
540
-            {
541
-                foreach($info['differs'] as $finfo)
542
-                {
493
+            } else {
494
+                foreach($info['differs'] as $finfo) {
543 495
                     $inDest = !empty($finfo['dest']);
544 496
                     $inSource = !empty($finfo['source']);
545
-                    if ($inSource && !$inDest)
546
-                    {
497
+                    if ($inSource && !$inDest) {
547 498
                         $sql = $finfo['source'];
548 499
                         $action = 'drop';
549
-                    }
550
-                    elseif ($inDest && !$inSource)
551
-                    {
500
+                    } elseif ($inDest && !$inSource) {
552 501
                         $sql = $finfo['dest'];
553 502
                         $action = 'add';
554
-                    }
555
-                    else
556
-                    {
503
+                    } else {
557 504
                         $sql = $finfo['dest'];
558 505
                         $action = 'modify';
559 506
                     }
@@ -579,65 +526,47 @@  discard block
 block discarded – undo
579 526
         $action = strtolower($action);
580 527
         $keyField = '`?\w`?(?:\(\d+\))?';//matches `name`(10)
581 528
         $keyFieldList = '(?:'.$keyField.'(?:,\s?)?)+';//matches `name`(10),`desc`(255)
582
-        if (preg_match('/((?:PRIMARY )|(?:UNIQUE )|(?:FULLTEXT ))?KEY `?(\w+)?`?\s(\('.$keyFieldList.'\))/i', $sql, $m))
583
-        {   //key and index operations
529
+        if (preg_match('/((?:PRIMARY )|(?:UNIQUE )|(?:FULLTEXT ))?KEY `?(\w+)?`?\s(\('.$keyFieldList.'\))/i', $sql, $m)) {
530
+//key and index operations
584 531
             $type = strtolower(trim($m[1]));
585 532
             $name = trim($m[2]);
586 533
             $fields = trim($m[3]);
587
-            switch($action)
588
-            {
534
+            switch($action) {
589 535
                 case 'drop':
590
-                    if ($type=='primary')
591
-                    {
536
+                    if ($type=='primary') {
592 537
                         $result.= 'DROP PRIMARY KEY';
593
-                    }
594
-                    else
595
-                    {
538
+                    } else {
596 539
                         $result.= 'DROP INDEX `'.$name.'`';
597 540
                     }
598 541
                 break;
599 542
                 case 'add':
600
-                    if ($type=='primary')
601
-                    {
543
+                    if ($type=='primary') {
602 544
                         $result.= 'ADD PRIMARY KEY '.$fields;
603
-                    }
604
-                    elseif ($type=='')
605
-                    {
545
+                    } elseif ($type=='') {
606 546
                         $result.= 'ADD INDEX `'.$name.'` '.$fields;
607
-                    }
608
-                    else
609
-                    {
547
+                    } else {
610 548
                         $result .='ADD '.strtoupper($type).' `'.$name.'` '.$fields;//fulltext or unique
611 549
                     }
612 550
                 break;
613 551
                 case 'modify':
614
-                    if ($type=='primary')
615
-                    {
552
+                    if ($type=='primary') {
616 553
                         $result.='DROP PRIMARY KEY, ADD PRIMARY KEY '.$fields;
617
-                    }
618
-                    elseif ($type=='')
619
-                    {
554
+                    } elseif ($type=='') {
620 555
                         $result.='DROP INDEX `'.$name.'`, ADD INDEX `'.$name.'` '.$fields;
621
-                    }
622
-                    else
623
-                    {
556
+                    } else {
624 557
                         $result.='DROP INDEX `'.$name.'`, ADD '.strtoupper($type).' `'.$name.'` '.$fields;//fulltext or unique
625 558
                     }
626 559
                 break;
627 560
 
628 561
             }
629
-        }
630
-        else //fields operations
562
+        } else //fields operations
631 563
         {
632 564
             $sql = rtrim(trim($sql), ',');
633 565
             $result.= strtoupper($action);
634
-            if ($action=='drop')
635
-            {
566
+            if ($action=='drop') {
636 567
                 $spacePos = strpos($sql, ' ');
637 568
                 $result.= ' '.substr($sql, 0, $spacePos);
638
-            }
639
-            else
640
-            {
569
+            } else {
641 570
                 $result.= ' '.$sql;
642 571
             }
643 572
         }
@@ -657,76 +586,69 @@  discard block
 block discarded – undo
657 586
         $rbs = '\\\\';  //reg - escaped backslash
658 587
         $regPrefix = "(?<!$rbs)(?:$rbs{2})*";
659 588
         $reg = $regPrefix.'("|\')|(/\\*)|(\\*/)|(-- )|(\r\n|\r|\n)|';
660
-        if ($skipInBrackets)
661
-        {
589
+        if ($skipInBrackets) {
662 590
             $reg.='(\(|\))|';
663
-        }
664
-        else
665
-        {
591
+        } else {
666 592
             $reg.='()';
667 593
         }
668 594
         $reg .= '('.preg_quote($delim).')';
669
-        while (preg_match('%'.$reg.'%', $string, $m, PREG_OFFSET_CAPTURE, $offset))
670
-        {
595
+        while (preg_match('%'.$reg.'%', $string, $m, PREG_OFFSET_CAPTURE, $offset)) {
671 596
             $offset = $m[0][1]+strlen($m[0][0]);
672
-            if (end($stack)=='/*')
673
-            {
674
-                if (!empty($m[3][0]))
675
-                {
597
+            if (end($stack)=='/*') {
598
+                if (!empty($m[3][0])) {
676 599
                     array_pop($stack);
677 600
                 }
678 601
                 continue;//here we could also simplify regexp
679 602
             }
680
-            if (end($stack)=='-- ')
681
-            {
682
-                if (!empty($m[5][0]))
683
-                {
603
+            if (end($stack)=='-- ') {
604
+                if (!empty($m[5][0])) {
684 605
                     array_pop($stack);
685 606
                 }
686 607
                 continue;//here we could also simplify regexp
687 608
             }
688 609
 
689
-            if (!empty($m[7][0]))// ';' found
610
+            if (!empty($m[7][0])) {
611
+                // ';' found
690 612
             {
691 613
                 if (empty($stack))
692 614
                 {
693 615
                     return $m[7][1];
694
-                }
695
-                else
696
-                {
616
+            }
617
+                } else {
697 618
                     //var_dump($stack, substr($string, $offset-strlen($m[0][0])));
698 619
                 }
699 620
             }
700
-            if (!empty($m[6][0]))// '(' or ')' found
621
+            if (!empty($m[6][0])) {
622
+                // '(' or ')' found
701 623
             {
702 624
                 if (empty($stack) && $m[6][0]=='(')
703 625
                 {
704 626
                     array_push($stack, $m[6][0]);
705
-                }
706
-                elseif($m[6][0]==')' && end($stack)=='(')
707
-                {
627
+            }
628
+                } elseif($m[6][0]==')' && end($stack)=='(') {
708 629
                     array_pop($stack);
709 630
                 }
710
-            }
711
-            elseif (!empty($m[1][0]))// ' or " found
631
+            } elseif (!empty($m[1][0])) {
632
+                // ' or " found
712 633
             {
713 634
                 if (end($stack)==$m[1][0])
714 635
                 {
715 636
                     array_pop($stack);
716
-                }
717
-                else
718
-                {
637
+            }
638
+                } else {
719 639
                     array_push($stack, $m[1][0]);
720 640
                 }
721
-            }
722
-            elseif (!empty($m[2][0])) // opening comment / *
641
+            } elseif (!empty($m[2][0])) {
642
+                // opening comment / *
723 643
             {
724 644
                 array_push($stack, $m[2][0]);
725 645
             }
726
-            elseif (!empty($m[4][0])) // opening comment --
646
+            } elseif (!empty($m[4][0])) {
647
+                // opening comment --
727 648
             {
728 649
                 array_push($stack, $m[4][0]);
729 650
             }
651
+            }
730 652
         }
731 653
         return false;
732 654
     }
@@ -738,15 +660,12 @@  discard block
 block discarded – undo
738 660
     function getDelimRpos($string, $offset=0, $delim=';', $skipInBrackets=false)
739 661
     {
740 662
         $pos = $this->getDelimPos($string, $offset, $delim, $skipInBrackets);
741
-        if ($pos===false)
742
-        {
663
+        if ($pos===false) {
743 664
             return false;
744 665
         }
745
-        do
746
-        {
666
+        do {
747 667
             $newPos=$this->getDelimPos($string, $pos+1, $delim, $skipInBrackets);
748
-            if ($newPos !== false)
749
-            {
668
+            if ($newPos !== false) {
750 669
                 $pos = $newPos;
751 670
             }
752 671
         }
Please login to merge, or discard this patch.
htdocs/okapi/views/update.php 4 patches
Doc Comments   +2 added lines patch added patch discarded remove patch
@@ -150,6 +150,8 @@
 block discarded – undo
150 150
      * Return the list of email addresses of developers who used any of the given
151 151
      * method names at least once. If $days is not null, then only consumers which
152 152
      * used the method in last X $days will be returned.
153
+     * @param string[] $service_names
154
+     * @param integer $days
153 155
      */
154 156
     public static function get_consumers_of($service_names, $days = null)
155 157
     {
Please login to merge, or discard this patch.
Unused Use Statements   +2 added lines, -10 removed lines patch added patch discarded remove patch
@@ -3,19 +3,11 @@
 block discarded – undo
3 3
 namespace okapi\views\update;
4 4
 
5 5
 use Exception;
6
-
7
-use okapi\Okapi;
8 6
 use okapi\Cache;
9 7
 use okapi\Db;
10
-use okapi\OkapiRequest;
11
-use okapi\OkapiRedirectResponse;
12
-use okapi\OkapiHttpResponse;
13
-use okapi\ParamMissing;
14
-use okapi\InvalidParam;
15
-use okapi\OkapiServiceRunner;
16
-use okapi\OkapiInternalRequest;
17
-use okapi\Settings;
8
+use okapi\Okapi;
18 9
 use okapi\OkapiLock;
10
+use okapi\Settings;
19 11
 use okapi\cronjobs\CronJobController;
20 12
 use okapi\services\replicate\ReplicateCommon;
21 13
 
Please login to merge, or discard this patch.
Spacing   +5 added lines, -5 removed lines patch added patch discarded remove patch
@@ -609,9 +609,9 @@  discard block
 block discarded – undo
609 609
     {
610 610
         # Remove unused locks (these might have been created in previous versions of OKAPI).
611 611
 
612
-        for ($z=0; $z<=2; $z++)
613
-            for ($x=0; $x<(1<<$z); $x++)
614
-                for ($y=0; $y<(1<<$z); $y++)
612
+        for ($z = 0; $z <= 2; $z++)
613
+            for ($x = 0; $x < (1 << $z); $x++)
614
+                for ($y = 0; $y < (1 << $z); $y++)
615 615
                 {
616 616
                     $lockname = "tile-computation-$z-$x-$y";
617 617
                     if (OkapiLock::exists($lockname))
@@ -623,7 +623,7 @@  discard block
 block discarded – undo
623 623
     {
624 624
         # Once again, remove unused locks.
625 625
 
626
-        for ($z=0; $z<=21; $z++)
626
+        for ($z = 0; $z <= 21; $z++)
627 627
         {
628 628
             foreach (array("", "-0", "-1") as $suffix)
629 629
             {
@@ -701,7 +701,7 @@  discard block
 block discarded – undo
701 701
         require_once($GLOBALS['rootpath']."okapi/services/replicate/replicate_common.inc.php");
702 702
         $new_geocache_fields = array(
703 703
             'attr_acodes', 'willattends', 'country', 'state', 'preview_image',
704
-            'trip_time', 'trip_distance', 'gc_code',  'hints2', 'protection_areas'
704
+            'trip_time', 'trip_distance', 'gc_code', 'hints2', 'protection_areas'
705 705
         );
706 706
         ReplicateCommon::verify_clog_consistency(true, $new_geocache_fields);
707 707
     }
Please login to merge, or discard this patch.
Braces   +217 added lines, -121 removed lines patch added patch discarded remove patch
@@ -25,14 +25,12 @@  discard block
 block discarded – undo
25 25
 {
26 26
     public static function get_current_version()
27 27
     {
28
-        try
29
-        {
28
+        try {
30 29
             return Okapi::get_var('db_version', 0) + 0;
31
-        }
32
-        catch (Exception $e)
33
-        {
34
-            if (strpos($e->getMessage(), "okapi_vars' doesn't exist") !== false)
35
-                return 0;
30
+        } catch (Exception $e) {
31
+            if (strpos($e->getMessage(), "okapi_vars' doesn't exist") !== false) {
32
+                            return 0;
33
+            }
36 34
             throw $e;
37 35
         }
38 36
     }
@@ -40,13 +38,12 @@  discard block
 block discarded – undo
40 38
     public static function get_max_version()
41 39
     {
42 40
         $max_db_version = 0;
43
-        foreach (get_class_methods(__CLASS__) as $name)
44
-        {
45
-            if (strpos($name, "ver") === 0)
46
-            {
41
+        foreach (get_class_methods(__CLASS__) as $name) {
42
+            if (strpos($name, "ver") === 0) {
47 43
                 $ver = substr($name, 3) + 0;
48
-                if ($ver > $max_db_version)
49
-                    $max_db_version = $ver;
44
+                if ($ver > $max_db_version) {
45
+                                    $max_db_version = $ver;
46
+                }
50 47
             }
51 48
         }
52 49
         return $max_db_version;
@@ -67,13 +64,10 @@  discard block
 block discarded – undo
67 64
         $lock = OkapiLock::get('db-update');
68 65
         $lock->acquire();
69 66
 
70
-        try
71
-        {
67
+        try {
72 68
             self::_call();
73 69
             $lock->release();
74
-        }
75
-        catch (Exception $e)
76
-        {
70
+        } catch (Exception $e) {
77 71
             # Error occured. Make sure the lock is released and rethrow.
78 72
 
79 73
             $lock->release();
@@ -91,16 +85,12 @@  discard block
 block discarded – undo
91 85
         $current_ver = self::get_current_version();
92 86
         $max_ver = self::get_max_version();
93 87
         self::out("Current OKAPI database version: $current_ver\n");
94
-        if ($current_ver == 0 && ((!isset($_GET['install'])) || ($_GET['install'] != 'true')))
95
-        {
88
+        if ($current_ver == 0 && ((!isset($_GET['install'])) || ($_GET['install'] != 'true'))) {
96 89
             self::out("Current OKAPI settings are:\n\n".Settings::describe_settings()."\n\n".
97 90
                 "Make sure they are correct, then append '?install=true' to your query.");
98
-            try
99
-            {
91
+            try {
100 92
                 Db::select_value("select 1 from caches limit 1");
101
-            }
102
-            catch (Exception $e)
103
-            {
93
+            } catch (Exception $e) {
104 94
                 self::out(
105 95
                     "\n\n".
106 96
                     "IMPORTANT: If you're trying to install OKAPI on an empty database then\n".
@@ -110,19 +100,14 @@  discard block
 block discarded – undo
110 100
                 );
111 101
             }
112 102
             return;
113
-        }
114
-        elseif ($max_ver == $current_ver)
115
-        {
103
+        } elseif ($max_ver == $current_ver) {
116 104
             self::out("It is up-to-date.\n\n");
117
-        }
118
-        elseif ($max_ver < $current_ver)
119
-            throw new Exception();
120
-        else
121
-        {
105
+        } elseif ($max_ver < $current_ver) {
106
+                    throw new Exception();
107
+        } else {
122 108
             self::out("Updating to version $max_ver... PLEASE WAIT\n\n");
123 109
 
124
-            while ($current_ver < $max_ver)
125
-            {
110
+            while ($current_ver < $max_ver) {
126 111
                 $version_to_apply = $current_ver + 1;
127 112
                 self::out("Applying mutation #$version_to_apply...");
128 113
                 try {
@@ -280,29 +265,73 @@  discard block
 block discarded – undo
280 265
         ");
281 266
     }
282 267
 
283
-    private static function ver9() { Db::execute("alter table okapi_consumers modify column `key` varchar(20) not null"); }
284
-    private static function ver10() { Db::execute("alter table okapi_consumers modify column secret varchar(40) not null"); }
285
-    private static function ver11() { Db::execute("alter table okapi_tokens modify column `key` varchar(20) not null"); }
286
-    private static function ver12() { Db::execute("alter table okapi_tokens modify column secret varchar(40) not null"); }
287
-    private static function ver13() { Db::execute("alter table okapi_tokens modify column consumer_key varchar(20) not null"); }
288
-    private static function ver14() { Db::execute("alter table okapi_tokens modify column verifier varchar(10) default null"); }
289
-    private static function ver15() { Db::execute("alter table okapi_authorizations modify column consumer_key varchar(20) not null"); }
290
-    private static function ver16() { Db::execute("alter table okapi_nonces modify column consumer_key varchar(20) not null"); }
291
-    private static function ver17() { Db::execute("alter table okapi_nonces modify column `key` varchar(255) not null"); }
292
-    private static function ver18() { Db::execute("alter table okapi_cache_logs modify column consumer_key varchar(20) not null"); }
293
-    private static function ver19() { Db::execute("alter table okapi_vars modify column `var` varchar(32) not null"); }
294
-
295
-    private static function ver20() { Db::execute("alter table okapi_consumers modify column `key` varchar(20) collate utf8_bin not null"); }
296
-    private static function ver21() { Db::execute("alter table okapi_consumers modify column secret varchar(40) collate utf8_bin not null"); }
297
-    private static function ver22() { Db::execute("alter table okapi_tokens modify column `key` varchar(20) collate utf8_bin not null"); }
298
-    private static function ver23() { Db::execute("alter table okapi_tokens modify column secret varchar(40) collate utf8_bin not null"); }
299
-    private static function ver24() { Db::execute("alter table okapi_tokens modify column consumer_key varchar(20) collate utf8_bin not null"); }
300
-    private static function ver25() { Db::execute("alter table okapi_tokens modify column verifier varchar(10) collate utf8_bin default null"); }
301
-    private static function ver26() { Db::execute("alter table okapi_authorizations modify column consumer_key varchar(20) collate utf8_bin not null"); }
302
-    private static function ver27() { Db::execute("alter table okapi_nonces modify column consumer_key varchar(20) collate utf8_bin not null"); }
303
-    private static function ver28() { Db::execute("alter table okapi_nonces modify column `key` varchar(255) collate utf8_bin not null"); }
304
-    private static function ver29() { Db::execute("alter table okapi_cache_logs modify column consumer_key varchar(20) collate utf8_bin not null"); }
305
-    private static function ver30() { Db::execute("alter table okapi_vars modify column `var` varchar(32) collate utf8_bin not null"); }
268
+    private static function ver9()
269
+    {
270
+Db::execute("alter table okapi_consumers modify column `key` varchar(20) not null"); }
271
+    private static function ver10()
272
+    {
273
+Db::execute("alter table okapi_consumers modify column secret varchar(40) not null"); }
274
+    private static function ver11()
275
+    {
276
+Db::execute("alter table okapi_tokens modify column `key` varchar(20) not null"); }
277
+    private static function ver12()
278
+    {
279
+Db::execute("alter table okapi_tokens modify column secret varchar(40) not null"); }
280
+    private static function ver13()
281
+    {
282
+Db::execute("alter table okapi_tokens modify column consumer_key varchar(20) not null"); }
283
+    private static function ver14()
284
+    {
285
+Db::execute("alter table okapi_tokens modify column verifier varchar(10) default null"); }
286
+    private static function ver15()
287
+    {
288
+Db::execute("alter table okapi_authorizations modify column consumer_key varchar(20) not null"); }
289
+    private static function ver16()
290
+    {
291
+Db::execute("alter table okapi_nonces modify column consumer_key varchar(20) not null"); }
292
+    private static function ver17()
293
+    {
294
+Db::execute("alter table okapi_nonces modify column `key` varchar(255) not null"); }
295
+    private static function ver18()
296
+    {
297
+Db::execute("alter table okapi_cache_logs modify column consumer_key varchar(20) not null"); }
298
+    private static function ver19()
299
+    {
300
+Db::execute("alter table okapi_vars modify column `var` varchar(32) not null"); }
301
+
302
+    private static function ver20()
303
+    {
304
+Db::execute("alter table okapi_consumers modify column `key` varchar(20) collate utf8_bin not null"); }
305
+    private static function ver21()
306
+    {
307
+Db::execute("alter table okapi_consumers modify column secret varchar(40) collate utf8_bin not null"); }
308
+    private static function ver22()
309
+    {
310
+Db::execute("alter table okapi_tokens modify column `key` varchar(20) collate utf8_bin not null"); }
311
+    private static function ver23()
312
+    {
313
+Db::execute("alter table okapi_tokens modify column secret varchar(40) collate utf8_bin not null"); }
314
+    private static function ver24()
315
+    {
316
+Db::execute("alter table okapi_tokens modify column consumer_key varchar(20) collate utf8_bin not null"); }
317
+    private static function ver25()
318
+    {
319
+Db::execute("alter table okapi_tokens modify column verifier varchar(10) collate utf8_bin default null"); }
320
+    private static function ver26()
321
+    {
322
+Db::execute("alter table okapi_authorizations modify column consumer_key varchar(20) collate utf8_bin not null"); }
323
+    private static function ver27()
324
+    {
325
+Db::execute("alter table okapi_nonces modify column consumer_key varchar(20) collate utf8_bin not null"); }
326
+    private static function ver28()
327
+    {
328
+Db::execute("alter table okapi_nonces modify column `key` varchar(255) collate utf8_bin not null"); }
329
+    private static function ver29()
330
+    {
331
+Db::execute("alter table okapi_cache_logs modify column consumer_key varchar(20) collate utf8_bin not null"); }
332
+    private static function ver30()
333
+    {
334
+Db::execute("alter table okapi_vars modify column `var` varchar(32) collate utf8_bin not null"); }
306 335
 
307 336
     private static function ver31()
308 337
     {
@@ -337,12 +366,9 @@  discard block
 block discarded – undo
337 366
 
338 367
     private static function ver33()
339 368
     {
340
-        try
341
-        {
369
+        try {
342 370
             Db::execute("alter table cache_logs add key `uuid` (`uuid`)");
343
-        }
344
-        catch (Exception $e)
345
-        {
371
+        } catch (Exception $e) {
346 372
             // key exists
347 373
         }
348 374
     }
@@ -373,11 +399,21 @@  discard block
 block discarded – undo
373 399
         );
374 400
     }
375 401
 
376
-    private static function ver36() { Db::execute("alter table okapi_cache modify column `key` varchar(64) not null"); }
377
-    private static function ver37() { Db::execute("delete from okapi_vars where var='last_clog_update'"); }
378
-    private static function ver38() { Db::execute("alter table okapi_clog modify column data mediumblob"); }
379
-    private static function ver39() { Db::execute("delete from okapi_clog"); }
380
-    private static function ver40() { Db::execute("alter table okapi_cache modify column value mediumblob"); }
402
+    private static function ver36()
403
+    {
404
+Db::execute("alter table okapi_cache modify column `key` varchar(64) not null"); }
405
+    private static function ver37()
406
+    {
407
+Db::execute("delete from okapi_vars where var='last_clog_update'"); }
408
+    private static function ver38()
409
+    {
410
+Db::execute("alter table okapi_clog modify column data mediumblob"); }
411
+    private static function ver39()
412
+    {
413
+Db::execute("delete from okapi_clog"); }
414
+    private static function ver40()
415
+    {
416
+Db::execute("alter table okapi_cache modify column value mediumblob"); }
381 417
 
382 418
     private static function ver41()
383 419
     {
@@ -389,7 +425,9 @@  discard block
 block discarded – undo
389 425
         Cache::delete('cron_schedule');
390 426
     }
391 427
 
392
-    private static function ver42() { Db::execute("delete from okapi_cache where length(value) = 65535"); }
428
+    private static function ver42()
429
+    {
430
+Db::execute("delete from okapi_cache where length(value) = 65535"); }
393 431
 
394 432
     private static function ver43()
395 433
     {
@@ -408,9 +446,15 @@  discard block
 block discarded – undo
408 446
         Okapi::mail_from_okapi($emails, "A change in the 'replicate' module.", ob_get_clean());
409 447
     }
410 448
 
411
-    private static function ver44() { Db::execute("alter table caches add column okapi_syncbase timestamp not null after last_modified;"); }
412
-    private static function ver45() { Db::execute("update caches set okapi_syncbase=last_modified;"); }
413
-    private static function ver46() { /* no longer necessary */ }
449
+    private static function ver44()
450
+    {
451
+Db::execute("alter table caches add column okapi_syncbase timestamp not null after last_modified;"); }
452
+    private static function ver45()
453
+    {
454
+Db::execute("update caches set okapi_syncbase=last_modified;"); }
455
+    private static function ver46()
456
+    {
457
+/* no longer necessary */ }
414 458
 
415 459
     private static function ver47()
416 460
     {
@@ -451,8 +495,12 @@  discard block
 block discarded – undo
451 495
         print "on this procedure, please submit them to our issue tracker.\n\n";
452 496
     }
453 497
 
454
-    private static function ver49() { Db::execute("alter table caches add key okapi_syncbase (okapi_syncbase);"); }
455
-    private static function ver50() { /* no longer necessary */ }
498
+    private static function ver49()
499
+    {
500
+Db::execute("alter table caches add key okapi_syncbase (okapi_syncbase);"); }
501
+    private static function ver50()
502
+    {
503
+/* no longer necessary */ }
456 504
 
457 505
     private static function ver51()
458 506
     {
@@ -468,13 +516,16 @@  discard block
 block discarded – undo
468 516
         # It doesn't do that anymore. Instead, it adds a separate column for itself (okapi_syncbase).
469 517
     }
470 518
 
471
-    private static function ver53() { Db::execute("alter table cache_logs add column okapi_syncbase timestamp not null after last_modified;"); }
472
-    private static function ver54() { Db::execute("update cache_logs set okapi_syncbase=last_modified;"); }
519
+    private static function ver53()
520
+    {
521
+Db::execute("alter table cache_logs add column okapi_syncbase timestamp not null after last_modified;"); }
522
+    private static function ver54()
523
+    {
524
+Db::execute("update cache_logs set okapi_syncbase=last_modified;"); }
473 525
 
474 526
     private static function ver55()
475 527
     {
476
-        if (Settings::get('OC_BRANCH') == 'oc.pl')
477
-        {
528
+        if (Settings::get('OC_BRANCH') == 'oc.pl') {
478 529
             # OCPL does not have cache_logs_archived table.
479 530
             return;
480 531
         }
@@ -483,8 +534,7 @@  discard block
 block discarded – undo
483 534
 
484 535
     private static function ver56()
485 536
     {
486
-        if (Settings::get('OC_BRANCH') == 'oc.pl')
487
-        {
537
+        if (Settings::get('OC_BRANCH') == 'oc.pl') {
488 538
             # OCPL does not have cache_logs_archived table.
489 539
             return;
490 540
         }
@@ -544,13 +594,11 @@  discard block
 block discarded – undo
544 594
         #
545 595
         $row = Db::select_row("show create table cache_logs");
546 596
         $stmt = $row["Create Table"];
547
-        if (strpos($stmt, "timestamp NOT NULL DEFAULT '0000-00-00 00:00:00'") > 0)
548
-        {
597
+        if (strpos($stmt, "timestamp NOT NULL DEFAULT '0000-00-00 00:00:00'") > 0) {
549 598
             Db::execute("alter table cache_logs modify column last_modified datetime not null;");
550 599
             Db::execute("alter table cache_logs modify column okapi_syncbase timestamp not null;");
551 600
             Db::execute("update cache_logs set okapi_syncbase=now() where okapi_syncbase='0000-00-00 00:00:00';");
552
-            if (Settings::get('OC_BRANCH') == 'oc.de')
553
-            {
601
+            if (Settings::get('OC_BRANCH') == 'oc.de') {
554 602
                 Db::execute("alter table cache_logs_archived modify column last_modified datetime not null;");
555 603
                 Db::execute("alter table cache_logs_archived modify column okapi_syncbase timestamp not null;");
556 604
                 Db::execute("update cache_logs_archived set okapi_syncbase=now() where okapi_syncbase='0000-00-00 00:00:00';");
@@ -558,12 +606,13 @@  discard block
 block discarded – undo
558 606
         }
559 607
     }
560 608
 
561
-    private static function ver61() { Db::execute("alter table cache_logs add key okapi_syncbase (okapi_syncbase);"); }
609
+    private static function ver61()
610
+    {
611
+Db::execute("alter table cache_logs add key okapi_syncbase (okapi_syncbase);"); }
562 612
 
563 613
     private static function ver62()
564 614
     {
565
-        if (Settings::get('OC_BRANCH') == 'oc.pl')
566
-        {
615
+        if (Settings::get('OC_BRANCH') == 'oc.pl') {
567 616
             # OCPL does not have cache_logs_archived table.
568 617
             return;
569 618
         }
@@ -602,20 +651,28 @@  discard block
 block discarded – undo
602 651
         ");
603 652
     }
604 653
 
605
-    private static function ver65() { Db::execute("alter table okapi_tile_status engine=innodb;"); }
606
-    private static function ver66() { Db::execute("alter table okapi_tile_caches engine=innodb;"); }
654
+    private static function ver65()
655
+    {
656
+Db::execute("alter table okapi_tile_status engine=innodb;"); }
657
+    private static function ver66()
658
+    {
659
+Db::execute("alter table okapi_tile_caches engine=innodb;"); }
607 660
 
608 661
     private static function ver67()
609 662
     {
610 663
         # Remove unused locks (these might have been created in previous versions of OKAPI).
611 664
 
612
-        for ($z=0; $z<=2; $z++)
613
-            for ($x=0; $x<(1<<$z); $x++)
614
-                for ($y=0; $y<(1<<$z); $y++)
615
-                {
665
+        for ($z=0; $z<=2; $z++) {
666
+                    for ($x=0;
667
+        }
668
+        $x<(1<<$z); $x++) {
669
+                            for ($y=0;
670
+            }
671
+            $y<(1<<$z); $y++) {
616 672
                     $lockname = "tile-computation-$z-$x-$y";
617
-                    if (OkapiLock::exists($lockname))
618
-                        OkapiLock::get($lockname)->remove();
673
+                    if (OkapiLock::exists($lockname)) {
674
+                                            OkapiLock::get($lockname)->remove();
675
+                    }
619 676
                 }
620 677
     }
621 678
 
@@ -623,13 +680,12 @@  discard block
 block discarded – undo
623 680
     {
624 681
         # Once again, remove unused locks.
625 682
 
626
-        for ($z=0; $z<=21; $z++)
627
-        {
628
-            foreach (array("", "-0", "-1") as $suffix)
629
-            {
683
+        for ($z=0; $z<=21; $z++) {
684
+            foreach (array("", "-0", "-1") as $suffix) {
630 685
                 $lockname = "tile-$z$suffix";
631
-                if (OkapiLock::exists($lockname))
632
-                    OkapiLock::get($lockname)->remove();
686
+                if (OkapiLock::exists($lockname)) {
687
+                                    OkapiLock::get($lockname)->remove();
688
+                }
633 689
             }
634 690
         }
635 691
     }
@@ -652,12 +708,24 @@  discard block
 block discarded – undo
652 708
         ");
653 709
     }
654 710
 
655
-    private static function ver71() { Db::execute("alter table okapi_cache add column score float(4,2) default null after `key`"); }
656
-    private static function ver72() { Db::execute("alter table okapi_cache change column expires expires datetime after score"); }
657
-    private static function ver73() { Db::execute("update okapi_cache set score=1, expires=date_add(now(), interval 360 day) where `key` like 'tile/%'"); }
658
-    private static function ver74() { Db::execute("update okapi_cache set score=1, expires=date_add(now(), interval 360 day) where `key` like 'tilecaption/%'"); }
659
-    private static function ver75() { Db::execute("alter table okapi_cache modify column score float default null"); }
660
-    private static function ver76() { Db::execute("update okapi_cache set expires=date_add(now(), interval 100 year) where `key` like 'clog#geocache#%'"); }
711
+    private static function ver71()
712
+    {
713
+Db::execute("alter table okapi_cache add column score float(4,2) default null after `key`"); }
714
+    private static function ver72()
715
+    {
716
+Db::execute("alter table okapi_cache change column expires expires datetime after score"); }
717
+    private static function ver73()
718
+    {
719
+Db::execute("update okapi_cache set score=1, expires=date_add(now(), interval 360 day) where `key` like 'tile/%'"); }
720
+    private static function ver74()
721
+    {
722
+Db::execute("update okapi_cache set score=1, expires=date_add(now(), interval 360 day) where `key` like 'tilecaption/%'"); }
723
+    private static function ver75()
724
+    {
725
+Db::execute("alter table okapi_cache modify column score float default null"); }
726
+    private static function ver76()
727
+    {
728
+Db::execute("update okapi_cache set expires=date_add(now(), interval 100 year) where `key` like 'clog#geocache#%'"); }
661 729
 
662 730
     private static function ver77()
663 731
     {
@@ -682,16 +750,36 @@  discard block
 block discarded – undo
682 750
         ");
683 751
     }
684 752
 
685
-    private static function ver79() { Db::execute("alter table okapi_search_results engine=MyISAM"); }
686
-    private static function ver80() { Db::execute("alter table okapi_search_sets add column date_created datetime not null"); }
687
-    private static function ver81() { Db::execute("alter table okapi_search_sets add column expires datetime not null"); }
688
-    private static function ver82() { CronJobController::reset_job_schedule("FulldumpGeneratorJob"); }
689
-    private static function ver83() { Db::execute("alter table okapi_stats_temp engine=InnoDB"); }
690
-    private static function ver84() { Db::execute("truncate okapi_nonces;"); }
691
-    private static function ver85() { Db::execute("alter table okapi_nonces drop primary key;"); }
692
-    private static function ver86() { Db::execute("alter table okapi_nonces change column `key` nonce_hash varchar(32) character set utf8 collate utf8_bin not null;"); }
693
-    private static function ver87() { Db::execute("alter table okapi_nonces add primary key (consumer_key, nonce_hash);"); }
694
-    private static function ver88() { Db::execute("alter table okapi_consumers add column admin tinyint not null default 0;"); }
753
+    private static function ver79()
754
+    {
755
+Db::execute("alter table okapi_search_results engine=MyISAM"); }
756
+    private static function ver80()
757
+    {
758
+Db::execute("alter table okapi_search_sets add column date_created datetime not null"); }
759
+    private static function ver81()
760
+    {
761
+Db::execute("alter table okapi_search_sets add column expires datetime not null"); }
762
+    private static function ver82()
763
+    {
764
+CronJobController::reset_job_schedule("FulldumpGeneratorJob"); }
765
+    private static function ver83()
766
+    {
767
+Db::execute("alter table okapi_stats_temp engine=InnoDB"); }
768
+    private static function ver84()
769
+    {
770
+Db::execute("truncate okapi_nonces;"); }
771
+    private static function ver85()
772
+    {
773
+Db::execute("alter table okapi_nonces drop primary key;"); }
774
+    private static function ver86()
775
+    {
776
+Db::execute("alter table okapi_nonces change column `key` nonce_hash varchar(32) character set utf8 collate utf8_bin not null;"); }
777
+    private static function ver87()
778
+    {
779
+Db::execute("alter table okapi_nonces add primary key (consumer_key, nonce_hash);"); }
780
+    private static function ver88()
781
+    {
782
+Db::execute("alter table okapi_consumers add column admin tinyint not null default 0;"); }
695 783
 
696 784
     private static function ver89()
697 785
     {
@@ -706,10 +794,18 @@  discard block
 block discarded – undo
706 794
         ReplicateCommon::verify_clog_consistency(true, $new_geocache_fields);
707 795
     }
708 796
 
709
-    private static function ver90() { Db::execute("alter table okapi_consumers change column admin bflags tinyint not null default 0;"); }
710
-    private static function ver91() { Db::execute("delete from okapi_tile_status"); }
711
-    private static function ver92() { Db::execute("delete from okapi_tile_caches"); }
712
-    private static function ver93() { Db::execute("alter table okapi_tile_caches add column name_crc int(10) unsigned not null default 0;"); }
797
+    private static function ver90()
798
+    {
799
+Db::execute("alter table okapi_consumers change column admin bflags tinyint not null default 0;"); }
800
+    private static function ver91()
801
+    {
802
+Db::execute("delete from okapi_tile_status"); }
803
+    private static function ver92()
804
+    {
805
+Db::execute("delete from okapi_tile_caches"); }
806
+    private static function ver93()
807
+    {
808
+Db::execute("alter table okapi_tile_caches add column name_crc int(10) unsigned not null default 0;"); }
713 809
 
714 810
     private static function ver94()
715 811
     {
Please login to merge, or discard this patch.