Passed
Push — development ( ab8e1f...ba4819 )
by Thomas
06:45
created

htdocs/search.php (1 issue)

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

1
<?php
2
/***************************************************************************
3
 * For license information see doc/license.txt
4
 *
5
 *
6
 * This module handles everything which results in the output of a list of
7
 * caches, including output formatting. It also handles search requests from
8
 * external tools like the Mozilla Firefox plugin.
9
 *
10
 * Search options will be loaded from
11
 * - a saved query in queries table, if either 'queryid' parameter or
12
 * 'lastqueryid' cookie is present and the query exists; otherwise from
13
 * - supplied HTTP parameters or
14
 * - hard-coded default values
15
 *
16
 * showresult=1 produces an SQL query from search options, executes it and
17
 * calls the output formatting module as specified by the 'output' parameter.
18
 * If 'showresult' != 1, the search options form is presented to the user.
19
 *
20
 * Note that 'showresult' is also stored in saved queries, so it can be
21
 * automatically included when the 'queryid' parameter is given.
22
 *
23
 * search type options:
24
 *    searchbyplz (obsolete => mapped to searchbyortplz)
25
 *    searchbyort (obsolete => mapped to searchbyortplz)
26
 *    searchbyortplz
27
 *    searchbywaypoint
28
 *    searchbydistance (obsolete => mapped to searchbycoords)
29
 *    searchbycoords
30
 *    searchbyname
31
 *    searchbyowner
32
 *    searchbyfinder
33
 *    searchbyfulltext
34
 *    searchbynofilter
35
 *    searchbycacheid
36
 *    searchbywp
37
 *    searchbylist
38
 *    searchall  (needs login)
39
 *
40
 * output options:
41
 * html         display browsable search results list
42
 * xml          undocumented - very old API
43
 * txt          plain-text cache listing, zipped if more than one cache
44
 * map2         internally used for map display and filtering
45
 *
46
 * gpx          common geocache data files
47
 * loc
48
 * ovl
49
 * ov2
50
 * kml
51
 *
52
 *
53
 * To do:
54
 * - port attributes code to res_attribgroup.tpl (see outputSearchForm)
55
 * - move output data list generation from prepareLocSelectionForm and
56
 * outputLocidSelectionForm to search_selectlocid.tpl.
57
 * - wtf is "expert mode"?
58
 ****************************************************************************/
59
60
require __DIR__ . '/lib2/web.inc.php';
61
require __DIR__ . '/lib2/logic/data-license.inc.php';
62
require __DIR__ . '/lib2/search/search.inc.php';
63
require __DIR__ . '/templates2/' . $opt['template']['style'] . '/search.tpl.inc.php';
64
65
66
//=========================================================
67
//  1. initialize searching and template variables
68
//=========================================================
69
70
$tpl->name = 'search';
71
$tpl->menuitem = MNU_CACHES_SEARCH;
72
73
// distance constants
74
define('DEFAULT_DISTANCE_UNIT', 'km');
75
define('DEFAULT_SEARCH_DISTANCE', 75);
76
77
$multiplier['km'] = 1;
78
$multiplier['sm'] = 0.62137;
79
$multiplier['nm'] = 0.53996;
80
81
$homecoords = ($login->logged_in() &&
82
    sql_value_slave("SELECT `latitude`+`longitude` FROM user WHERE `user_id`='&1'", 0, $login->userid) <> 0);
