source: trunk/Common/Global.php@ 516

Last change on this file since 516 was 516, checked in by chronos, 12 years ago
  • Upraveno: Obsluha chybových stavů přepracována na aplikační modul.
  • Property svn:executable set to *
File size: 18.0 KB
Line 
1<?php
2
3$Revision =
4
5/* @var $System System */
6$System = NULL;
7/* @var $Database Database */
8$Database = NULL;
9
10$ConfigFileName = dirname(__FILE__).'/../config.php';
11if(file_exists($ConfigFileName)) include_once($ConfigFileName);
12include_once(dirname(__FILE__).'/Version.php');
13include_once(dirname(__FILE__).'/Update.php');
14include_once(dirname(__FILE__).'/VarDumper.php');
15include_once(dirname(__FILE__).'/Module.php');
16include_once(dirname(__FILE__).'/AppModule.php');
17include_once(dirname(__FILE__).'/Database.php');
18include_once(dirname(__FILE__).'/Code.php');
19include_once(dirname(__FILE__).'/Mail.php');
20include_once(dirname(__FILE__).'/Log.php');
21include_once(dirname(__FILE__).'/User.php');
22include_once(dirname(__FILE__).'/Page.php');
23include_once(dirname(__FILE__).'/Form/Form.php');
24include_once(dirname(__FILE__).'/../finance/bills.php');
25include_once(dirname(__FILE__).'/../finance/finance.php');
26include_once(dirname(__FILE__).'/../form_classes.php');
27
28
29// Application modules
30include_once(dirname(__FILE__).'/../Modules/Error/Error.php');
31include_once(dirname(__FILE__).'/../Modules/File/File.php');
32include_once(dirname(__FILE__).'/../Modules/Meteostation/Meteostation.php');
33include_once(dirname(__FILE__).'/../Modules/Portal/Portal.php');
34include_once(dirname(__FILE__).'/../Modules/IS/IS.php');
35include_once(dirname(__FILE__).'/../Modules/Network/Network.php');
36include_once(dirname(__FILE__).'/../Modules/TV/TV.php');
37include_once(dirname(__FILE__).'/../Modules/OpeningHours/OpeningHours.php');
38include_once(dirname(__FILE__).'/../Modules/Map/Map.php');
39include_once(dirname(__FILE__).'/../Modules/Chat/Chat.php');
40include_once(dirname(__FILE__).'/../Modules/WebCam/WebCam.php');
41include_once(dirname(__FILE__).'/../Modules/User/User.php');
42include_once(dirname(__FILE__).'/../Modules/Finance/Finance.php');
43include_once(dirname(__FILE__).'/../Modules/FinanceBankAPI/FinanceBankAPI.php');
44include_once(dirname(__FILE__).'/../Modules/NetworkShare/NetworkShare.php');
45include_once(dirname(__FILE__).'/../Modules/News/News.php');
46include_once(dirname(__FILE__).'/../Modules/Meals/Meals.php');
47
48class System extends Module
49{
50 var $Modules;
51 /** @var Type */
52 var $Type;
53 var $Pages;
54 /** @var AppModuleManager */
55 var $ModuleManager;
56 var $PathItems;
57
58 function __construct()
59 {
60 parent::__construct();
61 $this->Modules = array();
62 $this->Pages = array();
63 $this->ModuleManager = new AppModuleManager();
64 $this->Database = new Database();
65 $this->FormManager = new FormManager($this->Database);
66 }
67
68 function RegisterPage($Path, $Handler)
69 {
70 $this->Pages[$Path] = $Handler;
71 }
72
73 function SearchPage($PathItems, $Pages)
74 {
75 $PathItem = $PathItems[0];
76 if(array_key_exists($PathItem, $Pages))
77 {
78 if(is_array($Pages[$PathItem]))
79 {
80 array_shift($PathItems);
81 return($this->SearchPage($PathItems, $Pages[$PathItem]));
82 } else return($Pages[$PathItem]);
83 } else return('');
84 }
85
86 function ShowPage()
87 {
88 /* @var $Page Page */
89 $ClassName = $this->SearchPage($this->PathItems, $this->Pages);
90 if($ClassName != '')
91 {
92 $Page = new $ClassName();
93 $Page->System = &$this;
94 $Page->Database = &$this->Database;
95 $Page->GetOutput();
96 } else echo('Page '.implode('/', $this->PathItems).' not found.');
97 }
98
99 function ModulePresent($Name)
100 {
101 return(array_key_exists($Name, $this->Modules));
102 }
103
104 function AddModule($Module)
105 {
106 //echo('Přidávám modul '.get_class($Module).'<br />');
107 $Module->System = &$this;
108 $Module->Database = &$this->Database;
109 $this->Modules[get_class($Module)] = $Module;
110 }
111
112 function AddEmailToQueue($To, $Subject, $Content, $From, $AttachmentFileId = '')
113 {
114 $Values = array('To' => $To,
115 'Subject' => $Subject, 'Content' => $Content, 'Time' => 'NOW()',
116 'From' => $From);
117 if($AttachmentFileId != '') $Values['AttachmentFile'] = $AttachmentFileId;
118 $this->Database->insert('EmailQueue', $Values);
119 }
120
121 function ProcessEmailQueue()
122 {
123 $Output = '';
124 $DbResult = $this->Database->select('EmailQueue', '*', 'Archive=0');
125 while($DbRow = $DbResult->fetch_assoc())
126 {
127 $Mail = new Mail();
128 $Mail->AddToCombined($DbRow['To']);
129 $Mail->Subject = $DbRow['Subject'];
130 $Mail->From = $DbRow['From'];
131 $Mail->AddBody(strip_tags($DbRow['Content']), 'text/plain');
132 $Mail->AddBody($DbRow['Content'], 'text/html');
133 if($DbRow['AttachmentFile'] != '')
134 {
135 $DbResult2 = $this->Database->select('File', '*', 'Id='.$DbRow['AttachmentFile']);
136 while($File = $DbResult2->fetch_assoc())
137 $Mail->AttachFile($this->Config['Web']['FileRootFolder'].$File['DrivePath'], $File['MimeType']);
138 }
139 $Mail->Send();
140 $this->Database->update('EmailQueue', 'Id='.$DbRow['Id'], array('Archive' => 1));
141 $this->Modules['Log']->NewRecord('System', 'SendEmail', $DbRow['Id']);
142 $Output .= 'To: '.$DbRow['To'].' Subject: '.$DbRow['Subject'].'<br />';
143 }
144 return($Output);
145 }
146
147 function HumanDate($Time)
148 {
149 return(date('j.n.Y', $Time));
150 }
151
152 function Link($Target)
153 {
154 global $Config;
155
156 return($Config['Web']['RootFolder'].$Target);
157 }
158}
159
160function GlobalInit()
161{
162 global $Config, $Database, $System, $ScriptTimeStart, $ConfigFileName, $Mail, $Type,
163 $DatabaseRevision;
164
165 date_default_timezone_set('Europe/Prague');
166 $ScriptTimeStart = GetMicrotime();
167
168 if(!isset($Config)) die('Systém není nainstalován. Pokračujte v instalaci <a href="admin/">zde</a>.');
169
170 // SQL injection hack protection
171 foreach($_POST as $Index => $Item) $_POST[$Index] = addslashes($Item);
172 foreach($_GET as $Index => $Item) $_GET[$Index] = addslashes($Item);
173
174 if(isset($_SERVER['REMOTE_ADDR'])) session_start();
175
176 $System = new System();
177 $System->Config = &$Config;
178 $System->Database->Connect($Config['Database']['Host'], $Config['Database']['User'], $Config['Database']['Password'], $Config['Database']['Database']);
179 $System->Database->Prefix = $Config['Database']['Prefix'];
180 $System->Database->charset($Config['Database']['Charset']);
181 $System->Database->ShowSQLError = $Config['Web']['ShowSQLError'];
182 $System->Database->ShowSQLQuery = $Config['Web']['ShowSQLQuery'];
183
184 // Check database persistence structure
185 $UpdateManager = new UpdateManager();
186 $UpdateManager->Database = &$System->Database;
187 $UpdateManager->Revision = $DatabaseRevision;
188 if(!$UpdateManager->IsInstalled()) die('Systém vyžaduje instalaci databáze.');
189 if(!$UpdateManager->IsUpToDate()) die('Systém vyžaduje aktualizaci databáze.');
190
191 // Init old modules
192 $System->AddModule(new Log());
193 $System->AddModule(new User());
194 if(isset($_SERVER['REMOTE_ADDR'])) $System->Modules['User']->Check();
195 $System->AddModule(new Bill());
196 $System->AddModule(new Finance());
197 $System->Modules['Finance']->MainSubject = $Config['Finance']['MainSubjectId'];
198 $System->Modules['Finance']->DirectoryId = $Config['Finance']['DirectoryId'];
199 $System->Modules['Finance']->LoadMonthParameters(0);
200 $System->Modules['Log']->Database->LastQuery = 'ssd';
201 RegisterFormClasses($System->FormManager);
202
203
204 // Register new modules
205 $System->ModuleManager->RegisterModule(new ModuleError($System));
206 $System->ModuleManager->RegisterModule(new ModuleFile($System));
207 $System->ModuleManager->RegisterModule(new ModuleMeteostation($System));
208 $System->ModuleManager->RegisterModule(new ModulePortal($System));
209 $System->ModuleManager->RegisterModule(new ModuleIS($System));
210 $System->ModuleManager->RegisterModule(new ModuleNetwork($System));
211 $System->ModuleManager->RegisterModule(new ModuleTV($System));
212 $System->ModuleManager->RegisterModule(new ModuleOpeningHours($System));
213 $System->ModuleManager->RegisterModule(new ModuleMap($System));
214 $System->ModuleManager->RegisterModule(new ModuleChat($System));
215 $System->ModuleManager->RegisterModule(new ModuleWebCam($System));
216 $System->ModuleManager->RegisterModule(new ModuleUser($System));
217 $System->ModuleManager->RegisterModule(new ModuleFinance($System));
218 $System->ModuleManager->RegisterModule(new ModuleFinanceBankAPI($System));
219 $System->ModuleManager->RegisterModule(new ModuleNetworkShare($System));
220 $System->ModuleManager->RegisterModule(new ModuleNews($System));
221 $System->ModuleManager->RegisterModule(new ModuleMeals($System));
222 $System->ModuleManager->StartAll();
223}
224
225$MonthNames = array('', 'Leden', 'Únor', 'Březen', 'Duben', 'Květen', 'Červen', 'Červenec', 'Srpen', 'Září', 'Říjen', 'Listopad', 'Prosinec');
226
227$UnitNames = array('B', 'kB', 'MB', 'GB', 'TB', 'PB', 'EB');
228
229function HumanSize($Value)
230{
231 global $UnitNames;
232
233 $UnitIndex = 0;
234 while($Value > 1024)
235 {
236 $Value = round($Value / 1024, 3);
237 $UnitIndex++;
238 }
239 return($Value.' '.$UnitNames[$UnitIndex]);
240}
241
242function GetMicrotime()
243{
244 list($Usec, $Sec) = explode(' ', microtime());
245 return ((float)$Usec + (float)$Sec);
246}
247
248function ShowArray($Pole)
249{
250 echo('<pre style="font-size: 8pt;">');
251 print_r($Pole);
252 echo('</pre>');
253}
254
255function HumanDate($Time)
256{
257 $Date = explode(' ', $Time);
258 $Parts = explode('-', $Date[0]);
259 if($Date != '0000-00-00') return(($Parts[2]*1).'.'.($Parts[1]*1).'.'.$Parts[0]);
260 else return('&nbsp;');
261}
262
263// Zobrazení číselný seznamu stránek
264function PagesList($URL, $Page, $TotalCount, $CountPerPage)
265{
266 $Count = ceil($TotalCount / $CountPerPage);
267 $Around = 10;
268 $Result = '';
269 if($Count>1)
270 {
271 if($Page>0)
272 {
273 $Result.= '<a href="'.$URL.'0">&lt;&lt;</a> ';
274 $Result.= '<a href="'.$URL.($Page-1).'">&lt;</a> ';
275 }
276 $PagesMax = $Count-1;
277 $PagesMin = 0;
278 if($PagesMax>($Page+$Around)) $PagesMax = $Page+$Around;
279 if($PagesMin<($Page-$Around))
280 {
281 $Result.= ' .. ';
282 $PagesMin = $Page-$Around;
283 }
284 for($i=$PagesMin;$i<=$PagesMax;$i++)
285 {
286 if($i==$Page) $Result.= '<strong>';
287 $Result.= '<a href="'.$URL.$i.'">'.($i+1).'</a> ';
288 if($i==$Page) $Result.= '</strong>';
289 }
290 if($PagesMax<($Count-1)) $Result .= ' .. ';
291 if($Page<($Count-1))
292 {
293 $Result.= '<a href="'.$URL.($Page+1).'">&gt;</a> ';
294 $Result.= '<a href="'.$URL.($Count-1).'">&gt;&gt;</a>';
295 }
296 }
297 return($Result);
298}
299
300function ExtractTime($Time)
301{
302 return(array(
303 'Year' => date('Y', $Time),
304 'Month' => date('n', $Time),
305 'Day' => date('j', $Time),
306 'Hour' => date('h', $Time),
307 'Minute' => date('i', $Time),
308 'Second' => date('s', $Time)
309 ));
310}
311
312function GetQueryStringArray($QueryString)
313{
314 $Result = array();
315 $Parts = explode('&', $QueryString);
316 foreach($Parts as $Part)
317 {
318 if($Part != '')
319 {
320 if(!strpos($Part, '=')) $Part .= '=';
321 $Item = explode('=', $Part);
322 $Result[$Item[0]] = $Item[1];
323 }
324 }
325 return($Result);
326}
327
328function SetQueryStringArray($QueryStringArray)
329{
330 $Parts = array();
331 foreach($QueryStringArray as $Index => $Item)
332 {
333 $Parts[] = $Index.'='.$Item;
334 }
335 return(implode('&amp;', $Parts));
336}
337
338function GetPageList($TotalCount)
339{
340 global $System;
341
342 $QueryItems = GetQueryStringArray($_SERVER['QUERY_STRING']);
343
344 $Result = '';
345 if(array_key_exists('all', $QueryItems))
346 {
347 $PageCount = 1;
348 $ItemPerPage = $TotalCount;
349 } else
350 {
351 $ItemPerPage = $System->Config['Web']['ItemsPerPage'];
352 $Around = round($System->Config['Web']['VisiblePagingItems'] / 2);
353 $PageCount = floor($TotalCount / $ItemPerPage) + 1;
354 }
355
356 if(!array_key_exists('Page', $_SESSION)) $_SESSION['Page'] = 0;
357 if(array_key_exists('page', $_GET)) $_SESSION['Page'] = $_GET['page'] * 1;
358 if($_SESSION['Page'] < 0) $_SESSION['Page'] = 0;
359 if($_SESSION['Page'] >= $PageCount) $_SESSION['Page'] = $PageCount - 1;
360 $CurrentPage = $_SESSION['Page'];
361
362
363 $Result .= 'Počet položek: <strong>'.$TotalCount.'</strong> &nbsp; Stránky: ';
364
365 $Result = '';
366 if($PageCount > 1)
367 {
368 if($CurrentPage > 0)
369 {
370 $QueryItems['page'] = 0;
371 $Result.= '<a href="?'.SetQueryStringArray($QueryItems).'">&lt;&lt;</a> ';
372 $QueryItems['page'] = ($CurrentPage - 1);
373 $Result.= '<a href="?'.SetQueryStringArray($QueryItems).'">&lt;</a> ';
374 }
375 $PagesMax = $PageCount - 1;
376 $PagesMin = 0;
377 if($PagesMax > ($CurrentPage + $Around)) $PagesMax = $CurrentPage + $Around;
378 if($PagesMin < ($CurrentPage - $Around))
379 {
380 $Result.= ' ... ';
381 $PagesMin = $CurrentPage - $Around;
382 }
383 for($i = $PagesMin; $i <= $PagesMax; $i++)
384 {
385 if($i == $CurrentPage) $Result.= '<strong>'.($i + 1).'</strong> ';
386 else {
387 $QueryItems['page'] = $i;
388 $Result .= '<a href="?'.SetQueryStringArray($QueryItems).'">'.($i + 1).'</a> ';
389 }
390 }
391 if($PagesMax < ($PageCount - 1)) $Result .= ' ... ';
392 if($CurrentPage < ($PageCount - 1))
393 {
394 $QueryItems['page'] = ($CurrentPage + 1);
395 $Result.= '<a href="?'.SetQueryStringArray($QueryItems).'">&gt;</a> ';
396 $QueryItems['page'] = ($PageCount - 1);
397 $Result.= '<a href="?'.SetQueryStringArray($QueryItems).'">&gt;&gt;</a>';
398 }
399 }
400 $QueryItems['all'] = '1';
401 if($PageCount > 1) $Result.= ' <a href="?'.SetQueryStringArray($QueryItems).'">Vše</a>';
402
403 $Result = '<div style="text-align: center">'.$Result.'</div>';
404 return(array('SQLLimit' => ' LIMIT '.$CurrentPage * $ItemPerPage.', '.$ItemPerPage,
405 'Page' => $CurrentPage,
406 'Output' => $Result,
407 ));
408}
409
410$OrderDirSQL = array('ASC', 'DESC');
411$OrderArrowImage = array('sort_asc.png', 'sort_desc.png');
412
413function GetOrderTableHeader($Columns, $DefaultColumn, $DefaultOrder = 0)
414{
415 global $OrderDirSQL, $OrderArrowImage, $Config, $System;
416
417 if(array_key_exists('OrderCol', $_GET)) $_SESSION['OrderCol'] = $_GET['OrderCol'];
418 if(array_key_exists('OrderDir', $_GET)) $_SESSION['OrderDir'] = $_GET['OrderDir'];
419 if(!array_key_exists('OrderCol', $_SESSION)) $_SESSION['OrderCol'] = $DefaultColumn;
420 if(!array_key_exists('OrderDir', $_SESSION)) $_SESSION['OrderDir'] = $DefaultOrder;
421
422 // Check OrderCol
423 $Found = false;
424 foreach($Columns as $Column)
425 {
426 if($Column['Name'] == $_SESSION['OrderCol'])
427 {
428 $Found = true;
429 break;
430 }
431 }
432 if($Found == false)
433 {
434 $_SESSION['OrderCol'] = $DefaultColumn;
435 $_SESSION['OrderDir'] = $DefaultOrder;
436 }
437 // Check OrderDir
438 if(($_SESSION['OrderDir'] != 0) and ($_SESSION['OrderDir'] != 1)) $_SESSION['OrderDir'] = 0;
439
440 $Result = '';
441 $QueryItems = GetQueryStringArray($_SERVER['QUERY_STRING']);
442 foreach($Columns as $Index => $Column)
443 {
444 $QueryItems['OrderCol'] = $Column['Name'];
445 $QueryItems['OrderDir'] = 1 - $_SESSION['OrderDir'];
446 if($Column['Name'] == $_SESSION['OrderCol']) $ArrowImage = '<img style="vertical-align: middle; border: 0px;" src="'.$System->Link('/images/'.$OrderArrowImage[$_SESSION['OrderDir']]).'" alt="order arrow">';
447 else $ArrowImage = '';
448 if($Column['Name'] == '') $Result .= '<th>'.$Column['Title'].'</th>';
449 else $Result .= '<th><a href="?'.SetQueryStringArray($QueryItems).'">'.$Column['Title'].$ArrowImage.'</a></th>';
450 }
451 return(array(
452 'SQL' => ' ORDER BY `'.$_SESSION['OrderCol'].'` '.$OrderDirSQL[$_SESSION['OrderDir']],
453 'Output' => '<tr>'.$Result.'</tr>',
454 'Column' => $_SESSION['OrderCol'],
455 'Direction' => $_SESSION['OrderDir'],
456 ));
457}
458
459function GetRemoteAddress()
460{
461 if(array_key_exists('HTTP_X_FORWARDED_FOR',$_SERVER)) $IP = $_SERVER['HTTP_X_FORWARDED_FOR'] ;
462 else if(array_key_exists('REMOTE_ADDR', $_SERVER)) $IP = $_SERVER['REMOTE_ADDR'];
463 else $IP = '0.0.0.0';
464 return($IP);
465}
466
467function IsInternetAddr()
468{
469 $RemoteAddr = GetRemoteAddress();
470 $RemoteAddr = explode('.', $RemoteAddr);
471// return(!(($RemoteAddr[0] == 10) and ($RemoteAddr[1] == 145)));
472 return(!(($RemoteAddr[0] == 10)));
473}
474
475function GetMemberByIP($IP)
476{
477 global $Database;
478
479 $DbResult = $Database->query('SELECT Id FROM Member WHERE (SELECT Member FROM NetworkDevice WHERE (SELECT Device FROM NetworkInterface WHERE LocalIP = "'.$IP.'") = NetworkDevice.Id) = Member.Id');
480 if($DbResult->num_rows > 0)
481 {
482 $DbRow = $DbResult->fetch_assoc();
483 return($DbRow['Id']);
484 } else return('');
485}
486
487function RemoveDiacritic($Text)
488{
489 return(str_replace(
490 array('á', 'č', 'ď', 'é', 'ě', 'í', 'ľ', 'ň', 'ó', 'ř', 'š', 'ť', 'ú', 'ů', 'ý', 'ž', 'Á', 'Č', 'Ď', 'É', 'Ě', 'Í', 'Ľ', 'Ň', 'Ó', 'Ř', 'Š', 'Ť', 'Ú', 'Ů', 'Ý', 'Ž'),
491 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'),
492 $Text));
493}
494
495function RouterOSIdent($Name)
496{
497 return(strtr(strtolower(trim($Name)), array(' ' => '-', '.' => '', '(' => '-', ')' => '-',
498 'č' => 'c', 'š' => 's', 'ě' => 'e', 'ř' => 'r', 'ž' => 'z', 'ý' => 'y', 'á' => 'a', 'í' => 'i', 'é' => 'e', 'ů' => 'u', 'ú' => 'u', 'ď' => 'd', 'ť' => 't', 'ň' => 'n', 'ó' => 'o',
499 'Č' => 'c', 'Š' => 's', 'Ě' => 'e', 'Ř' => 'r', 'Ž' => 'z', 'Ý' => 'y', 'Á' => 'a', 'Í' => 'i', 'É' => 'e', 'Ů' => 'u', 'Ú' => 'u', 'Ď' => 'd', 'Ť' => 't', 'Ň' => 'n', 'Ó' => 'o',
500)));
501}
502
503function NotBlank($Text)
504{
505 if($Text == '') return('&nbsp');
506 else return($Text);
507}
508
509function strip_cdata($string)
510{
511 preg_match_all('/<!\[cdata\[(.*?)\]\]>/is', $string, $matches);
512 return str_replace($matches[0], $matches[1], $string);
513}
514
515function html2txt($document)
516{
517 $search = array('@<script[^>]*?>.*?</script>@si', // Strip out javascript
518 '@<[\/\!]*?[^<>]*?>@si', // Strip out HTML tags
519 '@<style[^>]*?>.*?</style>@siU', // Strip style tags properly
520 '@<![\s\S]*?--[ \t\n\r]*>@' // Strip multi-line comments including CDATA
521 );
522 $text = preg_replace($search, '', $document);
523 return $text;
524}
525
526function ProcessURL()
527{
528 if(array_key_exists('REDIRECT_QUERY_STRING', $_SERVER))
529 $PathString = $_SERVER['REDIRECT_QUERY_STRING'];
530 else $PathString = '';
531 if(substr($PathString, -1, 1) == '/') $PathString = substr($PathString, 0, -1);
532 $PathItems = explode('/', $PathString);
533 if(strpos($_SERVER['REQUEST_URI'], '?') !== false)
534 $_SERVER['QUERY_STRING'] = substr($_SERVER['REQUEST_URI'], strpos($_SERVER['REQUEST_URI'], '?') + 1);
535 else $_SERVER['QUERY_STRING'] = '';
536 parse_str($_SERVER['QUERY_STRING'], $_GET);
537 return($PathItems);
538}
539
540GlobalInit();
541
542?>
Note: See TracBrowser for help on using the repository browser.