]> git.mxchange.org Git - friendica.git/blob - src/Model/Term.php
85b14174ae83fca4b0f197a033bf181d2c710c32
[friendica.git] / src / Model / Term.php
1 <?php
2 /**
3  * @file src/Model/Term
4  */
5 namespace Friendica\Model;
6
7 use Friendica\Core\System;
8 use Friendica\Database\DBM;
9 use Friendica\Model\Item;
10 use dba;
11
12 require_once 'boot.php';
13 require_once 'include/conversation.php';
14 require_once 'include/dba.php';
15
16 class Term
17 {
18         public static function tagTextFromItemId($itemid)
19         {
20                 $tag_text = '';
21                 $condition = ['otype' => TERM_OBJ_POST, 'oid' => $itemid, 'type' => [TERM_HASHTAG, TERM_MENTION]];
22                 $tags = dba::select('term', [], $condition);
23                 while ($tag = dba::fetch($tags)) {
24                         if ($tag_text != '') {
25                                 $tag_text .= ',';
26                         }
27
28                         if ($tag['type'] == 1) {
29                                 $tag_text .= '#';
30                         } else {
31                                 $tag_text .= '@';
32                         }
33                         $tag_text .= '[url=' . $tag['url'] . ']' . $tag['term'] . '[/url]';
34                 }
35                 return $tag_text;
36         }
37
38         public static function insertFromTagFieldByItemId($itemid, $tags)
39         {
40                 $profile_base = System::baseUrl();
41                 $profile_data = parse_url($profile_base);
42                 $profile_path = defaults($profile_data, 'path', '');
43                 $profile_base_friendica = $profile_data['host'] . $profile_path . '/profile/';
44                 $profile_base_diaspora = $profile_data['host'] . $profile_path . '/u/';
45
46                 $fields = ['guid', 'uid', 'id', 'edited', 'deleted', 'created', 'received', 'title', 'body', 'parent'];
47                 $message = Item::selectFirst($fields, ['id' => $itemid]);
48                 if (!DBM::is_result($message)) {
49                         return;
50                 }
51
52                 $message['tag'] = $tags;
53
54                 // Clean up all tags
55                 dba::delete('term', ['otype' => TERM_OBJ_POST, 'oid' => $itemid, 'type' => [TERM_HASHTAG, TERM_MENTION]]);
56
57                 if ($message['deleted']) {
58                         return;
59                 }
60
61                 $taglist = explode(',', $message['tag']);
62
63                 $tags_string = '';
64                 foreach ($taglist as $tag) {
65                         if ((substr(trim($tag), 0, 1) == '#') || (substr(trim($tag), 0, 1) == '@')) {
66                                 $tags_string .= ' ' . trim($tag);
67                         } else {
68                                 $tags_string .= ' #' . trim($tag);
69                         }
70                 }
71
72                 $data = ' ' . $message['title'] . ' ' . $message['body'] . ' ' . $tags_string . ' ';
73
74                 // ignore anything in a code block
75                 $data = preg_replace('/\[code\](.*?)\[\/code\]/sm', '', $data);
76
77                 $tags = [];
78
79                 $pattern = '/\W\#([^\[].*?)[\s\'".,:;\?!\[\]\/]/ism';
80                 if (preg_match_all($pattern, $data, $matches)) {
81                         foreach ($matches[1] as $match) {
82                                 $tags['#' . $match] = '';
83                         }
84                 }
85
86                 $pattern = '/\W([\#@])\[url\=(.*?)\](.*?)\[\/url\]/ism';
87                 if (preg_match_all($pattern, $data, $matches, PREG_SET_ORDER)) {
88                         foreach ($matches as $match) {
89                                 $tags[$match[1] . trim($match[3], ',.:;[]/\"?!')] = $match[2];
90                         }
91                 }
92
93                 foreach ($tags as $tag => $link) {
94                         if (substr(trim($tag), 0, 1) == '#') {
95                                 // try to ignore #039 or #1 or anything like that
96                                 if (ctype_digit(substr(trim($tag), 1))) {
97                                         continue;
98                                 }
99
100                                 // try to ignore html hex escapes, e.g. #x2317
101                                 if ((substr(trim($tag), 1, 1) == 'x' || substr(trim($tag), 1, 1) == 'X') && ctype_digit(substr(trim($tag), 2))) {
102                                         continue;
103                                 }
104
105                                 $type = TERM_HASHTAG;
106                                 $term = substr($tag, 1);
107                         } elseif (substr(trim($tag), 0, 1) == '@') {
108                                 $type = TERM_MENTION;
109                                 $term = substr($tag, 1);
110                         } else { // This shouldn't happen
111                                 $type = TERM_HASHTAG;
112                                 $term = $tag;
113                         }
114
115                         if ($message['uid'] == 0) {
116                                 $global = true;
117                                 dba::update('term', ['global' => true], ['otype' => TERM_OBJ_POST, 'guid' => $message['guid']]);
118                         } else {
119                                 $global = dba::exists('term', ['uid' => 0, 'otype' => TERM_OBJ_POST, 'guid' => $message['guid']]);
120                         }
121
122                         dba::insert('term', [
123                                 'uid'      => $message['uid'],
124                                 'oid'      => $itemid,
125                                 'otype'    => TERM_OBJ_POST,
126                                 'type'     => $type,
127                                 'term'     => $term,
128                                 'url'      => $link,
129                                 'guid'     => $message['guid'],
130                                 'created'  => $message['created'],
131                                 'received' => $message['received'],
132                                 'global'   => $global
133                         ]);
134
135                         // Search for mentions
136                         if ((substr($tag, 0, 1) == '@') && (strpos($link, $profile_base_friendica) || strpos($link, $profile_base_diaspora))) {
137                                 $users = q("SELECT `uid` FROM `contact` WHERE self AND (`url` = '%s' OR `nurl` = '%s')", $link, $link);
138                                 foreach ($users AS $user) {
139                                         if ($user['uid'] == $message['uid']) {
140                                                 /// @todo This function is called frim Item::update - so we mustn't call that function here
141                                                 dba::update('item', ['mention' => true], ['id' => $itemid]);
142                                                 dba::update('thread', ['mention' => true], ['iid' => $message['parent']]);
143                                         }
144                                 }
145                         }
146                 }
147         }
148
149         /**
150          * @param integer $itemid item id
151          * @return void
152          */
153         public static function insertFromFileFieldByItemId($itemid)
154         {
155                 $message = Item::selectFirst(['uid', 'deleted', 'file'], ['id' => $itemid]);
156                 if (!DBM::is_result($message)) {
157                         return;
158                 }
159
160                 // Clean up all tags
161                 dba::delete('term', ['otype' => TERM_OBJ_POST, 'oid' => $itemid, 'type' => [TERM_FILE, TERM_CATEGORY]]);
162
163                 if ($message["deleted"]) {
164                         return;
165                 }
166
167                 if (preg_match_all("/\[(.*?)\]/ism", $message["file"], $files)) {
168                         foreach ($files[1] as $file) {
169                                 dba::insert('term', [
170                                         'uid' => $message["uid"],
171                                         'oid' => $itemid,
172                                         'otype' => TERM_OBJ_POST,
173                                         'type' => TERM_FILE,
174                                         'term' => $file
175                                 ]);
176                         }
177                 }
178
179                 if (preg_match_all("/\<(.*?)\>/ism", $message["file"], $files)) {
180                         foreach ($files[1] as $file) {
181                                 dba::insert('term', [
182                                         'uid' => $message["uid"],
183                                         'oid' => $itemid,
184                                         'otype' => TERM_OBJ_POST,
185                                         'type' => TERM_CATEGORY,
186                                         'term' => $file
187                                 ]);
188                         }
189                 }
190         }
191
192         /**
193          * Sorts an item's tags into mentions, hashtags and other tags. Generate personalized URLs by user and modify the
194          * provided item's body with them.
195          *
196          * @param array $item
197          * @return array
198          */
199         public static function populateTagsFromItem(&$item)
200         {
201                 $return = [
202                         'tags' => [],
203                         'hashtags' => [],
204                         'mentions' => [],
205                 ];
206
207                 $searchpath = System::baseUrl() . "/search?tag=";
208
209                 $taglist = dba::select(
210                         'term',
211                         ['type', 'term', 'url'],
212                         ["`otype` = ? AND `oid` = ? AND `type` IN (?, ?)", TERM_OBJ_POST, $item['id'], TERM_HASHTAG, TERM_MENTION],
213                         ['order' => ['tid']]
214                 );
215
216                 while ($tag = dba::fetch($taglist)) {
217                         if ($tag["url"] == "") {
218                                 $tag["url"] = $searchpath . $tag["term"];
219                         }
220
221                         $orig_tag = $tag["url"];
222
223                         $tag["url"] = Contact::magicLinkById($item['author-id'], $tag['url']);
224
225                         if ($tag["type"] == TERM_HASHTAG) {
226                                 if ($orig_tag != $tag["url"]) {
227                                         $item['body'] = str_replace($orig_tag, $tag["url"], $item['body']);
228                                 }
229
230                                 $return['hashtags'][] = "#<a href=\"" . $tag["url"] . "\" target=\"_blank\">" . $tag["term"] . "</a>";
231                                 $prefix = "#";
232                         } elseif ($tag["type"] == TERM_MENTION) {
233                                 $return['mentions'][] = "@<a href=\"" . $tag["url"] . "\" target=\"_blank\">" . $tag["term"] . "</a>";
234                                 $prefix = "@";
235                         }
236
237                         $return['tags'][] = $prefix . "<a href=\"" . $tag["url"] . "\" target=\"_blank\">" . $tag["term"] . "</a>";
238                 }
239                 dba::close($taglist);
240
241                 return $return;
242         }
243 }