]> git.mxchange.org Git - friendica.git/blob - include/items.php
Remove library/jgrowl
[friendica.git] / include / items.php
1 <?php
2 /**
3  * @file include/items.php
4  */
5 use Friendica\App;
6 use Friendica\Content\Feature;
7 use Friendica\Core\Addon;
8 use Friendica\Core\Config;
9 use Friendica\Core\L10n;
10 use Friendica\Core\PConfig;
11 use Friendica\Core\Worker;
12 use Friendica\Core\System;
13 use Friendica\Database\DBM;
14 use Friendica\Model\Contact;
15 use Friendica\Model\GContact;
16 use Friendica\Model\Group;
17 use Friendica\Model\Term;
18 use Friendica\Model\User;
19 use Friendica\Model\Item;
20 use Friendica\Model\Conversation;
21 use Friendica\Object\Image;
22 use Friendica\Protocol\DFRN;
23 use Friendica\Protocol\OStatus;
24 use Friendica\Protocol\Feed;
25 use Friendica\Util\ParseUrl;
26
27 require_once 'include/bbcode.php';
28 require_once 'include/tags.php';
29 require_once 'include/text.php';
30 require_once 'include/threads.php';
31 require_once 'mod/share.php';
32 require_once 'include/enotify.php';
33
34 /* limit_body_size()
35  *
36  *
37  *
38  */
39
40 /**
41  * The purpose of this function is to apply system message length limits to
42  * imported messages without including any embedded photos in the length
43  *
44  * @brief Truncates imported message body string length to max_import_size
45  * @param string $body
46  * @return string
47  */
48 /// @TODO move to src/Model/Item.php
49 function limit_body_size($body)
50 {
51         $maxlen = get_max_import_size();
52
53         // If the length of the body, including the embedded images, is smaller
54         // than the maximum, then don't waste time looking for the images
55         if ($maxlen && (strlen($body) > $maxlen)) {
56
57                 logger('limit_body_size: the total body length exceeds the limit', LOGGER_DEBUG);
58
59                 $orig_body = $body;
60                 $new_body = '';
61                 $textlen = 0;
62
63                 $img_start = strpos($orig_body, '[img');
64                 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
65                 $img_end = ($img_start !== false ? strpos(substr($orig_body, $img_start), '[/img]') : false);
66                 while (($img_st_close !== false) && ($img_end !== false)) {
67
68                         $img_st_close++; // make it point to AFTER the closing bracket
69                         $img_end += $img_start;
70                         $img_end += strlen('[/img]');
71
72                         if (! strcmp(substr($orig_body, $img_start + $img_st_close, 5), 'data:')) {
73                                 // This is an embedded image
74
75                                 if (($textlen + $img_start) > $maxlen ) {
76                                         if ($textlen < $maxlen) {
77                                                 logger('limit_body_size: the limit happens before an embedded image', LOGGER_DEBUG);
78                                                 $new_body = $new_body . substr($orig_body, 0, $maxlen - $textlen);
79                                                 $textlen = $maxlen;
80                                         }
81                                 } else {
82                                         $new_body = $new_body . substr($orig_body, 0, $img_start);
83                                         $textlen += $img_start;
84                                 }
85
86                                 $new_body = $new_body . substr($orig_body, $img_start, $img_end - $img_start);
87                         } else {
88
89                                 if (($textlen + $img_end) > $maxlen ) {
90                                         if ($textlen < $maxlen) {
91                                                 logger('limit_body_size: the limit happens before the end of a non-embedded image', LOGGER_DEBUG);
92                                                 $new_body = $new_body . substr($orig_body, 0, $maxlen - $textlen);
93                                                 $textlen = $maxlen;
94                                         }
95                                 } else {
96                                         $new_body = $new_body . substr($orig_body, 0, $img_end);
97                                         $textlen += $img_end;
98                                 }
99                         }
100                         $orig_body = substr($orig_body, $img_end);
101
102                         if ($orig_body === false) {
103                                 // in case the body ends on a closing image tag
104                                 $orig_body = '';
105                         }
106
107                         $img_start = strpos($orig_body, '[img');
108                         $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
109                         $img_end = ($img_start !== false ? strpos(substr($orig_body, $img_start), '[/img]') : false);
110                 }
111
112                 if (($textlen + strlen($orig_body)) > $maxlen) {
113                         if ($textlen < $maxlen) {
114                                 logger('limit_body_size: the limit happens after the end of the last image', LOGGER_DEBUG);
115                                 $new_body = $new_body . substr($orig_body, 0, $maxlen - $textlen);
116                         }
117                 } else {
118                         logger('limit_body_size: the text size with embedded images extracted did not violate the limit', LOGGER_DEBUG);
119                         $new_body = $new_body . $orig_body;
120                 }
121
122                 return $new_body;
123         } else {
124                 return $body;
125         }
126 }
127
128 /// @TODO move to ???
129 function add_page_info_data($data) {
130         Addon::callHooks('page_info_data', $data);
131
132         // It maybe is a rich content, but if it does have everything that a link has,
133         // then treat it that way
134         if (($data["type"] == "rich") && is_string($data["title"]) &&
135                 is_string($data["text"]) && (sizeof($data["images"]) > 0)) {
136                 $data["type"] = "link";
137         }
138
139         if ((($data["type"] != "link") && ($data["type"] != "video") && ($data["type"] != "photo")) || ($data["title"] == $data["url"])) {
140                 return "";
141         }
142
143         if ($no_photos && ($data["type"] == "photo")) {
144                 return "";
145         }
146
147         // Escape some bad characters
148         $data["url"] = str_replace(["[", "]"], ["&#91;", "&#93;"], htmlentities($data["url"], ENT_QUOTES, 'UTF-8', false));
149         $data["title"] = str_replace(["[", "]"], ["&#91;", "&#93;"], htmlentities($data["title"], ENT_QUOTES, 'UTF-8', false));
150
151         $text = "[attachment type='".$data["type"]."'";
152
153         if ($data["text"] == "") {
154                 $data["text"] = $data["title"];
155         }
156
157         if ($data["text"] == "") {
158                 $data["text"] = $data["url"];
159         }
160
161         if ($data["url"] != "") {
162                 $text .= " url='".$data["url"]."'";
163         }
164
165         if ($data["title"] != "") {
166                 $text .= " title='".$data["title"]."'";
167         }
168
169         if (sizeof($data["images"]) > 0) {
170                 $preview = str_replace(["[", "]"], ["&#91;", "&#93;"], htmlentities($data["images"][0]["src"], ENT_QUOTES, 'UTF-8', false));
171                 // if the preview picture is larger than 500 pixels then show it in a larger mode
172                 // But only, if the picture isn't higher than large (To prevent huge posts)
173                 if (!Config::get('system', 'always_show_preview') && ($data["images"][0]["width"] >= 500)
174                         && ($data["images"][0]["width"] >= $data["images"][0]["height"])) {
175                         $text .= " image='".$preview."'";
176                 } else {
177                         $text .= " preview='".$preview."'";
178                 }
179         }
180
181         $text .= "]".$data["text"]."[/attachment]";
182
183         $hashtags = "";
184         if (isset($data["keywords"]) && count($data["keywords"])) {
185                 $hashtags = "\n";
186                 foreach ($data["keywords"] AS $keyword) {
187                         /// @TODO make a positive list of allowed characters
188                         $hashtag = str_replace([" ", "+", "/", ".", "#", "'", "’", "`", "(", ")", "„", "“"],
189                                                 ["", "", "", "", "", "", "", "", "", "", "", ""], $keyword);
190                         $hashtags .= "#[url=" . System::baseUrl() . "/search?tag=" . rawurlencode($hashtag) . "]" . $hashtag . "[/url] ";
191                 }
192         }
193
194         return "\n".$text.$hashtags;
195 }
196
197 /// @TODO move to ???
198 function query_page_info($url, $no_photos = false, $photo = "", $keywords = false, $keyword_blacklist = "") {
199
200         $data = ParseUrl::getSiteinfoCached($url, true);
201
202         if ($photo != "") {
203                 $data["images"][0]["src"] = $photo;
204         }
205
206         logger('fetch page info for ' . $url . ' ' . print_r($data, true), LOGGER_DEBUG);
207
208         if (!$keywords && isset($data["keywords"])) {
209                 unset($data["keywords"]);
210         }
211
212         if (($keyword_blacklist != "") && isset($data["keywords"])) {
213                 $list = explode(", ", $keyword_blacklist);
214                 foreach ($list AS $keyword) {
215                         $keyword = trim($keyword);
216                         $index = array_search($keyword, $data["keywords"]);
217                         if ($index !== false) {
218                                 unset($data["keywords"][$index]);
219                         }
220                 }
221         }
222
223         return $data;
224 }
225
226 /// @TODO move to ???
227 function add_page_keywords($url, $no_photos = false, $photo = "", $keywords = false, $keyword_blacklist = "") {
228         $data = query_page_info($url, $no_photos, $photo, $keywords, $keyword_blacklist);
229
230         $tags = "";
231         if (isset($data["keywords"]) && count($data["keywords"])) {
232                 foreach ($data["keywords"] AS $keyword) {
233                         $hashtag = str_replace([" ", "+", "/", ".", "#", "'"],
234                                 ["", "", "", "", "", ""], $keyword);
235
236                         if ($tags != "") {
237                                 $tags .= ", ";
238                         }
239
240                         $tags .= "#[url=" . System::baseUrl() . "/search?tag=" . rawurlencode($hashtag) . "]" . $hashtag . "[/url]";
241                 }
242         }
243
244         return $tags;
245 }
246
247 /// @TODO move to ???
248 function add_page_info($url, $no_photos = false, $photo = "", $keywords = false, $keyword_blacklist = "") {
249         $data = query_page_info($url, $no_photos, $photo, $keywords, $keyword_blacklist);
250
251         $text = add_page_info_data($data);
252
253         return $text;
254 }
255
256 /// @TODO move to ???
257 function add_page_info_to_body($body, $texturl = false, $no_photos = false) {
258
259         logger('add_page_info_to_body: fetch page info for body ' . $body, LOGGER_DEBUG);
260
261         $URLSearchString = "^\[\]";
262
263         // Fix for Mastodon where the mentions are in a different format
264         $body = preg_replace("/\[url\=([$URLSearchString]*)\]([#!@])(.*?)\[\/url\]/ism",
265                 '$2[url=$1]$3[/url]', $body);
266
267         // Adding these spaces is a quick hack due to my problems with regular expressions :)
268         preg_match("/[^!#@]\[url\]([$URLSearchString]*)\[\/url\]/ism", " " . $body, $matches);
269
270         if (!$matches) {
271                 preg_match("/[^!#@]\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", " " . $body, $matches);
272         }
273
274         // Convert urls without bbcode elements
275         if (!$matches && $texturl) {
276                 preg_match("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", " ".$body, $matches);
277
278                 // Yeah, a hack. I really hate regular expressions :)
279                 if ($matches) {
280                         $matches[1] = $matches[2];
281                 }
282         }
283
284         if ($matches) {
285                 $footer = add_page_info($matches[1], $no_photos);
286         }
287
288         // Remove the link from the body if the link is attached at the end of the post
289         if (isset($footer) && (trim($footer) != "") && (strpos($footer, $matches[1]))) {
290                 $removedlink = trim(str_replace($matches[1], "", $body));
291                 if (($removedlink == "") || strstr($body, $removedlink)) {
292                         $body = $removedlink;
293                 }
294
295                 $url = str_replace(['/', '.'], ['\/', '\.'], $matches[1]);
296                 $removedlink = preg_replace("/\[url\=" . $url . "\](.*?)\[\/url\]/ism", '', $body);
297                 if (($removedlink == "") || strstr($body, $removedlink)) {
298                         $body = $removedlink;
299                 }
300         }
301
302         // Add the page information to the bottom
303         if (isset($footer) && (trim($footer) != "")) {
304                 $body .= $footer;
305         }
306
307         return $body;
308 }
309
310 /// @TODO add type-hint array
311 /// @TODO move to src/Model/Item.php
312 function item_store($arr, $force_parent = false, $notify = false, $dontcache = false)
313 {
314         $a = get_app();
315
316         // If it is a posting where users should get notifications, then define it as wall posting
317         if ($notify) {
318                 $arr['wall'] = 1;
319                 $arr['type'] = 'wall';
320                 $arr['origin'] = 1;
321                 $arr['network'] = NETWORK_DFRN;
322                 $arr['protocol'] = PROTOCOL_DFRN;
323
324                 // We have to avoid duplicates. So we create the GUID in form of a hash of the plink or uri.
325                 // In difference to the call to "Item::guidFromUri" several lines below we add the hash of our own host.
326                 // This is done because our host is the original creator of the post.
327                 if (!isset($arr['guid'])) {
328                         if (isset($arr['plink'])) {
329                                 $arr['guid'] = Item::guidFromUri($arr['plink'], $a->get_hostname());
330                         } elseif (isset($arr['uri'])) {
331                                 $arr['guid'] = Item::guidFromUri($arr['uri'], $a->get_hostname());
332                         }
333                 }
334         } else {
335                 $arr['network'] = trim(defaults($arr, 'network', NETWORK_PHANTOM));
336         }
337
338         if ($notify) {
339                 $guid_prefix = "";
340         } elseif ((trim($arr['guid']) == "") && (trim($arr['plink']) != "")) {
341                 $arr['guid'] = Item::guidFromUri($arr['plink']);
342         } elseif ((trim($arr['guid']) == "") && (trim($arr['uri']) != "")) {
343                 $arr['guid'] = Item::guidFromUri($arr['uri']);
344         } else {
345                 $parsed = parse_url($arr["author-link"]);
346                 $guid_prefix = hash("crc32", $parsed["host"]);
347         }
348
349         $arr['guid']          = ((x($arr, 'guid'))          ? notags(trim($arr['guid']))          : get_guid(32, $guid_prefix));
350         $arr['uri']           = ((x($arr, 'uri'))           ? notags(trim($arr['uri']))           : item_new_uri($a->get_hostname(), $uid, $arr['guid']));
351
352         // Store conversation data
353         $arr = Conversation::insert($arr);
354
355         /*
356          * If a Diaspora signature structure was passed in, pull it out of the
357          * item array and set it aside for later storage.
358          */
359
360         $dsprsig = null;
361         if (x($arr, 'dsprsig')) {
362                 $encoded_signature = $arr['dsprsig'];
363                 $dsprsig = json_decode(base64_decode($arr['dsprsig']));
364                 unset($arr['dsprsig']);
365         }
366
367         // Converting the plink
368         /// @TODO Check if this is really still needed
369         if ($arr['network'] == NETWORK_OSTATUS) {
370                 if (isset($arr['plink'])) {
371                         $arr['plink'] = OStatus::convertHref($arr['plink']);
372                 } elseif (isset($arr['uri'])) {
373                         $arr['plink'] = OStatus::convertHref($arr['uri']);
374                 }
375         }
376
377         if (x($arr, 'gravity')) {
378                 $arr['gravity'] = intval($arr['gravity']);
379         } elseif ($arr['parent-uri'] === $arr['uri']) {
380                 $arr['gravity'] = 0;
381         } elseif (activity_match($arr['verb'],ACTIVITY_POST)) {
382                 $arr['gravity'] = 6;
383         } else {
384                 $arr['gravity'] = 6;   // extensible catchall
385         }
386
387         if (! x($arr, 'type')) {
388                 $arr['type']      = 'remote';
389         }
390
391         $uid = intval($arr['uid']);
392
393         // check for create date and expire time
394         $expire_interval = Config::get('system', 'dbclean-expire-days', 0);
395
396         $user = dba::selectFirst('user', ['expire'], ['uid' => $uid]);
397         if (DBM::is_result($user) && ($user['expire'] > 0) && (($user['expire'] < $expire_interval) || ($expire_interval == 0))) {
398                 $expire_interval = $user['expire'];
399         }
400
401         if (($expire_interval > 0) && !empty($arr['created'])) {
402                 $expire_date = time() - ($expire_interval * 86400);
403                 $created_date = strtotime($arr['created']);
404                 if ($created_date < $expire_date) {
405                         logger('item-store: item created ('.date('c', $created_date).') before expiration time ('.date('c', $expire_date).'). ignored. ' . print_r($arr,true), LOGGER_DEBUG);
406                         return 0;
407                 }
408         }
409
410         /*
411          * Do we already have this item?
412          * We have to check several networks since Friendica posts could be repeated
413          * via OStatus (maybe Diasporsa as well)
414          */
415         if (in_array($arr['network'], [NETWORK_DIASPORA, NETWORK_DFRN, NETWORK_OSTATUS, ""])) {
416                 $r = q("SELECT `id`, `network` FROM `item` WHERE `uri` = '%s' AND `uid` = %d AND `network` IN ('%s', '%s', '%s')  LIMIT 1",
417                                 dbesc(trim($arr['uri'])),
418                                 intval($uid),
419                                 dbesc(NETWORK_DIASPORA),
420                                 dbesc(NETWORK_DFRN),
421                                 dbesc(NETWORK_OSTATUS)
422                         );
423                 if (DBM::is_result($r)) {
424                         // We only log the entries with a different user id than 0. Otherwise we would have too many false positives
425                         if ($uid != 0) {
426                                 logger("Item with uri ".$arr['uri']." already existed for user ".$uid." with id ".$r[0]["id"]." target network ".$r[0]["network"]." - new network: ".$arr['network']);
427                         }
428
429                         return $r[0]["id"];
430                 }
431         }
432
433         /// @TODO old-lost code?
434         // Shouldn't happen but we want to make absolutely sure it doesn't leak from an addon.
435         // Deactivated, since the bbcode parser can handle with it - and it destroys posts with some smileys that contain "<"
436         //if ((strpos($arr['body'],'<') !== false) || (strpos($arr['body'],'>') !== false))
437         //      $arr['body'] = strip_tags($arr['body']);
438
439         Item::addLanguageInPostopts($arr);
440
441         $arr['wall']          = ((x($arr, 'wall'))          ? intval($arr['wall'])                : 0);
442         $arr['extid']         = ((x($arr, 'extid'))         ? notags(trim($arr['extid']))         : '');
443         $arr['author-name']   = ((x($arr, 'author-name'))   ? trim($arr['author-name'])   : '');
444         $arr['author-link']   = ((x($arr, 'author-link'))   ? notags(trim($arr['author-link']))   : '');
445         $arr['author-avatar'] = ((x($arr, 'author-avatar')) ? notags(trim($arr['author-avatar'])) : '');
446         $arr['owner-name']    = ((x($arr, 'owner-name'))    ? trim($arr['owner-name'])    : '');
447         $arr['owner-link']    = ((x($arr, 'owner-link'))    ? notags(trim($arr['owner-link']))    : '');
448         $arr['owner-avatar']  = ((x($arr, 'owner-avatar'))  ? notags(trim($arr['owner-avatar']))  : '');
449         $arr['received']      = ((x($arr, 'received') !== false) ? datetime_convert('UTC','UTC', $arr['received']) : datetime_convert());
450         $arr['created']       = ((x($arr, 'created') !== false) ? datetime_convert('UTC','UTC', $arr['created']) : $arr['received']);
451         $arr['edited']        = ((x($arr, 'edited') !== false) ? datetime_convert('UTC','UTC', $arr['edited']) : $arr['created']);
452         $arr['changed']       = ((x($arr, 'changed') !== false) ? datetime_convert('UTC','UTC', $arr['changed']) : $arr['created']);
453         $arr['commented']     = ((x($arr, 'commented') !== false) ? datetime_convert('UTC','UTC', $arr['commented']) : $arr['created']);
454         $arr['title']         = ((x($arr, 'title'))         ? trim($arr['title'])         : '');
455         $arr['location']      = ((x($arr, 'location'))      ? trim($arr['location'])      : '');
456         $arr['coord']         = ((x($arr, 'coord'))         ? notags(trim($arr['coord']))         : '');
457         $arr['visible']       = ((x($arr, 'visible') !== false) ? intval($arr['visible'])         : 1 );
458         $arr['deleted']       = 0;
459         $arr['parent-uri']    = ((x($arr, 'parent-uri'))    ? notags(trim($arr['parent-uri']))    : $arr['uri']);
460         $arr['verb']          = ((x($arr, 'verb'))          ? notags(trim($arr['verb']))          : '');
461         $arr['object-type']   = ((x($arr, 'object-type'))   ? notags(trim($arr['object-type']))   : '');
462         $arr['object']        = ((x($arr, 'object'))        ? trim($arr['object'])                : '');
463         $arr['target-type']   = ((x($arr, 'target-type'))   ? notags(trim($arr['target-type']))   : '');
464         $arr['target']        = ((x($arr, 'target'))        ? trim($arr['target'])                : '');
465         $arr['plink']         = ((x($arr, 'plink'))         ? notags(trim($arr['plink']))         : '');
466         $arr['allow_cid']     = ((x($arr, 'allow_cid'))     ? trim($arr['allow_cid'])             : '');
467         $arr['allow_gid']     = ((x($arr, 'allow_gid'))     ? trim($arr['allow_gid'])             : '');
468         $arr['deny_cid']      = ((x($arr, 'deny_cid'))      ? trim($arr['deny_cid'])              : '');
469         $arr['deny_gid']      = ((x($arr, 'deny_gid'))      ? trim($arr['deny_gid'])              : '');
470         $arr['private']       = ((x($arr, 'private'))       ? intval($arr['private'])             : 0 );
471         $arr['bookmark']      = ((x($arr, 'bookmark'))      ? intval($arr['bookmark'])            : 0 );
472         $arr['body']          = ((x($arr, 'body'))          ? trim($arr['body'])                  : '');
473         $arr['tag']           = ((x($arr, 'tag'))           ? notags(trim($arr['tag']))           : '');
474         $arr['attach']        = ((x($arr, 'attach'))        ? notags(trim($arr['attach']))        : '');
475         $arr['app']           = ((x($arr, 'app'))           ? notags(trim($arr['app']))           : '');
476         $arr['origin']        = ((x($arr, 'origin'))        ? intval($arr['origin'])              : 0 );
477         $arr['postopts']      = ((x($arr, 'postopts'))      ? trim($arr['postopts'])              : '');
478         $arr['resource-id']   = ((x($arr, 'resource-id'))   ? trim($arr['resource-id'])           : '');
479         $arr['event-id']      = ((x($arr, 'event-id'))      ? intval($arr['event-id'])            : 0 );
480         $arr['inform']        = ((x($arr, 'inform'))        ? trim($arr['inform'])                : '');
481         $arr['file']          = ((x($arr, 'file'))          ? trim($arr['file'])                  : '');
482
483         // When there is no content then we don't post it
484         if ($arr['body'].$arr['title'] == '') {
485                 return 0;
486         }
487
488         // Items cannot be stored before they happen ...
489         if ($arr['created'] > datetime_convert()) {
490                 $arr['created'] = datetime_convert();
491         }
492
493         // We haven't invented time travel by now.
494         if ($arr['edited'] > datetime_convert()) {
495                 $arr['edited'] = datetime_convert();
496         }
497
498         if (($arr['author-link'] == "") && ($arr['owner-link'] == "")) {
499                 logger("Both author-link and owner-link are empty. Called by: " . System::callstack(), LOGGER_DEBUG);
500         }
501
502         if ($arr['plink'] == "") {
503                 $arr['plink'] = System::baseUrl() . '/display/' . urlencode($arr['guid']);
504         }
505
506         if ($arr['network'] == NETWORK_PHANTOM) {
507                 $r = q("SELECT `network` FROM `contact` WHERE `network` IN ('%s', '%s', '%s') AND `nurl` = '%s' AND `uid` = %d LIMIT 1",
508                         dbesc(NETWORK_DFRN), dbesc(NETWORK_DIASPORA), dbesc(NETWORK_OSTATUS),
509                         dbesc(normalise_link($arr['author-link'])),
510                         intval($arr['uid'])
511                 );
512
513                 if (!DBM::is_result($r)) {
514                         $r = q("SELECT `network` FROM `gcontact` WHERE `network` IN ('%s', '%s', '%s') AND `nurl` = '%s' LIMIT 1",
515                                 dbesc(NETWORK_DFRN), dbesc(NETWORK_DIASPORA), dbesc(NETWORK_OSTATUS),
516                                 dbesc(normalise_link($arr['author-link']))
517                         );
518                 }
519
520                 if (!DBM::is_result($r)) {
521                         $r = q("SELECT `network` FROM `contact` WHERE `id` = %d AND `uid` = %d LIMIT 1",
522                                 intval($arr['contact-id']),
523                                 intval($arr['uid'])
524                         );
525                 }
526
527                 if (DBM::is_result($r)) {
528                         $arr['network'] = $r[0]["network"];
529                 }
530
531                 // Fallback to friendica (why is it empty in some cases?)
532                 if ($arr['network'] == "") {
533                         $arr['network'] = NETWORK_DFRN;
534                 }
535
536                 logger("item_store: Set network to " . $arr["network"] . " for " . $arr["uri"], LOGGER_DEBUG);
537         }
538
539         // The contact-id should be set before "item_store" was called - but there seems to be some issues
540         if ($arr["contact-id"] == 0) {
541                 /*
542                  * First we are looking for a suitable contact that matches with the author of the post
543                  * This is done only for comments (See below explanation at "gcontact-id")
544                  */
545                 if ($arr['parent-uri'] != $arr['uri']) {
546                         $arr["contact-id"] = Contact::getIdForURL($arr['author-link'], $uid);
547                 }
548
549                 // If not present then maybe the owner was found
550                 if ($arr["contact-id"] == 0) {
551                         $arr["contact-id"] = Contact::getIdForURL($arr['owner-link'], $uid);
552                 }
553
554                 // Still missing? Then use the "self" contact of the current user
555                 if ($arr["contact-id"] == 0) {
556                         $r = q("SELECT `id` FROM `contact` WHERE `self` AND `uid` = %d", intval($uid));
557
558                         if (DBM::is_result($r)) {
559                                 $arr["contact-id"] = $r[0]["id"];
560                         }
561                 }
562
563                 logger("Contact-id was missing for post ".$arr["guid"]." from user id ".$uid." - now set to ".$arr["contact-id"], LOGGER_DEBUG);
564         }
565
566         if (!x($arr, "gcontact-id")) {
567                 /*
568                  * The gcontact should mostly behave like the contact. But is is supposed to be global for the system.
569                  * This means that wall posts, repeated posts, etc. should have the gcontact id of the owner.
570                  * On comments the author is the better choice.
571                  */
572                 if ($arr['parent-uri'] === $arr['uri']) {
573                         $arr["gcontact-id"] = GContact::getId(["url" => $arr['owner-link'], "network" => $arr['network'],
574                                                                  "photo" => $arr['owner-avatar'], "name" => $arr['owner-name']]);
575                 } else {
576                         $arr["gcontact-id"] = GContact::getId(["url" => $arr['author-link'], "network" => $arr['network'],
577                                                                  "photo" => $arr['author-avatar'], "name" => $arr['author-name']]);
578                 }
579         }
580
581         if ($arr["author-id"] == 0) {
582                 $arr["author-id"] = Contact::getIdForURL($arr["author-link"], 0);
583         }
584
585         if (Contact::isBlocked($arr["author-id"])) {
586                 logger('Contact '.$arr["author-id"].' is blocked, item '.$arr["uri"].' will not be stored');
587                 return 0;
588         }
589
590         if ($arr["owner-id"] == 0) {
591                 $arr["owner-id"] = Contact::getIdForURL($arr["owner-link"], 0);
592         }
593
594         if (Contact::isBlocked($arr["owner-id"])) {
595                 logger('Contact '.$arr["owner-id"].' is blocked, item '.$arr["uri"].' will not be stored');
596                 return 0;
597         }
598
599         if ($arr['guid'] != "") {
600                 // Checking if there is already an item with the same guid
601                 logger('checking for an item for user '.$arr['uid'].' on network '.$arr['network'].' with the guid '.$arr['guid'], LOGGER_DEBUG);
602                 $r = q("SELECT `guid` FROM `item` WHERE `guid` = '%s' AND `network` = '%s' AND `uid` = '%d' LIMIT 1",
603                         dbesc($arr['guid']), dbesc($arr['network']), intval($arr['uid']));
604
605                 if (DBM::is_result($r)) {
606                         logger('found item with guid '.$arr['guid'].' for user '.$arr['uid'].' on network '.$arr['network'], LOGGER_DEBUG);
607                         return 0;
608                 }
609         }
610
611         // Check for hashtags in the body and repair or add hashtag links
612         item_body_set_hashtags($arr);
613
614         $arr['thr-parent'] = $arr['parent-uri'];
615
616         if ($arr['parent-uri'] === $arr['uri']) {
617                 $parent_id = 0;
618                 $parent_deleted = 0;
619                 $allow_cid = $arr['allow_cid'];
620                 $allow_gid = $arr['allow_gid'];
621                 $deny_cid  = $arr['deny_cid'];
622                 $deny_gid  = $arr['deny_gid'];
623                 $notify_type = 'wall-new';
624         } else {
625
626                 // find the parent and snarf the item id and ACLs
627                 // and anything else we need to inherit
628
629                 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d ORDER BY `id` ASC LIMIT 1",
630                         dbesc($arr['parent-uri']),
631                         intval($arr['uid'])
632                 );
633
634                 if (DBM::is_result($r)) {
635
636                         // is the new message multi-level threaded?
637                         // even though we don't support it now, preserve the info
638                         // and re-attach to the conversation parent.
639
640                         if ($r[0]['uri'] != $r[0]['parent-uri']) {
641                                 $arr['parent-uri'] = $r[0]['parent-uri'];
642                                 $z = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `parent-uri` = '%s' AND `uid` = %d
643                                         ORDER BY `id` ASC LIMIT 1",
644                                         dbesc($r[0]['parent-uri']),
645                                         dbesc($r[0]['parent-uri']),
646                                         intval($arr['uid'])
647                                 );
648
649                                 if (DBM::is_result($z)) {
650                                         $r = $z;
651                                 }
652                         }
653
654                         $parent_id      = $r[0]['id'];
655                         $parent_deleted = $r[0]['deleted'];
656                         $allow_cid      = $r[0]['allow_cid'];
657                         $allow_gid      = $r[0]['allow_gid'];
658                         $deny_cid       = $r[0]['deny_cid'];
659                         $deny_gid       = $r[0]['deny_gid'];
660                         $arr['wall']    = $r[0]['wall'];
661                         $notify_type    = 'comment-new';
662
663                         /*
664                          * If the parent is private, force privacy for the entire conversation
665                          * This differs from the above settings as it subtly allows comments from
666                          * email correspondents to be private even if the overall thread is not.
667                          */
668                         if ($r[0]['private']) {
669                                 $arr['private'] = $r[0]['private'];
670                         }
671
672                         /*
673                          * Edge case. We host a public forum that was originally posted to privately.
674                          * The original author commented, but as this is a comment, the permissions
675                          * weren't fixed up so it will still show the comment as private unless we fix it here.
676                          */
677                         if ((intval($r[0]['forum_mode']) == 1) && $r[0]['private']) {
678                                 $arr['private'] = 0;
679                         }
680
681                         // If its a post from myself then tag the thread as "mention"
682                         logger("item_store: Checking if parent ".$parent_id." has to be tagged as mention for user ".$arr['uid'], LOGGER_DEBUG);
683                         $u = q("SELECT `nickname` FROM `user` WHERE `uid` = %d", intval($arr['uid']));
684                         if (DBM::is_result($u)) {
685                                 $self = normalise_link(System::baseUrl() . '/profile/' . $u[0]['nickname']);
686                                 logger("item_store: 'myself' is ".$self." for parent ".$parent_id." checking against ".$arr['author-link']." and ".$arr['owner-link'], LOGGER_DEBUG);
687                                 if ((normalise_link($arr['author-link']) == $self) || (normalise_link($arr['owner-link']) == $self)) {
688                                         dba::update('thread', ['mention' => true], ['iid' => $parent_id]);
689                                         logger("item_store: tagged thread ".$parent_id." as mention for user ".$self, LOGGER_DEBUG);
690                                 }
691                         }
692                 } else {
693                         /*
694                          * Allow one to see reply tweets from status.net even when
695                          * we don't have or can't see the original post.
696                          */
697                         if ($force_parent) {
698                                 logger('item_store: $force_parent=true, reply converted to top-level post.');
699                                 $parent_id = 0;
700                                 $arr['parent-uri'] = $arr['uri'];
701                                 $arr['gravity'] = 0;
702                         } else {
703                                 logger('item_store: item parent '.$arr['parent-uri'].' for '.$arr['uid'].' was not found - ignoring item');
704                                 return 0;
705                         }
706
707                         $parent_deleted = 0;
708                 }
709         }
710
711         $r = q("SELECT `id` FROM `item` WHERE `uri` = '%s' AND `network` IN ('%s', '%s') AND `uid` = %d LIMIT 1",
712                 dbesc($arr['uri']),
713                 dbesc($arr['network']),
714                 dbesc(NETWORK_DFRN),
715                 intval($arr['uid'])
716         );
717         if (DBM::is_result($r)) {
718                 logger('duplicated item with the same uri found. '.print_r($arr,true));
719                 return 0;
720         }
721
722         // On Friendica and Diaspora the GUID is unique
723         if (in_array($arr['network'], [NETWORK_DFRN, NETWORK_DIASPORA])) {
724                 $r = q("SELECT `id` FROM `item` WHERE `guid` = '%s' AND `uid` = %d LIMIT 1",
725                         dbesc($arr['guid']),
726                         intval($arr['uid'])
727                 );
728                 if (DBM::is_result($r)) {
729                         logger('duplicated item with the same guid found. '.print_r($arr,true));
730                         return 0;
731                 }
732         } else {
733                 // Check for an existing post with the same content. There seems to be a problem with OStatus.
734                 $r = q("SELECT `id` FROM `item` WHERE `body` = '%s' AND `network` = '%s' AND `created` = '%s' AND `contact-id` = %d AND `uid` = %d LIMIT 1",
735                         dbesc($arr['body']),
736                         dbesc($arr['network']),
737                         dbesc($arr['created']),
738                         intval($arr['contact-id']),
739                         intval($arr['uid'])
740                 );
741                 if (DBM::is_result($r)) {
742                         logger('duplicated item with the same body found. '.print_r($arr,true));
743                         return 0;
744                 }
745         }
746
747         // Is this item available in the global items (with uid=0)?
748         if ($arr["uid"] == 0) {
749                 $arr["global"] = true;
750
751                 // Set the global flag on all items if this was a global item entry
752                 dba::update('item', ['global' => true], ['uri' => $arr["uri"]]);
753         } else {
754                 $isglobal = q("SELECT `global` FROM `item` WHERE `uid` = 0 AND `uri` = '%s'", dbesc($arr["uri"]));
755
756                 $arr["global"] = (DBM::is_result($isglobal) && count($isglobal) > 0);
757         }
758
759         // ACL settings
760         if (strlen($allow_cid) || strlen($allow_gid) || strlen($deny_cid) || strlen($deny_gid)) {
761                 $private = 1;
762         } else {
763                 $private = $arr['private'];
764         }
765
766         $arr["allow_cid"] = $allow_cid;
767         $arr["allow_gid"] = $allow_gid;
768         $arr["deny_cid"] = $deny_cid;
769         $arr["deny_gid"] = $deny_gid;
770         $arr["private"] = $private;
771         $arr["deleted"] = $parent_deleted;
772
773         // Fill the cache field
774         put_item_in_cache($arr);
775
776         if ($notify) {
777                 Addon::callHooks('post_local', $arr);
778         } else {
779                 Addon::callHooks('post_remote', $arr);
780         }
781
782         // This array field is used to trigger some automatic reactions
783         // It is mainly used in the "post_local" hook.
784         unset($arr['api_source']);
785
786         if (x($arr, 'cancel')) {
787                 logger('item_store: post cancelled by addon.');
788                 return 0;
789         }
790
791         /*
792          * Check for already added items.
793          * There is a timing issue here that sometimes creates double postings.
794          * An unique index would help - but the limitations of MySQL (maximum size of index values) prevent this.
795          */
796         if ($arr["uid"] == 0) {
797                 $r = q("SELECT `id` FROM `item` WHERE `uri` = '%s' AND `uid` = 0 LIMIT 1", dbesc(trim($arr['uri'])));
798                 if (DBM::is_result($r)) {
799                         logger('Global item already stored. URI: '.$arr['uri'].' on network '.$arr['network'], LOGGER_DEBUG);
800                         return 0;
801                 }
802         }
803
804         logger('item_store: ' . print_r($arr,true), LOGGER_DATA);
805
806         dba::transaction();
807         $r = dba::insert('item', $arr);
808
809         // When the item was successfully stored we fetch the ID of the item.
810         if (DBM::is_result($r)) {
811                 $current_post = dba::lastInsertId();
812         } else {
813                 // This can happen - for example - if there are locking timeouts.
814                 dba::rollback();
815
816                 // Store the data into a spool file so that we can try again later.
817
818                 // At first we restore the Diaspora signature that we removed above.
819                 if (isset($encoded_signature)) {
820                         $arr['dsprsig'] = $encoded_signature;
821                 }
822
823                 // Now we store the data in the spool directory
824                 // We use "microtime" to keep the arrival order and "mt_rand" to avoid duplicates
825                 $file = 'item-'.round(microtime(true) * 10000).'-'.mt_rand().'.msg';
826
827                 $spoolpath = get_spoolpath();
828                 if ($spoolpath != "") {
829                         $spool = $spoolpath.'/'.$file;
830                         file_put_contents($spool, json_encode($arr));
831                         logger("Item wasn't stored - Item was spooled into file ".$file, LOGGER_DEBUG);
832                 }
833                 return 0;
834         }
835
836         if ($current_post == 0) {
837                 // This is one of these error messages that never should occur.
838                 logger("couldn't find created item - we better quit now.");
839                 dba::rollback();
840                 return 0;
841         }
842
843         // How much entries have we created?
844         // We wouldn't need this query when we could use an unique index - but MySQL has length problems with them.
845         $r = q("SELECT COUNT(*) AS `entries` FROM `item` WHERE `uri` = '%s' AND `uid` = %d AND `network` = '%s'",
846                 dbesc($arr['uri']),
847                 intval($arr['uid']),
848                 dbesc($arr['network'])
849         );
850
851         if (!DBM::is_result($r)) {
852                 // This shouldn't happen, since COUNT always works when the database connection is there.
853                 logger("We couldn't count the stored entries. Very strange ...");
854                 dba::rollback();
855                 return 0;
856         }
857
858         if ($r[0]["entries"] > 1) {
859                 // There are duplicates. We delete our just created entry.
860                 logger('Duplicated post occurred. uri = ' . $arr['uri'] . ' uid = ' . $arr['uid']);
861
862                 // Yes, we could do a rollback here - but we are having many users with MyISAM.
863                 dba::delete('item', ['id' => $current_post]);
864                 dba::commit();
865                 return 0;
866         } elseif ($r[0]["entries"] == 0) {
867                 // This really should never happen since we quit earlier if there were problems.
868                 logger("Something is terribly wrong. We haven't found our created entry.");
869                 dba::rollback();
870                 return 0;
871         }
872
873         logger('item_store: created item '.$current_post);
874         Item::updateContact($arr);
875
876         if (!$parent_id || ($arr['parent-uri'] === $arr['uri'])) {
877                 $parent_id = $current_post;
878         }
879
880         // Set parent id
881         dba::update('item', ['parent' => $parent_id], ['id' => $current_post]);
882
883         $arr['id'] = $current_post;
884         $arr['parent'] = $parent_id;
885
886         // update the commented timestamp on the parent
887         // Only update "commented" if it is really a comment
888         if (($arr['verb'] == ACTIVITY_POST) || !Config::get("system", "like_no_comment")) {
889                 dba::update('item', ['commented' => datetime_convert(), 'changed' => datetime_convert()], ['id' => $parent_id]);
890         } else {
891                 dba::update('item', ['changed' => datetime_convert()], ['id' => $parent_id]);
892         }
893
894         if ($dsprsig) {
895
896                 /*
897                  * Friendica servers lower than 3.4.3-2 had double encoded the signature ...
898                  * We can check for this condition when we decode and encode the stuff again.
899                  */
900                 if (base64_encode(base64_decode(base64_decode($dsprsig->signature))) == base64_decode($dsprsig->signature)) {
901                         $dsprsig->signature = base64_decode($dsprsig->signature);
902                         logger("Repaired double encoded signature from handle ".$dsprsig->signer, LOGGER_DEBUG);
903                 }
904
905                 dba::insert('sign', ['iid' => $current_post, 'signed_text' => $dsprsig->signed_text,
906                                         'signature' => $dsprsig->signature, 'signer' => $dsprsig->signer]);
907         }
908
909         $deleted = tag_deliver($arr['uid'], $current_post);
910
911         /*
912          * current post can be deleted if is for a community page and no mention are
913          * in it.
914          */
915         if (!$deleted && !$dontcache) {
916
917                 $r = q('SELECT * FROM `item` WHERE `id` = %d', intval($current_post));
918                 if ((DBM::is_result($r)) && (count($r) == 1)) {
919                         if ($notify) {
920                                 Addon::callHooks('post_local_end', $r[0]);
921                         } else {
922                                 Addon::callHooks('post_remote_end', $r[0]);
923                         }
924                 } else {
925                         logger('item_store: new item not found in DB, id ' . $current_post);
926                 }
927         }
928
929         if ($arr['parent-uri'] === $arr['uri']) {
930                 add_thread($current_post);
931         } else {
932                 update_thread($parent_id);
933         }
934
935         dba::commit();
936
937         /*
938          * Due to deadlock issues with the "term" table we are doing these steps after the commit.
939          * This is not perfect - but a workable solution until we found the reason for the problem.
940          */
941         create_tags_from_item($current_post);
942         Term::createFromItem($current_post);
943
944         if ($arr['parent-uri'] === $arr['uri']) {
945                 Item::addShadow($current_post);
946         } else {
947                 Item::addShadowPost($current_post);
948         }
949
950         check_user_notification($current_post);
951
952         if ($notify) {
953                 Worker::add(['priority' => PRIORITY_HIGH, 'dont_fork' => true], "Notifier", $notify_type, $current_post);
954         }
955
956         return $current_post;
957 }
958
959 /// @TODO move to src/Model/Item.php
960 function item_body_set_hashtags(&$item) {
961
962         $tags = get_tags($item["body"]);
963
964         // No hashtags?
965         if (!count($tags)) {
966                 return false;
967         }
968
969         // This sorting is important when there are hashtags that are part of other hashtags
970         // Otherwise there could be problems with hashtags like #test and #test2
971         rsort($tags);
972
973         $URLSearchString = "^\[\]";
974
975         // All hashtags should point to the home server if "local_tags" is activated
976         if (Config::get('system', 'local_tags')) {
977                 $item["body"] = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
978                                 "#[url=".System::baseUrl()."/search?tag=$2]$2[/url]", $item["body"]);
979
980                 $item["tag"] = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
981                                 "#[url=".System::baseUrl()."/search?tag=$2]$2[/url]", $item["tag"]);
982         }
983
984         // mask hashtags inside of url, bookmarks and attachments to avoid urls in urls
985         $item["body"] = preg_replace_callback("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
986                 function ($match) {
987                         return ("[url=" . str_replace("#", "&num;", $match[1]) . "]" . str_replace("#", "&num;", $match[2]) . "[/url]");
988                 }, $item["body"]);
989
990         $item["body"] = preg_replace_callback("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism",
991                 function ($match) {
992                         return ("[bookmark=" . str_replace("#", "&num;", $match[1]) . "]" . str_replace("#", "&num;", $match[2]) . "[/bookmark]");
993                 }, $item["body"]);
994
995         $item["body"] = preg_replace_callback("/\[attachment (.*)\](.*?)\[\/attachment\]/ism",
996                 function ($match) {
997                         return ("[attachment " . str_replace("#", "&num;", $match[1]) . "]" . $match[2] . "[/attachment]");
998                 }, $item["body"]);
999
1000         // Repair recursive urls
1001         $item["body"] = preg_replace("/&num;\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
1002                         "&num;$2", $item["body"]);
1003
1004         foreach ($tags as $tag) {
1005                 if ((strpos($tag, '#') !== 0) || (strpos($tag, '[url='))) {
1006                         continue;
1007                 }
1008
1009                 $basetag = str_replace('_',' ',substr($tag,1));
1010
1011                 $newtag = '#[url=' . System::baseUrl() . '/search?tag=' . rawurlencode($basetag) . ']' . $basetag . '[/url]';
1012
1013                 $item["body"] = str_replace($tag, $newtag, $item["body"]);
1014
1015                 if (!stristr($item["tag"], "/search?tag=" . $basetag . "]" . $basetag . "[/url]")) {
1016                         if (strlen($item["tag"])) {
1017                                 $item["tag"] = ','.$item["tag"];
1018                         }
1019                         $item["tag"] = $newtag.$item["tag"];
1020                 }
1021         }
1022
1023         // Convert back the masked hashtags
1024         $item["body"] = str_replace("&num;", "#", $item["body"]);
1025 }
1026
1027 /// @TODO move to src/Model/Item.php
1028 function get_item_guid($id) {
1029         $r = q("SELECT `guid` FROM `item` WHERE `id` = %d LIMIT 1", intval($id));
1030         if (DBM::is_result($r)) {
1031                 return $r[0]["guid"];
1032         } else {
1033                 /// @TODO This else-block can be elimited again
1034                 return "";
1035         }
1036 }
1037
1038 /// @TODO move to src/Model/Item.php
1039 function get_item_id($guid, $uid = 0) {
1040
1041         $nick = "";
1042         $id = 0;
1043
1044         if ($uid == 0) {
1045                 $uid == local_user();
1046         }
1047
1048         // Does the given user have this item?
1049         if ($uid) {
1050                 $r = q("SELECT `item`.`id`, `user`.`nickname` FROM `item` INNER JOIN `user` ON `user`.`uid` = `item`.`uid`
1051                         WHERE `item`.`visible` = 1 AND `item`.`deleted` = 0 AND `item`.`moderated` = 0
1052                                 AND `item`.`guid` = '%s' AND `item`.`uid` = %d", dbesc($guid), intval($uid));
1053                 if (DBM::is_result($r)) {
1054                         $id = $r[0]["id"];
1055                         $nick = $r[0]["nickname"];
1056                 }
1057         }
1058
1059         // Or is it anywhere on the server?
1060         if ($nick == "") {
1061                 $r = q("SELECT `item`.`id`, `user`.`nickname` FROM `item` INNER JOIN `user` ON `user`.`uid` = `item`.`uid`
1062                         WHERE `item`.`visible` = 1 AND `item`.`deleted` = 0 AND `item`.`moderated` = 0
1063                                 AND `item`.`allow_cid` = ''  AND `item`.`allow_gid` = ''
1064                                 AND `item`.`deny_cid`  = '' AND `item`.`deny_gid`  = ''
1065                                 AND `item`.`private` = 0 AND `item`.`wall` = 1
1066                                 AND `item`.`guid` = '%s'", dbesc($guid));
1067                 if (DBM::is_result($r)) {
1068                         $id = $r[0]["id"];
1069                         $nick = $r[0]["nickname"];
1070                 }
1071         }
1072         return ["nick" => $nick, "id" => $id];
1073 }
1074
1075 /**
1076  * look for mention tags and setup a second delivery chain for forum/community posts if appropriate
1077  * @param int $uid
1078  * @param int $item_id
1079  * @return bool true if item was deleted, else false
1080  */
1081 /// @TODO move to src/Model/Item.php
1082 function tag_deliver($uid, $item_id)
1083 {
1084         $mention = false;
1085
1086         $u = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
1087                 intval($uid)
1088         );
1089         if (! DBM::is_result($u)) {
1090                 return;
1091         }
1092
1093         $community_page = (($u[0]['page-flags'] == PAGE_COMMUNITY) ? true : false);
1094         $prvgroup = (($u[0]['page-flags'] == PAGE_PRVGROUP) ? true : false);
1095
1096         $i = q("SELECT * FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1",
1097                 intval($item_id),
1098                 intval($uid)
1099         );
1100         if (! DBM::is_result($i)) {
1101                 return;
1102         }
1103
1104         $item = $i[0];
1105
1106         $link = normalise_link(System::baseUrl() . '/profile/' . $u[0]['nickname']);
1107
1108         /*
1109          * Diaspora uses their own hardwired link URL in @-tags
1110          * instead of the one we supply with webfinger
1111          */
1112         $dlink = normalise_link(System::baseUrl() . '/u/' . $u[0]['nickname']);
1113
1114         $cnt = preg_match_all('/[\@\!]\[url\=(.*?)\](.*?)\[\/url\]/ism', $item['body'], $matches, PREG_SET_ORDER);
1115         if ($cnt) {
1116                 foreach ($matches as $mtch) {
1117                         if (link_compare($link, $mtch[1]) || link_compare($dlink, $mtch[1])) {
1118                                 $mention = true;
1119                                 logger('tag_deliver: mention found: ' . $mtch[2]);
1120                         }
1121                 }
1122         }
1123
1124         if (! $mention) {
1125                 if (($community_page || $prvgroup) &&
1126                           (!$item['wall']) && (!$item['origin']) && ($item['id'] == $item['parent'])) {
1127                         // mmh.. no mention.. community page or private group... no wall.. no origin.. top-post (not a comment)
1128                         // delete it!
1129                         logger("tag_deliver: no-mention top-level post to communuty or private group. delete.");
1130                         dba::delete('item', ['id' => $item_id]);
1131                         return true;
1132                 }
1133                 return;
1134         }
1135
1136         $arr = ['item' => $item, 'user' => $u[0], 'contact' => $r[0]];
1137
1138         Addon::callHooks('tagged', $arr);
1139
1140         if ((! $community_page) && (! $prvgroup)) {
1141                 return;
1142         }
1143
1144         /*
1145          * tgroup delivery - setup a second delivery chain
1146          * prevent delivery looping - only proceed
1147          * if the message originated elsewhere and is a top-level post
1148          */
1149         if (($item['wall']) || ($item['origin']) || ($item['id'] != $item['parent'])) {
1150                 return;
1151         }
1152
1153         // now change this copy of the post to a forum head message and deliver to all the tgroup members
1154         $c = q("SELECT `name`, `url`, `thumb` FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
1155                 intval($u[0]['uid'])
1156         );
1157         if (! DBM::is_result($c)) {
1158                 return;
1159         }
1160
1161         // also reset all the privacy bits to the forum default permissions
1162
1163         $private = ($u[0]['allow_cid'] || $u[0]['allow_gid'] || $u[0]['deny_cid'] || $u[0]['deny_gid']) ? 1 : 0;
1164
1165         $forum_mode = (($prvgroup) ? 2 : 1);
1166
1167         q("UPDATE `item` SET `wall` = 1, `origin` = 1, `forum_mode` = %d, `owner-name` = '%s', `owner-link` = '%s', `owner-avatar` = '%s',
1168                 `private` = %d, `allow_cid` = '%s', `allow_gid` = '%s', `deny_cid` = '%s', `deny_gid` = '%s'  WHERE `id` = %d",
1169                 intval($forum_mode),
1170                 dbesc($c[0]['name']),
1171                 dbesc($c[0]['url']),
1172                 dbesc($c[0]['thumb']),
1173                 intval($private),
1174                 dbesc($u[0]['allow_cid']),
1175                 dbesc($u[0]['allow_gid']),
1176                 dbesc($u[0]['deny_cid']),
1177                 dbesc($u[0]['deny_gid']),
1178                 intval($item_id)
1179         );
1180         update_thread($item_id);
1181
1182         Worker::add(['priority' => PRIORITY_HIGH, 'dont_fork' => true], 'Notifier', 'tgroup', $item_id);
1183
1184 }
1185
1186 /**
1187  *
1188  * consume_feed - process atom feed and update anything/everything we might need to update
1189  *
1190  * $xml = the (atom) feed to consume - RSS isn't as fully supported but may work for simple feeds.
1191  *
1192  * $importer = the contact_record (joined to user_record) of the local user who owns this relationship.
1193  *             It is this person's stuff that is going to be updated.
1194  * $contact =  the person who is sending us stuff. If not set, we MAY be processing a "follow" activity
1195  *             from an external network and MAY create an appropriate contact record. Otherwise, we MUST
1196  *             have a contact record.
1197  * $hub = should we find a hub declation in the feed, pass it back to our calling process, who might (or
1198  *        might not) try and subscribe to it.
1199  * $datedir sorts in reverse order
1200  * $pass - by default ($pass = 0) we cannot guarantee that a parent item has been
1201  *      imported prior to its children being seen in the stream unless we are certain
1202  *      of how the feed is arranged/ordered.
1203  * With $pass = 1, we only pull parent items out of the stream.
1204  * With $pass = 2, we only pull children (comments/likes).
1205  *
1206  * So running this twice, first with pass 1 and then with pass 2 will do the right
1207  * thing regardless of feed ordering. This won't be adequate in a fully-threaded
1208  * model where comments can have sub-threads. That would require some massive sorting
1209  * to get all the feed items into a mostly linear ordering, and might still require
1210  * recursion.
1211  *
1212  * @TODO find proper type-hints
1213  */
1214 /// @TODO move to ???
1215 function consume_feed($xml, $importer, &$contact, &$hub, $datedir = 0, $pass = 0) {
1216         if ($contact['network'] === NETWORK_OSTATUS) {
1217                 if ($pass < 2) {
1218                         // Test - remove before flight
1219                         //$tempfile = tempnam(get_temppath(), "ostatus2");
1220                         //file_put_contents($tempfile, $xml);
1221                         logger("Consume OStatus messages ", LOGGER_DEBUG);
1222                         OStatus::import($xml, $importer, $contact, $hub);
1223                 }
1224                 return;
1225         }
1226
1227         if ($contact['network'] === NETWORK_FEED) {
1228                 if ($pass < 2) {
1229                         logger("Consume feeds", LOGGER_DEBUG);
1230                         Feed::import($xml, $importer, $contact, $hub);
1231                 }
1232                 return;
1233         }
1234
1235         if ($contact['network'] === NETWORK_DFRN) {
1236                 logger("Consume DFRN messages", LOGGER_DEBUG);
1237
1238                 $r = q("SELECT `contact`.*, `contact`.`uid` AS `importer_uid`,
1239                                         `contact`.`pubkey` AS `cpubkey`,
1240                                         `contact`.`prvkey` AS `cprvkey`,
1241                                         `contact`.`thumb` AS `thumb`,
1242                                         `contact`.`url` as `url`,
1243                                         `contact`.`name` as `senderName`,
1244                                         `user`.*
1245                         FROM `contact`
1246                         LEFT JOIN `user` ON `contact`.`uid` = `user`.`uid`
1247                         WHERE `contact`.`id` = %d AND `user`.`uid` = %d",
1248                         dbesc($contact["id"]), dbesc($importer["uid"])
1249                 );
1250                 if (DBM::is_result($r)) {
1251                         logger("Now import the DFRN feed");
1252                         DFRN::import($xml, $r[0], true);
1253                         return;
1254                 }
1255         }
1256 }
1257
1258 /// @TODO type-hint is array
1259 /// @TODO move to src/Model/Item.php
1260 function item_is_remote_self($contact, &$datarray) {
1261         $a = get_app();
1262
1263         if (!$contact['remote_self']) {
1264                 return false;
1265         }
1266
1267         // Prevent the forwarding of posts that are forwarded
1268         if ($datarray["extid"] == NETWORK_DFRN) {
1269                 return false;
1270         }
1271
1272         // Prevent to forward already forwarded posts
1273         if ($datarray["app"] == $a->get_hostname()) {
1274                 return false;
1275         }
1276
1277         // Only forward posts
1278         if ($datarray["verb"] != ACTIVITY_POST) {
1279                 return false;
1280         }
1281
1282         if (($contact['network'] != NETWORK_FEED) && $datarray['private']) {
1283                 return false;
1284         }
1285
1286         $datarray2 = $datarray;
1287         logger('remote-self start - Contact '.$contact['url'].' - '.$contact['remote_self'].' Item '.print_r($datarray, true), LOGGER_DEBUG);
1288         if ($contact['remote_self'] == 2) {
1289                 $r = q("SELECT `id`,`url`,`name`,`thumb` FROM `contact` WHERE `uid` = %d AND `self`",
1290                         intval($contact['uid']));
1291                 if (DBM::is_result($r)) {
1292                         $datarray['contact-id'] = $r[0]["id"];
1293
1294                         $datarray['owner-name'] = $r[0]["name"];
1295                         $datarray['owner-link'] = $r[0]["url"];
1296                         $datarray['owner-avatar'] = $r[0]["thumb"];
1297
1298                         $datarray['author-name']   = $datarray['owner-name'];
1299                         $datarray['author-link']   = $datarray['owner-link'];
1300                         $datarray['author-avatar'] = $datarray['owner-avatar'];
1301
1302                         unset($datarray['created']);
1303                         unset($datarray['edited']);
1304                 }
1305
1306                 if ($contact['network'] != NETWORK_FEED) {
1307                         $datarray["guid"] = get_guid(32);
1308                         unset($datarray["plink"]);
1309                         $datarray["uri"] = item_new_uri($a->get_hostname(), $contact['uid'], $datarray["guid"]);
1310                         $datarray["parent-uri"] = $datarray["uri"];
1311                         $datarray["extid"] = $contact['network'];
1312                         $urlpart = parse_url($datarray2['author-link']);
1313                         $datarray["app"] = $urlpart["host"];
1314                 } else {
1315                         $datarray['private'] = 0;
1316                 }
1317         }
1318
1319         if ($contact['network'] != NETWORK_FEED) {
1320                 // Store the original post
1321                 $r = item_store($datarray2, false, false);
1322                 logger('remote-self post original item - Contact '.$contact['url'].' return '.$r.' Item '.print_r($datarray2, true), LOGGER_DEBUG);
1323         } else {
1324                 $datarray["app"] = "Feed";
1325         }
1326
1327         // Trigger automatic reactions for addons
1328         $datarray['api_source'] = true;
1329
1330         // We have to tell the hooks who we are - this really should be improved
1331         $_SESSION["authenticated"] = true;
1332         $_SESSION["uid"] = $contact['uid'];
1333
1334         return true;
1335 }
1336
1337 /// @TODO find proper type-hints
1338 /// @TODO move to src/Model/Item.php
1339 function new_follower($importer, $contact, $datarray, $item, $sharing = false) {
1340         $url = notags(trim($datarray['author-link']));
1341         $name = notags(trim($datarray['author-name']));
1342         $photo = notags(trim($datarray['author-avatar']));
1343
1344         if (is_object($item)) {
1345                 $rawtag = $item->get_item_tags(NAMESPACE_ACTIVITY,'actor');
1346                 if ($rawtag && $rawtag[0]['child'][NAMESPACE_POCO]['preferredUsername'][0]['data']) {
1347                         $nick = $rawtag[0]['child'][NAMESPACE_POCO]['preferredUsername'][0]['data'];
1348                 }
1349         } else {
1350                 $nick = $item;
1351         }
1352
1353         if (is_array($contact)) {
1354                 if (($contact['network'] == NETWORK_OSTATUS && $contact['rel'] == CONTACT_IS_SHARING)
1355                         || ($sharing && $contact['rel'] == CONTACT_IS_FOLLOWER)) {
1356                         dba::update('contact', ['rel' => CONTACT_IS_FRIEND, 'writable' => true],
1357                                         ['id' => $contact['id'], 'uid' => $importer['uid']]);
1358                 }
1359                 // send email notification to owner?
1360         } else {
1361                 // create contact record
1362                 q("INSERT INTO `contact` (`uid`, `created`, `url`, `nurl`, `name`, `nick`, `photo`, `network`, `rel`,
1363                         `blocked`, `readonly`, `pending`, `writable`)
1364                         VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, 0, 0, 1, 1)",
1365                         intval($importer['uid']),
1366                         dbesc(datetime_convert()),
1367                         dbesc($url),
1368                         dbesc(normalise_link($url)),
1369                         dbesc($name),
1370                         dbesc($nick),
1371                         dbesc($photo),
1372                         dbesc(NETWORK_OSTATUS),
1373                         intval(CONTACT_IS_FOLLOWER)
1374                 );
1375
1376                 $r = q("SELECT `id`, `network` FROM `contact` WHERE `uid` = %d AND `url` = '%s' AND `pending` = 1 LIMIT 1",
1377                                 intval($importer['uid']),
1378                                 dbesc($url)
1379                 );
1380                 if (DBM::is_result($r)) {
1381                         $contact_record = $r[0];
1382                         Contact::updateAvatar($photo, $importer["uid"], $contact_record["id"], true);
1383                 }
1384
1385                 /// @TODO Encapsulate this into a function/method
1386                 $r = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
1387                         intval($importer['uid'])
1388                 );
1389                 if (DBM::is_result($r) && !in_array($r[0]['page-flags'], [PAGE_SOAPBOX, PAGE_FREELOVE, PAGE_COMMUNITY])) {
1390                         // create notification
1391                         $hash = random_string();
1392
1393                         if (is_array($contact_record)) {
1394                                 dba::insert('intro', ['uid' => $importer['uid'], 'contact-id' => $contact_record['id'],
1395                                                         'blocked' => false, 'knowyou' => false,
1396                                                         'hash' => $hash, 'datetime' => datetime_convert()]);
1397                         }
1398
1399                         Group::addMember(User::getDefaultGroup($importer['uid'], $contact_record["network"]), $contact_record['id']);
1400
1401                         if (($r[0]['notify-flags'] & NOTIFY_INTRO) &&
1402                                 in_array($r[0]['page-flags'], [PAGE_NORMAL])) {
1403
1404                                 notification([
1405                                         'type'         => NOTIFY_INTRO,
1406                                         'notify_flags' => $r[0]['notify-flags'],
1407                                         'language'     => $r[0]['language'],
1408                                         'to_name'      => $r[0]['username'],
1409                                         'to_email'     => $r[0]['email'],
1410                                         'uid'          => $r[0]['uid'],
1411                                         'link'             => System::baseUrl() . '/notifications/intro',
1412                                         'source_name'  => ((strlen(stripslashes($contact_record['name']))) ? stripslashes($contact_record['name']) : L10n::t('[Name Withheld]')),
1413                                         'source_link'  => $contact_record['url'],
1414                                         'source_photo' => $contact_record['photo'],
1415                                         'verb'         => ($sharing ? ACTIVITY_FRIEND : ACTIVITY_FOLLOW),
1416                                         'otype'        => 'intro'
1417                                 ]);
1418
1419                         }
1420                 } elseif (DBM::is_result($r) && in_array($r[0]['page-flags'], [PAGE_SOAPBOX, PAGE_FREELOVE, PAGE_COMMUNITY])) {
1421                         q("UPDATE `contact` SET `pending` = 0 WHERE `uid` = %d AND `url` = '%s' AND `pending` LIMIT 1",
1422                                         intval($importer['uid']),
1423                                         dbesc($url)
1424                         );
1425                 }
1426
1427         }
1428 }
1429
1430 /// @TODO move to src/Model/Item.php
1431 function lose_follower($importer, $contact, array $datarray = [], $item = "") {
1432
1433         if (($contact['rel'] == CONTACT_IS_FRIEND) || ($contact['rel'] == CONTACT_IS_SHARING)) {
1434                 dba::update('contact', ['rel' => CONTACT_IS_SHARING], ['id' => $contact['id']]);
1435         } else {
1436                 Contact::remove($contact['id']);
1437         }
1438 }
1439
1440 /// @TODO move to src/Model/Item.php
1441 function lose_sharer($importer, $contact, array $datarray = [], $item = "") {
1442
1443         if (($contact['rel'] == CONTACT_IS_FRIEND) || ($contact['rel'] == CONTACT_IS_FOLLOWER)) {
1444                 dba::update('contact', ['rel' => CONTACT_IS_FOLLOWER], ['id' => $contact['id']]);
1445         } else {
1446                 Contact::remove($contact['id']);
1447         }
1448 }
1449
1450 /// @TODO move to ???
1451 function subscribe_to_hub($url, $importer, $contact, $hubmode = 'subscribe') {
1452
1453         $a = get_app();
1454
1455         if (is_array($importer)) {
1456                 $r = q("SELECT `nickname` FROM `user` WHERE `uid` = %d LIMIT 1",
1457                         intval($importer['uid'])
1458                 );
1459         }
1460
1461         /*
1462          * Diaspora has different message-ids in feeds than they do
1463          * through the direct Diaspora protocol. If we try and use
1464          * the feed, we'll get duplicates. So don't.
1465          */
1466         if ((! DBM::is_result($r)) || $contact['network'] === NETWORK_DIASPORA) {
1467                 return;
1468         }
1469
1470         $push_url = Config::get('system','url') . '/pubsub/' . $r[0]['nickname'] . '/' . $contact['id'];
1471
1472         // Use a single verify token, even if multiple hubs
1473         $verify_token = ((strlen($contact['hub-verify'])) ? $contact['hub-verify'] : random_string());
1474
1475         $params= 'hub.mode=' . $hubmode . '&hub.callback=' . urlencode($push_url) . '&hub.topic=' . urlencode($contact['poll']) . '&hub.verify=async&hub.verify_token=' . $verify_token;
1476
1477         logger('subscribe_to_hub: ' . $hubmode . ' ' . $contact['name'] . ' to hub ' . $url . ' endpoint: '  . $push_url . ' with verifier ' . $verify_token);
1478
1479         if (!strlen($contact['hub-verify']) || ($contact['hub-verify'] != $verify_token)) {
1480                 dba::update('contact', ['hub-verify' => $verify_token], ['id' => $contact['id']]);
1481         }
1482
1483         post_url($url, $params);
1484
1485         logger('subscribe_to_hub: returns: ' . $a->get_curl_code(), LOGGER_DEBUG);
1486
1487         return;
1488
1489 }
1490
1491 /**
1492  *
1493  * @param string $s
1494  * @param int    $uid
1495  * @param array  $item
1496  * @param int    $cid
1497  * @return string
1498  */
1499 /// @TODO move to src/Model/Item.php
1500 function fix_private_photos($s, $uid, $item = null, $cid = 0)
1501 {
1502         if (Config::get('system', 'disable_embedded')) {
1503                 return $s;
1504         }
1505
1506         logger('fix_private_photos: check for photos', LOGGER_DEBUG);
1507         $site = substr(System::baseUrl(), strpos(System::baseUrl(), '://'));
1508
1509         $orig_body = $s;
1510         $new_body = '';
1511
1512         $img_start = strpos($orig_body, '[img');
1513         $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
1514         $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
1515
1516         while (($img_st_close !== false) && ($img_len !== false)) {
1517                 $img_st_close++; // make it point to AFTER the closing bracket
1518                 $image = substr($orig_body, $img_start + $img_st_close, $img_len);
1519
1520                 logger('fix_private_photos: found photo ' . $image, LOGGER_DEBUG);
1521
1522                 if (stristr($image, $site . '/photo/')) {
1523                         // Only embed locally hosted photos
1524                         $replace = false;
1525                         $i = basename($image);
1526                         $i = str_replace(['.jpg', '.png', '.gif'], ['', '', ''], $i);
1527                         $x = strpos($i, '-');
1528
1529                         if ($x) {
1530                                 $res = substr($i, $x + 1);
1531                                 $i = substr($i, 0, $x);
1532                                 $r = q("SELECT * FROM `photo` WHERE `resource-id` = '%s' AND `scale` = %d AND `uid` = %d",
1533                                         dbesc($i),
1534                                         intval($res),
1535                                         intval($uid)
1536                                 );
1537                                 if (DBM::is_result($r)) {
1538                                         /*
1539                                          * Check to see if we should replace this photo link with an embedded image
1540                                          * 1. No need to do so if the photo is public
1541                                          * 2. If there's a contact-id provided, see if they're in the access list
1542                                          *    for the photo. If so, embed it.
1543                                          * 3. Otherwise, if we have an item, see if the item permissions match the photo
1544                                          *    permissions, regardless of order but first check to see if they're an exact
1545                                          *    match to save some processing overhead.
1546                                          */
1547                                         if (has_permissions($r[0])) {
1548                                                 if ($cid) {
1549                                                         $recips = enumerate_permissions($r[0]);
1550                                                         if (in_array($cid, $recips)) {
1551                                                                 $replace = true;
1552                                                         }
1553                                                 } elseif ($item) {
1554                                                         if (compare_permissions($item, $r[0])) {
1555                                                                 $replace = true;
1556                                                         }
1557                                                 }
1558                                         }
1559                                         if ($replace) {
1560                                                 $data = $r[0]['data'];
1561                                                 $type = $r[0]['type'];
1562
1563                                                 // If a custom width and height were specified, apply before embedding
1564                                                 if (preg_match("/\[img\=([0-9]*)x([0-9]*)\]/is", substr($orig_body, $img_start, $img_st_close), $match)) {
1565                                                         logger('fix_private_photos: scaling photo', LOGGER_DEBUG);
1566
1567                                                         $width = intval($match[1]);
1568                                                         $height = intval($match[2]);
1569
1570                                                         $Image = new Image($data, $type);
1571                                                         if ($Image->isValid()) {
1572                                                                 $Image->scaleDown(max($width, $height));
1573                                                                 $data = $Image->asString();
1574                                                                 $type = $Image->getType();
1575                                                         }
1576                                                 }
1577
1578                                                 logger('fix_private_photos: replacing photo', LOGGER_DEBUG);
1579                                                 $image = 'data:' . $type . ';base64,' . base64_encode($data);
1580                                                 logger('fix_private_photos: replaced: ' . $image, LOGGER_DATA);
1581                                         }
1582                                 }
1583                         }
1584                 }
1585
1586                 $new_body = $new_body . substr($orig_body, 0, $img_start + $img_st_close) . $image . '[/img]';
1587                 $orig_body = substr($orig_body, $img_start + $img_st_close + $img_len + strlen('[/img]'));
1588                 if ($orig_body === false) {
1589                         $orig_body = '';
1590                 }
1591
1592                 $img_start = strpos($orig_body, '[img');
1593                 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
1594                 $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
1595         }
1596
1597         $new_body = $new_body . $orig_body;
1598
1599         return $new_body;
1600 }
1601
1602 /// @TODO type-hint is array
1603 /// @TODO move to src/Model/Item.php
1604 function has_permissions($obj) {
1605         return (
1606                 (
1607                         x($obj, 'allow_cid')
1608                 ) || (
1609                         x($obj, 'allow_gid')
1610                 ) || (
1611                         x($obj, 'deny_cid')
1612                 ) || (
1613                         x($obj, 'deny_gid')
1614                 )
1615         );
1616 }
1617
1618 /// @TODO type-hint is array
1619 /// @TODO move to src/Model/Item.php
1620 function compare_permissions($obj1, $obj2) {
1621         // first part is easy. Check that these are exactly the same.
1622         if (($obj1['allow_cid'] == $obj2['allow_cid'])
1623                 && ($obj1['allow_gid'] == $obj2['allow_gid'])
1624                 && ($obj1['deny_cid'] == $obj2['deny_cid'])
1625                 && ($obj1['deny_gid'] == $obj2['deny_gid'])) {
1626                 return true;
1627         }
1628
1629         // This is harder. Parse all the permissions and compare the resulting set.
1630         $recipients1 = enumerate_permissions($obj1);
1631         $recipients2 = enumerate_permissions($obj2);
1632         sort($recipients1);
1633         sort($recipients2);
1634
1635         /// @TODO Comparison of arrays, maybe use array_diff_assoc() here?
1636         return ($recipients1 == $recipients2);
1637 }
1638
1639 // returns an array of contact-ids that are allowed to see this object
1640 /// @TODO type-hint is array
1641 /// @TODO move to src/Model/Item.php
1642 function enumerate_permissions($obj) {
1643         $allow_people = expand_acl($obj['allow_cid']);
1644         $allow_groups = Group::expand(expand_acl($obj['allow_gid']));
1645         $deny_people  = expand_acl($obj['deny_cid']);
1646         $deny_groups  = Group::expand(expand_acl($obj['deny_gid']));
1647         $recipients   = array_unique(array_merge($allow_people, $allow_groups));
1648         $deny         = array_unique(array_merge($deny_people, $deny_groups));
1649         $recipients   = array_diff($recipients, $deny);
1650         return $recipients;
1651 }
1652
1653 /// @TODO move to src/Model/Item.php
1654 function item_getfeedtags($item) {
1655         $ret = [];
1656         $matches = false;
1657         $cnt = preg_match_all('|\#\[url\=(.*?)\](.*?)\[\/url\]|', $item['tag'], $matches);
1658         if ($cnt) {
1659                 for ($x = 0; $x < $cnt; $x ++) {
1660                         if ($matches[1][$x]) {
1661                                 $ret[$matches[2][$x]] = ['#', $matches[1][$x], $matches[2][$x]];
1662                         }
1663                 }
1664         }
1665         $matches = false;
1666         $cnt = preg_match_all('|\@\[url\=(.*?)\](.*?)\[\/url\]|', $item['tag'], $matches);
1667         if ($cnt) {
1668                 for ($x = 0; $x < $cnt; $x ++) {
1669                         if ($matches[1][$x]) {
1670                                 $ret[] = ['@', $matches[1][$x], $matches[2][$x]];
1671                         }
1672                 }
1673         }
1674         return $ret;
1675 }
1676
1677 /// @TODO move to src/Model/Item.php
1678 function item_expire($uid, $days, $network = "", $force = false) {
1679
1680         if (!$uid || ($days < 1)) {
1681                 return;
1682         }
1683
1684         /*
1685          * $expire_network_only = save your own wall posts
1686          * and just expire conversations started by others
1687          */
1688         $expire_network_only = PConfig::get($uid,'expire', 'network_only');
1689         $sql_extra = (intval($expire_network_only) ? " AND wall = 0 " : "");
1690
1691         if ($network != "") {
1692                 $sql_extra .= sprintf(" AND network = '%s' ", dbesc($network));
1693
1694                 /*
1695                  * There is an index "uid_network_received" but not "uid_network_created"
1696                  * This avoids the creation of another index just for one purpose.
1697                  * And it doesn't really matter wether to look at "received" or "created"
1698                  */
1699                 $range = "AND `received` < UTC_TIMESTAMP() - INTERVAL %d DAY ";
1700         } else {
1701                 $range = "AND `created` < UTC_TIMESTAMP() - INTERVAL %d DAY ";
1702         }
1703
1704         $r = q("SELECT `file`, `resource-id`, `starred`, `type`, `id` FROM `item`
1705                 WHERE `uid` = %d $range
1706                 AND `id` = `parent`
1707                 $sql_extra
1708                 AND `deleted` = 0",
1709                 intval($uid),
1710                 intval($days)
1711         );
1712
1713         if (!DBM::is_result($r)) {
1714                 return;
1715         }
1716
1717         $expire_items = PConfig::get($uid, 'expire', 'items', 1);
1718
1719         // Forcing expiring of items - but not notes and marked items
1720         if ($force) {
1721                 $expire_items = true;
1722         }
1723
1724         $expire_notes = PConfig::get($uid, 'expire', 'notes', 1);
1725         $expire_starred = PConfig::get($uid, 'expire', 'starred', 1);
1726         $expire_photos = PConfig::get($uid, 'expire', 'photos', 0);
1727
1728         logger('User '.$uid.': expire: # items=' . count($r). "; expire items: $expire_items, expire notes: $expire_notes, expire starred: $expire_starred, expire photos: $expire_photos");
1729
1730         foreach ($r as $item) {
1731
1732                 // don't expire filed items
1733
1734                 if (strpos($item['file'],'[') !== false) {
1735                         continue;
1736                 }
1737
1738                 // Only expire posts, not photos and photo comments
1739
1740                 if ($expire_photos == 0 && strlen($item['resource-id'])) {
1741                         continue;
1742                 } elseif ($expire_starred == 0 && intval($item['starred'])) {
1743                         continue;
1744                 } elseif ($expire_notes == 0 && $item['type'] == 'note') {
1745                         continue;
1746                 } elseif ($expire_items == 0 && $item['type'] != 'note') {
1747                         continue;
1748                 }
1749
1750                 Item::delete($item['id'], PRIORITY_LOW);
1751         }
1752 }
1753
1754 /// @TODO type-hint is array
1755 /// @TODO move to ...
1756 function drop_items($items) {
1757         $uid = 0;
1758
1759         if (!local_user() && !remote_user()) {
1760                 return;
1761         }
1762
1763         if (count($items)) {
1764                 foreach ($items as $item) {
1765                         $owner = Item::delete($item);
1766                         if ($owner && ! $uid)
1767                                 $uid = $owner;
1768                 }
1769         }
1770 }
1771
1772 /// @TODO move to ...
1773 function drop_item($id) {
1774
1775         $a = get_app();
1776
1777         // locate item to be deleted
1778
1779         $r = q("SELECT * FROM `item` WHERE `id` = %d LIMIT 1",
1780                 intval($id)
1781         );
1782
1783         if (!DBM::is_result($r)) {
1784                 notice(L10n::t('Item not found.') . EOL);
1785                 goaway(System::baseUrl() . '/' . $_SESSION['return_url']);
1786         }
1787
1788         $item = $r[0];
1789
1790         if ($item['deleted']) {
1791                 return 0;
1792         }
1793
1794         $contact_id = 0;
1795
1796         // check if logged in user is either the author or owner of this item
1797
1798         if (is_array($_SESSION['remote'])) {
1799                 foreach ($_SESSION['remote'] as $visitor) {
1800                         if ($visitor['uid'] == $item['uid'] && $visitor['cid'] == $item['contact-id']) {
1801                                 $contact_id = $visitor['cid'];
1802                                 break;
1803                         }
1804                 }
1805         }
1806
1807         if ((local_user() == $item['uid']) || $contact_id) {
1808
1809                 // Check if we should do HTML-based delete confirmation
1810                 if ($_REQUEST['confirm']) {
1811                         // <form> can't take arguments in its "action" parameter
1812                         // so add any arguments as hidden inputs
1813                         $query = explode_querystring($a->query_string);
1814                         $inputs = [];
1815                         foreach ($query['args'] as $arg) {
1816                                 if (strpos($arg, 'confirm=') === false) {
1817                                         $arg_parts = explode('=', $arg);
1818                                         $inputs[] = ['name' => $arg_parts[0], 'value' => $arg_parts[1]];
1819                                 }
1820                         }
1821
1822                         return replace_macros(get_markup_template('confirm.tpl'), [
1823                                 '$method' => 'get',
1824                                 '$message' => L10n::t('Do you really want to delete this item?'),
1825                                 '$extra_inputs' => $inputs,
1826                                 '$confirm' => L10n::t('Yes'),
1827                                 '$confirm_url' => $query['base'],
1828                                 '$confirm_name' => 'confirmed',
1829                                 '$cancel' => L10n::t('Cancel'),
1830                         ]);
1831                 }
1832                 // Now check how the user responded to the confirmation query
1833                 if ($_REQUEST['canceled']) {
1834                         goaway(System::baseUrl() . '/' . $_SESSION['return_url']);
1835                 }
1836
1837                 // delete the item
1838                 Item::delete($item['id']);
1839
1840                 goaway(System::baseUrl() . '/' . $_SESSION['return_url']);
1841                 //NOTREACHED
1842         } else {
1843                 notice(L10n::t('Permission denied.') . EOL);
1844                 goaway(System::baseUrl() . '/' . $_SESSION['return_url']);
1845                 //NOTREACHED
1846         }
1847 }
1848
1849 /// @TODO: This query seems to be really slow
1850 /// @TODO move to src/Model/Item.php
1851 function first_post_date($uid, $wall = false) {
1852         $r = q("SELECT `id`, `created` FROM `item`
1853                 WHERE `uid` = %d AND `wall` = %d AND `deleted` = 0 AND `visible` = 1 AND `moderated` = 0
1854                 AND `id` = `parent`
1855                 ORDER BY `created` ASC LIMIT 1",
1856                 intval($uid),
1857                 intval($wall ? 1 : 0)
1858         );
1859         if (DBM::is_result($r)) {
1860                 // logger('first_post_date: ' . $r[0]['id'] . ' ' . $r[0]['created'], LOGGER_DATA);
1861                 return substr(datetime_convert('',date_default_timezone_get(), $r[0]['created']),0,10);
1862         }
1863         return false;
1864 }
1865
1866 /* arrange the list in years */
1867 /// @TODO move to src/Model/Item.php
1868 function list_post_dates($uid, $wall) {
1869         $dnow = datetime_convert('',date_default_timezone_get(), 'now','Y-m-d');
1870
1871         $dthen = first_post_date($uid, $wall);
1872         if (! $dthen) {
1873                 return [];
1874         }
1875
1876         // Set the start and end date to the beginning of the month
1877         $dnow = substr($dnow, 0, 8) . '01';
1878         $dthen = substr($dthen, 0, 8) . '01';
1879
1880         $ret = [];
1881
1882         /*
1883          * Starting with the current month, get the first and last days of every
1884          * month down to and including the month of the first post
1885          */
1886         while (substr($dnow, 0, 7) >= substr($dthen, 0, 7)) {
1887                 $dyear = intval(substr($dnow, 0, 4));
1888                 $dstart = substr($dnow, 0, 8) . '01';
1889                 $dend = substr($dnow, 0, 8) . get_dim(intval($dnow), intval(substr($dnow, 5)));
1890                 $start_month = datetime_convert('', '', $dstart, 'Y-m-d');
1891                 $end_month = datetime_convert('', '', $dend, 'Y-m-d');
1892                 $str = day_translate(datetime_convert('', '', $dnow, 'F'));
1893                 if (!$ret[$dyear]) {
1894                         $ret[$dyear] = [];
1895                 }
1896                 $ret[$dyear][] = [$str, $end_month, $start_month];
1897                 $dnow = datetime_convert('', '', $dnow . ' -1 month', 'Y-m-d');
1898         }
1899         return $ret;
1900 }
1901
1902 /// @TODO move to src/Model/Item.php
1903 function posted_date_widget($url, $uid, $wall) {
1904         $o = '';
1905
1906         if (! Feature::isEnabled($uid, 'archives')) {
1907                 return $o;
1908         }
1909
1910         // For former Facebook folks that left because of "timeline"
1911         /*
1912          * @TODO old-lost code?
1913         if ($wall && intval(PConfig::get($uid, 'system', 'no_wall_archive_widget')))
1914                 return $o;
1915         */
1916
1917         $visible_years = PConfig::get($uid,'system','archive_visible_years');
1918         if (! $visible_years) {
1919                 $visible_years = 5;
1920         }
1921
1922         $ret = list_post_dates($uid, $wall);
1923
1924         if (! DBM::is_result($ret)) {
1925                 return $o;
1926         }
1927
1928         $cutoff_year = intval(datetime_convert('',date_default_timezone_get(), 'now', 'Y')) - $visible_years;
1929         $cutoff = ((array_key_exists($cutoff_year, $ret))? true : false);
1930
1931         $o = replace_macros(get_markup_template('posted_date_widget.tpl'),[
1932                 '$title' => L10n::t('Archives'),
1933                 '$size' => $visible_years,
1934                 '$cutoff_year' => $cutoff_year,
1935                 '$cutoff' => $cutoff,
1936                 '$url' => $url,
1937                 '$dates' => $ret,
1938                 '$showmore' => L10n::t('show more')
1939
1940         ]);
1941         return $o;
1942 }