83
84
// Determine if search.php was called by a search function ('Caches' menu,
85
// stored query etc.) or for other purpose (e.g. user profile cache lists):
86
$called_by_search = isset($_REQUEST['calledbysearch']) ? $_REQUEST['calledbysearch'] <> 0 : true;
87
$called_by_profile_query = false;
88
$load_query = false;
89
$show_lastsearchbutton = true;
90
91
if (isset($_REQUEST['queryid']) || isset($_REQUEST['showresult'])) {  // Ocprop: showresult, queryid
92
    $bCookieQueryid = false;
93
    $load_query = true;
94
    $queryid = isset($_REQUEST['queryid']) ? $_REQUEST['queryid'] : 0;
95
    if ($queryid &&
96
        sql_value("SELECT `user_id` FROM `queries` WHERE `id`='&1'", 0, $queryid)
97
    ) {
98
        $called_by_profile_query = true;
99
    }
100
} else {
101
    $bCookieQueryid = true;
102
    $load_query = true;
103
    $queryid = $cookie->get('lastqueryid', false);
104
    if ($queryid === false ||
105
        sql_value("SELECT COUNT(*) FROM `queries` WHERE id='&1'", 0, $queryid) == 0
106
    ) {
107
        $show_lastsearchbutton = false;
108
    }
109
    if (!isset($_REQUEST['lastsearch'])) {
110
        $queryid = 0;
111
    }
112
    if ($queryid === false ||
113
        sql_value("SELECT COUNT(*) FROM `queries` WHERE id='&1'", 0, $queryid) == 0
114
    ) {
115
        $queryid = 0;
116
        $load_query = false;
117
    }
118
119
    newquery:
120
    if ($queryid == 0) {
121
        $load_query = false;
122
        // initialize search form with defaults, as we have no parameters
123
        // or saved query to start from
124
125
        $_REQUEST['cache_attribs'] = '';
126
        $rs = sql("SELECT `id` FROM `cache_attrib` WHERE `default`=1 AND NOT IFNULL(`hidden`, 0)=1");
127 View Code Duplication
        while ($r = sql_fetch_assoc($rs)) {
128
            if ($_REQUEST['cache_attribs'] != '') {
129
                $_REQUEST['cache_attribs'] .= ';';
130
            }
131
            $_REQUEST['cache_attribs'] .= $r['id'];
132
        }
133
        sql_free_result($rs);
134
135
        $_REQUEST['cache_attribs_not'] = '';
136
        $rs = sql("SELECT `id` FROM `cache_attrib` WHERE `default`=2 AND NOT IFNULL(`hidden`, 0)=1");
137 View Code Duplication
        while ($r = sql_fetch_assoc($rs)) {
138
            if ($_REQUEST['cache_attribs_not'] != '') {
139
                $_REQUEST['cache_attribs_not'] .= ';';
140
            }
141
            $_REQUEST['cache_attribs_not'] .= $r['id'];
142
        }
143
        sql_free_result($rs);
144
    }
145
}
146
147
$queryid += 0; // safety measure: force $queryid to be numeric
148
149
150
//=========================================================
151
//  2. Build search options ($options) array
152
//=========================================================
153
154
if ($queryid != 0) {
155
    // load search options from stored query
156
157
    $query_rs = sql(
158
        "SELECT `user_id`, `options`, `name`
159
         FROM `queries`
160
         WHERE id='&1' AND (`user_id`=0 OR `user_id`='&2')",
161
        $queryid,
162
        $login->userid
163
    );
164
165
    if (sql_num_rows($query_rs) == 0) {
166
        // can happen if logged out after query was created (fix for RT #3915)
167
        $queryid = 0;
168
        goto newquery; // goto needs PHP 5.3
169
        /*
170
        $tpl->error($error_query_not_found);
171
        */
172
    } else {
173
        $record = sql_fetch_array($query_rs);
174
        $options = unserialize($record['options']);
175
        if ($record['user_id'] != 0) {
176
            $query_userid = $record['user_id'];
177
            $query_name = $record['name'];
178
        }
179
        sql_free_result($query_rs);
180
181
        $options['queryid'] = $queryid;
182
183
        sql("UPDATE `queries` SET `last_queried`=NOW() WHERE `id`='&1'", $queryid);
184
185
        // overwrite variable options
186
        if (isset($_REQUEST['output'])) {
187
            $options['output'] = $_REQUEST['output'];
188
        }
189
190
        if (isset($_REQUEST['showresult'])) {
191
            $options['showresult'] = $_REQUEST['showresult'];
192
        } else {
193
            if ($bCookieQueryid) {
194
                $options['showresult'] = 0;
195
            }
196
        }
197
198
        // overwrite variable options; see 'set common variable options' for more
199
        if (isset($_REQUEST['sortby'])) {
200
            $options['sort'] = $_REQUEST['sortby'];
201
        }
202
203
        // get findername from finderid
204
        $options['finderid'] = isset($options['finderid']) ? $options['finderid'] + 0 : 0; // Ocprop
205 View Code Duplication
        if (isset($options['finder']) && $options['finderid'] > 0) {
206
            $rs_name = sql("SELECT `username` FROM `user` WHERE `user_id`='&1'", $options['finderid']);
207
            if (sql_num_rows($rs_name) == 1) {
208
                $record_name = sql_fetch_array($rs_name);
209
                $options['finder'] = $record_name['username'];
210
            }
211
            unset($record_name);
212
            sql_free_result($rs_name);
213
        }
214
215
        // get ownername from ownerid
216
        $options['ownerid'] = isset($options['ownerid']) ? $options['ownerid'] + 0 : 0; // Ocprop
217 View Code Duplication
        if (isset($options['owner']) && $options['ownerid'] > 0) {
218
            $rs_name = sql("SELECT `username` FROM `user` WHERE `user_id`='&1'", $options['ownerid']);
219
            if (sql_num_rows($rs_name) == 1) {
220
                $record_name = sql_fetch_array($rs_name);
221
                $options['owner'] = $record_name['username'];
222
            }
223
            unset($record_name);
224
            sql_free_result($rs_name);
225
        }
226
227
        // map obsolete search types
228
        if ($options['searchtype'] == 'bydistance') {
229
            $options['searchtype'] = 'bycoords';
230
        }
231
    }
232
} else {  // $queryid == 0
233
    // build search options from GET/POST parameters or default values
234
235
    // hack
236
    if (isset($_REQUEST['searchto']) && ($_REQUEST['searchto'] != '')) {
237
        unset(
238
            $_REQUEST['searchbyplz'],
239
            $_REQUEST['searchbyort'],
240
            $_REQUEST['searchbyortplz'],
241
            $_REQUEST['searchbycoords'],
242
            $_REQUEST['searchbydistance'],
243
            $_REQUEST['searchbyname'],
244
            $_REQUEST['searchbyowner'],
245
            $_REQUEST['searchbyfinder'],
246
            $_REQUEST['searchbywaypoint'],
247
            $_REQUEST['searchbyfulltext'],
248
            $_REQUEST['searchbynofilter'],
249
            $_REQUEST['searchall']
250
        );
251
        $_REQUEST[$_REQUEST['searchto']] = $_REQUEST['searchto'];
252
    }
253
254
    // get the search options parameters and store them in the queries table (to view "the next page")
255
    $options['f_userowner'] = isset($_REQUEST['f_userowner']) ? $_REQUEST['f_userowner'] : 0; // Ocprop
256
    $options['f_userfound'] = isset($_REQUEST['f_userfound']) ? $_REQUEST['f_userfound'] : 0; // Ocprop
257
    $options['f_disabled'] = isset($_REQUEST['f_disabled']) ? $_REQUEST['f_disabled'] : 0;
258
    $options['f_inactive'] = isset($_REQUEST['f_inactive']) ? $_REQUEST['f_inactive'] : 1; // Ocprop
259
    // f_inactive formerly was used for both, archived and disabled caches.
260
    // After adding the separate f_disabled option, it is used only for archived
261
    // caches, but keeps its name for compatibility with existing stored or
262
    // external searches.
263
    $options['f_ignored'] = isset($_REQUEST['f_ignored']) ? $_REQUEST['f_ignored'] : 1;
264
    $options['f_otherPlatforms'] = isset($_REQUEST['f_otherPlatforms']) ? $_REQUEST['f_otherPlatforms'] : 0;
265
    $options['f_geokrets'] = isset($_REQUEST['f_geokrets']) ? $_REQUEST['f_geokrets'] : 0;
266
    $options['expert'] = isset($_REQUEST['expert']) ? $_REQUEST['expert'] : 0; // Ocprop: 0
267
    $options['showresult'] = isset($_REQUEST['showresult']) ? $_REQUEST['showresult'] : 0;
268
    $options['output'] = isset($_REQUEST['output']) ? $_REQUEST['output'] : 'HTML'; // Ocprop: HTML
269
    $options['bbox'] = isset($_REQUEST['bbox']) ? $_REQUEST['bbox'] : false;
270
271 View Code Duplication
    if (isset($_REQUEST['cache_attribs'])) {
272
        if ($_REQUEST['cache_attribs'] != '') {
273
            $aAttribs = mb_split(';', $_REQUEST['cache_attribs']);
274
            $countAttribs = count($aAttribs);
275
            for ($i = 0; $i < $countAttribs; $i++) {
276
                $options['cache_attribs'][$aAttribs[$i] + 0] = $aAttribs[$i] + 0;
277
            }
278
            unset($aAttribs);
279
        } else {
280
            $options['cache_attribs'] = [];
281
        }
282
    } else {
283
        $options['cache_attribs'] = [];
284
    }
285
286 View Code Duplication
    if (isset($_REQUEST['cache_attribs_not'])) {
287
        if ($_REQUEST['cache_attribs_not'] != '') {
288
            $aAttribs = mb_split(';', $_REQUEST['cache_attribs_not']);
289
            $countAttribs = count($aAttribs);
290
            for ($i = 0; $i < $countAttribs; $i++) {
291
                $options['cache_attribs_not'][$aAttribs[$i] + 0] = $aAttribs[$i] + 0;
292
            }
293
            unset($aAttribs);
294
        } else {
295
            $options['cache_attribs_not'] = [];
296
        }
297
    } else {
298
        $options['cache_attribs_not'] = [];
299
    }
300
301
    if (!isset($_REQUEST['unit'])) {
302
        $options['unit'] = 'km';
303
    } elseif (mb_strtolower($_REQUEST['unit']) == 'sm') {
304
        $options['unit'] = 'sm';
305
    } elseif (mb_strtolower($_REQUEST['unit']) == 'nm') {
306
        $options['unit'] = 'nm';
307
    } else {
308
        $options['unit'] = DEFAULT_DISTANCE_UNIT;
309
    }
310
311
    if (isset($_REQUEST['searchbyname'])) {
312
        $options['searchtype'] = 'byname';
313
        $options['cachename'] = isset($_REQUEST['cachename']) ? stripslashes($_REQUEST['cachename']) : '';
314
315 View Code Duplication
        if (!isset($_REQUEST['utf8'])) {
316
            $options['cachename'] = iconv("ISO-8859-1", "UTF-8", $options['cachename']);
317
        }
318
    } elseif (isset($_REQUEST['searchbyowner'])) { // Ocprop
319
        $options['searchtype'] = 'byowner';
320
321
        $options['ownerid'] = isset($_REQUEST['ownerid']) ? $_REQUEST['ownerid'] : 0;
322
        $options['owner'] = isset($_REQUEST['owner']) ? stripslashes($_REQUEST['owner']) : '';
323
324 View Code Duplication
        if (isset($options['owner'])) {
325
            $rs_name = sql("SELECT `user_id` FROM `user` WHERE `username`='&1'", $options['owner']);
326
            if (sql_num_rows($rs_name) == 1) {
327
                $record_id = sql_fetch_array($rs_name);
328
                $options['ownerid'] = $record_id['user_id'];
329
                $user = new user($options['ownerid']);
330
            }
331
            unset($record_id);
332
            sql_free_result($rs_name);
333
        }
334
    } elseif (isset($_REQUEST['searchbyfinder'])) { // Ocprop
335
        $options['searchtype'] = 'byfinder';
336
337
        $options['finderid'] = isset($_REQUEST['finderid']) ? $_REQUEST['finderid'] : 0;
338
        $options['finder'] = isset($_REQUEST['finder']) ? stripslashes($_REQUEST['finder']) : '';
339
        $options['logtype'] = isset($_REQUEST['logtype']) ? $_REQUEST['logtype'] : '1,7'; // Ocprop
340
341 View Code Duplication
        if (isset($options['finder'])) {
342
            $rs_name = sql("SELECT `user_id` FROM `user` WHERE `username`='&1'", $options['finder']);
343
            if (sql_num_rows($rs_name) == 1) {
344
                $record_id = sql_fetch_array($rs_name);
345
                $options['finderid'] = $record_id['user_id'];
346
                $user = new user($options['finderid']);
347
            }
348
            unset($record_id);
349
            sql_free_result($rs_name);
350
        }
351
    } elseif ((isset($_REQUEST['searchbyortplz']) && is_numeric($_REQUEST['ortplz']))
352
              || isset($_REQUEST['searchbyplz'])) {
353
        $options['searchtype'] = 'byplz';
354 View Code Duplication
        if (isset($_REQUEST['searchbyortplz'])) {
355
            $options['ortplz'] = $_REQUEST['ortplz'];
356
        } else {
357
            $options['ortplz'] = $_REQUEST['plz'];
358
        }
359
        $options['locid'] = isset($_REQUEST['locid']) ? $_REQUEST['locid'] + 0 : 0;
360
        $options['distance'] = isset($_REQUEST['distance']) ? $_REQUEST['distance'] + 0 : DEFAULT_SEARCH_DISTANCE;
361
    } elseif (isset($_REQUEST['searchbyortplz']) || isset($_REQUEST['searchbyort'])) {
362
        $options['searchtype'] = 'byort';
363 View Code Duplication
        if (isset($_REQUEST['searchbyortplz'])) {
364
            $options['ortplz'] = $_REQUEST['ortplz'];
365
        } else {
366
            $options['ortplz'] = $_REQUEST['ort'];
367
        }
368
        $options['locid'] = isset($_REQUEST['locid']) ? $_REQUEST['locid'] + 0 : 0;
369
        $options['distance'] = isset($_REQUEST['distance']) ? $_REQUEST['distance'] + 0 : DEFAULT_SEARCH_DISTANCE;
370
    } elseif (isset($_REQUEST['searchbywaypoint'])) {
371
        $options['searchtype'] = 'bywaypoint';
372
373
        $options['waypoint'] = isset($_REQUEST['waypoint']) ? stripslashes($_REQUEST['waypoint']) : '';
374
        $options['distance'] = isset($_REQUEST['distance']) ? $_REQUEST['distance'] + 0 : DEFAULT_SEARCH_DISTANCE;
375
    } elseif (isset($_REQUEST['searchbycoords']) || isset($_REQUEST['searchbydistance'])) {
376
        $options['searchtype'] = 'bycoords';
377
378
        // Ocprop: all of the following options
379
        if (isset($_REQUEST['lat']) && isset($_REQUEST['lon'])) {
380
            $options['lat'] = $_REQUEST['lat'] + 0;
381
            $options['lon'] = $_REQUEST['lon'] + 0;
382
        } else {
383
            $options['latNS'] = isset($_REQUEST['latNS']) ? $_REQUEST['latNS'] : 'N';
384
            $options['lonEW'] = isset($_REQUEST['lonEW']) ? $_REQUEST['lonEW'] : 'E';
385
386
            $options['lat_h'] = isset($_REQUEST['lat_h']) ? $_REQUEST['lat_h'] : 0;
387
            $options['lon_h'] = isset($_REQUEST['lon_h']) ? $_REQUEST['lon_h'] : 0;
388
            $options['lat_min'] = isset($_REQUEST['lat_min']) ? $_REQUEST['lat_min'] : 0;
389
            $options['lon_min'] = isset($_REQUEST['lon_min']) ? $_REQUEST['lon_min'] : 0;
390
        }
391
392
        $options['distance'] = isset($_REQUEST['distance']) ? $_REQUEST['distance'] : 0;
393
    } elseif (isset($_REQUEST['searchbyfulltext'])) {
394
        $options['searchtype'] = 'byfulltext';
395
396
        $options['ft_name'] = isset($_REQUEST['ft_name']) ? $_REQUEST['ft_name'] + 0 : 0;
397
        $options['ft_desc'] = isset($_REQUEST['ft_desc']) ? $_REQUEST['ft_desc'] + 0 : 0;
398
        $options['ft_logs'] = isset($_REQUEST['ft_logs']) ? $_REQUEST['ft_logs'] + 0 : 0;
399
        $options['ft_pictures'] = isset($_REQUEST['ft_pictures']) ? $_REQUEST['ft_pictures'] + 0 : 0;
400
401
        $options['fulltext'] = isset($_REQUEST['fulltext']) ? $_REQUEST['fulltext'] : '';
402
    } elseif (isset($_REQUEST['searchbycacheid'])) {
403
        $options['searchtype'] = 'bycacheid';
404
        $options['cacheid'] = isset($_REQUEST['cacheid']) ? $_REQUEST['cacheid'] : 0;
405
        if (!is_numeric($options['cacheid'])) {
406
            $options['cacheid'] = 0;
407
        }
408
    } elseif (isset($_REQUEST['searchbywp'])) {
409
        $options['searchtype'] = 'bywp';
410
        $options['wp'] = isset($_REQUEST['wp']) ? $_REQUEST['wp'] : '';
411
    } elseif (isset($_REQUEST['searchbynofilter'])) {
412
        $options['searchtype'] = 'bynofilter';
413
    } elseif (isset($_REQUEST['searchbylist'])) {
414
        $options['searchtype'] = 'bylist';
415
        $options['listid'] = isset($_REQUEST['listid']) ? $_REQUEST['listid'] + 0 : 0;
416
        $invalid_waypoints = isset($_REQUEST['invalidwp']) ? $_REQUEST['invalidwp'] : false;
417
418
        $password = isset($_REQUEST['listkey']) ? $_REQUEST['listkey'] : '';
419
        $list = new cachelist($options['listid']);
420
        if (!$list->allowView($password)) {
421
            $tpl->redirect("cachelists.php");
422
        }
423
        $options['cachelist'] = cachelist::getListById($options['listid']); // null for invalid ID
424
        $options['cachelist_pw'] = $password;
425
    } elseif (isset($_REQUEST['searchall'])) {
426
        if (!$login->logged_in() &&
427
            !(isset($_REQUEST['country']) && $_REQUEST['country'] != '') &&
428
            !(isset($_REQUEST['language']) && $_REQUEST['language'] != '')
429
        ) {
430
            // This operation is very expensive and therefore available only
431
            // for logged-in users.
432
            $tpl->error(ERROR_LOGIN_REQUIRED);
433
        } else {
434
            $options['searchtype'] = 'all';
435
        }
436
    } else {
437
        if (isset($_REQUEST['showresult'])) {
438
            $tpl->error('unknown search option');
439
        } else {
440
            // Set default search type; this prevents errors in outputSearchForm()
441
            // when initializing searchtype-dependent options:
442
            $options['searchtype'] = 'byname';
443
            $options['cachename'] = '';
444
        }
445
    }
446
447
    $options['sort'] = isset($_REQUEST['sort']) ? $_REQUEST['sort'] : ($homecoords ? 'bydistance' : 'byname');
448
    if (isset($_REQUEST['orderRatingFirst']) && $_REQUEST['orderRatingFirst'] == 1) {
449
        $options['orderRatingFirst'] = true;
450
    }
451
452
    $options['country'] = isset($_REQUEST['country']) ? $_REQUEST['country'] : '';
453
    $options['language'] = isset($_REQUEST['language']) ? $_REQUEST['language'] : '';
454
    $options['adm2'] = isset($_REQUEST['adm2']) ? $_REQUEST['adm2'] : '';
455
    $options['cachetype'] = isset($_REQUEST['cachetype']) ? $_REQUEST['cachetype'] : '';
456
457
    $options['cachesize'] = isset($_REQUEST['cachesize']) ? $_REQUEST['cachesize'] : '';
458
    $options['difficultymin'] = isset($_REQUEST['difficultymin']) ? $_REQUEST['difficultymin'] + 0 : 0;
459
    $options['difficultymax'] = isset($_REQUEST['difficultymax']) ? $_REQUEST['difficultymax'] + 0 : 0;
460
    $options['terrainmin'] = isset($_REQUEST['terrainmin']) ? $_REQUEST['terrainmin'] + 0 : 0;
461
    $options['terrainmax'] = isset($_REQUEST['terrainmax']) ? $_REQUEST['terrainmax'] + 0 : 0;
462
    $options['recommendationmin'] = isset($_REQUEST['recommendationmin']) ? $_REQUEST['recommendationmin'] + 0 : 0;
463
464
    if (in_array($options['searchtype'], ['byort', 'byplz', 'bydistance', 'bywaypoint'])) {
465
        // For distance-based searches, sort by distance instead of name.
466
        if ($options['sort'] == 'byname') {
467
            $options['sort'] = 'bydistance';
468
        }
469
    } else {
470
        // For non-distance-based searches, sort by name instead of distance if
471
        // no reference coords exist.
472
        if (!isset($options['lat']) || !isset($options['lon']) || $options['lat'] + $options['lon'] == 0) {
473
            if (!$homecoords) {
474
                $options['sort'] = 'byname';
475
            }
476
        }
477
    }
478
479
    $options['queryid'] = 0;
480
}  // $queryid == 0
481
482
// set common variable options
483
if (isset($_REQUEST['sortorder'])) {
484
    $options['sortorder'] = $_REQUEST['sortorder'];
485
}
486
if (isset($_REQUEST['creationdate'])) {
487
    $options['creationdate'] = $_REQUEST['creationdate'];
488
}
489
490
491
//=========================================================
492
//  3. query caching
493
//=========================================================
494
495
$bRememberQuery = isset($_REQUEST['skipqueryid']) ? !$_REQUEST['skipqueryid'] : true;
496
// This is used by the map, which implements its own query-caching.
497
if ($bRememberQuery) {
498
    if ($queryid == 0 && $options['showresult'] != 0) { // 'showresult' = "execute query"
499
        sql(
500
            "INSERT INTO `queries` (`user_id`, `options`, `last_queried`) VALUES (0, '&1', NOW())",
501
            serialize($options)
502
        );
503
        $options['queryid'] = sql_insert_id();
504
        $cookie->set('lastqueryid', $options['queryid']);
505
    }
506
}
507
508
// remove old queries (after 1 hour without use);
509
// execute only every 50 search calls
510
if (mt_rand(1, 50) == 1) {
511
    sql('DELETE FROM `queries` WHERE `last_queried` < NOW() - INTERVAL 1 HOUR AND `user_id` = 0');
512
}
513
514
515
//=========================================================
516
//  4. set defaults for new search options
517
//     which may not be present in a stored query
518
//=========================================================
519
520
if (!isset($options['orderRatingFirst'])) {
521
    $options['orderRatingFirst'] = false;
522
}
523
if (!isset($options['f_otherPlatforms'])) {
524
    $options['f_otherPlatforms'] = 0;
525
}
526
if (!isset($options['difficultymin'])) {
527
    $options['difficultymin'] = 0;
528
}
529
if (!isset($options['difficultymax'])) {
530
    $options['difficultymax'] = 0;
531
}
532
if (!isset($options['terrainmin'])) {
533
    $options['terrainmin'] = 0;
534
}
535
if (!isset($options['terrainmax'])) {
536
    $options['terrainmax'] = 0;
537
}
538
if (!isset($options['recommendationmin'])) {
539
    $options['recommendationmin'] = 0;
540
}
541
if (!isset($options['cachetype'])) {
542
    $options['cachetype'] = '';
543
}
544
if (!isset($options['cachesize'])) {
545
    $options['cachesize'] = '';
546
}
547
if (!isset($options['bbox'])) {
548
    $options['bbox'] = false;
549
}
550
if (!isset($options['f_disabled'])) {
551
    $options['f_disabled'] = 0;
552
}
553
if (!isset($options['f_geokrets'])) {
554
    $options['f_geokrets'] = 0;
555
}
556
557
if (!isset($options['showresult'])) {
558
    $options['showresult'] = 0;
559
}
560
if ($options['showresult'] == 1) {
561
    //===============================================================
562
    //  X5. build basic SQL statement depends on search type
563
    //      and filtering options
564
    //===============================================================
565
566
    sql_drop_temp_table_slave('result_caches');
567
    $cachesFilter = '';
568
569
    if (!isset($options['output'])) {
570
        $options['output'] = '';
571
    }
572
    if ((mb_strpos($options['output'], '.') !== false) ||
573
        (mb_strpos($options['output'], '/') !== false) ||
574
        (mb_strpos($options['output'], '\\') !== false)
575
    ) {
576
        $options['output'] = 'HTML';
577
    }
578
579
    // make a list of cache-ids that are in the result
580
    if (!isset($options['expert'])) {
581
        $options['expert'] = 0;
582
    }
583
    if ($options['expert'] == 0) {
584
        $sql_select = [];
585
        $sql_from = '';
586
        $sql_innerjoin = [];
587
        $sql_leftjoin = [];
588
        $sql_where = [];
589
        $sql_having = [];
590
        $sql_group = [];
591
592
        //check the entered data and build SQL
593
        if (!isset($options['searchtype'])) {
594
            $options['searchtype'] = '';
595
        }
596
        if ($options['searchtype'] == 'byname') {
597
            $sql_select[] = '`caches`.`cache_id` `cache_id`';
598
            $sql_from = '`caches`';
599
            $sql_where[] = '`caches`.`name` LIKE \'%' . sql_escape($options['cachename']) . '%\'';
600
        } elseif ($options['searchtype'] == 'byowner') {
601
            if ($options['ownerid'] != 0) {
602
                $sql_select[] = '`caches`.`cache_id` `cache_id`';
603
                $sql_from = '`caches`';
604
                $sql_where[] = '`user_id`=\'' . sql_escape($options['ownerid']) . '\'';
605 View Code Duplication
            } else {
606
                $sql_select[] = '`caches`.`cache_id` `cache_id`';
607
                $sql_from = '`caches`';
608
                $sql_innerjoin[] = '`user` ON `caches`.`user_id`=`user`.`user_id`';
609
                $sql_where[] = '`user`.`username`=\'' . sql_escape($options['owner']) . '\'';
610
            }
611
        } elseif (($options['searchtype'] == 'byplz') || ($options['searchtype'] == 'byort')) {
612
            $locid = $options['locid'];
613
614
            if ($options['searchtype'] == 'byplz') {
615
                if ($locid == 0) {
616 View Code Duplication
                    if (isset($options['ortplz'])) {
617
                        $plz = $options['ortplz'];
618
                    } else {
619
                        $plz = $options['plz'];
620
                    }
621
                    $sql =
622
                        "SELECT `loc_id`
623
                         FROM `geodb_textdata`
624
                         WHERE `text_type`=500300000 AND `text_val`='" . sql_escape($plz) . "'";
625
                    $rs = sql($sql);
626
                    if (sql_num_rows($rs) == 0) {
627
                        sql_free_result($rs);
628
                        $options['error_plz'] = true;
629
                        outputSearchForm($options);
630
                        exit;
631
                    } elseif (sql_num_rows($rs) == 1) {
632
                        $r = sql_fetch_array($rs);
633
                        sql_free_result($rs);
634
                        $locid = $r['loc_id'];
635
                    } else {
636
                        sql_free_result($rs);
637
                        // ok, viele locations ... alle auflisten ...
638
                        outputLocidSelectionForm($sql, $options);
639
                        exit;
640
                    }
641
                }
642
                // ok, wir haben einen ort ... koordinaten ermitteln
643
                $locid = $locid + 0;
644
                $rs = sql(
645
                    "SELECT `lon`, `lat`
646
                     FROM `geodb_coordinates`
647
                     WHERE `loc_id`='&1' AND coord_type=200100000",
648
                    $locid
649
                );
650 View Code Duplication
                if (isset($rs) && $r = sql_fetch_array($rs)) {
651
                    // ok ... wir haben koordinaten ...
652
                    $lat = $r['lat'] + 0;
653
                    $lon = $r['lon'] + 0;
654
                    sql_free_result($rs);
655
656
                    $lon_rad = $lon * 3.14159 / 180;
657
                    $lat_rad = $lat * 3.14159 / 180;
658
659
                    if (isset($options['distance'])) {
660
                        $distance = $options['distance'];
661
                    } else {
662
                        $distance = DEFAULT_SEARCH_DISTANCE;
663
                    }
664
                    if (isset($options['unit'])) {
665
                        $distance_unit = $options['unit'];
666
                    } else {
667
                        $distance_unit = DEFAULT_DISTANCE_UNIT;
668
                    }
669
670
                    sqlStringbySearchradius($distance, $lat, $lon, $multiplier, $distance_unit);
671
                } else {
672
                    if (isset($rs)) {
673
                        sql_free_result($rs);
674
                    }
675
                    $options['error_locidnocoords'] = true;
676
                    outputSearchForm($options);
677
                    exit;
678
                }
679
            } else {
680
                if ($options['searchtype'] == 'byort') {
681
                    if ($locid == 0) {
682 View Code Duplication
                        if (isset($options['ortplz'])) {
683
                            $ort = $options['ortplz'];
684
                        } else {
685
                            $ort = $options['ort'];
686
                        }
687
                        $simpletexts = search_text2sort($ort, true);
688
                        $simpletextsarray = explode_multi($simpletexts, ' -/,');
689
690
                        $sqlhashes = '';
691
                        $wordscount = 0;
692
                        foreach ($simpletextsarray as $text) {
693
                            if ($text != '') {
694
                                $searchstring = search_text2simple($text);
695
696
                                if ($sqlhashes != '') {
697
                                    $sqlhashes .= ' OR ';
698
                                }
699
                                $sqlhashes .= '`gns_search`.`simplehash`=' . sprintf("%u", crc32($searchstring));
700
701
                                $wordscount++;
702
                            }
703
                        }
704
705
                        if ($sqlhashes == '') {
706
                            $options['error_ort'] = true;
707
                            outputSearchForm($options);
708
                        }
709
710
                        // temporäre tabelle erstellen und dann einträge entfernen, die nicht mindestens so oft vorkommen wie worte gegeben wurden
711
                        sql_drop_temp_table_slave('tmpuniids');
712
                        sql_temp_table_slave('tmpuniids');
713
                        sql_slave(
714
                            "CREATE TEMPORARY TABLE &tmpuniids (
715
                                `uni_id` int(11) NOT NULL,
716
                                `cnt` int(11) NOT NULL,
717
                                `olduni` int(11) NOT NULL,
718
                                `simplehash` int(11) NOT NULL
719
                             ) ENGINE=MEMORY
720
                                 SELECT
721
                                    `gns_search`.`uni_id` `uni_id`,
722
                                    0 `cnt`,
723
                                    0 `olduni`,
724
                                    `simplehash`
725
                                 FROM `gns_search`
726
                                 WHERE " . $sqlhashes
727
                        );
728
                        sql_slave('ALTER TABLE &tmpuniids ADD INDEX (`uni_id`)');
729
730
                        //    BUGFIX: dieser Code sollte nur ausgeführt werden, wenn mehr als ein Suchbegriff eingegeben wurde
731
                        //                    damit alle Einträge gefiltert, die nicht alle Suchbegriffe enthalten
732
                        //                    nun wird dieser Quellcode auch ausgeführt, um mehrfache uni_id's zu filtern
733
                        //          Notwendig, wenn nach Baden gesucht wird => Baden-Baden war doppelt in der Liste
734
                        //    if ($wordscount > 1)
735
                        //    {
736
                        sql_temp_table_slave('tmpuniids2');
737
                        sql_slave(
738
                            "CREATE TEMPORARY TABLE &tmpuniids2 (
739
                                `uni_id` int(11) NOT NULL,
740
                                `cnt` int(11) NOT NULL,
741
                                `olduni` int(11) NOT NULL
742
                             ) ENGINE=MEMORY
743
                                SELECT `uni_id`, COUNT(*) `cnt`, 0 olduni
744
                                FROM &tmpuniids
745
                                GROUP BY `uni_id`
746
                                HAVING `cnt` >= " . $wordscount
747
                        );
748
                        sql_slave('ALTER TABLE &tmpuniids2 ADD INDEX (`uni_id`)');
749
                        sql_drop_temp_table_slave('tmpuniids');
750
                        sql_rename_temp_table_slave('tmpuniids2', 'tmpuniids');
751
                        //    }
752
753
                        //    add: SELECT g2.uni FROM &tmpuniids JOIN gns_locations g1 ON &tmpuniids.uni_id=g1.uni JOIN gns_locations g2 ON g1.ufi=g2.ufi WHERE g1.nt!='N' AND g2.nt='N'
754
                        // remove: SELECT g1.uni FROM &tmpuniids JOIN gns_locations g1 ON &tmpuniids.uni_id=g1.uni JOIN gns_locations g2 ON g1.ufi=g2.ufi WHERE g1.nt!='N' AND g2.nt='N'
755
756
                        // und jetzt noch alle englischen bezeichnungen durch deutsche ersetzen (wo möglich) ...
757
                        sql_temp_table_slave('tmpuniidsAdd');
758
                        sql_slave(
759
                            "CREATE TEMPORARY TABLE &tmpuniidsAdd (
760
                                `uni` int(11) NOT NULL,
761
                                `olduni` int(11) NOT NULL,
762
                                PRIMARY KEY  (`uni`)
763
                            ) ENGINE=MEMORY
764
                                SELECT g2.uni uni, g1.uni olduni
765
                                FROM &tmpuniids
766
                                JOIN gns_locations g1 ON &tmpuniids.uni_id=g1.uni
767
                                JOIN gns_locations g2 ON g1.ufi=g2.ufi
768
                                WHERE g1.nt!='N' AND g2.nt='N' GROUP BY uni"
769
                        );
770
                        sql_temp_table_slave('tmpuniidsRemove');
771
                        sql_slave(
772
                            "CREATE TEMPORARY TABLE &tmpuniidsRemove (
773
                                `uni` int(11) NOT NULL,
774
                                PRIMARY KEY  (`uni`)
775
                            ) ENGINE=MEMORY
776
                                SELECT DISTINCT g1.uni uni
777
                                FROM &tmpuniids
778
                                JOIN gns_locations g1 ON &tmpuniids.uni_id=g1.uni
779
                                JOIN gns_locations g2 ON g1.ufi=g2.ufi
780
                                WHERE g1.nt!='N' AND g2.nt='N'"
781
                        );
782
                        sql_slave(
783
                            "DELETE FROM &tmpuniids
784
                             WHERE uni_id IN (SELECT uni FROM &tmpuniidsRemove)"
785
                        );
786
                        sql_slave(
787
                            "DELETE FROM &tmpuniidsAdd
788
                             WHERE uni IN (SELECT uni_id FROM &tmpuniids)"
789
                        );
790
                        sql_slave(
791
                            "INSERT INTO &tmpuniids (uni_id, olduni)
792
                             SELECT uni, olduni FROM &tmpuniidsAdd"
793
                        );
794
                        sql_drop_temp_table_slave('tmpuniidsAdd');
795
                        sql_drop_temp_table_slave('tmpuniidsRemove');
796
797
                        $rs = sql_slave("SELECT `uni_id` FROM &tmpuniids");
798
                        if (sql_num_rows($rs) == 0) {
799
                            sql_free_result($rs);
800
801
                            $options['error_ort'] = true;
802
                            outputSearchForm($options);
803
                            exit;
804
                        } elseif (sql_num_rows($rs) == 1) {
805
                            $r = sql_fetch_array($rs);
806
                            sql_free_result($rs);
807
808
                            // wenn keine 100%ige übereinstimmung nochmals anzeigen
809
                            $locid = $r['uni_id'] + 0;
810
                            $rsCmp = sql_slave(
811
                                "SELECT `full_name` FROM `gns_locations` WHERE `uni`='&1' LIMIT 1",
812
                                $locid
813
                            );
814
                            $rCmp = sql_fetch_array($rsCmp);
815
                            sql_free_result($rsCmp);
816
817
                            if (mb_strtolower($rCmp['full_name']) != mb_strtolower($ort)) {
818
                                outputUniidSelectionForm(
819
                                    "SELECT `uni_id`, `olduni` FROM `&tmpuniids`",
820
                                    $options
821
                                );
822
                            }
823
                        } else {
824
                            sql_free_result($rs);
825
                            outputUniidSelectionForm(
826
                                "SELECT `uni_id`, `olduni` FROM `&tmpuniids`",
827
                                $options
828
                            );
829
                            exit;
830
                        }
831
                    }
832
833
834
                    // ok, wir haben einen ort ... koordinaten ermitteln
835
                    $locid = $locid + 0;
836
                    $rs = sql_slave(
837
                        "SELECT `lon`, `lat` FROM `gns_locations` WHERE `uni`='&1' LIMIT 1",
838
                        $locid
839
                    );
840 View Code Duplication
                    if (isset($rs) && $r = sql_fetch_array($rs)) {
841
                        // ok ... wir haben koordinaten ...
842
843
                        $lat = $r['lat'] + 0;
844
                        $lon = $r['lon'] + 0;
845
                        sql_free_result($rs);
846
847
                        $lon_rad = $lon * 3.14159 / 180;
848
                        $lat_rad = $lat * 3.14159 / 180;
849
850
                        if (isset($options['distance'])) {
851
                            $distance = $options['distance'];
852
                        } else {
853
                            $distance = DEFAULT_SEARCH_DISTANCE;
854
                        }
855
                        if (isset($options['unit'])) {
856
                            $distance_unit = $options['unit'];
857
                        } else {
858
                            $distance_unit = DEFAULT_DISTANCE_UNIT;
859
                        }
860
861
                        sqlStringbySearchradius($distance, $lat, $lon, $multiplier, $distance_unit);
862
                    } else {
863
                        if (isset($rs)) {
864
                            sql_free_result($rs);
865
                        }
866
                        $options['error_locidnocoords'] = true;
867
                        outputSearchForm($options);
868
                        exit;
869
                    }
870
                }
