forked from retostauffer/wp-wetterturnier
-
Notifications
You must be signed in to change notification settings - Fork 0
/
generalclass.php
1839 lines (1648 loc) · 74.2 KB
/
generalclass.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* @file generalclass.php
* @author Reto Stauffer
* @date 16 June 2017
* @brief This is the `core class` of the wp-wetterturnier plugin.
* This class will be extended by both, the @ref wp_wetterturnier_userclass
* and the @ref wp_wetterturnier_adminclass.
* @ref wetterturnier_generalclass contains a set of functions and
* methods used in the wordpress frontend and backend (admin interface).
*/
/** General-class which is used by the main class, the
* adminclass and the userclass. Contains a wide range of
* functions.
*/
class wetterturnier_generalclass
{
public $version = "1.1-3"; // Wp-wetterturnier version (used when registering css/js files)
public $date_format = "%Y-%m-%d"; // Default date format on initialization
public $datetime_format = "%Y-%m-%d %H:%M"; // Default datetime format on init
/// Private attribute to store the current @ref wetterturnier_cityObject
/// object. Try to avoid to call/load the same information multiple times
/// as this object is used in many methods.
/// @see get_current_cityObj
private $current_cityObj = NULL;
/// Private attribute to store an array with all ACTIVE cities as
/// @ref wetterturnier_cityObject. This is used to create the navigation
/// menu on top and for some other methods. Not to load the data several
/// times I am using the attribute all_cityObj to store the information.
/// Once initialized other methods will just return them.
private $all_cityObj_active = NULL;
/// Private attribute to store an array with all ACTIVE AND INACTIVE cities
/// as @ref wetterturnier_cityObject.
private $all_cityObj_all = NULL;
/// Attribute to store the 'next tournament' once.
public $current_tournament = false;
/** The current city is used in varous scripts and methods. Not to
* load the same information multiple times I am using this method to
* load the current city once from the database. The information
* (a @ref wetterturnier_cityObject object) will be stored on
* the private attribute current_cityObj. If the attribute is `NULL`
* load the information once. If not `NULL` return the object.
*
* @return Returns a @ref wetterturnier_cityObject object with the
* active city.
*/
function get_current_cityObj() {
if ( is_null($this->current_cityObj) ) {
$this->current_cityObj = new wetterturnier_cityObject();
}
return( $this->current_cityObj );
}
/** @details Initialize wordpress options. Loads a set of
* wetterturnier related options from the wordpress options
* database table and returns a stdClass object containing
* these options.
*
* @return stdClass object containing all options as specified
* in the array $names inside this method.
*/
function init_options() {
// Initialize some wordpress wetterturnier options.
// Will be loaded from the database whenever init_options
// is called. Returns a standard class containing the
// options and some additional elements.
$options = new stdClass();
global $wpdb;
$res = $wpdb->get_results("SELECT option_name, option_value FROM "
.$wpdb->prefix."options WHERE option_name LIKE \"wetterturnier_%\"");
// Put options into the stdClass object $options
foreach ( $res as $rec ) {
$name = $rec->option_name;
$options->$name = $rec->option_value;
}
// ----------------------------------------------------------
// Convert deadline for tournament into unix time stamp
$next = $this->next_tournament(0,false);
if ( ! $next->closed ) {
$lock = strftime('%Y-%m-%d',$next->tdate*86400.)
." ".(int)$options->wetterturnier_bet_closingtime;
$lock = strptime($lock,'%Y-%m-%d %H%M');
$lock = mktime($lock['tm_hour'], $lock['tm_min'], $lock['tm_sec'],
$lock['tm_mon']+1, $lock['tm_mday'], $lock['tm_year']+1900);
$lock = $lock + 60.*(int)$options->wetterturnier_bet_closingoffset;
} else {
$lock = true;
}
$options->wetterturnier_bet_closing_timestamp = $lock;
// Loading floatin point format
$this->load_float_format();
return( $options );
}
/** Quick-access to the plugins url for the wp-wetterturnier
* plugin (returns the path to the plugin). Wrapper around the
* wordpress-function plugins_url.
*
* @param $pluginname. String, default is `wp-wetterturnier` (name
* of the plugin).
* @return Returns (string) the path to the plugin.
*/
function plugins_url( $pluginname = "wp-wetterturnier" ) {
return( plugins_url($pluginname) );
}
/** Save 'next tournament' once. Used in various
* positions, e.g., the widgets.
*/
function load_current_tournament_once() {
$this->current_tournament = $this->current_tournament(0,false,0,true);
}
/** An own number_format function to print well formatted
* numbers (integers and floating point numbers). The
* wetterturnier plugin offers some user defined options (See
* wetterturnier plugin backend settings) where the thousand
* separator and decimal separator can be specified. These
* specifications are stored.
*
* @param $value. Numeric value which has to be formatted.
*
* @param $decimals. Integer, default is `2`. Number of decimal
* values. Can also be 0.
*
* @return Returns a string containing the formatted number.
*/
function number_format($value,$decimals=2) {
return number_format((float)$value,$decimals,$this->float_format->dsep,$this->float_format->tsep);
}
/** Adding css files (array) to the head of the wordpress theme.
* Uses the public attribute $version to add a version string to
* overcome browser caching issues.*/
function register_css_files() {
if ( ! empty( $this->options->wetterturnier_style_deps ) & ! is_admin() )
{ $arr = array($this->options->wetterturnier_style_deps); }
else
{ $arr = array(); }
//!!! RETO TODO set to all . no dependencies. Dependency
//still set in backend, wetterturnier plugin.
$arr = array();
// Now add
foreach ( $this->css_files as $file ) {
wp_register_style( 'wetterturnier_'.$file,
sprintf('%s/css/%s.css',$this->plugins_url(),$file),
$arr, $this->version);
wp_enqueue_style( 'wetterturnier_'.$file);
}
}
/** Adding js files (array) to the head of the wordpress.
* Uses the public attribute $version to add a version string to
* overcome browser caching issues.*/
function register_js_files() {
foreach ( $this->js_files as $file ) {
wp_register_script( 'wetterturnier_'.$file,
sprintf("%s/js/%s.js",$this->plugins_url(), $file), array(), $this->version);
wp_enqueue_script( 'wetterturnier_'.$file );
}
}
/** Adding js files to the head of the wordpress.
*
* @param $file. Name of the javascript file without postfix!
*/
function register_js_file( $file ) {
wp_register_script( 'wetterturnier_'.$file,
sprintf('%s/js/%s.js',plugins_url('wp-wetterturnier'),$file));
wp_enqueue_script( 'wetterturnier_'.$file );
}
/** Including a js script file outside the wordpress header.
* Wont call wp_register_script, but includes the js file whereever
* you need. Using this for special jquery functions only needed
* for some special purposes, as e.g., the synopsymbols page.
* Benefit: the synopsymbols-jQuery code is not loaded globally
* whenever a wordpress page will be opened which reduces the
* response time. Drawback: only available where included. Therefore
* some js scripts (e.g., used for the navigation) will be registered
* in wordpress to make them available everywhere.
*
* @param $file. Name of the javascript file without postfix!
*/
function include_js_script( $name ) {
printf("<script type='text/javascript' src='%s/js/%s.js'></script>",
$this->plugins_url(),$name);
}
/** Returns current language if pll (polylang plugin)
* is active. Else use `en_US` as default language.
*
* @param $value. String, default is `slug`. If set to `slug`
* the language slug will be returned (e.g., `en` or `de`).
* Can also be set to `name`. If set to `name` the
* language name will be returned (e.g., `en_US`, `de_DE`).
*
* @todo Reto: if $vlaue is not slug or name: problem?
*/
function get_user_language( $value = 'slug' ) {
// Getting language
if ( is_callable("pll_current_language") ) {
$user_language = pll_current_language( $value );
if ( strlen((string)$user_language)==0 && $value == 'slug' ) { $user_language = 'en'; }
else if ( strlen((string)$user_language)==0 ) { $user_language = 'en_US'; }
} else {
if ( $value == 'slug' ) {
$user_language = 'en'; # default defined by wetterturnier plugin
} else {
$user_language = 'en_US'; # default defined by wetterturnier plugin
}
}
return( $user_language );
}
/** Setting locale based on the active polylang slug */
function set_locale( $locale = false ) {
$locale = $this->get_user_language( 'locale' );
setlocale(LC_ALL,$locale);
}
/** Depending on the current language configuration (based
* on the polylang plugin if active) the floating point number
* format is specified here. Saves a stdClass object into the
* parent class called `float_format`. This is mainly used by
* the @ref number_format method.
*
* @see number_format
*
* @see load_date_format
*
* @see load_datetime_format
*/
function load_float_format() {
$default = new stdClass(); $default->dsep = ","; $default->tsep = "";
global $polylang;
if ( function_exists("pll_current_language") ) {
$fmt = new stdClass();
$slug = pll_current_language("slug");
$fmt->tsep = get_option(sprintf('wetterturnier_floattsep_format_%s',$slug));
$fmt->dsep = get_option(sprintf('wetterturnier_floatdsep_format_%s',$slug));
if ( strlen($fmt->dsep) == 0 ) { $fmt = $default; }
} else { $fmt = $default; }
$this->float_format = $fmt;
return true;
}
/** The wetterturnier plugins also allows to define
* language specific date formats. Based on the polylang
* plugin (if active) the date format will be loaded as set
* in the wetterturnier admin backend. If not found or
* polylang is inactive, the default format `%Y-%m-%d` will be
* used. Saves the `date_format` into the parent class and
* is used to create user-friendly date format output on the
* frontend.
*
* @see load_float_format
*
* @see load_datetime_format
*/
function load_date_format() {
$default = "%Y-%m-%d";
global $polylang;
if ( function_exists("pll_current_language") ) {
$slug = pll_current_language("slug");
$fmt = get_option(sprintf('wetterturnier_date_format_%s',$slug));
if ( strlen($fmt) == 0 ) { $fmt = $default; }
} else { $fmt = $default; }
$this->date_format = $fmt;
return true;
}
/** The wetterturnier plugins also allows to define
* language specific datetime formats. Based on the polylang
* plugin (if active) the date format will be loaded as set
* in the wetterturnier admin backend. If not found or
* polylang is inactive, the default format `%Y-%m-%d %H:%M:%S` will be
* used. Saves the `datetime_format` into the parent class and
* is used to create user-friendly datetime format output on the
* frontend.
*
* @see load_float_format
*
* @see load_date_format
*/
function load_datetime_format() {
$default="%Y-%m-%d %H:%M:%S";
global $polylang;
if ( function_exists("pll_current_language") ) {
$slug = pll_current_language("slug");
$fmt = get_option(sprintf('wetterturnier_datetime_format_%s',$slug));
if ( strlen($fmt) == 0 ) { $fmt = $default; }
} else { $fmt = $default; }
$this->datetime_format = $fmt;
return true;
}
/** Converting $tdate (days sincd 1970-01-01) to the format
* specified. Can be used for specific date conversion like e.g.,
* to print the day of the week or something.
*
* @param $tdate. Integer representation of the date.
*
* @param $fmt. String, format (see php date() manual). Default
* Return format is `%Y-%m-%d %H:%M:%S`
*
* @return Returns string with the date in the format specified.
*/
public function convert_tdate( $tdate, $fmt = "%Y-%m-%d %H:%M:%S" ) {
return( date( $fmt, (int)$tdate*86400 ) );
}
/** Small helper class to convert a tournament date
* into a string given a certain format.
*
* @param $tdate. Integer, days since 1970-01-01.
*
* @param $fmt. Format. Either a string (see php date manual page for
* more details) or `NULL`. If `NULL` the `date_format` will
* be used (@ref load_date_format).
*
* @see datetime_format
*
* @see number_format
*/
function date_format( $tdate, $fmt = NULL ) {
if ( is_null($fmt) ) { $fmt = $this->date_format; }
return( strftime( $fmt, (int)$tdate * 86400 ) );
}
/** Small helper class to convert a timestamp
* into a string given a certain format.
*
* @param $tdate. Integer, seconds since 1970-01-01.
*
* @param $fmt. Format. Either a string (see php date manual page for
* more details) or `NULL`. If `NULL` the `datetime_format` will
* be used (@ref load_datetime_format).
* @see datetime_format
*
* @see number_format
*/
function datetime_format( $tdate, $fmt = NULL ) {
if ( is_null($fmt) ) { $fmt = $this->datetime_format; }
return( strftime( $fmt, (int)$tdate ) );
}
/** Returns the web-link to the terms and conditions
* pages which can be defined via the wetterturnier plugin
* settings page in the admin backend.
*/
function get_terms_link() {
global $polylang;
if ( function_exists("pll_current_language") ) {
$slug = pll_current_language("slug");
} else { $slug = "en"; }
$link = get_option(sprintf('wetterturnier_terms_link_%s',$slug));
return $link;
}
/** Small insert or update workaround for wordpress as
* a `insert on duplicate update` method is not yet implemented
* in the wordpress core.
*
* @param $table. Name of the database table.
*
* @param $data. Array which consists of `key`/`value` pairs
* where the `key` specifies the name of the column in the
* database while `value` defines the value which should be
* inserted.
*/
function insertonduplicate($table, $data, $updatecol = array(), $useprepare = True ) {
global $wpdb;
$formatted_fields = array();
$onduplicate = array();
foreach ( $data as $field=>$value ) {
$formatted_fields[] = "%s";
// If field name is in "updatecol": do not append
// to ON DUPLICATE KEY UPDATE array.
if ( ! in_array($field,$updatecol) ) {
array_push( $onduplicate, $field );
}
}
$sql = "INSERT INTO `$table` (`" . implode( '`,`', array_keys($data) )
."`) VALUES "
." ('" . implode( "','", $formatted_fields ) . "')"
." ON DUPLICATE KEY UPDATE ";
for ( $i = 0; $i < count($onduplicate); $i++ ) {
$onduplicate[$i] = sprintf("`%s` = VALUES(`%s`)",
$onduplicate[$i], $onduplicate[$i] );
}
$sql = sprintf("%s %s",$sql,implode(",",$onduplicate));
// There is one problem with the prepare function: it does not take
// NULL and converts it to '0'. If $useprepare is set to False we ignore
// the wpdb->prepare and do it manually.
if ( $useprepare ) {
return $wpdb->query( $wpdb->prepare( $sql, $data) );
} else {
$dbvals = array();
// Define the sql 'values' string once
foreach ( array_keys($data) AS $v ) { array_push($dbvals,sprintf("`%s`",$v)); }
// Combine
$dbvals = sprintf("(%s)",join(",",$dbvals));
// If $updatecol is NULL or empty: append all
$add = ( (is_null($updatecol) | count($updatecol) === 0) ? true : false );
// For each entry: define the data array
#printf("VALS: %s<br>\n",$dbvals);
$dbdata = array();
$dbupdate = array();
foreach ( $data as $key=>$elem ) {
$type = gettype($elem);
switch( (string)$type ) {
case "string":
$tmp = sprintf("'%s'",$elem);
array_push($dbdata,$tmp);
if ( $add | in_array($key,$updatecol) ) { $dbupdate[$key] = $tmp; }
break;
case "double":
$tmp = number_format($elem,2,".","");
array_push($dbdata,$tmp);
if ( $add | in_array($key,$updatecol) ) { $dbupdate[$key] = $tmp; }
break;
case "integer":
$tmp = number_format($elem,0,".","");
array_push($dbdata,$tmp);
if ( $add | in_array($key,$updatecol) ) { $dbupdate[$key] = $tmp; }
break;
case "NULL":
$tmp = "NULL";
array_push($dbdata,$tmp);
if ( $add | in_array($key,$updatecol) ) { $dbupdate[$key] = $tmp; }
break;
default:
die("UNKNOWN DATA TYPE IN insertonduplicate WITH \$useparepare=false");
}
}
// Combine
$dbdata = sprintf("(%s)",join(",",$dbdata));
$sql = sprintf("INSERT INTO `%s` %s VALUES %s",
$table, $dbvals, $dbdata);
$sqlupdate = array();
foreach ( $dbupdate as $key=>$val ) {
array_push($sqlupdate,sprintf("%s = %s",$key,$val));
}
$sql = $sql." ".sprintf(" ON DUPLICATE KEY UPDATE %s",join(", ",$sqlupdate));
//printf("<br><br>\n\n%s<br>\n",$sql);
return $wpdb->query( $sql );
}
}
/** @details Checks which one is the next tournament date
* dayoffset can be used to get 'todays tournament'
*
* @param $row_offset. Default is `0`. Can be set to (any)
* if set to `1` the function won't return the next tournament
* but the one after. Please have a look to input $backwards.
* If `backwards=true` this $row_offset can be used to get the
* previous rather than the upcoming tournament.
*
* @param $check_access. Boolean, default is `true`. Checks
* whether the visitor has access to the data of this
* tournament. This is important as we don't want the user
* to see the bets/forecasts of other competitors before the
* bet form is closed and the tournament has been started.
*
* @param $dayoffset. Default `0`.
*
* @param $backwards. Boolean, default `false`. If `false`
* we are looking forward in time if e.g., $row_offset is
* set. If `true` we are looking/searching backwards to e.g.,
* get the `last tournament date` rather than the `next`.
*
* @return Returns a stdClass object containing the requrested
* tournament date and some more information (e.g., wheter
* the user has access to the data for the requested tournament
* date or the dates of the `bet days` where the forecasts will
* be placed and so far and so on.
*
* @see next_tournament
* @see current_tournament
* @see latest_tournament
* @see older_tournament
* @see newer_tournament
*/
public function next_tournament($row_offset=0,$check_access=true,$dayoffset=0,$backwards=false) {
//printf("<br>Calling next_tournament with row_offset = %d, check_access = %s, dayoffset = %d, and backwars = %s<br>\n",
// $row_offset,($check_access ? 'true' : 'false'), $dayoffset, ($backwards ? 'true' : 'false'));
global $wpdb;
// If dayoffset is bigger than 100 we expect that
// it is a tournament date (days since 1970) and
// therefore take this one.
if ( (int)$dayoffset > 100 ) {
$today = (int)$dayoffset;
} else {
$today = (int)floor(gmdate('U') / 86400. ) + $dayoffset;
}
// Loading next tournament row
// NOTE there are two modes. Default is backwards == false menas that the system
// is searching for the tournaments in the future. If backwards
// is true (actually only ued by current_tournament method) searches
// backwards in time.
if ( ! $backwards ) {
$sql = sprintf("SELECT tdate FROM %swetterturnier_dates "
."WHERE tdate >= %d AND status = 1 ORDER BY tdate ASC LIMIT %d",
$wpdb->prefix,$today,$row_offset + 1);
$rows = $wpdb->get_results( $sql );
} else {
$sql = sprintf("SELECT tdate FROM %swetterturnier_dates "
."WHERE tdate <= %d AND status = 1 ORDER BY tdate DESC LIMIT %d",
$wpdb->prefix,$today,$row_offset + 1);
$rows = $wpdb->get_results( $sql );
}
// - No rows? Return "closed = true"
// Do the same if the db returned less rows
// then the requested offset!
if ( ! $rows || count($rows) < $row_offset ) {
$next = new stdClass();
$next->closed = true;
$next->debug = "Nothing found in database";
return $next;
}
// Else take row with offset, if set
$row = $rows[$row_offset];
// Generate return object
$next = new stdClass();
$next->tdate = $row->tdate;
//$next->readable = gmdate($this->date_format,$next->tdate * 86400. );
//$next->weekday = gmdate('l',$next->tdate * 86400. );
$next->readable = $this->date_format( $next->tdate );
$next->weekday = $this->date_format( $next->tdate, "%A" );
// if row_offset == 0, check if open or allready closed.
// if row_offset >= 1, the form is allways closed! Do NOT
// call check_view_is_closed because this will
// crash (loop inside the class)
if ( $row_offset == 0 & $check_access ) {
$next->closed = $this->check_view_is_closed( $row->tdate, $next );
} else if ( $row_offset > 0 ) {
$next->closed = true;
} else {
$next->closed = false;
}
// Adding tournament date and the two bet dates
$next->tdate = $row->tdate;
$next->betdate_day1 = $row->tdate + 1;
$next->betdate_day2 = $row->tdate + 2;
//$next->day1 = gmdate($this->date_format,($next->tdate+1) * 86400. );
//$next->day2 = gmdate($this->date_format,($next->tdate+2) * 86400. );
$next->day1 = $this->date_format((int)$next->tdate+1);
$next->day2 = $this->date_format((int)$next->tdate+2);
return $next;
}
/** @details This method is based on @ref next_tournament and returns
* the current/last turnament. This is used to show
* current bets/observations.
* @param $row_offset. Positive integer, default `0` (no row offset)
*
* @param $check_access. Boolean, default `true`.
*
* @param $dayoffset. Integer, default `-2`. We are forecasting two
* days at the moment. `$dayoffset-2` uses 'today - 2 days' to
* find the current tournament.
*
* @see next_tournament
* @see latest_tournament
* @see older_tournament
* @see newer_tournament
*
* @todo Reto should use the 'number of bet days' variable rather
* than this fixed number of -2.
*/
public function current_tournament($row_offset=0,$check_access=true,$dayoffset=-2,$backwards=false) {
return $this->next_tournament($row_offset,$check_access,$dayoffset,$backwards);
}
/** This method is based on @ref next_tournament and returns
* the latest (last) tournament based on $tdate. Please check
* the next_tournament method to see what $tdate can be (either
* "day_offset" or explicit "tournament date").
* @param Please check the @ref next_tournament method to see what $tdate
* can be (either "day_offset" or explicit "tournament date").
*
* @see next_tournament
* @see current_tournament
* @see older_tournament
* @see newer_tournament
*/
public function latest_tournament($tdate) {
return( $this->next_tournament(0,false,$tdate,$backwards=true) );
}
/** This method is based on @ref next_tournament and returns
* the tournament before the one specified by input $tdate.
*
* @param Please check the @ref next_tournament method to see what $tdate
* can be (either "day_offset" or explicit "tournament date").
*
* @see next_tournament
* @see current_tournament
* @see latest_tournament
* @see newer_tournament
*/
public function older_tournament($tdate) {
return( $this->next_tournament(1,false,$tdate,$backwards=true) );
}
/** This method is based on @ref next_tournament and returns
* the tournament after thie current one (so the next upcoming one)
* depending on the input $tdate.
*
* @param Please check the @ref next_tournament method to see what $tdate
* can be (either "day_offset" or explicit "tournament date").
*
* @see next_tournament
* @see current_tournament
* @see latest_tournament
* @see older_tournament
*/
public function newer_tournament($tdate) {
return( $this->next_tournament(1,false,$tdate,$backwards=false) );
}
/** We allow the user to enter and save the forecasts
* partially. As soon as all required fields are provided (all
* forecasts filled in and submitted) the wetterturnier plugin
* appends a row in the betstat database table. Note that this
* line will be deleted if the user decides to delete one or more
* values and stores them as empty. This function checks wheter
* the row in the betstat table exists or not. If it exists the
* function will return `true`, else `false` (not submitted or only
* partially submitted).
* @param $userID. Integer, numeric ID of the user.
* @param $cityObj. Object of class @wetterturnier_cityObject.
* @param $tdate. Integer, date of the tournament.
* @return Returns `true` if the user successfully submitted the
* forecast (all values) and `false` else.
*/
public function check_bet_is_submitted($userID,$cityObj,$tdate) {
global $wpdb;
$return = new stdClass();
$return->submitted = NULL;
$return->placed = NULL;
// Check if we have received full bet (all fine)
$res = $wpdb->get_row( sprintf("SELECT submitted FROM %swetterturnier_betstat "
." WHERE userID = %d AND cityID = %d AND tdate = %d",
$wpdb->prefix, $userID, $cityObj->get('ID'), $tdate));
if ( ! $res ) { $return->submitted = false; }
else if ( ! $res->submitted ) { $return->submitted = false; }
else if ( strtotime( $res->submitted ) < 0 ) { $return->submitted = false; }
else { $return->submitted = $res->submitted; }
// Else check when the last submission was (bets table)
$res = $wpdb->get_row( sprintf("SELECT max(placed) AS placed FROM %swetterturnier_bets "
." WHERE userID = %d AND cityID = %d AND tdate = %d",
$wpdb->prefix, $userID, $cityObj->get('ID'), $tdate));
if ( ! $res ) { $return->placed = false; }
else if ( strtotime( $res->placed ) < 0 ) { $return->placed = false; }
else { $return->placed = $res->placed; }
return( $return );
}
/** Checks whether the current user is in a specific group
* or not (is group member).
* @param $userID. Integer, numeric ID of the user.
* @param $groupName. Name of the group to check.
* @return Returns `true` if the user is a member of the group and false` else.
*/
public function check_user_is_in_group( $userID, $groupName ) {
global $wpdb;
$res = $wpdb->get_row(
sprintf("SELECT gu.active FROM %swetterturnier_groups AS g "
."LEFT OUTER JOIN %swetterturnier_groupusers AS gu "
."ON g.groupID = gu.groupID "
."WHERE g.groupName = '%s' AND gu.userID = %d",
$wpdb->prefix,$wpdb->prefix,$groupName,$userID));
if ( ! $res ) { return false; }
if ( ! $res->active == 1 ) { return false; }
return true;
}
/** Returns names of the groups the user is a member of.
*
* @param $userID. Integer, numeric user ID.
*
* @return Returns `false` if the user is not yet a member of
* at least one group and a stdClass object containing the group
* ID and group names for all groups where the user is a member of.
*/
public function get_groups_for_user( $userID ) {
global $wpdb;
$res = $wpdb->get_results(
sprintf("SELECT gu.ID, g.groupName FROM %swetterturnier_groups AS g "
."LEFT OUTER JOIN %swetterturnier_groupusers AS gu "
."ON g.groupID = gu.groupID "
."WHERE gu.userID = %d AND gu.active = 1",
$wpdb->prefix,$wpdb->prefix,$userID));
if ( ! $res ) { return false; }
return $res;
}
/** @details Returns a stdClass object with all information about a
* certain user specified by it's numeric ID.
*
* @param $userID. Integer, numeric user ID.
*
* @return stdClass containing the detailed user information.
*
* @see get_user_by_username
*/
public function get_user_by_ID( $userID ) {
global $wpdb;
///$res = $wpdb->get_results(sprintf('SELECT * FROM %susers '
$res = $wpdb->get_row(sprintf('SELECT * FROM %susers '
.' WHERE ID = %d',$wpdb->prefix,(int)$userID));
if ( ! $res ) { return false; }
return $res;
}
// ------------------------------------------------------------------
/** @details Returns user details based on user login name.
* Not case sensitive.
*
* @param $username. String containing the user login name.
*
* @return stdClass containing the detailed user information.
*
* @see get_user_by_ID
*/
public function get_user_by_username( $username ) {
global $wpdb;
$res = $wpdb->get_row(sprintf('SELECT * FROM %susers '
.' WHERE LOWER(user_login) = "%s"',$wpdb->prefix,
strtolower(trim($username))));
if ( ! $res ) { return false; }
return $res;
}
/** Sometimes I have to add a special userclass to some elements
* to display them as I want. Therefore there is a small method
* returning the userclass based on the uderID and the user_login
* name.
* The same yields for the username. We replace some special
* character strings with another string.
* e.g. GRP_ will be replaced but then we add [group] to the end.
*
* @param $userID. Integer, numeric user ID.
*
* @param $user_login. String containing the user_login name.
*
* @return stdClass containing two strings. `userclass` contains
* the main class (automat, referenz, mitteltip, or Sleepy),
* `username` the modified username.
*/
public function get_user_display_class_and_name($userID,$usr) {
$username = $usr->user_login;
// Check if user is Automat or mix or so
if ( $this->check_user_is_in_group($userID, 'Automaten') ) {
$userclass = 'automat';
} elseif ( $this->check_user_is_in_group($userID, 'Referenztipps') ) {
$userclass = 'referenz';
} else if ( substr($usr->user_login,0,4) == 'GRP_' ) {
$userclass = 'mitteltip';
$username = str_replace('GRP_','',$usr->user_login).' '.__('[group]','wpwt');
} else if ( strtolower($usr->user_login) == 'Sleepy' ) {
$userclass = 'Sleepy';
$username = sprintf('%s <span></span>',$usr->user_login);
} else { $userclass = 'player'; }
$res = new stdClass();
$res->userclass = $userclass;
$res->display_name = $username;
$res->user_login = $usr->user_login;
return( $res );
}
/** Returns the link to the profile page of the player.
* @param $usr. Wordpress user object.
* @return Returns `<a href=...>...</a>` tag with the link to the
* user profile (currently to bbpress /forum/users/<username>).
*/
public function get_user_profile_link( $usr ) {
if ( is_null($usr->display_name) ) {
$link = sprintf("<a href=\"/forums/users/%s/\" target=\"_self\">%s</a>",
$usr->user_login, $usr->user_login);
} else {
$link = sprintf("<a href=\"/forums/users/%s/\" target=\"_self\">%s</a>",
$usr->user_login, $usr->display_name);
}
return( $link );
}
/** Function which checks if we can show the bet-form or not.
* If user is allowed to see the data, function returns true.
* Else return value is false and the function places some notes.
*
* @param $tdate. Integer date value of a certain tournament.
*
* @return Prints a message and returns `true` if the view is closed
* and we do not allow the user to retreive the data at the moment
* (maybe locked because the tournament has not been started yet).
* or `false` (not locked) if to grant access.
*
* @see check_allowed_to_display_betdata
*/
function check_view_is_closed($tdate) {
// STOP if user should not see these data!
$today = (int)floor(gmdate('U')/86400.);
$tdate_string = strftime('%Y-%m-%d',$tdate*86400);
$open_string = strftime('%Y-%m-%d %H:%M UTC',($tdate-(int)$this->options->wetterturnier_bet_open_days)*86400);
// Is there a running wetterturnier?
// The tournament is always for the next two days, give the user
// a forward link to the tournament if there is a running
// tournament at the moment.
// WARNING: the check_access = false is very important not to
// create a loopback!!!!
$check = (int)(floor(gmdate('U')/86400)) - $this->older_tournament(0,false)->tdate;
if ( $check >= 0 and $check <= 2 ) {
$info = "<div class=\"wetterturnier-info ok\">\n"
.__("There is an ongoing tournament right now.","wpwt")."<br>\n"
.__("Current values can be found here:","wpwt")."<br>\n"
."<a href=\"/current\" target=\"_self\">".__("Link ... ","wpwt")."</a>"
."</div>\n";
}
// If user is too early (bet form opens X days before, see
// plugin settings) return false.
if ( $today < ( $tdate - $this->options->wetterturnier_bet_open_days) ) {
echo "<div class=\"wetterturnier-info error\">\n";
printf("%s.<br>\n",__("Sorry, no access to these bet form","wpwt"));
printf("%s.<br>\n",sprintf(__("The form to submit tips always opens %d days in advance.","wpwt"),
$this->options->wetterturnier_bet_open_days));
printf("%s.<br>\n",sprintf(__("Next tournament will take place on %s","wpwt"),
$this->date_format($tdate)));
printf("%s.\n",sprintf(__("The bet form opens %s","wpwt"),
$this->datetime_format(86400*$tdate)));
echo "</div>\n";
return( true ); # closed true
}
// Locked again
if ( (int)gmdate('U') > $this->options->wetterturnier_bet_closing_timestamp ) {
$nextnext = $this->next_tournament($row_offset=1);
echo "<div class=\"wetterturnier-info error\">\n";
printf("%s<br>\n",__("Sorry, no access to these bet form.","wpwt"));
printf("%s<br>\n",__("The form to submit tips for todays tournament is allready closed.","wpwt"));
printf("%s<br>\n",sprintf("%s %s, %s.",__("The next tournament will take place on %s","wpwt"),
$nextnext->weekday, $nextnext->readable));
echo "</div>\n";
return( true ); # closed true
}
return( false ); # closed = false (not closed)
}
/** Function which checks if we can show the placed bets/archive data
* If user is allowed to see the data, function returns true.
* Else return value is false and the function places some notes.
*
* @param $tdate. Integer date value of a certain tournament.
*
* @param $showinfo. Boolean, default true. If set to false the
* user-messages "sorry not access" are suppressed. This is used
* to not show the messages twice for two consecutive days.
*
* @return Prints a message and returns `true` if the view is closed
* and we do not allow the user to retreive the data at the moment
* (maybe locked because the tournament has not been started yet).
* or `false` (not locked) if to grant access.
*
* @see check_view_is_closed
*/
function check_allowed_to_display_betdata($tdate,$showinfo=true) {
// STOP if user should not see these data!
$today = floor(gmdate('U')/86400.);
if ( $today < $tdate ) {
echo "<div class=\"wetterturnier-info error\">\n";
echo __("The requested tournament date is in the future.","wpwt")."<br>\n";
echo __("Do you try to cheat, bro?","wpwt")."<br>\n";
echo "</div>\n";
return false;
}
// If it is today we have to be sure that the bet-form
// is closed now.
if ( $tdate == $today ) {
// How many minuts until you can see the data?
$now = gmdate('U');
$lock = strftime('%Y-%m-%d',$tdate*86400.)." ".(int)$this->options->wetterturnier_bet_closingtime;
$lock = strptime($lock,'%Y-%m-%d %H%M');
$lock = mktime($lock['tm_hour'], $lock['tm_min'], $lock['tm_sec'],
$lock['tm_mon']+1, $lock['tm_mday'], $lock['tm_year']+1900);
$lock = $lock + 60.*(int)$this->options->wetterturnier_bet_closingoffset;
$diff = ceil( abs($lock - $now) / 60. );
// ----------------------------------------------------------
// If lock is smaller than now show message and stop.
// ----------------------------------------------------------
if ( (int)$now < (int)$lock ) {
if ( $showinfo ) {
echo "<div class=\"wetterturnier-info error\">\n";
echo __("Sorry, no access to these data.","wpwt")."<br>\n";
echo __("We will show the current bets as soon as the bet-form has been closed.","wpwt")."<br>\n";
if ( $diff < 600 ) {
if ( $diff <= 60 ) {
echo __("You can see the newest tips in ","wpwt")." ".$diff." ".__("minutes","wpwt").".<br>\n";
} else {
$diff_hour = floor( $diff / 60 );
$diff_min = $diff - $diff_hour*60;
if ( (int)$diff_hour == 1 ) { $str_hour = sprintf(" %s ",__("hour")); } else { $str_hour = sprintf(" %s ",__("hours","wpwt")); }
if ( (int)$diff_min == 1 ) { $str_min = sprintf(" %s ",__("minute")); } else { $str_min = sprintf(" %s ",__("minutes","wpwt")); }
echo __("You can see the newest tips in ","wpwt")." ".(int)$diff_hour.$str_hour.__("and","wpwt")." "
.$diff_min.$str_min.".<br>\n";
}
}
echo "</div>\n";
# - Give a hint where to find the tournament bet form
echo "<div class=\"wetterturnier-info ok\">\n";
echo __("If you would like to submitt a bet please go to the \"SUBMISSION-FORM\" in the navigation.","wpwt")."<br>\n";
echo "</div>\n";
}
return false;
}
}
return true;
}
/** Returns parameter details from the database given
* a parameter ID.
*
* @param $ID. Integer, numeric parameter ID.
* @return Returns stdClass object with all the information
* in the corresponding row in the database or boolean `false`
* if the parameter cannot be found.
*/
public function get_param_by_ID($ID) {
global $wpdb;
$res = $wpdb->get_row(sprintf("SELECT * FROM %swetterturnier_param WHERE paramID = %d",
$wpdb->prefix,(int)$ID));
if ( ! $res ) { return(false); } else { return($res); }
}
/** Returns parameter details from the database given
* a parameter name (e.g., RR, Wn, Wv, ...).
*
* @return Returns stdClass object with all the information
* in the corresponding row in the database or boolean `false`
* if the parameter cannot be found.
*/
public function get_param_by_name($paramName) {
global $wpdb;
$res = $wpdb->get_row(sprintf("SELECT * FROM %swetterturnier_param WHERE UPPER(paramName) = \"%s\"",
$wpdb->prefix,strtoupper((string)$paramName)));
if ( ! $res ) { return(false); } else { return($res); }
}
/** Returns the numeric parameter ID given the parameter