]> git.mxchange.org Git - friendica.git/blob - include/tags.php
Use short form array syntax everywhere
[friendica.git] / include / tags.php
1 <?php
2
3 /**
4  * @file include/tags.php
5  */
6 use Friendica\App;
7 use Friendica\Content\Feature;
8 use Friendica\Core\System;
9 use Friendica\Database\DBM;
10 use Friendica\Model\Contact;
11
12 function create_tags_from_item($itemid)
13 {
14         $profile_base = System::baseUrl();
15         $profile_data = parse_url($profile_base);
16         $profile_path = defaults($profile_data, 'path', '');
17         $profile_base_friendica = $profile_data['host'] . $profile_path . '/profile/';
18         $profile_base_diaspora = $profile_data['host'] . $profile_path . '/u/';
19
20         $messages = q("SELECT `guid`, `uid`, `id`, `edited`, `deleted`, `created`, `received`, `title`, `body`, `tag`, `parent` FROM `item` WHERE `id` = %d LIMIT 1", intval($itemid));
21
22         if (!$messages)
23                 return;
24
25         $message = $messages[0];
26
27         // Clean up all tags
28         q("DELETE FROM `term` WHERE `otype` = %d AND `oid` = %d AND `type` IN (%d, %d)",
29                 intval(TERM_OBJ_POST),
30                 intval($itemid),
31                 intval(TERM_HASHTAG),
32                 intval(TERM_MENTION));
33
34         if ($message['deleted']) {
35                 return;
36         }
37
38         $taglist = explode(',', $message['tag']);
39
40         $tags = '';
41         foreach ($taglist as $tag) {
42                 if ((substr(trim($tag), 0, 1) == '#') || (substr(trim($tag), 0, 1) == '@')) {
43                         $tags .= ' ' . trim($tag);
44                 } else {
45                         $tags .= ' #' . trim($tag);
46                 }
47         }
48
49         $data = ' ' . $message['title'] . ' ' . $message['body'] . ' ' . $tags . ' ';
50
51         // ignore anything in a code block
52         $data = preg_replace('/\[code\](.*?)\[\/code\]/sm', '', $data);
53
54         $tags = [];
55
56         $pattern = '/\W\#([^\[].*?)[\s\'".,:;\?!\[\]\/]/ism';
57         if (preg_match_all($pattern, $data, $matches)) {
58                 foreach ($matches[1] as $match) {
59                         $tags['#' . strtolower($match)] = '';
60                 }
61         }
62
63         $pattern = '/\W([\#@])\[url\=(.*?)\](.*?)\[\/url\]/ism';
64         if (preg_match_all($pattern, $data, $matches, PREG_SET_ORDER)) {
65                 foreach ($matches as $match) {
66                         $tags[$match[1] . strtolower(trim($match[3], ',.:;[]/\"?!'))] = $match[2];
67                 }
68         }
69
70         foreach ($tags as $tag => $link) {
71                 if (substr(trim($tag), 0, 1) == '#') {
72                         // try to ignore #039 or #1 or anything like that
73                         if (ctype_digit(substr(trim($tag), 1)))
74                                 continue;
75                         // try to ignore html hex escapes, e.g. #x2317
76                         if ((substr(trim($tag), 1, 1) == 'x' || substr(trim($tag), 1, 1) == 'X') && ctype_digit(substr(trim($tag), 2)))
77                                 continue;
78                         $type = TERM_HASHTAG;
79                         $term = substr($tag, 1);
80                 } elseif (substr(trim($tag), 0, 1) == '@') {
81                         $type = TERM_MENTION;
82                         $term = substr($tag, 1);
83                 } else { // This shouldn't happen
84                         $type = TERM_HASHTAG;
85                         $term = $tag;
86                 }
87
88                 if ($message['uid'] == 0) {
89                         $global = true;
90
91                         q("UPDATE `term` SET `global` = 1 WHERE `otype` = %d AND `guid` = '%s'",
92                                 intval(TERM_OBJ_POST), dbesc($message['guid']));
93                 } else {
94                         $isglobal = q("SELECT `global` FROM `term` WHERE `uid` = 0 AND `otype` = %d AND `guid` = '%s'",
95                                 intval(TERM_OBJ_POST), dbesc($message['guid']));
96
97                         $global = (count($isglobal) > 0);
98                 }
99
100                 q("INSERT INTO `term` (`uid`, `oid`, `otype`, `type`, `term`, `url`, `guid`, `created`, `received`, `global`)
101                                 VALUES (%d, %d, %d, %d, '%s', '%s', '%s', '%s', '%s', %d)",
102                         intval($message['uid']), intval($itemid), intval(TERM_OBJ_POST), intval($type), dbesc($term),
103                         dbesc($link), dbesc($message['guid']), dbesc($message['created']), dbesc($message['received']), intval($global));
104
105                 // Search for mentions
106                 if ((substr($tag, 0, 1) == '@') && (strpos($link, $profile_base_friendica) || strpos($link, $profile_base_diaspora))) {
107                         $users = q("SELECT `uid` FROM `contact` WHERE self AND (`url` = '%s' OR `nurl` = '%s')", $link, $link);
108                         foreach ($users AS $user) {
109                                 if ($user['uid'] == $message['uid']) {
110                                         q("UPDATE `item` SET `mention` = 1 WHERE `id` = %d", intval($itemid));
111
112                                         q("UPDATE `thread` SET `mention` = 1 WHERE `iid` = %d", intval($message['parent']));
113                                 }
114                         }
115                 }
116         }
117 }
118
119 function create_tags_from_itemuri($itemuri, $uid)
120 {
121         $messages = q("SELECT `id` FROM `item` WHERE uri ='%s' AND uid=%d", dbesc($itemuri), intval($uid));
122
123         if (count($messages)) {
124                 foreach ($messages as $message) {
125                         create_tags_from_item($message['id']);
126                 }
127         }
128 }
129
130 function update_items()
131 {
132         $messages = dba::p("SELECT `oid`,`item`.`guid`, `item`.`created`, `item`.`received` FROM `term` INNER JOIN `item` ON `item`.`id`=`term`.`oid` WHERE `term`.`otype` = 1 AND `term`.`guid` = ''");
133
134         logger('fetched messages: ' . dba::num_rows($messages));
135         while ($message = dba::fetch($messages)) {
136                 if ($message['uid'] == 0) {
137                         $global = true;
138
139                         q("UPDATE `term` SET `global` = 1 WHERE `otype` = %d AND `guid` = '%s'",
140                                 intval(TERM_OBJ_POST), dbesc($message['guid']));
141                 } else {
142                         $isglobal = q("SELECT `global` FROM `term` WHERE `uid` = 0 AND `otype` = %d AND `guid` = '%s'",
143                                 intval(TERM_OBJ_POST), dbesc($message['guid']));
144
145                         $global = (count($isglobal) > 0);
146                 }
147
148                 q("UPDATE `term` SET `guid` = '%s', `created` = '%s', `received` = '%s', `global` = %d WHERE `otype` = %d AND `oid` = %d",
149                         dbesc($message['guid']), dbesc($message['created']), dbesc($message['received']),
150                         intval($global), intval(TERM_OBJ_POST), intval($message['oid']));
151         }
152
153         dba::close($messages);
154
155         $messages = dba::p("SELECT `guid` FROM `item` WHERE `uid` = 0");
156
157         logger('fetched messages: ' . dba::num_rows($messages));
158         while ($message = dba::fetch(messages)) {
159                 q("UPDATE `item` SET `global` = 1 WHERE `guid` = '%s'", dbesc($message['guid']));
160         }
161
162         dba::close($messages);
163 }
164
165 /**
166  * @brief Get alphabetical sorted array of used tags/terms of an user including
167  * a weighting by frequency of use.
168  *
169  * @param int $uid      The user ID.
170  * @param int $count    Max number of displayed tags/terms.
171  * @param int $owner_id The contact id of the owner of the tagged items.
172  * @param string $flags Special item flags.
173  * @param int $type     The tag/term type.
174  *
175  * @return arr          Alphabetical sorted array of used tags of an user.
176  */
177 function tagadelic($uid, $count = 0, $owner_id = 0, $flags = '', $type = TERM_HASHTAG)
178 {
179         require_once 'include/security.php';
180
181         $item_condition = item_condition();
182         $sql_options = item_permissions_sql($uid);
183         $limit = $count ? sprintf('LIMIT %d', intval($count)) : '';
184
185         if ($flags) {
186                 if ($flags === 'wall') {
187                         $sql_options .= ' AND `item`.`wall` ';
188                 }
189         }
190
191         if ($owner_id) {
192                 $sql_options .= ' AND `item`.`owner-id` = ' . intval($owner_id) . ' ';
193         }
194
195         // Fetch tags
196         $r = dba::p("SELECT `term`, COUNT(`term`) AS `total` FROM `term`
197                 LEFT JOIN `item` ON `term`.`oid` = `item`.`id`
198                 WHERE `term`.`uid` = ? AND `term`.`type` = ?
199                 AND `term`.`otype` = ?
200                 AND $item_condition $sql_options
201                 GROUP BY `term` ORDER BY `total` DESC $limit",
202                 $uid,
203                 $type,
204                 TERM_OBJ_POST
205         );
206         if (!DBM::is_result($r)) {
207                 return [];
208         }
209
210         return tag_calc($r);
211 }
212
213 /**
214  * @brief Construct a tag/term cloud block for an user.
215  *
216  * @param int $uid      The user ID.
217  * @param int $count    Max number of displayed tags/terms.
218  * @param int $owner_id The contact ID of the owner of the tagged items.
219  * @param string $flags Special item flags.
220  * @param int $type     The tag/term type.
221  *
222  * @return string       HTML formatted output.
223  */
224 function wtagblock($uid, $count = 0, $owner_id = 0, $flags = '', $type = TERM_HASHTAG)
225 {
226         $o = '';
227         $r = tagadelic($uid, $count, $owner_id, $flags, $type);
228         if (count($r)) {
229                 $contact = dba::selectFirst('contact', ['url'], ['id' => $uid]);
230                 $url = System::removedBaseUrl($contact['url']);
231
232                 foreach ($r as $rr) {
233                         $tag['level'] = $rr[2];
234                         $tag['url'] = $url . '?tag=' . urlencode($rr[0]);
235                         $tag['name'] = $rr[0];
236
237                         $tags[] = $tag;
238                 }
239
240                 $tpl = get_markup_template('tagblock_widget.tpl');
241                 $o = replace_macros($tpl, [
242                         '$title' => t('Tags'),
243                         '$tags' => $tags
244                 ]);
245         }
246         return $o;
247 }
248
249 /**
250  * @brief Calculate weighting of tags according to the frequency of use.
251  *
252  * @param array $arr Array of tags/terms with tag/term name and total count of use.
253  * @return array     Alphabetical sorted array of used tags/terms of an user.
254  */
255 function tag_calc($arr)
256 {
257         $tags = [];
258         $min = 1e9;
259         $max = -1e9;
260         $x = 0;
261
262         if (!$arr) {
263                 return [];
264         }
265
266         foreach ($arr as $rr) {
267                 $tags[$x][0] = $rr['term'];
268                 $tags[$x][1] = log($rr['total']);
269                 $tags[$x][2] = 0;
270                 $min = min($min, $tags[$x][1]);
271                 $max = max($max, $tags[$x][1]);
272                 $x ++;
273         }
274
275         usort($tags, 'tags_sort');
276         $range = max(.01, $max - $min) * 1.0001;
277
278         for ($x = 0; $x < count($tags); $x ++) {
279                 $tags[$x][2] = 1 + floor(9 * ($tags[$x][1] - $min) / $range);
280         }
281
282         return $tags;
283 }
284
285 /**
286  * @brief Compare function to sort tags/terms alphabetically.
287  *
288  * @param type $a
289  * @param type $b
290  *
291  * @return int
292  */
293 function tags_sort($a, $b)
294 {
295         if (strtolower($a[0]) == strtolower($b[0])) {
296                 return 0;
297         }
298         return ((strtolower($a[0]) < strtolower($b[0])) ? -1 : 1);
299 }
300
301 /**
302  * @brief Insert a tag cloud widget for the present profile.
303  *
304  * @param int     $limit Max number of displayed tags.
305  * @return string HTML formattat output.
306  */
307 function tagcloud_wall_widget($limit = 50)
308 {
309         $a = get_app();
310
311         if (!$a->profile['profile_uid'] || !$a->profile['url']) {
312                 return '';
313         }
314
315         if (Feature::isEnabled($a->profile['profile_uid'], 'tagadelic')) {
316                 $owner_id = Contact::getIdForURL($a->profile['url']);
317
318                 if (!$owner_id) {
319                         return '';
320                 }
321                 return wtagblock($a->profile['profile_uid'], $limit, $owner_id, 'wall');
322         }
323
324         return '';
325 }