871
            }
872
        } elseif ($options['searchtype'] == 'bywaypoint') {
873
            if (preg_match('/gc[0-9a-z]{2,}/i', $options['waypoint'])) {
874
                $rs = sql_slave(
875
                    "SELECT `longitude`, `latitude`
876
                     FROM `caches`
877
                     WHERE `wp_gc_maintained`='&1' ",
878
                    $options['waypoint']
879
                );
880
            } else {
881
                $rs = sql_slave(
882
                    "SELECT `longitude`, `latitude`
883
                     FROM `caches`
884
                     WHERE `wp_oc`='&1' ",
885
                    $options['waypoint']
886
                );
887
            }
888
            $r = sql_fetch_array($rs);
889
            
890
            if ($r) {
891
                $lat = $r['latitude'];
892
                $lon = $r['longitude'];
893
                sql_free_result($rs);
894
895
                $distance = $options['distance'];
896
                $distance_unit = $options['unit'];
897
898
                $lon_rad = $lon * 3.14159 / 180;
899
                $lat_rad = $lat * 3.14159 / 180;
900
901
                sqlStringbySearchradius($distance, $lat, $lon, $multiplier, $distance_unit);
902
            } else {
903
                $options['error_nowaypointfound'] = true;
904
                outputSearchForm($options);
905
                exit;
906
            }
907
        } elseif ($options['searchtype'] == 'bycoords') {  // Ocprop
908
            //check the entered data
909
            if (isset($options['lat']) && isset($options['lon'])) {
910
                $lat = $options['lat'] + 0;
911
                $lon = $options['lon'] + 0;
912
            } else {
913
                $latNS = $options['latNS'];
914
                $lonEW = $options['lonEW'];
915
916
                $lon_h = $options['lon_h'];
917
                $lat_h = $options['lat_h'];
918
                $lon_min = $options['lon_min'];
919
                $lat_min = $options['lat_min'];
920
921
                if (is_numeric($lon_h)
922
                    && is_numeric($lon_min)
923
                    && ($lon_h >= 0)
924
                    && ($lon_h < 180)
925
                    && ($lon_min >= 0)
926
                    && ($lon_min < 60)
927
                ) {
928
                    $lon = $lon_h + $lon_min / 60;
929
                    if ($lonEW == 'W') {
930
                        $lon = -$lon;
931
                    }
932
                }
933
934
                if (is_numeric($lat_h)
935
                    && is_numeric($lat_min)
936
                    && ($lat_h >= 0)
937
                    && ($lat_h < 90)
938
                    && ($lat_min >= 0)
939
                    && ($lat_min < 60)
940
                ) {
941
                    $lat = $lat_h + $lat_min / 60;
942
                    if ($latNS == 'S') {
943
                        $lat = - $lat;
944
                    }
945
                }
946
            }
947
948
            $distance = $options['distance'];
949
            $distance_unit = $options['unit'];
950
951
            if ((!isset($lon)) || (!isset($lat)) || (!is_numeric($distance))) {
952
                $options['error_nocoords'] = true;
953
                outputSearchForm($options);
954
                exit;
955
            }
956
957
            $lon_rad = $lon * 3.14159 / 180;
958
            $lat_rad = $lat * 3.14159 / 180;
959
960
            sqlStringbySearchradius($distance, $lat, $lon, $multiplier, $distance_unit);
961
        } elseif ($options['searchtype'] == 'byfinder') {
962
            if ($options['finderid'] != 0) {
963
                $finder_id = $options['finderid'];
964
            } else {
965
                $rs = sql_slave(
966
                    "SELECT `user_id` FROM `user` WHERE `username`='&1'",
967
                    $options['finder']
968
                );
969
                $finder_record = sql_fetch_array($rs);
970
                $finder_id = $finder_record['user_id'];
971
                sql_free_result($rs);
972
            }
973
974
            if (!isset($options['logtype'])) {
975
                $options['logtype'] = '1,7';
976
            }
977
978
            $sql_select[] = 'distinct `caches`.`cache_id` `cache_id`';
979
            // needs distinct because there can be multiple matching logs per cache
980
            $sql_from = '`caches`';
981
            $sql_innerjoin[] = '`cache_logs` ON `caches`.`cache_id`=`cache_logs`.`cache_id`';
982
            $sql_where[] = '`cache_logs`.`user_id`=\'' . sql_escape($finder_id) . '\'';
983
984
            if ($options['logtype'] != '0') { // 0 = all types
985
                $ids = explode(',', $options['logtype']);
986
                $idNumbers = '0';
987
                foreach ($ids as $id) {
988
                    if ($idNumbers != '') {
989
                        $idNumbers .= ',';
990
                    }
991
                    $idNumbers .= ($id + 0);
992
                }
993
                $sql_where[] = '`cache_logs`.`type` IN (' . $idNumbers . ')';
994
            }
995 View Code Duplication
        } elseif ($options['searchtype'] == 'bycacheid') {
996
            $sql_select[] = '`caches`.`cache_id` `cache_id`';
997
            $sql_from = '`caches`';
998
            $sql_where[] = '`caches`.`cache_id`=\'' . sql_escape($options['cacheid']) . '\'';
999
        } elseif ($options['searchtype'] == 'bywp') {
1000
            $sql_select[] = '`caches`.`cache_id` `cache_id`';
1001
            $sql_from = '`caches`';
1002
            $sql_where[] = '`caches`.`wp_oc`=\'' . sql_escape($options['wp']) . '\'';
1003
        } elseif ($options['searchtype'] == 'byfulltext') {
1004
            require_once __DIR__ . '/lib2/search/ftsearch.inc.php';
1005
1006
            $fulltext = $options['fulltext'];
1007
            $hashes = ftsearch_hash($fulltext);
1008
1009
            if (count($hashes) == 0) {
1010
                $options['error_nofulltext'] = true;
1011
                outputSearchForm($options);
1012
            } else {
1013
                if (count($hashes) > 50) {
1014
                    $options['error_fulltexttoolong'] = true;
1015
                    outputSearchForm($options);
1016
                }
1017
            }
1018
1019
            $ft_types = [];
1020
            if (isset($options['ft_name']) && $options['ft_name']) {
1021
                $ft_types[] = 2;
1022
            }
1023
            if (isset($options['ft_logs']) && $options['ft_logs']) {
1024
                $ft_types[] = 1;
1025
            }
1026
            if (isset($options['ft_desc']) && $options['ft_desc']) {
1027
                $ft_types[] = 3;
1028
            }
1029
            if (isset($options['ft_pictures']) && $options['ft_pictures']) {
1030
                $ft_types[] = 6;
1031
            }
1032
            if (count($ft_types) == 0) {
1033
                $ft_types[] = 0;
1034
            }
1035
1036
            $sql_select[] = '`caches`.`cache_id` `cache_id`';
1037
            $sql_from = '`caches`';
1038
1039
            $n = 1;
1040
            foreach ($hashes as $k => $h) {
1041
                if ($n > 1) {
1042
                    $sql_innerjoin[] = '`search_index` AS `s' . $n . '` ON `s' .
1043
                        ($n - 1) . '`.`cache_id`=`s' . $n . '`.`cache_id`';
1044
                } else {
1045
                    $sql_innerjoin[] = '`search_index` AS `s1` ON `s1`.`cache_id`=`caches`.`cache_id`';
1046
                }
1047
1048
                $sql_where[] = '`s' . $n . '`.`hash`=\'' . sql_escape($h) . '\'';
1049
                $sql_where[] = '`s' . $n . '`.`object_type` IN (' . implode(',', $ft_types) . ')';
1050
1051
                $n++;
1052
            }
1053
1054
            $sqlFilter =
1055
                'SELECT DISTINCT ' . implode(',', $sql_select) .
1056
                ' FROM ' . $sql_from .
1057
                ' INNER JOIN ' . implode(' INNER JOIN ', $sql_innerjoin) .
1058
                ' WHERE ' . implode(' AND ', $sql_where);
1059
1060
            sql_drop_temp_table_slave('tmpFTCaches');
1061
            sql_temp_table_slave('tmpFTCaches');
1062
            sql_slave(
1063
                "CREATE TEMPORARY TABLE &tmpFTCaches (`cache_id` int (11) PRIMARY KEY) " . $sqlFilter
1064
            );
1065
1066
            $sql_select = [];
1067
            $sql_from = '';
1068
            $sql_innerjoin = [];
1069
            $sql_leftjoin = [];
1070
            $sql_where = [];
1071
1072
            $sql_select[] = '`caches`.`cache_id` `cache_id`';
1073
            $sql_from = '&tmpFTCaches';
1074
            $sql_innerjoin[] = '`caches` ON `caches`.`cache_id`=&tmpFTCaches.`cache_id`';
1075
        } elseif ($options['searchtype'] == 'bynofilter') {
1076
            $sql_select[] = '`caches`.`cache_id` `cache_id`';
1077
            $sql_from = '`caches`';
1078
        } elseif ($options['searchtype'] == 'bylist') {
1079
            sql_temp_table_slave('result_caches');
1080
            $list = new cachelist($options['listid']);
1081
            if ($list->allowView($options['cachelist_pw'])) {
1082
                $cachesFilter =
1083
                    "CREATE TEMPORARY TABLE &result_caches ENGINE=MEMORY
1084
                        SELECT `cache_id`
1085
                        FROM `cache_list_items`
1086
                        LEFT JOIN `cache_lists` ON `cache_lists`.`id`=`cache_list_items`.`cache_list_id`
1087
                        WHERE `cache_list_id`='" . sql_escape($options['listid']) . "'";
1088
                sql_slave($cachesFilter);
1089
                sql_slave('ALTER TABLE &result_caches ADD PRIMARY KEY (`cache_id`)');
1090
1091
                $sql_select[] = '&result_caches.`cache_id`';
1092
                $sql_from = '&result_caches';
1093
                $sql_innerjoin[] = '`caches` ON `caches`.`cache_id`=&result_caches.`cache_id`';
1094
            } else {
1095
                // should not happen, but just for the case ...
1096
                $sql_select[] = '`caches`.`cache_id` `cache_id`';
1097
                $sql_from = '`caches`';
1098
                $sql_where[] = 'FALSE';
1099
            }
1100
        } else {
1101
            if ($options['searchtype'] == 'all') {
1102
                $sql_select[] = '`caches`.`cache_id` `cache_id`';
1103
                $sql_from = '`caches`';
1104
                $sql_where[] = 'TRUE';
1105
            } else {
1106
                $tpl->error($unknown_searchtype);
1107
            }
1108
        }
