source: trunk/includes/Global.php

Last change on this file was 894, checked in by chronos, 15 months ago
  • Fixed: Export error due to PHP 8.1 deprecated code.
  • Modified: Code cleanup.
File size: 26.5 KB
Line 
1<?php
2
3include_once(dirname(__FILE__).'/../Packages/Common/Common.php');
4if (file_exists(dirname(__FILE__).'/../Config/Config.php'))
5 include_once(dirname(__FILE__).'/../Config/Config.php');
6include_once(dirname(__FILE__).'/../Application/Core.php');
7include_once(dirname(__FILE__).'/../Application/View.php');
8include_once(dirname(__FILE__).'/../Application/Version.php');
9include_once(dirname(__FILE__).'/../Application/DefaultConfig.php');
10include_once(dirname(__FILE__).'/../Application/UpdateTrace.php');
11include_once(dirname(__FILE__).'/PageEdit.php');
12
13// Back compatibility, will be removed
14if (isset($InitSystem) and $InitSystem)
15{
16 $System = new Core();
17 $System->DoNotShowPage = true;
18 $System->Run();
19}
20
21class TempPage extends Page
22{
23 function Show(): string
24 {
25 global $TempPageContent;
26 return $TempPageContent;
27 }
28}
29
30function ShowPageClass($Page)
31{
32 global $TempPageContent, $System;
33
34 $System->Pages['temporary-page'] = get_class($Page);
35 $_SERVER['REDIRECT_QUERY_STRING'] = 'temporary-page';
36 $System->PathItems = ProcessURL();
37 $System->ShowPage();
38}
39
40function ShowPage($Content)
41{
42 global $TempPageContent, $System;
43
44 $TempPage = new TempPage($System);
45 $System->Pages['temporary-page'] = 'TempPage';
46 $_SERVER['REDIRECT_QUERY_STRING'] = 'temporary-page';
47 $TempPageContent = $Content;
48 $System->PathItems = ProcessURL();
49 $System->ShowPage();
50}
51
52function GetMicrotime()
53{
54 list($Usec, $Sec) = explode(' ', microtime());
55 return (float)$Usec + (float)$Sec;
56}
57
58$UnitNames = array('B', 'kB', 'MB', 'GB', 'TB', 'PB', 'EB');
59
60function HumanSize($Value)
61{
62 global $UnitNames;
63
64 $UnitIndex = 0;
65 while ($Value > 1024)
66 {
67 $Value = round($Value / 1024, 3);
68 $UnitIndex++;
69 }
70 return $Value.' '.$UnitNames[$UnitIndex];
71}
72
73function GetQueryStringArray($QueryString)
74{
75 $Result = array();
76 $Parts = explode('&', $QueryString);
77 foreach ($Parts as $Part)
78 {
79 if ($Part != '')
80 {
81 if (!strpos($Part, '=')) $Part .= '=';
82 $Item = explode('=', $Part);
83 $Result[$Item[0]] = $Item[1];
84 }
85 }
86 return $Result;
87}
88
89function SetQueryStringArray($QueryStringArray)
90{
91 $Parts = array();
92 foreach ($QueryStringArray as $Index => $Item)
93 {
94 $Parts[] = $Index.'='.$Item;
95 }
96 return implode('&amp;', $Parts);
97}
98
99function utf2ascii($text)
100{
101 $return = Str_Replace(
102 Array("á","č","ď","é","ě","í","ľ","ň","ó","ř","š","ť","ú","ů","ý","ž","Á","Č","Ď","É","Ě","Í","Ľ","Ň","Ó","Ř","Š","Ť","Ú","Ů","Ý","Ž") ,
103 Array("a","c","d","e","e","i","l","n","o","r","s","t","u","u","y","z","A","C","D","E","E","I","L","N","O","R","S","T","U","U","Y","Z") ,
104 $text);
105 //$return = Str_Replace(Array(" ", "_"), "-", $return); //nahradí mezery a podtržítka pomlčkami
106 //$return = Str_Replace(Array("(",")",".","!",",","\"","'"), "", $return); //odstraní ().!,"'
107 //$return = StrToLower($return); // velká písmena nahradí malými.
108 return $return;
109}
110
111function getmonthyears($Days)
112{
113 $month = floor($Days / 30);
114 $year = floor($month / 12);
115 $Days = floor($Days - $month * 30);
116 $month = $month - $year * 12;
117 return $year.'r '.$month.'m '.$Days.'d';
118}
119
120function GetTranslateGoogle($System, $text, $withouttitle = false)
121{
122// $text = 'Balthule\'s letter is dire. This Cult of the Dark Strand is a thorn in my side that must be removed. I have been dealing with some of the Dark Strand scum northeast of here at Ordil\'Aran. One of their number possesses a soul gem that I believe holds the secret to the cult\'s power.$b$bBring it to me, and I will be able to decipher the secrets held within.';
123 // $text = htmlspecialchars($text);
124
125 $text = str_replace('$B','$B ', $text);
126 $text = urlencode($text);
127 // $text = strtolower($text);
128// $text = str_replace('&','',$text);
129// $text = str_replace(' ','%20',$text);
130 $User = ModuleUser::Cast($System->GetModule('User'))->User;
131 $DbResult = $System->Database->select('Language', '`Code`', '`Id`='.$User->Language);
132 $DbRow = $DbResult->fetch_assoc();
133 $lang = $DbRow['Code'];
134 $url = 'https://translate.google.cz/?sl=en&tl='.$lang.'&text='.$text;
135
136 error_reporting(E_ALL ^ E_WARNING);
137 if (($handle = @fopen($url, "r")) === FALSE) return false;
138
139 $data = stream_get_contents($handle);
140 $data = substr($data, strpos($data, 'result_box'));
141 $data = substr($data, strpos($data, '>') + 1);
142 $data = substr($data, 0, strpos($data, '</div>'));
143
144 if ($withouttitle)
145 while ((strpos($data, '>') !== false and (strpos($data, '<') !== false)) and (strpos($data, '>') > strpos($data, '<')))
146 {
147 $partbefore = substr($data, 0, strpos($data, '<'));
148 // echo $partbefore;
149 $partafter = substr($data, strpos($data, '>') + 1);
150 // echo $partafter;
151 $data = $partbefore.' '.$partafter;
152 }
153
154 $Encoding = new Encoding();
155 $data = $Encoding->ToUTF8($data);
156 //$data = utf8_encode($data);
157
158 $data = str_replace('$ ', '$',$data);
159 $data = str_replace('$b $b', '$b$b', $data);
160 $data = str_replace('| ', '|', $data);
161
162 $data = strip_tags($data);
163
164 return $data;
165}
166
167function GetPageList($TotalCount)
168{
169 global $System;
170
171 $QueryItems = GetQueryStringArray($_SERVER['QUERY_STRING']);
172
173 $ItemPerPage = $System->Config['Web']['ItemsPerPage'];
174 $Around = round($System->Config['Web']['VisiblePagingItems'] / 2);
175 $Result = '';
176 $PageCount = floor($TotalCount / $ItemPerPage) + 1;
177
178 if (!array_key_exists('Page', $_SESSION)) $_SESSION['Page'] = 0;
179 if (array_key_exists('page', $_GET)) $_SESSION['Page'] = $_GET['page'] * 1;
180 if ($_SESSION['Page'] < 0) $_SESSION['Page'] = 0;
181 if ($_SESSION['Page'] >= $PageCount) $_SESSION['Page'] = $PageCount - 1;
182 $CurrentPage = $_SESSION['Page'];
183
184
185 $Result .= 'Počet položek: <strong>'.$TotalCount.'</strong> &nbsp; Stránky: ';
186
187 $Result = '';
188 if ($PageCount > 1)
189 {
190 if ($CurrentPage > 0)
191 {
192 $QueryItems['page'] = 0;
193 $Result.= '<a href="?'.SetQueryStringArray($QueryItems).'">&lt;&lt;</a> ';
194 $QueryItems['page'] = ($CurrentPage - 1);
195 $Result.= '<a href="?'.SetQueryStringArray($QueryItems).'">&lt;</a> ';
196 }
197 $PagesMax = $PageCount - 1;
198 $PagesMin = 0;
199 if ($PagesMax > ($CurrentPage + $Around)) $PagesMax = $CurrentPage + $Around;
200 if ($PagesMin < ($CurrentPage - $Around))
201 {
202 $Result.= ' ... ';
203 $PagesMin = $CurrentPage - $Around;
204 }
205 for ($i = $PagesMin; $i <= $PagesMax; $i++)
206 {
207 if ($i == $CurrentPage) $Result.= '<strong>'.($i + 1).'</strong> ';
208 else {
209 $QueryItems['page'] = $i;
210 $Result .= '<a href="?'.SetQueryStringArray($QueryItems).'">'.($i + 1).'</a> ';
211 }
212 }
213 if ($PagesMax < ($PageCount - 1)) $Result .= ' ... ';
214 if ($CurrentPage < ($PageCount - 1))
215 {
216 $QueryItems['page'] = ($CurrentPage + 1);
217 $Result.= '<a href="?'.SetQueryStringArray($QueryItems).'">&gt;</a> ';
218 $QueryItems['page'] = ($PageCount - 1);
219 $Result.= '<a href="?'.SetQueryStringArray($QueryItems).'">&gt;&gt;</a>';
220 }
221 }
222 $Result = '<div style="text-align: center">'.$Result.'</div>';
223 return array('SQLLimit' => ' LIMIT '.$CurrentPage * $ItemPerPage.', '.$ItemPerPage,
224 'Page' => $CurrentPage,
225 'Output' => $Result,
226 );
227}
228
229$OrderDirSQL = array('ASC', 'DESC');
230$OrderArrowImage = array('sort_asc.png', 'sort_desc.png');
231
232function GetOrderTableHeader($Columns, $DefaultColumn, $DefaultOrder = 0)
233{
234 global $OrderDirSQL, $OrderArrowImage, $Config, $System;
235
236 if (array_key_exists('OrderCol', $_GET)) $_SESSION['OrderCol'] = $_GET['OrderCol'];
237 if (array_key_exists('OrderDir', $_GET) and (array_key_exists($_GET['OrderDir'], $OrderArrowImage)))
238 $_SESSION['OrderDir'] = $_GET['OrderDir'];
239 if (!array_key_exists('OrderCol', $_SESSION)) $_SESSION['OrderCol'] = $DefaultColumn;
240 if (!array_key_exists('OrderDir', $_SESSION)) $_SESSION['OrderDir'] = $DefaultOrder;
241
242 // Check OrderCol
243 $Found = false;
244 foreach ($Columns as $Column)
245 {
246 if ($Column['Name'] == $_SESSION['OrderCol'])
247 {
248 $Found = true;
249 break;
250 }
251 }
252 if ($Found == false)
253 {
254 $_SESSION['OrderCol'] = $DefaultColumn;
255 $_SESSION['OrderDir'] = $DefaultOrder;
256 }
257 // Check OrderDir
258 if (($_SESSION['OrderDir'] != 0) and ($_SESSION['OrderDir'] != 1)) $_SESSION['OrderDir'] = 0;
259
260 $Result = '';
261 $QueryItems = GetQueryStringArray($_SERVER['QUERY_STRING']);
262 foreach ($Columns as $Index => $Column)
263 {
264 $QueryItems['OrderCol'] = $Column['Name'];
265 $QueryItems['OrderDir'] = 1 - $_SESSION['OrderDir'];
266 if ($Column['Name'] == $_SESSION['OrderCol']) $ArrowImage = '<img style="vertical-align: middle; border: 0px;" src="'.
267 $System->Link('/images/'.$OrderArrowImage[$_SESSION['OrderDir']]).'" alt="order arrow"/>';
268 else $ArrowImage = '';
269 if ($Column['Name'] == '') $Result .= '<th>'.$Column['Title'].'</th>';
270 else $Result .= '<th><a href="?'.SetQueryStringArray($QueryItems).'">'.$Column['Title'].$ArrowImage.'</a></th>';
271 }
272 return array(
273 'SQL' => ' ORDER BY `'.$_SESSION['OrderCol'].'` '.$OrderDirSQL[$_SESSION['OrderDir']],
274 'Output' => '<tr>'.$Result.'</tr>',
275 'Column' => $_SESSION['OrderCol'],
276 'Direction' => $_SESSION['OrderDir'],
277 );
278}
279
280function ClientVersionSelection($Selected)
281{
282 global $System;
283
284 $Output = '<select name="ClientVersion">';
285 $DbResult = $System->Database->select('ClientVersion', '`Id`, `Version`', '`Imported` = 1');
286 $Output .= '<option value=""';
287 if ($Selected == '')
288 $Output .= ' selected="selected"';
289 $Output .= '>'.T('None').'</option>';
290 while ($ClientVersion = $DbResult->fetch_assoc())
291 {
292 $Output .= '<option value="'.$ClientVersion['Id'].'"';
293 if ($Selected == $ClientVersion['Id'])
294 $Output .= ' selected="selected"';
295 $Output .= '>'.$ClientVersion['Version'].'</option>';
296 }
297 $Output .= '</select>';
298 return $Output;
299}
300
301function GetLanguageList()
302{
303 global $System;
304
305 $Result = array();
306 $DbResult = $System->Database->query('SELECT * FROM `Language` WHERE `Enabled` = 1');
307 while ($DbRow = $DbResult->fetch_assoc())
308 $Result[$DbRow['Id']] = $DbRow;
309 return $Result;
310}
311
312$Moderators = array('Překladatel', 'Moderátor', 'Administrátor');
313
314function HumanDate($SQLDateTime)
315{
316 if ($SQLDateTime == '') return '&nbsp;';
317 $DateTimeParts = explode(' ', $SQLDateTime);
318 if ($DateTimeParts[0] != '0000-00-00')
319 {
320 $DateParts = explode('-', $DateTimeParts[0]);
321 return ($DateParts[2] * 1).'.'.($DateParts[1] * 1).'.'.($DateParts[0] * 1);
322 } else return '&nbsp;';
323}
324
325function HumanDateTime($SQLDateTime)
326{
327 if ($SQLDateTime == '') return '&nbsp;';
328 $DateTimeParts = explode(' ', $SQLDateTime);
329 if ($DateTimeParts[0] != '0000-00-00' and $SQLDateTime <> '')
330 {
331 $DateParts = explode('-', $DateTimeParts[0]);
332 $Output = ($DateParts[2] * 1).'.'.($DateParts[1] * 1).'.'.($DateParts[0] * 1);
333 } else $Output = '&nbsp;';
334 if (count($DateTimeParts) > 1)
335 if ($DateTimeParts[1] != '00:00:00')
336 {
337 $TimeParts = explode(':', $DateTimeParts[1]);
338 $Output .= ' '.($TimeParts[0] * 1).':'.($TimeParts[1] * 1).':'.($TimeParts[2] * 1);
339 };
340 return $Output;
341}
342
343function FollowingTran($TextID, $Table, $GroupId, $Prev = false)
344{
345 global $System, $Config;
346
347 if ($Prev)
348 $sql = 'SELECT `ID` FROM `'.$Table.'` AS `item` WHERE '.
349 '(`Language` = '.$Config['OriginalLanguage'].') AND NOT EXISTS(SELECT `entry` '.
350 'FROM `'.$Table.'` AS `sub` WHERE (`sub`.`Language` <> '.$Config['OriginalLanguage'].') '.
351 'AND (`sub`.`entry` = `item`.`entry`)) AND (`ID` < '.$TextID.') ORDER BY `ID` DESC LIMIT 1';
352 else $sql = 'SELECT `ID` FROM `'.$Table.'` AS `item` WHERE '.
353 '(`Language` = '.$Config['OriginalLanguage'].') AND NOT EXISTS(SELECT `entry` '.
354 'FROM `'.$Table.'` AS `sub` WHERE (`sub`.`Language` <> '.$Config['OriginalLanguage'].') '.
355 'AND (`sub`.`entry` = `item`.`entry`)) AND `ID` > '.$TextID.' ORDER BY `ID` LIMIT 1';
356
357 $DbResult = $System->Database->query($sql);
358 $Next = $DbResult->fetch_assoc();
359 if ($Next)
360 {
361 if ($Prev) $Output = '<a href="form.php?group='.$GroupId.'&amp;ID='.$Next['ID'].'">Předcházející '.$Next['ID'].'</a> ';
362 else $Output = '<a href="form.php?group='.$GroupId.'&amp;ID='.$Next['ID'].'">Následující '.$Next['ID'].'</a> ';
363 return 'form.php?group='.$GroupId.'&amp;ID='.$Next['ID'];
364 }
365}
366
367function GetBuildNumber($Version)
368{
369 global $System, $BuildNumbers;
370
371 if (isset($BuildNumbers[$Version]) == false)
372 {
373 $sql = 'SELECT `BuildNumber` FROM `ClientVersion` WHERE `Version` = "'.$Version.'"';
374 $DbResult = $System->Database->query($sql);
375 $DbRow = $DbResult->fetch_assoc();
376 $BuildNumbers[$Version] = $DbRow['BuildNumber'];
377 }
378 return $BuildNumbers[$Version];
379}
380
381// TODO: Client version build number should not be used in internal references
382function GetVersionWOW($BuildNumber)
383{
384 global $System, $VersionsWOW;
385
386 if (isset($VersionsWOW[$BuildNumber]) == false)
387 {
388 $sql = 'SELECT `Version` FROM `ClientVersion` WHERE `BuildNumber` = "'.$BuildNumber.'"';
389 $DbResult = $System->Database->query($sql);
390 $Version = $DbResult->fetch_assoc();
391 $VersionsWOW[$BuildNumber] = $Version['Version'];
392 }
393 return $VersionsWOW[$BuildNumber];
394}
395
396// TODO: Client version build number should not be used in internal references
397function GetVersionWOWId($BuildNumber)
398{
399 global $System, $VersionsWOWId;
400
401 if (isset($VersionsWOWId[$BuildNumber]) == false)
402 {
403 $sql = 'SELECT `Id` FROM `ClientVersion` WHERE `BuildNumber` = "'.$BuildNumber.'"';
404 $DbResult = $System->Database->query($sql);
405 $Version = $DbResult->fetch_assoc();
406 $VersionsWOWId[$BuildNumber] = $Version['Id'];
407 }
408 return $VersionsWOWId[$BuildNumber];
409}
410
411function LoadGroupIdParameter()
412{
413 global $System;
414 $TranslationTree = ModuleTranslation::Cast($System->ModuleManager->GetModule('Translation'))->GetTranslationTree();
415
416 if (array_key_exists('group', $_GET)) $GroupId = $_GET['group'] * 1;
417 else $GroupId = 1;
418
419 if (isset($TranslationTree[$GroupId]) == false) ErrorMessage('Překladová skupina dle zadaného Id neexistuje.');
420 return $GroupId;
421}
422
423function LoadCommandLineParameters()
424{
425 if (!array_key_exists('REMOTE_ADDR', $_SERVER))
426 {
427 foreach ($_SERVER['argv'] as $Parameter)
428 {
429 if (strpos($Parameter, '=') !== false)
430 {
431 $Index = substr($Parameter, 0, strpos($Parameter, '='));
432 $Parameter = substr($Parameter, strpos($Parameter, '=') + 1);
433 //echo($Index.' ---- '.$Parameter);
434 $_GET[$Index] = $Parameter;
435 }
436 }
437 }
438}
439
440function ShowTabs($Tabs)
441{
442 $QueryItems = GetQueryStringArray($_SERVER['QUERY_STRING']);
443
444 if (array_key_exists('Tab', $_GET)) $_SESSION['Tab'] = $_GET['Tab'];
445 if (!array_key_exists('Tab', $_SESSION)) $_SESSION['Tab'] = 0;
446 if (($_SESSION['Tab'] < 0) or ($_SESSION['Tab'] > (count($Tabs) - 1))) $_SESSION['Tab'] = 0;
447 $Output = '<div id="header">'.
448 '<ul>';
449 foreach ($Tabs as $Index => $Tab)
450 {
451 $QueryItems['Tab'] = $Index;
452 if ($Index == $_SESSION['Tab']) $Selected = ' id="selected"';
453 else $Selected = '';
454 $Output .= '<li'.$Selected.'><a href="?'.SetQueryStringArray($QueryItems).'">'.$Tab.'</a></li>';
455 }
456 $Output .= '</ul></div>';
457 return $Output;
458}
459
460function CheckBox($Name, $Checked = false, $Id = '', $Class = '', $Disabled = false)
461{
462 if ($Id) $Id = ' id="'.$Id.'"'; else $Id = '';
463 if ($Class) $Class = ' class="'.$Class.'"'; else $Class = '';
464 if ($Checked) $Checked = ' checked="checked"'; else $Checked = '';
465 if ($Disabled) $Disabled = ' disabled="disabled"'; else $Disabled = '';
466 return '<input type="checkbox" value="checked" name="'.$Name.'"'.$Checked.$Disabled.$Id.$Class.' />';
467}
468
469function RadioButton($Name, $Value, $Checked = false, $OnClick = '', $Disabled = false)
470{
471 if ($Checked) $Checked = ' checked="checked"'; else $Checked = '';
472 if ($OnClick != '') $OnClick = ' onclick="'.$OnClick.'"'; else $OnClick = '';
473 if ($Disabled) $Disabled = ' disabled="disabled"'; else $Disabled = '';
474 return '<input type="radio" name="'.$Name.'" value="'.$Value.'"'.$Checked.$Disabled.$OnClick.'/>';
475}
476
477function SelectOption($Name, $Text, $Selected = false)
478{
479 if ($Selected) $Selected = ' selected="selected"'; else $Selected = '';
480 return '<option value="'.$Name.'"'.$Selected.'>'.$Text.'</option>';
481}
482
483function DeleteDirectory($dirname)
484{
485 if (is_dir($dirname))
486 {
487 $dir_handle = opendir($dirname);
488 if (!$dir_handle) return false;
489 while ($file = readdir($dir_handle))
490 {
491 if (($file != '.') and ($file != '..'))
492 {
493 if (!is_dir($dirname.'/'.$file)) unlink($dirname.'/'.$file);
494 else DeleteDirectory($dirname.'/'.$file);
495 }
496 }
497 closedir($dir_handle);
498 rmdir($dirname);
499 }
500 return true;
501}
502
503function ErrorMessage($Text)
504{
505 ShowPage($Text);
506 die();
507}
508
509function GetIDbyName($Table)
510{
511 global $System;
512
513 $TranslationTree = ModuleTranslation::Cast($System->ModuleManager->GetModule('Translation'))->GetTranslationTree();
514
515 foreach ($TranslationTree as $TableID => $Value)
516 {
517 if ($Value['TablePrefix'] == $Table) return $TableID;
518 }
519}
520
521function GetTranslatNamesArray()
522{
523 $TablesColumn = array
524 (
525 'TextGameObject' => 'Name',
526 'TextCreature' => 'name',
527 'TextTransport' => 'Name',
528 'TextAreaTriggerTeleport' => 'Name',
529 'TextAreaTriggerTavern' => 'Name',
530 'TextArea' => 'Name',
531 'TextAreaPOI' => 'Name',
532 'TextCharacterClass' => 'Name',
533 'TextCharacterRace' => 'Name1',
534 'TextItemSubClass' => 'Name',
535 'TextItemSubClass' => 'Name2',
536 'TextCreatureType' => 'Name',
537 'TextItem' => 'Name',
538 'Dictionary' => 'Text',
539 );
540 return $TablesColumn;
541}
542
543function GetTranslatNames($Text, $mode, $TablesColumn, $FirstBig = True)
544{
545 global $System, $Config;
546
547 /* $TablesID = array('gameobject' => 5,
548 'creature' => 6,
549 'item' => 4,
550 'transports' => 'Name',
551 'areatrigger_teleport' => 'Name',
552 'areatrigger_tavern' => 'Name',); */
553 $buff = array();
554
555 // change chars by we want to separate
556 $Text = str_replace('$B$B', ' ', $Text);
557 $Text = str_replace('$b$b', ' ', $Text);
558 $Text = str_replace('$G', ' ', $Text);
559 $Text = str_replace('$I', ' ', $Text);
560 $Text = str_replace('$N', ' ', $Text);
561 $Text = str_replace('$R', ' ', $Text);
562 $Text = str_replace('$g', ' ', $Text);
563 $Text = str_replace('$i', ' ', $Text);
564 $Text = str_replace('$n', ' ', $Text);
565 $Text = str_replace('$r', ' ', $Text);
566 $Text = str_replace(':', ' ', $Text);
567 $Text = str_replace(';', ' ', $Text);
568 $Text = str_replace('!', ' ', $Text);
569 $Text = str_replace('?', ' ', $Text);
570 $Text = str_replace('.', ' ', $Text);
571 $Text = str_replace(',', ' ', $Text);
572 $Text = str_replace('\'s', ' ', $Text);
573 $Text = str_replace('<', ' ', $Text);
574 $Text = str_replace('>', ' ', $Text);
575 $ArrStr = explode(' ', $Text);
576 $sqlall = '';
577
578 foreach ($TablesColumn as $Table => $Column)
579 {
580 $orderinby = ' ORDER BY ID DESC ';
581 $sql = 'SELECT `ID`, (SELECT CONCAT(\''.GetIDbyName($Table).'\' )) AS `GroupId`,`'.
582 $Column.'` AS Orig, (SELECT `'.$Column.'` FROM `'.$Table.'` AS `T` WHERE '.
583 '(`O`.`Entry` = `T`.`Entry`) AND (`Language` <> '.$Config['OriginalLanguage'].') '.
584 $orderinby.' LIMIT 1) AS `Tran` FROM `'.$Table.'` AS `O` WHERE ';
585 $groupby = ' GROUP BY `'.$Column.'` ';
586
587 $where = '(`Language` = '.$Config['OriginalLanguage'].') ';
588 if ($mode == 1)
589 {
590 $where .= ' AND EXISTS(SELECT 1 FROM `'.$Table.
591 '` AS `Sub` WHERE (`Sub`.`Language` <> '.$Config['OriginalLanguage'].
592 ') AND (`Sub`.`Entry` = `O`.`Entry`))';
593 }
594 if ($mode == 2)
595 {
596 $where .= ' AND NOT EXISTS(SELECT 1 FROM `'.$Table.
597 '` AS `Sub` WHERE (`Sub`.`Language` <> '.$Config['OriginalLanguage'].
598 ') AND (`Sub`.`Entry` = `O`.`Entry`))';
599 }
600 $where .= ' AND (';
601 if (array_search('the', $ArrStr))
602 {
603 $where .= '(`O`.`'.$Column.'` LIKE "The %") OR ';
604 }
605
606 $SqlOK = false;
607 if (count($ArrStr) > 0)
608 {
609 for ($i = 0; $i < count($ArrStr); $i++)
610 {
611 // find word only if is 3 characters and more, and if starts by upper char, and search only once
612 if ((strlen($ArrStr[$i]) > 3) or ( ((count($ArrStr) < 6) or ($i == 0)) and (strlen($ArrStr[$i]) > 0) ) ) //length
613 if ((!$FirstBig) or (ctype_upper(substr($ArrStr[$i], 0, 1))) or (count($ArrStr) < 6) ) //first big
614 if (array_search($ArrStr[$i], $ArrStr) == $i)
615 { // first in array
616 $where .= '(`O`.`'.$Column.'` LIKE "'.addslashes($ArrStr[$i]).'%") OR ';
617 $SqlOK = true;
618 }
619 }
620 $where = substr($where, 0, strlen($where) - 4);
621 $where .= ')';
622 }
623 if ($SqlOK)
624 {
625 //$sql.$where.$groupby.$orderby
626// $buff[] = array($Line['ID'], GetIDbyName($Table), $Line['Orig'], $Line['Tran']);
627 if ($sqlall <> '')
628 {
629 $sqlall .= ' UNION ALL ( '.$sql.$where.$groupby.' )';
630 } else {
631 $sqlall .= ' ( '.$sql.$where.$groupby.' )';
632 }
633 }
634 }
635 if ($SqlOK)
636 {
637 $orderby = ' ORDER BY LENGTH(Orig) DESC ';
638 // echo $sqlall. $orderby;
639 $DbResult = $System->Database->query($sqlall.$orderby);
640 // echo ($sql.'|'.$where.'|'.$groupby);
641 while ($Line = $DbResult->fetch_assoc())
642 {
643 $buff[] = array($Line['ID'], $Line['GroupId'], $Line['Orig'], $Line['Tran']);
644 }
645 }
646 return $buff;
647}
648
649function ProgressBar($Width, $Percent, $Text = '')
650{
651 $Pixels = $Width * ($Percent / 100);
652 if ($Pixels > $Width) $Pixels = $Width;
653 if ($Text == '') $Text = $Percent;
654
655 return '<div class="progressbar" style="width: '.$Width.'px">'.
656 '<div class="bar" style="width: '.$Pixels.'px;"></div>'.
657 '<div class="text" style="width: '.$Width.'px">'.$Text.'</div>'.
658 '</div>';
659}
660
661function GetLevelMinMax($XP)
662{
663 $IndexLevel = 100;
664
665 if ($XP > 0) $Level = floor(sqrt($XP / $IndexLevel));
666 else $Level = 0;
667 $MinXP = $Level * $Level * $IndexLevel;
668 $MaxXP = ($Level + 1) * ($Level + 1) * $IndexLevel;
669 $MaxXP = $MaxXP - $MinXP;
670 $XP = $XP - $MinXP;
671 return array('Level' => $Level, 'XP' => $XP, 'MaxXP' => $MaxXP);
672}
673
674function GetParameter($Name, $Default = '', $Numeric = false, $Session = false)
675{
676 $Result = $Default;
677 if (array_key_exists($Name, $_GET)) $Result = $_GET[$Name];
678 else if (array_key_exists($Name, $_POST)) $Result = $_POST[$Name];
679 else if ($Session and array_key_exists($Name, $_SESSION)) $Result = $_SESSION[$Name];
680 if ($Numeric and !is_numeric($Result)) $Result = $Default;
681 if ($Session) $_SESSION[$Name] = $Result;
682 return $Result;
683}
684
685function MakeActiveLinks($Content)
686{
687 $Content = htmlspecialchars($Content);
688 $Content = str_replace("\n", ' <br/>', $Content);
689 $Content = str_replace("\r", '', $Content);
690
691 $Result = '';
692 $I = 0;
693 while ((strpos($Content, 'http://') !== false) or (strpos($Content, 'https://') !== false))
694 {
695 if (strpos($Content, 'http://') !== false) $I = strpos($Content, 'http://');
696 if (strpos($Content, 'https://') !== false) $I = strpos($Content, 'https://');
697 $Result .= substr($Content, 0, $I);
698 $Content = substr($Content, $I);
699 $SpacePos = strpos($Content, ' ');
700 if ($SpacePos !== false) $URL = substr($Content, 0, strpos($Content, ' '));
701 else $URL = substr($Content, 0);
702
703 $Result .= '<a href="'.$URL.'">'.$URL.'</a>';
704 $Content = substr($Content, strlen($URL));
705 }
706 $Result .= $Content;
707 return $Result;
708}
709
710define('MESSAGE_WARNING', 0);
711define('MESSAGE_CRITICAL', 1);
712define('MESSAGE_INFORMATION', 2);
713
714function ShowMessage($Text, $Type = MESSAGE_INFORMATION)
715{
716 global $System;
717
718 $IconName = array(
719 MESSAGE_INFORMATION => 'information',
720 MESSAGE_WARNING => 'warning',
721 MESSAGE_CRITICAL => 'critical'
722 );
723 $BackgroundColor = array(
724 MESSAGE_INFORMATION => '#e0e0ff',
725 MESSAGE_WARNING => '#ffffe0',
726 MESSAGE_CRITICAL => '#ffe0e0'
727 );
728
729 return '<div class="message" style="background-color: '.$BackgroundColor[$Type].
730 ';"><table><tr><td class="icon"><img src="'.
731 $System->Link('/images/message/'.$IconName[$Type].'.png').'" alt="'.
732 $IconName[$Type].'"><td>'.$Text.'</td></tr></table></div>';
733}
734
735function ProcessURL()
736{
737 if (array_key_exists('REDIRECT_QUERY_STRING', $_SERVER))
738 $PathString = $_SERVER['REDIRECT_QUERY_STRING'];
739 else $PathString = '';
740 if (substr($PathString, -1, 1) == '/') $PathString = substr($PathString, 0, -1);
741 $PathItems = explode('/', $PathString);
742 if (strpos(GetRequestURI(), '?') !== false)
743 $_SERVER['QUERY_STRING'] = substr(GetRequestURI(), strpos(GetRequestURI(), '?') + 1);
744 else $_SERVER['QUERY_STRING'] = '';
745 parse_str($_SERVER['QUERY_STRING'], $_GET);
746 // SQL injection hack protection
747 foreach ($_GET as $Index => $Item) $_GET[$Index] = addslashes($_GET[$Index]);
748 return $PathItems;
749}
750
751function WriteLanguages($Selected)
752{
753 global $System;
754
755 $Output = '<select name="Language">';
756 $DbResult = $System->Database->select('Language', '`Id`, `Name`', '`Enabled` = 1');
757 while ($Language = $DbResult->fetch_assoc())
758 {
759 $Output .= '<option value="'.$Language['Id'].'"';
760 if ($Selected == $Language['Id'])
761 $Output .= ' selected="selected"';
762 $Output .= '>'.T($Language['Name']).'</option>';
763 }
764 $Output .= '</select>';
765 return $Output;
766}
767
768function GetClientProxyAddresses()
769{
770 if (array_key_exists('HTTP_X_FORWARDED_FOR',$_SERVER)) $IP = $_SERVER['HTTP_X_FORWARDED_FOR'];
771 else $IP = array();
772}
773
774function GetRemoteAddress()
775{
776 if (array_key_exists('REMOTE_ADDR', $_SERVER)) $IP = $_SERVER['REMOTE_ADDR'];
777 else $IP = '';
778 return $IP;
779}
780
781function GetRequestURI()
782{
783 if (array_key_exists('REQUEST_URI', $_SERVER)) return $_SERVER['REQUEST_URI'];
784 else return $_SERVER['PHP_SELF'];
785}
786
787function ShowBBcodes($text)
788{
789 // NOTE : I had to update this sample code with below line to prevent obvious attacks as pointed out by many users.
790 // Always ensure that user inputs are scanned and filtered properly.
791 $text = htmlspecialchars($text, ENT_QUOTES, 'UTF-8');
792
793 // BBcode array
794 $find = array(
795 '~\[b\](.*?)\[/b\]~s',
796 '~\[i\](.*?)\[/i\]~s',
797 '~\[u\](.*?)\[/u\]~s',
798 '~\[quote\](.*?)\[/quote\]~s',
799 '~\[size=(.*?)\](.*?)\[/size\]~s',
800 '~\[color=(.*?)\](.*?)\[/color\]~s',
801 '~\[url\]((?:ftp|https?)://.*?)\[/url\]~s',
802 '~\[img\](https?://.*?\.(?:jpg|jpeg|gif|png|bmp))\[/img\]~s'
803 );
804
805 // HTML tags to replace BBcode
806 $replace = array(
807 '<b>$1</b>',
808 '<i>$1</i>',
809 '<span style="text-decoration:underline;">$1</span>',
810 '<pre>$1</'.'pre>',
811 '<span style="font-size:$1px;">$2</span>',
812 '<span style="color:$1;">$2</span>',
813 '<a href="$1">$1</a>',
814 '<img src="$1" alt="" />'
815 );
816
817 // Replacing the BBcodes with corresponding HTML tags
818 return preg_replace($find, $replace, $text);
819}
820
821function NormalizePath(string $Path): string
822{
823 $Segments = explode('/', $Path);
824 $Result = array();
825 for ($I = 0; $I < count($Segments); $I++)
826 {
827 $Segment = $Segments[$I];
828 if (($Segment == '.') || ((strlen($Segment) == 0) && ($I > 0) && ($I < count($Segments) - 1)))
829 {
830 continue;
831 }
832 if ($Segment == '..')
833 {
834 array_pop($Result);
835 } else
836 {
837 array_push($Result, $Segment);
838 }
839 }
840 return implode('/', $Result);
841}
Note: See TracBrowser for help on using the repository browser.