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 17KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661
  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. $ext = substr($files['file']['name'], strrpos($files['file']['name'], '.')+1);
  155. if ($logged_in == 1)
  156. {
  157. $user_id = $user->id;
  158. }
  159. else
  160. {
  161. $user_id = 0;
  162. }
  163. if ($filesize <= (pow(1024, 2) * $CONF['max_upload_size']))
  164. {
  165. $iv = rand_string(32);
  166. $targetFile = upload_file($files, $CONF['upload_dir'], $CONF['key'], $iv, $CONF['cipher']);
  167. $file_used = true;
  168. while ($file_used)
  169. {
  170. $randomString = rand_string(6);
  171. if (empty($ext)) {
  172. $fileURL = $randomString;
  173. } else {
  174. $fileURL = $randomString.".".$ext;
  175. }
  176. $result = $db->select("uploads", "url=?", array($fileURL));
  177. if (!$result)
  178. {
  179. $file_used = false;
  180. }
  181. }
  182. $data = array(
  183. "filename" => $targetFile,
  184. "url" => $fileURL,
  185. "type" => $file_type,
  186. "user_id" => $user_id,
  187. "upload_date" => date("Y-m-d H:i:s",time()),
  188. "filesize" => $filesize,
  189. "hash" => $iv,
  190. "cipher" => $CONF['cipher']
  191. );
  192. $db->insert($data, 'uploads');
  193. $_SESSION[$fileURL] = $fileURL;
  194. return array('results' => array('file' => array('name' => $fileURL, 'url' => get_page_url("u", $CONF).'/'.$fileURL, 'type' => $file_type, 'size' => $filesize)));
  195. }
  196. return array('error' => $CONF['errors']['InvFile']);
  197. }
  198. return array('error' => $CONF['errors']['NoFile']);
  199. }
  200. function upload_file($file, $destination, $key, $iv, $cipher)
  201. {
  202. $tempFile = $file['file']['tmp_name'];
  203. $fileType = pathinfo($file['file']['name'], PATHINFO_EXTENSION);
  204. $file_used = true;
  205. while ($file_used)
  206. {
  207. $randomString = rand_string(12);
  208. $targetFile = $randomString.'.'.$fileType;
  209. if (!file_exists($destination.$targetFile))
  210. {
  211. $file_used = false;
  212. }
  213. }
  214. $crypt = new Cryptography();
  215. $crypt->Encrypt($key, $iv, $tempFile, $destination.$targetFile, $cipher);
  216. $result = unlink($tempFile);
  217. return $targetFile;
  218. }
  219. function get_blog($blog_id, $db, $post_count = null, $start_post = null)
  220. {
  221. if ($post_count != null && $start_post != null)
  222. {
  223. $limit = " LIMIT ".$start_post.", ".$post_count;
  224. }
  225. else if ($post_count != null)
  226. {
  227. $limit = " LIMIT ".$post_count;
  228. }
  229. else
  230. {
  231. $limit == "";
  232. }
  233. $blog_posts = $db->select('blog', "user_id=? ORDER BY date_posted DESC".$limit, array($blog_id));
  234. $posts = array();
  235. foreach ($blog_posts as $post)
  236. {
  237. if (!is_array($post))
  238. {
  239. $posts = array($blog_posts);
  240. break;
  241. }
  242. array_push($posts, $post);
  243. }
  244. return $posts;
  245. }
  246. function get_podcast($db, $post_count = null, $start_post = null)
  247. {
  248. if ($post_count != null && $start_post != null)
  249. {
  250. $limit = " LIMIT ".$start_post.", ".$post_count;
  251. }
  252. else if ($post_count != null)
  253. {
  254. $limit = " LIMIT ".$post_count;
  255. }
  256. else
  257. {
  258. $limit == "";
  259. }
  260. $podcast_posts = $db->select('podcast', "1=? ORDER BY date_posted DESC".$limit, array(1));
  261. $posts = array();
  262. foreach ($podcast_posts as $post)
  263. {
  264. if (!is_array($post))
  265. {
  266. $posts = array($podcast_posts);
  267. break;
  268. }
  269. array_push($posts, $post);
  270. }
  271. return $posts;
  272. }
  273. function get_comments($service, $post_id, $db, $comment_count = null, $start_comment = null)
  274. {
  275. if ($comment_count != null && $start_comment != null)
  276. {
  277. $limit = " LIMIT ".$start_comment.", ".$comment_count;
  278. }
  279. else if ($comment_count != null)
  280. {
  281. $limit = " LIMIT ".$comment_count;
  282. }
  283. else
  284. {
  285. $limit == "";
  286. }
  287. $post_comments = $db->select('comments', "service=? AND reply_id=? ORDER BY date_posted ASC".$limit, array($service, $post_id));
  288. $comments = array();
  289. foreach ($post_comments as $comment)
  290. {
  291. if (!is_array($comment))
  292. {
  293. $comments = array($post_comments);
  294. break;
  295. }
  296. array_push($comments, $comment);
  297. }
  298. return $comments;
  299. }
  300. function get_post($service, $post_id, $db)
  301. {
  302. $all_posts = $db->select($service, "id=?", array($post_id));
  303. $posts = array();
  304. foreach ($all_posts as $post)
  305. {
  306. if (!is_array($post))
  307. {
  308. $posts = array($all_posts);
  309. break;
  310. }
  311. array_push($posts, $post);
  312. }
  313. return $posts;
  314. }
  315. function run_command($command, $cwd = ".") {
  316. $descriptorspec = array(
  317. 1 => array('pipe', 'w'),
  318. 2 => array('pipe', 'w'),
  319. );
  320. $pipes = array();
  321. /* Depending on the value of variables_order, $_ENV may be empty.
  322. * In that case, we have to explicitly set the new variables with
  323. * putenv, and call proc_open with env=null to inherit the reset
  324. * of the system.
  325. *
  326. * This is kind of crappy because we cannot easily restore just those
  327. * variables afterwards.
  328. *
  329. * If $_ENV is not empty, then we can just copy it and be done with it.
  330. */
  331. if(count($_ENV) === 0) {
  332. $env = NULL;
  333. foreach($this->envopts as $k => $v) {
  334. putenv(sprintf("%s=%s",$k,$v));
  335. }
  336. } else {
  337. $env = array_merge($_ENV, $this->envopts);
  338. }
  339. $resource = proc_open($command, $descriptorspec, $pipes, $cwd, $env);
  340. $stdout = stream_get_contents($pipes[1]);
  341. $stderr = stream_get_contents($pipes[2]);
  342. foreach ($pipes as $pipe) {
  343. fclose($pipe);
  344. }
  345. $status = trim(proc_close($resource));
  346. if ($status) throw new Exception($stderr);
  347. //exec($command, $stdout);
  348. return $stdout;
  349. }
  350. function mirc2html($x) {
  351. $tokenizer = new Tokenizer($x);
  352. while(list($token, $data) = $tokenizer->getNext())
  353. {
  354. switch($token)
  355. {
  356. case 'color-fgbg':
  357. printf('<%s:%d,%d>', $token, $data[1], $data[2]);
  358. break;
  359. case 'color-fg':
  360. printf('<%s:%d>', $token, $data[1]);
  361. break;
  362. case 'color-reset':
  363. case 'style-bold';
  364. printf('<%s>', $token);
  365. break;
  366. case 'catch-all':
  367. echo $data[0];
  368. break;
  369. default:
  370. throw new Exception(sprintf('Unknown token <%s>.', $token));
  371. }
  372. }
  373. //$c = array("FFF","000","00007F","009000","FF0000","7F0000","9F009F","FF7F00","FFFF00","00F800","00908F","00FFFF","0000FF","FF00FF","7F7F7F","CFD0CF");
  374. $x = preg_replace("/\x02(.*?)((?=\x02)\x02|$)/", "<b>$1</b>", $x);
  375. $x = preg_replace("/\x1F(.*?)((?=\x1F)\x1F|$)/", "<u>$1</u>", $x);
  376. $x = preg_replace("/\x1D(.*?)((?=\x1D)\x1D|$)/", "<i>$1</i>", $x);
  377. /*
  378. $x = preg_replace("/\x03(\d\d?),(\d\d?)(.*?)(?(?=\x03)|$)/e", "'</span><span style=\"color: #'.\$c[$1].'; background-color: #'.\$c[$2].';\">$3</span>'", $x);
  379. $x = preg_replace("/\x03(\d\d?)(.*?)(?(?=\x03)|$)/e", "'</span><span style=\"color: #'.\$c[$1].';\">$2</span>'", $x);
  380. $x = preg_replace("/(\x0F|\x03)(.*?)/", "<span style=\"color: #000; background-color: #FFF;\">$2</span>", $x);
  381. //$x = preg_replace("/\x16(.*?)/", "<span style=\"color: #FFF; background-color: #000;\">$1</span>", $x);
  382. //$x = preg_replace("/\<\/span\>/","",$x,1);
  383. //$x = preg_replace("/(\<\/span\>){2}/","</span>",$x);
  384. */
  385. //preg_replace_callback("/(\x03)(\d\d?,\d\d?|\d\d?)(\s?.*?)(?(?=\x03)|$)/","color_rep",trim($topic));
  386. $x = preg_replace_callback('/\^C([0-9]{1,2}),?([0-9]{1,2})(.*?)\^C/', 'mycallback', $x);
  387. return $x;
  388. }
  389. function mycallback($matches) {
  390. $bindings = array(
  391. 0=>'white',
  392. 1=>'black',
  393. 2=>'blue',
  394. 3=>'green',
  395. 4=>'red',
  396. 5=>'brown',
  397. 6=>'purple',
  398. );
  399. $c = array("FFF","000","00007F","009000","FF0000","7F0000","9F009F","FF7F00","FFFF00","00F800","00908F","00FFFF","0000FF","FF00FF","7F7F7F","CFD0CF");
  400. $fg = isset($c[$matches[1]]) ? $c[$matches[1]] : 'transparent';
  401. $bg = isset($c[$matches[2]]) ? $c[$matches[2]] : 'transparent';
  402. return '<span style="color: #'.$fg.'; background: #'.$bg.';">'.$matches[3].'</span>';
  403. }
  404. function color_rep($matches) {
  405. $matches[2] = ltrim($matches[2], "0");
  406. $bindings = array(0=>'white',1=>'black',2=>'blue',3=>'green',4=>'red',5=>'brown',6=>'purple',7=>'orange',8=>'yellow',9=>'lightgreen',10=>'#00908F',
  407. 11=>'lightblue',12=>'blue',13=>'pink',14=>'grey',15=>'lightgrey');
  408. $preg = preg_match_all('/(\d\d?),(\d\d?)/',$matches[2], $col_arr);
  409. //print_r($col_arr);
  410. $fg = isset($bindings[$matches[2]]) ? $bindings[$matches[2]] : 'transparent';
  411. if ($preg == 1) {
  412. $fg = $bindings[$col_arr[1][0]];
  413. $bg = $bindings[$col_arr[2][0]];
  414. }
  415. else {
  416. $bg = 'transparent';
  417. }
  418. return '<span style="color: '.$fg.'; background: '.$bg.';">'.$matches[3].'</span>';
  419. }
  420. function curPageURL() {
  421. $pageURL = 'http';
  422. if ($_SERVER["HTTPS"] == "on") {$pageURL .= "s";}
  423. $pageURL .= "://";
  424. if ($_SERVER["SERVER_PORT"] != "80") {
  425. $pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
  426. } else {
  427. $pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
  428. }
  429. return $pageURL;
  430. }
  431. /*
  432. // Extend the rcon class to tweak it for minecraft.
  433. class minecraftRcon extends rcon {
  434. function mcSendCommand($Command) {
  435. $this->_Write(SERVERDATA_EXECCOMMAND,$Command,'');
  436. }
  437. function mcRconCommand($Command) {
  438. $this->mcSendcommand($Command);
  439. $ret = $this->Read();
  440. return $ret[$this->_Id]['S1'];
  441. }
  442. function Auth () {
  443. $PackID = $this->_Write(SERVERDATA_AUTH,$this->Password);$ret = $this->_PacketRead();
  444. if ($ret[0]['ID'] == -1) {
  445. die("Authentication Failure\n");
  446. }
  447. return true;
  448. }
  449. }
  450. */
  451. function full_copy($source, $target)
  452. {
  453. if ( is_dir( $source ) )
  454. {
  455. @mkdir( $target );
  456. $d = dir( $source );
  457. while ( FALSE !== ( $entry = $d->read() ) )
  458. {
  459. if ( $entry == '.' || $entry == '..' )
  460. {
  461. continue;
  462. }
  463. $Entry = $source . '/' . $entry;
  464. if ( is_dir( $Entry ) )
  465. {
  466. full_copy( $Entry, $target . '/' . $entry );
  467. continue;
  468. }
  469. copy( $Entry, $target . '/' . $entry );
  470. }
  471. $d->close();
  472. }
  473. else
  474. {
  475. copy( $source, $target );
  476. }
  477. }
  478. function deleteAll($directory, $empty = false)
  479. {
  480. if(substr($directory,-1) == "/") {
  481. $directory = substr($directory,0,-1);
  482. }
  483. if(!file_exists($directory) || !is_dir($directory)) {
  484. return false;
  485. } elseif(!is_readable($directory)) {
  486. return false;
  487. } else {
  488. $directoryHandle = opendir($directory);
  489. while ($contents = readdir($directoryHandle)) {
  490. if($contents != '.' && $contents != '..') {
  491. $path = $directory . "/" . $contents;
  492. if(is_dir($path)) {
  493. deleteAll($path);
  494. } else {
  495. unlink($path);
  496. }
  497. }
  498. }
  499. closedir($directoryHandle);
  500. if($empty == false) {
  501. if(!rmdir($directory)) {
  502. return false;
  503. }
  504. }
  505. return true;
  506. }
  507. }
  508. function bytesToSize($bytes, $precision = 2)
  509. {
  510. $kilobyte = 1024;
  511. $megabyte = $kilobyte * 1024;
  512. $gigabyte = $megabyte * 1024;
  513. $terabyte = $gigabyte * 1024;
  514. if (($bytes >= 0) && ($bytes < $kilobyte)) {
  515. return $bytes . ' B';
  516. } elseif (($bytes >= $kilobyte) && ($bytes < $megabyte)) {
  517. return round($bytes / $kilobyte, $precision) . ' KB';
  518. } elseif (($bytes >= $megabyte) && ($bytes < $gigabyte)) {
  519. return round($bytes / $megabyte, $precision) . ' MB';
  520. } elseif (($bytes >= $gigabyte) && ($bytes < $terabyte)) {
  521. return round($bytes / $gigabyte, $precision) . ' GB';
  522. } elseif ($bytes >= $terabyte) {
  523. return round($bytes / $terabyte, $precision) . ' TB';
  524. } else {
  525. return $bytes . ' B';
  526. }
  527. }
  528. function trim_value(&$value)
  529. {
  530. $value = trim($value); // this removes whitespace and related characters from the beginning and end of the string
  531. }
  532. function compress($buffer)
  533. {
  534. /* remove comments */
  535. $buffer = preg_replace('!/\*[^*]*\*+([^/][^*]*\*+)*/!', '', $buffer);
  536. /* remove tabs, spaces, newlines, etc. */
  537. $buffer = str_replace(array("\r\n", "\r", "\n", "\t", ' ', ' ', ' '), '', $buffer);
  538. return $buffer;
  539. }
  540. function is_dir_empty($dir)
  541. {
  542. if (!is_readable($dir)) return NULL;
  543. $handle = opendir($dir);
  544. while (false !== ($entry = readdir($handle)))
  545. {
  546. if ($entry != "." && $entry != "..")
  547. {
  548. return FALSE;
  549. }
  550. }
  551. return TRUE;
  552. }
  553. function multi_array_search($array, $search)
  554. {
  555. // Create the result array
  556. $result = array();
  557. // Iterate over each array element
  558. foreach ($array as $key => $value)
  559. {
  560. // Iterate over each search condition
  561. foreach ($search as $k => $v)
  562. {
  563. // If the array element does not meet the search condition then continue to the next element
  564. if (!isset($value[$k]) || $value[$k] != $v)
  565. {
  566. continue 2;
  567. }
  568. }
  569. // Add the array element's key to the result array
  570. $result[] = $key;
  571. }
  572. // Return the result array
  573. return $result;
  574. }
  575. ?>