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