BioTorrents.de’s version of Gazelle
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.

misc.class.php 18KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580
  1. <?php
  2. class Misc
  3. {
  4. /**
  5. * Send an email.
  6. *
  7. * @param string $To the email address to send it to.
  8. * @param string $Subject
  9. * @param string $Body
  10. * @param string $From The user part of the user@$ENV->SITE_DOMAIN email address.
  11. * @param string $ContentType text/plain or text/html
  12. */
  13. public static function send_email($To, $Subject, $Body, $From = 'noreply', $ContentType = 'text/plain')
  14. {
  15. $ENV = ENV::go();
  16. # todo: <<<EOT
  17. $Headers = "MIME-Version: 1.0\r\n";
  18. $Headers .= "Content-type: $ContentType; charset=utf-8\r\n";
  19. $Headers .= "From: $ENV->SITE_NAME <$From@$ENV->SITE_DOMAIN>\r\n";
  20. $Headers .= "Reply-To: $From@$ENV->SITE_DOMAIN\r\n";
  21. $Headers .= "X-Mailer: Project Gazelle\r\n";
  22. $Headers .= "Message-Id: <".Users::make_secret()."@$ENV->SITE_DOMAIN>\r\n";
  23. $Headers .= "X-Priority: 3\r\n";
  24. // Check if email is enabled
  25. if ($ENV->FEATURE_SEND_EMAIL) {
  26. mail($To, $Subject, $Body, $Headers, "-f $From@$ENV->SITE_DOMAIN");
  27. }
  28. }
  29. /**
  30. * Sanitize a string to be allowed as a filename.
  31. *
  32. * @param string $EscapeStr the string to escape
  33. * @return the string with all banned characters removed.
  34. */
  35. public static function file_string($EscapeStr)
  36. {
  37. $ENV = ENV::go();
  38. return str_replace($ENV->BAD_CHARS, '', $EscapeStr);
  39. }
  40. /**
  41. * Sends a PM from $FromId to $ToId.
  42. *
  43. * @param string $ToID ID of user to send PM to. If $ToID is an array and $ConvID is empty, a message will be sent to multiple users.
  44. * @param string $FromID ID of user to send PM from, 0 to send from system
  45. * @param string $Subject
  46. * @param string $Body
  47. * @param int $ConvID The conversation the message goes in. Leave blank to start a new conversation.
  48. * @return
  49. */
  50. public static function send_pm($ToID, $FromID, $Subject, $Body, $ConvID = '')
  51. {
  52. global $Time;
  53. $UnescapedSubject = $Subject;
  54. $UnescapedBody = $Body;
  55. $Subject = db_string($Subject);
  56. $Body = Crypto::encrypt(substr($Body, 0, 49135)); // 49135 -> encryption -> 65536 (max length in mysql)
  57. if ($ToID === 0) {
  58. // Don't allow users to send messages to the system
  59. return;
  60. }
  61. $QueryID = G::$DB->get_query_id();
  62. if ($ConvID === '') {
  63. // Create a new conversation.
  64. G::$DB->query("
  65. INSERT INTO pm_conversations (Subject)
  66. VALUES ('$Subject')");
  67. $ConvID = G::$DB->inserted_id();
  68. G::$DB->query("
  69. INSERT INTO pm_conversations_users
  70. (UserID, ConvID, InInbox, InSentbox, SentDate, ReceivedDate, UnRead)
  71. VALUES
  72. ('$ToID', '$ConvID', '1','0', NOW(), NOW(), '1')");
  73. if ($FromID === $ToID) {
  74. G::$DB->query(
  75. "
  76. UPDATE pm_conversations_users
  77. SET InSentbox = '1'
  78. WHERE ConvID = '$ConvID'"
  79. );
  80. } elseif ($FromID !== 0) {
  81. G::$DB->query("
  82. INSERT INTO pm_conversations_users
  83. (UserID, ConvID, InInbox, InSentbox, SentDate, ReceivedDate, UnRead)
  84. VALUES
  85. ('$FromID', '$ConvID', '0','1', NOW(), NOW(), '0')");
  86. }
  87. $ToID = array($ToID);
  88. } else {
  89. // Update the pre-existing conversations
  90. G::$DB->query("
  91. UPDATE pm_conversations_users
  92. SET
  93. InInbox = '1',
  94. UnRead = '1',
  95. ReceivedDate = NOW()
  96. WHERE UserID IN (".implode(',', $ToID).")
  97. AND ConvID = '$ConvID'");
  98. G::$DB->query("
  99. UPDATE pm_conversations_users
  100. SET
  101. InSentbox = '1',
  102. SentDate = NOW()
  103. WHERE UserID = '$FromID'
  104. AND ConvID = '$ConvID'");
  105. }
  106. // Now that we have a $ConvID for sure, send the message
  107. G::$DB->query("
  108. INSERT INTO pm_messages
  109. (SenderID, ConvID, SentDate, Body)
  110. VALUES
  111. ('$FromID', '$ConvID', NOW(), '$Body')");
  112. // Update the cached new message count
  113. foreach ($ToID as $ID) {
  114. G::$DB->query("
  115. SELECT COUNT(ConvID)
  116. FROM pm_conversations_users
  117. WHERE UnRead = '1'
  118. AND UserID = '$ID'
  119. AND InInbox = '1'");
  120. list($UnRead) = G::$DB->next_record();
  121. G::$Cache->cache_value("inbox_new_$ID", $UnRead);
  122. }
  123. G::$DB->query("
  124. SELECT Username
  125. FROM users_main
  126. WHERE ID = '$FromID'");
  127. list($SenderName) = G::$DB->next_record();
  128. foreach ($ToID as $ID) {
  129. G::$DB->query("
  130. SELECT COUNT(ConvID)
  131. FROM pm_conversations_users
  132. WHERE UnRead = '1'
  133. AND UserID = '$ID'
  134. AND InInbox = '1'");
  135. list($UnRead) = G::$DB->next_record();
  136. G::$Cache->cache_value("inbox_new_$ID", $UnRead);
  137. }
  138. G::$DB->set_query_id($QueryID);
  139. return $ConvID;
  140. }
  141. /**
  142. * Create thread function, things should already be escaped when sent here.
  143. *
  144. * @param int $ForumID
  145. * @param int $AuthorID ID of the user creating the post.
  146. * @param string $Title
  147. * @param string $PostBody
  148. * @return -1 on error, -2 on user not existing, thread id on success.
  149. */
  150. public static function create_thread($ForumID, $AuthorID, $Title, $PostBody)
  151. {
  152. global $Time;
  153. if (!$ForumID || !$AuthorID || !is_number($AuthorID) || !$Title || !$PostBody) {
  154. return -1;
  155. }
  156. $QueryID = G::$DB->get_query_id();
  157. G::$DB->query("
  158. SELECT Username
  159. FROM users_main
  160. WHERE ID = $AuthorID");
  161. if (!G::$DB->has_results()) {
  162. G::$DB->set_query_id($QueryID);
  163. return -2;
  164. }
  165. list($AuthorName) = G::$DB->next_record();
  166. $ThreadInfo = [];
  167. $ThreadInfo['IsLocked'] = 0;
  168. $ThreadInfo['IsSticky'] = 0;
  169. G::$DB->query("
  170. INSERT INTO forums_topics
  171. (Title, AuthorID, ForumID, LastPostTime, LastPostAuthorID, CreatedTime)
  172. VALUES
  173. ('$Title', '$AuthorID', '$ForumID', NOW(), '$AuthorID', NOW())");
  174. $TopicID = G::$DB->inserted_id();
  175. $Posts = 1;
  176. G::$DB->query("
  177. INSERT INTO forums_posts
  178. (TopicID, AuthorID, AddedTime, Body)
  179. VALUES
  180. ('$TopicID', '$AuthorID', NOW(), '$PostBody')");
  181. $PostID = G::$DB->inserted_id();
  182. G::$DB->query("
  183. UPDATE forums
  184. SET
  185. NumPosts = NumPosts + 1,
  186. NumTopics = NumTopics + 1,
  187. LastPostID = '$PostID',
  188. LastPostAuthorID = '$AuthorID',
  189. LastPostTopicID = '$TopicID',
  190. LastPostTime = NOW()
  191. WHERE ID = '$ForumID'");
  192. G::$DB->query("
  193. UPDATE forums_topics
  194. SET
  195. NumPosts = NumPosts + 1,
  196. LastPostID = '$PostID',
  197. LastPostAuthorID = '$AuthorID',
  198. LastPostTime = NOW()
  199. WHERE ID = '$TopicID'");
  200. // Bump this topic to head of the cache
  201. list($Forum, , , $Stickies) = G::$Cache->get_value("forums_$ForumID");
  202. if (!empty($Forum)) {
  203. if (count($Forum) === TOPICS_PER_PAGE && $Stickies < TOPICS_PER_PAGE) {
  204. array_pop($Forum);
  205. }
  206. G::$DB->query("
  207. SELECT IsLocked, IsSticky, NumPosts
  208. FROM forums_topics
  209. WHERE ID ='$TopicID'");
  210. list($IsLocked, $IsSticky, $NumPosts) = G::$DB->next_record();
  211. $Part1 = array_slice($Forum, 0, $Stickies, true); // Stickies
  212. $Part2 = array(
  213. $TopicID => array(
  214. 'ID' => $TopicID,
  215. 'Title' => $Title,
  216. 'AuthorID' => $AuthorID,
  217. 'IsLocked' => $IsLocked,
  218. 'IsSticky' => $IsSticky,
  219. 'NumPosts' => $NumPosts,
  220. 'LastPostID' => $PostID,
  221. 'LastPostTime' => sqltime(),
  222. 'LastPostAuthorID' => $AuthorID,
  223. )
  224. ); // Bumped thread
  225. $Part3 = array_slice($Forum, $Stickies, TOPICS_PER_PAGE, true); //Rest of page
  226. if ($Stickies > 0) {
  227. $Part1 = array_slice($Forum, 0, $Stickies, true); //Stickies
  228. $Part3 = array_slice($Forum, $Stickies, TOPICS_PER_PAGE - $Stickies - 1, true); //Rest of page
  229. } else {
  230. $Part1 = [];
  231. $Part3 = $Forum;
  232. }
  233. if (is_null($Part1)) {
  234. $Part1 = [];
  235. }
  236. if (is_null($Part3)) {
  237. $Part3 = [];
  238. }
  239. $Forum = $Part1 + $Part2 + $Part3;
  240. G::$Cache->cache_value("forums_$ForumID", array($Forum, '', 0, $Stickies), 0);
  241. }
  242. // Update the forum root
  243. G::$Cache->begin_transaction('forums_list');
  244. $UpdateArray = array(
  245. 'NumPosts' => '+1',
  246. 'NumTopics' => '+1',
  247. 'LastPostID' => $PostID,
  248. 'LastPostAuthorID' => $AuthorID,
  249. 'LastPostTopicID' => $TopicID,
  250. 'LastPostTime' => sqltime(),
  251. 'Title' => $Title,
  252. 'IsLocked' => $ThreadInfo['IsLocked'],
  253. 'IsSticky' => $ThreadInfo['IsSticky']
  254. );
  255. $UpdateArray['NumTopics'] = '+1';
  256. G::$Cache->update_row($ForumID, $UpdateArray);
  257. G::$Cache->commit_transaction(0);
  258. $CatalogueID = floor((POSTS_PER_PAGE * ceil($Posts / POSTS_PER_PAGE) - POSTS_PER_PAGE) / THREAD_CATALOGUE);
  259. G::$Cache->begin_transaction('thread_'.$TopicID.'_catalogue_'.$CatalogueID);
  260. $Post = array(
  261. 'ID' => $PostID,
  262. 'AuthorID' => G::$LoggedUser['ID'],
  263. 'AddedTime' => sqltime(),
  264. 'Body' => $PostBody,
  265. 'EditedUserID' => 0,
  266. 'EditedTime' => null,
  267. 'Username' => ''
  268. );
  269. G::$Cache->insert('', $Post);
  270. G::$Cache->commit_transaction(0);
  271. G::$Cache->begin_transaction('thread_'.$TopicID.'_info');
  272. G::$Cache->update_row(false, array('Posts' => '+1', 'LastPostAuthorID' => $AuthorID));
  273. G::$Cache->commit_transaction(0);
  274. G::$DB->set_query_id($QueryID);
  275. return $TopicID;
  276. }
  277. /**
  278. * If the suffix of $Haystack is $Needle
  279. *
  280. * @param string $Haystack String to search in
  281. * @param string $Needle String to search for
  282. * @return boolean True if $Needle is a suffix of $Haystack
  283. */
  284. public static function ends_with($Haystack, $Needle)
  285. {
  286. return substr($Haystack, strlen($Needle) * -1) === $Needle;
  287. }
  288. /**
  289. * If the prefix of $Haystack is $Needle
  290. *
  291. * @param string $Haystack String to search in
  292. * @param string $Needle String to search for
  293. * @return boolean True if $Needle is a prefix of $Haystack
  294. */
  295. public static function starts_with($Haystack, $Needle)
  296. {
  297. return strpos($Haystack, $Needle) === 0;
  298. }
  299. /**
  300. * Variant of in_array() with trailing wildcard support
  301. *
  302. * @param string $Needle, array $Haystack
  303. * @return boolean true if (substring of) $Needle exists in $Haystack
  304. */
  305. public static function in_array_partial($Needle, $Haystack)
  306. {
  307. static $Searches = [];
  308. if (array_key_exists($Needle, $Searches)) {
  309. return $Searches[$Needle];
  310. }
  311. foreach ($Haystack as $String) {
  312. if (substr($String, -1) === '*') {
  313. if (!strncmp($Needle, $String, strlen($String) - 1)) {
  314. $Searches[$Needle] = true;
  315. return true;
  316. }
  317. } elseif (!strcmp($Needle, $String)) {
  318. $Searches[$Needle] = true;
  319. return true;
  320. }
  321. }
  322. $Searches[$Needle] = false;
  323. return false;
  324. }
  325. /**
  326. * Used to check if keys in $_POST and $_GET are all set, and throws an error if not.
  327. * This reduces 'if' statement redundancy for a lot of variables
  328. *
  329. * @param array $Request Either $_POST or $_GET, or whatever other array you want to check.
  330. * @param array $Keys The keys to ensure are set.
  331. * @param boolean $AllowEmpty If set to true, a key that is in the request but blank will not throw an error.
  332. * @param int $Error The error code to throw if one of the keys isn't in the array.
  333. */
  334. public static function assert_isset_request($Request, $Keys = null, $AllowEmpty = false, $Error = 0)
  335. {
  336. if (isset($Keys)) {
  337. foreach ($Keys as $K) {
  338. if (!isset($Request[$K]) || ($AllowEmpty === false && $Request[$K] === '')) {
  339. error($Error);
  340. break;
  341. }
  342. }
  343. } else {
  344. foreach ($Request as $R) {
  345. if (!isset($R) || ($AllowEmpty === false && $R === '')) {
  346. error($Error);
  347. break;
  348. }
  349. }
  350. }
  351. }
  352. /**
  353. * Given an array of tags, return an array of their IDs.
  354. *
  355. * @param array $TagNames
  356. * @return array IDs
  357. */
  358. public static function get_tags($TagNames)
  359. {
  360. $TagIDs = [];
  361. foreach ($TagNames as $Index => $TagName) {
  362. $Tag = G::$Cache->get_value("tag_id_$TagName");
  363. if (is_array($Tag)) {
  364. unset($TagNames[$Index]);
  365. $TagIDs[$Tag['ID']] = $Tag['Name'];
  366. }
  367. }
  368. if (count($TagNames) > 0) {
  369. $QueryID = G::$DB->get_query_id();
  370. G::$DB->query("
  371. SELECT ID, Name
  372. FROM tags
  373. WHERE Name IN ('".implode("', '", $TagNames)."')");
  374. $SQLTagIDs = G::$DB->to_array();
  375. G::$DB->set_query_id($QueryID);
  376. foreach ($SQLTagIDs as $Tag) {
  377. $TagIDs[$Tag['ID']] = $Tag['Name'];
  378. G::$Cache->cache_value('tag_id_'.$Tag['Name'], $Tag, 0);
  379. }
  380. }
  381. return($TagIDs);
  382. }
  383. /**
  384. * Gets the alias of the tag; if there is no alias, silently returns the original tag.
  385. *
  386. * @param string $BadTag the tag we want to alias
  387. * @return string The aliased tag.
  388. */
  389. public static function get_alias_tag($BadTag)
  390. {
  391. $QueryID = G::$DB->get_query_id();
  392. G::$DB->query("
  393. SELECT AliasTag
  394. FROM tag_aliases
  395. WHERE BadTag = '$BadTag'
  396. LIMIT 1");
  397. if (G::$DB->has_results()) {
  398. list($AliasTag) = G::$DB->next_record();
  399. } else {
  400. $AliasTag = $BadTag;
  401. }
  402. G::$DB->set_query_id($QueryID);
  403. return $AliasTag;
  404. }
  405. /*
  406. * Write a message to the system log.
  407. *
  408. * @param string $Message the message to write.
  409. */
  410. public static function write_log($Message)
  411. {
  412. global $Time;
  413. $QueryID = G::$DB->get_query_id();
  414. G::$DB->query("
  415. INSERT INTO log (Message, Time)
  416. VALUES (?, NOW())", $Message);
  417. G::$DB->set_query_id($QueryID);
  418. }
  419. /**
  420. * Get a tag ready for database input and display.
  421. *
  422. * @param string $Str
  423. * @return sanitized version of $Str
  424. */
  425. public static function sanitize_tag($Str)
  426. {
  427. $Str = strtolower($Str);
  428. $Str = preg_replace('/[^a-z0-9:.]/', '', $Str);
  429. $Str = preg_replace('/(^[.,]*)|([.,]*$)/', '', $Str);
  430. $Str = htmlspecialchars($Str);
  431. $Str = db_string(trim($Str));
  432. return $Str;
  433. }
  434. /**
  435. * HTML escape an entire array for output.
  436. * @param array $Array, what we want to escape
  437. * @param boolean/array $Escape
  438. * if true, all keys escaped
  439. * if false, no escaping.
  440. * If array, it's a list of array keys not to escape.
  441. * @return mutated version of $Array with values escaped.
  442. */
  443. public static function display_array($Array, $Escape = [])
  444. {
  445. foreach ($Array as $Key => $Val) {
  446. if ((!is_array($Escape) && $Escape === true) || !in_array($Key, $Escape)) {
  447. $Array[$Key] = display_str($Val);
  448. }
  449. }
  450. return $Array;
  451. }
  452. /**
  453. * Searches for a key/value pair in an array.
  454. *
  455. * @return array of results
  456. */
  457. public static function search_array($Array, $Key, $Value)
  458. {
  459. $Results = [];
  460. if (is_array($Array)) {
  461. if (isset($Array[$Key]) && $Array[$Key] === $Value) {
  462. $Results[] = $Array;
  463. }
  464. foreach ($Array as $subarray) {
  465. $Results = array_merge($Results, self::search_array($subarray, $Key, $Value));
  466. }
  467. }
  468. return $Results;
  469. }
  470. /**
  471. * Search for $Needle in the string $Haystack which is a list of values separated by $Separator.
  472. * @param string $Haystack
  473. * @param string $Needle
  474. * @param string $Separator
  475. * @param boolean $Strict
  476. * @return boolean
  477. */
  478. public static function search_joined_string($Haystack, $Needle, $Separator = '|', $Strict = true)
  479. {
  480. return (array_search($Needle, explode($Separator, $Haystack), $Strict) !== false);
  481. }
  482. /**
  483. * Check for a ":" in the beginning of a torrent meta data string
  484. * to see if it's stored in the old base64-encoded format
  485. *
  486. * @param string $Torrent the torrent data
  487. * @return true if the torrent is stored in binary format
  488. */
  489. public static function is_new_torrent(&$Data)
  490. {
  491. return strpos(substr($Data, 0, 10), ':') !== false;
  492. }
  493. public static function display_recommend($ID, $Type, $Hide = true)
  494. {
  495. if ($Hide) {
  496. $Hide = ' style="display: none;"';
  497. } ?>
  498. <div id="recommendation_div" data-id="<?=$ID?>"
  499. data-type="<?=$Type?>" <?=$Hide?> class="center">
  500. <div style="display: inline-block;">
  501. <strong>Recommend to:</strong>
  502. <select id="friend" name="friend">
  503. <option value="0" selected="selected">Choose friend</option>
  504. </select>
  505. <input type="text" id="recommendation_note" placeholder="Add note..." />
  506. <button id="send_recommendation" disabled="disabled">Send</button>
  507. </div>
  508. <div class="new" id="recommendation_status"><br /></div>
  509. </div>
  510. <?php
  511. }
  512. public static function is_valid_url($URL)
  513. {
  514. return preg_match('|^http(s)?://[a-z0-9-]+(.[a-z0-9-]+)*(:[0-9]+)?(/.*)?$|i', $URL);
  515. }
  516. }