Oppaitime'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

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