/
functions.php
1303 lines (1104 loc) · 33.4 KB
/
functions.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
/**
* Useful functions
*
* @package MyAAC
* @author Slawkens <slawkens@gmail.com>
* @copyright 2019 MyAAC
* @link https://my-aac.org
*/
defined('MYAAC') or die('Direct access not allowed!');
use Twig\Loader\ArrayLoader as Twig_ArrayLoader;
function message($message, $type, $return)
{
if(IS_CLI) {
if($return) {
return $message;
}
echo $message;
return true;
}
if($return)
return '<div class="' . $type . '" style="margin-bottom:10px;">' . $message . '</div>';
echo '<div class="' . $type . '" style="margin-bottom:10px;">' . $message . '</div>';
return true;
}
function success($message, $return = false) {
return message($message, 'success', $return);
}
function warning($message, $return = false) {
return message($message, 'warning', $return);
}
function note($message, $return = false) {
return message($message, 'note', $return);
}
function error($message, $return = false) {
return message($message, 'error', $return);
}
function message1($head, $message, $type, $icon , $return)
{//return '<div class="' . $type . '">' . $message . '</div>';
if($return)
return '<div class="alert alert-'.$type.' alert-dismissible"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button><h4><i class="icon fa fa-'.$icon.'"></i> '.$head.':</h4>'.$message.'</div>';
echo '<div class="alert alert-'.$type.' alert-dismissible"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button><h4><i class="icon fa fa-'.$icon.'"></i> '.$head.':</h4>'.$message.'</div>';
return true;
}
function success1($message, $return = false) {
return message('Info', $message, 'success','success', $return);
}
function warning1($message, $return = false) {
return message('Warning',$message, 'warning','ban', $return);
}
function note1($message, $return = false) {
return message('Info',$message, 'info','info', $return);
}
function error1($message, $return = false) {
return message("Alert", $message, 'danger','check', $return);
}
function longToIp($ip)
{
$exp = explode(".", long2ip($ip));
return $exp[3].".".$exp[2].".".$exp[1].".".$exp[0];
}
function generateLink($url, $name, $blank = false) {
return '<a href="' . $url . '"' . ($blank ? ' target="_blank"' : '') . '>' . $name . '</a>';
}
function getFullLink($page, $name, $blank = false) {
return generateLink(getLink($page), $name, $blank);
}
function getLink($page, $action = null)
{
global $config;
return BASE_URL . ($config['friendly_urls'] ? '' : '?') . $page . ($action ? '/' . $action : '');
}
function internalLayoutLink($page, $action = null) {return getLink($page, $action);}
function getForumThreadLink($thread_id, $page = NULL)
{
global $config;
return BASE_URL . ($config['friendly_urls'] ? '' : '?') . 'forum/thread/' . (int)$thread_id . (isset($page) ? '/' . $page : '');
}
function getForumBoardLink($board_id, $page = NULL)
{
global $config;
return BASE_URL . ($config['friendly_urls'] ? '' : '?') . 'forum/board/' . (int)$board_id . (isset($page) ? '/' . $page : '');
}
function getPlayerLink($name, $generate = true)
{
global $config;
if(is_numeric($name))
{
$player = new OTS_Player();
$player->load((int)$name);
if($player->isLoaded())
$name = $player->getName();
}
$url = BASE_URL . ($config['friendly_urls'] ? '' : '?') . 'characters/' . urlencode($name);
if(!$generate) return $url;
return generateLink($url, $name);
}
function getHouseLink($name, $generate = true)
{
global $db, $config;
if(is_numeric($name))
{
$house = $db->query(
'SELECT `name` FROM `houses` WHERE `id` = ' . (int)$name);
if($house->rowCount() > 0)
$name = $house->fetchColumn();
}
$url = BASE_URL . ($config['friendly_urls'] ? '' : '?') . 'houses/' . urlencode($name);
if(!$generate) return $url;
return generateLink($url, $name);
}
function getGuildLink($name, $generate = true)
{
global $db, $config;
if(is_numeric($name))
{
$guild = $db->query(
'SELECT `name` FROM `guilds` WHERE `id` = ' . (int)$name);
if($guild->rowCount() > 0)
$name = $guild->fetchColumn();
}
$url = BASE_URL . ($config['friendly_urls'] ? '' : '?') . 'guilds/' . urlencode($name);
if(!$generate) return $url;
return generateLink($url, $name);
}
function getItemNameById($id) {
require_once LIBS . 'items.php';
$item = Items::get($id);
return !empty($item['name']) ? $item['name'] : '';
}
function getItemImage($id, $count = 1)
{
$tooltip = '';
$name = getItemNameById($id);
if(!empty($name)) {
$tooltip = ' class="item_image" title="' . $name . '"';
}
$file_name = $id;
if($count > 1)
$file_name .= '-' . $count;
global $config;
return '<img src="' . $config['item_images_url'] . $file_name . '.gif"' . $tooltip . ' width="32" height="32" border="0" alt="' .$id . '" />';
}
function getFlagImage($country)
{
if(!isset($country[0]))
return '';
global $config;
if(!isset($config['countries']))
require SYSTEM . 'countries.conf.php';
if(!isset($config['countries'][$country])) {
return '';
}
return '<img src="images/flags/' . $country . '.gif" title="' . $config['countries'][$country]. '"/>';
}
/**
* Performs a boolean check on the value.
*
* @param mixed $v Variable to check.
* @return bool Value boolean status.
*/
function getBoolean($v)
{
if(is_bool($v)) {
return $v;
}
if(is_numeric($v))
return (int)$v > 0;
$v = strtolower($v);
return $v === 'yes' || $v === 'true';
}
/**
* Generates random string.
*
* @param int $length Length of the generated string.
* @param bool $lowCase Should lower case characters be used?
* @param bool $upCase Should upper case characters be used?
* @param bool $numeric Should numbers by used too?
* @param bool $special Should special characters by used?
* @return string Generated string.
*/
function generateRandomString($length, $lowCase = true, $upCase = false, $numeric = false, $special = false)
{
$characters = '';
if($lowCase)
$characters .= 'abcdefghijklmnopqrstuxyvwz';
if($upCase)
$characters .= 'ABCDEFGHIJKLMNPQRSTUXYVWZ';
if($numeric)
$characters .= '123456789';
if($special)
$characters .= '+-*#&@!?';
$characters_length = strlen($characters) - 1;
if($characters_length <= 0) return '';
$ret = '';
for($i = 0; $i < $length; $i++)
$ret .= $characters[mt_rand(0, $characters_length)];
return $ret;
}
/**
* Get forum sections
*
* @return array Forum sections.
*/
function getForumBoards()
{
global $db, $canEdit;
$sections = $db->query('SELECT `id`, `name`, `description`, `closed`, `guild`, `access`' . ($canEdit ? ', `hidden`, `ordering`' : '') . ' FROM `' . TABLE_PREFIX . 'forum_boards` ' . (!$canEdit ? ' WHERE `hidden` != 1' : '') .
' ORDER BY `ordering`;');
if($sections)
return $sections->fetchAll();
return array();
}
/**
* Retrieves data from myaac database config.
*
* @param string $name Key.
* @param string &$value Reference where requested data will be set to.
* @return bool False if value was not found in table, otherwise true.
*/
function fetchDatabaseConfig($name, &$value)
{
global $db;
$query = $db->query('SELECT `value` FROM `' . TABLE_PREFIX . 'config` WHERE `name` = ' . $db->quote($name));
if($query->rowCount() <= 0)
return false;
$value = $query->fetchColumn();
return true;
}
/**
* Retrieves data from database config.
*
* $param string $name Key.
* @return string Requested data.
*/
function getDatabaseConfig($name)
{
$value = null;
fetchDatabaseConfig($name, $value);
return $value;
}
/**
* Register a new key pair in myaac database config.
*
* @param string $name Key name.
* @param string $value Data to be associated with key.
*/
function registerDatabaseConfig($name, $value)
{
global $db;
$db->insert(TABLE_PREFIX . 'config', array('name' => $name, 'value' => $value));
}
/**
* Updates a value in myaac database config.
*
* @param string $name Key name.
* @param string $value New data.
*/
function updateDatabaseConfig($name, $value)
{
global $db;
$db->update(TABLE_PREFIX . 'config', array('value' => $value), array('name' => $name));
}
/**
* Encrypt text using method specified in config.lua (encryptionType or passwordType)
*/
function encrypt($str)
{
global $config;
if(isset($config['database_salt'])) // otserv
$str .= $config['database_salt'];
$encryptionType = $config['database_encryption'];
if(isset($encryptionType) && strtolower($encryptionType) !== 'plain')
{
if($encryptionType === 'vahash')
return base64_encode(hash('sha256', $str));
return hash($encryptionType, $str);
}
return $str;
}
//delete player with name
function delete_player($name)
{
global $db;
$player = new OTS_Player();
$player->find($name);
if($player->isLoaded()) {
try { $db->exec("DELETE FROM player_skills WHERE player_id = '".$player->getId()."';"); } catch(PDOException $error) {}
try { $db->exec("DELETE FROM guild_invites WHERE player_id = '".$player->getId()."';"); } catch(PDOException $error) {}
try { $db->exec("DELETE FROM player_items WHERE player_id = '".$player->getId()."';"); } catch(PDOException $error) {}
try { $db->exec("DELETE FROM player_depotitems WHERE player_id = '".$player->getId()."';"); } catch(PDOException $error) {}
try { $db->exec("DELETE FROM player_spells WHERE player_id = '".$player->getId()."';"); } catch(PDOException $error) {}
try { $db->exec("DELETE FROM player_storage WHERE player_id = '".$player->getId()."';"); } catch(PDOException $error) {}
try { $db->exec("DELETE FROM player_viplist WHERE player_id = '".$player->getId()."';"); } catch(PDOException $error) {}
try { $db->exec("DELETE FROM player_deaths WHERE player_id = '".$player->getId()."';"); } catch(PDOException $error) {}
try { $db->exec("DELETE FROM player_deaths WHERE killed_by = '".$player->getId()."';"); } catch(PDOException $error) {}
$rank = $player->getRank();
if($rank->isLoaded()) {
$guild = $rank->getGuild();
if($guild->getOwner()->getId() == $player->getId()) {
$rank_list = $guild->getGuildRanksList();
if(count($rank_list) > 0) {
$rank_list->orderBy('level');
foreach($rank_list as $rank_in_guild) {
$players_with_rank = $rank_in_guild->getPlayersList();
$players_with_rank->orderBy('name');
$players_with_rank_number = count($players_with_rank);
if($players_with_rank_number > 0) {
foreach($players_with_rank as $player_in_guild) {
$player_in_guild->setRank();
$player_in_guild->save();
}
}
$rank_in_guild->delete();
}
$guild->delete();
}
}
}
$player->delete();
return true;
}
return false;
}
//delete guild with id
function delete_guild($id)
{
$guild = new OTS_Guild();
$guild->load($id);
if(!$guild->isLoaded())
return false;
$rank_list = $guild->getGuildRanksList();
if(count($rank_list) > 0) {
$rank_list->orderBy('level');
global $db, $ots;
foreach($rank_list as $rank_in_guild) {
if($db->hasTable('guild_members'))
$players_with_rank = $db->query('SELECT `players`.`id` as `id`, `guild_members`.`rank_id` as `rank_id` FROM `players`, `guild_members` WHERE `guild_members`.`rank_id` = ' . $rank_in_guild->getId() . ' AND `players`.`id` = `guild_members`.`player_id` ORDER BY `name`;');
else if($db->hasTable('guild_membership'))
$players_with_rank = $db->query('SELECT `players`.`id` as `id`, `guild_membership`.`rank_id` as `rank_id` FROM `players`, `guild_membership` WHERE `guild_membership`.`rank_id` = ' . $rank_in_guild->getId() . ' AND `players`.`id` = `guild_membership`.`player_id` ORDER BY `name`;');
else
$players_with_rank = $db->query('SELECT `id`, `rank_id` FROM `players` WHERE `rank_id` = ' . $rank_in_guild->getId() . ' AND `deleted` = 0;');
$players_with_rank_number = $players_with_rank->rowCount();
if($players_with_rank_number > 0) {
foreach($players_with_rank as $result) {
$player = new OTS_Player();
$player->load($result['id']);
if(!$player->isLoaded())
continue;
$player->setRank();
$player->save();
}
}
$rank_in_guild->delete();
}
}
$guild->delete();
return true;
}
//################### DISPLAY FUNCTIONS #####################
//return shorter text (news ticker)
function short_text($text, $limit)
{
if(strlen($text) > $limit)
return substr($text, 0, strrpos(substr($text, 0, $limit), " ")).'...';
return $text;
}
function tickers()
{
global $tickers_content, $featured_article;
if(PAGE === 'news') {
if(isset($tickers_content))
return $tickers_content . $featured_article;
}
return '';
}
/**
* Template place holder
*
* Types: head_start, head_end, body_start, body_end, center_top
*
*/
function template_place_holder($type)
{
global $twig, $template_place_holders;
$ret = '';
if(array_key_exists($type, $template_place_holders) && is_array($template_place_holders[$type]))
$ret = implode($template_place_holders[$type]);
if($type === 'head_start') {
$ret .= template_header();
}
elseif ($type === 'body_start') {
$ret .= $twig->render('browsehappy.html.twig');
}
elseif($type === 'body_end') {
$ret .= template_ga_code();
}
return $ret;
}
/**
* Returns <head> content to be used by templates.
*/
function template_header($is_admin = false)
{
global $title_full, $config;
$charset = isset($config['charset']) ? $config['charset'] : 'utf-8';
$ret = '
<meta charset="' . $charset . '">
<meta http-equiv="content-language" content="' . $config['language'] . '" />
<meta http-equiv="content-type" content="text/html; charset=' . $charset . '" />';
if(!$is_admin)
$ret .= '
<base href="' . BASE_URL . '" />
<title>' . $title_full . '</title>';
$ret .= '
<meta name="description" content="' . $config['meta_description'] . '" />
<meta name="keywords" content="' . $config['meta_keywords'] . ', myaac, wodzaac" />
<meta name="generator" content="MyAAC" />
<link rel="stylesheet" type="text/css" href="' . BASE_URL . 'tools/css/messages.css" />
<script type="text/javascript" src="' . BASE_URL . 'tools/js/jquery.min.js"></script>
<noscript>
<div class="warning" style="text-align: center; font-size: 14px;">Your browser does not support JavaScript or its disabled!<br/>
Please turn it on, or be aware that some features on this website will not work correctly.</div>
</noscript>
';
if($config['recaptcha_enabled'])
$ret .= "<script src='https://www.google.com/recaptcha/api.js'></script>";
return $ret;
}
/**
* Returns footer content to be used by templates.
*/
function template_footer()
{
global $config, $views_counter;
$ret = '';
if(admin())
$ret .= generateLink(ADMIN_URL, 'Admin Panel', true);
if($config['visitors_counter'])
{
global $visitors;
$amount = $visitors->getAmountVisitors();
$ret .= '<br/>Currently there ' . ($amount > 1 ? 'are' : 'is') . ' ' . $amount . ' visitor' . ($amount > 1 ? 's' : '') . '.';
}
if($config['views_counter'])
$ret .= '<br/>Page has been viewed ' . $views_counter . ' times.';
if(config('footer_show_load_time')) {
$ret .= '<br/>Load time: ' . round(microtime(true) - START_TIME, 4) . ' seconds.';
}
if(isset($config['footer'][0]))
$ret .= '<br/>' . $config['footer'];
// please respect my work and help spreading the word, thanks!
return $ret . '<br/>' . base64_decode('UG93ZXJlZCBieSA8YSBocmVmPSJodHRwOi8vbXktYWFjLm9yZyIgdGFyZ2V0PSJfYmxhbmsiPk15QUFDLjwvYT4=');
}
function template_ga_code()
{
global $config, $twig;
if(!isset($config['google_analytics_id'][0]))
return '';
return $twig->render('google_analytics.html.twig');
}
function template_form()
{
global $template_name;
$cache = Cache::getInstance();
if($cache->enabled())
{
$tmp = '';
if($cache->fetch('templates', $tmp)) {
$templates = unserialize($tmp);
}
else
{
$templates = get_templates();
$cache->set('templates', serialize($templates), 30);
}
}
else
$templates = get_templates();
$options = '';
foreach($templates as $key => $value)
$options .= '<option ' . ($template_name == $value ? 'SELECTED' : '') . '>' . $value . '</option>';
return '<form method="get" action="' . BASE_URL . '">
<hidden name="subtopic" value="' . PAGE . '"/>
<select name="template" onchange="this.form.submit()">' . $options . '</select>
</form>';
}
function getStyle($i)
{
global $config;
return is_int($i / 2) ? $config['darkborder'] : $config['lightborder'];
}
$vowels = array('e', 'y', 'u', 'i', 'o', 'a');
function getCreatureName($killer, $showStatus = false, $extendedInfo = false)
{
global $vowels, $ots, $config;
$str = "";
$players_rows = '';
if(is_numeric($killer))
{
$player = new OTS_Player();
$player->load($killer);
if($player->isLoaded())
{
$str .= '<a href="' . getPlayerLink($player->getName(), false) . '">';
if(!$showStatus)
return $str.'<b>'.$player->getName().'</b></a>';
$str .= '<span style="color: '.($player->isOnline() ? 'green' : 'red').'">' . $player->getName() . '</span></b></a>';
if($extendedInfo) {
$str .= '<br><small>'.$player->getLevel().' '.$player->getVocationName().'</small>';
}
return $str;
}
}
else
{
if($killer == "-1")
$players_rows .= "item or field";
else
{
if(in_array(strtolower($killer[0]), $vowels))
$players_rows .= "an ";
else
$players_rows .= "a ";
$players_rows .= $killer;
}
}
return $players_rows;
}
/**
* Find skill name using skill id.
*
* @param int $skillId Skill id.
* @param bool $suffix Should suffix also be added?
* @return string Skill name or 'unknown' if not found.
*/
function getSkillName($skillId, $suffix = true)
{
switch($skillId)
{
case POT::SKILL_FIST:
{
$tmp = 'fist';
if($suffix)
$tmp .= ' fighting';
return $tmp;
}
case POT::SKILL_CLUB:
{
$tmp = 'club';
if($suffix)
$tmp .= ' fighting';
return $tmp;
}
case POT::SKILL_SWORD:
{
$tmp = 'sword';
if($suffix)
$tmp .= ' fighting';
return $tmp;
}
case POT::SKILL_AXE:
{
$tmp = 'axe';
if($suffix)
$tmp .= ' fighting';
return $tmp;
}
case POT::SKILL_DIST:
{
$tmp = 'distance';
if($suffix)
$tmp .= ' fighting';
return $tmp;
}
case POT::SKILL_SHIELD:
return 'shielding';
case POT::SKILL_FISH:
return 'fishing';
case POT::SKILL__MAGLEVEL:
return 'magic level';
case POT::SKILL__LEVEL:
return 'level';
default:
break;
}
return 'unknown';
}
/**
* Performs flag check on the current logged in user.
* Table in database: accounts, field: website_flags
*
* @param int @flag Flag to be verified.
* @return bool If user got flag.
*/
function hasFlag($flag) {
global $logged, $logged_flags;
return ($logged && ($logged_flags & $flag) == $flag);
}
/**
* Check if current logged user have got admin flag set.
*/
function admin() {
return hasFlag(FLAG_ADMIN) || superAdmin();
}
/**
* Check if current logged user have got super admin flag set.
*/
function superAdmin() {
return hasFlag(FLAG_SUPER_ADMIN);
}
/**
* Format experience according to its amount (natural/negative number).
*
* @param int $exp Experience amount.
* @param bool $color Should result be colorized?
* @return string Resulted message attached in <span> tag.
*/
function formatExperience($exp, $color = true)
{
$ret = '';
if($color)
{
$ret .= '<span';
if($exp != 0) {
$ret .= ' style="color: ' . ($exp > 0 ? 'green' : 'red') . '">';
}
else {
$ret .= '>';
}
}
$ret .= '<b>' . ($exp > 0 ? '+' : '') . number_format($exp) . '</b>';
if($color)
$ret .= '</span>';
return $ret;
}
function get_locales()
{
$ret = array();
$path = LOCALE;
foreach(scandir($path, 0) as $file)
{
if($file[0] != '.' && $file != '..' && is_dir($path . $file))
$ret[] = $file;
}
return $ret;
}
function get_browser_languages()
{
$ret = array();
if(empty($_SERVER['HTTP_ACCEPT_LANGUAGE']))
return $ret;
$acceptLang = $_SERVER['HTTP_ACCEPT_LANGUAGE'];
$languages = strtolower($acceptLang);
// $languages = 'pl,en-us;q=0.7,en;q=0.3 ';
// need to remove spaces from strings to avoid error
$languages = str_replace(' ', '', $languages);
foreach(explode(',', $languages) as $language_list)
$ret[] .= substr($language_list, 0, 2);
return $ret;
}
/**
* Generates list of templates, according to templates/ dir.
*/
function get_templates()
{
$ret = array();
$path = TEMPLATES;
foreach(scandir($path, 0) as $file)
{
if($file[0] !== '.' && $file !== '..' && is_dir($path . $file))
$ret[] = $file;
}
return $ret;
}
/**
* Generates list of installed plugins
* @return array $plugins
*/
function get_plugins()
{
$ret = array();
$path = PLUGINS;
foreach(scandir($path, SCANDIR_SORT_ASCENDING) as $file) {
$file_ext = pathinfo($file, PATHINFO_EXTENSION);
$file_name = pathinfo($file, PATHINFO_FILENAME);
if ($file === '.' || $file === '..' || $file === 'disabled' || $file === 'example.json' || $file_ext !== 'json' || is_dir($path . $file))
continue;
$ret[] = str_replace('.json', '', $file_name);
}
return $ret;
}
function getWorldName($id)
{
global $config;
if(isset($config['worlds'][$id]))
return $config['worlds'][$id];
return $config['lua']['serverName'];
}
/**
* Mailing users.
* $config['mail_enabled'] have to be enabled.
*
* @param string $to Recipient email address.
* @param string $subject Subject of the message.
* @param string $body Message body in html format.
* @param string $altBody Alternative message body, plain text.
* @return bool PHPMailer status returned (success/failure).
*/
function _mail($to, $subject, $body, $altBody = '', $add_html_tags = true)
{
/** @var PHPMailer $mailer */
global $mailer, $config;
if(!$mailer)
{
require SYSTEM . 'libs/phpmailer/PHPMailerAutoload.php';
$mailer = new PHPMailer();
$mailer->setLanguage('en', LIBS . 'phpmailer/language/');
}
else {
$mailer->clearAllRecipients();
}
$signature_html = '';
if(isset($config['mail_signature']['html']))
$signature_html = $config['mail_signature']['html'];
if($add_html_tags && isset($body[0]))
$tmp_body = '<html><head></head><body>' . $body . '<br/><br/>' . $signature_html . '</body></html>';
else
$tmp_body = $body . '<br/><br/>' . $signature_html;
if($config['smtp_enabled'])
{
$mailer->isSMTP();
$mailer->Host = $config['smtp_host'];
$mailer->Port = (int)$config['smtp_port'];
$mailer->SMTPAuth = $config['smtp_auth'];
$mailer->Username = $config['smtp_user'];
$mailer->Password = $config['smtp_pass'];
$mailer->SMTPSecure = isset($config['smtp_secure']) ? $config['smtp_secure'] : '';
}
else {
$mailer->isMail();
}
$mailer->isHTML(isset($body[0]) > 0);
$mailer->From = $config['mail_address'];
$mailer->Sender = $config['mail_address'];
$mailer->CharSet = 'utf-8';
$mailer->FromName = $config['lua']['serverName'];
$mailer->Subject = $subject;
$mailer->addAddress($to);
$mailer->Body = $tmp_body;
if(config('smtp_debug')) {
$mailer->SMTPDebug = 2;
$mailer->Debugoutput = 'echo';
}
$signature_plain = '';
if(isset($config['mail_signature']['plain']))
$signature_plain = $config['mail_signature']['plain'];
if(isset($altBody[0])) {
$mailer->AltBody = $altBody . $signature_plain;
}
else { // automatically generate plain html
$mailer->AltBody = strip_tags(preg_replace('/<a(.*)href="([^"]*)"(.*)>/','$2', $body)) . "\n" . $signature_plain;
}
ob_start();
if(!$mailer->Send()) {
log_append('mailer-error.log', PHP_EOL . $mailer->ErrorInfo . PHP_EOL . ob_get_clean());
return false;
}
ob_end_clean();
return true;
}
function convert_bytes($size)
{
$unit = array('b', 'kb', 'mb', 'gb', 'tb', 'pb');
return @round($size / pow(1024, ($i = floor(log($size, 1024)))), 2) . ' ' . $unit[$i];
}
function log_append($file, $str, array $params = [])
{
if(count($params) > 0) {
$str .= print_r($params, true);
}
$f = fopen(LOGS . $file, 'ab');
fwrite($f, '[' . date(DateTime::RFC1123) . '] ' . $str . PHP_EOL);
fclose($f);
}
function load_config_lua($filename)
{
global $config;
$config_file = $filename;
if(!@file_exists($config_file))
{
log_append('error.log', '[load_config_file] Fatal error: Cannot load config.lua (' . $filename . ').');
throw new RuntimeException('ERROR: Cannot find ' . $filename . ' file.');
}
$result = array();
$config_string = str_replace(array("\r\n", "\r"), "\n", file_get_contents($filename));
$lines = explode("\n", $config_string);
if(count($lines) > 0) {
foreach($lines as $ln => $line)
{
$line = trim($line);
if(@$line[0] === '{' || @$line[0] === '}') {
// arrays are not supported yet
// just ignore the error
continue;
}
$tmp_exp = explode('=', $line, 2);
if(strpos($line, 'dofile') !== false)
{
$delimiter = '"';
if(strpos($line, $delimiter) === false)
$delimiter = "'";
$tmp = explode($delimiter, $line);
$result = array_merge($result, load_config_lua($config['server_path'] . $tmp[1]));
}
else if(count($tmp_exp) >= 2)
{
$key = trim($tmp_exp[0]);
if(0 !== strpos($key, '--'))
{
$value = trim($tmp_exp[1]);
if(strpos($value, '--') !== false) {// found some deep comment
$value = preg_replace('/--.*$/i', '', $value);
}
if(is_numeric($value))
$result[$key] = (float) $value;
elseif(in_array(@$value[0], array("'", '"')) && in_array(@$value[strlen($value) - 1], array("'", '"')))
$result[$key] = (string) substr(substr($value, 1), 0, -1);
elseif(in_array($value, array('true', 'false')))
$result[$key] = ($value === 'true') ? true : false;
elseif(@$value[0] === '{') {
// arrays are not supported yet
// just ignore the error
continue;
}
else
{
foreach($result as $tmp_key => $tmp_value) // load values definied by other keys, like: dailyFragsToBlackSkull = dailyFragsToRedSkull
$value = str_replace($tmp_key, $tmp_value, $value);
$ret = @eval("return $value;");
if((string) $ret == '' && trim($value) !== '""') // = parser error
{
throw new RuntimeException('ERROR: Loading config.lua file. Line <b>' . ($ln + 1) . '</b> of LUA config file is not valid [key: <b>' . $key . '</b>]');
}
$result[$key] = $ret;
}
}
}
}
}
$result = array_merge($result, isset($config['lua']) ? $config['lua'] : array());
return $result;
}
function str_replace_first($search, $replace, $subject) {
$pos = strpos($subject, $search);
if ($pos !== false) {
return substr_replace($subject, $replace, $pos, strlen($search));
}
return $subject;
}