summoner.class.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636
  1. <?php
  2. /**
  3. * Insipid
  4. * Personal web-bookmark-system
  5. *
  6. * Copyright 2016-2020 Johannes Keßler
  7. *
  8. * Development starting from 2011: Johannes Keßler
  9. * https://www.bananas-playground.net/projekt/insipid/
  10. *
  11. * creator:
  12. * Luke Reeves <luke@neuro-tech.net>
  13. *
  14. * This program is free software: you can redistribute it and/or modify
  15. * it under the terms of the GNU General Public License as published by
  16. * the Free Software Foundation, either version 3 of the License, or
  17. * (at your option) any later version.
  18. *
  19. * This program is distributed in the hope that it will be useful,
  20. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  21. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  22. * GNU General Public License for more details.
  23. *
  24. * You should have received a copy of the GNU General Public License
  25. * along with this program. If not, see http://www.gnu.org/licenses/gpl-3.0.
  26. *
  27. */
  28. /**
  29. * a static helper class
  30. */
  31. class Summoner {
  32. /**
  33. * validate the given string with the given type. Optional check the string
  34. * length
  35. *
  36. * @param string $input The string to check
  37. * @param string $mode How the string should be checked
  38. * @param mixed $limit If int given the string is checked for length
  39. *
  40. * @see http://de.php.net/manual/en/regexp.reference.unicode.php
  41. * http://www.sql-und-xml.de/unicode-database/#pc
  42. *
  43. * the pattern replaces all that is allowed. the correct result after
  44. * the replace should be empty, otherwise are there chars which are not
  45. * allowed
  46. *
  47. * @return bool
  48. */
  49. static function validate($input,$mode='text',$limit=false) {
  50. // check if we have input
  51. $input = trim($input);
  52. if($input == "") return false;
  53. $ret = false;
  54. switch ($mode) {
  55. case 'mail':
  56. if(filter_var($input,FILTER_VALIDATE_EMAIL) === $input) {
  57. return true;
  58. }
  59. else {
  60. return false;
  61. }
  62. break;
  63. case 'url':
  64. if(filter_var($input,FILTER_VALIDATE_URL) === $input) {
  65. return true;
  66. }
  67. else {
  68. return false;
  69. }
  70. break;
  71. case 'nospace':
  72. // text without any whitespace and special chars
  73. $pattern = '/[\p{L}\p{N}]/u';
  74. break;
  75. case 'nospaceP':
  76. // text without any whitespace and special chars
  77. // but with Punctuation other
  78. # http://www.sql-und-xml.de/unicode-database/po.html
  79. $pattern = '/[\p{L}\p{N}\p{Po}\-]/u';
  80. break;
  81. case 'digit':
  82. // only numbers and digit
  83. // warning with negative numbers...
  84. $pattern = '/[\p{N}\-]/';
  85. break;
  86. case 'pageTitle':
  87. // text with whitespace and without special chars
  88. // but with Punctuation
  89. $pattern = '/[\p{L}\p{N}\p{Po}\p{Z}\s-]/u';
  90. break;
  91. # strange. the \p{M} is needed.. don't know why..
  92. case 'filename':
  93. $pattern = '/[\p{L}\p{N}\p{M}\-_\.\p{Zs}]/u';
  94. break;
  95. case 'text':
  96. default:
  97. $pattern = '/[\p{L}\p{N}\p{P}\p{S}\p{Z}\p{M}\s]/u';
  98. }
  99. $value = preg_replace($pattern, '', $input);
  100. if($value === "") {
  101. $ret = true;
  102. }
  103. if(!empty($limit)) {
  104. # isset starts with 0
  105. if(isset($input[$limit])) {
  106. # too long
  107. $ret = false;
  108. }
  109. }
  110. return $ret;
  111. }
  112. /**
  113. * return if the given string is utf8
  114. * http://php.net/manual/en/function.mb-detect-encoding.php
  115. *
  116. * @param string $string
  117. * @return number
  118. */
  119. static function is_utf8($string) {
  120. // From http://w3.org/International/questions/qa-forms-utf-8.html
  121. return preg_match('%^(?:
  122. [\x09\x0A\x0D\x20-\x7E] # ASCII
  123. | [\xC2-\xDF][\x80-\xBF] # non-overlong 2-byte
  124. | \xE0[\xA0-\xBF][\x80-\xBF] # excluding overlongs
  125. | [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2} # straight 3-byte
  126. | \xED[\x80-\x9F][\x80-\xBF] # excluding surrogates
  127. | \xF0[\x90-\xBF][\x80-\xBF]{2} # planes 1-3
  128. | [\xF1-\xF3][\x80-\xBF]{3} # planes 4-15
  129. | \xF4[\x80-\x8F][\x80-\xBF]{2} # plane 16
  130. )*$%xs', $string);
  131. }
  132. /**
  133. * execute a curl call to the given $url
  134. * @param string $url The request url
  135. * @param bool $port
  136. * @return bool|mixed
  137. */
  138. static function curlCall($url,$port=false) {
  139. $ret = false;
  140. $ch = curl_init();
  141. curl_setopt($ch, CURLOPT_URL, $url);
  142. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  143. curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 15);
  144. curl_setopt($ch, CURLOPT_TIMEOUT, 30);
  145. curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
  146. curl_setopt($ch, CURLOPT_MAXREDIRS, 2);
  147. curl_setopt($ch, CURLOPT_USERAGENT,'Mozilla/5.0 (X11; Linux x86_64; rv:68.0) Gecko/20100101 Firefox/68.0');
  148. // curl_setopt($ch, CURLOPT_VERBOSE, true);
  149. //curl_setopt($ch, CURLOPT_HEADER, true);
  150. if(!empty($port)) {
  151. curl_setopt($ch, CURLOPT_PORT, $port);
  152. }
  153. $do = curl_exec($ch);
  154. if(is_string($do) === true) {
  155. $ret = $do;
  156. }
  157. else {
  158. error_log('ERROR '.var_export(curl_error($ch),true));
  159. }
  160. curl_close($ch);
  161. return $ret;
  162. }
  163. /**
  164. * Download given url to given file
  165. * @param $url
  166. * @param $whereToStore
  167. * @param bool $port
  168. * @return bool
  169. */
  170. static function downloadFile($url, $whereToStore, $port=false) {
  171. $fh = fopen($whereToStore, 'w+');
  172. $ret = false;
  173. if($fh !== false) {
  174. $ch = curl_init($url);
  175. curl_setopt($ch, CURLOPT_FILE, $fh);
  176. curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 15);
  177. curl_setopt($ch, CURLOPT_TIMEOUT, 30);
  178. curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
  179. curl_setopt($ch, CURLOPT_MAXREDIRS, 2);
  180. curl_setopt($ch, CURLOPT_USERAGENT,'Mozilla/5.0 (X11; Linux x86_64; rv:68.0) Gecko/20100101 Firefox/68.0');
  181. if(!empty($port)) {
  182. curl_setopt($ch, CURLOPT_PORT, $port);
  183. }
  184. curl_exec($ch);
  185. curl_close($ch);
  186. $ret = true;
  187. }
  188. fclose($fh);
  189. return $ret;
  190. }
  191. /**
  192. * check if a string starts with a given string
  193. *
  194. * @param string $haystack
  195. * @param string $needle
  196. * @return boolean
  197. */
  198. static function startsWith($haystack, $needle) {
  199. $length = strlen($needle);
  200. return (substr($haystack, 0, $length) === $needle);
  201. }
  202. /**
  203. * check if a string ends with a given string
  204. *
  205. * @param string $haystack
  206. * @param string $needle
  207. * @return boolean
  208. */
  209. static function endsWith($haystack, $needle) {
  210. $length = strlen($needle);
  211. if ($length == 0) {
  212. return true;
  213. }
  214. return (substr($haystack, -$length) === $needle);
  215. }
  216. /**
  217. * simulate the Null coalescing operator in php5
  218. * this only works with arrays and checking if the key is there and echo/return it.
  219. * http://php.net/manual/en/migration70.new-features.php#migration70.new-features.null-coalesce-op
  220. *
  221. * @param $array
  222. * @param $key
  223. * @return bool
  224. */
  225. static function ifset($array,$key) {
  226. return isset($array[$key]) ? $array[$key] : false;
  227. }
  228. /**
  229. * try to gather meta information from given URL
  230. * @param string $url
  231. * @return array|bool
  232. */
  233. static function gatherInfoFromURL($url) {
  234. $ret = false;
  235. if(self::validate($url,'url')) {
  236. $data = self::curlCall($url);
  237. if(!empty($data)) {
  238. $ret = self::socialMetaInfos($data);
  239. }
  240. }
  241. return $ret;
  242. }
  243. /**
  244. * get as much as possible social meta infos from given string
  245. * the string is usually a HTML source
  246. * @param string $string
  247. * @return array
  248. */
  249. static function socialMetaInfos($string) {
  250. #http://www.w3bees.com/2013/11/fetch-facebook-og-meta-tags-with-php.html
  251. #http://www.9lessons.info/2014/01/social-meta-tags-for-google-twitter-and.html
  252. #http://ogp.me/
  253. #https://moz.com/blog/meta-data-templates-123
  254. $dom = new DomDocument;
  255. # surpress invalid html warnings
  256. @$dom->loadHTML($string);
  257. $xpath = new DOMXPath($dom);
  258. $metas = $xpath->query('//*/meta');
  259. $mediaInfos = array();
  260. # meta tags
  261. foreach($metas as $meta) {
  262. if($meta->getAttribute('property')) {
  263. $prop = $meta->getAttribute('property');
  264. $prop = mb_strtolower($prop);
  265. # minimum required information
  266. # http://ogp.me/#metadata
  267. if($prop == "og:title") {
  268. $mediaInfos['title'] = $meta->getAttribute('content');
  269. }
  270. elseif($prop == "og:image") {
  271. $mediaInfos['image'] = $meta->getAttribute('content');
  272. }
  273. elseif($prop == "og:url") {
  274. $mediaInfos['link'] = $meta->getAttribute('content');
  275. }
  276. elseif($prop == "og:description") {
  277. $mediaInfos['description'] = $meta->getAttribute('content');
  278. }
  279. }
  280. elseif($meta->getAttribute('name')) {
  281. $name = $meta->getAttribute('name');
  282. $name = mb_strtolower($name);
  283. # twitter
  284. # https://dev.twitter.com/cards/overview
  285. if($name == "twitter:title") {
  286. $mediaInfos['title'] = $meta->getAttribute('content');
  287. }
  288. elseif($name == "twitter:description") {
  289. $mediaInfos['description'] = $meta->getAttribute('content');
  290. }
  291. elseif($name == "twitter:image") {
  292. $mediaInfos['image'] = $meta->getAttribute('content');
  293. }
  294. elseif($name == "description") {
  295. $mediaInfos['description'] = $meta->getAttribute('content');
  296. }
  297. }
  298. elseif($meta->getAttribute('itemprop')) {
  299. $itemprop = $meta->getAttribute('itemprop');
  300. $itemprop = mb_strtolower($itemprop);
  301. # google plus
  302. if($itemprop == "name") {
  303. $mediaInfos['title'] = $meta->getAttribute('content');
  304. }
  305. elseif($itemprop == "description") {
  306. $mediaInfos['description'] = $meta->getAttribute('content');
  307. }
  308. elseif($itemprop == "image") {
  309. $mediaInfos['image'] = $meta->getAttribute('content');
  310. }
  311. }
  312. }
  313. if(!isset($mediaInfos['title'])) {
  314. $titleDom = $xpath->query('//title');
  315. $mediaInfos['title'] = $titleDom->item(0)->nodeValue;
  316. }
  317. return $mediaInfos;
  318. }
  319. /**
  320. * at creation a category or tag can be a string with multiple values.
  321. * separated with space or ,
  322. * category and tag is a single string without any separators
  323. *
  324. * @param string $string
  325. * @return array
  326. */
  327. static function prepareTagOrCategoryStr($string) {
  328. $ret = array();
  329. $string = trim($string, ", ");
  330. if(strstr($string, ",")) {
  331. $_t = explode(",", $string);
  332. foreach($_t as $new) {
  333. $ret[$new] = $new;
  334. }
  335. unset($_t);
  336. unset($new);
  337. foreach($ret as $e) {
  338. if(strstr($e, " ")) {
  339. unset($ret[$e]);
  340. $_t = explode(" ", $e);
  341. foreach($_t as $new) {
  342. $new = trim($new);
  343. if(!empty($new)) {
  344. $ret[$new] = $new;
  345. }
  346. }
  347. }
  348. }
  349. }
  350. else {
  351. $_t = explode(" ", $string);
  352. foreach($_t as $new) {
  353. $new = trim($new);
  354. if(!empty($new)) {
  355. $ret[$new] = $new;
  356. }
  357. }
  358. }
  359. return $ret;
  360. }
  361. /**
  362. * a very simple HTTP_AUTH authentication.
  363. */
  364. static function simpleAuth() {
  365. if (!isset($_SERVER['PHP_AUTH_USER']) || !isset($_SERVER['PHP_AUTH_PW'])
  366. || $_SERVER['PHP_AUTH_USER'] !== FRONTEND_USERNAME || $_SERVER['PHP_AUTH_PW'] !== FRONTEND_PASSWORD
  367. ) {
  368. header('WWW-Authenticate: Basic realm="Insipid edit area"');
  369. header('HTTP/1.0 401 Unauthorized');
  370. echo 'No Access.';
  371. exit;
  372. }
  373. }
  374. /**
  375. * check if we have a valid auth. Nothing more.
  376. * @see Summoner::simpleAuth to trigger the auth
  377. * @return bool
  378. */
  379. static function simpleAuthCheck() {
  380. if (isset($_SERVER['PHP_AUTH_USER']) && isset($_SERVER['PHP_AUTH_PW'])
  381. && $_SERVER['PHP_AUTH_USER'] === FRONTEND_USERNAME && $_SERVER['PHP_AUTH_PW'] === FRONTEND_PASSWORD
  382. ) {
  383. return true;
  384. }
  385. return false;
  386. }
  387. /**
  388. * Checks if in the given urlstring a scheme is existent. If not add http:// to it
  389. * @param $urlString
  390. * @return string
  391. */
  392. static function addSchemeToURL($urlString) {
  393. $ret = $urlString;
  394. if(empty(parse_url($ret, PHP_URL_SCHEME))) {
  395. $ret = "http://".$ret;
  396. }
  397. return $ret;
  398. }
  399. /**
  400. * retrieve the folder size with its children of given folder path
  401. * @param $folder
  402. * @return false|int
  403. */
  404. static function folderSize($folder) {
  405. $ret = 0;
  406. if(file_exists($folder) && is_readable($folder)) {
  407. foreach (glob(rtrim($folder, '/') . '/*', GLOB_NOSORT) as $each) {
  408. $ret += is_file($each) ? filesize($each) : self::folderSize($each);
  409. }
  410. }
  411. return $ret;
  412. }
  413. /**
  414. * Calculate the given byte size in more human readable format.
  415. * @param $size
  416. * @param string $unit
  417. * @return string
  418. */
  419. static function humanFileSize($size,$unit="") {
  420. $ret = number_format($size)." bytes";
  421. if((!$unit && $size >= 1<<30) || $unit == "GB") {
  422. $ret = number_format($size / (1 << 30), 2)."GB";
  423. }
  424. elseif((!$unit && $size >= 1<<20) || $unit == "MB") {
  425. $ret = number_format($size / (1 << 20), 2) . "MB";
  426. }
  427. elseif( (!$unit && $size >= 1<<10) || $unit == "KB") {
  428. $ret = number_format($size / (1 << 10), 2) . "KB";
  429. }
  430. return $ret;
  431. }
  432. /**
  433. * delete and/or empty a directory
  434. *
  435. * $empty = true => empty the directory but do not delete it
  436. *
  437. * @param string $directory
  438. * @param boolean $empty
  439. * @param int $fTime If not false remove files older then this value in sec.
  440. * @return boolean
  441. */
  442. static function recursive_remove_directory($directory,$empty=false,$fTime=0) {
  443. if(substr($directory,-1) == '/') {
  444. $directory = substr($directory,0,-1);
  445. }
  446. if(!file_exists($directory) || !is_dir($directory)) {
  447. return false;
  448. }
  449. elseif(!is_readable($directory)) {
  450. return false;
  451. }
  452. else {
  453. $handle = opendir($directory);
  454. // and scan through the items inside
  455. while (false !== ($item = readdir($handle))) {
  456. if($item[0] != '.') {
  457. $path = $directory.'/'.$item;
  458. if(is_dir($path)) {
  459. recursive_remove_directory($path);
  460. }
  461. else {
  462. if($fTime !== false && is_int($fTime)) {
  463. $ft = filemtime($path);
  464. $offset = time()-$fTime;
  465. if($ft <= $offset) {
  466. unlink($path);
  467. }
  468. }
  469. else {
  470. unlink($path);
  471. }
  472. }
  473. }
  474. }
  475. closedir($handle);
  476. if($empty === false) {
  477. if(!rmdir($directory)) {
  478. return false;
  479. }
  480. }
  481. return true;
  482. }
  483. }
  484. /**
  485. * http_build_query with modify array
  486. * modify will add: key AND value not empty
  487. * modify will remove: only key with no value
  488. *
  489. * @param $array
  490. * @param bool $modify
  491. * @return string
  492. */
  493. static function createFromParameterLinkQuery($array,$modify=false) {
  494. $ret = '';
  495. if(!empty($modify)) {
  496. foreach($modify as $k=>$v) {
  497. if(empty($v)) {
  498. unset($array[$k]);
  499. }
  500. else {
  501. $array[$k] = $v;
  502. }
  503. }
  504. }
  505. if(!empty($array)) {
  506. $ret = http_build_query($array);
  507. }
  508. return $ret;
  509. }
  510. /**
  511. * Simple helper to detect the $_FILES upload status
  512. * Expects the error value from $_FILES['error']
  513. * @param $error
  514. * @return array
  515. */
  516. static function checkFileUploadStatus($error) {
  517. $message = "Unknown upload error";
  518. $status = false;
  519. switch ($error) {
  520. case UPLOAD_ERR_OK:
  521. $message = "There is no error, the file uploaded with success.";
  522. $status = true;
  523. break;
  524. case UPLOAD_ERR_INI_SIZE:
  525. $message = "The uploaded file exceeds the upload_max_filesize directive in php.ini";
  526. break;
  527. case UPLOAD_ERR_FORM_SIZE:
  528. $message = "The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form";
  529. break;
  530. case UPLOAD_ERR_PARTIAL:
  531. $message = "The uploaded file was only partially uploaded";
  532. break;
  533. case UPLOAD_ERR_NO_FILE:
  534. $message = "No file was uploaded";
  535. break;
  536. case UPLOAD_ERR_NO_TMP_DIR:
  537. $message = "Missing a temporary folder";
  538. break;
  539. case UPLOAD_ERR_CANT_WRITE:
  540. $message = "Failed to write file to disk";
  541. break;
  542. case UPLOAD_ERR_EXTENSION:
  543. $message = "File upload stopped by extension";
  544. break;
  545. }
  546. return array(
  547. 'message' => $message,
  548. 'status' => $status
  549. );
  550. }
  551. }