add current dev version (WIP)
[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
56 $this->initDB();
57 self::buildOptions();
58 $this->initSession();
59 $this->initLanguage();
60 $this->initTPL();
61 new RequestHandler(self::$module);
62 }
63
64 /**
65 * get database
66 */
67 public static function getDB() {
68 return self::$dbObj;
69 }
70
71 /**
72 * init database
73 */
74 protected function initDB() {
75 require(DNS_DIR.'/config.inc.php');
76 self::$dbObj = new DB($driver, $host, $user, $pass, $db, $port);
77 }
78
79 /**
80 * init session system
81 */
82 protected function initSession() {
83 self::$sessionObj = new SessionHandler();
84 }
85
86 /**
87 * return session object
88 */
89 public static function getSession() {
90 return self::$sessionObj;
91 }
92
93 /*
94 * autoload class files from namespace uses
95 *
96 * @param string $className
97 */
98 public static function autoload ($className) {
99 $namespaces = explode('\\', $className);
100 if (count($namespaces) > 1) {
101 array_shift($namespaces);
102 $classPath = DNS_DIR.'/lib/'.implode('/', $namespaces).'.class.php';
103 if (file_exists($classPath)) {
104 require_once($classPath);
105 }
106 }
107 }
108
109 /**
110 * Calls the show method on the given exception.
111 *
112 * @param \Exception $e
113 */
114 public static final function handleException(\Exception $e) {
115 try {
116 if ($e instanceof SystemException) {
117 $e->show();
118 exit;
119 }
120
121 // repack Exception
122 self::handleException(new SystemException($e->getMessage(), $e->getCode(), '', $e));
123 }
124 catch (\Exception $exception) {
125 die("<pre>DNS::handleException() Unhandled exception: ".$exception->getMessage()."\n\n".$exception->getTraceAsString());
126 }
127 }
128
129 /**
130 * Catches php errors and throws instead a system exception.
131 *
132 * @param integer $errorNo
133 * @param string $message
134 * @param string $filename
135 * @param integer $lineNo
136 */
137 public static final function handleError($errorNo, $message, $filename, $lineNo) {
138 if (error_reporting() != 0) {
139 $type = 'error';
140 switch ($errorNo) {
141 case 2:
142 $type = 'warning';
143 break;
144 case 8:
145 $type = 'notice';
146 break;
147 }
148
149 throw new SystemException('PHP '.$type.' in file '.$filename.' ('.$lineNo.'): '.$message, 0);
150 }
151 }
152
153 /**
154 * Returns true if the debug mode is enabled, otherwise false.
155 *
156 * @return boolean
157 */
158 public static function debugModeIsEnabled() {
159 // try to load constants
160 if (!defined('ENABLE_DEBUG')) {
161 self::buildOptions();
162 }
163
164 if (defined('ENABLE_DEBUG') && ENABLE_DEBUG) {
165 return true;
166 }
167
168 return false;
169 }
170
171 /**
172 * init language system
173 */
174 protected function initLanguage () {
175 /*
176 * @TODO: activate this later
177 * self::buildlanguage();
178 */
179 $availableLanguages = array("de", "en");
180 $languageCode = 'de';
181
182 if (isset($_GET['l'])) {
183 $code = strtolower($_GET['l']);
184 if (in_array($code, $availableLanguages)) {
185 $languageCode = $code;
186 }
187 else if (array_key_exists($code, $availableLanguages)) {
188 $languageCode = $availableLanguages[$code];
189 }
190 }
191 else if (self::getSession()->language !== null) {
192 $code = strtolower(self::getSession()->language);
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 (isset($_SERVER['HTTP_ACCEPT_LANGUAGE']) && $_SERVER['HTTP_ACCEPT_LANGUAGE']) {
201 $acceptedLanguages = explode(',', str_replace('_', '-', strtolower($_SERVER['HTTP_ACCEPT_LANGUAGE'])));
202 foreach ($acceptedLanguages as $acceptedLanguage) {
203 $code = strtolower(preg_replace('%^([a-z]{2}).*$%i', '$1', $acceptedLanguage));
204 if (in_array($code, $availableLanguages)) {
205 $languageCode = $code;
206 break;
207 }
208 }
209 }
210
211 // @TODO: remove this later
212 /* try to load module language files */
213 if (!empty(self::$module)) {
214 $basedir = DNS_DIR.'/'.self::$module.'/lang/';
215 $file = $basedir.$languageCode.'.lang.php';
216 self::getSession()->register('language', $languageCode);
217
218 if (file_exists($file)) {
219 require_once($file);
220 if (isset($lang) && !empty($lang) && is_array($lang)) {
221 $this->language = array_merge($this->language, $lang);
222 }
223 }
224 }
225
226 /* load default language files */
227 $basedir = DNS_DIR.'/lang/';
228 $file = $basedir.$languageCode.'.lang.php';
229 self::getSession()->register('language', $languageCode);
230
231 if (file_exists($file)) {
232 require_once($file);
233 if (isset($lang) && !empty($lang) && is_array($lang)) {
234 $this->language = array_merge($this->language, $lang);
235 }
236 }
237
238 return;
239 }
240
241 /**
242 * Executes template scripting in a language variable.
243 *
244 * @param string $item
245 * @param array $variables
246 * @return string result
247 */
248 public static function getLanguageVariable ($item, array $variables = array()) {
249 $lang = self::getTPL()->getTemplateVars('language');
250
251 if ($lang == null) {
252 return $item;
253 }
254
255 if (!empty($variables)) {
256 self::getTPL()->assign($variables);
257 }
258
259 if (isset($lang[$item])) {
260 if (strpos($lang[$item], self::getTPL()->left_delimiter) !== false && strpos($lang[$item], self::getTPL()->right_delimiter) !== false) {
261 $data = str_replace("\$", '$', $lang[$item]);
262 $template_class = self::getTPL()->template_class;
263 $template = new $template_class('eval:'.$data, self::getTPL(), self::getTPL());
264 return $template->fetch();
265 }
266
267 return $lang[$item];
268 }
269
270 return $item;
271 }
272
273 /**
274 * init template engine
275 */
276 protected function initTPL () {
277 require(DNS_DIR.'/config.inc.php');
278
279 if (self::getSession()->tpl !== null && !empty(self::getSession()->tpl)) {
280 $tpl = self::getSession()->tpl;
281 }
282
283 if (!file_exists(DNS_DIR.'/lib/system/api/smarty/libs/Smarty.class.php')) {
284 throw new SystemException('Unable to find Smarty');
285 }
286
287 require_once(DNS_DIR.'/lib/system/api/smarty/libs/Smarty.class.php');
288 self::$tplObj = new \Smarty;
289
290 if (!empty(self::$module)) {
291 // try first to load the template from module then from core
292 self::getTPL()->addTemplateDir(DNS_DIR.'/'.self::$module."/templates/".$tpl);
293 }
294
295 self::getTPL()->addTemplateDir(DNS_DIR."/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/system/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 }