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

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