Teknik is a suite of services with attractive and functional interfaces. https://www.teknik.io/
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

common.php 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636
  1. <?php
  2. function get_page_url($page, $CONF, $full = true)
  3. {
  4. $full_url = get_http($CONF).$CONF['host'];
  5. switch ($CONF['url_type'])
  6. {
  7. case 'sub':
  8. if ($page == $CONF['default_page'])
  9. {
  10. $page = 'www';
  11. }
  12. $full_url = get_subdomain_full($page, $CONF);
  13. break;
  14. case 'page':
  15. $cur_sub = get_subdomain($CONF);
  16. $full_url = get_http($CONF).$cur_sub.".".$CONF['host']."/".$page;
  17. break;
  18. }
  19. return $full_url;
  20. }
  21. function get_subdomain_full($sub_part, $CONF)
  22. {
  23. $url = get_http($CONF).$sub_part.".".$CONF['host'];
  24. return $url;
  25. }
  26. function extract_domain($domain)
  27. {
  28. if(preg_match("/(?P<domain>[a-z0-9][a-z0-9\-]{1,63}\.[a-z\.]{2,6})$/i", $domain, $matches))
  29. {
  30. return $matches['domain'];
  31. } else {
  32. return $domain;
  33. }
  34. }
  35. function extract_subdomains($domain)
  36. {
  37. $subdomains = $domain;
  38. $domain = extract_domain($subdomains);
  39. $subdomains = rtrim(strstr($subdomains, $domain, true), '.');
  40. return $subdomains;
  41. }
  42. function get_subdomain($CONF)
  43. {
  44. $sub = extract_subdomains($_SERVER['HTTP_HOST']);
  45. if ($sub == "" || $sub == "www")
  46. {
  47. $sub = $CONF['default_page'];
  48. }
  49. return $sub;
  50. }
  51. function get_page()
  52. {
  53. $url_array = explode("/",$_SERVER["REQUEST_URI"]);
  54. return ltrim($url_array[1], "/");
  55. }
  56. function get_http($CONF)
  57. {
  58. if ($CONF['https'] != "on")
  59. {
  60. $http = "http://";
  61. }
  62. else
  63. {
  64. $http = "https://";
  65. }
  66. return $http;
  67. }
  68. function get_active($page, $CONF)
  69. {
  70. $cur_page = '';
  71. switch ($CONF['url_type'])
  72. {
  73. case 'sub':
  74. $cur_page = get_subdomain($CONF);
  75. break;
  76. case 'page':
  77. $cur_page = get_page();
  78. break;
  79. }
  80. if ($cur_page == $page)
  81. {
  82. return 'active';
  83. }
  84. return "";
  85. }
  86. function checkemail($email)
  87. {
  88. return preg_match('/^\S+@[\w\d.-]{2,}\.[\w]{2,6}$/iU', $email) ? TRUE : FALSE;
  89. }
  90. function safe($input)
  91. {
  92. $valid_input = addslashes($input);
  93. return $valid_input;
  94. }
  95. function safe_register($input)
  96. {
  97. $input = rawurlencode($input);
  98. $valid_input = mysql_real_escape_string($input);
  99. return $valid_input;
  100. }
  101. function rand_string( $length ) {
  102. $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
  103. $size = strlen( $chars );
  104. for( $i = 0; $i < $length; $i++ ) {
  105. $str .= $chars[ rand( 0, $size - 1 ) ];
  106. }
  107. return $str;
  108. }
  109. function hashPassword($password, $CONF)
  110. {
  111. $hashed_pass = hash("sha256",sha1($CONF['salt'].$password.$CONF['salt_2']));
  112. return $hashed_pass;
  113. }
  114. function generate_code($key, $CONF)
  115. {
  116. $randomString = rand_string(6);
  117. $key = hash("sha256",sha1($randomString.$CONF['salt'].$key.$CONF['salt_2']));
  118. return $key;
  119. }
  120. function get_mime_type($filepath) {
  121. ob_start();
  122. system("file -i -b {$filepath}");
  123. $output = ob_get_clean();
  124. $output = explode("; ",$output);
  125. if ( is_array($output) ) {
  126. $output = $output[0];
  127. }
  128. return $output;
  129. }
  130. function set_page_title($title)
  131. {
  132. $output = ob_get_contents();
  133. // clean the buffer to avoid duplicates
  134. ob_clean();
  135. // replace the title with the generated title
  136. $output = str_replace('{title_holder}', $title,$output);
  137. // put the html back in buffer
  138. echo $output;
  139. }
  140. function redirect($url){
  141. if (headers_sent()){
  142. die('<script type="text/javascript">window.location.href="' . $url . '";</script>');
  143. }else{
  144. header('Location: ' . $url);
  145. die();
  146. }
  147. }
  148. function upload($files, $CONF, $db)
  149. {
  150. if (!empty($files)) {
  151. $filesize = filesize($files['file']['tmp_name']);
  152. $file_type = mime_content_type($files['file']['tmp_name']);
  153. $ext = pathinfo($files['file']['name'], PATHINFO_EXTENSION);
  154. if ($logged_in == 1)
  155. {
  156. $user_id = $user->id;
  157. }
  158. else
  159. {
  160. $user_id = 0;
  161. }
  162. if ($filesize <= (pow(1024, 2) * $CONF['max_upload_size']))
  163. {
  164. $iv = rand_string(32);
  165. $targetFile = upload_file($files, $CONF['upload_dir'], $CONF['key'], $iv, $CONF['cipher']);
  166. $file_used = true;
  167. while ($file_used)
  168. {
  169. $randomString = rand_string(6);
  170. if (empty($ext)) {
  171. $fileURL = $randomString;
  172. } else {
  173. $fileURL = $randomString.".".$ext;
  174. }
  175. $result = $db->select("uploads", "url=?", array($fileURL));
  176. if (!$result)
  177. {
  178. $file_used = false;
  179. }
  180. }
  181. $data = array(
  182. "filename" => $targetFile,
  183. "url" => $fileURL,
  184. "type" => $file_type,
  185. "user_id" => $user_id,
  186. "upload_date" => date("Y-m-d H:i:s",time()),
  187. "filesize" => $filesize,
  188. "hash" => $iv,
  189. "cipher" => $CONF['cipher']
  190. );
  191. $db->insert($data, 'uploads');
  192. $_SESSION[$fileURL] = $fileURL;
  193. return array('results' => array('file' => array('name' => $fileURL, 'url' => get_page_url("u", $CONF).'/'.$fileURL, 'type' => $file_type, 'size' => $filesize)));
  194. }
  195. return array('error' => $CONF['errors']['InvFile']);
  196. }
  197. return array('error' => $CONF['errors']['NoFile']);
  198. }
  199. function upload_file($file, $destination, $key, $iv, $cipher)
  200. {
  201. $tempFile = $file['file']['tmp_name'];
  202. $fileType = pathinfo($file['file']['name'], PATHINFO_EXTENSION);
  203. $file_used = true;
  204. while ($file_used)
  205. {
  206. $randomString = rand_string(12);
  207. $targetFile = $randomString.'.'.$fileType;
  208. if (!file_exists($destination.$targetFile))
  209. {
  210. $file_used = false;
  211. }
  212. }
  213. $crypt = new Cryptography();
  214. $crypt->Encrypt($key, $iv, $tempFile, $destination.$targetFile, $cipher);
  215. $result = unlink($tempFile);
  216. return $targetFile;
  217. }
  218. function get_blog($blog_id, $db, $post_count = null, $start_post = null)
  219. {
  220. if ($post_count != null && $start_post != null)
  221. {
  222. $limit = " LIMIT ".$start_post.", ".$post_count;
  223. }
  224. else if ($post_count != null)
  225. {
  226. $limit = " LIMIT ".$post_count;
  227. }
  228. else
  229. {
  230. $limit == "";
  231. }
  232. $blog_posts = $db->select('blog', "user_id=? ORDER BY date_posted DESC".$limit, array($blog_id));
  233. $posts = array();
  234. foreach ($blog_posts as $post)
  235. {
  236. if (!is_array($post))
  237. {
  238. $posts = array($blog_posts);
  239. break;
  240. }
  241. array_push($posts, $post);
  242. }
  243. return $posts;
  244. }
  245. function get_podcast($db, $post_count = null, $start_post = null)
  246. {
  247. if ($post_count != null && $start_post != null)
  248. {
  249. $limit = " LIMIT ".$start_post.", ".$post_count;
  250. }
  251. else if ($post_count != null)
  252. {
  253. $limit = " LIMIT ".$post_count;
  254. }
  255. else
  256. {
  257. $limit == "";
  258. }
  259. $podcast_posts = $db->select('podcast', "1=? ORDER BY date_posted DESC".$limit, array(1));
  260. $posts = array();
  261. foreach ($podcast_posts as $post)
  262. {
  263. if (!is_array($post))
  264. {
  265. $posts = array($podcast_posts);
  266. break;
  267. }
  268. array_push($posts, $post);
  269. }
  270. return $posts;
  271. }
  272. function get_comments($service, $post_id, $db, $comment_count = null, $start_comment = null)
  273. {
  274. if ($comment_count != null && $start_comment != null)
  275. {
  276. $limit = " LIMIT ".$start_comment.", ".$comment_count;
  277. }
  278. else if ($comment_count != null)
  279. {
  280. $limit = " LIMIT ".$comment_count;
  281. }
  282. else
  283. {
  284. $limit == "";
  285. }
  286. $post_comments = $db->select('comments', "service=? AND reply_id=? ORDER BY date_posted ASC".$limit, array($service, $post_id));
  287. $comments = array();
  288. foreach ($post_comments as $comment)
  289. {
  290. if (!is_array($comment))
  291. {
  292. $comments = array($post_comments);
  293. break;
  294. }
  295. array_push($comments, $comment);
  296. }
  297. return $comments;
  298. }
  299. function get_post($service, $post_id, $db)
  300. {
  301. $all_posts = $db->select($service, "id=?", array($post_id));
  302. $posts = array();
  303. foreach ($all_posts as $post)
  304. {
  305. if (!is_array($post))
  306. {
  307. $posts = array($all_posts);
  308. break;
  309. }
  310. array_push($posts, $post);
  311. }
  312. return $posts;
  313. }
  314. function run_command($command, $cwd = ".") {
  315. $descriptorspec = array(
  316. 1 => array('pipe', 'w'),
  317. 2 => array('pipe', 'w'),
  318. );
  319. $pipes = array();
  320. /* Depending on the value of variables_order, $_ENV may be empty.
  321. * In that case, we have to explicitly set the new variables with
  322. * putenv, and call proc_open with env=null to inherit the reset
  323. * of the system.
  324. *
  325. * This is kind of crappy because we cannot easily restore just those
  326. * variables afterwards.
  327. *
  328. * If $_ENV is not empty, then we can just copy it and be done with it.
  329. */
  330. if(count($_ENV) === 0) {
  331. $env = NULL;
  332. foreach($this->envopts as $k => $v) {
  333. putenv(sprintf("%s=%s",$k,$v));
  334. }
  335. } else {
  336. $env = array_merge($_ENV, $this->envopts);
  337. }
  338. $resource = proc_open($command, $descriptorspec, $pipes, $cwd, $env);
  339. $stdout = stream_get_contents($pipes[1]);
  340. $stderr = stream_get_contents($pipes[2]);
  341. foreach ($pipes as $pipe) {
  342. fclose($pipe);
  343. }
  344. $status = trim(proc_close($resource));
  345. if ($status) throw new Exception($stderr);
  346. //exec($command, $stdout);
  347. return $stdout;
  348. }
  349. function mirc2html($x) {
  350. $tokenizer = new Tokenizer($x);
  351. while(list($token, $data) = $tokenizer->getNext())
  352. {
  353. switch($token)
  354. {
  355. case 'color-fgbg':
  356. printf('<%s:%d,%d>', $token, $data[1], $data[2]);
  357. break;
  358. case 'color-fg':
  359. printf('<%s:%d>', $token, $data[1]);
  360. break;
  361. case 'color-reset':
  362. case 'style-bold';
  363. printf('<%s>', $token);
  364. break;
  365. case 'catch-all':
  366. echo $data[0];
  367. break;
  368. default:
  369. throw new Exception(sprintf('Unknown token <%s>.', $token));
  370. }
  371. }
  372. //$c = array("FFF","000","00007F","009000","FF0000","7F0000","9F009F","FF7F00","FFFF00","00F800","00908F","00FFFF","0000FF","FF00FF","7F7F7F","CFD0CF");
  373. $x = preg_replace("/\x02(.*?)((?=\x02)\x02|$)/", "<b>$1</b>", $x);
  374. $x = preg_replace("/\x1F(.*?)((?=\x1F)\x1F|$)/", "<u>$1</u>", $x);
  375. $x = preg_replace("/\x1D(.*?)((?=\x1D)\x1D|$)/", "<i>$1</i>", $x);
  376. /*
  377. $x = preg_replace("/\x03(\d\d?),(\d\d?)(.*?)(?(?=\x03)|$)/e", "'</span><span style=\"color: #'.\$c[$1].'; background-color: #'.\$c[$2].';\">$3</span>'", $x);
  378. $x = preg_replace("/\x03(\d\d?)(.*?)(?(?=\x03)|$)/e", "'</span><span style=\"color: #'.\$c[$1].';\">$2</span>'", $x);
  379. $x = preg_replace("/(\x0F|\x03)(.*?)/", "<span style=\"color: #000; background-color: #FFF;\">$2</span>", $x);
  380. //$x = preg_replace("/\x16(.*?)/", "<span style=\"color: #FFF; background-color: #000;\">$1</span>", $x);
  381. //$x = preg_replace("/\<\/span\>/","",$x,1);
  382. //$x = preg_replace("/(\<\/span\>){2}/","</span>",$x);
  383. */
  384. //preg_replace_callback("/(\x03)(\d\d?,\d\d?|\d\d?)(\s?.*?)(?(?=\x03)|$)/","color_rep",trim($topic));
  385. $x = preg_replace_callback('/\^C([0-9]{1,2}),?([0-9]{1,2})(.*?)\^C/', 'mycallback', $x);
  386. return $x;
  387. }
  388. function mycallback($matches) {
  389. $bindings = array(
  390. 0=>'white',
  391. 1=>'black',
  392. 2=>'blue',
  393. 3=>'green',
  394. 4=>'red',
  395. 5=>'brown',
  396. 6=>'purple',
  397. );
  398. $c = array("FFF","000","00007F","009000","FF0000","7F0000","9F009F","FF7F00","FFFF00","00F800","00908F","00FFFF","0000FF","FF00FF","7F7F7F","CFD0CF");
  399. $fg = isset($c[$matches[1]]) ? $c[$matches[1]] : 'transparent';
  400. $bg = isset($c[$matches[2]]) ? $c[$matches[2]] : 'transparent';
  401. return '<span style="color: #'.$fg.'; background: #'.$bg.';">'.$matches[3].'</span>';
  402. }
  403. function color_rep($matches) {
  404. $matches[2] = ltrim($matches[2], "0");
  405. $bindings = array(0=>'white',1=>'black',2=>'blue',3=>'green',4=>'red',5=>'brown',6=>'purple',7=>'orange',8=>'yellow',9=>'lightgreen',10=>'#00908F',
  406. 11=>'lightblue',12=>'blue',13=>'pink',14=>'grey',15=>'lightgrey');
  407. $preg = preg_match_all('/(\d\d?),(\d\d?)/',$matches[2], $col_arr);
  408. //print_r($col_arr);
  409. $fg = isset($bindings[$matches[2]]) ? $bindings[$matches[2]] : 'transparent';
  410. if ($preg == 1) {
  411. $fg = $bindings[$col_arr[1][0]];
  412. $bg = $bindings[$col_arr[2][0]];
  413. }
  414. else {
  415. $bg = 'transparent';
  416. }
  417. return '<span style="color: '.$fg.'; background: '.$bg.';">'.$matches[3].'</span>';
  418. }
  419. function curPageURL() {
  420. $pageURL = 'http';
  421. if ($_SERVER["HTTPS"] == "on") {$pageURL .= "s";}
  422. $pageURL .= "://";
  423. if ($_SERVER["SERVER_PORT"] != "80") {
  424. $pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
  425. } else {
  426. $pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
  427. }
  428. return $pageURL;
  429. }
  430. /*
  431. // Extend the rcon class to tweak it for minecraft.
  432. class minecraftRcon extends rcon {
  433. function mcSendCommand($Command) {
  434. $this->_Write(SERVERDATA_EXECCOMMAND,$Command,'');
  435. }
  436. function mcRconCommand($Command) {
  437. $this->mcSendcommand($Command);
  438. $ret = $this->Read();
  439. return $ret[$this->_Id]['S1'];
  440. }
  441. function Auth () {
  442. $PackID = $this->_Write(SERVERDATA_AUTH,$this->Password);$ret = $this->_PacketRead();
  443. if ($ret[0]['ID'] == -1) {
  444. die("Authentication Failure\n");
  445. }
  446. return true;
  447. }
  448. }
  449. */
  450. function full_copy($source, $target)
  451. {
  452. if ( is_dir( $source ) )
  453. {
  454. @mkdir( $target );
  455. $d = dir( $source );
  456. while ( FALSE !== ( $entry = $d->read() ) )
  457. {
  458. if ( $entry == '.' || $entry == '..' )
  459. {
  460. continue;
  461. }
  462. $Entry = $source . '/' . $entry;
  463. if ( is_dir( $Entry ) )
  464. {
  465. full_copy( $Entry, $target . '/' . $entry );
  466. continue;
  467. }
  468. copy( $Entry, $target . '/' . $entry );
  469. }
  470. $d->close();
  471. }
  472. else
  473. {
  474. copy( $source, $target );
  475. }
  476. }
  477. function deleteAll($directory, $empty = false)
  478. {
  479. if(substr($directory,-1) == "/") {
  480. $directory = substr($directory,0,-1);
  481. }
  482. if(!file_exists($directory) || !is_dir($directory)) {
  483. return false;
  484. } elseif(!is_readable($directory)) {
  485. return false;
  486. } else {
  487. $directoryHandle = opendir($directory);
  488. while ($contents = readdir($directoryHandle)) {
  489. if($contents != '.' && $contents != '..') {
  490. $path = $directory . "/" . $contents;
  491. if(is_dir($path)) {
  492. deleteAll($path);
  493. } else {
  494. unlink($path);
  495. }
  496. }
  497. }
  498. closedir($directoryHandle);
  499. if($empty == false) {
  500. if(!rmdir($directory)) {
  501. return false;
  502. }
  503. }
  504. return true;
  505. }
  506. }
  507. function bytesToSize($bytes, $precision = 2)
  508. {
  509. $kilobyte = 1024;
  510. $megabyte = $kilobyte * 1024;
  511. $gigabyte = $megabyte * 1024;
  512. $terabyte = $gigabyte * 1024;
  513. if (($bytes >= 0) && ($bytes < $kilobyte)) {
  514. return $bytes . ' B';
  515. } elseif (($bytes >= $kilobyte) && ($bytes < $megabyte)) {
  516. return round($bytes / $kilobyte, $precision) . ' KB';
  517. } elseif (($bytes >= $megabyte) && ($bytes < $gigabyte)) {
  518. return round($bytes / $megabyte, $precision) . ' MB';
  519. } elseif (($bytes >= $gigabyte) && ($bytes < $terabyte)) {
  520. return round($bytes / $gigabyte, $precision) . ' GB';
  521. } elseif ($bytes >= $terabyte) {
  522. return round($bytes / $terabyte, $precision) . ' TB';
  523. } else {
  524. return $bytes . ' B';
  525. }
  526. }
  527. function trim_value(&$value)
  528. {
  529. $value = trim($value); // this removes whitespace and related characters from the beginning and end of the string
  530. }
  531. function compress($buffer)
  532. {
  533. /* remove comments */
  534. $buffer = preg_replace('!/\*[^*]*\*+([^/][^*]*\*+)*/!', '', $buffer);
  535. /* remove tabs, spaces, newlines, etc. */
  536. $buffer = str_replace(array("\r\n", "\r", "\n", "\t", ' ', ' ', ' '), '', $buffer);
  537. return $buffer;
  538. }
  539. function is_dir_empty($dir)
  540. {
  541. if (!is_readable($dir)) return NULL;
  542. $handle = opendir($dir);
  543. while (false !== ($entry = readdir($handle)))
  544. {
  545. if ($entry != "." && $entry != "..")
  546. {
  547. return FALSE;
  548. }
  549. }
  550. return TRUE;
  551. }
  552. ?>