1: <?php
2: 3: 4: 5: 6: 7: 8: 9: 10:
11:
12: namespace Xoops\Core\Text\Sanitizer\Extensions;
13:
14: use Xoops\Core\Text\Sanitizer;
15: use Xoops\Core\Text\Sanitizer\FilterAbstract;
16:
17: 18: 19: 20: 21: 22: 23: 24: 25: 26:
27: class Embed extends FilterAbstract
28: {
29: 30: 31:
32: protected static $defaultConfiguration = [
33: 'enabled' => true,
34: 'cache_time' => 15552000,
35: ];
36:
37: 38: 39: 40: 41: 42: 43:
44: public function applyFilter($text)
45: {
46: if (!$this->config['enabled']) {
47: return $text;
48: }
49:
50: $pattern = '/^(https?:\/\/([\p{L}\p{N}]{1,}\.){1,}[\p{L}\p{N}]{2,}[\/\?\.\-_&=:#\p{L}\p{N}]{0,})$/m';
51:
52: $text = preg_replace_callback(
53: $pattern,
54: [$this, 'decorateUrl'],
55: $text
56: );
57:
58: return $text;
59: }
60:
61: 62: 63: 64: 65: 66: 67:
68: protected function decorateUrl($match) {
69: $url = $match[1];
70: $decorated = null;
71: $xoops = \Xoops::getInstance();
72: $md5 = md5($url);
73: $crc = hash("crc32b", $url);
74: $key = ['embed', substr($crc, -2), $md5];
75:
76: $decorated = $xoops->cache()->cacheRead(
77: $key,
78: function ($url) {
79: $return = null;
80: try {
81: $info = \Embed\Embed::create($url);
82: } catch (\Exception $e) {
83: $info = null;
84: }
85: if (is_object($info)) {
86: $return = $info->code;
87: if (empty($return)) {
88: $return = $this->mediaBox($info->url, $info->image, $info->title, $info->description);
89: }
90: }
91: if (empty($return)) {
92: $return = $url;
93: }
94: return $return;
95: },
96: $this->config['cache_time'],
97: $url
98: );
99: return $decorated;
100: }
101:
102: protected function mediaBox($link, $imageSrc, $title, $description)
103: {
104: $htmlTemplate = <<<'EOT'
105: <div class="media">
106: <a class="pull-left" href="%1$s" rel="external">
107: <img src="%2$s" class="media-object" style="max-height: 128px; max-width: 128px;">
108: </a>
109: <div class="media-body">
110: <h4 class="media-heading">%3$s</h4>
111: %4$s
112: </div>
113: </div>
114: EOT;
115:
116: if(empty($imageSrc)) {
117: $imageSrc = \Xoops::getInstance()->url('media/xoops/images/icons/link-ext.svg');
118: }
119: $box = sprintf($htmlTemplate, $link, $imageSrc, $title, $description);
120: return $box;
121: }
122:
123: }
124: