3 * @file include/items.php
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\Network;
26 use Friendica\Util\ParseUrl;
28 require_once 'include/bbcode.php';
29 require_once 'include/tags.php';
30 require_once 'include/text.php';
31 require_once 'include/threads.php';
32 require_once 'mod/share.php';
33 require_once 'include/enotify.php';
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
45 * @brief Truncates imported message body string length to max_import_size
49 /// @TODO move to src/Model/Item.php
50 function limit_body_size($body)
52 $maxlen = get_max_import_size();
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)) {
58 logger('limit_body_size: the total body length exceeds the limit', LOGGER_DEBUG);
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)) {
69 $img_st_close++; // make it point to AFTER the closing bracket
70 $img_end += $img_start;
71 $img_end += strlen('[/img]');
73 if (! strcmp(substr($orig_body, $img_start + $img_st_close, 5), 'data:')) {
74 // This is an embedded image
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);
83 $new_body = $new_body . substr($orig_body, 0, $img_start);
84 $textlen += $img_start;
87 $new_body = $new_body . substr($orig_body, $img_start, $img_end - $img_start);
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);
97 $new_body = $new_body . substr($orig_body, 0, $img_end);
101 $orig_body = substr($orig_body, $img_end);
103 if ($orig_body === false) {
104 // in case the body ends on a closing image tag
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);
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);
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;
129 /// @TODO move to ???
130 function add_page_info_data($data) {
131 Addon::callHooks('page_info_data', $data);
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";
140 if ((($data["type"] != "link") && ($data["type"] != "video") && ($data["type"] != "photo")) || ($data["title"] == $data["url"])) {
144 if ($no_photos && ($data["type"] == "photo")) {
148 // Escape some bad characters
149 $data["url"] = str_replace(["[", "]"], ["[", "]"], htmlentities($data["url"], ENT_QUOTES, 'UTF-8', false));
150 $data["title"] = str_replace(["[", "]"], ["[", "]"], htmlentities($data["title"], ENT_QUOTES, 'UTF-8', false));
152 $text = "[attachment type='".$data["type"]."'";
154 if ($data["text"] == "") {
155 $data["text"] = $data["title"];
158 if ($data["text"] == "") {
159 $data["text"] = $data["url"];
162 if ($data["url"] != "") {
163 $text .= " url='".$data["url"]."'";
166 if ($data["title"] != "") {
167 $text .= " title='".$data["title"]."'";
170 if (sizeof($data["images"]) > 0) {
171 $preview = str_replace(["[", "]"], ["[", "]"], 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."'";
178 $text .= " preview='".$preview."'";
182 $text .= "]".$data["text"]."[/attachment]";
185 if (isset($data["keywords"]) && count($data["keywords"])) {
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] ";
195 return "\n".$text.$hashtags;
198 /// @TODO move to ???
199 function query_page_info($url, $no_photos = false, $photo = "", $keywords = false, $keyword_blacklist = "") {
201 $data = ParseUrl::getSiteinfoCached($url, true);
204 $data["images"][0]["src"] = $photo;
207 logger('fetch page info for ' . $url . ' ' . print_r($data, true), LOGGER_DEBUG);
209 if (!$keywords && isset($data["keywords"])) {
210 unset($data["keywords"]);
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]);
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);
232 if (isset($data["keywords"]) && count($data["keywords"])) {
233 foreach ($data["keywords"] AS $keyword) {
234 $hashtag = str_replace([" ", "+", "/", ".", "#", "'"],
235 ["", "", "", "", "", ""], $keyword);
241 $tags .= "#[url=" . System::baseUrl() . "/search?tag=" . rawurlencode($hashtag) . "]" . $hashtag . "[/url]";
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);
252 $text = add_page_info_data($data);
257 /// @TODO move to ???
258 function add_page_info_to_body($body, $texturl = false, $no_photos = false) {
260 logger('add_page_info_to_body: fetch page info for body ' . $body, LOGGER_DEBUG);
262 $URLSearchString = "^\[\]";
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);
268 // Adding these spaces is a quick hack due to my problems with regular expressions :)
269 preg_match("/[^!#@]\[url\]([$URLSearchString]*)\[\/url\]/ism", " " . $body, $matches);
272 preg_match("/[^!#@]\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", " " . $body, $matches);
275 // Convert urls without bbcode elements
276 if (!$matches && $texturl) {
277 preg_match("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", " ".$body, $matches);
279 // Yeah, a hack. I really hate regular expressions :)
281 $matches[1] = $matches[2];
286 $footer = add_page_info($matches[1], $no_photos);
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;
296 $url = str_replace(['/', '.'], ['\/', '\.'], $matches[1]);
297 $removedlink = preg_replace("/\[url\=" . $url . "\](.*?)\[\/url\]/ism", '', $body);
298 if (($removedlink == "") || strstr($body, $removedlink)) {
299 $body = $removedlink;
303 // Add the page information to the bottom
304 if (isset($footer) && (trim($footer) != "")) {
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)
317 // If it is a posting where users should get notifications, then define it as wall posting
320 $arr['type'] = 'wall';
322 $arr['network'] = NETWORK_DFRN;
323 $arr['protocol'] = PROTOCOL_DFRN;
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());
336 $arr['network'] = trim(defaults($arr, 'network', NETWORK_PHANTOM));
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']);
346 $parsed = parse_url($arr["author-link"]);
347 $guid_prefix = hash("crc32", $parsed["host"]);
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']));
353 // Store conversation data
354 $arr = Conversation::insert($arr);
357 * If a Diaspora signature structure was passed in, pull it out of the
358 * item array and set it aside for later storage.
362 if (x($arr, 'dsprsig')) {
363 $encoded_signature = $arr['dsprsig'];
364 $dsprsig = json_decode(base64_decode($arr['dsprsig']));
365 unset($arr['dsprsig']);
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']);
378 if (x($arr, 'gravity')) {
379 $arr['gravity'] = intval($arr['gravity']);
380 } elseif ($arr['parent-uri'] === $arr['uri']) {
382 } elseif (activity_match($arr['verb'],ACTIVITY_POST)) {
385 $arr['gravity'] = 6; // extensible catchall
388 if (! x($arr, 'type')) {
389 $arr['type'] = 'remote';
392 $uid = intval($arr['uid']);
394 // check for create date and expire time
395 $expire_interval = Config::get('system', 'dbclean-expire-days', 0);
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'];
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);
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)
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'])),
420 dbesc(NETWORK_DIASPORA),
422 dbesc(NETWORK_OSTATUS)
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
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']);
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']);
440 Item::addLanguageInPostopts($arr);
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 );
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']) : '');
484 // When there is no content then we don't post it
485 if ($arr['body'].$arr['title'] == '') {
489 // Items cannot be stored before they happen ...
490 if ($arr['created'] > datetime_convert()) {
491 $arr['created'] = datetime_convert();
494 // We haven't invented time travel by now.
495 if ($arr['edited'] > datetime_convert()) {
496 $arr['edited'] = datetime_convert();
499 if (($arr['author-link'] == "") && ($arr['owner-link'] == "")) {
500 logger("Both author-link and owner-link are empty. Called by: " . System::callstack(), LOGGER_DEBUG);
503 if ($arr['plink'] == "") {
504 $arr['plink'] = System::baseUrl() . '/display/' . urlencode($arr['guid']);
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'])),
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']))
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']),
528 if (DBM::is_result($r)) {
529 $arr['network'] = $r[0]["network"];
532 // Fallback to friendica (why is it empty in some cases?)
533 if ($arr['network'] == "") {
534 $arr['network'] = NETWORK_DFRN;
537 logger("item_store: Set network to " . $arr["network"] . " for " . $arr["uri"], LOGGER_DEBUG);
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) {
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")
546 if ($arr['parent-uri'] != $arr['uri']) {
547 $arr["contact-id"] = Contact::getIdForURL($arr['author-link'], $uid);
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);
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));
559 if (DBM::is_result($r)) {
560 $arr["contact-id"] = $r[0]["id"];
564 logger("Contact-id was missing for post ".$arr["guid"]." from user id ".$uid." - now set to ".$arr["contact-id"], LOGGER_DEBUG);
567 if (!x($arr, "gcontact-id")) {
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.
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']]);
577 $arr["gcontact-id"] = GContact::getId(["url" => $arr['author-link'], "network" => $arr['network'],
578 "photo" => $arr['author-avatar'], "name" => $arr['author-name']]);
582 if ($arr["author-id"] == 0) {
583 $arr["author-id"] = Contact::getIdForURL($arr["author-link"], 0);
586 if (Contact::isBlocked($arr["author-id"])) {
587 logger('Contact '.$arr["author-id"].' is blocked, item '.$arr["uri"].' will not be stored');
591 if ($arr["owner-id"] == 0) {
592 $arr["owner-id"] = Contact::getIdForURL($arr["owner-link"], 0);
595 if (Contact::isBlocked($arr["owner-id"])) {
596 logger('Contact '.$arr["owner-id"].' is blocked, item '.$arr["uri"].' will not be stored');
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']));
606 if (DBM::is_result($r)) {
607 logger('found item with guid '.$arr['guid'].' for user '.$arr['uid'].' on network '.$arr['network'], LOGGER_DEBUG);
612 // Check for hashtags in the body and repair or add hashtag links
613 item_body_set_hashtags($arr);
615 $arr['thr-parent'] = $arr['parent-uri'];
617 if ($arr['parent-uri'] === $arr['uri']) {
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';
627 // find the parent and snarf the item id and ACLs
628 // and anything else we need to inherit
630 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d ORDER BY `id` ASC LIMIT 1",
631 dbesc($arr['parent-uri']),
635 if (DBM::is_result($r)) {
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.
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']),
650 if (DBM::is_result($z)) {
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';
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.
669 if ($r[0]['private']) {
670 $arr['private'] = $r[0]['private'];
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.
678 if ((intval($r[0]['forum_mode']) == 1) && $r[0]['private']) {
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);
695 * Allow one to see reply tweets from status.net even when
696 * we don't have or can't see the original post.
699 logger('item_store: $force_parent=true, reply converted to top-level post.');
701 $arr['parent-uri'] = $arr['uri'];
704 logger('item_store: item parent '.$arr['parent-uri'].' for '.$arr['uid'].' was not found - ignoring item');
712 $r = q("SELECT `id` FROM `item` WHERE `uri` = '%s' AND `network` IN ('%s', '%s') AND `uid` = %d LIMIT 1",
714 dbesc($arr['network']),
718 if (DBM::is_result($r)) {
719 logger('duplicated item with the same uri found. '.print_r($arr,true));
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",
729 if (DBM::is_result($r)) {
730 logger('duplicated item with the same guid found. '.print_r($arr,true));
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",
737 dbesc($arr['network']),
738 dbesc($arr['created']),
739 intval($arr['contact-id']),
742 if (DBM::is_result($r)) {
743 logger('duplicated item with the same body found. '.print_r($arr,true));
748 // Is this item available in the global items (with uid=0)?
749 if ($arr["uid"] == 0) {
750 $arr["global"] = true;
752 // Set the global flag on all items if this was a global item entry
753 dba::update('item', ['global' => true], ['uri' => $arr["uri"]]);
755 $isglobal = q("SELECT `global` FROM `item` WHERE `uid` = 0 AND `uri` = '%s'", dbesc($arr["uri"]));
757 $arr["global"] = (DBM::is_result($isglobal) && count($isglobal) > 0);
761 if (strlen($allow_cid) || strlen($allow_gid) || strlen($deny_cid) || strlen($deny_gid)) {
764 $private = $arr['private'];
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;
774 // Fill the cache field
775 put_item_in_cache($arr);
778 Addon::callHooks('post_local', $arr);
780 Addon::callHooks('post_remote', $arr);
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']);
787 if (x($arr, 'cancel')) {
788 logger('item_store: post cancelled by addon.');
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.
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);
805 logger('item_store: ' . print_r($arr,true), LOGGER_DATA);
808 $r = dba::insert('item', $arr);
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();
814 // This can happen - for example - if there are locking timeouts.
817 // Store the data into a spool file so that we can try again later.
819 // At first we restore the Diaspora signature that we removed above.
820 if (isset($encoded_signature)) {
821 $arr['dsprsig'] = $encoded_signature;
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';
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);
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.");
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'",
849 dbesc($arr['network'])
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 ...");
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']);
863 // Yes, we could do a rollback here - but we are having many users with MyISAM.
864 dba::delete('item', ['id' => $current_post]);
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.");
874 logger('item_store: created item '.$current_post);
875 Item::updateContact($arr);
877 if (!$parent_id || ($arr['parent-uri'] === $arr['uri'])) {
878 $parent_id = $current_post;
882 dba::update('item', ['parent' => $parent_id], ['id' => $current_post]);
884 $arr['id'] = $current_post;
885 $arr['parent'] = $parent_id;
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]);
892 dba::update('item', ['changed' => datetime_convert()], ['id' => $parent_id]);
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.
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);
906 dba::insert('sign', ['iid' => $current_post, 'signed_text' => $dsprsig->signed_text,
907 'signature' => $dsprsig->signature, 'signer' => $dsprsig->signer]);
910 $deleted = tag_deliver($arr['uid'], $current_post);
913 * current post can be deleted if is for a community page and no mention are
916 if (!$deleted && !$dontcache) {
918 $r = q('SELECT * FROM `item` WHERE `id` = %d', intval($current_post));
919 if ((DBM::is_result($r)) && (count($r) == 1)) {
921 Addon::callHooks('post_local_end', $r[0]);
923 Addon::callHooks('post_remote_end', $r[0]);
926 logger('item_store: new item not found in DB, id ' . $current_post);
930 if ($arr['parent-uri'] === $arr['uri']) {
931 add_thread($current_post);
933 update_thread($parent_id);
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.
942 create_tags_from_item($current_post);
943 Term::createFromItem($current_post);
945 if ($arr['parent-uri'] === $arr['uri']) {
946 Item::addShadow($current_post);
948 Item::addShadowPost($current_post);
951 check_user_notification($current_post);
954 Worker::add(['priority' => PRIORITY_HIGH, 'dont_fork' => true], "Notifier", $notify_type, $current_post);
957 return $current_post;
960 /// @TODO move to src/Model/Item.php
961 function item_body_set_hashtags(&$item) {
963 $tags = get_tags($item["body"]);
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
974 $URLSearchString = "^\[\]";
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"]);
981 $item["tag"] = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
982 "#[url=".System::baseUrl()."/search?tag=$2]$2[/url]", $item["tag"]);
985 // mask hashtags inside of url, bookmarks and attachments to avoid urls in urls
986 $item["body"] = preg_replace_callback("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
988 return ("[url=" . str_replace("#", "#", $match[1]) . "]" . str_replace("#", "#", $match[2]) . "[/url]");
991 $item["body"] = preg_replace_callback("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism",
993 return ("[bookmark=" . str_replace("#", "#", $match[1]) . "]" . str_replace("#", "#", $match[2]) . "[/bookmark]");
996 $item["body"] = preg_replace_callback("/\[attachment (.*)\](.*?)\[\/attachment\]/ism",
998 return ("[attachment " . str_replace("#", "#", $match[1]) . "]" . $match[2] . "[/attachment]");
1001 // Repair recursive urls
1002 $item["body"] = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
1003 "#$2", $item["body"]);
1005 foreach ($tags as $tag) {
1006 if ((strpos($tag, '#') !== 0) || (strpos($tag, '[url='))) {
1010 $basetag = str_replace('_',' ',substr($tag,1));
1012 $newtag = '#[url=' . System::baseUrl() . '/search?tag=' . rawurlencode($basetag) . ']' . $basetag . '[/url]';
1014 $item["body"] = str_replace($tag, $newtag, $item["body"]);
1016 if (!stristr($item["tag"], "/search?tag=" . $basetag . "]" . $basetag . "[/url]")) {
1017 if (strlen($item["tag"])) {
1018 $item["tag"] = ','.$item["tag"];
1020 $item["tag"] = $newtag.$item["tag"];
1024 // Convert back the masked hashtags
1025 $item["body"] = str_replace("#", "#", $item["body"]);
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"];
1034 /// @TODO This else-block can be elimited again
1039 /// @TODO move to src/Model/Item.php
1040 function get_item_id($guid, $uid = 0) {
1046 $uid == local_user();
1049 // Does the given user have this item?
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)) {
1056 $nick = $r[0]["nickname"];
1060 // Or is it anywhere on the server?
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)) {
1070 $nick = $r[0]["nickname"];
1073 return ["nick" => $nick, "id" => $id];
1077 * look for mention tags and setup a second delivery chain for forum/community posts if appropriate
1079 * @param int $item_id
1080 * @return bool true if item was deleted, else false
1082 /// @TODO move to src/Model/Item.php
1083 function tag_deliver($uid, $item_id)
1087 $u = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
1090 if (! DBM::is_result($u)) {
1094 $community_page = (($u[0]['page-flags'] == PAGE_COMMUNITY) ? true : false);
1095 $prvgroup = (($u[0]['page-flags'] == PAGE_PRVGROUP) ? true : false);
1097 $i = q("SELECT * FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1",
1101 if (! DBM::is_result($i)) {
1107 $link = normalise_link(System::baseUrl() . '/profile/' . $u[0]['nickname']);
1110 * Diaspora uses their own hardwired link URL in @-tags
1111 * instead of the one we supply with webfinger
1113 $dlink = normalise_link(System::baseUrl() . '/u/' . $u[0]['nickname']);
1115 $cnt = preg_match_all('/[\@\!]\[url\=(.*?)\](.*?)\[\/url\]/ism', $item['body'], $matches, PREG_SET_ORDER);
1117 foreach ($matches as $mtch) {
1118 if (link_compare($link, $mtch[1]) || link_compare($dlink, $mtch[1])) {
1120 logger('tag_deliver: mention found: ' . $mtch[2]);
1126 if (($community_page || $prvgroup) &&
1127 (!$item['wall']) && (!$item['origin']) && ($item['id'] == $item['parent'])) {
1128 // mmh.. no mention.. community page or private group... no wall.. no origin.. top-post (not a comment)
1130 logger("tag_deliver: no-mention top-level post to communuty or private group. delete.");
1131 dba::delete('item', ['id' => $item_id]);
1137 $arr = ['item' => $item, 'user' => $u[0], 'contact' => $r[0]];
1139 Addon::callHooks('tagged', $arr);
1141 if ((! $community_page) && (! $prvgroup)) {
1146 * tgroup delivery - setup a second delivery chain
1147 * prevent delivery looping - only proceed
1148 * if the message originated elsewhere and is a top-level post
1150 if (($item['wall']) || ($item['origin']) || ($item['id'] != $item['parent'])) {
1154 // now change this copy of the post to a forum head message and deliver to all the tgroup members
1155 $c = q("SELECT `name`, `url`, `thumb` FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
1156 intval($u[0]['uid'])
1158 if (! DBM::is_result($c)) {
1162 // also reset all the privacy bits to the forum default permissions
1164 $private = ($u[0]['allow_cid'] || $u[0]['allow_gid'] || $u[0]['deny_cid'] || $u[0]['deny_gid']) ? 1 : 0;
1166 $forum_mode = (($prvgroup) ? 2 : 1);
1168 q("UPDATE `item` SET `wall` = 1, `origin` = 1, `forum_mode` = %d, `owner-name` = '%s', `owner-link` = '%s', `owner-avatar` = '%s',
1169 `private` = %d, `allow_cid` = '%s', `allow_gid` = '%s', `deny_cid` = '%s', `deny_gid` = '%s' WHERE `id` = %d",
1170 intval($forum_mode),
1171 dbesc($c[0]['name']),
1172 dbesc($c[0]['url']),
1173 dbesc($c[0]['thumb']),
1175 dbesc($u[0]['allow_cid']),
1176 dbesc($u[0]['allow_gid']),
1177 dbesc($u[0]['deny_cid']),
1178 dbesc($u[0]['deny_gid']),
1181 update_thread($item_id);
1183 Worker::add(['priority' => PRIORITY_HIGH, 'dont_fork' => true], 'Notifier', 'tgroup', $item_id);
1189 * consume_feed - process atom feed and update anything/everything we might need to update
1191 * $xml = the (atom) feed to consume - RSS isn't as fully supported but may work for simple feeds.
1193 * $importer = the contact_record (joined to user_record) of the local user who owns this relationship.
1194 * It is this person's stuff that is going to be updated.
1195 * $contact = the person who is sending us stuff. If not set, we MAY be processing a "follow" activity
1196 * from an external network and MAY create an appropriate contact record. Otherwise, we MUST
1197 * have a contact record.
1198 * $hub = should we find a hub declation in the feed, pass it back to our calling process, who might (or
1199 * might not) try and subscribe to it.
1200 * $datedir sorts in reverse order
1201 * $pass - by default ($pass = 0) we cannot guarantee that a parent item has been
1202 * imported prior to its children being seen in the stream unless we are certain
1203 * of how the feed is arranged/ordered.
1204 * With $pass = 1, we only pull parent items out of the stream.
1205 * With $pass = 2, we only pull children (comments/likes).
1207 * So running this twice, first with pass 1 and then with pass 2 will do the right
1208 * thing regardless of feed ordering. This won't be adequate in a fully-threaded
1209 * model where comments can have sub-threads. That would require some massive sorting
1210 * to get all the feed items into a mostly linear ordering, and might still require
1213 * @TODO find proper type-hints
1215 /// @TODO move to ???
1216 function consume_feed($xml, $importer, &$contact, &$hub, $datedir = 0, $pass = 0) {
1217 if ($contact['network'] === NETWORK_OSTATUS) {
1219 // Test - remove before flight
1220 //$tempfile = tempnam(get_temppath(), "ostatus2");
1221 //file_put_contents($tempfile, $xml);
1222 logger("Consume OStatus messages ", LOGGER_DEBUG);
1223 OStatus::import($xml, $importer, $contact, $hub);
1228 if ($contact['network'] === NETWORK_FEED) {
1230 logger("Consume feeds", LOGGER_DEBUG);
1231 Feed::import($xml, $importer, $contact, $hub);
1236 if ($contact['network'] === NETWORK_DFRN) {
1237 logger("Consume DFRN messages", LOGGER_DEBUG);
1239 $r = q("SELECT `contact`.*, `contact`.`uid` AS `importer_uid`,
1240 `contact`.`pubkey` AS `cpubkey`,
1241 `contact`.`prvkey` AS `cprvkey`,
1242 `contact`.`thumb` AS `thumb`,
1243 `contact`.`url` as `url`,
1244 `contact`.`name` as `senderName`,
1247 LEFT JOIN `user` ON `contact`.`uid` = `user`.`uid`
1248 WHERE `contact`.`id` = %d AND `user`.`uid` = %d",
1249 dbesc($contact["id"]), dbesc($importer["uid"])
1251 if (DBM::is_result($r)) {
1252 logger("Now import the DFRN feed");
1253 DFRN::import($xml, $r[0], true);
1259 /// @TODO type-hint is array
1260 /// @TODO move to src/Model/Item.php
1261 function item_is_remote_self($contact, &$datarray) {
1264 if (!$contact['remote_self']) {
1268 // Prevent the forwarding of posts that are forwarded
1269 if ($datarray["extid"] == NETWORK_DFRN) {
1273 // Prevent to forward already forwarded posts
1274 if ($datarray["app"] == $a->get_hostname()) {
1278 // Only forward posts
1279 if ($datarray["verb"] != ACTIVITY_POST) {
1283 if (($contact['network'] != NETWORK_FEED) && $datarray['private']) {
1287 $datarray2 = $datarray;
1288 logger('remote-self start - Contact '.$contact['url'].' - '.$contact['remote_self'].' Item '.print_r($datarray, true), LOGGER_DEBUG);
1289 if ($contact['remote_self'] == 2) {
1290 $r = q("SELECT `id`,`url`,`name`,`thumb` FROM `contact` WHERE `uid` = %d AND `self`",
1291 intval($contact['uid']));
1292 if (DBM::is_result($r)) {
1293 $datarray['contact-id'] = $r[0]["id"];
1295 $datarray['owner-name'] = $r[0]["name"];
1296 $datarray['owner-link'] = $r[0]["url"];
1297 $datarray['owner-avatar'] = $r[0]["thumb"];
1299 $datarray['author-name'] = $datarray['owner-name'];
1300 $datarray['author-link'] = $datarray['owner-link'];
1301 $datarray['author-avatar'] = $datarray['owner-avatar'];
1303 unset($datarray['created']);
1304 unset($datarray['edited']);
1307 if ($contact['network'] != NETWORK_FEED) {
1308 $datarray["guid"] = get_guid(32);
1309 unset($datarray["plink"]);
1310 $datarray["uri"] = item_new_uri($a->get_hostname(), $contact['uid'], $datarray["guid"]);
1311 $datarray["parent-uri"] = $datarray["uri"];
1312 $datarray["extid"] = $contact['network'];
1313 $urlpart = parse_url($datarray2['author-link']);
1314 $datarray["app"] = $urlpart["host"];
1316 $datarray['private'] = 0;
1320 if ($contact['network'] != NETWORK_FEED) {
1321 // Store the original post
1322 $r = item_store($datarray2, false, false);
1323 logger('remote-self post original item - Contact '.$contact['url'].' return '.$r.' Item '.print_r($datarray2, true), LOGGER_DEBUG);
1325 $datarray["app"] = "Feed";
1328 // Trigger automatic reactions for addons
1329 $datarray['api_source'] = true;
1331 // We have to tell the hooks who we are - this really should be improved
1332 $_SESSION["authenticated"] = true;
1333 $_SESSION["uid"] = $contact['uid'];
1338 /// @TODO find proper type-hints
1339 /// @TODO move to src/Model/Item.php
1340 function new_follower($importer, $contact, $datarray, $item, $sharing = false) {
1341 $url = notags(trim($datarray['author-link']));
1342 $name = notags(trim($datarray['author-name']));
1343 $photo = notags(trim($datarray['author-avatar']));
1345 if (is_object($item)) {
1346 $rawtag = $item->get_item_tags(NAMESPACE_ACTIVITY,'actor');
1347 if ($rawtag && $rawtag[0]['child'][NAMESPACE_POCO]['preferredUsername'][0]['data']) {
1348 $nick = $rawtag[0]['child'][NAMESPACE_POCO]['preferredUsername'][0]['data'];
1354 if (is_array($contact)) {
1355 if (($contact['network'] == NETWORK_OSTATUS && $contact['rel'] == CONTACT_IS_SHARING)
1356 || ($sharing && $contact['rel'] == CONTACT_IS_FOLLOWER)) {
1357 dba::update('contact', ['rel' => CONTACT_IS_FRIEND, 'writable' => true],
1358 ['id' => $contact['id'], 'uid' => $importer['uid']]);
1360 // send email notification to owner?
1362 // create contact record
1363 q("INSERT INTO `contact` (`uid`, `created`, `url`, `nurl`, `name`, `nick`, `photo`, `network`, `rel`,
1364 `blocked`, `readonly`, `pending`, `writable`)
1365 VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, 0, 0, 1, 1)",
1366 intval($importer['uid']),
1367 dbesc(datetime_convert()),
1369 dbesc(normalise_link($url)),
1373 dbesc(NETWORK_OSTATUS),
1374 intval(CONTACT_IS_FOLLOWER)
1377 $r = q("SELECT `id`, `network` FROM `contact` WHERE `uid` = %d AND `url` = '%s' AND `pending` = 1 LIMIT 1",
1378 intval($importer['uid']),
1381 if (DBM::is_result($r)) {
1382 $contact_record = $r[0];
1383 Contact::updateAvatar($photo, $importer["uid"], $contact_record["id"], true);
1386 /// @TODO Encapsulate this into a function/method
1387 $r = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
1388 intval($importer['uid'])
1390 if (DBM::is_result($r) && !in_array($r[0]['page-flags'], [PAGE_SOAPBOX, PAGE_FREELOVE, PAGE_COMMUNITY])) {
1391 // create notification
1392 $hash = random_string();
1394 if (is_array($contact_record)) {
1395 dba::insert('intro', ['uid' => $importer['uid'], 'contact-id' => $contact_record['id'],
1396 'blocked' => false, 'knowyou' => false,
1397 'hash' => $hash, 'datetime' => datetime_convert()]);
1400 Group::addMember(User::getDefaultGroup($importer['uid'], $contact_record["network"]), $contact_record['id']);
1402 if (($r[0]['notify-flags'] & NOTIFY_INTRO) &&
1403 in_array($r[0]['page-flags'], [PAGE_NORMAL])) {
1406 'type' => NOTIFY_INTRO,
1407 'notify_flags' => $r[0]['notify-flags'],
1408 'language' => $r[0]['language'],
1409 'to_name' => $r[0]['username'],
1410 'to_email' => $r[0]['email'],
1411 'uid' => $r[0]['uid'],
1412 'link' => System::baseUrl() . '/notifications/intro',
1413 'source_name' => ((strlen(stripslashes($contact_record['name']))) ? stripslashes($contact_record['name']) : L10n::t('[Name Withheld]')),
1414 'source_link' => $contact_record['url'],
1415 'source_photo' => $contact_record['photo'],
1416 'verb' => ($sharing ? ACTIVITY_FRIEND : ACTIVITY_FOLLOW),
1421 } elseif (DBM::is_result($r) && in_array($r[0]['page-flags'], [PAGE_SOAPBOX, PAGE_FREELOVE, PAGE_COMMUNITY])) {
1422 q("UPDATE `contact` SET `pending` = 0 WHERE `uid` = %d AND `url` = '%s' AND `pending` LIMIT 1",
1423 intval($importer['uid']),
1431 /// @TODO move to src/Model/Item.php
1432 function lose_follower($importer, $contact, array $datarray = [], $item = "") {
1434 if (($contact['rel'] == CONTACT_IS_FRIEND) || ($contact['rel'] == CONTACT_IS_SHARING)) {
1435 dba::update('contact', ['rel' => CONTACT_IS_SHARING], ['id' => $contact['id']]);
1437 Contact::remove($contact['id']);
1441 /// @TODO move to src/Model/Item.php
1442 function lose_sharer($importer, $contact, array $datarray = [], $item = "") {
1444 if (($contact['rel'] == CONTACT_IS_FRIEND) || ($contact['rel'] == CONTACT_IS_FOLLOWER)) {
1445 dba::update('contact', ['rel' => CONTACT_IS_FOLLOWER], ['id' => $contact['id']]);
1447 Contact::remove($contact['id']);
1451 /// @TODO move to ???
1452 function subscribe_to_hub($url, $importer, $contact, $hubmode = 'subscribe') {
1456 if (is_array($importer)) {
1457 $r = q("SELECT `nickname` FROM `user` WHERE `uid` = %d LIMIT 1",
1458 intval($importer['uid'])
1463 * Diaspora has different message-ids in feeds than they do
1464 * through the direct Diaspora protocol. If we try and use
1465 * the feed, we'll get duplicates. So don't.
1467 if ((! DBM::is_result($r)) || $contact['network'] === NETWORK_DIASPORA) {
1471 $push_url = Config::get('system','url') . '/pubsub/' . $r[0]['nickname'] . '/' . $contact['id'];
1473 // Use a single verify token, even if multiple hubs
1474 $verify_token = ((strlen($contact['hub-verify'])) ? $contact['hub-verify'] : random_string());
1476 $params= 'hub.mode=' . $hubmode . '&hub.callback=' . urlencode($push_url) . '&hub.topic=' . urlencode($contact['poll']) . '&hub.verify=async&hub.verify_token=' . $verify_token;
1478 logger('subscribe_to_hub: ' . $hubmode . ' ' . $contact['name'] . ' to hub ' . $url . ' endpoint: ' . $push_url . ' with verifier ' . $verify_token);
1480 if (!strlen($contact['hub-verify']) || ($contact['hub-verify'] != $verify_token)) {
1481 dba::update('contact', ['hub-verify' => $verify_token], ['id' => $contact['id']]);
1484 Network::post($url, $params);
1486 logger('subscribe_to_hub: returns: ' . $a->get_curl_code(), LOGGER_DEBUG);
1496 * @param array $item
1500 /// @TODO move to src/Model/Item.php
1501 function fix_private_photos($s, $uid, $item = null, $cid = 0)
1503 if (Config::get('system', 'disable_embedded')) {
1507 logger('fix_private_photos: check for photos', LOGGER_DEBUG);
1508 $site = substr(System::baseUrl(), strpos(System::baseUrl(), '://'));
1513 $img_start = strpos($orig_body, '[img');
1514 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
1515 $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
1517 while (($img_st_close !== false) && ($img_len !== false)) {
1518 $img_st_close++; // make it point to AFTER the closing bracket
1519 $image = substr($orig_body, $img_start + $img_st_close, $img_len);
1521 logger('fix_private_photos: found photo ' . $image, LOGGER_DEBUG);
1523 if (stristr($image, $site . '/photo/')) {
1524 // Only embed locally hosted photos
1526 $i = basename($image);
1527 $i = str_replace(['.jpg', '.png', '.gif'], ['', '', ''], $i);
1528 $x = strpos($i, '-');
1531 $res = substr($i, $x + 1);
1532 $i = substr($i, 0, $x);
1533 $r = q("SELECT * FROM `photo` WHERE `resource-id` = '%s' AND `scale` = %d AND `uid` = %d",
1538 if (DBM::is_result($r)) {
1540 * Check to see if we should replace this photo link with an embedded image
1541 * 1. No need to do so if the photo is public
1542 * 2. If there's a contact-id provided, see if they're in the access list
1543 * for the photo. If so, embed it.
1544 * 3. Otherwise, if we have an item, see if the item permissions match the photo
1545 * permissions, regardless of order but first check to see if they're an exact
1546 * match to save some processing overhead.
1548 if (has_permissions($r[0])) {
1550 $recips = enumerate_permissions($r[0]);
1551 if (in_array($cid, $recips)) {
1555 if (compare_permissions($item, $r[0])) {
1561 $data = $r[0]['data'];
1562 $type = $r[0]['type'];
1564 // If a custom width and height were specified, apply before embedding
1565 if (preg_match("/\[img\=([0-9]*)x([0-9]*)\]/is", substr($orig_body, $img_start, $img_st_close), $match)) {
1566 logger('fix_private_photos: scaling photo', LOGGER_DEBUG);
1568 $width = intval($match[1]);
1569 $height = intval($match[2]);
1571 $Image = new Image($data, $type);
1572 if ($Image->isValid()) {
1573 $Image->scaleDown(max($width, $height));
1574 $data = $Image->asString();
1575 $type = $Image->getType();
1579 logger('fix_private_photos: replacing photo', LOGGER_DEBUG);
1580 $image = 'data:' . $type . ';base64,' . base64_encode($data);
1581 logger('fix_private_photos: replaced: ' . $image, LOGGER_DATA);
1587 $new_body = $new_body . substr($orig_body, 0, $img_start + $img_st_close) . $image . '[/img]';
1588 $orig_body = substr($orig_body, $img_start + $img_st_close + $img_len + strlen('[/img]'));
1589 if ($orig_body === false) {
1593 $img_start = strpos($orig_body, '[img');
1594 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
1595 $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
1598 $new_body = $new_body . $orig_body;
1603 /// @TODO type-hint is array
1604 /// @TODO move to src/Model/Item.php
1605 function has_permissions($obj) {
1608 x($obj, 'allow_cid')
1610 x($obj, 'allow_gid')
1619 /// @TODO type-hint is array
1620 /// @TODO move to src/Model/Item.php
1621 function compare_permissions($obj1, $obj2) {
1622 // first part is easy. Check that these are exactly the same.
1623 if (($obj1['allow_cid'] == $obj2['allow_cid'])
1624 && ($obj1['allow_gid'] == $obj2['allow_gid'])
1625 && ($obj1['deny_cid'] == $obj2['deny_cid'])
1626 && ($obj1['deny_gid'] == $obj2['deny_gid'])) {
1630 // This is harder. Parse all the permissions and compare the resulting set.
1631 $recipients1 = enumerate_permissions($obj1);
1632 $recipients2 = enumerate_permissions($obj2);
1636 /// @TODO Comparison of arrays, maybe use array_diff_assoc() here?
1637 return ($recipients1 == $recipients2);
1640 // returns an array of contact-ids that are allowed to see this object
1641 /// @TODO type-hint is array
1642 /// @TODO move to src/Model/Item.php
1643 function enumerate_permissions($obj) {
1644 $allow_people = expand_acl($obj['allow_cid']);
1645 $allow_groups = Group::expand(expand_acl($obj['allow_gid']));
1646 $deny_people = expand_acl($obj['deny_cid']);
1647 $deny_groups = Group::expand(expand_acl($obj['deny_gid']));
1648 $recipients = array_unique(array_merge($allow_people, $allow_groups));
1649 $deny = array_unique(array_merge($deny_people, $deny_groups));
1650 $recipients = array_diff($recipients, $deny);
1654 /// @TODO move to src/Model/Item.php
1655 function item_getfeedtags($item) {
1658 $cnt = preg_match_all('|\#\[url\=(.*?)\](.*?)\[\/url\]|', $item['tag'], $matches);
1660 for ($x = 0; $x < $cnt; $x ++) {
1661 if ($matches[1][$x]) {
1662 $ret[$matches[2][$x]] = ['#', $matches[1][$x], $matches[2][$x]];
1667 $cnt = preg_match_all('|\@\[url\=(.*?)\](.*?)\[\/url\]|', $item['tag'], $matches);
1669 for ($x = 0; $x < $cnt; $x ++) {
1670 if ($matches[1][$x]) {
1671 $ret[] = ['@', $matches[1][$x], $matches[2][$x]];
1678 /// @TODO move to src/Model/Item.php
1679 function item_expire($uid, $days, $network = "", $force = false) {
1681 if (!$uid || ($days < 1)) {
1686 * $expire_network_only = save your own wall posts
1687 * and just expire conversations started by others
1689 $expire_network_only = PConfig::get($uid,'expire', 'network_only');
1690 $sql_extra = (intval($expire_network_only) ? " AND wall = 0 " : "");
1692 if ($network != "") {
1693 $sql_extra .= sprintf(" AND network = '%s' ", dbesc($network));
1696 * There is an index "uid_network_received" but not "uid_network_created"
1697 * This avoids the creation of another index just for one purpose.
1698 * And it doesn't really matter wether to look at "received" or "created"
1700 $range = "AND `received` < UTC_TIMESTAMP() - INTERVAL %d DAY ";
1702 $range = "AND `created` < UTC_TIMESTAMP() - INTERVAL %d DAY ";
1705 $r = q("SELECT `file`, `resource-id`, `starred`, `type`, `id` FROM `item`
1706 WHERE `uid` = %d $range
1714 if (!DBM::is_result($r)) {
1718 $expire_items = PConfig::get($uid, 'expire', 'items', 1);
1720 // Forcing expiring of items - but not notes and marked items
1722 $expire_items = true;
1725 $expire_notes = PConfig::get($uid, 'expire', 'notes', 1);
1726 $expire_starred = PConfig::get($uid, 'expire', 'starred', 1);
1727 $expire_photos = PConfig::get($uid, 'expire', 'photos', 0);
1729 logger('User '.$uid.': expire: # items=' . count($r). "; expire items: $expire_items, expire notes: $expire_notes, expire starred: $expire_starred, expire photos: $expire_photos");
1731 foreach ($r as $item) {
1733 // don't expire filed items
1735 if (strpos($item['file'],'[') !== false) {
1739 // Only expire posts, not photos and photo comments
1741 if ($expire_photos == 0 && strlen($item['resource-id'])) {
1743 } elseif ($expire_starred == 0 && intval($item['starred'])) {
1745 } elseif ($expire_notes == 0 && $item['type'] == 'note') {
1747 } elseif ($expire_items == 0 && $item['type'] != 'note') {
1751 Item::delete($item['id'], PRIORITY_LOW);
1755 /// @TODO type-hint is array
1756 /// @TODO move to ...
1757 function drop_items($items) {
1760 if (!local_user() && !remote_user()) {
1764 if (count($items)) {
1765 foreach ($items as $item) {
1766 $owner = Item::delete($item);
1767 if ($owner && ! $uid)
1773 /// @TODO move to ...
1774 function drop_item($id) {
1778 // locate item to be deleted
1780 $r = q("SELECT * FROM `item` WHERE `id` = %d LIMIT 1",
1784 if (!DBM::is_result($r)) {
1785 notice(L10n::t('Item not found.') . EOL);
1786 goaway(System::baseUrl() . '/' . $_SESSION['return_url']);
1791 if ($item['deleted']) {
1797 // check if logged in user is either the author or owner of this item
1799 if (is_array($_SESSION['remote'])) {
1800 foreach ($_SESSION['remote'] as $visitor) {
1801 if ($visitor['uid'] == $item['uid'] && $visitor['cid'] == $item['contact-id']) {
1802 $contact_id = $visitor['cid'];
1808 if ((local_user() == $item['uid']) || $contact_id) {
1810 // Check if we should do HTML-based delete confirmation
1811 if ($_REQUEST['confirm']) {
1812 // <form> can't take arguments in its "action" parameter
1813 // so add any arguments as hidden inputs
1814 $query = explode_querystring($a->query_string);
1816 foreach ($query['args'] as $arg) {
1817 if (strpos($arg, 'confirm=') === false) {
1818 $arg_parts = explode('=', $arg);
1819 $inputs[] = ['name' => $arg_parts[0], 'value' => $arg_parts[1]];
1823 return replace_macros(get_markup_template('confirm.tpl'), [
1825 '$message' => L10n::t('Do you really want to delete this item?'),
1826 '$extra_inputs' => $inputs,
1827 '$confirm' => L10n::t('Yes'),
1828 '$confirm_url' => $query['base'],
1829 '$confirm_name' => 'confirmed',
1830 '$cancel' => L10n::t('Cancel'),
1833 // Now check how the user responded to the confirmation query
1834 if ($_REQUEST['canceled']) {
1835 goaway(System::baseUrl() . '/' . $_SESSION['return_url']);
1839 Item::delete($item['id']);
1841 goaway(System::baseUrl() . '/' . $_SESSION['return_url']);
1844 notice(L10n::t('Permission denied.') . EOL);
1845 goaway(System::baseUrl() . '/' . $_SESSION['return_url']);
1850 /// @TODO: This query seems to be really slow
1851 /// @TODO move to src/Model/Item.php
1852 function first_post_date($uid, $wall = false) {
1853 $r = q("SELECT `id`, `created` FROM `item`
1854 WHERE `uid` = %d AND `wall` = %d AND `deleted` = 0 AND `visible` = 1 AND `moderated` = 0
1856 ORDER BY `created` ASC LIMIT 1",
1858 intval($wall ? 1 : 0)
1860 if (DBM::is_result($r)) {
1861 // logger('first_post_date: ' . $r[0]['id'] . ' ' . $r[0]['created'], LOGGER_DATA);
1862 return substr(datetime_convert('',date_default_timezone_get(), $r[0]['created']),0,10);
1867 /* arrange the list in years */
1868 /// @TODO move to src/Model/Item.php
1869 function list_post_dates($uid, $wall) {
1870 $dnow = datetime_convert('',date_default_timezone_get(), 'now','Y-m-d');
1872 $dthen = first_post_date($uid, $wall);
1877 // Set the start and end date to the beginning of the month
1878 $dnow = substr($dnow, 0, 8) . '01';
1879 $dthen = substr($dthen, 0, 8) . '01';
1884 * Starting with the current month, get the first and last days of every
1885 * month down to and including the month of the first post
1887 while (substr($dnow, 0, 7) >= substr($dthen, 0, 7)) {
1888 $dyear = intval(substr($dnow, 0, 4));
1889 $dstart = substr($dnow, 0, 8) . '01';
1890 $dend = substr($dnow, 0, 8) . get_dim(intval($dnow), intval(substr($dnow, 5)));
1891 $start_month = datetime_convert('', '', $dstart, 'Y-m-d');
1892 $end_month = datetime_convert('', '', $dend, 'Y-m-d');
1893 $str = day_translate(datetime_convert('', '', $dnow, 'F'));
1894 if (!$ret[$dyear]) {
1897 $ret[$dyear][] = [$str, $end_month, $start_month];
1898 $dnow = datetime_convert('', '', $dnow . ' -1 month', 'Y-m-d');
1903 /// @TODO move to src/Model/Item.php
1904 function posted_date_widget($url, $uid, $wall) {
1907 if (! Feature::isEnabled($uid, 'archives')) {
1911 // For former Facebook folks that left because of "timeline"
1913 * @TODO old-lost code?
1914 if ($wall && intval(PConfig::get($uid, 'system', 'no_wall_archive_widget')))
1918 $visible_years = PConfig::get($uid,'system','archive_visible_years');
1919 if (! $visible_years) {
1923 $ret = list_post_dates($uid, $wall);
1925 if (! DBM::is_result($ret)) {
1929 $cutoff_year = intval(datetime_convert('',date_default_timezone_get(), 'now', 'Y')) - $visible_years;
1930 $cutoff = ((array_key_exists($cutoff_year, $ret))? true : false);
1932 $o = replace_macros(get_markup_template('posted_date_widget.tpl'),[
1933 '$title' => L10n::t('Archives'),
1934 '$size' => $visible_years,
1935 '$cutoff_year' => $cutoff_year,
1936 '$cutoff' => $cutoff,
1939 '$showmore' => L10n::t('show more')