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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546
  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 = Crypto::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. }
  131. G::$DB->set_query_id($QueryID);
  132. return $ConvID;
  133. }
  134. /**
  135. * Create thread function, things should already be escaped when sent here.
  136. *
  137. * @param int $ForumID
  138. * @param int $AuthorID ID of the user creating the post.
  139. * @param string $Title
  140. * @param string $PostBody
  141. * @return -1 on error, -2 on user not existing, thread id on success.
  142. */
  143. public static function create_thread($ForumID, $AuthorID, $Title, $PostBody) {
  144. global $Time;
  145. if (!$ForumID || !$AuthorID || !is_number($AuthorID) || !$Title || !$PostBody) {
  146. return -1;
  147. }
  148. $QueryID = G::$DB->get_query_id();
  149. G::$DB->query("
  150. SELECT Username
  151. FROM users_main
  152. WHERE ID = $AuthorID");
  153. if (!G::$DB->has_results()) {
  154. G::$DB->set_query_id($QueryID);
  155. return -2;
  156. }
  157. list($AuthorName) = G::$DB->next_record();
  158. $ThreadInfo = [];
  159. $ThreadInfo['IsLocked'] = 0;
  160. $ThreadInfo['IsSticky'] = 0;
  161. G::$DB->query("
  162. INSERT INTO forums_topics
  163. (Title, AuthorID, ForumID, LastPostTime, LastPostAuthorID, CreatedTime)
  164. VALUES
  165. ('$Title', '$AuthorID', '$ForumID', NOW(), '$AuthorID', NOW())");
  166. $TopicID = G::$DB->inserted_id();
  167. $Posts = 1;
  168. G::$DB->query("
  169. INSERT INTO forums_posts
  170. (TopicID, AuthorID, AddedTime, Body)
  171. VALUES
  172. ('$TopicID', '$AuthorID', NOW(), '$PostBody')");
  173. $PostID = G::$DB->inserted_id();
  174. G::$DB->query("
  175. UPDATE forums
  176. SET
  177. NumPosts = NumPosts + 1,
  178. NumTopics = NumTopics + 1,
  179. LastPostID = '$PostID',
  180. LastPostAuthorID = '$AuthorID',
  181. LastPostTopicID = '$TopicID',
  182. LastPostTime = NOW()
  183. WHERE ID = '$ForumID'");
  184. G::$DB->query("
  185. UPDATE forums_topics
  186. SET
  187. NumPosts = NumPosts + 1,
  188. LastPostID = '$PostID',
  189. LastPostAuthorID = '$AuthorID',
  190. LastPostTime = NOW()
  191. WHERE ID = '$TopicID'");
  192. // Bump this topic to head of the cache
  193. list($Forum,,, $Stickies) = G::$Cache->get_value("forums_$ForumID");
  194. if (!empty($Forum)) {
  195. if (count($Forum) == TOPICS_PER_PAGE && $Stickies < TOPICS_PER_PAGE) {
  196. array_pop($Forum);
  197. }
  198. G::$DB->query("
  199. SELECT IsLocked, IsSticky, NumPosts
  200. FROM forums_topics
  201. WHERE ID ='$TopicID'");
  202. list($IsLocked, $IsSticky, $NumPosts) = G::$DB->next_record();
  203. $Part1 = array_slice($Forum, 0, $Stickies, true); //Stickys
  204. $Part2 = array(
  205. $TopicID => array(
  206. 'ID' => $TopicID,
  207. 'Title' => $Title,
  208. 'AuthorID' => $AuthorID,
  209. 'IsLocked' => $IsLocked,
  210. 'IsSticky' => $IsSticky,
  211. 'NumPosts' => $NumPosts,
  212. 'LastPostID' => $PostID,
  213. 'LastPostTime' => sqltime(),
  214. 'LastPostAuthorID' => $AuthorID,
  215. )
  216. ); //Bumped thread
  217. $Part3 = array_slice($Forum, $Stickies, TOPICS_PER_PAGE, true); //Rest of page
  218. if ($Stickies > 0) {
  219. $Part1 = array_slice($Forum, 0, $Stickies, true); //Stickies
  220. $Part3 = array_slice($Forum, $Stickies, TOPICS_PER_PAGE - $Stickies - 1, true); //Rest of page
  221. } else {
  222. $Part1 = [];
  223. $Part3 = $Forum;
  224. }
  225. if (is_null($Part1)) {
  226. $Part1 = [];
  227. }
  228. if (is_null($Part3)) {
  229. $Part3 = [];
  230. }
  231. $Forum = $Part1 + $Part2 + $Part3;
  232. G::$Cache->cache_value("forums_$ForumID", array($Forum, '', 0, $Stickies), 0);
  233. }
  234. //Update the forum root
  235. G::$Cache->begin_transaction('forums_list');
  236. $UpdateArray = array(
  237. 'NumPosts' => '+1',
  238. 'NumTopics' => '+1',
  239. 'LastPostID' => $PostID,
  240. 'LastPostAuthorID' => $AuthorID,
  241. 'LastPostTopicID' => $TopicID,
  242. 'LastPostTime' => sqltime(),
  243. 'Title' => $Title,
  244. 'IsLocked' => $ThreadInfo['IsLocked'],
  245. 'IsSticky' => $ThreadInfo['IsSticky']
  246. );
  247. $UpdateArray['NumTopics'] = '+1';
  248. G::$Cache->update_row($ForumID, $UpdateArray);
  249. G::$Cache->commit_transaction(0);
  250. $CatalogueID = floor((POSTS_PER_PAGE * ceil($Posts / POSTS_PER_PAGE) - POSTS_PER_PAGE) / THREAD_CATALOGUE);
  251. G::$Cache->begin_transaction('thread_'.$TopicID.'_catalogue_'.$CatalogueID);
  252. $Post = array(
  253. 'ID' => $PostID,
  254. 'AuthorID' => G::$LoggedUser['ID'],
  255. 'AddedTime' => sqltime(),
  256. 'Body' => $PostBody,
  257. 'EditedUserID' => 0,
  258. 'EditedTime' => NULL,
  259. 'Username' => ''
  260. );
  261. G::$Cache->insert('', $Post);
  262. G::$Cache->commit_transaction(0);
  263. G::$Cache->begin_transaction('thread_'.$TopicID.'_info');
  264. G::$Cache->update_row(false, array('Posts' => '+1', 'LastPostAuthorID' => $AuthorID));
  265. G::$Cache->commit_transaction(0);
  266. G::$DB->set_query_id($QueryID);
  267. return $TopicID;
  268. }
  269. /**
  270. * If the suffix of $Haystack is $Needle
  271. *
  272. * @param string $Haystack String to search in
  273. * @param string $Needle String to search for
  274. * @return boolean True if $Needle is a suffix of $Haystack
  275. */
  276. public static function ends_with($Haystack, $Needle) {
  277. return substr($Haystack, strlen($Needle) * -1) == $Needle;
  278. }
  279. /**
  280. * If the prefix of $Haystack is $Needle
  281. *
  282. * @param string $Haystack String to search in
  283. * @param string $Needle String to search for
  284. * @return boolean True if $Needle is a prefix of $Haystack
  285. */
  286. public static function starts_with($Haystack, $Needle) {
  287. return strpos($Haystack, $Needle) === 0;
  288. }
  289. /**
  290. * Variant of in_array() with trailing wildcard support
  291. *
  292. * @param string $Needle, array $Haystack
  293. * @return boolean true if (substring of) $Needle exists in $Haystack
  294. */
  295. public static function in_array_partial($Needle, $Haystack) {
  296. static $Searches = [];
  297. if (array_key_exists($Needle, $Searches)) {
  298. return $Searches[$Needle];
  299. }
  300. foreach ($Haystack as $String) {
  301. if (substr($String, -1) == '*') {
  302. if (!strncmp($Needle, $String, strlen($String) - 1)) {
  303. $Searches[$Needle] = true;
  304. return true;
  305. }
  306. } elseif (!strcmp($Needle, $String)) {
  307. $Searches[$Needle] = true;
  308. return true;
  309. }
  310. }
  311. $Searches[$Needle] = false;
  312. return false;
  313. }
  314. /**
  315. * Used to check if keys in $_POST and $_GET are all set, and throws an error if not.
  316. * This reduces 'if' statement redundancy for a lot of variables
  317. *
  318. * @param array $Request Either $_POST or $_GET, or whatever other array you want to check.
  319. * @param array $Keys The keys to ensure are set.
  320. * @param boolean $AllowEmpty If set to true, a key that is in the request but blank will not throw an error.
  321. * @param int $Error The error code to throw if one of the keys isn't in the array.
  322. */
  323. public static function assert_isset_request($Request, $Keys = null, $AllowEmpty = false, $Error = 0) {
  324. if (isset($Keys)) {
  325. foreach ($Keys as $K) {
  326. if (!isset($Request[$K]) || ($AllowEmpty == false && $Request[$K] == '')) {
  327. error($Error);
  328. break;
  329. }
  330. }
  331. } else {
  332. foreach ($Request as $R) {
  333. if (!isset($R) || ($AllowEmpty == false && $R == '')) {
  334. error($Error);
  335. break;
  336. }
  337. }
  338. }
  339. }
  340. /**
  341. * Given an array of tags, return an array of their IDs.
  342. *
  343. * @param array $TagNames
  344. * @return array IDs
  345. */
  346. public static function get_tags($TagNames) {
  347. $TagIDs = [];
  348. foreach ($TagNames as $Index => $TagName) {
  349. $Tag = G::$Cache->get_value("tag_id_$TagName");
  350. if (is_array($Tag)) {
  351. unset($TagNames[$Index]);
  352. $TagIDs[$Tag['ID']] = $Tag['Name'];
  353. }
  354. }
  355. if (count($TagNames) > 0) {
  356. $QueryID = G::$DB->get_query_id();
  357. G::$DB->query("
  358. SELECT ID, Name
  359. FROM tags
  360. WHERE Name IN ('".implode("', '", $TagNames)."')");
  361. $SQLTagIDs = G::$DB->to_array();
  362. G::$DB->set_query_id($QueryID);
  363. foreach ($SQLTagIDs as $Tag) {
  364. $TagIDs[$Tag['ID']] = $Tag['Name'];
  365. G::$Cache->cache_value('tag_id_'.$Tag['Name'], $Tag, 0);
  366. }
  367. }
  368. return($TagIDs);
  369. }
  370. /**
  371. * Gets the alias of the tag; if there is no alias, silently returns the original tag.
  372. *
  373. * @param string $BadTag the tag we want to alias
  374. * @return string The aliased tag.
  375. */
  376. public static function get_alias_tag($BadTag) {
  377. $QueryID = G::$DB->get_query_id();
  378. G::$DB->query("
  379. SELECT AliasTag
  380. FROM tag_aliases
  381. WHERE BadTag = '$BadTag'
  382. LIMIT 1");
  383. if (G::$DB->has_results()) {
  384. list($AliasTag) = G::$DB->next_record();
  385. } else {
  386. $AliasTag = $BadTag;
  387. }
  388. G::$DB->set_query_id($QueryID);
  389. return $AliasTag;
  390. }
  391. /*
  392. * Write a message to the system log.
  393. *
  394. * @param string $Message the message to write.
  395. */
  396. public static function write_log($Message) {
  397. global $Time;
  398. $QueryID = G::$DB->get_query_id();
  399. G::$DB->query("
  400. INSERT INTO log (Message, Time)
  401. VALUES (?, NOW())", $Message);
  402. G::$DB->set_query_id($QueryID);
  403. }
  404. /**
  405. * Get a tag ready for database input and display.
  406. *
  407. * @param string $Str
  408. * @return sanitized version of $Str
  409. */
  410. public static function sanitize_tag($Str) {
  411. $Str = strtolower($Str);
  412. $Str = preg_replace('/[^a-z0-9:.]/', '', $Str);
  413. $Str = preg_replace('/(^[.,]*)|([.,]*$)/', '', $Str);
  414. $Str = htmlspecialchars($Str);
  415. $Str = db_string(trim($Str));
  416. return $Str;
  417. }
  418. /**
  419. * HTML escape an entire array for output.
  420. * @param array $Array, what we want to escape
  421. * @param boolean/array $Escape
  422. * if true, all keys escaped
  423. * if false, no escaping.
  424. * If array, it's a list of array keys not to escape.
  425. * @return mutated version of $Array with values escaped.
  426. */
  427. public static function display_array($Array, $Escape = []) {
  428. foreach ($Array as $Key => $Val) {
  429. if ((!is_array($Escape) && $Escape == true) || !in_array($Key, $Escape)) {
  430. $Array[$Key] = display_str($Val);
  431. }
  432. }
  433. return $Array;
  434. }
  435. /**
  436. * Searches for a key/value pair in an array.
  437. *
  438. * @return array of results
  439. */
  440. public static function search_array($Array, $Key, $Value) {
  441. $Results = [];
  442. if (is_array($Array))
  443. {
  444. if (isset($Array[$Key]) && $Array[$Key] == $Value) {
  445. $Results[] = $Array;
  446. }
  447. foreach ($Array as $subarray) {
  448. $Results = array_merge($Results, self::search_array($subarray, $Key, $Value));
  449. }
  450. }
  451. return $Results;
  452. }
  453. /**
  454. * Search for $Needle in the string $Haystack which is a list of values separated by $Separator.
  455. * @param string $Haystack
  456. * @param string $Needle
  457. * @param string $Separator
  458. * @param boolean $Strict
  459. * @return boolean
  460. */
  461. public static function search_joined_string($Haystack, $Needle, $Separator = '|', $Strict = true) {
  462. return (array_search($Needle, explode($Separator, $Haystack), $Strict) !== false);
  463. }
  464. /**
  465. * Check for a ":" in the beginning of a torrent meta data string
  466. * to see if it's stored in the old base64-encoded format
  467. *
  468. * @param string $Torrent the torrent data
  469. * @return true if the torrent is stored in binary format
  470. */
  471. public static function is_new_torrent(&$Data) {
  472. return strpos(substr($Data, 0, 10), ':') !== false;
  473. }
  474. public static function display_recommend($ID, $Type, $Hide = true) {
  475. if ($Hide) {
  476. $Hide = ' style="display: none;"';
  477. }
  478. ?>
  479. <div id="recommendation_div" data-id="<?=$ID?>" data-type="<?=$Type?>"<?=$Hide?> class="center">
  480. <div style="display: inline-block;">
  481. <strong>Recommend to:</strong>
  482. <select id="friend" name="friend">
  483. <option value="0" selected="selected">Choose friend</option>
  484. </select>
  485. <input type="text" id="recommendation_note" placeholder="Add note..." />
  486. <button id="send_recommendation" disabled="disabled">Send</button>
  487. </div>
  488. <div class="new" id="recommendation_status"><br /></div>
  489. </div>
  490. <?
  491. }
  492. public static function is_valid_url($URL) {
  493. return preg_match('|^http(s)?://[a-z0-9-]+(.[a-z0-9-]+)*(:[0-9]+)?(/.*)?$|i', $URL);
  494. }
  495. }
  496. ?>