1109
1110
        // additional options
1111
        if (!isset($options['f_userowner'])) {
1112
            $options['f_userowner'] = '0';
1113
        }
1114
        if ($options['f_userowner'] != 0) {  // Ocprop
1115
            $sql_where[] = '`caches`.`user_id`!=\'' . $login->userid . '\'';
1116
        }
1117
1118
        if (!isset($options['f_userfound'])) {
1119
            $options['f_userfound'] = '0';
1120
        }
1121
        if ($options['f_userfound'] != 0) {  // Ocprop
1122
            $sql_where[] =
1123
                "`caches`.`cache_id` NOT IN
1124
                    (SELECT `cache_logs`.`cache_id`
1125
                     FROM `cache_logs`
1126
                     WHERE
1127
                        `cache_logs`.`user_id`='" . sql_escape($login->userid) . "'
1128
                        AND `cache_logs`.`type` IN (1, 7))";
1129
        }
1130
        if (!isset($options['f_inactive'])) {
1131
            $options['f_inactive'] = '0';
1132
        }
1133
        if ($options['f_inactive'] != 0) {  // Ocprop
1134
            $sql_where[] = '`caches`.`status` NOT IN (3,6,7)';
1135
        }
1136
        // f_inactive formerly was used for both, archived and disabled caches.
1137
        // After adding the separate f_disabled option, it is used only for archived
1138
        // caches, but keeps its name for compatibility with existing stored or
1139
        // external searches.
1140
        if (!isset($options['f_disabled'])) {
1141
            $options['f_disabled'] = '0';
1142
        }
1143
        if ($options['f_disabled'] != 0) {
1144
            $sql_where[] = '`caches`.`status`<>2';
1145
        }
1146
1147
        if ($login->logged_in()) {
1148
            if (!isset($options['f_ignored'])) {
1149
                $options['f_ignored'] = '0';
1150
            }
1151
            if ($options['f_ignored'] != 0) {
1152
                // only use this filter, if it is really needed
1153
                // this enables better caching in map2.php with ignored-filter
1154
                if (sql_value_slave(
1155
                    "SELECT COUNT(*) FROM `cache_ignore` WHERE `user_id`='" . sql_escape($login->userid) . "'",
1156
                    0
1157
                ) > 0) {
1158
                    $sql_where[] =
1159
                        "`caches`.`cache_id` NOT IN
1160
                            (SELECT `cache_ignore`.`cache_id`
1161
                             FROM `cache_ignore`
1162
                             WHERE `cache_ignore`.`user_id`='" . sql_escape($login->userid) . "')";
1163
                }
1164
            }
1165
        }
1166
        if (!isset($options['f_otherPlatforms'])) {
1167
            $options['f_otherPlatforms'] = '0';
1168
        }
1169
        if ($options['f_otherPlatforms'] != 0) {
1170
            $sql_where[] = "`caches`.`wp_gc_maintained`=''";
1171
        }
1172
1173
        if (!isset($options['f_geokrets'])) {
1174
            $options['f_geokrets'] = '0';
1175
        }
1176
        if ($options['f_geokrets'] != 0) {
1177
            $sql_where[] = "(SELECT COUNT(*) FROM `gk_item_waypoint` WHERE `wp`=`caches`.`wp_oc`)";
1178
        }
1179
1180
        if (!isset($options['country'])) {
1181
            $options['country'] = '';
1182
        }
1183
        if ($options['country'] != '') {
1184
            $sql_where[] = '`caches`.`country`=\'' . sql_escape($options['country']) . '\'';
1185
        }
1186
1187
        if (!isset($options['language'])) {
1188
            $options['language'] = '';
1189
        }
1190
        if ($options['language'] != '') {
1191
            /*
0 ignored issues
show
Unused Code Comprehensibility introduced by
57% of this comment could be valid code. Did you maybe forget this after debugging?

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

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

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

Loading history...
1192
            $sql_innerjoin[] = '`cache_desc` ON `cache_desc`.`cache_id`=`caches`.`cache_id`';
1193
            $sql_where[] = '`cache_desc`.`language`=\'' . sql_escape($options['language']) . '\'';
1194
            */
1195
            // optimized query:
1196
            $sql_where[] = 'INSTR(`caches`.`desc_languages`,\'' . sql_escape($options['language']) . '\')';
1197
        }
1198
1199
        if (!isset($options['adm2'])) {
1200
            $options['adm2'] = '';
1201
        }
1202 View Code Duplication
        if ($options['adm2'] != '') {
1203
            $sql_innerjoin[] = '`cache_location` ON `cache_location`.`cache_id`=`caches`.`cache_id`';
1204
            $sql_where[] = '`cache_location`.`code2`=\'' . sql_escape($options['adm2']) . '\'';
1205
        }
1206
1207 View Code Duplication
        if ($options['cachetype'] != '') {
1208
            $types = explode(';', $options['cachetype']);
1209
            if (count($types) < sql_value_slave("SELECT COUNT(*) FROM `cache_type`", 0)) {
1210
                $countTypes = count($types);
1211
                for ($i = 0; $i < $countTypes; $i++) {
1212
                    $types[$i] = "'" . sql_escape($types[$i]) . "'";
1213
                }
1214
                $sql_where[] = '`caches`.`type` IN (' . implode(',', $types) . ')';
1215
            }
1216
        }
1217
1218 View Code Duplication
        if ($options['cachesize'] != '') {
1219
            $sizes = explode(';', $options['cachesize']);
1220
            if (count($sizes) < sql_value_slave('SELECT COUNT(*) FROM `cache_size`', 0)) {
1221
                $countSizes = count($sizes);
1222
                for ($i = 0; $i < $countSizes; $i++) {
1223
                    $sizes[$i] = "'" . sql_escape($sizes[$i]) . "'";
1224
                }
1225
                $sql_where[] = '`caches`.`size` IN (' . implode(',', $sizes) . ')';
1226
            }
1227
        }
1228
1229
        if ($options['difficultymin'] != 0) {
1230
            $sql_where[] = '`caches`.`difficulty`>=\'' . sql_escape($options['difficultymin']) . '\'';
1231
        }
1232
        if ($options['difficultymax'] != 0) {
1233
            $sql_where[] = '`caches`.`difficulty`<=\'' . sql_escape($options['difficultymax']) . '\'';
1234
        }
1235
        if ($options['terrainmin'] != 0) {
1236
            $sql_where[] = '`caches`.`terrain`>=\'' . sql_escape($options['terrainmin']) . '\'';
1237
        }
1238
        if ($options['terrainmax'] != 0) {
1239
            $sql_where[] = '`caches`.`terrain`<=\'' . sql_escape($options['terrainmax']) . '\'';
1240
        }
1241 View Code Duplication
        if ($options['recommendationmin'] > 0) {
1242
            $sql_innerjoin[] = '`stat_caches` ON `caches`.`cache_id`=`stat_caches`.`cache_id`';
1243
            $sql_where[] = '`stat_caches`.`toprating`>=\'' . sql_escape($options['recommendationmin']) . '\'';
1244
        }
1245
1246
        if (isset($options['cache_attribs']) && count($options['cache_attribs']) > 0) {
1247
            foreach ($options['cache_attribs'] as $attr) {
1248
                $sql_innerjoin[] = '`caches_attributes` AS `a' . ($attr + 0) . '` ON `a' .
1249
                    ($attr + 0) . '`.`cache_id`=`caches`.`cache_id`';
1250
                $sql_where[] = '`a' . ($attr + 0) . '`.`attrib_id`=' . ($attr + 0);
1251
            }
1252
        }
1253
1254
        if (isset($options['cache_attribs_not']) && count($options['cache_attribs_not']) > 0) {
1255
            foreach ($options['cache_attribs_not'] as $attr) {
1256
                $sql_where[] =
1257
                    "NOT EXISTS
1258
                        (SELECT `caches_attributes`.`cache_id`
1259
                         FROM `caches_attributes`
1260
                         WHERE
1261
                            `caches_attributes`.`cache_id`=`caches`.`cache_id`
1262
                            AND `caches_attributes`.`attrib_id`='" . sql_escape($attr + 0) . "'
1263
                        )";
1264
            }
1265
        }
