4 * @file src/Model/Item.php
7 namespace Friendica\Model;
9 use Friendica\BaseObject;
10 use Friendica\Core\Addon;
11 use Friendica\Core\Config;
12 use Friendica\Core\L10n;
13 use Friendica\Core\PConfig;
14 use Friendica\Core\System;
15 use Friendica\Core\Worker;
16 use Friendica\Database\DBM;
17 use Friendica\Model\Contact;
18 use Friendica\Model\Conversation;
19 use Friendica\Model\GContact;
20 use Friendica\Model\Group;
21 use Friendica\Model\Term;
22 use Friendica\Object\Image;
23 use Friendica\Protocol\Diaspora;
24 use Friendica\Protocol\OStatus;
25 use Friendica\Util\DateTimeFormat;
26 use Friendica\Util\Temporal;
28 use Text_LanguageDetect;
30 require_once 'boot.php';
31 require_once 'include/tags.php';
32 require_once 'include/threads.php';
33 require_once 'include/items.php';
34 require_once 'include/text.php';
36 class Item extends BaseObject
39 * @brief Update existing item entries
41 * @param array $fields The fields that are to be changed
42 * @param array $condition The condition for finding the item entries
44 * In the future we may have to change permissions as well.
45 * Then we had to add the user id as third parameter.
47 * A return value of "0" doesn't mean an error - but that 0 rows had been changed.
49 * @return integer|boolean number of affected rows - or "false" if there was an error
51 public static function update(array $fields, array $condition)
53 if (empty($condition) || empty($fields)) {
57 $success = dba::update('item', $fields, $condition);
63 $rows = dba::affected_rows();
65 // We cannot simply expand the condition to check for origin entries
66 // The condition needn't to be a simple array but could be a complex condition.
67 $items = dba::select('item', ['id', 'origin'], $condition);
68 while ($item = dba::fetch($items)) {
69 // We only need to notfiy others when it is an original entry from us
70 if (!$item['origin']) {
74 create_tags_from_item($item['id']);
75 Term::createFromItem($item['id']);
76 update_thread($item['id']);
78 Worker::add(PRIORITY_HIGH, "Notifier", 'edit_post', $item['id']);
85 * @brief Delete an item and notify others about it - if it was ours
87 * @param integer $item_id Item ID that should be delete
89 * @return $boolean success
91 public static function delete($item_id, $priority = PRIORITY_HIGH)
93 // locate item to be deleted
94 $fields = ['id', 'uid', 'parent', 'parent-uri', 'origin', 'deleted', 'file', 'resource-id', 'event-id', 'attach'];
95 $item = dba::selectFirst('item', $fields, ['id' => $item_id]);
96 if (!DBM::is_result($item)) {
100 if ($item['deleted']) {
104 $parent = dba::selectFirst('item', ['origin'], ['id' => $item['parent']]);
105 if (!DBM::is_result($parent)) {
106 $parent = ['origin' => false];
109 logger('delete item: ' . $item['id'], LOGGER_DEBUG);
111 // clean up categories and tags so they don't end up as orphans
114 $cnt = preg_match_all('/<(.*?)>/', $item['file'], $matches, PREG_SET_ORDER);
116 foreach ($matches as $mtch) {
117 file_tag_unsave_file($item['uid'], $item['id'], $mtch[1],true);
123 $cnt = preg_match_all('/\[(.*?)\]/', $item['file'], $matches, PREG_SET_ORDER);
125 foreach ($matches as $mtch) {
126 file_tag_unsave_file($item['uid'], $item['id'], $mtch[1],false);
131 * If item is a link to a photo resource, nuke all the associated photos
132 * (visitors will not have photo resources)
133 * This only applies to photos uploaded from the photos page. Photos inserted into a post do not
134 * generate a resource-id and therefore aren't intimately linked to the item.
136 if (strlen($item['resource-id'])) {
137 dba::delete('photo', ['resource-id' => $item['resource-id'], 'uid' => $item['uid']]);
140 // If item is a link to an event, nuke the event record.
141 if (intval($item['event-id'])) {
142 dba::delete('event', ['id' => $item['event-id'], 'uid' => $item['uid']]);
145 // If item has attachments, drop them
146 foreach (explode(", ", $item['attach']) as $attach) {
147 preg_match("|attach/(\d+)|", $attach, $matches);
148 dba::delete('attach', ['id' => $matches[1], 'uid' => $item['uid']]);
151 // Set the item to "deleted"
152 dba::update('item', ['deleted' => true, 'title' => '', 'body' => '',
153 'edited' => DateTimeFormat::utcNow(), 'changed' => DateTimeFormat::utcNow()],
154 ['id' => $item['id']]);
156 create_tags_from_item($item['id']);
157 Term::createFromItem($item['id']);
158 delete_thread($item['id'], $item['parent-uri']);
160 // If it's the parent of a comment thread, kill all the kids
161 if ($item['id'] == $item['parent']) {
162 $items = dba::select('item', ['id'], ['parent' => $item['parent']]);
163 while ($row = dba::fetch($items)) {
164 self::delete($row['id'], $priority);
168 // send the notification upstream/downstream
169 if ($item['origin'] || $parent['origin']) {
170 Worker::add(['priority' => $priority, 'dont_fork' => true], "Notifier", "drop", intval($item['id']));
176 public static function insert($arr, $force_parent = false, $notify = false, $dontcache = false)
180 // If it is a posting where users should get notifications, then define it as wall posting
183 $arr['type'] = 'wall';
185 $arr['network'] = NETWORK_DFRN;
186 $arr['protocol'] = PROTOCOL_DFRN;
188 // We have to avoid duplicates. So we create the GUID in form of a hash of the plink or uri.
189 // In difference to the call to "self::guidFromUri" several lines below we add the hash of our own host.
190 // This is done because our host is the original creator of the post.
191 if (!isset($arr['guid'])) {
192 if (isset($arr['plink'])) {
193 $arr['guid'] = self::guidFromUri($arr['plink'], $a->get_hostname());
194 } elseif (isset($arr['uri'])) {
195 $arr['guid'] = self::guidFromUri($arr['uri'], $a->get_hostname());
199 $arr['network'] = trim(defaults($arr, 'network', NETWORK_PHANTOM));
204 } elseif ((trim($arr['guid']) == "") && (trim($arr['plink']) != "")) {
205 $arr['guid'] = self::guidFromUri($arr['plink']);
206 } elseif ((trim($arr['guid']) == "") && (trim($arr['uri']) != "")) {
207 $arr['guid'] = self::guidFromUri($arr['uri']);
209 $parsed = parse_url($arr["author-link"]);
210 $guid_prefix = hash("crc32", $parsed["host"]);
213 $arr['guid'] = notags(trim(defaults($arr, 'guid', get_guid(32, $guid_prefix))));
214 $arr['uri'] = notags(trim(defaults($arr, 'uri', item_new_uri($a->get_hostname(), $uid, $arr['guid']))));
216 // Store conversation data
217 $arr = Conversation::insert($arr);
220 * If a Diaspora signature structure was passed in, pull it out of the
221 * item array and set it aside for later storage.
225 if (x($arr, 'dsprsig')) {
226 $encoded_signature = $arr['dsprsig'];
227 $dsprsig = json_decode(base64_decode($arr['dsprsig']));
228 unset($arr['dsprsig']);
231 // Converting the plink
232 /// @TODO Check if this is really still needed
233 if ($arr['network'] == NETWORK_OSTATUS) {
234 if (isset($arr['plink'])) {
235 $arr['plink'] = OStatus::convertHref($arr['plink']);
236 } elseif (isset($arr['uri'])) {
237 $arr['plink'] = OStatus::convertHref($arr['uri']);
241 if (x($arr, 'gravity')) {
242 $arr['gravity'] = intval($arr['gravity']);
243 } elseif ($arr['parent-uri'] === $arr['uri']) {
245 } elseif (activity_match($arr['verb'],ACTIVITY_POST)) {
248 $arr['gravity'] = 6; // extensible catchall
251 $arr['type'] = defaults($arr, 'type', 'remote');
253 $uid = intval($arr['uid']);
255 // check for create date and expire time
256 $expire_interval = Config::get('system', 'dbclean-expire-days', 0);
258 $user = dba::selectFirst('user', ['expire'], ['uid' => $uid]);
259 if (DBM::is_result($user) && ($user['expire'] > 0) && (($user['expire'] < $expire_interval) || ($expire_interval == 0))) {
260 $expire_interval = $user['expire'];
263 if (($expire_interval > 0) && !empty($arr['created'])) {
264 $expire_date = time() - ($expire_interval * 86400);
265 $created_date = strtotime($arr['created']);
266 if ($created_date < $expire_date) {
267 logger('item-store: item created ('.date('c', $created_date).') before expiration time ('.date('c', $expire_date).'). ignored. ' . print_r($arr,true), LOGGER_DEBUG);
273 * Do we already have this item?
274 * We have to check several networks since Friendica posts could be repeated
275 * via OStatus (maybe Diasporsa as well)
277 if (in_array($arr['network'], [NETWORK_DIASPORA, NETWORK_DFRN, NETWORK_OSTATUS, ""])) {
278 $r = q("SELECT `id`, `network` FROM `item` WHERE `uri` = '%s' AND `uid` = %d AND `network` IN ('%s', '%s', '%s') LIMIT 1",
279 dbesc(trim($arr['uri'])),
281 dbesc(NETWORK_DIASPORA),
283 dbesc(NETWORK_OSTATUS)
285 if (DBM::is_result($r)) {
286 // We only log the entries with a different user id than 0. Otherwise we would have too many false positives
288 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']);
295 self::addLanguageInPostopts($arr);
297 $arr['wall'] = intval(defaults($arr, 'wall', 0));
298 $arr['extid'] = trim(defaults($arr, 'extid', ''));
299 $arr['author-name'] = trim(defaults($arr, 'author-name', ''));
300 $arr['author-link'] = trim(defaults($arr, 'author-link', ''));
301 $arr['author-avatar'] = trim(defaults($arr, 'author-avatar', ''));
302 $arr['owner-name'] = trim(defaults($arr, 'owner-name', ''));
303 $arr['owner-link'] = trim(defaults($arr, 'owner-link', ''));
304 $arr['owner-avatar'] = trim(defaults($arr, 'owner-avatar', ''));
305 $arr['received'] = ((x($arr, 'received') !== false) ? DateTimeFormat::utc($arr['received']) : DateTimeFormat::utcNow());
306 $arr['created'] = ((x($arr, 'created') !== false) ? DateTimeFormat::utc($arr['created']) : $arr['received']);
307 $arr['edited'] = ((x($arr, 'edited') !== false) ? DateTimeFormat::utc($arr['edited']) : $arr['created']);
308 $arr['changed'] = ((x($arr, 'changed') !== false) ? DateTimeFormat::utc($arr['changed']) : $arr['created']);
309 $arr['commented'] = ((x($arr, 'commented') !== false) ? DateTimeFormat::utc($arr['commented']) : $arr['created']);
310 $arr['title'] = trim(defaults($arr, 'title', ''));
311 $arr['location'] = trim(defaults($arr, 'location', ''));
312 $arr['coord'] = trim(defaults($arr, 'coord', ''));
313 $arr['visible'] = ((x($arr, 'visible') !== false) ? intval($arr['visible']) : 1);
315 $arr['parent-uri'] = trim(defaults($arr, 'parent-uri', $arr['uri']));
316 $arr['verb'] = trim(defaults($arr, 'verb', ''));
317 $arr['object-type'] = trim(defaults($arr, 'object-type', ''));
318 $arr['object'] = trim(defaults($arr, 'object', ''));
319 $arr['target-type'] = trim(defaults($arr, 'target-type', ''));
320 $arr['target'] = trim(defaults($arr, 'target', ''));
321 $arr['plink'] = trim(defaults($arr, 'plink', ''));
322 $arr['allow_cid'] = trim(defaults($arr, 'allow_cid', ''));
323 $arr['allow_gid'] = trim(defaults($arr, 'allow_gid', ''));
324 $arr['deny_cid'] = trim(defaults($arr, 'deny_cid', ''));
325 $arr['deny_gid'] = trim(defaults($arr, 'deny_gid', ''));
326 $arr['private'] = intval(defaults($arr, 'private', 0));
327 $arr['bookmark'] = intval(defaults($arr, 'bookmark', 0));
328 $arr['body'] = trim(defaults($arr, 'body', ''));
329 $arr['tag'] = trim(defaults($arr, 'tag', ''));
330 $arr['attach'] = trim(defaults($arr, 'attach', ''));
331 $arr['app'] = trim(defaults($arr, 'app', ''));
332 $arr['origin'] = intval(defaults($arr, 'origin', 0));
333 $arr['postopts'] = trim(defaults($arr, 'postopts', ''));
334 $arr['resource-id'] = trim(defaults($arr, 'resource-id', ''));
335 $arr['event-id'] = intval(defaults($arr, 'event-id', 0));
336 $arr['inform'] = trim(defaults($arr, 'inform', ''));
337 $arr['file'] = trim(defaults($arr, 'file', ''));
339 // When there is no content then we don't post it
340 if ($arr['body'].$arr['title'] == '') {
344 // Items cannot be stored before they happen ...
345 if ($arr['created'] > DateTimeFormat::utcNow()) {
346 $arr['created'] = DateTimeFormat::utcNow();
349 // We haven't invented time travel by now.
350 if ($arr['edited'] > DateTimeFormat::utcNow()) {
351 $arr['edited'] = DateTimeFormat::utcNow();
354 if (($arr['author-link'] == "") && ($arr['owner-link'] == "")) {
355 logger("Both author-link and owner-link are empty. Called by: " . System::callstack(), LOGGER_DEBUG);
358 if ($arr['plink'] == "") {
359 $arr['plink'] = System::baseUrl() . '/display/' . urlencode($arr['guid']);
362 if ($arr['network'] == NETWORK_PHANTOM) {
363 $r = q("SELECT `network` FROM `contact` WHERE `network` IN ('%s', '%s', '%s') AND `nurl` = '%s' AND `uid` = %d LIMIT 1",
364 dbesc(NETWORK_DFRN), dbesc(NETWORK_DIASPORA), dbesc(NETWORK_OSTATUS),
365 dbesc(normalise_link($arr['author-link'])),
369 if (!DBM::is_result($r)) {
370 $r = q("SELECT `network` FROM `gcontact` WHERE `network` IN ('%s', '%s', '%s') AND `nurl` = '%s' LIMIT 1",
371 dbesc(NETWORK_DFRN), dbesc(NETWORK_DIASPORA), dbesc(NETWORK_OSTATUS),
372 dbesc(normalise_link($arr['author-link']))
376 if (!DBM::is_result($r)) {
377 $r = q("SELECT `network` FROM `contact` WHERE `id` = %d AND `uid` = %d LIMIT 1",
378 intval($arr['contact-id']),
383 if (DBM::is_result($r)) {
384 $arr['network'] = $r[0]["network"];
387 // Fallback to friendica (why is it empty in some cases?)
388 if ($arr['network'] == "") {
389 $arr['network'] = NETWORK_DFRN;
392 logger("Set network to " . $arr["network"] . " for " . $arr["uri"], LOGGER_DEBUG);
395 // The contact-id should be set before "self::insert" was called - but there seems to be some issues
396 if ($arr["contact-id"] == 0) {
398 * First we are looking for a suitable contact that matches with the author of the post
399 * This is done only for comments (See below explanation at "gcontact-id")
401 if ($arr['parent-uri'] != $arr['uri']) {
402 $arr["contact-id"] = Contact::getIdForURL($arr['author-link'], $uid);
405 // If not present then maybe the owner was found
406 if ($arr["contact-id"] == 0) {
407 $arr["contact-id"] = Contact::getIdForURL($arr['owner-link'], $uid);
410 // Still missing? Then use the "self" contact of the current user
411 if ($arr["contact-id"] == 0) {
412 $r = q("SELECT `id` FROM `contact` WHERE `self` AND `uid` = %d", intval($uid));
414 if (DBM::is_result($r)) {
415 $arr["contact-id"] = $r[0]["id"];
419 logger("Contact-id was missing for post ".$arr["guid"]." from user id ".$uid." - now set to ".$arr["contact-id"], LOGGER_DEBUG);
422 if (!x($arr, "gcontact-id")) {
424 * The gcontact should mostly behave like the contact. But is is supposed to be global for the system.
425 * This means that wall posts, repeated posts, etc. should have the gcontact id of the owner.
426 * On comments the author is the better choice.
428 if ($arr['parent-uri'] === $arr['uri']) {
429 $arr["gcontact-id"] = GContact::getId(["url" => $arr['owner-link'], "network" => $arr['network'],
430 "photo" => $arr['owner-avatar'], "name" => $arr['owner-name']]);
432 $arr["gcontact-id"] = GContact::getId(["url" => $arr['author-link'], "network" => $arr['network'],
433 "photo" => $arr['author-avatar'], "name" => $arr['author-name']]);
437 if ($arr["author-id"] == 0) {
438 $arr["author-id"] = Contact::getIdForURL($arr["author-link"], 0);
441 if (Contact::isBlocked($arr["author-id"])) {
442 logger('Contact '.$arr["author-id"].' is blocked, item '.$arr["uri"].' will not be stored');
446 if ($arr["owner-id"] == 0) {
447 $arr["owner-id"] = Contact::getIdForURL($arr["owner-link"], 0);
450 if (Contact::isBlocked($arr["owner-id"])) {
451 logger('Contact '.$arr["owner-id"].' is blocked, item '.$arr["uri"].' will not be stored');
455 if ($arr['guid'] != "") {
456 // Checking if there is already an item with the same guid
457 logger('checking for an item for user '.$arr['uid'].' on network '.$arr['network'].' with the guid '.$arr['guid'], LOGGER_DEBUG);
458 $r = q("SELECT `guid` FROM `item` WHERE `guid` = '%s' AND `network` = '%s' AND `uid` = '%d' LIMIT 1",
459 dbesc($arr['guid']), dbesc($arr['network']), intval($arr['uid']));
461 if (DBM::is_result($r)) {
462 logger('found item with guid '.$arr['guid'].' for user '.$arr['uid'].' on network '.$arr['network'], LOGGER_DEBUG);
467 // Check for hashtags in the body and repair or add hashtag links
468 self::setHashtags($arr);
470 $arr['thr-parent'] = $arr['parent-uri'];
472 if ($arr['parent-uri'] === $arr['uri']) {
475 $allow_cid = $arr['allow_cid'];
476 $allow_gid = $arr['allow_gid'];
477 $deny_cid = $arr['deny_cid'];
478 $deny_gid = $arr['deny_gid'];
479 $notify_type = 'wall-new';
482 // find the parent and snarf the item id and ACLs
483 // and anything else we need to inherit
485 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d ORDER BY `id` ASC LIMIT 1",
486 dbesc($arr['parent-uri']),
490 if (DBM::is_result($r)) {
492 // is the new message multi-level threaded?
493 // even though we don't support it now, preserve the info
494 // and re-attach to the conversation parent.
496 if ($r[0]['uri'] != $r[0]['parent-uri']) {
497 $arr['parent-uri'] = $r[0]['parent-uri'];
498 $z = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `parent-uri` = '%s' AND `uid` = %d
499 ORDER BY `id` ASC LIMIT 1",
500 dbesc($r[0]['parent-uri']),
501 dbesc($r[0]['parent-uri']),
505 if (DBM::is_result($z)) {
510 $parent_id = $r[0]['id'];
511 $parent_deleted = $r[0]['deleted'];
512 $allow_cid = $r[0]['allow_cid'];
513 $allow_gid = $r[0]['allow_gid'];
514 $deny_cid = $r[0]['deny_cid'];
515 $deny_gid = $r[0]['deny_gid'];
516 $arr['wall'] = $r[0]['wall'];
517 $notify_type = 'comment-new';
520 * If the parent is private, force privacy for the entire conversation
521 * This differs from the above settings as it subtly allows comments from
522 * email correspondents to be private even if the overall thread is not.
524 if ($r[0]['private']) {
525 $arr['private'] = $r[0]['private'];
529 * Edge case. We host a public forum that was originally posted to privately.
530 * The original author commented, but as this is a comment, the permissions
531 * weren't fixed up so it will still show the comment as private unless we fix it here.
533 if ((intval($r[0]['forum_mode']) == 1) && $r[0]['private']) {
537 // If its a post from myself then tag the thread as "mention"
538 logger("Checking if parent ".$parent_id." has to be tagged as mention for user ".$arr['uid'], LOGGER_DEBUG);
539 $u = q("SELECT `nickname` FROM `user` WHERE `uid` = %d", intval($arr['uid']));
540 if (DBM::is_result($u)) {
541 $self = normalise_link(System::baseUrl() . '/profile/' . $u[0]['nickname']);
542 logger("'myself' is ".$self." for parent ".$parent_id." checking against ".$arr['author-link']." and ".$arr['owner-link'], LOGGER_DEBUG);
543 if ((normalise_link($arr['author-link']) == $self) || (normalise_link($arr['owner-link']) == $self)) {
544 dba::update('thread', ['mention' => true], ['iid' => $parent_id]);
545 logger("tagged thread ".$parent_id." as mention for user ".$self, LOGGER_DEBUG);
550 * Allow one to see reply tweets from status.net even when
551 * we don't have or can't see the original post.
554 logger('$force_parent=true, reply converted to top-level post.');
556 $arr['parent-uri'] = $arr['uri'];
559 logger('item parent '.$arr['parent-uri'].' for '.$arr['uid'].' was not found - ignoring item');
567 $r = q("SELECT `id` FROM `item` WHERE `uri` = '%s' AND `network` IN ('%s', '%s') AND `uid` = %d LIMIT 1",
569 dbesc($arr['network']),
573 if (DBM::is_result($r)) {
574 logger('duplicated item with the same uri found. '.print_r($arr,true));
578 // On Friendica and Diaspora the GUID is unique
579 if (in_array($arr['network'], [NETWORK_DFRN, NETWORK_DIASPORA])) {
580 $r = q("SELECT `id` FROM `item` WHERE `guid` = '%s' AND `uid` = %d LIMIT 1",
584 if (DBM::is_result($r)) {
585 logger('duplicated item with the same guid found. '.print_r($arr,true));
589 // Check for an existing post with the same content. There seems to be a problem with OStatus.
590 $r = q("SELECT `id` FROM `item` WHERE `body` = '%s' AND `network` = '%s' AND `created` = '%s' AND `contact-id` = %d AND `uid` = %d LIMIT 1",
592 dbesc($arr['network']),
593 dbesc($arr['created']),
594 intval($arr['contact-id']),
597 if (DBM::is_result($r)) {
598 logger('duplicated item with the same body found. '.print_r($arr,true));
603 // Is this item available in the global items (with uid=0)?
604 if ($arr["uid"] == 0) {
605 $arr["global"] = true;
607 // Set the global flag on all items if this was a global item entry
608 dba::update('item', ['global' => true], ['uri' => $arr["uri"]]);
610 $isglobal = q("SELECT `global` FROM `item` WHERE `uid` = 0 AND `uri` = '%s'", dbesc($arr["uri"]));
612 $arr["global"] = (DBM::is_result($isglobal) && count($isglobal) > 0);
616 if (strlen($allow_cid) || strlen($allow_gid) || strlen($deny_cid) || strlen($deny_gid)) {
619 $private = $arr['private'];
622 $arr["allow_cid"] = $allow_cid;
623 $arr["allow_gid"] = $allow_gid;
624 $arr["deny_cid"] = $deny_cid;
625 $arr["deny_gid"] = $deny_gid;
626 $arr["private"] = $private;
627 $arr["deleted"] = $parent_deleted;
629 // Fill the cache field
630 put_item_in_cache($arr);
633 Addon::callHooks('post_local', $arr);
635 Addon::callHooks('post_remote', $arr);
638 // This array field is used to trigger some automatic reactions
639 // It is mainly used in the "post_local" hook.
640 unset($arr['api_source']);
642 if (x($arr, 'cancel')) {
643 logger('post cancelled by addon.');
648 * Check for already added items.
649 * There is a timing issue here that sometimes creates double postings.
650 * An unique index would help - but the limitations of MySQL (maximum size of index values) prevent this.
652 if ($arr["uid"] == 0) {
653 $r = q("SELECT `id` FROM `item` WHERE `uri` = '%s' AND `uid` = 0 LIMIT 1", dbesc(trim($arr['uri'])));
654 if (DBM::is_result($r)) {
655 logger('Global item already stored. URI: '.$arr['uri'].' on network '.$arr['network'], LOGGER_DEBUG);
660 logger('' . print_r($arr,true), LOGGER_DATA);
663 $r = dba::insert('item', $arr);
665 // When the item was successfully stored we fetch the ID of the item.
666 if (DBM::is_result($r)) {
667 $current_post = dba::lastInsertId();
669 // This can happen - for example - if there are locking timeouts.
672 // Store the data into a spool file so that we can try again later.
674 // At first we restore the Diaspora signature that we removed above.
675 if (isset($encoded_signature)) {
676 $arr['dsprsig'] = $encoded_signature;
679 // Now we store the data in the spool directory
680 // We use "microtime" to keep the arrival order and "mt_rand" to avoid duplicates
681 $file = 'item-'.round(microtime(true) * 10000).'-'.mt_rand().'.msg';
683 $spoolpath = get_spoolpath();
684 if ($spoolpath != "") {
685 $spool = $spoolpath.'/'.$file;
686 file_put_contents($spool, json_encode($arr));
687 logger("Item wasn't stored - Item was spooled into file ".$file, LOGGER_DEBUG);
692 if ($current_post == 0) {
693 // This is one of these error messages that never should occur.
694 logger("couldn't find created item - we better quit now.");
699 // How much entries have we created?
700 // We wouldn't need this query when we could use an unique index - but MySQL has length problems with them.
701 $r = q("SELECT COUNT(*) AS `entries` FROM `item` WHERE `uri` = '%s' AND `uid` = %d AND `network` = '%s'",
704 dbesc($arr['network'])
707 if (!DBM::is_result($r)) {
708 // This shouldn't happen, since COUNT always works when the database connection is there.
709 logger("We couldn't count the stored entries. Very strange ...");
714 if ($r[0]["entries"] > 1) {
715 // There are duplicates. We delete our just created entry.
716 logger('Duplicated post occurred. uri = ' . $arr['uri'] . ' uid = ' . $arr['uid']);
718 // Yes, we could do a rollback here - but we are having many users with MyISAM.
719 dba::delete('item', ['id' => $current_post]);
722 } elseif ($r[0]["entries"] == 0) {
723 // This really should never happen since we quit earlier if there were problems.
724 logger("Something is terribly wrong. We haven't found our created entry.");
729 logger('created item '.$current_post);
730 self::updateContact($arr);
732 if (!$parent_id || ($arr['parent-uri'] === $arr['uri'])) {
733 $parent_id = $current_post;
737 dba::update('item', ['parent' => $parent_id], ['id' => $current_post]);
739 $arr['id'] = $current_post;
740 $arr['parent'] = $parent_id;
742 // update the commented timestamp on the parent
743 // Only update "commented" if it is really a comment
744 if (($arr['verb'] == ACTIVITY_POST) || !Config::get("system", "like_no_comment")) {
745 dba::update('item', ['commented' => DateTimeFormat::utcNow(), 'changed' => DateTimeFormat::utcNow()], ['id' => $parent_id]);
747 dba::update('item', ['changed' => DateTimeFormat::utcNow()], ['id' => $parent_id]);
752 * Friendica servers lower than 3.4.3-2 had double encoded the signature ...
753 * We can check for this condition when we decode and encode the stuff again.
755 if (base64_encode(base64_decode(base64_decode($dsprsig->signature))) == base64_decode($dsprsig->signature)) {
756 $dsprsig->signature = base64_decode($dsprsig->signature);
757 logger("Repaired double encoded signature from handle ".$dsprsig->signer, LOGGER_DEBUG);
760 dba::insert('sign', ['iid' => $current_post, 'signed_text' => $dsprsig->signed_text,
761 'signature' => $dsprsig->signature, 'signer' => $dsprsig->signer]);
764 $deleted = self::tagDeliver($arr['uid'], $current_post);
767 * current post can be deleted if is for a community page and no mention are
770 if (!$deleted && !$dontcache) {
771 $r = q('SELECT * FROM `item` WHERE `id` = %d', intval($current_post));
772 if (DBM::is_result($r) && (count($r) == 1)) {
774 Addon::callHooks('post_local_end', $r[0]);
776 Addon::callHooks('post_remote_end', $r[0]);
779 logger('new item not found in DB, id ' . $current_post);
783 if ($arr['parent-uri'] === $arr['uri']) {
784 add_thread($current_post);
786 update_thread($parent_id);
792 * Due to deadlock issues with the "term" table we are doing these steps after the commit.
793 * This is not perfect - but a workable solution until we found the reason for the problem.
795 create_tags_from_item($current_post);
796 Term::createFromItem($current_post);
798 if ($arr['parent-uri'] === $arr['uri']) {
799 self::addShadow($current_post);
801 self::addShadowPost($current_post);
804 check_user_notification($current_post);
807 Worker::add(['priority' => PRIORITY_HIGH, 'dont_fork' => true], "Notifier", $notify_type, $current_post);
810 return $current_post;
814 * @brief Add a shadow entry for a given item id that is a thread starter
816 * We store every public item entry additionally with the user id "0".
817 * This is used for the community page and for the search.
818 * It is planned that in the future we will store public item entries only once.
820 * @param integer $itemid Item ID that should be added
822 public static function addShadow($itemid)
824 $fields = ['uid', 'wall', 'private', 'moderated', 'visible', 'contact-id', 'deleted', 'network', 'author-id', 'owner-id'];
825 $condition = ["`id` = ? AND (`parent` = ? OR `parent` = 0)", $itemid, $itemid];
826 $item = dba::selectFirst('item', $fields, $condition);
828 if (!DBM::is_result($item)) {
832 // is it already a copy?
833 if (($itemid == 0) || ($item['uid'] == 0)) {
837 // Is it a visible public post?
838 if (!$item["visible"] || $item["deleted"] || $item["moderated"] || $item["private"]) {
842 // is it an entry from a connector? Only add an entry for natively connected networks
843 if (!in_array($item["network"], [NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, ""])) {
847 // Is the public contact configured as hidden?
848 if (Contact::isHidden($item["owner-id"]) || Contact::isHidden($item["author-id"])) {
852 // Only do these checks if the post isn't a wall post
853 if (!$item["wall"]) {
854 // Check, if hide-friends is activated - then don't do a shadow entry
855 if (dba::exists('profile', ['is-default' => true, 'uid' => $item['uid'], 'hide-friends' => true])) {
859 // Check if the contact is hidden or blocked
860 if (!dba::exists('contact', ['hidden' => false, 'blocked' => false, 'id' => $item['contact-id']])) {
865 // Only add a shadow, if the profile isn't hidden
866 if (dba::exists('user', ['uid' => $item['uid'], 'hidewall' => true])) {
870 $item = dba::selectFirst('item', [], ['id' => $itemid]);
872 if (DBM::is_result($item) && ($item["allow_cid"] == '') && ($item["allow_gid"] == '') &&
873 ($item["deny_cid"] == '') && ($item["deny_gid"] == '')) {
875 if (!dba::exists('item', ['uri' => $item['uri'], 'uid' => 0])) {
876 // Preparing public shadow (removing user specific data)
881 $item['contact-id'] = Contact::getIdForURL($item['author-link'], 0);
883 if (in_array($item['type'], ["net-comment", "wall-comment"])) {
884 $item['type'] = 'remote-comment';
885 } elseif ($item['type'] == 'wall') {
886 $item['type'] = 'remote';
889 $public_shadow = self::insert($item, false, false, true);
891 logger("Stored public shadow for thread ".$itemid." under id ".$public_shadow, LOGGER_DEBUG);
897 * @brief Add a shadow entry for a given item id that is a comment
899 * This function does the same like the function above - but for comments
901 * @param integer $itemid Item ID that should be added
903 public static function addShadowPost($itemid)
905 $item = dba::selectFirst('item', [], ['id' => $itemid]);
906 if (!DBM::is_result($item)) {
910 // Is it a toplevel post?
911 if ($item['id'] == $item['parent']) {
912 self::addShadow($itemid);
916 // Is this a shadow entry?
917 if ($item['uid'] == 0)
920 // Is there a shadow parent?
921 if (!dba::exists('item', ['uri' => $item['parent-uri'], 'uid' => 0])) {
925 // Is there already a shadow entry?
926 if (dba::exists('item', ['uri' => $item['uri'], 'uid' => 0])) {
930 // Preparing public shadow (removing user specific data)
935 $item['contact-id'] = Contact::getIdForURL($item['author-link'], 0);
937 if (in_array($item['type'], ["net-comment", "wall-comment"])) {
938 $item['type'] = 'remote-comment';
939 } elseif ($item['type'] == 'wall') {
940 $item['type'] = 'remote';
943 $public_shadow = self::insert($item, false, false, true);
945 logger("Stored public shadow for comment ".$item['uri']." under id ".$public_shadow, LOGGER_DEBUG);
949 * Adds a "lang" specification in a "postopts" element of given $arr,
950 * if possible and not already present.
951 * Expects "body" element to exist in $arr.
953 private static function addLanguageInPostopts(&$arr)
955 if (x($arr, 'postopts')) {
956 if (strstr($arr['postopts'], 'lang=')) {
960 $postopts = $arr['postopts'];
965 $naked_body = preg_replace('/\[(.+?)\]/','', $arr['body']);
966 $l = new Text_LanguageDetect();
967 $lng = $l->detect($naked_body, 3);
969 if (sizeof($lng) > 0) {
970 if ($postopts != "") {
971 $postopts .= '&'; // arbitrary separator, to be reviewed
974 $postopts .= 'lang=';
977 foreach ($lng as $language => $score) {
978 $postopts .= $sep . $language . ";" . $score;
981 $arr['postopts'] = $postopts;
986 * @brief Creates an unique guid out of a given uri
988 * @param string $uri uri of an item entry
989 * @param string $host (Optional) hostname for the GUID prefix
990 * @return string unique guid
992 public static function guidFromUri($uri, $host = "")
994 // Our regular guid routine is using this kind of prefix as well
995 // We have to avoid that different routines could accidentally create the same value
996 $parsed = parse_url($uri);
998 // When the hostname isn't given, we take it from the uri
1000 // Is it in the format data@host.tld?
1001 if ((count($parsed) == 1) && strstr($uri, '@')) {
1002 $mailparts = explode('@', $uri);
1003 $host = array_pop($mailparts);
1005 $host = $parsed["host"];
1009 // We use a hash of the hostname as prefix for the guid
1010 $guid_prefix = hash("crc32", $host);
1012 // Remove the scheme to make sure that "https" and "http" doesn't make a difference
1013 unset($parsed["scheme"]);
1015 // Glue it together to be able to make a hash from it
1016 $host_id = implode("/", $parsed);
1018 // We could use any hash algorithm since it isn't a security issue
1019 $host_hash = hash("ripemd128", $host_id);
1021 return $guid_prefix.$host_hash;
1025 * @brief Set "success_update" and "last-item" to the date of the last time we heard from this contact
1027 * This can be used to filter for inactive contacts.
1028 * Only do this for public postings to avoid privacy problems, since poco data is public.
1029 * Don't set this value if it isn't from the owner (could be an author that we don't know)
1031 * @param array $arr Contains the just posted item record
1033 private static function updateContact($arr)
1035 // Unarchive the author
1036 $contact = dba::selectFirst('contact', [], ['id' => $arr["author-link"]]);
1037 if ($contact['term-date'] > NULL_DATE) {
1038 Contact::unmarkForArchival($contact);
1041 // Unarchive the contact if it is a toplevel posting
1042 if ($arr["parent-uri"] === $arr["uri"]) {
1043 $contact = dba::selectFirst('contact', [], ['id' => $arr["contact-id"]]);
1044 if ($contact['term-date'] > NULL_DATE) {
1045 Contact::unmarkForArchival($contact);
1049 $update = (!$arr['private'] && (($arr["author-link"] === $arr["owner-link"]) || ($arr["parent-uri"] === $arr["uri"])));
1051 // Is it a forum? Then we don't care about the rules from above
1052 if (!$update && ($arr["network"] == NETWORK_DFRN) && ($arr["parent-uri"] === $arr["uri"])) {
1053 $isforum = q("SELECT `forum` FROM `contact` WHERE `id` = %d AND `forum`",
1054 intval($arr['contact-id']));
1055 if (DBM::is_result($isforum)) {
1061 dba::update('contact', ['success_update' => $arr['received'], 'last-item' => $arr['received']],
1062 ['id' => $arr['contact-id']]);
1064 // Now do the same for the system wide contacts with uid=0
1065 if (!$arr['private']) {
1066 dba::update('contact', ['success_update' => $arr['received'], 'last-item' => $arr['received']],
1067 ['id' => $arr['owner-id']]);
1069 if ($arr['owner-id'] != $arr['author-id']) {
1070 dba::update('contact', ['success_update' => $arr['received'], 'last-item' => $arr['received']],
1071 ['id' => $arr['author-id']]);
1076 private static function setHashtags(&$item)
1079 $tags = get_tags($item["body"]);
1082 if (!count($tags)) {
1086 // This sorting is important when there are hashtags that are part of other hashtags
1087 // Otherwise there could be problems with hashtags like #test and #test2
1090 $URLSearchString = "^\[\]";
1092 // All hashtags should point to the home server if "local_tags" is activated
1093 if (Config::get('system', 'local_tags')) {
1094 $item["body"] = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
1095 "#[url=".System::baseUrl()."/search?tag=$2]$2[/url]", $item["body"]);
1097 $item["tag"] = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
1098 "#[url=".System::baseUrl()."/search?tag=$2]$2[/url]", $item["tag"]);
1101 // mask hashtags inside of url, bookmarks and attachments to avoid urls in urls
1102 $item["body"] = preg_replace_callback("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
1104 return ("[url=" . str_replace("#", "#", $match[1]) . "]" . str_replace("#", "#", $match[2]) . "[/url]");
1107 $item["body"] = preg_replace_callback("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism",
1109 return ("[bookmark=" . str_replace("#", "#", $match[1]) . "]" . str_replace("#", "#", $match[2]) . "[/bookmark]");
1112 $item["body"] = preg_replace_callback("/\[attachment (.*)\](.*?)\[\/attachment\]/ism",
1114 return ("[attachment " . str_replace("#", "#", $match[1]) . "]" . $match[2] . "[/attachment]");
1117 // Repair recursive urls
1118 $item["body"] = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
1119 "#$2", $item["body"]);
1121 foreach ($tags as $tag) {
1122 if ((strpos($tag, '#') !== 0) || strpos($tag, '[url=')) {
1126 $basetag = str_replace('_',' ',substr($tag,1));
1128 $newtag = '#[url=' . System::baseUrl() . '/search?tag=' . rawurlencode($basetag) . ']' . $basetag . '[/url]';
1130 $item["body"] = str_replace($tag, $newtag, $item["body"]);
1132 if (!stristr($item["tag"], "/search?tag=" . $basetag . "]" . $basetag . "[/url]")) {
1133 if (strlen($item["tag"])) {
1134 $item["tag"] = ','.$item["tag"];
1136 $item["tag"] = $newtag.$item["tag"];
1140 // Convert back the masked hashtags
1141 $item["body"] = str_replace("#", "#", $item["body"]);
1144 public static function getGuidById($id)
1146 $r = q("SELECT `guid` FROM `item` WHERE `id` = %d LIMIT 1", intval($id));
1147 if (DBM::is_result($r)) {
1148 return $r[0]["guid"];
1154 public static function getIdAndNickByGuid($guid, $uid = 0)
1160 $uid == local_user();
1163 // Does the given user have this item?
1165 $r = q("SELECT `item`.`id`, `user`.`nickname` FROM `item` INNER JOIN `user` ON `user`.`uid` = `item`.`uid`
1166 WHERE `item`.`visible` = 1 AND `item`.`deleted` = 0 AND `item`.`moderated` = 0
1167 AND `item`.`guid` = '%s' AND `item`.`uid` = %d", dbesc($guid), intval($uid));
1168 if (DBM::is_result($r)) {
1170 $nick = $r[0]["nickname"];
1174 // Or is it anywhere on the server?
1176 $r = q("SELECT `item`.`id`, `user`.`nickname` FROM `item` INNER JOIN `user` ON `user`.`uid` = `item`.`uid`
1177 WHERE `item`.`visible` = 1 AND `item`.`deleted` = 0 AND `item`.`moderated` = 0
1178 AND `item`.`allow_cid` = '' AND `item`.`allow_gid` = ''
1179 AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = ''
1180 AND `item`.`private` = 0 AND `item`.`wall` = 1
1181 AND `item`.`guid` = '%s'", dbesc($guid));
1182 if (DBM::is_result($r)) {
1184 $nick = $r[0]["nickname"];
1187 return ["nick" => $nick, "id" => $id];
1191 * look for mention tags and setup a second delivery chain for forum/community posts if appropriate
1193 * @param int $item_id
1194 * @return bool true if item was deleted, else false
1196 private static function tagDeliver($uid, $item_id)
1200 $u = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
1203 if (!DBM::is_result($u)) {
1207 $community_page = (($u[0]['page-flags'] == PAGE_COMMUNITY) ? true : false);
1208 $prvgroup = (($u[0]['page-flags'] == PAGE_PRVGROUP) ? true : false);
1210 $i = q("SELECT * FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1",
1214 if (!DBM::is_result($i)) {
1220 $link = normalise_link(System::baseUrl() . '/profile/' . $u[0]['nickname']);
1223 * Diaspora uses their own hardwired link URL in @-tags
1224 * instead of the one we supply with webfinger
1226 $dlink = normalise_link(System::baseUrl() . '/u/' . $u[0]['nickname']);
1228 $cnt = preg_match_all('/[\@\!]\[url\=(.*?)\](.*?)\[\/url\]/ism', $item['body'], $matches, PREG_SET_ORDER);
1230 foreach ($matches as $mtch) {
1231 if (link_compare($link, $mtch[1]) || link_compare($dlink, $mtch[1])) {
1233 logger('mention found: ' . $mtch[2]);
1239 if (($community_page || $prvgroup) &&
1240 !$item['wall'] && !$item['origin'] && ($item['id'] == $item['parent'])) {
1241 // mmh.. no mention.. community page or private group... no wall.. no origin.. top-post (not a comment)
1243 logger("no-mention top-level post to communuty or private group. delete.");
1244 dba::delete('item', ['id' => $item_id]);
1250 $arr = ['item' => $item, 'user' => $u[0], 'contact' => $r[0]];
1252 Addon::callHooks('tagged', $arr);
1254 if (!$community_page && !$prvgroup) {
1259 * tgroup delivery - setup a second delivery chain
1260 * prevent delivery looping - only proceed
1261 * if the message originated elsewhere and is a top-level post
1263 if ($item['wall'] || $item['origin'] || ($item['id'] != $item['parent'])) {
1267 // now change this copy of the post to a forum head message and deliver to all the tgroup members
1268 $c = q("SELECT `name`, `url`, `thumb` FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
1269 intval($u[0]['uid'])
1271 if (!DBM::is_result($c)) {
1275 // also reset all the privacy bits to the forum default permissions
1277 $private = ($u[0]['allow_cid'] || $u[0]['allow_gid'] || $u[0]['deny_cid'] || $u[0]['deny_gid']) ? 1 : 0;
1279 $forum_mode = (($prvgroup) ? 2 : 1);
1281 q("UPDATE `item` SET `wall` = 1, `origin` = 1, `forum_mode` = %d, `owner-name` = '%s', `owner-link` = '%s', `owner-avatar` = '%s',
1282 `private` = %d, `allow_cid` = '%s', `allow_gid` = '%s', `deny_cid` = '%s', `deny_gid` = '%s' WHERE `id` = %d",
1283 intval($forum_mode),
1284 dbesc($c[0]['name']),
1285 dbesc($c[0]['url']),
1286 dbesc($c[0]['thumb']),
1288 dbesc($u[0]['allow_cid']),
1289 dbesc($u[0]['allow_gid']),
1290 dbesc($u[0]['deny_cid']),
1291 dbesc($u[0]['deny_gid']),
1294 update_thread($item_id);
1296 Worker::add(['priority' => PRIORITY_HIGH, 'dont_fork' => true], 'Notifier', 'tgroup', $item_id);
1300 public static function isRemoteSelf($contact, &$datarray)
1304 if (!$contact['remote_self']) {
1308 // Prevent the forwarding of posts that are forwarded
1309 if ($datarray["extid"] == NETWORK_DFRN) {
1313 // Prevent to forward already forwarded posts
1314 if ($datarray["app"] == $a->get_hostname()) {
1318 // Only forward posts
1319 if ($datarray["verb"] != ACTIVITY_POST) {
1323 if (($contact['network'] != NETWORK_FEED) && $datarray['private']) {
1327 $datarray2 = $datarray;
1328 logger('remote-self start - Contact '.$contact['url'].' - '.$contact['remote_self'].' Item '.print_r($datarray, true), LOGGER_DEBUG);
1329 if ($contact['remote_self'] == 2) {
1330 $r = q("SELECT `id`,`url`,`name`,`thumb` FROM `contact` WHERE `uid` = %d AND `self`",
1331 intval($contact['uid']));
1332 if (DBM::is_result($r)) {
1333 $datarray['contact-id'] = $r[0]["id"];
1335 $datarray['owner-name'] = $r[0]["name"];
1336 $datarray['owner-link'] = $r[0]["url"];
1337 $datarray['owner-avatar'] = $r[0]["thumb"];
1339 $datarray['author-name'] = $datarray['owner-name'];
1340 $datarray['author-link'] = $datarray['owner-link'];
1341 $datarray['author-avatar'] = $datarray['owner-avatar'];
1343 unset($datarray['created']);
1344 unset($datarray['edited']);
1347 if ($contact['network'] != NETWORK_FEED) {
1348 $datarray["guid"] = get_guid(32);
1349 unset($datarray["plink"]);
1350 $datarray["uri"] = item_new_uri($a->get_hostname(), $contact['uid'], $datarray["guid"]);
1351 $datarray["parent-uri"] = $datarray["uri"];
1352 $datarray["extid"] = $contact['network'];
1353 $urlpart = parse_url($datarray2['author-link']);
1354 $datarray["app"] = $urlpart["host"];
1356 $datarray['private'] = 0;
1360 if ($contact['network'] != NETWORK_FEED) {
1361 // Store the original post
1362 $r = self::insert($datarray2, false, false);
1363 logger('remote-self post original item - Contact '.$contact['url'].' return '.$r.' Item '.print_r($datarray2, true), LOGGER_DEBUG);
1365 $datarray["app"] = "Feed";
1368 // Trigger automatic reactions for addons
1369 $datarray['api_source'] = true;
1371 // We have to tell the hooks who we are - this really should be improved
1372 $_SESSION["authenticated"] = true;
1373 $_SESSION["uid"] = $contact['uid'];
1382 * @param array $item
1386 public static function fixPrivatePhotos($s, $uid, $item = null, $cid = 0)
1388 if (Config::get('system', 'disable_embedded')) {
1392 logger('check for photos', LOGGER_DEBUG);
1393 $site = substr(System::baseUrl(), strpos(System::baseUrl(), '://'));
1398 $img_start = strpos($orig_body, '[img');
1399 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
1400 $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
1402 while (($img_st_close !== false) && ($img_len !== false)) {
1403 $img_st_close++; // make it point to AFTER the closing bracket
1404 $image = substr($orig_body, $img_start + $img_st_close, $img_len);
1406 logger('found photo ' . $image, LOGGER_DEBUG);
1408 if (stristr($image, $site . '/photo/')) {
1409 // Only embed locally hosted photos
1411 $i = basename($image);
1412 $i = str_replace(['.jpg', '.png', '.gif'], ['', '', ''], $i);
1413 $x = strpos($i, '-');
1416 $res = substr($i, $x + 1);
1417 $i = substr($i, 0, $x);
1418 $r = q("SELECT * FROM `photo` WHERE `resource-id` = '%s' AND `scale` = %d AND `uid` = %d",
1423 if (DBM::is_result($r)) {
1425 * Check to see if we should replace this photo link with an embedded image
1426 * 1. No need to do so if the photo is public
1427 * 2. If there's a contact-id provided, see if they're in the access list
1428 * for the photo. If so, embed it.
1429 * 3. Otherwise, if we have an item, see if the item permissions match the photo
1430 * permissions, regardless of order but first check to see if they're an exact
1431 * match to save some processing overhead.
1433 if (self::hasPermissions($r[0])) {
1435 $recips = self::enumeratePermissions($r[0]);
1436 if (in_array($cid, $recips)) {
1440 if (self::samePermissions($item, $r[0])) {
1446 $data = $r[0]['data'];
1447 $type = $r[0]['type'];
1449 // If a custom width and height were specified, apply before embedding
1450 if (preg_match("/\[img\=([0-9]*)x([0-9]*)\]/is", substr($orig_body, $img_start, $img_st_close), $match)) {
1451 logger('scaling photo', LOGGER_DEBUG);
1453 $width = intval($match[1]);
1454 $height = intval($match[2]);
1456 $Image = new Image($data, $type);
1457 if ($Image->isValid()) {
1458 $Image->scaleDown(max($width, $height));
1459 $data = $Image->asString();
1460 $type = $Image->getType();
1464 logger('replacing photo', LOGGER_DEBUG);
1465 $image = 'data:' . $type . ';base64,' . base64_encode($data);
1466 logger('replaced: ' . $image, LOGGER_DATA);
1472 $new_body = $new_body . substr($orig_body, 0, $img_start + $img_st_close) . $image . '[/img]';
1473 $orig_body = substr($orig_body, $img_start + $img_st_close + $img_len + strlen('[/img]'));
1474 if ($orig_body === false) {
1478 $img_start = strpos($orig_body, '[img');
1479 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
1480 $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
1483 $new_body = $new_body . $orig_body;
1488 private static function hasPermissions($obj)
1492 x($obj, 'allow_cid')
1494 x($obj, 'allow_gid')
1503 private static function samePermissions($obj1, $obj2)
1505 // first part is easy. Check that these are exactly the same.
1506 if (($obj1['allow_cid'] == $obj2['allow_cid'])
1507 && ($obj1['allow_gid'] == $obj2['allow_gid'])
1508 && ($obj1['deny_cid'] == $obj2['deny_cid'])
1509 && ($obj1['deny_gid'] == $obj2['deny_gid'])) {
1513 // This is harder. Parse all the permissions and compare the resulting set.
1514 $recipients1 = self::enumeratePermissions($obj1);
1515 $recipients2 = self::enumeratePermissions($obj2);
1519 /// @TODO Comparison of arrays, maybe use array_diff_assoc() here?
1520 return ($recipients1 == $recipients2);
1523 // returns an array of contact-ids that are allowed to see this object
1524 private static function enumeratePermissions($obj)
1526 $allow_people = expand_acl($obj['allow_cid']);
1527 $allow_groups = Group::expand(expand_acl($obj['allow_gid']));
1528 $deny_people = expand_acl($obj['deny_cid']);
1529 $deny_groups = Group::expand(expand_acl($obj['deny_gid']));
1530 $recipients = array_unique(array_merge($allow_people, $allow_groups));
1531 $deny = array_unique(array_merge($deny_people, $deny_groups));
1532 $recipients = array_diff($recipients, $deny);
1536 public static function getFeedTags($item)
1540 $cnt = preg_match_all('|\#\[url\=(.*?)\](.*?)\[\/url\]|', $item['tag'], $matches);
1542 for ($x = 0; $x < $cnt; $x ++) {
1543 if ($matches[1][$x]) {
1544 $ret[$matches[2][$x]] = ['#', $matches[1][$x], $matches[2][$x]];
1549 $cnt = preg_match_all('|\@\[url\=(.*?)\](.*?)\[\/url\]|', $item['tag'], $matches);
1551 for ($x = 0; $x < $cnt; $x ++) {
1552 if ($matches[1][$x]) {
1553 $ret[] = ['@', $matches[1][$x], $matches[2][$x]];
1560 public static function expire($uid, $days, $network = "", $force = false)
1562 if (!$uid || ($days < 1)) {
1567 * $expire_network_only = save your own wall posts
1568 * and just expire conversations started by others
1570 $expire_network_only = PConfig::get($uid,'expire', 'network_only');
1571 $sql_extra = (intval($expire_network_only) ? " AND wall = 0 " : "");
1573 if ($network != "") {
1574 $sql_extra .= sprintf(" AND network = '%s' ", dbesc($network));
1577 * There is an index "uid_network_received" but not "uid_network_created"
1578 * This avoids the creation of another index just for one purpose.
1579 * And it doesn't really matter wether to look at "received" or "created"
1581 $range = "AND `received` < UTC_TIMESTAMP() - INTERVAL %d DAY ";
1583 $range = "AND `created` < UTC_TIMESTAMP() - INTERVAL %d DAY ";
1586 $r = q("SELECT `file`, `resource-id`, `starred`, `type`, `id` FROM `item`
1587 WHERE `uid` = %d $range
1595 if (!DBM::is_result($r)) {
1599 $expire_items = PConfig::get($uid, 'expire', 'items', 1);
1601 // Forcing expiring of items - but not notes and marked items
1603 $expire_items = true;
1606 $expire_notes = PConfig::get($uid, 'expire', 'notes', 1);
1607 $expire_starred = PConfig::get($uid, 'expire', 'starred', 1);
1608 $expire_photos = PConfig::get($uid, 'expire', 'photos', 0);
1610 logger('User '.$uid.': expire: # items=' . count($r). "; expire items: $expire_items, expire notes: $expire_notes, expire starred: $expire_starred, expire photos: $expire_photos");
1612 foreach ($r as $item) {
1614 // don't expire filed items
1616 if (strpos($item['file'],'[') !== false) {
1620 // Only expire posts, not photos and photo comments
1622 if ($expire_photos == 0 && strlen($item['resource-id'])) {
1624 } elseif ($expire_starred == 0 && intval($item['starred'])) {
1626 } elseif ($expire_notes == 0 && $item['type'] == 'note') {
1628 } elseif ($expire_items == 0 && $item['type'] != 'note') {
1632 self::delete($item['id'], PRIORITY_LOW);
1636 /// @TODO: This query seems to be really slow
1637 public static function firstPostDate($uid, $wall = false)
1639 $r = q("SELECT `id`, `created` FROM `item`
1640 WHERE `uid` = %d AND `wall` = %d AND `deleted` = 0 AND `visible` = 1 AND `moderated` = 0
1642 ORDER BY `created` ASC LIMIT 1",
1644 intval($wall ? 1 : 0)
1646 if (DBM::is_result($r)) {
1647 return substr(DateTimeFormat::local($r[0]['created']),0,10);
1653 * @brief add/remove activity to an item
1655 * Toggle activities as like,dislike,attend of an item
1657 * @param string $item_id
1658 * @param string $verb
1659 * Activity verb. One of
1660 * like, unlike, dislike, undislike, attendyes, unattendyes,
1661 * attendno, unattendno, attendmaybe, unattendmaybe
1662 * @hook 'post_local_end'
1664 * 'post_id' => ID of posted item
1666 public static function performLike($item_id, $verb)
1668 if (!local_user() && !remote_user()) {
1675 $bodyverb = L10n::t('%1$s likes %2$s\'s %3$s');
1676 $activity = ACTIVITY_LIKE;
1680 $bodyverb = L10n::t('%1$s doesn\'t like %2$s\'s %3$s');
1681 $activity = ACTIVITY_DISLIKE;
1685 $bodyverb = L10n::t('%1$s is attending %2$s\'s %3$s');
1686 $activity = ACTIVITY_ATTEND;
1690 $bodyverb = L10n::t('%1$s is not attending %2$s\'s %3$s');
1691 $activity = ACTIVITY_ATTENDNO;
1694 case 'unattendmaybe':
1695 $bodyverb = L10n::t('%1$s may attend %2$s\'s %3$s');
1696 $activity = ACTIVITY_ATTENDMAYBE;
1699 logger('like: unknown verb ' . $verb . ' for item ' . $item_id);
1703 // Enable activity toggling instead of on/off
1704 $event_verb_flag = $activity === ACTIVITY_ATTEND || $activity === ACTIVITY_ATTENDNO || $activity === ACTIVITY_ATTENDMAYBE;
1706 logger('like: verb ' . $verb . ' item ' . $item_id);
1708 $item = dba::selectFirst('item', [], ['`id` = ? OR `uri` = ?', $item_id, $item_id]);
1709 if (!DBM::is_result($item)) {
1710 logger('like: unknown item ' . $item_id);
1714 $uid = $item['uid'];
1715 if (($uid == 0) && local_user()) {
1716 $uid = local_user();
1719 if (!can_write_wall($uid)) {
1720 logger('like: unable to write on wall ' . $uid);
1724 // Retrieves the local post owner
1725 $owner_self_contact = dba::selectFirst('contact', [], ['uid' => $uid, 'self' => true]);
1726 if (!DBM::is_result($owner_self_contact)) {
1727 logger('like: unknown owner ' . $uid);
1731 // Retrieve the current logged in user's public contact
1732 $author_id = public_contact();
1734 $author_contact = dba::selectFirst('contact', [], ['id' => $author_id]);
1735 if (!DBM::is_result($author_contact)) {
1736 logger('like: unknown author ' . $author_id);
1740 // Contact-id is the uid-dependant author contact
1741 if (local_user() == $uid) {
1742 $item_contact_id = $owner_self_contact['id'];
1743 $item_contact = $owner_self_contact;
1745 $item_contact_id = Contact::getIdForURL($author_contact['url'], $uid);
1746 $item_contact = dba::selectFirst('contact', [], ['id' => $item_contact_id]);
1747 if (!DBM::is_result($item_contact)) {
1748 logger('like: unknown item contact ' . $item_contact_id);
1753 // Look for an existing verb row
1754 // event participation are essentially radio toggles. If you make a subsequent choice,
1755 // we need to eradicate your first choice.
1756 if ($event_verb_flag) {
1757 $verbs = "'" . dbesc(ACTIVITY_ATTEND) . "', '" . dbesc(ACTIVITY_ATTENDNO) . "', '" . dbesc(ACTIVITY_ATTENDMAYBE) . "'";
1759 $verbs = "'".dbesc($activity)."'";
1762 $existing_like = q("SELECT `id`, `guid`, `verb` FROM `item`
1763 WHERE `verb` IN ($verbs)
1765 AND `author-id` = %d
1767 AND (`parent` = '%s' OR `parent-uri` = '%s' OR `thr-parent` = '%s')
1769 intval($author_contact['id']),
1770 intval($item['uid']),
1771 dbesc($item_id), dbesc($item_id), dbesc($item['uri'])
1774 // If it exists, mark it as deleted
1775 if (DBM::is_result($existing_like)) {
1776 $like_item = $existing_like[0];
1778 // Already voted, undo it
1779 $fields = ['deleted' => true, 'unseen' => true, 'changed' => datetime_convert()];
1780 dba::update('item', $fields, ['id' => $like_item['id']]);
1782 // Clean up the Diaspora signatures for this like
1783 // Go ahead and do it even if Diaspora support is disabled. We still want to clean up
1784 // if it had been enabled in the past
1785 dba::delete('sign', ['iid' => $like_item['id']]);
1787 $like_item_id = $like_item['id'];
1788 Worker::add(PRIORITY_HIGH, "Notifier", "like", $like_item_id);
1790 if (!$event_verb_flag || $like_item['verb'] == $activity) {
1795 // Verb is "un-something", just trying to delete existing entries
1796 if (strpos($verb, 'un') === 0) {
1800 // Else or if event verb different from existing row, create a new item row
1801 $post_type = (($item['resource-id']) ? L10n::t('photo') : L10n::t('status'));
1802 if ($item['object-type'] === ACTIVITY_OBJ_EVENT) {
1803 $post_type = L10n::t('event');
1805 $objtype = $item['resource-id'] ? ACTIVITY_OBJ_IMAGE : ACTIVITY_OBJ_NOTE ;
1806 $link = xmlify('<link rel="alternate" type="text/html" href="' . System::baseUrl() . '/display/' . $owner_self_contact['nick'] . '/' . $item['id'] . '" />' . "\n") ;
1807 $body = $item['body'];
1812 <type>$objtype</type>
1814 <id>{$item['uri']}</id>
1817 <content>$body</content>
1821 $ulink = '[url=' . $author_contact['url'] . ']' . $author_contact['name'] . '[/url]';
1822 $alink = '[url=' . $item['author-link'] . ']' . $item['author-name'] . '[/url]';
1823 $plink = '[url=' . System::baseUrl() . '/display/' . $owner_self_contact['nick'] . '/' . $item['id'] . ']' . $post_type . '[/url]';
1826 'guid' => get_guid(32),
1827 'uri' => item_new_uri(self::getApp()->get_hostname(), $item['uid']),
1828 'uid' => $item['uid'],
1829 'contact-id' => $item_contact_id,
1830 'type' => 'activity',
1831 'wall' => $item['wall'],
1833 'gravity' => GRAVITY_LIKE,
1834 'parent' => $item['id'],
1835 'parent-uri' => $item['uri'],
1836 'thr-parent' => $item['uri'],
1837 'owner-id' => $item['owner-id'],
1838 'owner-name' => $item['owner-name'],
1839 'owner-link' => $item['owner-link'],
1840 'owner-avatar' => $item['owner-avatar'],
1841 'author-id' => $author_contact['id'],
1842 'author-name' => $author_contact['name'],
1843 'author-link' => $author_contact['url'],
1844 'author-avatar' => $author_contact['thumb'],
1845 'body' => sprintf($bodyverb, $ulink, $alink, $plink),
1846 'verb' => $activity,
1847 'object-type' => $objtype,
1849 'allow_cid' => $item['allow_cid'],
1850 'allow_gid' => $item['allow_gid'],
1851 'deny_cid' => $item['deny_cid'],
1852 'deny_gid' => $item['deny_gid'],
1857 $new_item_id = Item::insert($new_item);
1859 // @todo: Explain this block
1860 if (! $item['visible']) {
1861 q("UPDATE `item` SET `visible` = 1 WHERE `id` = %d",
1866 // Save the author information for the like in case we need to relay to Diaspora
1867 Diaspora::storeLikeSignature($item_contact, $new_item_id);
1869 $new_item['id'] = $new_item_id;
1871 Addon::callHooks('post_local_end', $new_item);
1873 Worker::add(PRIORITY_HIGH, "Notifier", "like", $new_item_id);