Нема описа

Emoji.php 2.0KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. <?php
  2. namespace MailPoet\WP;
  3. if (!defined('ABSPATH')) exit;
  4. use MailPoet\WP\Functions as WPFunctions;
  5. class Emoji {
  6. /** @var WPFunctions */
  7. private $wp;
  8. public function __construct(
  9. WPFunctions $wp = null
  10. ) {
  11. if ($wp === null) {
  12. $wp = new WPFunctions();
  13. }
  14. $this->wp = $wp;
  15. }
  16. public function encodeEmojisInBody($newsletterRenderedBody) {
  17. if (is_array($newsletterRenderedBody)) {
  18. return array_map([$this, 'encodeRenderedBodyForUTF8Column'], $newsletterRenderedBody);
  19. }
  20. return $this->encodeRenderedBodyForUTF8Column($newsletterRenderedBody);
  21. }
  22. public function decodeEmojisInBody($newsletterRenderedBody) {
  23. if (is_array($newsletterRenderedBody)) {
  24. return array_map([$this, 'decodeEntities'], $newsletterRenderedBody);
  25. }
  26. return $this->decodeEntities($newsletterRenderedBody);
  27. }
  28. public function sanitizeEmojisInFormBody(array $body): array {
  29. $bodyJson = json_encode($body, JSON_UNESCAPED_UNICODE);
  30. $fixedJson = $this->encodeForUTF8Column(MP_FORMS_TABLE, 'body', $bodyJson);
  31. return json_decode($fixedJson, true);
  32. }
  33. private function encodeRenderedBodyForUTF8Column($value) {
  34. return $this->encodeForUTF8Column(
  35. MP_SENDING_QUEUES_TABLE,
  36. 'newsletter_rendered_body',
  37. $value
  38. );
  39. }
  40. public function encodeForUTF8Column($table, $field, $value) {
  41. global $wpdb;
  42. $charset = $wpdb->get_col_charset($table, $field);
  43. if ($charset === 'utf8') {
  44. $value = $this->wp->wpEncodeEmoji($value);
  45. }
  46. return $value;
  47. }
  48. public function decodeEntities($content) {
  49. // Based on WPFunctions::get()->wpStaticizeEmoji()
  50. // Loosely match the Emoji Unicode range.
  51. $regex = '/(&#x[2-3][0-9a-f]{3};|&#x1f[1-6][0-9a-f]{2};)/';
  52. $matches = [];
  53. if (preg_match_all($regex, $content, $matches)) {
  54. if (!empty($matches[1])) {
  55. foreach ($matches[1] as $emoji) {
  56. $entity = html_entity_decode($emoji, ENT_COMPAT, 'UTF-8');
  57. $content = str_replace($emoji, $entity, $content);
  58. }
  59. }
  60. }
  61. return $content;
  62. }
  63. }