1266
1267
        if (isset($options['bbox']) && ($options['bbox'] !== false)) {
1268
            // bbox=<lon_from>,<lat_from>,<lon_to>,<lat_to>
1269
            $coords = explode(',', $options['bbox']);
1270
            if (count($coords) == 4) {
1271
                $sql_where[] = '`caches`.`longitude`>=' . ($coords[0] + 0) . ' AND `caches`.`latitude`>=' .
1272
                    ($coords[1] + 0) . ' AND `caches`.`longitude`<=' . ($coords[2] + 0) .
1273
                    ' AND `caches`.`latitude`<=' . ($coords[3] + 0);
1274
            }
1275
        }
1276
1277
        $sql_innerjoin[] = '`cache_status` ON `caches`.`status`=`cache_status`.`id`';
1278
        if ($login->logged_in()) {
1279
            $sql_where[] =
1280
                '(`cache_status`.`allow_user_view`=1 OR `caches`.`user_id`='
1281
                . sql_escape($login->userid)
1282
                . ' OR (`caches`.`status`<>5 AND ' . ($login->hasAdminPriv(ADMIN_USER) ? '1' : '0') . '))';
1283
        } else {
1284
            $sql_where[] = '`cache_status`.`allow_user_view`=1';
1285
        }
1286
1287
        // do the search
1288
        $innerjoin = sizeof($sql_innerjoin) ? ' INNER JOIN ' . implode(' INNER JOIN ', $sql_innerjoin) : '';
1289
        $leftjoin = sizeof($sql_leftjoin) ? ' LEFT JOIN ' . implode(' LEFT JOIN ', $sql_leftjoin) : '';
1290
        $group = sizeof($sql_group) ? ' GROUP BY ' . implode(', ', $sql_group) : '';
1291
        $having = sizeof($sql_having) ? ' HAVING ' . implode(' AND ', $sql_having) : '';
1292
1293
        $sqlFilter = 'SELECT ' . implode(',', $sql_select) .
1294
            ' FROM ' . $sql_from .
1295
            $innerjoin .
1296
            $leftjoin .
1297
            ' WHERE ' . implode(' AND ', $sql_where) .
1298
            $group .
1299
            $having;
1300
1301
        // echo "DEBUG ".$sqlFilter." DEBUG<br>";
1302
    } else {
1303
        $tpl->error($unknown_searchtype);
1304
    }
1305
1306
    //=================================================================
1307
    //  X6. load output module and output-dependent options
1308
    //=================================================================
1309
1310
    $output_module = mb_strtolower($options['output']); // Ocprop: HTML, gpx
1311
1312
    $map2_bounds = ($output_module == 'map2bounds');
1313
    if ($map2_bounds) {
1314
        $output_module = 'map2';
1315
    }
1316
1317
    if ($map2_bounds && $options['queryid'] == 0) {
1318
        $tpl->error('map2bounds requires queryid');
1319
    } elseif (!file_exists(__DIR__ . '/lib2/search/search.' . $output_module . '.inc.php')) {
1320
        $tpl->error($outputformat_notexist);
1321
    }
1322
1323
    $caches_per_page = 20;
1324
1325
    // Default parameters; may be modified by output modules
1326
    $content_type_plain = 'application/octet-stream';
1327
    $content_type_zipped = 'application/zip';
1328
    $zip_threshold = $caches_per_page;
1329
    $add_to_zipfile = true;
1330
    $sAddJoin = '';
1331
    $sAddGroupBy = '';
1332
    $sAddFields = '';
1333
    $sAddWhere = '';
1334
    $sGroupBy = '';
1335
1336
    // disallow mapping other users' logs for data protection reasons
1337
    $enable_mapdisplay = ($options['searchtype'] != 'byfinder') ||
1338
        ($options['finderid'] == $login->userid);
1339
1340
    // *** load output module ***
1341
    //
1342
    // (map2 module will execute and exit; it will use the variables
1343
    // $cachesFilter, $sqlFilter and $map2_bounds and $options['queryid'].)
1344
1345
    require __DIR__ . '/lib2/search/search.' . $output_module . '.inc.php';
1346
1347
    if (!isset($search_output_file_download)) {
1348
        die("search_output_file_download flag not set for '$output_module' search");
1349
    }
1350
1351
    //=================================================================
1352
    //  X7. complete SQL statement with output-dependend options,
1353
    //      sorting and Limits
1354
    //=================================================================
1355
1356
    $sql = '';
1357
1358
    // If no distance unit is preselected by distance search, use 'km'.
1359
    // The unit will be shown e.g. in HTML and XML search results.
1360
    if (!isset($distance_unit)) {
1361
        $distance_unit = DEFAULT_DISTANCE_UNIT;
1362
    }
1363
1364
    if (isset($lat_rad) && isset($lon_rad)) {
1365
        $sql .= geomath::getSqlDistanceFormula(
1366
            $lon_rad * 180 / 3.14159,
1367
            $lat_rad * 180 / 3.14159,
1368
            0,
1369
            $multiplier[$distance_unit]
1370
        ) . ' `distance`, ';
1371
    } else {
1372
        if (!$login->logged_in()) {
1373
            $sql .= 'NULL distance, ';
1374
        } else {
1375
            // get the user's home coords
1376
            $rs_coords = sql_slave(
1377
                "SELECT `latitude`, `longitude` FROM `user` WHERE `user_id`='&1'",
1378
                $login->userid
1379
            );
1380
            $record_coords = sql_fetch_array($rs_coords);
1381
1382
            if ($record_coords['latitude'] == 0 && $record_coords['longitude'] == 0) {
1383
                $sql .= 'NULL distance, ';
1384
            } else {
1385
                $lon_rad = $record_coords['longitude'] * 3.14159 / 180;
1386
                $lat_rad = $record_coords['latitude'] * 3.14159 / 180;
1387
1388
                $sql .= geomath::getSqlDistanceFormula(
1389
                    $record_coords['longitude'],
1390
                    $record_coords['latitude'],
1391
                    0,
1392
                    $multiplier[$distance_unit]
1393
                ) . ' `distance`, ';
1394
            }
1395
            sql_free_result($rs_coords);
1396
        }
1397
    }
1398
1399
    if ($options['sort'] == 'bylastlog' || $options['sort'] == 'bymylastlog') {
1400
        $sAddFields .= ', MAX(`cache_logs`.`date`) AS `lastLog`';
1401
        $sAddJoin .= ' LEFT JOIN `cache_logs` ON `caches`.`cache_id`=`cache_logs`.`cache_id`';
1402
        if ($options['sort'] == 'bymylastlog') {
1403
            $sAddJoin .= ' AND `cache_logs`.`user_id`=' . sql_escape($login->userid);
1404
        }
1405
        $sGroupBy .= ' GROUP BY `caches`.`cache_id`';
1406
    }
1407
1408
    $sql .= '`caches`.`cache_id`,
1409
                             `caches`.`status`,
1410
                             `caches`.`type`,
1411
                             `caches`.`size`,
1412
                             `caches`.`longitude`, `caches`.`latitude`,
1413
                             `caches`.`user_id`,
1414
                             IFNULL(`stat_caches`.`toprating`, 0) `ratingvalue`' .
1415
        $sAddFields
1416
        . ' FROM `caches`
1417
          LEFT JOIN `stat_caches` ON `caches`.`cache_id`=`stat_caches`.`cache_id`' .
1418
        $sAddJoin
1419
        . ' WHERE `caches`.`cache_id` IN (' . $sqlFilter . ')' .
1420
        $sAddWhere . ' ' .
1421
        $sGroupBy;
1422
    $sortby = $options['sort'];
1423
1424
    $sql .= ' ORDER BY ';
1425
    if ($options['orderRatingFirst']) {
1426
        $sql .= '`ratingvalue` DESC, ';
1427
    }
1428
1429
    if ($sortby == 'bylastlog' || $options['sort'] == 'bymylastlog') {
1430
        $sql .= '`lastLog`';
1431 View Code Duplication
        if (isset($options['sortorder']) && $options['sortorder'] == 'asc') {
1432
            $sql .= ' ASC, `caches`.`date_created` DESC,';
1433
        } else {
1434
            $sql .= ' DESC, `caches`.`date_created` DESC,';
1435
        }
1436
        $sortby = 'bydistance';
1437
    }
1438
1439
    if (isset($lat_rad) && isset($lon_rad) && $sortby == 'bydistance') {
1440
        $sql .= '`distance`';
1441 View Code Duplication
        if (isset($options['sortorder']) && $options['sortorder'] == 'desc') {
1442
            $sql .= ' DESC';
1443
        } else {
1444
            $sql .= ' ASC';
1445
        }
1446
    } else {
1447
        if ($sortby == 'bycreated') {
1448
            $sql .= '`caches`.`date_created`';
1449 View Code Duplication
            if (isset($options['sortorder']) && $options['sortorder'] == 'asc') {
1450
                $sql .= ' ASC';
1451
            } else {
1452
                $sql .= ' DESC';
1453
            }
1454 View Code Duplication
        } else { // by name
1455
            $sql .= '`caches`.`name`';
1456
            if (isset($options['sortorder']) && $options['sortorder'] == 'desc') {
1457
                $sql .= ' DESC';
1458
            } else {
1459
                $sql .= ' ASC';
1460
            }
1461
        }
1462
    }
1463
1464
    // range of output
1465
    $startat = isset($_REQUEST['startat']) ? floor($_REQUEST['startat'] + 0) : 0;
1466
    if (!is_numeric($startat)) {
1467
        $startat = 0;
1468
    }
1469
1470
    $count = $caches_per_page;
1471
    if (isset($_REQUEST['count'])) { // Ocprop
1472
        $count = floor($_REQUEST['count'] + 0);
1473
    }
1474
    if ($count == 'max') {
1475
        $count = 500;
1476
    }
1477
    if ($count < 1) {
1478
        $count = 1;
1479
    }
1480
    if ($count > 500) {
1481
        $count = 500;
1482
    }
1483
1484
    $sqlLimit = ' LIMIT ' . $startat . ', ' . $count;
1485
1486
    if ($search_output_file_download) {
1487
        //===================================================================
1488
        //  X8a. run query and output for file downloads (GPX, KML, OVL ...)
1489
        //===================================================================
1490
1491
        sql_drop_temp_table_slave('searchtmp');
1492
        // for the case something went wrong and it was not propery cleaned up
1493
1494
        sql_temp_table_slave('searchtmp');
1495
        sql_slave("CREATE TEMPORARY TABLE &searchtmp SELECT " . $sql . $sqlLimit);
1496
1497
        $count = sql_value_slave("SELECT COUNT(*) FROM &searchtmp", 0);
1498
        if ($count == 1) {
1499
            $sFilebasename = sql_value_slave(
1500
                "SELECT `caches`.`wp_oc`
1501
                 FROM &searchtmp, `caches`
1502
                 WHERE &searchtmp.`cache_id`=`caches`.`cache_id`
1503
                 LIMIT 1",
1504
                '?'
1505
            );
1506
        } else {
1507
            $sFilebasename = 'ocde' . $options['queryid'];
1508
        }
1509
1510
        $bUseZip = ($count > $zip_threshold) ||
1511
            (isset($_REQUEST['zip']) && ($_REQUEST['zip'] == '1'));
1512
        if ($bUseZip) {
1513
            $phpzip = new ss_zip('', 6);
1514
        }
1515
1516
        if (!$db['debug']) {
1517
            if ($bUseZip) {
1518
                header('Content-type: ' . $content_type_zipped);
1519
                header('Content-disposition: attachment; filename="' . $sFilebasename . '.zip"');
1520
            } else {
1521
                header('Content-type: ' . $content_type_plain);
1522
                header('Content-disposition: attachment; filename="' . $sFilebasename . '.' . $output_module . '"');
1523
            }
1524
        }
1525
1526
        // helper function for output modules
1527
1528
        /**
1529
         * @param string $str
1530
         */
1531
        function append_output($str)
1532
        {
1533
            global $db, $content, $bUseZip;
1534
1535
            if (!$db['debug']) {
1536
                if ($bUseZip) {
1537
                    $content .= $str;
1538
                } else {
1539
                    echo $str;
1540
                }
1541
            }
1542
        }
1543
1544
        // *** run output module ***
1545
        //
1546
        // Modules will use these variables from search.php:
1547
        //
1548
        //   $phpzip
1549
        //   $bUseZip
1550
1551
        $content = '';
1552
        search_output();
1553
1554
        sql_drop_temp_table_slave('searchtmp');
1555
1556
        // output zip file
1557
        if ($bUseZip && !$db['debug']) {
1558
            if ($add_to_zipfile) {
1559
                $phpzip->add_data($sFilebasename . '.' . $output_module, $content);
1560
            }
1561
            echo $phpzip->save($sFilebasename . '.zip', 'r');
1562
        }
1563
    } else {
1564
        //===================================================================
1565
        //  X8b. run other output module (XML, HTML)
1566
        //
1567
        //  The following variables from search.php are used by output modules:
1568
        //
1569
        //      $called_by_search
1570
        //      $called_by_profile_query
1571
        //      $distance_unit
1572
        //      $lat_rad, $lon_rad
1573
        //      $startat
1574
        //      $count
1575
        //      $caches_per_page
1576
        //      $sql
1577
        //      $sqlLimit
1578
        //      $options['sort']
1579
        //      $options['sortorder']
1580
        //      $options['creationdate']
1581
        //      $options['queryid']
1582
        //      $options['query_name']
1583
        //      $enable_mapdisplay
1584
        //      $invalid_waypoints
1585
        //=================================================================
1586
1587
        search_output();
1588
    }
1589
1590
    if ($db['debug']) {
1591
        $tpl->display();
1592
    } else {
1593
        exit;
1594
    }
