add module system
[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-2015 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 $language = array();
46
47 /**
48 * init main system
49 */
50 public function __construct($module = '') {
51 self::$module = $module;
52 spl_autoload_register(array('dns\system\DNS', 'autoload'));
53 set_exception_handler(array('dns\system\DNS', 'handleException'));
54 set_error_handler(array('dns\system\DNS', 'handleError'), E_ALL);
55 /*register_shutdown_function(array('dns\system\DNS', 'destruct'));*/
56
57 $this->initDB();
58 self::buildOptions();
59 $this->initSession();
60 $this->initLanguage();
61 $this->initTPL();
62 new RequestHandler(self::$module);
63 }
64
65 /*
66 public static function destruct() {
67 $error = error_get_last();
68 if (!empty($error)) {
69 self::handleException(new SystemException($error['message'], $error['line']));
70 }
71
72 }
73 */
74
75 /**
76 * get database
77 */
78 public static function getDB() {
79 return self::$dbObj;
80 }
81
82 /**
83 * init database
84 */
85 protected function initDB() {
86 require(DNS_DIR.'/config.inc.php');
87 self::$dbObj = new DB($driver, $host, $user, $pass, $db, $port);
88 }
89
90 /**
91 * init session system
92 */
93 protected function initSession() {
94 self::$sessionObj = new SessionHandler();
95 }
96
97 /**
98 * return session object
99 */
100 public static function getSession() {
101 return self::$sessionObj;
102 }
103
104 /*
105 * autoload class files from namespace uses
106 *
107 * @param string $className
108 */
109 public static function autoload ($className) {
110 $namespaces = explode('\\', $className);
111 if (count($namespaces) > 1) {
112 array_shift($namespaces);
113 $classPath = DNS_DIR.'/lib/'.implode('/', $namespaces).'.class.php';
114 if (file_exists($classPath)) {
115 require_once($classPath);
116 }
117 }
118 }
119
120 /**
121 * Calls the show method on the given exception.
122 *
123 * @param \Exception $e
124 */
125 public static final function handleException(\Exception $e) {
126 try {
127 if ($e instanceof SystemException) {
128 $e->show();
129 exit;
130 }
131
132 // repack Exception
133 self::handleException(new SystemException($e->getMessage(), $e->getCode(), '', $e));
134 }
135 catch (\Exception $exception) {
136 die("<pre>DNS::handleException() Unhandled exception: ".$exception->getMessage()."\n\n".$exception->getTraceAsString());
137 }
138 }
139
140 /**
141 * Catches php errors and throws instead a system exception.
142 *
143 * @param integer $errorNo
144 * @param string $message
145 * @param string $filename
146 * @param integer $lineNo
147 */
148 public static final function handleError($errorNo, $message, $filename, $lineNo) {
149 if (error_reporting() != 0) {
150 $type = 'error';
151 switch ($errorNo) {
152 case 2: $type = 'warning';
153 break;
154 case 8: $type = 'notice';
155 break;
156 }
157
158 throw new SystemException('PHP '.$type.' in file '.$filename.' ('.$lineNo.'): '.$message, 0);
159 }
160 }
161
162 /**
163 * Returns true if the debug mode is enabled, otherwise false.
164 *
165 * @return boolean
166 */
167 public static function debugModeIsEnabled() {
168 // try to load constants
169 if (!defined('ENABLE_DEBUG')) {
170 self::buildOptions();
171 }
172
173 if (defined('ENABLE_DEBUG') && ENABLE_DEBUG) {
174 return true;
175 }
176
177 return false;
178 }
179
180 /**
181 * init language system
182 */
183 protected function initLanguage () {
184 /*
185 * @TODO: activate this later
186 * self::buildlanguage();
187 */
188 $availableLanguages = array("de", "en");
189 $languageCode = 'de';
190
191 if (isset($_GET['l'])) {
192 $code = strtolower($_GET['l']);
193 if (in_array($code, $availableLanguages)) {
194 $languageCode = $code;
195 }
196 else if (array_key_exists($code, $availableLanguages)) {
197 $languageCode = $availableLanguages[$code];
198 }
199 }
200 else if (self::getSession()->language !== null) {
201 $code = strtolower(self::getSession()->language);
202 if (in_array($code, $availableLanguages)) {
203 $languageCode = $code;
204 }
205 else if (array_key_exists($code, $availableLanguages)) {
206 $languageCode = $availableLanguages[$code];
207 }
208 }
209 else if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE']) && $_SERVER['HTTP_ACCEPT_LANGUAGE']) {
210 $acceptedLanguages = explode(',', str_replace('_', '-', strtolower($_SERVER['HTTP_ACCEPT_LANGUAGE'])));
211 foreach ($acceptedLanguages as $acceptedLanguage) {
212 $code = strtolower(preg_replace('%^([a-z]{2}).*$%i', '$1', $acceptedLanguage));
213 if (in_array($code, $availableLanguages)) {
214 $languageCode = $code;
215 break;
216 }
217 }
218 }
219
220 // @TODO: remove this later
221 /* try to load module language files */
222 if (!empty(self::$module)) {
223 $basedir = DNS_DIR.'/'.self::$module.'/lang/';
224 $file = $basedir.$languageCode.'.lang.php';
225 self::getSession()->register('language', $languageCode);
226
227 if (file_exists($file)) {
228 require_once($file);
229 if (isset($lang) && !empty($lang) && is_array($lang)) {
230 $this->language = array_merge($this->language, $lang);
231 }
232 }
233 }
234
235 /* load default language files */
236 $basedir = DNS_DIR.'/lang/';
237 $file = $basedir.$languageCode.'.lang.php';
238 self::getSession()->register('language', $languageCode);
239
240 if (file_exists($file)) {
241 require_once($file);
242 if (isset($lang) && !empty($lang) && is_array($lang)) {
243 $this->language = array_merge($this->language, $lang);
244 }
245 }
246
247 return;
248 }
249
250 /**
251 * Executes template scripting in a language variable.
252 *
253 * @param string $item
254 * @param array $variables
255 * @return string result
256 */
257 public static function getLanguageVariable ($item, array $variables = array()) {
258 $lang = self::getTPL()->getTemplateVars('language');
259
260 if ($lang == null) {
261 return $item;
262 }
263
264 if (!empty($variables)) {
265 self::getTPL()->assign($variables);
266 }
267
268 if (isset($lang[$item])) {
269 if (strpos($lang[$item], self::getTPL()->left_delimiter) !== false && strpos($lang[$item], self::getTPL()->right_delimiter) !== false) {
270 $data = str_replace("\$", '$', $lang[$item]);
271 $template_class = self::getTPL()->template_class;
272 $template = new $template_class('eval:'.$data, self::getTPL(), self::getTPL());
273 return $template->fetch();
274 }
275
276 return $lang[$item];
277 }
278
279 return $item;
280 }
281
282 /**
283 * init template engine
284 */
285 protected function initTPL () {
286 require(DNS_DIR.'/config.inc.php');
287
288 if (self::getSession()->tpl !== null && !empty(self::getSession()->tpl)) {
289 $tpl = self::getSession()->tpl;
290 }
291
292 require_once(DNS_DIR.'/lib/system/api/smarty/libs/Smarty.class.php');
293 self::$tplObj = new \Smarty;
294
295 self::getTPL()->setTemplateDir(DNS_DIR.(empty(self::$module) ? '' : '/'.self::$module)."/templates/".$tpl);
296 self::getTPL()->setCompileDir(DNS_DIR.(empty(self::$module) ? '' : '/'.self::$module)."/templates/compiled/".$tpl);
297 self::getTPL()->setPluginsDir(array(
298 DNS_DIR."/lib/system/api/smarty/libs/plugins",
299 DNS_DIR."/lib/template/plugins"
300 ));
301 self::getTPL()->loadFilter('pre', 'hascontent');
302
303 if (!ENABLE_DEBUG) {
304 self::getTPL()->loadFilter('output', 'trimwhitespace');
305 }
306
307 /* assign language variables */
308 self::getTPL()->assign(array(
309 "language" => $this->language,
310 "isReseller" => User::isReseller(),
311 "isAdmin" => User::isAdmin()
312 ));
313
314 /*self::getTPL()->assign("version", mb_substr(sha1(DNS_VERSION), 0, 8));*/
315
316 }
317
318 /**
319 * get template engine
320 */
321 public static function getTPL () {
322 return self::$tplObj;
323 }
324
325 /**
326 * Creates a random hash.
327 *
328 * @return string
329 */
330 public static function generateRandomID() {
331 return sha1(microtime() . uniqid(mt_rand(), true));
332 }
333
334 /**
335 * Creates an UUID.
336 *
337 * @return string
338 */
339 public static function generateUUID() {
340 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)));
341 }
342
343 /**
344 * build options from database
345 *
346 * @param boolean $force
347 */
348 public static function buildOptions ($force = false) {
349 $file = DNS_DIR."/options.inc.php";
350 if (!file_exists($file) || (filemtime($file) + 86400) < time() || $force === true) {
351 if (file_exists($file)) {
352 @unlink($file);
353 }
354
355 @touch($file);
356 $options = self::getDB()->query("select * from dns_options");
357 $content = "<?php\n/* generated at ".gmdate('r')." */\n";
358
359 while ($row = self::getDB()->fetch_array($options)) {
360 $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";
361 }
362
363 $handler = fOpen($file, "a+");
364 fWrite($handler, $content);
365 fClose($handler);
366 }
367
368 require_once($file);
369 }
370
371 /**
372 * build language files from database
373 *
374 * @param boolean $force
375 */
376 public static function buildlanguage ($force = false) {
377 $availableLanguages = array("de", "en");
378 foreach ($availableLanguages as $languageID => $languageCode) {
379
380 $file = DNS_DIR."/lang/".$languageCode.".lang.php";
381 if (!file_exists($file) || (filemtime($file) + 86400) < time() || $force === true) {
382 if (file_exists($file)) {
383 @unlink($file);
384 }
385
386 @touch($file);
387
388 $items = self::getDB()->query("select * from dns_language where languageID = ?", array($languageID));
389 $content = "<?php\n/**\n* language: ".$languageCode."\n* encoding: UTF-8\n* generated at ".gmdate("r")."\n* \n* DO NOT EDIT THIS FILE\n*/\n";
390 $content .= "\$lang = array();\n";
391 while ($row = self::getDB()->fetch_array($items)) {
392 print_r($row);
393 $content .= "\$lang['".$row['languageItem']."'] = '".str_replace("\$", '$', $row['languageValue'])."';\n";
394 }
395
396 $handler = fOpen($file, "a+");
397 fWrite($handler, $content);
398 fClose($handler);
399 }
400 }
401 }
402 }