5b26c32dea52e446ade9ed5a818e9cc3c61402bf
[GitHub/Stricted/Domain-Control-Panel.git] / lib / system / DNS.class.php
1 <?php
2 namespace dns\system;
3
4 if (!defined('DNS_VERSION')) define('DNS_VERSION', '3.0.0 Beta');
5
6 /**
7 * @author Jan Altensen (Stricted)
8 * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
9 * @copyright 2014-2016 Jan Altensen (Stricted)
10 */
11 class DNS {
12 /**
13 * module name
14 *
15 * @var string
16 */
17 protected static $module = '';
18
19 /**
20 * database object
21 *
22 * @var object
23 */
24 protected static $dbObj = null;
25
26 /**
27 * session object
28 *
29 * @var object
30 */
31 protected static $sessionObj = null;
32
33 /**
34 * template object
35 *
36 * @var object
37 */
38 protected static $tplObj = null;
39
40 /**
41 * language array
42 *
43 * @var array
44 */
45 protected static $language = array();
46
47 /**
48 * language code
49 *
50 * @var string
51 */
52 protected static $languageCode = '';
53
54 /**
55 * init main system
56 */
57 public function __construct($module = '') {
58 self::$module = $module;
59 spl_autoload_register(array('dns\system\DNS', 'autoload'));
60 set_exception_handler(array('dns\system\DNS', 'handleException'));
61 set_error_handler(array('dns\system\DNS', 'handleError'), E_ALL);
62
63 $this->initDB();
64 self::buildOptions();
65 $this->initSession();
66 $this->initLanguage();
67 $this->initTPL();
68
69 AclHandler::getInstance();
70
71 $requestHandler = RequestHandler::getInstance();
72 $requestHandler->setDB(self::getDB());
73 $requestHandler->setRoutes($module);
74 $requestHandler->handle();
75 }
76
77 /**
78 * get database
79 */
80 public static function getDB() {
81 return self::$dbObj;
82 }
83
84 /**
85 * init database
86 */
87 protected function initDB() {
88 require(DNS_DIR.'/config.inc.php');
89 self::$dbObj = new DB($driver, $host, $user, $pass, $db, $port);
90 }
91
92 /**
93 * init session system
94 */
95 protected function initSession() {
96 self::$sessionObj = new SessionHandler();
97 }
98
99 /**
100 * return session object
101 */
102 public static function getSession() {
103 return self::$sessionObj;
104 }
105
106 /*
107 * autoload class files from namespace uses
108 *
109 * @param string $className
110 */
111 public static function autoload ($className) {
112 $namespaces = explode('\\', $className);
113 if (count($namespaces) > 1) {
114 $abbreviation = array_shift($namespaces);
115 if ($abbreviation == "dns") {
116 $classPath = DNS_DIR.'/lib/'.implode('/', $namespaces).'.class.php';
117 if (file_exists($classPath)) {
118 require_once($classPath);
119 }
120 }
121 else if ($abbreviation == "Mso") {
122 array_shift($namespaces);
123
124 $classPath = DNS_DIR.'/vendor/idna-convert/src/'.implode('/', $namespaces).'.php';
125 if (file_exists($classPath)) {
126 require_once($classPath);
127 }
128 }
129 else if ($abbreviation == "Zend") {
130 $classPath = DNS_DIR.'/vendor/Zend/'.implode('/', $namespaces).'.php';
131 if (file_exists($classPath)) {
132 require_once($classPath);
133 }
134 }
135 else if ($abbreviation == "Interop") {
136 $classPath = DNS_DIR.'/vendor/Interop/'.implode('/', $namespaces).'.php';
137 if (file_exists($classPath)) {
138 require_once($classPath);
139 }
140 }
141 }
142 }
143
144 /**
145 * Calls the show method on the given exception.
146 *
147 * @param \Exception $e
148 */
149 public static final function handleException(\Exception $e) {
150 try {
151 if ($e instanceof SystemException) {
152 $e->show();
153 exit;
154 }
155
156 // repack Exception
157 self::handleException(new SystemException($e->getMessage(), $e->getCode(), '', $e));
158 }
159 catch (\Exception $exception) {
160 die("<pre>DNS::handleException() Unhandled exception: ".$exception->getMessage()."\n\n".$exception->getTraceAsString());
161 }
162 }
163
164 /**
165 * Catches php errors and throws instead a system exception.
166 *
167 * @param integer $errorNo
168 * @param string $message
169 * @param string $filename
170 * @param integer $lineNo
171 */
172 public static final function handleError($errorNo, $message, $filename, $lineNo) {
173 if (error_reporting() != 0) {
174 $type = 'error';
175 switch ($errorNo) {
176 case 2:
177 $type = 'warning';
178 break;
179 case 8:
180 $type = 'notice';
181 break;
182 }
183
184 throw new SystemException('PHP '.$type.' in file '.$filename.' ('.$lineNo.'): '.$message, 0);
185 }
186 }
187
188 /**
189 * Returns true if the debug mode is enabled, otherwise false.
190 *
191 * @return boolean
192 */
193 public static function debugModeIsEnabled() {
194 // try to load constants
195 if (!defined('ENABLE_DEBUG')) {
196 self::buildOptions();
197 }
198
199 if (defined('ENABLE_DEBUG') && ENABLE_DEBUG) {
200 return true;
201 }
202
203 return false;
204 }
205
206 /**
207 * init language system
208 */
209 protected function initLanguage () {
210 /*
211 * @TODO: activate this later
212 * self::buildlanguage();
213 */
214 $availableLanguages = array("de", "en");
215 $languageCode = 'de';
216
217 if (isset($_GET['l'])) {
218 $code = strtolower($_GET['l']);
219 if (in_array($code, $availableLanguages)) {
220 $languageCode = $code;
221 }
222 else if (array_key_exists($code, $availableLanguages)) {
223 $languageCode = $availableLanguages[$code];
224 }
225 }
226 else if (self::getSession()->language !== null) {
227 $code = strtolower(self::getSession()->language);
228 if (in_array($code, $availableLanguages)) {
229 $languageCode = $code;
230 }
231 else if (array_key_exists($code, $availableLanguages)) {
232 $languageCode = $availableLanguages[$code];
233 }
234 }
235 else if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE']) && $_SERVER['HTTP_ACCEPT_LANGUAGE']) {
236 $acceptedLanguages = explode(',', str_replace('_', '-', strtolower($_SERVER['HTTP_ACCEPT_LANGUAGE'])));
237 foreach ($acceptedLanguages as $acceptedLanguage) {
238 $code = strtolower(preg_replace('%^([a-z]{2}).*$%i', '$1', $acceptedLanguage));
239 if (in_array($code, $availableLanguages)) {
240 $languageCode = $code;
241 break;
242 }
243 }
244 }
245
246 self::$languageCode = $languageCode;
247
248 // @TODO: remove this later
249 /* try to load module language files */
250 if (!empty(self::$module)) {
251 $basedir = DNS_DIR.'/'.self::$module.'/lang/';
252 $file = $basedir.$languageCode.'.lang.php';
253 self::getSession()->register('language', $languageCode);
254
255 if (file_exists($file)) {
256 require_once($file);
257 if (isset($lang) && !empty($lang) && is_array($lang)) {
258 $this->language = array_merge($this->language, $lang);
259 }
260 }
261 }
262
263 /* load default language files */
264 $basedir = DNS_DIR.'/lang/';
265 $file = $basedir.$languageCode.'.lang.php';
266 self::getSession()->register('language', $languageCode);
267
268 if (file_exists($file)) {
269 require_once($file);
270 if (isset($lang) && !empty($lang) && is_array($lang)) {
271 self::$language = array_merge(self::$language, $lang);
272 }
273 }
274
275 return;
276 }
277
278 /**
279 * Executes template scripting in a language variable.
280 *
281 * @param string $item
282 * @param array $variables
283 * @return string result
284 */
285 public static function getLanguageVariable ($item, array $variables = array()) {
286 $lang = self::$language;
287
288 if ($lang == null) {
289 return $item;
290 }
291
292 if (!empty($variables)) {
293 self::getTPL()->assign($variables);
294 }
295
296 if (isset($lang[$item])) {
297 if (strpos($lang[$item], self::getTPL()->left_delimiter) !== false && strpos($lang[$item], self::getTPL()->right_delimiter) !== false) {
298 $data = str_replace("\$", '$', $lang[$item]);
299 $dir = self::getTPL()->getTemplateDir();
300
301 if (is_array($dir)) {
302 $dir = $dir[0];
303 }
304
305 $filename = "lang.".self::$languageCode.".".sha1($item).".tpl";
306 if (file_exists($dir.$filename)) {
307 $mtime = filemtime($dir.$filename);
308 $maxLifetime = 3600;
309
310 if ($mtime === false || ($maxLifetime > 0 && (time() - $mtime) > $maxLifetime)) {
311 @unlink($dir.$filename);
312 }
313 }
314
315 if (!file_exists($dir.$filename)) {
316 $h = fopen($dir.$filename, "a+");
317 fwrite($h, '{* '.$item.' *}'.$lang[$item]);
318 fclose($h);
319 }
320
321 return self::getTPL()->fetch($filename);
322 }
323
324 return $lang[$item];
325 }
326
327 return $item;
328 }
329
330 /**
331 * init template engine
332 */
333 protected function initTPL () {
334 require(DNS_DIR.'/config.inc.php');
335
336 if (self::getSession()->tpl !== null && !empty(self::getSession()->tpl)) {
337 $tpl = self::getSession()->tpl;
338 }
339
340 if (!file_exists(DNS_DIR.'/vendor/smarty/libs/Smarty.class.php')) {
341 throw new SystemException('Unable to find Smarty');
342 }
343
344 require_once(DNS_DIR.'/vendor/smarty/libs/Smarty.class.php');
345 self::$tplObj = new \Smarty;
346
347 if (!empty(self::$module)) {
348 // try first to load the template from module then from core
349 self::getTPL()->addTemplateDir(DNS_DIR.'/'.self::$module."/templates/".$tpl);
350 }
351
352 self::getTPL()->addTemplateDir(DNS_DIR."/templates/".$tpl);
353 self::getTPL()->setCompileDir(DNS_DIR.(empty(self::$module) ? '' : '/'.self::$module)."/templates/compiled/".$tpl);
354 self::getTPL()->setPluginsDir(array(
355 DNS_DIR."/vendor/smarty/libs/plugins",
356 DNS_DIR."/lib/system/template/plugins"
357 ));
358 self::getTPL()->loadFilter('pre', 'hascontent');
359
360 if (!ENABLE_DEBUG) {
361 self::getTPL()->loadFilter('output', 'trimwhitespace');
362 }
363
364 /* assign language variables */
365 self::getTPL()->assign(array(
366 "isReseller" => User::isReseller(),
367 "isAdmin" => User::isAdmin(),
368 'baseurl' => RequestHandler::getInstance()->getBaseUrl()
369 ));
370
371 /*self::getTPL()->assign("version", mb_substr(sha1(DNS_VERSION), 0, 8));*/
372
373 }
374
375 /**
376 * get template engine
377 */
378 public static function getTPL () {
379 return self::$tplObj;
380 }
381
382 /**
383 * Creates a random hash.
384 *
385 * @return string
386 */
387 public static function generateRandomID() {
388 return sha1(microtime() . uniqid(mt_rand(), true));
389 }
390
391 /**
392 * Creates an UUID.
393 *
394 * @return string
395 */
396 public static function generateUUID() {
397 return strtoupper(sprintf('%04x%04x-%04x-%04x-%04x-%04x%04x%04x', mt_rand(0, 65535), mt_rand(0, 65535), mt_rand(0, 65535), mt_rand(16384, 20479), mt_rand(32768, 49151), mt_rand(0, 65535), mt_rand(0, 65535), mt_rand(0, 65535)));
398 }
399
400 /**
401 * build options from database
402 *
403 * @param boolean $force
404 */
405 public static function buildOptions ($force = false) {
406 $file = DNS_DIR."/options.inc.php";
407 if (!file_exists($file) || (filemtime($file) + 86400) < time() || $force === true) {
408 if (file_exists($file)) {
409 @unlink($file);
410 }
411
412 @touch($file);
413 $options = self::getDB()->query("select * from dns_options");
414 $content = "<?php\n/* generated at ".gmdate('r')." */\n";
415
416 while ($row = self::getDB()->fetch_array($options)) {
417 $content .= "if (!defined('".strtoupper($row['optionName'])."')) define('".strtoupper($row['optionName'])."', ".((is_bool($row['optionValue']) || is_numeric($row['optionValue'])) ? intval($row['optionValue']) : "'".addcslashes($row['optionValue'], "'\\")."'").");\n";
418 }
419
420 $handler = fOpen($file, "a+");
421 fWrite($handler, $content);
422 fClose($handler);
423 }
424
425 require_once($file);
426 }
427
428 /**
429 * build language files from database
430 *
431 * @param boolean $force
432 */
433 public static function buildlanguage ($force = false) {
434 $availableLanguages = array("de", "en");
435 foreach ($availableLanguages as $languageID => $languageCode) {
436
437 $file = DNS_DIR."/lang/".$languageCode.".lang.php";
438 if (!file_exists($file) || (filemtime($file) + 86400) < time() || $force === true) {
439 if (file_exists($file)) {
440 @unlink($file);
441 }
442
443 @touch($file);
444
445 $items = self::getDB()->query("select * from dns_language where languageID = ?", array($languageID));
446 $content = "<?php\n/**\n* language: ".$languageCode."\n* encoding: UTF-8\n* generated at ".gmdate("r")."\n* \n* DO NOT EDIT THIS FILE\n*/\n";
447 $content .= "\$lang = array();\n";
448 while ($row = self::getDB()->fetch_array($items)) {
449 print_r($row);
450 $content .= "\$lang['".$row['languageItem']."'] = '".str_replace("\$", '$', $row['languageValue'])."';\n";
451 }
452
453 $handler = fOpen($file, "a+");
454 fWrite($handler, $content);
455 fClose($handler);
456 }
457 }
458 }
459 }