1595
} else { // $options['showresult'] == 0
1596
    //=============================================================
1597
    //  F5. present search options form to the user
1598
    //=============================================================
1599
1600
    if ($options['expert'] == 1) {
1601
        // "expert mode" - what is this?
1602
        $tpl->assign('formmethod', 'post');
1603
        $tpl->display();
1604
    } else {
1605
        outputSearchForm($options);
1606
    }
1607
}
1608
1609
1610
//=============================================================
1611
//  F6. build and output search options form
1612
//=============================================================
1613
1614
function sqlStringbySearchradius($distance, $lat, $lon, $multiplier, $distance_unit)
1615
{
1616
    global $sql_select, $sql_from, $sql_innerjoin;
1617
1618
    //all target caches are between lat - max_lat_diff and lat + max_lat_diff
1619
    $max_lat_diff = $distance / (111.12 * $multiplier[$distance_unit]);
1620
1621
    //all target caches are between lon - max_lon_diff and lon + max_lon_diff
1622
    //TODO: check!!!
1623
    $max_lon_diff =
1624
        $distance * 180
1625
        / (abs(sin((90 - $lat) * 3.14159 / 180)) * 6378 * $multiplier[$distance_unit] * 3.14159);
1626
1627
    $lon_rad = $lon * 3.14159 / 180;
1628
    $lat_rad = $lat * 3.14159 / 180;
1629
1630
    sql_temp_table_slave('result_caches');
1631
    $cachesFilter =
1632
        "CREATE TEMPORARY TABLE &result_caches ENGINE=MEMORY
1633
            SELECT
1634
                (" . geomath::getSqlDistanceFormula($lon, $lat, $distance, $multiplier[$distance_unit]) . ") `distance`,
1635
                `caches`.`cache_id` `cache_id`
1636
            FROM `caches` FORCE INDEX (`latitude`)
1637
            WHERE
1638
                `longitude` > " . ($lon - $max_lon_diff) . "
1639
                AND `longitude` < " . ($lon + $max_lon_diff) . "
1640
                AND `latitude` > " . ($lat - $max_lat_diff) . "
1641
                AND `latitude` < " . ($lat + $max_lat_diff) . "
1642
            HAVING `distance` < " . ($distance + 0);
1643
    sql_slave($cachesFilter);
1644
    sql_slave("ALTER TABLE &result_caches ADD PRIMARY KEY ( `cache_id` )");
1645
1646
    $sql_select[] = '&result_caches.`cache_id`';
1647
    $sql_from = '&result_caches';
1648
    $sql_innerjoin[] = '`caches` ON `caches`.`cache_id`=&result_caches.`cache_id`';
1649
}
1650
1651
function outputSearchForm($options)
1652
{
1653
    global $tpl, $login, $opt;
1654
    global $error_ort, $error_plz, $error_locidnocoords, $error_nowaypointfound;
1655
    global $error_nocoords, $error_nofulltext, $error_fulltexttoolong;
1656
    global $cache_attrib_jsarray_line, $cache_attrib_group, $cache_attrib_img_line1, $cache_attrib_img_line2;
1657
    global $load_query, $show_lastsearchbutton;
1658
1659
    $tpl->assign('formmethod', 'get');
1660
1661
    $tpl->assign('logged_in', $login->logged_in());
1662
    $tpl->assign('load_query', $load_query == false);
1663
    $tpl->assign('show_lastsearchbutton', $show_lastsearchbutton == true);
1664
1665
    //sort search by (radio button + 1 checkbox)
1666
1667
    if (isset($options['sort'])) {
1668
        $bBynameChecked = ($options['sort'] == 'byname');
1669
    } else { // Ocprop
1670
        $bBynameChecked = (!$login->logged_in());
1671
    }
1672
    $tpl->assign('byname_checked', $bBynameChecked);
1673
1674
    if (isset($options['sort'])) {
1675
        $bBydistanceChecked = ($options['sort'] == 'bydistance');
1676
    } else {
1677
        $bBydistanceChecked = ($login->logged_in());
1678
    }
1679
    $tpl->assign('bydistance_checked', $bBydistanceChecked);
1680
1681
    if (isset($options['sort'])) {
1682
        $bBycreatedChecked = ($options['sort'] == 'bycreated');
1683
    } else {
1684
        $bBycreatedChecked = (!$login->logged_in());
1685
    }
1686
    $tpl->assign('bycreated_checked', $bBycreatedChecked);
1687
1688
    if (isset($options['sort'])) {
1689
        $bBylastlogChecked = ($options['sort'] == 'bylastlog');
1690
    } else {
1691
        $bBylastlogChecked = ($login->logged_in());
1692
    }
1693
    $tpl->assign('bylastlog_checked', $bBylastlogChecked);
1694
1695
    if (isset($options['sort'])) {
1696
        $bBymylastlogChecked = ($options['sort'] == 'bymylastlog');
1697
    } else {
1698
        $bBymylastlogChecked = ($login->logged_in());
1699
    }
1700
    $tpl->assign('bymylastlog_checked', $bBymylastlogChecked);
1701
1702
    $tpl->assign('hidopt_sort', $options['sort']);
1703
1704
    $tpl->assign('orderRatingFirst_checked', $options['orderRatingFirst']);
1705
    $tpl->assign('hidopt_orderRatingFirst', $options['orderRatingFirst'] ? '1' : '0');
1706
1707
    //hide caches... (checkboxes)
1708
1709
    $tpl->assign('f_userowner_checked', $login->logged_in() && ($options['f_userowner'] == 1));
1710
    $tpl->assign('hidopt_userowner', ($options['f_userowner'] == 1) ? '1' : '0');
1711
1712
    $tpl->assign('f_userfound_checked', $login->logged_in() && ($options['f_userfound'] == 1));
1713
    $tpl->assign('hidopt_userfound', ($options['f_userfound'] == 1) ? '1' : '0');
1714
1715
    $tpl->assign('f_ignored_checked', $login->logged_in() && ($options['f_ignored'] == 1));
1716
    $tpl->assign('hidopt_ignored', ($options['f_ignored'] == 1) ? '1' : '0');
1717
1718
    $tpl->assign('f_disabled_checked', $options['f_disabled'] == 1);
1719
    $tpl->assign('hidopt_disabled', ($options['f_disabled'] == 1) ? '1' : '0');
1720
1721
    // archived is called "disabled" here for backward compatibility
1722
    $tpl->assign('f_inactive_checked', $options['f_inactive'] == 1);
1723
    $tpl->assign('hidopt_inactive', ($options['f_inactive'] == 1) ? '1' : '0');
1724
1725
    $tpl->assign('f_otherPlatforms_checked', $options['f_otherPlatforms'] == 1);
1726
    $tpl->assign('hidopt_otherPlatforms', ($options['f_otherPlatforms'] == 1) ? '1' : '0');
1727
1728
    $tpl->assign('f_geokrets_checked', $options['f_geokrets'] == 1);
1729
    $tpl->assign('hidopt_geokrets', ($options['f_geokrets'] == 1) ? '1' : '0');
1730
1731
    if (!isset($options['country'])) {
1732
        $options['country'] = '';
1733
    }
1734
    $tpl->assign('country', htmlspecialchars($options['country'], ENT_COMPAT, 'UTF-8'));
1735
1736
    if (!isset($options['language'])) {
1737
        $options['language'] = '';
1738
    }
1739
    $tpl->assign('language', htmlspecialchars($options['language'], ENT_COMPAT, 'UTF-8'));
1740
1741
    if (isset($options['cachetype'])) {
1742
        $tpl->assign('cachetype', htmlspecialchars($options['cachetype'], ENT_COMPAT, 'UTF-8'));
1743
    } else {
1744
        $tpl->assign('cachetype', '');
1745
    }
1746
1747
    // cachename
1748
    $tpl->assign(
1749
        'cachename',
1750
        isset($options['cachename']) ? htmlspecialchars($options['cachename'], ENT_COMPAT, 'UTF-8') : ''
1751
    );
1752
    $tpl->assign('searchtype_byname', $options['searchtype'] == 'byname');
1753
1754
    // distance
1755
    $tpl->assign('distance', isset($options['distance']) ? $options['distance'] : DEFAULT_SEARCH_DISTANCE);
1756
1757
    if (!isset($options['unit'])) {
1758
        $options['unit'] = DEFAULT_DISTANCE_UNIT;
1759
    }
1760
    $tpl->assign('sel_km', $options['unit'] == 'km');
1761
    $tpl->assign('sel_sm', $options['unit'] == 'sm');
1762
    $tpl->assign('sel_nm', $options['unit'] == 'nm');
1763
1764
    // ... from ortplz
1765
    if (isset($options['ortplz'])) {
1766
        $ortplz = htmlspecialchars($options['ortplz'], ENT_COMPAT, 'UTF-8');
1767
    } elseif (isset($options['ort'])) {
1768
        $ortplz = htmlspecialchars($options['ort'], ENT_COMPAT, 'UTF-8');
1769
    } elseif (isset($options['plz'])) {
1770
        $ortplz = htmlspecialchars($options['plz'], ENT_COMPAT, 'UTF-8');
1771
    } else {
1772
        $ortplz = '';
1773
    }
1774
    $tpl->assign('ortplz', $ortplz);
1775
1776
    // ... from waypoint
1777
    $tpl->assign(
1778
        'waypoint',
1779
        isset($options['waypoint']) ? htmlspecialchars($options['waypoint'], ENT_COMPAT, 'UTF-8') : ''
1780
    );
1781
1782
    // ... from coords
1783
    if (!isset($options['lat_h'])) {
1784
        if ($login->logged_in()) {
1785
            $rs = sql(
1786
                "SELECT `latitude`, `longitude`
1787
                 FROM `user`
1788
                 WHERE `user_id`='" . sql_escape($login->userid) . "'"
1789
            );
1790
            $record = sql_fetch_array($rs);
1791
            $lon = $record['longitude'];
1792
            $lat = $record['latitude'];
1793
            sql_free_result($rs);
1794
1795
            $tpl->assign('lonE_sel', $lon >= 0);
1796
            $tpl->assign('lonW_sel', $lon < 0);
1797
            $tpl->assign('latN_sel', $lat >= 0);
1798
            $tpl->assign('latS_sel', $lat < 0);
1799
1800
            $lon_h = floor($lon);
1801
            $lat_h = floor($lat);
1802
1803
            $lon_min = ($lon - $lon_h) * 60;
1804
            $lat_min = ($lat - $lat_h) * 60;
1805
1806
            if ($lat < 0 && $lat_h < 0) {
1807
                $lat_min = 60 - $lat_min;
1808
            }
1809
            if ($lon < 0 && $lon_h < 0) {
1810
                $lon_min = 60 - $lon_min;
1811
            }
1812
1813
            $tpl->assign('lat_min', sprintf('%02.3f', $lat_min));
1814
            $tpl->assign('lon_min', sprintf('%02.3f', $lon_min));
1815
1816
            if ($lat < 0 && $lat_h < 0) {
1817
                $lat_h = - $lat_h;
1818
                if ($lat_min != 0) {
1819
                    $lat_h = $lat_h - 1;
1820
                }
1821
            }
1822
            if ($lon < 0 && $lon_h < 0) {
1823
                $lon_h = - $lon_h;
1824
                if ($lon_min != 0) {
1825
                    $lon_h = $lon_h - 1;
1826
                }
1827
            }
1828
            $tpl->assign('lat_h', $lat_h);
1829
            $tpl->assign('lon_h', $lon_h);
1830
        } else {
1831
            $tpl->assign('lat_h', '00');
1832
            $tpl->assign('lon_h', '000');
1833
            $tpl->assign('lat_min', '00.000');
1834
            $tpl->assign('lon_min', '00.000');
1835
        }
1836
    } else {
1837
        $tpl->assign('lat_h', isset($options['lat_h']) ? $options['lat_h'] : '00');
1838
        $tpl->assign('lon_h', isset($options['lon_h']) ? $options['lon_h'] : '000');
1839
        $tpl->assign('lat_min', isset($options['lat_min']) ? $options['lat_min'] : '00.000');
1840
        $tpl->assign('lon_min', isset($options['lon_min']) ? $options['lon_min'] : '00.000');
1841
1842
        if ($options['lonEW'] == 'W') {
1843
            $tpl->assign('lonE_sel', '');
1844
            $tpl->assign('lonW_sel', 'selected="selected"');
1845
        } else {
1846
            $tpl->assign('lonE_sel', 'selected="selected"');
1847
            $tpl->assign('lonW_sel', '');
1848
        }
1849
1850
        if ($options['latNS'] == 'S') {
1851
            $tpl->assign('latS_sel', 'selected="selected"');
1852
            $tpl->assign('latN_sel', '');
1853
        } else {
1854
            $tpl->assign('latS_sel', '');
1855
            $tpl->assign('latN_sel', 'selected="selected"');
1856
        }
1857
    }
1858
1859
    $dfromortplz_checked = in_array($options['searchtype'], ['byplz', 'byort']);
1860
    $dfromwaypoint_checked = ($options['searchtype'] == 'bywaypoint');
1861
    $dfromcoords_checked = ($options['searchtype'] == 'bycoords');
1862
    if (!$dfromortplz_checked && !$dfromwaypoint_checked && !$dfromcoords_checked) {
1863
        $dfromcoords_checked = true; // default
1864
    }
1865
    $tpl->assign('dfromortplz_checked', $dfromortplz_checked);
1866
    $tpl->assign('dfromwaypoint_checked', $dfromwaypoint_checked);
1867
    $tpl->assign('dfromcoords_checked', $dfromcoords_checked);
1868
1869
    $tpl->assign('searchtype_byortplz', in_array($options['searchtype'], ['byplz', 'byort']));
1870
    $tpl->assign('searchtype_bywaypoint', $options['searchtype'] == 'bywaypoint');
1871
    $tpl->assign('searchtype_bycoords', $options['searchtype'] == 'bycoords');
1872
    
1873
    // owner
1874
    $tpl->assign('owner', isset($options['owner']) ? htmlspecialchars($options['owner'], ENT_COMPAT, 'UTF-8') : '');
1875
    $tpl->assign('searchtype_byowner', $options['searchtype'] == 'byowner');
1876
1877
    // finder
1878
    $tpl->assign('finder', isset($options['finder']) ? htmlspecialchars($options['finder'], ENT_COMPAT, 'UTF-8') : '');
1879
    $tpl->assign('searchtype_byfinder', $options['searchtype'] == 'byfinder');
1880
1881
    // country options
1882
    $rs = sql(
1883
        "SELECT IFNULL(`sys_trans_text`.`text`, `countries`.`name`) AS `name`,
1884
                `countries`.`short`,
1885
                `countries`.`short`='&2' AS `selected`
1886
         FROM `countries`
1887
         LEFT JOIN `sys_trans`
1888
           ON `countries`.`trans_id`=`sys_trans`.`id`
1889
           AND `sys_trans`.`text`=`countries`.`name`
1890
         LEFT JOIN `sys_trans_text`
1891
           ON `sys_trans`.`id`=`sys_trans_text`.`trans_id`
1892
           AND `sys_trans_text`.`lang`='&1'
1893
         WHERE `countries`.`short` IN (SELECT DISTINCT `country` FROM `caches`)
1894
         ORDER BY `name` ASC",
1895
        $opt['template']['locale'],
1896
        $options['country']
1897
    );
1898
    $tpl->assign_rs('countryoptions', $rs);
1899
    sql_free_result($rs);
1900
    $tpl->assign('all_countries', $options['country'] == '');
1901
1902
    // language options
1903
    $rs = sql(
1904
        "SELECT IFNULL(`sys_trans_text`.`text`,`languages`.`name`) AS `name`,
1905
                `short`,
1906
                `short`='&2' AS `selected`
1907
         FROM `languages`
1908
         LEFT JOIN `sys_trans`
1909
           ON `sys_trans`.`text`=`languages`.`name`
1910
         LEFT JOIN `sys_trans_text`
1911
           ON `sys_trans_text`.`trans_id`=`sys_trans`.`id`
1912
           AND `sys_trans_text`.`lang`='&1'
1913
         ORDER BY `name`",
1914
        $opt['template']['locale'],
1915
        $options['language']
1916
    );
1917
    $tpl->assign_rs('languageoptions', $rs);
1918
    sql_free_result($rs);
1919
    $tpl->assign('all_languages', $options['language'] == '');
1920
1921
    $rs = sql('SELECT `id` FROM `cache_type` ORDER BY `ordinal`');
1922
    $rCachetypes = sql_fetch_assoc_table($rs);
1923
    foreach ($rCachetypes as &$rCachetype) {
1924
        $rCachetype['checked'] =
1925
            ($options['cachetype'] == '')
1926
            || (strpos(
1927
                ';' . $options['cachetype'] . ';',
1928
                ';' . $rCachetype['id'] . ';'
1929
            ) !== false);
1930
        $rCachetype['unchecked'] = !$rCachetype['checked'];
1931
    }
1932
    $tpl->assign('cachetypes', $rCachetypes);
1933
    $tpl->assign('cachetype', $options['cachetype']);
1934
1935
    $cachesizes = [];
1936
    $rs = sql("SELECT `id` FROM `cache_size`");
1937
    while ($r = sql_fetch_assoc($rs)) {
1938
        $cachesizes[$r['id']]['checked'] =
1939
            (strpos(
1940
                ';' . $options['cachesize'] . ';',
1941
                ';' . $r['id'] . ';'
1942
            ) !== false)
1943
            || ($options['cachesize'] == '');
1944
    }
1945
    sql_free_result($rs);
1946
    $tpl->assign('cachesizes', $cachesizes);
1947
    $tpl->assign('cachesize', $options['cachesize']);
1948
1949
    // difficulty + terrain
1950
    $tpl->assign('difficultymin', $options['difficultymin']);
1951
    $tpl->assign('difficultymax', $options['difficultymax']);
1952
    $tpl->assign('difficulty_options', [0, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
1953
    $tpl->assign('terrainmin', $options['terrainmin']);
1954
    $tpl->assign('terrainmax', $options['terrainmax']);
1955
    $tpl->assign('terrain_options', [0, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
1956
1957
    $logtypes = [];
1958
    if (isset($options['logtype'])) {
1959
        $logtypes = explode(',', $options['logtype']);
1960
    }
1961
1962
    $rs = sql(
1963
        "SELECT `id`,
1964
                IFNULL(`sys_trans_text`.`text`, `log_types`.`name`) AS `name`,
1965
                `id`='&2' AS `selected`
1966
         FROM
1967
            (SELECT `id`,`name`,`trans_id` FROM `log_types`
1968
             UNION
1969
             SELECT 0, 'all', (SELECT id FROM sys_trans WHERE `text`='all')
1970
            ) `log_types`
1971
         LEFT JOIN `sys_trans_text`
1972
           ON `sys_trans_text`.`trans_id`=`log_types`.`trans_id`
1973
           AND `sys_trans_text`.`lang`='&1'
1974
         ORDER BY `log_types`.`id` ASC",
1975
        $opt['template']['locale'],
1976
        $logtypes ? $logtypes[0] : 0
1977
    );
1978
1979
    $tpl->assign_rs('logtype_options', $rs);
1980
    sql_free_result($rs);
1981
1982
    // cache-attributes
1983
    $attributes_jsarray = '';
1984
1985
    $bBeginLine2 = true;
1986
    $nPrevLineAttrCount2 = 0;
1987
    $nLineAttrCount2 = 0;
1988
    $attributes_img2 = '';
1989
1990
    /* perpare 'all attributes' */
1991
    $rsAttrGroup = sql(
1992
        "SELECT `attribute_groups`.`id`,
1993
                IFNULL(`sys_trans_text`.`text`, `attribute_groups`.`name`) AS `name`,
1994
                `attribute_categories`.`color`
1995
         FROM `attribute_groups`
1996
         INNER JOIN `attribute_categories`
1997
           ON `attribute_groups`.`category_id`=`attribute_categories`.`id`
1998
         LEFT JOIN `sys_trans`
1999
           ON `attribute_groups`.`trans_id`=`sys_trans`.`id`
2000
           AND `sys_trans`.`text`=`attribute_groups`.`name`
2001
         LEFT JOIN `sys_trans_text`
2002
           ON `sys_trans`.`id`=`sys_trans_text`.`trans_id`
2003
           AND `sys_trans_text`.`lang`='&1'
2004
         ORDER BY `attribute_groups`.`category_id` ASC, `attribute_groups`.`id` ASC",
2005
        $opt['template']['locale']
2006
    );
2007
    while ($rAttrGroup = sql_fetch_assoc($rsAttrGroup)) {
2008
        $group_line = '';
2009
2010
        $rs = sql(
2011
            "SELECT `cache_attrib`.`id`,
2012
                    IFNULL(`ttname`.`text`, `cache_attrib`.`name`) AS `name`,
2013
                    `cache_attrib`.`icon_large`,
2014
                    `cache_attrib`.`icon_no`,
2015
                    `cache_attrib`.`icon_undef`,
2016
                    `cache_attrib`.`search_default`,
2017
                    IFNULL(`ttdesc`.`text`, `cache_attrib`.`html_desc`) AS `html_desc`
2018
             FROM `cache_attrib`
2019
             LEFT JOIN `sys_trans` AS `tname`
2020
               ON `cache_attrib`.`trans_id`=`tname`.`id`
2021
               AND `cache_attrib`.`name`=`tname`.`text`
2022
             LEFT JOIN `sys_trans_text` AS `ttname`
2023
               ON `tname`.`id`=`ttname`.`trans_id`
2024
               AND `ttname`.`lang`='&1'
2025
             LEFT JOIN `sys_trans` AS `tdesc`
2026
               ON `cache_attrib`.`html_desc_trans_id`=`tdesc`.`id`
2027
               AND `cache_attrib`.`html_desc`=`tdesc`.`text`
2028
             LEFT JOIN `sys_trans_text` AS `ttdesc`
2029
               ON `tdesc`.`id`=`ttdesc`.`trans_id`
2030
               AND `ttdesc`.`lang`='&1'
2031
             WHERE `cache_attrib`.`group_id` = '&2'
2032
               AND `selectable`
2033
               AND NOT IFNULL(`cache_attrib`.`hidden`, 0)=1
2034
             ORDER BY `cache_attrib`.`id`",
2035
            $opt['template']['locale'],
2036
            $rAttrGroup['id']
2037
        );
2038
        while ($record = sql_fetch_array($rs)) {
2039
            // icon specified
2040
            $line = $cache_attrib_jsarray_line;
2041
            $line = mb_ereg_replace('{id}', $record['id'], $line);
2042
2043
            if (!isset($options['cache_attribs'])) {
2044
                $line = mb_ereg_replace('{state}', 0, $line);
2045
            } else {
2046
                if (array_search($record['id'], $options['cache_attribs']) === false) {
2047
                    if (array_search($record['id'], $options['cache_attribs_not']) === false) {
2048
                        $line = mb_ereg_replace('{state}', 0, $line);
2049
                    } else {
2050
                        $line = mb_ereg_replace('{state}', 2, $line);
2051
                    }
2052
                } else {
2053
                    $line = mb_ereg_replace('{state}', 1, $line);
2054
                }
2055
            }
2056
2057
            $line = mb_ereg_replace('{text_long}', escape_javascript($record['name']), $line);
2058
            $line = mb_ereg_replace('{icon}', $record['icon_large'], $line);
2059
            $line = mb_ereg_replace('{icon_no}', $record['icon_no'], $line);
2060
            $line = mb_ereg_replace('{icon_undef}', $record['icon_undef'], $line);
2061
            $line = mb_ereg_replace('{search_default}', $record['search_default'], $line);
2062
            if ($attributes_jsarray != '') {
2063
                $attributes_jsarray .= ",\n";
2064
            }
2065
            $attributes_jsarray .= $line;
2066
2067
            $line = $cache_attrib_img_line1;
2068
            $line = mb_ereg_replace('{id}', $record['id'], $line);
2069
            $line = mb_ereg_replace('{text_long}', escape_javascript($record['name']), $line);
2070 View Code Duplication
            if (!isset($options['cache_attribs'])) {
2071
                $line = mb_ereg_replace('{icon}', $record['icon_undef'], $line);
2072
            } else {
2073
                if (array_search($record['id'], $options['cache_attribs']) === false) {
2074
                    if (array_search($record['id'], $options['cache_attribs_not']) === false) {
2075
                        $line = mb_ereg_replace('{icon}', $record['icon_undef'], $line);
2076
                    } else {
2077
                        $line = mb_ereg_replace('{icon}', $record['icon_no'], $line);
2078
                    }
2079
                } else {
2080
                    $line = mb_ereg_replace('{icon}', $record['icon_large'], $line);
2081
                }
2082
            }
2083
2084
            $line = mb_ereg_replace('{html_desc}', escape_javascript($record['html_desc']), $line);
2085
            $line = mb_ereg_replace('{name}', escape_javascript($record['name']), $line);
2086
            $line = mb_ereg_replace('{color}', $rAttrGroup['color'], $line);
2087
2088
            $group_line .= $line;
2089
            $nLineAttrCount2++;
2090
        }
2091
        sql_free_result($rs);
2092
2093 View Code Duplication
        if ($group_line != '') {
2094
            $group_img = $cache_attrib_group;
2095
            $group_img = mb_ereg_replace('{color}', $rAttrGroup['color'], $group_img);
2096
            $group_img = mb_ereg_replace('{attribs}', $group_line, $group_img);
2097
            $group_img = mb_ereg_replace(
2098
                '{name}',
2099
                htmlspecialchars($rAttrGroup['name'], ENT_COMPAT, 'UTF-8'),
2100
                $group_img
2101
            );
2102
2103
            if ($bBeginLine2 == true) {
2104
                $attributes_img2 .= '<div id="attribs2">';
2105
                $bBeginLine2 = false;
2106
            }
2107
2108
            $attributes_img2 .= $group_img;
2109
            $nPrevLineAttrCount2 += $nLineAttrCount2;
2110
2111
            $nLineAttrCount2 = 0;
2112
        }
2113
    }
2114
    sql_free_result($rsAttrGroup);
2115
    if ($bBeginLine2 == false) {
2116
        $attributes_img2 .= '</div>';
2117
    }
2118
2119
    /* prepare default attributes */
2120
    $bBeginLine1 = true;
2121
    $nPrevLineAttrCount1 = 0;
2122
    $nLineAttrCount1 = 0;
2123
    $attributes_img1 = '';
2124
2125
    $rsAttrGroup = sql(
2126
        "SELECT `attribute_groups`.`id`,
2127
                IFNULL(`sys_trans_text`.`text`, `attribute_groups`.`name`) AS `name`,
2128
                `attribute_categories`.`color`
2129
         FROM `attribute_groups`
2130
         INNER JOIN `attribute_categories`
2131
           ON `attribute_groups`.`category_id`=`attribute_categories`.`id`
2132
         LEFT JOIN `sys_trans`
2133
           ON `attribute_groups`.`trans_id`=`sys_trans`.`id`
2134
           AND `sys_trans`.`text`=`attribute_groups`.`name`
2135
         LEFT JOIN `sys_trans_text`
2136
           ON `sys_trans`.`id`=`sys_trans_text`.`trans_id`
2137
           AND `sys_trans_text`.`lang`='&1'
2138
         ORDER BY `attribute_groups`.`category_id` ASC,
2139
                  `attribute_groups`.`id` ASC",
2140
        $opt['template']['locale']
2141
    );
2142
    while ($rAttrGroup = sql_fetch_assoc($rsAttrGroup)) {
2143
        $group_line = '';
2144
2145
        $rs = sql(
2146
            "SELECT `cache_attrib`.`id`,
2147
                    IFNULL(`ttname`.`text`, `cache_attrib`.`name`) AS `name`,
2148
                    `cache_attrib`.`icon_large`,
2149
                    `cache_attrib`.`icon_no`,
2150
                    `cache_attrib`.`icon_undef`,
2151
                    `cache_attrib`.`search_default`,
2152
                    IFNULL(`ttdesc`.`text`, `cache_attrib`.`html_desc`) AS `html_desc`
2153
             FROM `cache_attrib`
2154
             LEFT JOIN `sys_trans` AS `tname`
2155
               ON `cache_attrib`.`trans_id`=`tname`.`id`
2156
               AND `cache_attrib`.`name`=`tname`.`text`
2157
             LEFT JOIN `sys_trans_text` AS `ttname`
2158
               ON `tname`.`id`=`ttname`.`trans_id`
2159
               AND `ttname`.`lang`='&1'
2160
             LEFT JOIN `sys_trans` AS `tdesc`
2161
               ON `cache_attrib`.`html_desc_trans_id`=`tdesc`.`id`
2162
               AND `cache_attrib`.`html_desc`=`tdesc`.`text`
2163
             LEFT JOIN `sys_trans_text` AS `ttdesc`
2164
               ON `tdesc`.`id`=`ttdesc`.`trans_id`
2165
               AND `ttdesc`.`lang`='&1'
2166
             WHERE `cache_attrib`.`group_id`='&2'
2167
               AND `cache_attrib`.`search_default` = 1
2168
               AND `selectable`
2169
               AND NOT IFNULL(`cache_attrib`.`hidden`, 0)=1
2170
             ORDER BY `cache_attrib`.`id`",
2171
            $opt['template']['locale'],
2172
            $rAttrGroup['id']
2173
        );
2174
        while ($record = sql_fetch_array($rs)) {
2175
            $line = $cache_attrib_img_line2;
2176
            $line = mb_ereg_replace('{id}', $record['id'], $line);
2177
            $line = mb_ereg_replace('{text_long}', escape_javascript($record['name']), $line);
2178 View Code Duplication
            if (!isset($options['cache_attribs'])) {
2179
                $line = mb_ereg_replace('{icon}', $record['icon_undef'], $line);
2180
            } else {
2181
                if (array_search($record['id'], $options['cache_attribs']) === false) {
2182
                    if (array_search($record['id'], $options['cache_attribs_not']) === false) {
2183
                        $line = mb_ereg_replace('{icon}', $record['icon_undef'], $line);
2184
                    } else {
2185
                        $line = mb_ereg_replace('{icon}', $record['icon_no'], $line);
2186
                    }
2187
                } else {
2188
                    $line = mb_ereg_replace('{icon}', $record['icon_large'], $line);
2189
                }
2190
            }
2191
2192
            $line = mb_ereg_replace('{html_desc}', escape_javascript($record['html_desc']), $line);
2193
            $line = mb_ereg_replace('{name}', escape_javascript($record['name']), $line);
2194
            $line = mb_ereg_replace('{color}', $rAttrGroup['color'], $line);
2195
2196
            $group_line .= $line;
2197
            $nLineAttrCount1++;
2198
        }
2199
        sql_free_result($rs);
2200
2201 View Code Duplication
        if ($group_line != '') {
2202
            $group_img = $cache_attrib_group;
2203
            $group_img = mb_ereg_replace('{color}', $rAttrGroup['color'], $group_img);
2204
            $group_img = mb_ereg_replace('{attribs}', $group_line, $group_img);
2205
            $group_img = mb_ereg_replace(
2206
                '{name}',
2207
                htmlspecialchars($rAttrGroup['name'], ENT_COMPAT, 'UTF-8'),
2208
                $group_img
2209
            );
2210
2211
            if ($bBeginLine1 == true) {
2212
                $attributes_img1 .= '<div id="attribs1">';
2213
                $bBeginLine1 = false;
2214
            }
2215
2216
            $attributes_img1 .= $group_img;
2217
            $nPrevLineAttrCount1 += $nLineAttrCount1;
2218
2219
            $nLineAttrCount1 = 0;
2220
        }
2221
    }
2222
    sql_free_result($rsAttrGroup);
2223
    if ($bBeginLine1 == false) {
2224
        $attributes_img1 .= '</div>';
2225
    }
2226
2227
    $tpl->assign('cache_attribCat1_list', $attributes_img1);
2228
    $tpl->assign('cache_attribCat2_list', $attributes_img2);
2229
    $tpl->assign('attributes_jsarray', $attributes_jsarray);
2230
    $tpl->assign('hidopt_attribs', isset($options['cache_attribs']) ? implode(';', $options['cache_attribs']) : '');
2231
    $tpl->assign(
2232
        'hidopt_attribs_not',
2233
        isset($options['cache_attribs_not']) ? implode(';', $options['cache_attribs_not']) : ''
2234
    );
2235
2236
    $tpl->assign('fulltext', '');
2237
    $tpl->assign('ft_desc_checked', true);
2238
    $tpl->assign('ft_name_checked', true);
2239
    $tpl->assign('ft_pictures_checked', false);
2240
    $tpl->assign('ft_logs_checked', false);
2241
2242
    // fulltext options
2243
    if ($options['searchtype'] == 'byfulltext') {
2244
        if (!isset($options['fulltext'])) {
2245
            $options['fulltext'] = '';
2246
        }
2247
        $tpl->assign('fulltext', htmlspecialchars($options['fulltext'], ENT_COMPAT, 'UTF-8'));
2248
2249
        if (isset($options['ft_name'])) {
2250
            $tpl->assign('ft_name_checked', $options['ft_name'] == 1);
2251
        }
2252
2253
        if (isset($options['ft_desc'])) {
2254
            $tpl->assign('ft_desc_checked', $options['ft_desc'] == 1);
2255
        }
2256
2257
        if (isset($options['ft_logs'])) {
2258
            $tpl->assign('ft_logs_checked', $options['ft_logs'] == 1);
2259
        }
2260
2261
        if (isset($options['ft_pictures'])) {
2262
            $tpl->assign('ft_pictures_checked', $options['ft_pictures'] == 1);
2263
        }
2264
    }
2265
    $tpl->assign('searchtype_byfulltext', $options['searchtype'] == 'byfulltext');
2266
2267
    //all
2268
    $tpl->assign('searchtype_byall', $options['searchtype'] == 'all');
2269
    
2270
    // error messages
2271
    $tpl->assign('ortserror', '');
2272
    if (isset($options['error_plz'])) {
2273
        $tpl->assign('ortserror', $error_plz);
2274
    } elseif (isset($options['error_ort'])) {
2275
        $tpl->assign('ortserror', $error_ort);
2276
    } elseif (isset($options['error_locidnocoords'])) {
2277
        $tpl->assign('ortserror', $error_locidnocoords);
2278
    } elseif (isset($options['error_nowaypointfound'])) {
2279
        $tpl->assign('ortserror', $error_nowaypointfound);
2280
    } elseif (isset($options['error_nocoords'])) {
2281
        $tpl->assign('ortserror', $error_nocoords);
2282
    }
2283
2284
    $tpl->assign('fulltexterror', '');
2285
    if (isset($options['error_nofulltext'])) {
2286
        $tpl->assign('fulltexterror', $error_nofulltext);
2287
    } else {
2288
        if (isset($options['error_fulltexttoolong'])) {
2289
            $tpl->assign('fulltexterror', $error_fulltexttoolong);
2290
        }
2291
    }
2292
2293
    $tpl->display();
2294
}
2295
2296
2297
//=============================================================
2298
//  Prompt the user with a list of locations when the entered
2299
//  'ort' or 'plz' is not unique.
2300
//=============================================================
2301
2302
function prepareLocSelectionForm($options)
2303
{
2304
    global $tpl;
2305
2306
    $tpl->name = 'search_selectlocid';
2307
2308
    unset($options['queryid']);
2309
    unset($options['locid']);
2310
    $options['searchto'] = 'searchbyortplz';
2311
    unset($options['searchtype']);
2312
2313
    // urlparams zusammenbauen
2314
    $urlparamString = '';
2315
    foreach ($options as $name => $param) {
2316
        // workaround for attribs
2317
        if (is_array($param)) {
2318
            $pnew = '';
2319
            foreach ($param as $p) {
2320
                if ($pnew != '') {
2321
                    $pnew .= ';' . $p;
2322
                } else {
2323
                    $pnew .= $p;
2324
                }
2325
            }
2326
2327
            $param = $pnew;
2328
        }
2329
2330
        if ($urlparamString != '') {
2331
            $urlparamString .= '&' . $name . '=' . urlencode($param);
2332
        } else {
2333
            $urlparamString = $name . '=' . urlencode($param);
2334
        }
2335
    }
2336
    $urlparamString .= '';
2337
2338
    return $urlparamString;
2339
}
2340
2341
2342
function outputUniidSelectionForm($uniSql, $options)
2343
{
2344
    global $tpl; // settings
2345
    global $locline, $secondlocationname;
2346
2347
    $urlparamString = prepareLocSelectionForm($options);
2348
2349
    sql_temp_table_slave('uniids');
2350
    sql_slave("CREATE TEMPORARY TABLE &uniids ENGINE=MEMORY " . $uniSql);
2351
    sql_slave("ALTER TABLE &uniids ADD PRIMARY KEY (`uni_id`)");
2352
2353
    // locidsite
2354
    $locidsite = isset($_REQUEST['locidsite']) ? $_REQUEST['locidsite'] : 0;
2355
    if (!is_numeric($locidsite)) {
2356
        $locidsite = 0;
2357
    }
2358
2359
    $count = sql_value_slave("SELECT COUNT(*) FROM &uniids", 0);
2360
    $tpl->assign('resultscount', $count);
2361
2362
    // create page browser
2363
    $pager = new pager('search.php?' . $urlparamString . '&locidsite={offset}');
2364
    $pager->make_from_offset($locidsite, ceil($count / 20), 1);
2365
2366
    // create locations list
2367
    $rs = sql_slave(
2368
        "SELECT `gns_locations`.`rc` `rc`,
2369
                `gns_locations`.`cc1` `cc1`,
2370
                `gns_locations`.`admtxt1` `admtxt1`,
2371
                `gns_locations`.`admtxt2` `admtxt2`,
2372
                `gns_locations`.`admtxt3` `admtxt3`,
2373
                `gns_locations`.`admtxt4` `admtxt4`,
2374
                `gns_locations`.`uni` `uni_id`,
2375
                `gns_locations`.`lon` `lon`,
2376
                `gns_locations`.`lat` `lat`,
2377
                `gns_locations`.`full_name` `full_name`,
2378
                &uniids.`olduni` `olduni`
2379
         FROM `gns_locations`, &uniids
2380
         WHERE &uniids.`uni_id`=`gns_locations`.`uni`
2381
         ORDER BY `gns_locations`.`full_name` ASC
2382
         LIMIT " . ($locidsite * 20) . ', 20'
2383
    );
2384
2385
    $nr = $locidsite * 20 + 1;
2386
    $locations = '';
2387
    while ($r = sql_fetch_array($rs)) {
2388
        $thislocation = $locline;
2389
2390
        $locString = '';
2391 View Code Duplication
        if ($r['admtxt1'] != '') {
2392
            if ($locString != '') {
2393
                $locString .= ' &gt; ';
2394
            }
2395
            $locString .= htmlspecialchars($r['admtxt1'], ENT_COMPAT, 'UTF-8');
2396
        }
2397 View Code Duplication
        if ($r['admtxt2'] != '') {
2398
            if ($locString != '') {
2399
                $locString .= ' &gt; ';
2400
            }
2401
            $locString .= htmlspecialchars($r['admtxt2'], ENT_COMPAT, 'UTF-8');
2402
        }
2403 View Code Duplication
        if ($r['admtxt4'] != '') {
2404
            if ($locString != '') {
2405
                $locString .= ' &gt; ';
2406
            }
2407
            $locString .= htmlspecialchars($r['admtxt4'], ENT_COMPAT, 'UTF-8');
2408
        }
2409
2410
        $thislocation = mb_ereg_replace('{parentlocations}', $locString, $thislocation);
2411
2412
        // koordinaten ermitteln
2413
        $coordString = help_latToDegreeStr($r['lat']) . ' ' . help_lonToDegreeStr($r['lon']);
2414
        $thislocation = mb_ereg_replace('{coords}', htmlspecialchars($coordString, ENT_COMPAT, 'UTF-8'), $thislocation);
2415
2416
        if ($r['olduni'] != 0) {
2417
            // der alte name wurde durch den native-wert ersetzt
2418
            $thissecloc = $secondlocationname;
2419
2420
            $r['olduni'] = $r['olduni'] + 0;
2421
            $rsSecLoc = sql_slave(
2422
                "SELECT full_name FROM gns_locations WHERE uni='&1'",
2423
                $r['olduni']
2424
            );
2425
            $rSecLoc = sql_fetch_assoc($rsSecLoc);
2426
            $thissecloc = mb_ereg_replace(
2427
                '{secondlocationname}',
2428
                htmlspecialchars($rSecLoc['full_name'], ENT_COMPAT, 'UTF-8'),
2429
                $thissecloc
2430
            );
2431
            sql_free_result($rsSecLoc);
2432
2433
            $thislocation = mb_ereg_replace('{secondlocationname}', $thissecloc, $thislocation);
2434
        } else {
2435
            $thislocation = mb_ereg_replace('{secondlocationname}', '', $thislocation);
2436
        }
2437
2438
        $thislocation = mb_ereg_replace(
2439
            '{locationname}',
2440
            htmlspecialchars($r['full_name'], ENT_COMPAT, 'UTF-8'),
2441
            $thislocation
2442
        );
2443
        $thislocation = mb_ereg_replace('{urlparams}', $urlparamString . '&locid={locid}', $thislocation);
2444
        $thislocation = mb_ereg_replace('{locid}', urlencode($r['uni_id']), $thislocation);
2445
        $thislocation = mb_ereg_replace('{nr}', $nr, $thislocation);
2446
2447
        $nr++;
2448
        $locations .= $thislocation . "\n";
2449
    }
2450
    sql_free_result($rs);
2451
    sql_drop_temp_table_slave('uniids');
2452
2453
    $tpl->assign('locations', $locations);
2454
2455
    $tpl->display();
2456
    exit;
2457
}
2458
2459
2460
function outputLocidSelectionForm($locSql, $options)
2461
{
2462
    global $tpl;
2463
    global $locline, $bgcolor1, $bgcolor2;
2464
2465
    require_once __DIR__ . '/lib2/logic/geodb.class.php';
2466
2467
    $urlparamString = prepareLocSelectionForm($options) . '&locid={locid}';
2468
2469
    sql_temp_table_slave('locids');
2470
    sql_slave("CREATE TEMPORARY TABLE &locids ENGINE=MEMORY " . $locSql);
2471
    sql_slave("ALTER TABLE &locids ADD PRIMARY KEY (`loc_id`)");
2472
2473
    $rs = sql_slave(
2474
        "SELECT `geodb_textdata`.`loc_id` `loc_id`,
2475
                `geodb_textdata`.`text_val` `text_val`
2476
         FROM `geodb_textdata`, &locids
2477
         WHERE &locids.`loc_id`=`geodb_textdata`.`loc_id`
2478
           AND `geodb_textdata`.`text_type` = 500100000
2479
         ORDER BY `text_val`"
2480
    );
2481
2482
    $nr = 1;
2483
    $locations = '';
2484
    while ($r = sql_fetch_array($rs)) {
2485
        $thislocation = $locline;
2486
2487
        // locationsdings zusammenbauen
2488
        $locString = '';
2489
        $land = GeoDb::landFromLocid($r['loc_id']);
2490
        if ($land != '') {
2491
            $locString .= htmlspecialchars($land, ENT_COMPAT, 'UTF-8');
2492
        }
2493
2494
        $rb = GeoDb::regierungsbezirkFromLocid($r['loc_id']);
2495
        if ($rb != '') {
2496
            $locString .= ' &gt; ' . htmlspecialchars($rb, ENT_COMPAT, 'UTF-8');
2497
        }
2498
2499
        $lk = GeoDb::landkreisFromLocid($r['loc_id']);
2500
        if ($lk != '') {
2501
            $locString .= ' &gt; ' . htmlspecialchars($lk, ENT_COMPAT, 'UTF-8');
2502
        }
2503
2504
        $thislocation = mb_ereg_replace('{parentlocations}', $locString, $thislocation);
2505
2506
        // koordinaten ermitteln
2507
        $r['loc_id'] = $r['loc_id'] + 0;
2508
        $rsCoords = sql_slave(
2509
            "SELECT `lon`, `lat`
2510
             FROM `geodb_coordinates`
2511
             WHERE loc_id='&1'
2512
             LIMIT 1",
2513
            $r['loc_id']
2514
        );
2515
        if ($rCoords = sql_fetch_array($rsCoords)) {
2516
            $coordString = help_latToDegreeStr($rCoords['lat']) . ' ' . help_lonToDegreeStr($rCoords['lon']);
2517
        } else {
2518
            $coordString = '[' . $no_location_coords . ']';
2519
        }
2520
2521
        $thislocation = mb_ereg_replace('{coords}', htmlspecialchars($coordString, ENT_COMPAT, 'UTF-8'), $thislocation);
2522
        $thislocation = mb_ereg_replace(
2523
            '{locationname}',
2524
            htmlspecialchars($r['text_val'], ENT_COMPAT, 'UTF-8'),
2525
            $thislocation
2526
        );
2527
        $thislocation = mb_ereg_replace('{urlparams}', $urlparamString, $thislocation);
2528
        $thislocation = mb_ereg_replace('{locid}', urlencode($r['loc_id']), $thislocation);
2529
        $thislocation = mb_ereg_replace('{nr}', $nr, $thislocation);
2530
        $thislocation = mb_ereg_replace('{secondlocationname}', '', $thislocation);
2531
2532
        if ($nr % 2) {
2533
            $thislocation = mb_ereg_replace('{bgcolor}', $bgcolor1, $thislocation);
2534
        } else {
2535
            $thislocation = mb_ereg_replace('{bgcolor}', $bgcolor2, $thislocation);
2536
        }
2537
2538
        $nr++;
2539
        $locations .= $thislocation . "\n";
2540
    }
2541
2542
    $tpl->assign('locations', $locations);
2543
2544
    $tpl->assign('resultscount', sql_num_rows($rs));
2545
    $tpl->assign('pages', '');
2546
2547
    sql_free_result($rs);
2548
    sql_drop_temp_table_slave('locids');
2549
2550
    $tpl->display();
2551
    exit;
2552
}
2553