source: trunk/includes/Global.php

Last change on this file was 901, checked in by chronos, 3 months ago
  • Fixed: More integer URL parameters checking.
  • Modified: More explicit function types.
File size: 27.3 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 $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(string $Content): void
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(): float
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(float $Value): string
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(string $QueryString): array
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(array $QueryStringArray): string
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(string $text): string
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(int $Days): string
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, string $text, bool $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(int $TotalCount): array
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 $Result .= 'Počet položek: <strong>'.$TotalCount.'</strong> &nbsp; Stránky: ';
185
186 $Result = '';
187 if ($PageCount > 1)
188 {
189 if ($CurrentPage > 0)
190 {
191 $QueryItems['page'] = 0;
192 $Result.= '<a href="?'.SetQueryStringArray($QueryItems).'">&lt;&lt;</a> ';
193 $QueryItems['page'] = ($CurrentPage - 1);
194 $Result.= '<a href="?'.SetQueryStringArray($QueryItems).'">&lt;</a> ';
195 }
196 $PagesMax = $PageCount - 1;
197 $PagesMin = 0;
198 if ($PagesMax > ($CurrentPage + $Around)) $PagesMax = $CurrentPage + $Around;
199 if ($PagesMin < ($CurrentPage - $Around))
200 {
201 $Result.= ' ... ';
202 $PagesMin = $CurrentPage - $Around;
203 }
204 for ($i = $PagesMin; $i <= $PagesMax; $i++)
205 {
206 if ($i == $CurrentPage) $Result.= '<strong>'.($i + 1).'</strong> ';
207 else {
208 $QueryItems['page'] = $i;
209 $Result .= '<a href="?'.SetQueryStringArray($QueryItems).'">'.($i + 1).'</a> ';
210 }
211 }
212 if ($PagesMax < ($PageCount - 1)) $Result .= ' ... ';
213 if ($CurrentPage < ($PageCount - 1))
214 {
215 $QueryItems['page'] = ($CurrentPage + 1);
216 $Result.= '<a href="?'.SetQueryStringArray($QueryItems).'">&gt;</a> ';
217 $QueryItems['page'] = ($PageCount - 1);
218 $Result.= '<a href="?'.SetQueryStringArray($QueryItems).'">&gt;&gt;</a>';
219 }
220 }
221 $Result = '<div style="text-align: center">'.$Result.'</div>';
222 return array('SQLLimit' => ' LIMIT '.$CurrentPage * $ItemPerPage.', '.$ItemPerPage,
223 'Page' => $CurrentPage,
224 'Output' => $Result,
225 );
226}
227
228$OrderDirSQL = array('ASC', 'DESC');
229$OrderArrowImage = array('sort_asc.png', 'sort_desc.png');
230
231function GetOrderTableHeader(array $Columns, string $DefaultColumn, int $DefaultOrder = 0): array
232{
233 global $OrderDirSQL, $OrderArrowImage, $System;
234
235 if (array_key_exists('OrderCol', $_GET)) $_SESSION['OrderCol'] = $_GET['OrderCol'];
236 if (array_key_exists('OrderDir', $_GET) and (array_key_exists($_GET['OrderDir'], $OrderArrowImage)))
237 $_SESSION['OrderDir'] = $_GET['OrderDir'];
238 if (!array_key_exists('OrderCol', $_SESSION)) $_SESSION['OrderCol'] = $DefaultColumn;
239 if (!array_key_exists('OrderDir', $_SESSION)) $_SESSION['OrderDir'] = $DefaultOrder;
240
241 // Check OrderCol
242 $Found = false;
243 foreach ($Columns as $Column)
244 {
245 if ($Column['Name'] == $_SESSION['OrderCol'])
246 {
247 $Found = true;
248 break;
249 }
250 }
251 if ($Found == false)
252 {
253 $_SESSION['OrderCol'] = $DefaultColumn;
254 $_SESSION['OrderDir'] = $DefaultOrder;
255 }
256 // Check OrderDir
257 if (($_SESSION['OrderDir'] != 0) and ($_SESSION['OrderDir'] != 1)) $_SESSION['OrderDir'] = 0;
258
259 $Result = '';
260 $QueryItems = GetQueryStringArray($_SERVER['QUERY_STRING']);
261 foreach ($Columns as $Index => $Column)
262 {
263 $QueryItems['OrderCol'] = $Column['Name'];
264 $QueryItems['OrderDir'] = 1 - $_SESSION['OrderDir'];
265 if ($Column['Name'] == $_SESSION['OrderCol']) $ArrowImage = '<img style="vertical-align: middle; border: 0px;" src="'.
266 $System->Link('/images/'.$OrderArrowImage[$_SESSION['OrderDir']]).'" alt="order arrow"/>';
267 else $ArrowImage = '';
268 if ($Column['Name'] == '') $Result .= '<th>'.$Column['Title'].'</th>';
269 else $Result .= '<th><a href="?'.SetQueryStringArray($QueryItems).'">'.$Column['Title'].$ArrowImage.'</a></th>';
270 }
271 return array(
272 'SQL' => ' ORDER BY `'.$_SESSION['OrderCol'].'` '.$OrderDirSQL[$_SESSION['OrderDir']],
273 'Output' => '<tr>'.$Result.'</tr>',
274 'Column' => $_SESSION['OrderCol'],
275 'Direction' => $_SESSION['OrderDir'],
276 );
277}
278
279function ClientVersionSelection(string $Selected): string
280{
281 global $System;
282
283 $Output = '<select name="ClientVersion">';
284 $DbResult = $System->Database->select('ClientVersion', '`Id`, `Version`', '`Imported` = 1');
285 $Output .= '<option value=""';
286 if ($Selected == '')
287 $Output .= ' selected="selected"';
288 $Output .= '>'.T('None').'</option>';
289 while ($ClientVersion = $DbResult->fetch_assoc())
290 {
291 $Output .= '<option value="'.$ClientVersion['Id'].'"';
292 if ($Selected == $ClientVersion['Id'])
293 $Output .= ' selected="selected"';
294 $Output .= '>'.$ClientVersion['Version'].'</option>';
295 }
296 $Output .= '</select>';
297 return $Output;
298}
299
300function GetLanguageList(): array
301{
302 global $System;
303
304 $Result = array();
305 $DbResult = $System->Database->query('SELECT * FROM `Language` WHERE `Enabled` = 1');
306 while ($DbRow = $DbResult->fetch_assoc())
307 $Result[$DbRow['Id']] = $DbRow;
308 return $Result;
309}
310
311$Moderators = array('Překladatel', 'Moderátor', 'Administrátor');
312
313function HumanDate(string $SQLDateTime): string
314{
315 if ($SQLDateTime == '') return '&nbsp;';
316 $DateTimeParts = explode(' ', $SQLDateTime);
317 if ($DateTimeParts[0] != '0000-00-00')
318 {
319 $DateParts = explode('-', $DateTimeParts[0]);
320 return ($DateParts[2] * 1).'.'.($DateParts[1] * 1).'.'.($DateParts[0] * 1);
321 } else return '&nbsp;';
322}
323
324function HumanDateTime(string $SQLDateTime): string
325{
326 if ($SQLDateTime == '') return '&nbsp;';
327 $DateTimeParts = explode(' ', $SQLDateTime);
328 if ($DateTimeParts[0] != '0000-00-00' and $SQLDateTime <> '')
329 {
330 $DateParts = explode('-', $DateTimeParts[0]);
331 $Output = ($DateParts[2] * 1).'.'.($DateParts[1] * 1).'.'.($DateParts[0] * 1);
332 } else $Output = '&nbsp;';
333 if (count($DateTimeParts) > 1)
334 if ($DateTimeParts[1] != '00:00:00')
335 {
336 $TimeParts = explode(':', $DateTimeParts[1]);
337 $Output .= ' '.($TimeParts[0] * 1).':'.($TimeParts[1] * 1).':'.($TimeParts[2] * 1);
338 };
339 return $Output;
340}
341
342function FollowingTran($TextID, $Table, $GroupId, $Prev = false)
343{
344 global $System, $Config;
345
346 if ($Prev)
347 $sql = 'SELECT `ID` FROM `'.$Table.'` AS `item` WHERE '.
348 '(`Language` = '.$Config['OriginalLanguage'].') AND NOT EXISTS(SELECT `entry` '.
349 'FROM `'.$Table.'` AS `sub` WHERE (`sub`.`Language` <> '.$Config['OriginalLanguage'].') '.
350 'AND (`sub`.`entry` = `item`.`entry`)) AND (`ID` < '.$TextID.') ORDER BY `ID` DESC LIMIT 1';
351 else $sql = 'SELECT `ID` FROM `'.$Table.'` AS `item` WHERE '.
352 '(`Language` = '.$Config['OriginalLanguage'].') AND NOT EXISTS(SELECT `entry` '.
353 'FROM `'.$Table.'` AS `sub` WHERE (`sub`.`Language` <> '.$Config['OriginalLanguage'].') '.
354 'AND (`sub`.`entry` = `item`.`entry`)) AND `ID` > '.$TextID.' ORDER BY `ID` LIMIT 1';
355
356 $DbResult = $System->Database->query($sql);
357 $Next = $DbResult->fetch_assoc();
358 if ($Next)
359 {
360 if ($Prev) $Output = '<a href="form.php?group='.$GroupId.'&amp;ID='.$Next['ID'].'">Předcházející '.$Next['ID'].'</a> ';
361 else $Output = '<a href="form.php?group='.$GroupId.'&amp;ID='.$Next['ID'].'">Následující '.$Next['ID'].'</a> ';
362 return 'form.php?group='.$GroupId.'&amp;ID='.$Next['ID'];
363 }
364}
365
366function GetBuildNumber(string $Version): int
367{
368 global $System, $BuildNumbers;
369
370 if (!isset($BuildNumbers)) $BuildNumbers = array();
371 if (!array_key_exists($Version, $BuildNumbers))
372 {
373 $DbResult = $System->Database->select('ClientVersion', 'BuildNumber', '`Version` = "'.$Version.'"');
374 if ($DbResult->num_rows == 1)
375 {
376 $DbRow = $DbResult->fetch_assoc();
377 $BuildNumbers[$Version] = $DbRow['BuildNumber'];
378 } else return 0;
379 }
380 return $BuildNumbers[$Version];
381}
382
383// TODO: Client version build number should not be used in internal references
384function GetVersionWOW(int $BuildNumber): string
385{
386 global $System, $VersionsWOW;
387
388 if (!isset($VersionsWOW)) $VersionsWOW = array();
389 if (!array_key_exists($BuildNumber, $VersionsWOW))
390 {
391 $DbResult = $System->Database->select('ClientVersion', 'Version', '`BuildNumber` = "'.$BuildNumber.'"');
392 if ($DbResult->num_rows == 1)
393 {
394 $Version = $DbResult->fetch_assoc();
395 $VersionsWOW[$BuildNumber] = $Version['Version'];
396 } else return '';
397 }
398 return $VersionsWOW[$BuildNumber];
399}
400
401// TODO: Client version build number should not be used in internal references
402function GetVersionWOWId($BuildNumber)
403{
404 global $System, $VersionsWOWId;
405
406 if (isset($VersionsWOWId[$BuildNumber]) == false)
407 {
408 $sql = 'SELECT `Id` FROM `ClientVersion` WHERE `BuildNumber` = "'.$BuildNumber.'"';
409 $DbResult = $System->Database->query($sql);
410 $Version = $DbResult->fetch_assoc();
411 $VersionsWOWId[$BuildNumber] = $Version['Id'];
412 }
413 return $VersionsWOWId[$BuildNumber];
414}
415
416function LoadGroupIdParameter()
417{
418 global $System;
419 $TranslationTree = ModuleTranslation::Cast($System->ModuleManager->GetModule('Translation'))->GetTranslationTree();
420
421 $GroupId = 0;
422 if (TryGetUrlParameterInt('group', $GroupId))
423 {
424 if (isset($TranslationTree[$GroupId]) == false) ErrorMessage('Překladová skupina dle zadaného Id neexistuje.');
425 return $GroupId;
426 }
427 ErrorMessage('Group not valid.');
428}
429
430function LoadCommandLineParameters(): void
431{
432 if (!array_key_exists('REMOTE_ADDR', $_SERVER))
433 {
434 foreach ($_SERVER['argv'] as $Parameter)
435 {
436 if (strpos($Parameter, '=') !== false)
437 {
438 $Index = substr($Parameter, 0, strpos($Parameter, '='));
439 $Parameter = substr($Parameter, strpos($Parameter, '=') + 1);
440 //echo($Index.' ---- '.$Parameter);
441 $_GET[$Index] = $Parameter;
442 }
443 }
444 }
445}
446
447function ShowTabs(array $Tabs): string
448{
449 $QueryItems = GetQueryStringArray($_SERVER['QUERY_STRING']);
450
451 if (array_key_exists('Tab', $_GET)) $_SESSION['Tab'] = $_GET['Tab'];
452 if (!array_key_exists('Tab', $_SESSION)) $_SESSION['Tab'] = 0;
453 if (($_SESSION['Tab'] < 0) or ($_SESSION['Tab'] > (count($Tabs) - 1))) $_SESSION['Tab'] = 0;
454 $Output = '<div id="header">'.
455 '<ul>';
456 foreach ($Tabs as $Index => $Tab)
457 {
458 $QueryItems['Tab'] = $Index;
459 if ($Index == $_SESSION['Tab']) $Selected = ' id="selected"';
460 else $Selected = '';
461 $Output .= '<li'.$Selected.'><a href="?'.SetQueryStringArray($QueryItems).'">'.$Tab.'</a></li>';
462 }
463 $Output .= '</ul></div>';
464 return $Output;
465}
466
467function CheckBox($Name, $Checked = false, $Id = '', $Class = '', $Disabled = false)
468{
469 if ($Id) $Id = ' id="'.$Id.'"'; else $Id = '';
470 if ($Class) $Class = ' class="'.$Class.'"'; else $Class = '';
471 if ($Checked) $Checked = ' checked="checked"'; else $Checked = '';
472 if ($Disabled) $Disabled = ' disabled="disabled"'; else $Disabled = '';
473 return '<input type="checkbox" value="checked" name="'.$Name.'"'.$Checked.$Disabled.$Id.$Class.' />';
474}
475
476function RadioButton($Name, $Value, $Checked = false, $OnClick = '', $Disabled = false)
477{
478 if ($Checked) $Checked = ' checked="checked"'; else $Checked = '';
479 if ($OnClick != '') $OnClick = ' onclick="'.$OnClick.'"'; else $OnClick = '';
480 if ($Disabled) $Disabled = ' disabled="disabled"'; else $Disabled = '';
481 return '<input type="radio" name="'.$Name.'" value="'.$Value.'"'.$Checked.$Disabled.$OnClick.'/>';
482}
483
484function SelectOption($Name, $Text, $Selected = false)
485{
486 if ($Selected) $Selected = ' selected="selected"'; else $Selected = '';
487 return '<option value="'.$Name.'"'.$Selected.'>'.$Text.'</option>';
488}
489
490function DeleteDirectory(string $dirname): bool
491{
492 if (is_dir($dirname))
493 {
494 $dir_handle = opendir($dirname);
495 if (!$dir_handle) return false;
496 while ($file = readdir($dir_handle))
497 {
498 if (($file != '.') and ($file != '..'))
499 {
500 if (!is_dir($dirname.'/'.$file)) unlink($dirname.'/'.$file);
501 else DeleteDirectory($dirname.'/'.$file);
502 }
503 }
504 closedir($dir_handle);
505 rmdir($dirname);
506 }
507 return true;
508}
509
510function ErrorMessage(string $Text): void
511{
512 ShowPage($Text);
513 die();
514}
515
516function GetIDbyName(string $Table)
517{
518 global $System;
519
520 $TranslationTree = ModuleTranslation::Cast($System->ModuleManager->GetModule('Translation'))->GetTranslationTree();
521
522 foreach ($TranslationTree as $TableID => $Value)
523 {
524 if ($Value['TablePrefix'] == $Table) return $TableID;
525 }
526}
527
528function GetTranslatNamesArray(): array
529{
530 $TablesColumn = array
531 (
532 'TextGameObject' => 'Name',
533 'TextCreature' => 'name',
534 'TextTransport' => 'Name',
535 'TextAreaTriggerTeleport' => 'Name',
536 'TextAreaTriggerTavern' => 'Name',
537 'TextArea' => 'Name',
538 'TextAreaPOI' => 'Name',
539 'TextCharacterClass' => 'Name',
540 'TextCharacterRace' => 'Name1',
541 'TextItemSubClass' => 'Name',
542 'TextItemSubClass' => 'Name2',
543 'TextCreatureType' => 'Name',
544 'TextItem' => 'Name',
545 'Dictionary' => 'Text',
546 );
547 return $TablesColumn;
548}
549
550function GetTranslatNames($Text, $mode, $TablesColumn, $FirstBig = True)
551{
552 global $System, $Config;
553
554 /* $TablesID = array('gameobject' => 5,
555 'creature' => 6,
556 'item' => 4,
557 'transports' => 'Name',
558 'areatrigger_teleport' => 'Name',
559 'areatrigger_tavern' => 'Name',); */
560 $buff = array();
561
562 // change chars by we want to separate
563 $Text = str_replace('$B$B', ' ', $Text);
564 $Text = str_replace('$b$b', ' ', $Text);
565 $Text = str_replace('$G', ' ', $Text);
566 $Text = str_replace('$I', ' ', $Text);
567 $Text = str_replace('$N', ' ', $Text);
568 $Text = str_replace('$R', ' ', $Text);
569 $Text = str_replace('$g', ' ', $Text);
570 $Text = str_replace('$i', ' ', $Text);
571 $Text = str_replace('$n', ' ', $Text);
572 $Text = str_replace('$r', ' ', $Text);
573 $Text = str_replace(':', ' ', $Text);
574 $Text = str_replace(';', ' ', $Text);
575 $Text = str_replace('!', ' ', $Text);
576 $Text = str_replace('?', ' ', $Text);
577 $Text = str_replace('.', ' ', $Text);
578 $Text = str_replace(',', ' ', $Text);
579 $Text = str_replace('\'s', ' ', $Text);
580 $Text = str_replace('<', ' ', $Text);
581 $Text = str_replace('>', ' ', $Text);
582 $ArrStr = explode(' ', $Text);
583 $sqlall = '';
584
585 foreach ($TablesColumn as $Table => $Column)
586 {
587 $orderinby = ' ORDER BY ID DESC ';
588 $sql = 'SELECT `ID`, (SELECT CONCAT(\''.GetIDbyName($Table).'\' )) AS `GroupId`,`'.
589 $Column.'` AS Orig, (SELECT `'.$Column.'` FROM `'.$Table.'` AS `T` WHERE '.
590 '(`O`.`Entry` = `T`.`Entry`) AND (`Language` <> '.$Config['OriginalLanguage'].') '.
591 $orderinby.' LIMIT 1) AS `Tran` FROM `'.$Table.'` AS `O` WHERE ';
592 $groupby = ' GROUP BY `'.$Column.'` ';
593
594 $where = '(`Language` = '.$Config['OriginalLanguage'].') ';
595 if ($mode == 1)
596 {
597 $where .= ' AND EXISTS(SELECT 1 FROM `'.$Table.
598 '` AS `Sub` WHERE (`Sub`.`Language` <> '.$Config['OriginalLanguage'].
599 ') AND (`Sub`.`Entry` = `O`.`Entry`))';
600 }
601 if ($mode == 2)
602 {
603 $where .= ' AND NOT EXISTS(SELECT 1 FROM `'.$Table.
604 '` AS `Sub` WHERE (`Sub`.`Language` <> '.$Config['OriginalLanguage'].
605 ') AND (`Sub`.`Entry` = `O`.`Entry`))';
606 }
607 $where .= ' AND (';
608 if (array_search('the', $ArrStr))
609 {
610 $where .= '(`O`.`'.$Column.'` LIKE "The %") OR ';
611 }
612
613 $SqlOK = false;
614 if (count($ArrStr) > 0)
615 {
616 for ($i = 0; $i < count($ArrStr); $i++)
617 {
618 // find word only if is 3 characters and more, and if starts by upper char, and search only once
619 if ((strlen($ArrStr[$i]) > 3) or ( ((count($ArrStr) < 6) or ($i == 0)) and (strlen($ArrStr[$i]) > 0) ) ) //length
620 if ((!$FirstBig) or (ctype_upper(substr($ArrStr[$i], 0, 1))) or (count($ArrStr) < 6) ) //first big
621 if (array_search($ArrStr[$i], $ArrStr) == $i)
622 { // first in array
623 $where .= '(`O`.`'.$Column.'` LIKE "'.addslashes($ArrStr[$i]).'%") OR ';
624 $SqlOK = true;
625 }
626 }
627 $where = substr($where, 0, strlen($where) - 4);
628 $where .= ')';
629 }
630 if ($SqlOK)
631 {
632 //$sql.$where.$groupby.$orderby
633// $buff[] = array($Line['ID'], GetIDbyName($Table), $Line['Orig'], $Line['Tran']);
634 if ($sqlall <> '')
635 {
636 $sqlall .= ' UNION ALL ( '.$sql.$where.$groupby.' )';
637 } else {
638 $sqlall .= ' ( '.$sql.$where.$groupby.' )';
639 }
640 }
641 }
642 if ($SqlOK)
643 {
644 $orderby = ' ORDER BY LENGTH(Orig) DESC ';
645 // echo $sqlall. $orderby;
646 $DbResult = $System->Database->query($sqlall.$orderby);
647 // echo ($sql.'|'.$where.'|'.$groupby);
648 while ($Line = $DbResult->fetch_assoc())
649 {
650 $buff[] = array($Line['ID'], $Line['GroupId'], $Line['Orig'], $Line['Tran']);
651 }
652 }
653 return $buff;
654}
655
656function ProgressBar($Width, $Percent, $Text = '')
657{
658 $Pixels = $Width * ($Percent / 100);
659 if ($Pixels > $Width) $Pixels = $Width;
660 if ($Text == '') $Text = $Percent;
661
662 return '<div class="progressbar" style="width: '.$Width.'px">'.
663 '<div class="bar" style="width: '.$Pixels.'px;"></div>'.
664 '<div class="text" style="width: '.$Width.'px">'.$Text.'</div>'.
665 '</div>';
666}
667
668function GetLevelMinMax(int $XP): array
669{
670 $IndexLevel = 100;
671
672 if ($XP > 0) $Level = floor(sqrt($XP / $IndexLevel));
673 else $Level = 0;
674 $MinXP = $Level * $Level * $IndexLevel;
675 $MaxXP = ($Level + 1) * ($Level + 1) * $IndexLevel;
676 $MaxXP = $MaxXP - $MinXP;
677 $XP = $XP - $MinXP;
678 return array('Level' => $Level, 'XP' => $XP, 'MaxXP' => $MaxXP);
679}
680
681function GetParameter(string $Name, string $Default = '', bool $Numeric = false, bool $Session = false): string
682{
683 $Result = $Default;
684 if (array_key_exists($Name, $_GET)) $Result = $_GET[$Name];
685 else if (array_key_exists($Name, $_POST)) $Result = $_POST[$Name];
686 else if ($Session and array_key_exists($Name, $_SESSION)) $Result = $_SESSION[$Name];
687 if ($Numeric and !is_numeric($Result)) $Result = $Default;
688 if ($Session) $_SESSION[$Name] = $Result;
689 return $Result;
690}
691
692function MakeActiveLinks(string $Content): string
693{
694 $Content = htmlspecialchars($Content);
695 $Content = str_replace("\n", ' <br/>', $Content);
696 $Content = str_replace("\r", '', $Content);
697
698 $Result = '';
699 $I = 0;
700 while ((strpos($Content, 'http://') !== false) or (strpos($Content, 'https://') !== false))
701 {
702 if (strpos($Content, 'http://') !== false) $I = strpos($Content, 'http://');
703 if (strpos($Content, 'https://') !== false) $I = strpos($Content, 'https://');
704 $Result .= substr($Content, 0, $I);
705 $Content = substr($Content, $I);
706 $SpacePos = strpos($Content, ' ');
707 if ($SpacePos !== false) $URL = substr($Content, 0, strpos($Content, ' '));
708 else $URL = substr($Content, 0);
709
710 $Result .= '<a href="'.$URL.'">'.$URL.'</a>';
711 $Content = substr($Content, strlen($URL));
712 }
713 $Result .= $Content;
714 return $Result;
715}
716
717define('MESSAGE_WARNING', 0);
718define('MESSAGE_CRITICAL', 1);
719define('MESSAGE_INFORMATION', 2);
720
721function ShowMessage(string $Text, int $Type = MESSAGE_INFORMATION)
722{
723 global $System;
724
725 $IconName = array(
726 MESSAGE_INFORMATION => 'information',
727 MESSAGE_WARNING => 'warning',
728 MESSAGE_CRITICAL => 'critical'
729 );
730 $BackgroundColor = array(
731 MESSAGE_INFORMATION => '#e0e0ff',
732 MESSAGE_WARNING => '#ffffe0',
733 MESSAGE_CRITICAL => '#ffe0e0'
734 );
735
736 return '<div class="message" style="background-color: '.$BackgroundColor[$Type].
737 ';"><table><tr><td class="icon"><img src="'.
738 $System->Link('/images/message/'.$IconName[$Type].'.png').'" alt="'.
739 $IconName[$Type].'"><td>'.$Text.'</td></tr></table></div>';
740}
741
742function ProcessURL(): array
743{
744 if (array_key_exists('REDIRECT_QUERY_STRING', $_SERVER))
745 $PathString = $_SERVER['REDIRECT_QUERY_STRING'];
746 else $PathString = '';
747 if (substr($PathString, -1, 1) == '/') $PathString = substr($PathString, 0, -1);
748 $PathItems = explode('/', $PathString);
749 if (strpos(GetRequestURI(), '?') !== false)
750 $_SERVER['QUERY_STRING'] = substr(GetRequestURI(), strpos(GetRequestURI(), '?') + 1);
751 else $_SERVER['QUERY_STRING'] = '';
752 parse_str($_SERVER['QUERY_STRING'], $_GET);
753 // SQL injection hack protection
754 foreach ($_GET as $Index => $Item) $_GET[$Index] = addslashes($_GET[$Index]);
755 return $PathItems;
756}
757
758function WriteLanguages($Selected)
759{
760 global $System;
761
762 $Output = '<select name="Language">';
763 $DbResult = $System->Database->select('Language', '`Id`, `Name`', '`Enabled` = 1');
764 while ($Language = $DbResult->fetch_assoc())
765 {
766 $Output .= '<option value="'.$Language['Id'].'"';
767 if ($Selected == $Language['Id'])
768 $Output .= ' selected="selected"';
769 $Output .= '>'.T($Language['Name']).'</option>';
770 }
771 $Output .= '</select>';
772 return $Output;
773}
774
775function GetClientProxyAddresses()
776{
777 if (array_key_exists('HTTP_X_FORWARDED_FOR',$_SERVER)) $IP = $_SERVER['HTTP_X_FORWARDED_FOR'];
778 else $IP = array();
779}
780
781function GetRemoteAddress()
782{
783 if (array_key_exists('REMOTE_ADDR', $_SERVER)) $IP = $_SERVER['REMOTE_ADDR'];
784 else $IP = '';
785 return $IP;
786}
787
788function GetRequestURI()
789{
790 if (array_key_exists('REQUEST_URI', $_SERVER)) return $_SERVER['REQUEST_URI'];
791 else return $_SERVER['PHP_SELF'];
792}
793
794function ShowBBcodes($text)
795{
796 // NOTE : I had to update this sample code with below line to prevent obvious attacks as pointed out by many users.
797 // Always ensure that user inputs are scanned and filtered properly.
798 $text = htmlspecialchars($text, ENT_QUOTES, 'UTF-8');
799
800 // BBcode array
801 $find = array(
802 '~\[b\](.*?)\[/b\]~s',
803 '~\[i\](.*?)\[/i\]~s',
804 '~\[u\](.*?)\[/u\]~s',
805 '~\[quote\](.*?)\[/quote\]~s',
806 '~\[size=(.*?)\](.*?)\[/size\]~s',
807 '~\[color=(.*?)\](.*?)\[/color\]~s',
808 '~\[url\]((?:ftp|https?)://.*?)\[/url\]~s',
809 '~\[img\](https?://.*?\.(?:jpg|jpeg|gif|png|bmp))\[/img\]~s'
810 );
811
812 // HTML tags to replace BBcode
813 $replace = array(
814 '<b>$1</b>',
815 '<i>$1</i>',
816 '<span style="text-decoration:underline;">$1</span>',
817 '<pre>$1</'.'pre>',
818 '<span style="font-size:$1px;">$2</span>',
819 '<span style="color:$1;">$2</span>',
820 '<a href="$1">$1</a>',
821 '<img src="$1" alt="" />'
822 );
823
824 // Replacing the BBcodes with corresponding HTML tags
825 return preg_replace($find, $replace, $text);
826}
827
828function NormalizePath(string $Path): string
829{
830 $Segments = explode('/', $Path);
831 $Result = array();
832 for ($I = 0; $I < count($Segments); $I++)
833 {
834 $Segment = $Segments[$I];
835 if (($Segment == '.') || ((strlen($Segment) == 0) && ($I > 0) && ($I < count($Segments) - 1)))
836 {
837 continue;
838 }
839 if ($Segment == '..')
840 {
841 array_pop($Result);
842 } else
843 {
844 array_push($Result, $Segment);
845 }
846 }
847 return implode('/', $Result);
848}
849
850function TryGetUrlParameterInt(string $Name, int &$Value): bool
851{
852 if (array_key_exists($Name, $_GET))
853 {
854 if (is_numeric($_GET[$Name]))
855 {
856 $Value = $_GET[$Name] * 1;
857 return true;
858 }
859 return false;
860 }
861 return false;
862}
Note: See TracBrowser for help on using the repository browser.