]> git.mxchange.org Git - friendica.git/blob - include/items.php
Birthdays are now transmitted reliably to Diaspora
[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\PConfig;
10 use Friendica\Core\Worker;
11 use Friendica\Core\System;
12 use Friendica\Database\DBM;
13 use Friendica\Model\Contact;
14 use Friendica\Model\GContact;
15 use Friendica\Model\Group;
16 use Friendica\Model\Term;
17 use Friendica\Model\User;
18 use Friendica\Model\Item;
19 use Friendica\Model\Conversation;
20 use Friendica\Object\Image;
21 use Friendica\Protocol\DFRN;
22 use Friendica\Protocol\OStatus;
23 use Friendica\Protocol\Feed;
24 use Friendica\Util\ParseUrl;
25
26 require_once 'include/bbcode.php';
27 require_once 'include/tags.php';
28 require_once 'include/text.php';
29 require_once 'include/threads.php';
30 require_once 'include/plaintext.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 // return - test
1076 /// @TODO move to src/Model/Item.php
1077 function get_item_contact($item, $contacts) {
1078         if (! count($contacts) || (! is_array($item))) {
1079                 return false;
1080         }
1081         foreach ($contacts as $contact) {
1082                 if ($contact['id'] == $item['contact-id']) {
1083                         return $contact;
1084                 }
1085         }
1086         return false;
1087 }
1088
1089 /**
1090  * look for mention tags and setup a second delivery chain for forum/community posts if appropriate
1091  * @param int $uid
1092  * @param int $item_id
1093  * @return bool true if item was deleted, else false
1094  */
1095 /// @TODO move to src/Model/Item.php
1096 function tag_deliver($uid, $item_id)
1097 {
1098         $mention = false;
1099
1100         $u = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
1101                 intval($uid)
1102         );
1103         if (! DBM::is_result($u)) {
1104                 return;
1105         }
1106
1107         $community_page = (($u[0]['page-flags'] == PAGE_COMMUNITY) ? true : false);
1108         $prvgroup = (($u[0]['page-flags'] == PAGE_PRVGROUP) ? true : false);
1109
1110         $i = q("SELECT * FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1",
1111                 intval($item_id),
1112                 intval($uid)
1113         );
1114         if (! DBM::is_result($i)) {
1115                 return;
1116         }
1117
1118         $item = $i[0];
1119
1120         $link = normalise_link(System::baseUrl() . '/profile/' . $u[0]['nickname']);
1121
1122         /*
1123          * Diaspora uses their own hardwired link URL in @-tags
1124          * instead of the one we supply with webfinger
1125          */
1126         $dlink = normalise_link(System::baseUrl() . '/u/' . $u[0]['nickname']);
1127
1128         $cnt = preg_match_all('/[\@\!]\[url\=(.*?)\](.*?)\[\/url\]/ism', $item['body'], $matches, PREG_SET_ORDER);
1129         if ($cnt) {
1130                 foreach ($matches as $mtch) {
1131                         if (link_compare($link, $mtch[1]) || link_compare($dlink, $mtch[1])) {
1132                                 $mention = true;
1133                                 logger('tag_deliver: mention found: ' . $mtch[2]);
1134                         }
1135                 }
1136         }
1137
1138         if (! $mention) {
1139                 if (($community_page || $prvgroup) &&
1140                           (!$item['wall']) && (!$item['origin']) && ($item['id'] == $item['parent'])) {
1141                         // mmh.. no mention.. community page or private group... no wall.. no origin.. top-post (not a comment)
1142                         // delete it!
1143                         logger("tag_deliver: no-mention top-level post to communuty or private group. delete.");
1144                         dba::delete('item', ['id' => $item_id]);
1145                         return true;
1146                 }
1147                 return;
1148         }
1149
1150         $arr = ['item' => $item, 'user' => $u[0], 'contact' => $r[0]];
1151
1152         Addon::callHooks('tagged', $arr);
1153
1154         if ((! $community_page) && (! $prvgroup)) {
1155                 return;
1156         }
1157
1158         /*
1159          * tgroup delivery - setup a second delivery chain
1160          * prevent delivery looping - only proceed
1161          * if the message originated elsewhere and is a top-level post
1162          */
1163         if (($item['wall']) || ($item['origin']) || ($item['id'] != $item['parent'])) {
1164                 return;
1165         }
1166
1167         // now change this copy of the post to a forum head message and deliver to all the tgroup members
1168         $c = q("SELECT `name`, `url`, `thumb` FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
1169                 intval($u[0]['uid'])
1170         );
1171         if (! DBM::is_result($c)) {
1172                 return;
1173         }
1174
1175         // also reset all the privacy bits to the forum default permissions
1176
1177         $private = ($u[0]['allow_cid'] || $u[0]['allow_gid'] || $u[0]['deny_cid'] || $u[0]['deny_gid']) ? 1 : 0;
1178
1179         $forum_mode = (($prvgroup) ? 2 : 1);
1180
1181         q("UPDATE `item` SET `wall` = 1, `origin` = 1, `forum_mode` = %d, `owner-name` = '%s', `owner-link` = '%s', `owner-avatar` = '%s',
1182                 `private` = %d, `allow_cid` = '%s', `allow_gid` = '%s', `deny_cid` = '%s', `deny_gid` = '%s'  WHERE `id` = %d",
1183                 intval($forum_mode),
1184                 dbesc($c[0]['name']),
1185                 dbesc($c[0]['url']),
1186                 dbesc($c[0]['thumb']),
1187                 intval($private),
1188                 dbesc($u[0]['allow_cid']),
1189                 dbesc($u[0]['allow_gid']),
1190                 dbesc($u[0]['deny_cid']),
1191                 dbesc($u[0]['deny_gid']),
1192                 intval($item_id)
1193         );
1194         update_thread($item_id);
1195
1196         Worker::add(['priority' => PRIORITY_HIGH, 'dont_fork' => true], 'Notifier', 'tgroup', $item_id);
1197
1198 }
1199
1200 /// @TODO move to src/Protocol/DFRN.php
1201 function tgroup_check($uid, $item) {
1202
1203         $mention = false;
1204
1205         // check that the message originated elsewhere and is a top-level post
1206
1207         if (($item['wall']) || ($item['origin']) || ($item['uri'] != $item['parent-uri'])) {
1208                 return false;
1209         }
1210
1211         /// @TODO Encapsulate this or find it encapsulated and replace all occurrances
1212         $u = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
1213                 intval($uid)
1214         );
1215         if (! DBM::is_result($u)) {
1216                 return false;
1217         }
1218
1219         $community_page = (($u[0]['page-flags'] == PAGE_COMMUNITY) ? true : false);
1220         $prvgroup = (($u[0]['page-flags'] == PAGE_PRVGROUP) ? true : false);
1221
1222         $link = normalise_link(System::baseUrl() . '/profile/' . $u[0]['nickname']);
1223
1224         /*
1225          * Diaspora uses their own hardwired link URL in @-tags
1226          * instead of the one we supply with webfinger
1227          */
1228         $dlink = normalise_link(System::baseUrl() . '/u/' . $u[0]['nickname']);
1229
1230         $cnt = preg_match_all('/[\@\!]\[url\=(.*?)\](.*?)\[\/url\]/ism', $item['body'], $matches, PREG_SET_ORDER);
1231         if ($cnt) {
1232                 foreach ($matches as $mtch) {
1233                         if (link_compare($link, $mtch[1]) || link_compare($dlink, $mtch[1])) {
1234                                 $mention = true;
1235                                 logger('tgroup_check: mention found: ' . $mtch[2]);
1236                         }
1237                 }
1238         }
1239
1240         if (! $mention) {
1241                 return false;
1242         }
1243
1244         /// @TODO Combine both return statements into one
1245         return (($community_page) || ($prvgroup));
1246 }
1247
1248 /**
1249  * This function returns true if $update has an edited timestamp newer
1250  * than $existing, i.e. $update contains new data which should override
1251  * what's already there.  If there is no timestamp yet, the update is
1252  * assumed to be newer.  If the update has no timestamp, the existing
1253  * item is assumed to be up-to-date.  If the timestamps are equal it
1254  * assumes the update has been seen before and should be ignored.
1255  *
1256  * @TODO fix type-hints (both array)
1257  */
1258 /// @TODO move to src/Protocol/DFRN.php
1259 function edited_timestamp_is_newer($existing, $update) {
1260         if (!x($existing, 'edited') || !$existing['edited']) {
1261                 return true;
1262         }
1263         if (!x($update, 'edited') || !$update['edited']) {
1264                 return false;
1265         }
1266
1267         $existing_edited = datetime_convert('UTC', 'UTC', $existing['edited']);
1268         $update_edited = datetime_convert('UTC', 'UTC', $update['edited']);
1269         return (strcmp($existing_edited, $update_edited) < 0);
1270 }
1271
1272 /**
1273  *
1274  * consume_feed - process atom feed and update anything/everything we might need to update
1275  *
1276  * $xml = the (atom) feed to consume - RSS isn't as fully supported but may work for simple feeds.
1277  *
1278  * $importer = the contact_record (joined to user_record) of the local user who owns this relationship.
1279  *             It is this person's stuff that is going to be updated.
1280  * $contact =  the person who is sending us stuff. If not set, we MAY be processing a "follow" activity
1281  *             from an external network and MAY create an appropriate contact record. Otherwise, we MUST
1282  *             have a contact record.
1283  * $hub = should we find a hub declation in the feed, pass it back to our calling process, who might (or
1284  *        might not) try and subscribe to it.
1285  * $datedir sorts in reverse order
1286  * $pass - by default ($pass = 0) we cannot guarantee that a parent item has been
1287  *      imported prior to its children being seen in the stream unless we are certain
1288  *      of how the feed is arranged/ordered.
1289  * With $pass = 1, we only pull parent items out of the stream.
1290  * With $pass = 2, we only pull children (comments/likes).
1291  *
1292  * So running this twice, first with pass 1 and then with pass 2 will do the right
1293  * thing regardless of feed ordering. This won't be adequate in a fully-threaded
1294  * model where comments can have sub-threads. That would require some massive sorting
1295  * to get all the feed items into a mostly linear ordering, and might still require
1296  * recursion.
1297  *
1298  * @TODO find proper type-hints
1299  */
1300 /// @TODO move to ???
1301 function consume_feed($xml, $importer, &$contact, &$hub, $datedir = 0, $pass = 0) {
1302         if ($contact['network'] === NETWORK_OSTATUS) {
1303                 if ($pass < 2) {
1304                         // Test - remove before flight
1305                         //$tempfile = tempnam(get_temppath(), "ostatus2");
1306                         //file_put_contents($tempfile, $xml);
1307                         logger("Consume OStatus messages ", LOGGER_DEBUG);
1308                         OStatus::import($xml, $importer, $contact, $hub);
1309                 }
1310                 return;
1311         }
1312
1313         if ($contact['network'] === NETWORK_FEED) {
1314                 if ($pass < 2) {
1315                         logger("Consume feeds", LOGGER_DEBUG);
1316                         Feed::import($xml, $importer, $contact, $hub);
1317                 }
1318                 return;
1319         }
1320
1321         if ($contact['network'] === NETWORK_DFRN) {
1322                 logger("Consume DFRN messages", LOGGER_DEBUG);
1323
1324                 $r = q("SELECT `contact`.*, `contact`.`uid` AS `importer_uid`,
1325                                         `contact`.`pubkey` AS `cpubkey`,
1326                                         `contact`.`prvkey` AS `cprvkey`,
1327                                         `contact`.`thumb` AS `thumb`,
1328                                         `contact`.`url` as `url`,
1329                                         `contact`.`name` as `senderName`,
1330                                         `user`.*
1331                         FROM `contact`
1332                         LEFT JOIN `user` ON `contact`.`uid` = `user`.`uid`
1333                         WHERE `contact`.`id` = %d AND `user`.`uid` = %d",
1334                         dbesc($contact["id"]), dbesc($importer["uid"])
1335                 );
1336                 if (DBM::is_result($r)) {
1337                         logger("Now import the DFRN feed");
1338                         DFRN::import($xml, $r[0], true);
1339                         return;
1340                 }
1341         }
1342 }
1343
1344 /// @TODO type-hint is array
1345 /// @TODO move to src/Model/Item.php
1346 function item_is_remote_self($contact, &$datarray) {
1347         $a = get_app();
1348
1349         if (!$contact['remote_self']) {
1350                 return false;
1351         }
1352
1353         // Prevent the forwarding of posts that are forwarded
1354         if ($datarray["extid"] == NETWORK_DFRN) {
1355                 return false;
1356         }
1357
1358         // Prevent to forward already forwarded posts
1359         if ($datarray["app"] == $a->get_hostname()) {
1360                 return false;
1361         }
1362
1363         // Only forward posts
1364         if ($datarray["verb"] != ACTIVITY_POST) {
1365                 return false;
1366         }
1367
1368         if (($contact['network'] != NETWORK_FEED) && $datarray['private']) {
1369                 return false;
1370         }
1371
1372         $datarray2 = $datarray;
1373         logger('remote-self start - Contact '.$contact['url'].' - '.$contact['remote_self'].' Item '.print_r($datarray, true), LOGGER_DEBUG);
1374         if ($contact['remote_self'] == 2) {
1375                 $r = q("SELECT `id`,`url`,`name`,`thumb` FROM `contact` WHERE `uid` = %d AND `self`",
1376                         intval($contact['uid']));
1377                 if (DBM::is_result($r)) {
1378                         $datarray['contact-id'] = $r[0]["id"];
1379
1380                         $datarray['owner-name'] = $r[0]["name"];
1381                         $datarray['owner-link'] = $r[0]["url"];
1382                         $datarray['owner-avatar'] = $r[0]["thumb"];
1383
1384                         $datarray['author-name']   = $datarray['owner-name'];
1385                         $datarray['author-link']   = $datarray['owner-link'];
1386                         $datarray['author-avatar'] = $datarray['owner-avatar'];
1387
1388                         unset($datarray['created']);
1389                         unset($datarray['edited']);
1390                 }
1391
1392                 if ($contact['network'] != NETWORK_FEED) {
1393                         $datarray["guid"] = get_guid(32);
1394                         unset($datarray["plink"]);
1395                         $datarray["uri"] = item_new_uri($a->get_hostname(), $contact['uid'], $datarray["guid"]);
1396                         $datarray["parent-uri"] = $datarray["uri"];
1397                         $datarray["extid"] = $contact['network'];
1398                         $urlpart = parse_url($datarray2['author-link']);
1399                         $datarray["app"] = $urlpart["host"];
1400                 } else {
1401                         $datarray['private'] = 0;
1402                 }
1403         }
1404
1405         if ($contact['network'] != NETWORK_FEED) {
1406                 // Store the original post
1407                 $r = item_store($datarray2, false, false);
1408                 logger('remote-self post original item - Contact '.$contact['url'].' return '.$r.' Item '.print_r($datarray2, true), LOGGER_DEBUG);
1409         } else {
1410                 $datarray["app"] = "Feed";
1411         }
1412
1413         // Trigger automatic reactions for addons
1414         $datarray['api_source'] = true;
1415
1416         // We have to tell the hooks who we are - this really should be improved
1417         $_SESSION["authenticated"] = true;
1418         $_SESSION["uid"] = $contact['uid'];
1419
1420         return true;
1421 }
1422
1423 /// @TODO find proper type-hints
1424 /// @TODO move to src/Model/Item.php
1425 function new_follower($importer, $contact, $datarray, $item, $sharing = false) {
1426         $url = notags(trim($datarray['author-link']));
1427         $name = notags(trim($datarray['author-name']));
1428         $photo = notags(trim($datarray['author-avatar']));
1429
1430         if (is_object($item)) {
1431                 $rawtag = $item->get_item_tags(NAMESPACE_ACTIVITY,'actor');
1432                 if ($rawtag && $rawtag[0]['child'][NAMESPACE_POCO]['preferredUsername'][0]['data']) {
1433                         $nick = $rawtag[0]['child'][NAMESPACE_POCO]['preferredUsername'][0]['data'];
1434                 }
1435         } else {
1436                 $nick = $item;
1437         }
1438
1439         if (is_array($contact)) {
1440                 if (($contact['network'] == NETWORK_OSTATUS && $contact['rel'] == CONTACT_IS_SHARING)
1441                         || ($sharing && $contact['rel'] == CONTACT_IS_FOLLOWER)) {
1442                         dba::update('contact', ['rel' => CONTACT_IS_FRIEND, 'writable' => true],
1443                                         ['id' => $contact['id'], 'uid' => $importer['uid']]);
1444                 }
1445                 // send email notification to owner?
1446         } else {
1447                 // create contact record
1448                 q("INSERT INTO `contact` (`uid`, `created`, `url`, `nurl`, `name`, `nick`, `photo`, `network`, `rel`,
1449                         `blocked`, `readonly`, `pending`, `writable`)
1450                         VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, 0, 0, 1, 1)",
1451                         intval($importer['uid']),
1452                         dbesc(datetime_convert()),
1453                         dbesc($url),
1454                         dbesc(normalise_link($url)),
1455                         dbesc($name),
1456                         dbesc($nick),
1457                         dbesc($photo),
1458                         dbesc(NETWORK_OSTATUS),
1459                         intval(CONTACT_IS_FOLLOWER)
1460                 );
1461
1462                 $r = q("SELECT `id`, `network` FROM `contact` WHERE `uid` = %d AND `url` = '%s' AND `pending` = 1 LIMIT 1",
1463                                 intval($importer['uid']),
1464                                 dbesc($url)
1465                 );
1466                 if (DBM::is_result($r)) {
1467                         $contact_record = $r[0];
1468                         Contact::updateAvatar($photo, $importer["uid"], $contact_record["id"], true);
1469                 }
1470
1471                 /// @TODO Encapsulate this into a function/method
1472                 $r = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
1473                         intval($importer['uid'])
1474                 );
1475                 if (DBM::is_result($r) && !in_array($r[0]['page-flags'], [PAGE_SOAPBOX, PAGE_FREELOVE, PAGE_COMMUNITY])) {
1476                         // create notification
1477                         $hash = random_string();
1478
1479                         if (is_array($contact_record)) {
1480                                 dba::insert('intro', ['uid' => $importer['uid'], 'contact-id' => $contact_record['id'],
1481                                                         'blocked' => false, 'knowyou' => false,
1482                                                         'hash' => $hash, 'datetime' => datetime_convert()]);
1483                         }
1484
1485                         Group::addMember(User::getDefaultGroup($importer['uid'], $contact_record["network"]), $contact_record['id']);
1486
1487                         if (($r[0]['notify-flags'] & NOTIFY_INTRO) &&
1488                                 in_array($r[0]['page-flags'], [PAGE_NORMAL])) {
1489
1490                                 notification([
1491                                         'type'         => NOTIFY_INTRO,
1492                                         'notify_flags' => $r[0]['notify-flags'],
1493                                         'language'     => $r[0]['language'],
1494                                         'to_name'      => $r[0]['username'],
1495                                         'to_email'     => $r[0]['email'],
1496                                         'uid'          => $r[0]['uid'],
1497                                         'link'             => System::baseUrl() . '/notifications/intro',
1498                                         'source_name'  => ((strlen(stripslashes($contact_record['name']))) ? stripslashes($contact_record['name']) : t('[Name Withheld]')),
1499                                         'source_link'  => $contact_record['url'],
1500                                         'source_photo' => $contact_record['photo'],
1501                                         'verb'         => ($sharing ? ACTIVITY_FRIEND : ACTIVITY_FOLLOW),
1502                                         'otype'        => 'intro'
1503                                 ]);
1504
1505                         }
1506                 } elseif (DBM::is_result($r) && in_array($r[0]['page-flags'], [PAGE_SOAPBOX, PAGE_FREELOVE, PAGE_COMMUNITY])) {
1507                         q("UPDATE `contact` SET `pending` = 0 WHERE `uid` = %d AND `url` = '%s' AND `pending` LIMIT 1",
1508                                         intval($importer['uid']),
1509                                         dbesc($url)
1510                         );
1511                 }
1512
1513         }
1514 }
1515
1516 /// @TODO move to src/Model/Item.php
1517 function lose_follower($importer, $contact, array $datarray = [], $item = "") {
1518
1519         if (($contact['rel'] == CONTACT_IS_FRIEND) || ($contact['rel'] == CONTACT_IS_SHARING)) {
1520                 dba::update('contact', ['rel' => CONTACT_IS_SHARING], ['id' => $contact['id']]);
1521         } else {
1522                 Contact::remove($contact['id']);
1523         }
1524 }
1525
1526 /// @TODO move to src/Model/Item.php
1527 function lose_sharer($importer, $contact, array $datarray = [], $item = "") {
1528
1529         if (($contact['rel'] == CONTACT_IS_FRIEND) || ($contact['rel'] == CONTACT_IS_FOLLOWER)) {
1530                 dba::update('contact', ['rel' => CONTACT_IS_FOLLOWER], ['id' => $contact['id']]);
1531         } else {
1532                 Contact::remove($contact['id']);
1533         }
1534 }
1535
1536 /// @TODO move to ???
1537 function subscribe_to_hub($url, $importer, $contact, $hubmode = 'subscribe') {
1538
1539         $a = get_app();
1540
1541         if (is_array($importer)) {
1542                 $r = q("SELECT `nickname` FROM `user` WHERE `uid` = %d LIMIT 1",
1543                         intval($importer['uid'])
1544                 );
1545         }
1546
1547         /*
1548          * Diaspora has different message-ids in feeds than they do
1549          * through the direct Diaspora protocol. If we try and use
1550          * the feed, we'll get duplicates. So don't.
1551          */
1552         if ((! DBM::is_result($r)) || $contact['network'] === NETWORK_DIASPORA) {
1553                 return;
1554         }
1555
1556         $push_url = Config::get('system','url') . '/pubsub/' . $r[0]['nickname'] . '/' . $contact['id'];
1557
1558         // Use a single verify token, even if multiple hubs
1559         $verify_token = ((strlen($contact['hub-verify'])) ? $contact['hub-verify'] : random_string());
1560
1561         $params= 'hub.mode=' . $hubmode . '&hub.callback=' . urlencode($push_url) . '&hub.topic=' . urlencode($contact['poll']) . '&hub.verify=async&hub.verify_token=' . $verify_token;
1562
1563         logger('subscribe_to_hub: ' . $hubmode . ' ' . $contact['name'] . ' to hub ' . $url . ' endpoint: '  . $push_url . ' with verifier ' . $verify_token);
1564
1565         if (!strlen($contact['hub-verify']) || ($contact['hub-verify'] != $verify_token)) {
1566                 dba::update('contact', ['hub-verify' => $verify_token], ['id' => $contact['id']]);
1567         }
1568
1569         post_url($url, $params);
1570
1571         logger('subscribe_to_hub: returns: ' . $a->get_curl_code(), LOGGER_DEBUG);
1572
1573         return;
1574
1575 }
1576
1577 /**
1578  *
1579  * @param string $s
1580  * @param int    $uid
1581  * @param array  $item
1582  * @param int    $cid
1583  * @return string
1584  */
1585 /// @TODO move to src/Model/Item.php
1586 function fix_private_photos($s, $uid, $item = null, $cid = 0)
1587 {
1588         if (Config::get('system', 'disable_embedded')) {
1589                 return $s;
1590         }
1591
1592         logger('fix_private_photos: check for photos', LOGGER_DEBUG);
1593         $site = substr(System::baseUrl(), strpos(System::baseUrl(), '://'));
1594
1595         $orig_body = $s;
1596         $new_body = '';
1597
1598         $img_start = strpos($orig_body, '[img');
1599         $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
1600         $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
1601
1602         while (($img_st_close !== false) && ($img_len !== false)) {
1603                 $img_st_close++; // make it point to AFTER the closing bracket
1604                 $image = substr($orig_body, $img_start + $img_st_close, $img_len);
1605
1606                 logger('fix_private_photos: found photo ' . $image, LOGGER_DEBUG);
1607
1608                 if (stristr($image, $site . '/photo/')) {
1609                         // Only embed locally hosted photos
1610                         $replace = false;
1611                         $i = basename($image);
1612                         $i = str_replace(['.jpg', '.png', '.gif'], ['', '', ''], $i);
1613                         $x = strpos($i, '-');
1614
1615                         if ($x) {
1616                                 $res = substr($i, $x + 1);
1617                                 $i = substr($i, 0, $x);
1618                                 $r = q("SELECT * FROM `photo` WHERE `resource-id` = '%s' AND `scale` = %d AND `uid` = %d",
1619                                         dbesc($i),
1620                                         intval($res),
1621                                         intval($uid)
1622                                 );
1623                                 if (DBM::is_result($r)) {
1624                                         /*
1625                                          * Check to see if we should replace this photo link with an embedded image
1626                                          * 1. No need to do so if the photo is public
1627                                          * 2. If there's a contact-id provided, see if they're in the access list
1628                                          *    for the photo. If so, embed it.
1629                                          * 3. Otherwise, if we have an item, see if the item permissions match the photo
1630                                          *    permissions, regardless of order but first check to see if they're an exact
1631                                          *    match to save some processing overhead.
1632                                          */
1633                                         if (has_permissions($r[0])) {
1634                                                 if ($cid) {
1635                                                         $recips = enumerate_permissions($r[0]);
1636                                                         if (in_array($cid, $recips)) {
1637                                                                 $replace = true;
1638                                                         }
1639                                                 } elseif ($item) {
1640                                                         if (compare_permissions($item, $r[0])) {
1641                                                                 $replace = true;
1642                                                         }
1643                                                 }
1644                                         }
1645                                         if ($replace) {
1646                                                 $data = $r[0]['data'];
1647                                                 $type = $r[0]['type'];
1648
1649                                                 // If a custom width and height were specified, apply before embedding
1650                                                 if (preg_match("/\[img\=([0-9]*)x([0-9]*)\]/is", substr($orig_body, $img_start, $img_st_close), $match)) {
1651                                                         logger('fix_private_photos: scaling photo', LOGGER_DEBUG);
1652
1653                                                         $width = intval($match[1]);
1654                                                         $height = intval($match[2]);
1655
1656                                                         $Image = new Image($data, $type);
1657                                                         if ($Image->isValid()) {
1658                                                                 $Image->scaleDown(max($width, $height));
1659                                                                 $data = $Image->asString();
1660                                                                 $type = $Image->getType();
1661                                                         }
1662                                                 }
1663
1664                                                 logger('fix_private_photos: replacing photo', LOGGER_DEBUG);
1665                                                 $image = 'data:' . $type . ';base64,' . base64_encode($data);
1666                                                 logger('fix_private_photos: replaced: ' . $image, LOGGER_DATA);
1667                                         }
1668                                 }
1669                         }
1670                 }
1671
1672                 $new_body = $new_body . substr($orig_body, 0, $img_start + $img_st_close) . $image . '[/img]';
1673                 $orig_body = substr($orig_body, $img_start + $img_st_close + $img_len + strlen('[/img]'));
1674                 if ($orig_body === false) {
1675                         $orig_body = '';
1676                 }
1677
1678                 $img_start = strpos($orig_body, '[img');
1679                 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
1680                 $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
1681         }
1682
1683         $new_body = $new_body . $orig_body;
1684
1685         return $new_body;
1686 }
1687
1688 /// @TODO type-hint is array
1689 /// @TODO move to src/Model/Item.php
1690 function has_permissions($obj) {
1691         return (
1692                 (
1693                         x($obj, 'allow_cid')
1694                 ) || (
1695                         x($obj, 'allow_gid')
1696                 ) || (
1697                         x($obj, 'deny_cid')
1698                 ) || (
1699                         x($obj, 'deny_gid')
1700                 )
1701         );
1702 }
1703
1704 /// @TODO type-hint is array
1705 /// @TODO move to src/Model/Item.php
1706 function compare_permissions($obj1, $obj2) {
1707         // first part is easy. Check that these are exactly the same.
1708         if (($obj1['allow_cid'] == $obj2['allow_cid'])
1709                 && ($obj1['allow_gid'] == $obj2['allow_gid'])
1710                 && ($obj1['deny_cid'] == $obj2['deny_cid'])
1711                 && ($obj1['deny_gid'] == $obj2['deny_gid'])) {
1712                 return true;
1713         }
1714
1715         // This is harder. Parse all the permissions and compare the resulting set.
1716         $recipients1 = enumerate_permissions($obj1);
1717         $recipients2 = enumerate_permissions($obj2);
1718         sort($recipients1);
1719         sort($recipients2);
1720
1721         /// @TODO Comparison of arrays, maybe use array_diff_assoc() here?
1722         return ($recipients1 == $recipients2);
1723 }
1724
1725 // returns an array of contact-ids that are allowed to see this object
1726 /// @TODO type-hint is array
1727 /// @TODO move to src/Model/Item.php
1728 function enumerate_permissions($obj) {
1729         $allow_people = expand_acl($obj['allow_cid']);
1730         $allow_groups = Group::expand(expand_acl($obj['allow_gid']));
1731         $deny_people  = expand_acl($obj['deny_cid']);
1732         $deny_groups  = Group::expand(expand_acl($obj['deny_gid']));
1733         $recipients   = array_unique(array_merge($allow_people, $allow_groups));
1734         $deny         = array_unique(array_merge($deny_people, $deny_groups));
1735         $recipients   = array_diff($recipients, $deny);
1736         return $recipients;
1737 }
1738
1739 /// @TODO move to src/Model/Item.php
1740 function item_getfeedtags($item) {
1741         $ret = [];
1742         $matches = false;
1743         $cnt = preg_match_all('|\#\[url\=(.*?)\](.*?)\[\/url\]|', $item['tag'], $matches);
1744         if ($cnt) {
1745                 for ($x = 0; $x < $cnt; $x ++) {
1746                         if ($matches[1][$x]) {
1747                                 $ret[$matches[2][$x]] = ['#', $matches[1][$x], $matches[2][$x]];
1748                         }
1749                 }
1750         }
1751         $matches = false;
1752         $cnt = preg_match_all('|\@\[url\=(.*?)\](.*?)\[\/url\]|', $item['tag'], $matches);
1753         if ($cnt) {
1754                 for ($x = 0; $x < $cnt; $x ++) {
1755                         if ($matches[1][$x]) {
1756                                 $ret[] = ['@', $matches[1][$x], $matches[2][$x]];
1757                         }
1758                 }
1759         }
1760         return $ret;
1761 }
1762
1763 /// @TODO move to src/Model/Item.php
1764 function item_expire($uid, $days, $network = "", $force = false) {
1765
1766         if (!$uid || ($days < 1)) {
1767                 return;
1768         }
1769
1770         /*
1771          * $expire_network_only = save your own wall posts
1772          * and just expire conversations started by others
1773          */
1774         $expire_network_only = PConfig::get($uid,'expire', 'network_only');
1775         $sql_extra = (intval($expire_network_only) ? " AND wall = 0 " : "");
1776
1777         if ($network != "") {
1778                 $sql_extra .= sprintf(" AND network = '%s' ", dbesc($network));
1779
1780                 /*
1781                  * There is an index "uid_network_received" but not "uid_network_created"
1782                  * This avoids the creation of another index just for one purpose.
1783                  * And it doesn't really matter wether to look at "received" or "created"
1784                  */
1785                 $range = "AND `received` < UTC_TIMESTAMP() - INTERVAL %d DAY ";
1786         } else {
1787                 $range = "AND `created` < UTC_TIMESTAMP() - INTERVAL %d DAY ";
1788         }
1789
1790         $r = q("SELECT `file`, `resource-id`, `starred`, `type`, `id` FROM `item`
1791                 WHERE `uid` = %d $range
1792                 AND `id` = `parent`
1793                 $sql_extra
1794                 AND `deleted` = 0",
1795                 intval($uid),
1796                 intval($days)
1797         );
1798
1799         if (!DBM::is_result($r)) {
1800                 return;
1801         }
1802
1803         $expire_items = PConfig::get($uid, 'expire', 'items', 1);
1804
1805         // Forcing expiring of items - but not notes and marked items
1806         if ($force) {
1807                 $expire_items = true;
1808         }
1809
1810         $expire_notes = PConfig::get($uid, 'expire', 'notes', 1);
1811         $expire_starred = PConfig::get($uid, 'expire', 'starred', 1);
1812         $expire_photos = PConfig::get($uid, 'expire', 'photos', 0);
1813
1814         logger('User '.$uid.': expire: # items=' . count($r). "; expire items: $expire_items, expire notes: $expire_notes, expire starred: $expire_starred, expire photos: $expire_photos");
1815
1816         foreach ($r as $item) {
1817
1818                 // don't expire filed items
1819
1820                 if (strpos($item['file'],'[') !== false) {
1821                         continue;
1822                 }
1823
1824                 // Only expire posts, not photos and photo comments
1825
1826                 if ($expire_photos == 0 && strlen($item['resource-id'])) {
1827                         continue;
1828                 } elseif ($expire_starred == 0 && intval($item['starred'])) {
1829                         continue;
1830                 } elseif ($expire_notes == 0 && $item['type'] == 'note') {
1831                         continue;
1832                 } elseif ($expire_items == 0 && $item['type'] != 'note') {
1833                         continue;
1834                 }
1835
1836                 Item::delete($item['id'], PRIORITY_LOW);
1837         }
1838 }
1839
1840 /// @TODO type-hint is array
1841 /// @TODO move to ...
1842 function drop_items($items) {
1843         $uid = 0;
1844
1845         if (!local_user() && !remote_user()) {
1846                 return;
1847         }
1848
1849         if (count($items)) {
1850                 foreach ($items as $item) {
1851                         $owner = Item::delete($item);
1852                         if ($owner && ! $uid)
1853                                 $uid = $owner;
1854                 }
1855         }
1856 }
1857
1858 /// @TODO move to ...
1859 function drop_item($id) {
1860
1861         $a = get_app();
1862
1863         // locate item to be deleted
1864
1865         $r = q("SELECT * FROM `item` WHERE `id` = %d LIMIT 1",
1866                 intval($id)
1867         );
1868
1869         if (!DBM::is_result($r)) {
1870                 notice(t('Item not found.') . EOL);
1871                 goaway(System::baseUrl() . '/' . $_SESSION['return_url']);
1872         }
1873
1874         $item = $r[0];
1875
1876         if ($item['deleted']) {
1877                 return 0;
1878         }
1879
1880         $contact_id = 0;
1881
1882         // check if logged in user is either the author or owner of this item
1883
1884         if (is_array($_SESSION['remote'])) {
1885                 foreach ($_SESSION['remote'] as $visitor) {
1886                         if ($visitor['uid'] == $item['uid'] && $visitor['cid'] == $item['contact-id']) {
1887                                 $contact_id = $visitor['cid'];
1888                                 break;
1889                         }
1890                 }
1891         }
1892
1893         if ((local_user() == $item['uid']) || $contact_id) {
1894
1895                 // Check if we should do HTML-based delete confirmation
1896                 if ($_REQUEST['confirm']) {
1897                         // <form> can't take arguments in its "action" parameter
1898                         // so add any arguments as hidden inputs
1899                         $query = explode_querystring($a->query_string);
1900                         $inputs = [];
1901                         foreach ($query['args'] as $arg) {
1902                                 if (strpos($arg, 'confirm=') === false) {
1903                                         $arg_parts = explode('=', $arg);
1904                                         $inputs[] = ['name' => $arg_parts[0], 'value' => $arg_parts[1]];
1905                                 }
1906                         }
1907
1908                         return replace_macros(get_markup_template('confirm.tpl'), [
1909                                 '$method' => 'get',
1910                                 '$message' => t('Do you really want to delete this item?'),
1911                                 '$extra_inputs' => $inputs,
1912                                 '$confirm' => t('Yes'),
1913                                 '$confirm_url' => $query['base'],
1914                                 '$confirm_name' => 'confirmed',
1915                                 '$cancel' => t('Cancel'),
1916                         ]);
1917                 }
1918                 // Now check how the user responded to the confirmation query
1919                 if ($_REQUEST['canceled']) {
1920                         goaway(System::baseUrl() . '/' . $_SESSION['return_url']);
1921                 }
1922
1923                 // delete the item
1924                 Item::delete($item['id']);
1925
1926                 goaway(System::baseUrl() . '/' . $_SESSION['return_url']);
1927                 //NOTREACHED
1928         } else {
1929                 notice(t('Permission denied.') . EOL);
1930                 goaway(System::baseUrl() . '/' . $_SESSION['return_url']);
1931                 //NOTREACHED
1932         }
1933 }
1934
1935 /// @TODO: This query seems to be really slow
1936 /// @TODO move to src/Model/Item.php
1937 function first_post_date($uid, $wall = false) {
1938         $r = q("SELECT `id`, `created` FROM `item`
1939                 WHERE `uid` = %d AND `wall` = %d AND `deleted` = 0 AND `visible` = 1 AND `moderated` = 0
1940                 AND `id` = `parent`
1941                 ORDER BY `created` ASC LIMIT 1",
1942                 intval($uid),
1943                 intval($wall ? 1 : 0)
1944         );
1945         if (DBM::is_result($r)) {
1946                 // logger('first_post_date: ' . $r[0]['id'] . ' ' . $r[0]['created'], LOGGER_DATA);
1947                 return substr(datetime_convert('',date_default_timezone_get(), $r[0]['created']),0,10);
1948         }
1949         return false;
1950 }
1951
1952 /* arrange the list in years */
1953 /// @TODO move to src/Model/Item.php
1954 function list_post_dates($uid, $wall) {
1955         $dnow = datetime_convert('',date_default_timezone_get(), 'now','Y-m-d');
1956
1957         $dthen = first_post_date($uid, $wall);
1958         if (! $dthen) {
1959                 return [];
1960         }
1961
1962         // Set the start and end date to the beginning of the month
1963         $dnow = substr($dnow, 0, 8) . '01';
1964         $dthen = substr($dthen, 0, 8) . '01';
1965
1966         $ret = [];
1967
1968         /*
1969          * Starting with the current month, get the first and last days of every
1970          * month down to and including the month of the first post
1971          */
1972         while (substr($dnow, 0, 7) >= substr($dthen, 0, 7)) {
1973                 $dyear = intval(substr($dnow, 0, 4));
1974                 $dstart = substr($dnow, 0, 8) . '01';
1975                 $dend = substr($dnow, 0, 8) . get_dim(intval($dnow), intval(substr($dnow, 5)));
1976                 $start_month = datetime_convert('', '', $dstart, 'Y-m-d');
1977                 $end_month = datetime_convert('', '', $dend, 'Y-m-d');
1978                 $str = day_translate(datetime_convert('', '', $dnow, 'F'));
1979                 if (!$ret[$dyear]) {
1980                         $ret[$dyear] = [];
1981                 }
1982                 $ret[$dyear][] = [$str, $end_month, $start_month];
1983                 $dnow = datetime_convert('', '', $dnow . ' -1 month', 'Y-m-d');
1984         }
1985         return $ret;
1986 }
1987
1988 /// @TODO move to src/Model/Item.php
1989 function posted_date_widget($url, $uid, $wall) {
1990         $o = '';
1991
1992         if (! Feature::isEnabled($uid, 'archives')) {
1993                 return $o;
1994         }
1995
1996         // For former Facebook folks that left because of "timeline"
1997         /*
1998          * @TODO old-lost code?
1999         if ($wall && intval(PConfig::get($uid, 'system', 'no_wall_archive_widget')))
2000                 return $o;
2001         */
2002
2003         $visible_years = PConfig::get($uid,'system','archive_visible_years');
2004         if (! $visible_years) {
2005                 $visible_years = 5;
2006         }
2007
2008         $ret = list_post_dates($uid, $wall);
2009
2010         if (! DBM::is_result($ret)) {
2011                 return $o;
2012         }
2013
2014         $cutoff_year = intval(datetime_convert('',date_default_timezone_get(), 'now', 'Y')) - $visible_years;
2015         $cutoff = ((array_key_exists($cutoff_year, $ret))? true : false);
2016
2017         $o = replace_macros(get_markup_template('posted_date_widget.tpl'),[
2018                 '$title' => t('Archives'),
2019                 '$size' => $visible_years,
2020                 '$cutoff_year' => $cutoff_year,
2021                 '$cutoff' => $cutoff,
2022                 '$url' => $url,
2023                 '$dates' => $ret,
2024                 '$showmore' => t('show more')
2025
2026         ]);
2027         return $o;
2028 }