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