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