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