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;
27 use Text_LanguageDetect;
29 require_once 'boot.php';
30 require_once 'include/threads.php';
31 require_once 'include/items.php';
32 require_once 'include/text.php';
34 class Item extends BaseObject
37 * @brief Update existing item entries
39 * @param array $fields The fields that are to be changed
40 * @param array $condition The condition for finding the item entries
42 * In the future we may have to change permissions as well.
43 * Then we had to add the user id as third parameter.
45 * A return value of "0" doesn't mean an error - but that 0 rows had been changed.
47 * @return integer|boolean number of affected rows - or "false" if there was an error
49 public static function update(array $fields, array $condition)
51 if (empty($condition) || empty($fields)) {
55 $success = dba::update('item', $fields, $condition);
61 $rows = dba::affected_rows();
63 // We cannot simply expand the condition to check for origin entries
64 // The condition needn't to be a simple array but could be a complex condition.
65 $items = dba::select('item', ['id', 'origin'], $condition);
66 while ($item = dba::fetch($items)) {
67 // We only need to notfiy others when it is an original entry from us
68 if (!$item['origin']) {
72 Term::insertFromTagFieldByItemId($item['id']);
73 Term::insertFromFileFieldByItemId($item['id']);
74 self::updateThread($item['id']);
76 Worker::add(PRIORITY_HIGH, "Notifier", 'edit_post', $item['id']);
83 * @brief Delete an item and notify others about it - if it was ours
85 * @param integer $item_id Item ID that should be delete
87 * @return $boolean success
89 public static function delete($item_id, $priority = PRIORITY_HIGH)
91 // locate item to be deleted
92 $fields = ['id', 'uid', 'parent', 'parent-uri', 'origin', 'deleted', 'file', 'resource-id', 'event-id', 'attach'];
93 $item = dba::selectFirst('item', $fields, ['id' => $item_id]);
94 if (!DBM::is_result($item)) {
98 if ($item['deleted']) {
102 $parent = dba::selectFirst('item', ['origin'], ['id' => $item['parent']]);
103 if (!DBM::is_result($parent)) {
104 $parent = ['origin' => false];
107 logger('delete item: ' . $item['id'], LOGGER_DEBUG);
109 // clean up categories and tags so they don't end up as orphans
112 $cnt = preg_match_all('/<(.*?)>/', $item['file'], $matches, PREG_SET_ORDER);
114 foreach ($matches as $mtch) {
115 file_tag_unsave_file($item['uid'], $item['id'], $mtch[1],true);
121 $cnt = preg_match_all('/\[(.*?)\]/', $item['file'], $matches, PREG_SET_ORDER);
123 foreach ($matches as $mtch) {
124 file_tag_unsave_file($item['uid'], $item['id'], $mtch[1],false);
129 * If item is a link to a photo resource, nuke all the associated photos
130 * (visitors will not have photo resources)
131 * This only applies to photos uploaded from the photos page. Photos inserted into a post do not
132 * generate a resource-id and therefore aren't intimately linked to the item.
134 if (strlen($item['resource-id'])) {
135 dba::delete('photo', ['resource-id' => $item['resource-id'], 'uid' => $item['uid']]);
138 // If item is a link to an event, nuke the event record.
139 if (intval($item['event-id'])) {
140 dba::delete('event', ['id' => $item['event-id'], 'uid' => $item['uid']]);
143 // If item has attachments, drop them
144 foreach (explode(", ", $item['attach']) as $attach) {
145 preg_match("|attach/(\d+)|", $attach, $matches);
146 dba::delete('attach', ['id' => $matches[1], 'uid' => $item['uid']]);
149 // Set the item to "deleted"
150 dba::update('item', ['deleted' => true, 'title' => '', 'body' => '',
151 'edited' => DateTimeFormat::utcNow(), 'changed' => DateTimeFormat::utcNow()],
152 ['id' => $item['id']]);
154 Term::insertFromTagFieldByItemId($item['id']);
155 Term::insertFromFileFieldByItemId($item['id']);
156 self::deleteThread($item['id'], $item['parent-uri']);
158 // If it's the parent of a comment thread, kill all the kids
159 if ($item['id'] == $item['parent']) {
160 $items = dba::select('item', ['id'], ['parent' => $item['parent']]);
161 while ($row = dba::fetch($items)) {
162 self::delete($row['id'], $priority);
166 // send the notification upstream/downstream
167 if ($item['origin'] || $parent['origin']) {
168 Worker::add(['priority' => $priority, 'dont_fork' => true], "Notifier", "drop", intval($item['id']));
174 public static function insert($arr, $force_parent = false, $notify = false, $dontcache = false)
178 // If it is a posting where users should get notifications, then define it as wall posting
181 $arr['type'] = 'wall';
183 $arr['network'] = NETWORK_DFRN;
184 $arr['protocol'] = PROTOCOL_DFRN;
186 // We have to avoid duplicates. So we create the GUID in form of a hash of the plink or uri.
187 // In difference to the call to "self::guidFromUri" several lines below we add the hash of our own host.
188 // This is done because our host is the original creator of the post.
189 if (!isset($arr['guid'])) {
190 if (isset($arr['plink'])) {
191 $arr['guid'] = self::guidFromUri($arr['plink'], $a->get_hostname());
192 } elseif (isset($arr['uri'])) {
193 $arr['guid'] = self::guidFromUri($arr['uri'], $a->get_hostname());
197 $arr['network'] = trim(defaults($arr, 'network', NETWORK_PHANTOM));
202 } elseif ((trim($arr['guid']) == "") && (trim($arr['plink']) != "")) {
203 $arr['guid'] = self::guidFromUri($arr['plink']);
204 } elseif ((trim($arr['guid']) == "") && (trim($arr['uri']) != "")) {
205 $arr['guid'] = self::guidFromUri($arr['uri']);
207 $parsed = parse_url($arr["author-link"]);
208 $guid_prefix = hash("crc32", $parsed["host"]);
211 $arr['guid'] = notags(trim(defaults($arr, 'guid', get_guid(32, $guid_prefix))));
212 $arr['uri'] = notags(trim(defaults($arr, 'uri', item_new_uri($a->get_hostname(), $uid, $arr['guid']))));
214 // Store conversation data
215 $arr = Conversation::insert($arr);
218 * If a Diaspora signature structure was passed in, pull it out of the
219 * item array and set it aside for later storage.
223 if (x($arr, 'dsprsig')) {
224 $encoded_signature = $arr['dsprsig'];
225 $dsprsig = json_decode(base64_decode($arr['dsprsig']));
226 unset($arr['dsprsig']);
229 // Converting the plink
230 /// @TODO Check if this is really still needed
231 if ($arr['network'] == NETWORK_OSTATUS) {
232 if (isset($arr['plink'])) {
233 $arr['plink'] = OStatus::convertHref($arr['plink']);
234 } elseif (isset($arr['uri'])) {
235 $arr['plink'] = OStatus::convertHref($arr['uri']);
239 if (x($arr, 'gravity')) {
240 $arr['gravity'] = intval($arr['gravity']);
241 } elseif ($arr['parent-uri'] === $arr['uri']) {
243 } elseif (activity_match($arr['verb'],ACTIVITY_POST)) {
246 $arr['gravity'] = 6; // extensible catchall
249 $arr['type'] = defaults($arr, 'type', 'remote');
251 $uid = intval($arr['uid']);
253 // check for create date and expire time
254 $expire_interval = Config::get('system', 'dbclean-expire-days', 0);
256 $user = dba::selectFirst('user', ['expire'], ['uid' => $uid]);
257 if (DBM::is_result($user) && ($user['expire'] > 0) && (($user['expire'] < $expire_interval) || ($expire_interval == 0))) {
258 $expire_interval = $user['expire'];
261 if (($expire_interval > 0) && !empty($arr['created'])) {
262 $expire_date = time() - ($expire_interval * 86400);
263 $created_date = strtotime($arr['created']);
264 if ($created_date < $expire_date) {
265 logger('item-store: item created ('.date('c', $created_date).') before expiration time ('.date('c', $expire_date).'). ignored. ' . print_r($arr,true), LOGGER_DEBUG);
271 * Do we already have this item?
272 * We have to check several networks since Friendica posts could be repeated
273 * via OStatus (maybe Diasporsa as well)
275 if (in_array($arr['network'], [NETWORK_DIASPORA, NETWORK_DFRN, NETWORK_OSTATUS, ""])) {
276 $r = q("SELECT `id`, `network` FROM `item` WHERE `uri` = '%s' AND `uid` = %d AND `network` IN ('%s', '%s', '%s') LIMIT 1",
277 dbesc(trim($arr['uri'])),
279 dbesc(NETWORK_DIASPORA),
281 dbesc(NETWORK_OSTATUS)
283 if (DBM::is_result($r)) {
284 // We only log the entries with a different user id than 0. Otherwise we would have too many false positives
286 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']);
293 self::addLanguageInPostopts($arr);
295 $arr['wall'] = intval(defaults($arr, 'wall', 0));
296 $arr['extid'] = trim(defaults($arr, 'extid', ''));
297 $arr['author-name'] = trim(defaults($arr, 'author-name', ''));
298 $arr['author-link'] = trim(defaults($arr, 'author-link', ''));
299 $arr['author-avatar'] = trim(defaults($arr, 'author-avatar', ''));
300 $arr['owner-name'] = trim(defaults($arr, 'owner-name', ''));
301 $arr['owner-link'] = trim(defaults($arr, 'owner-link', ''));
302 $arr['owner-avatar'] = trim(defaults($arr, 'owner-avatar', ''));
303 $arr['received'] = ((x($arr, 'received') !== false) ? DateTimeFormat::utc($arr['received']) : DateTimeFormat::utcNow());
304 $arr['created'] = ((x($arr, 'created') !== false) ? DateTimeFormat::utc($arr['created']) : $arr['received']);
305 $arr['edited'] = ((x($arr, 'edited') !== false) ? DateTimeFormat::utc($arr['edited']) : $arr['created']);
306 $arr['changed'] = ((x($arr, 'changed') !== false) ? DateTimeFormat::utc($arr['changed']) : $arr['created']);
307 $arr['commented'] = ((x($arr, 'commented') !== false) ? DateTimeFormat::utc($arr['commented']) : $arr['created']);
308 $arr['title'] = trim(defaults($arr, 'title', ''));
309 $arr['location'] = trim(defaults($arr, 'location', ''));
310 $arr['coord'] = trim(defaults($arr, 'coord', ''));
311 $arr['visible'] = ((x($arr, 'visible') !== false) ? intval($arr['visible']) : 1);
313 $arr['parent-uri'] = trim(defaults($arr, 'parent-uri', $arr['uri']));
314 $arr['verb'] = trim(defaults($arr, 'verb', ''));
315 $arr['object-type'] = trim(defaults($arr, 'object-type', ''));
316 $arr['object'] = trim(defaults($arr, 'object', ''));
317 $arr['target-type'] = trim(defaults($arr, 'target-type', ''));
318 $arr['target'] = trim(defaults($arr, 'target', ''));
319 $arr['plink'] = trim(defaults($arr, 'plink', ''));
320 $arr['allow_cid'] = trim(defaults($arr, 'allow_cid', ''));
321 $arr['allow_gid'] = trim(defaults($arr, 'allow_gid', ''));
322 $arr['deny_cid'] = trim(defaults($arr, 'deny_cid', ''));
323 $arr['deny_gid'] = trim(defaults($arr, 'deny_gid', ''));
324 $arr['private'] = intval(defaults($arr, 'private', 0));
325 $arr['bookmark'] = intval(defaults($arr, 'bookmark', 0));
326 $arr['body'] = trim(defaults($arr, 'body', ''));
327 $arr['tag'] = trim(defaults($arr, 'tag', ''));
328 $arr['attach'] = trim(defaults($arr, 'attach', ''));
329 $arr['app'] = trim(defaults($arr, 'app', ''));
330 $arr['origin'] = intval(defaults($arr, 'origin', 0));
331 $arr['postopts'] = trim(defaults($arr, 'postopts', ''));
332 $arr['resource-id'] = trim(defaults($arr, 'resource-id', ''));
333 $arr['event-id'] = intval(defaults($arr, 'event-id', 0));
334 $arr['inform'] = trim(defaults($arr, 'inform', ''));
335 $arr['file'] = trim(defaults($arr, 'file', ''));
337 // When there is no content then we don't post it
338 if ($arr['body'].$arr['title'] == '') {
342 // Items cannot be stored before they happen ...
343 if ($arr['created'] > DateTimeFormat::utcNow()) {
344 $arr['created'] = DateTimeFormat::utcNow();
347 // We haven't invented time travel by now.
348 if ($arr['edited'] > DateTimeFormat::utcNow()) {
349 $arr['edited'] = DateTimeFormat::utcNow();
352 if (($arr['author-link'] == "") && ($arr['owner-link'] == "")) {
353 logger("Both author-link and owner-link are empty. Called by: " . System::callstack(), LOGGER_DEBUG);
356 if ($arr['plink'] == "") {
357 $arr['plink'] = System::baseUrl() . '/display/' . urlencode($arr['guid']);
360 if ($arr['network'] == NETWORK_PHANTOM) {
361 $r = q("SELECT `network` FROM `contact` WHERE `network` IN ('%s', '%s', '%s') AND `nurl` = '%s' AND `uid` = %d LIMIT 1",
362 dbesc(NETWORK_DFRN), dbesc(NETWORK_DIASPORA), dbesc(NETWORK_OSTATUS),
363 dbesc(normalise_link($arr['author-link'])),
367 if (!DBM::is_result($r)) {
368 $r = q("SELECT `network` FROM `gcontact` WHERE `network` IN ('%s', '%s', '%s') AND `nurl` = '%s' LIMIT 1",
369 dbesc(NETWORK_DFRN), dbesc(NETWORK_DIASPORA), dbesc(NETWORK_OSTATUS),
370 dbesc(normalise_link($arr['author-link']))
374 if (!DBM::is_result($r)) {
375 $r = q("SELECT `network` FROM `contact` WHERE `id` = %d AND `uid` = %d LIMIT 1",
376 intval($arr['contact-id']),
381 if (DBM::is_result($r)) {
382 $arr['network'] = $r[0]["network"];
385 // Fallback to friendica (why is it empty in some cases?)
386 if ($arr['network'] == "") {
387 $arr['network'] = NETWORK_DFRN;
390 logger("Set network to " . $arr["network"] . " for " . $arr["uri"], LOGGER_DEBUG);
393 // The contact-id should be set before "self::insert" was called - but there seems to be some issues
394 if ($arr["contact-id"] == 0) {
396 * First we are looking for a suitable contact that matches with the author of the post
397 * This is done only for comments (See below explanation at "gcontact-id")
399 if ($arr['parent-uri'] != $arr['uri']) {
400 $arr["contact-id"] = Contact::getIdForURL($arr['author-link'], $uid);
403 // If not present then maybe the owner was found
404 if ($arr["contact-id"] == 0) {
405 $arr["contact-id"] = Contact::getIdForURL($arr['owner-link'], $uid);
408 // Still missing? Then use the "self" contact of the current user
409 if ($arr["contact-id"] == 0) {
410 $r = q("SELECT `id` FROM `contact` WHERE `self` AND `uid` = %d", intval($uid));
412 if (DBM::is_result($r)) {
413 $arr["contact-id"] = $r[0]["id"];
417 logger("Contact-id was missing for post ".$arr["guid"]." from user id ".$uid." - now set to ".$arr["contact-id"], LOGGER_DEBUG);
420 if (!x($arr, "gcontact-id")) {
422 * The gcontact should mostly behave like the contact. But is is supposed to be global for the system.
423 * This means that wall posts, repeated posts, etc. should have the gcontact id of the owner.
424 * On comments the author is the better choice.
426 if ($arr['parent-uri'] === $arr['uri']) {
427 $arr["gcontact-id"] = GContact::getId(["url" => $arr['owner-link'], "network" => $arr['network'],
428 "photo" => $arr['owner-avatar'], "name" => $arr['owner-name']]);
430 $arr["gcontact-id"] = GContact::getId(["url" => $arr['author-link'], "network" => $arr['network'],
431 "photo" => $arr['author-avatar'], "name" => $arr['author-name']]);
435 if ($arr["author-id"] == 0) {
436 $arr["author-id"] = Contact::getIdForURL($arr["author-link"], 0);
439 if (Contact::isBlocked($arr["author-id"])) {
440 logger('Contact '.$arr["author-id"].' is blocked, item '.$arr["uri"].' will not be stored');
444 if ($arr["owner-id"] == 0) {
445 $arr["owner-id"] = Contact::getIdForURL($arr["owner-link"], 0);
448 if (Contact::isBlocked($arr["owner-id"])) {
449 logger('Contact '.$arr["owner-id"].' is blocked, item '.$arr["uri"].' will not be stored');
453 if ($arr['guid'] != "") {
454 // Checking if there is already an item with the same guid
455 logger('checking for an item for user '.$arr['uid'].' on network '.$arr['network'].' with the guid '.$arr['guid'], LOGGER_DEBUG);
456 $r = q("SELECT `guid` FROM `item` WHERE `guid` = '%s' AND `network` = '%s' AND `uid` = '%d' LIMIT 1",
457 dbesc($arr['guid']), dbesc($arr['network']), intval($arr['uid']));
459 if (DBM::is_result($r)) {
460 logger('found item with guid '.$arr['guid'].' for user '.$arr['uid'].' on network '.$arr['network'], LOGGER_DEBUG);
465 // Check for hashtags in the body and repair or add hashtag links
466 self::setHashtags($arr);
468 $arr['thr-parent'] = $arr['parent-uri'];
470 if ($arr['parent-uri'] === $arr['uri']) {
473 $allow_cid = $arr['allow_cid'];
474 $allow_gid = $arr['allow_gid'];
475 $deny_cid = $arr['deny_cid'];
476 $deny_gid = $arr['deny_gid'];
477 $notify_type = 'wall-new';
480 // find the parent and snarf the item id and ACLs
481 // and anything else we need to inherit
483 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d ORDER BY `id` ASC LIMIT 1",
484 dbesc($arr['parent-uri']),
488 if (DBM::is_result($r)) {
490 // is the new message multi-level threaded?
491 // even though we don't support it now, preserve the info
492 // and re-attach to the conversation parent.
494 if ($r[0]['uri'] != $r[0]['parent-uri']) {
495 $arr['parent-uri'] = $r[0]['parent-uri'];
496 $z = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `parent-uri` = '%s' AND `uid` = %d
497 ORDER BY `id` ASC LIMIT 1",
498 dbesc($r[0]['parent-uri']),
499 dbesc($r[0]['parent-uri']),
503 if (DBM::is_result($z)) {
508 $parent_id = $r[0]['id'];
509 $parent_deleted = $r[0]['deleted'];
510 $allow_cid = $r[0]['allow_cid'];
511 $allow_gid = $r[0]['allow_gid'];
512 $deny_cid = $r[0]['deny_cid'];
513 $deny_gid = $r[0]['deny_gid'];
514 $arr['wall'] = $r[0]['wall'];
515 $notify_type = 'comment-new';
518 * If the parent is private, force privacy for the entire conversation
519 * This differs from the above settings as it subtly allows comments from
520 * email correspondents to be private even if the overall thread is not.
522 if ($r[0]['private']) {
523 $arr['private'] = $r[0]['private'];
527 * Edge case. We host a public forum that was originally posted to privately.
528 * The original author commented, but as this is a comment, the permissions
529 * weren't fixed up so it will still show the comment as private unless we fix it here.
531 if ((intval($r[0]['forum_mode']) == 1) && $r[0]['private']) {
535 // If its a post from myself then tag the thread as "mention"
536 logger("Checking if parent ".$parent_id." has to be tagged as mention for user ".$arr['uid'], LOGGER_DEBUG);
537 $u = q("SELECT `nickname` FROM `user` WHERE `uid` = %d", intval($arr['uid']));
538 if (DBM::is_result($u)) {
539 $self = normalise_link(System::baseUrl() . '/profile/' . $u[0]['nickname']);
540 logger("'myself' is ".$self." for parent ".$parent_id." checking against ".$arr['author-link']." and ".$arr['owner-link'], LOGGER_DEBUG);
541 if ((normalise_link($arr['author-link']) == $self) || (normalise_link($arr['owner-link']) == $self)) {
542 dba::update('thread', ['mention' => true], ['iid' => $parent_id]);
543 logger("tagged thread ".$parent_id." as mention for user ".$self, LOGGER_DEBUG);
548 * Allow one to see reply tweets from status.net even when
549 * we don't have or can't see the original post.
552 logger('$force_parent=true, reply converted to top-level post.');
554 $arr['parent-uri'] = $arr['uri'];
557 logger('item parent '.$arr['parent-uri'].' for '.$arr['uid'].' was not found - ignoring item');
565 $r = q("SELECT `id` FROM `item` WHERE `uri` = '%s' AND `network` IN ('%s', '%s') AND `uid` = %d LIMIT 1",
567 dbesc($arr['network']),
571 if (DBM::is_result($r)) {
572 logger('duplicated item with the same uri found. '.print_r($arr,true));
576 // On Friendica and Diaspora the GUID is unique
577 if (in_array($arr['network'], [NETWORK_DFRN, NETWORK_DIASPORA])) {
578 $r = q("SELECT `id` FROM `item` WHERE `guid` = '%s' AND `uid` = %d LIMIT 1",
582 if (DBM::is_result($r)) {
583 logger('duplicated item with the same guid found. '.print_r($arr,true));
587 // Check for an existing post with the same content. There seems to be a problem with OStatus.
588 $r = q("SELECT `id` FROM `item` WHERE `body` = '%s' AND `network` = '%s' AND `created` = '%s' AND `contact-id` = %d AND `uid` = %d LIMIT 1",
590 dbesc($arr['network']),
591 dbesc($arr['created']),
592 intval($arr['contact-id']),
595 if (DBM::is_result($r)) {
596 logger('duplicated item with the same body found. '.print_r($arr,true));
601 // Is this item available in the global items (with uid=0)?
602 if ($arr["uid"] == 0) {
603 $arr["global"] = true;
605 // Set the global flag on all items if this was a global item entry
606 dba::update('item', ['global' => true], ['uri' => $arr["uri"]]);
608 $isglobal = q("SELECT `global` FROM `item` WHERE `uid` = 0 AND `uri` = '%s'", dbesc($arr["uri"]));
610 $arr["global"] = (DBM::is_result($isglobal) && count($isglobal) > 0);
614 if (strlen($allow_cid) || strlen($allow_gid) || strlen($deny_cid) || strlen($deny_gid)) {
617 $private = $arr['private'];
620 $arr["allow_cid"] = $allow_cid;
621 $arr["allow_gid"] = $allow_gid;
622 $arr["deny_cid"] = $deny_cid;
623 $arr["deny_gid"] = $deny_gid;
624 $arr["private"] = $private;
625 $arr["deleted"] = $parent_deleted;
627 // Fill the cache field
628 put_item_in_cache($arr);
631 Addon::callHooks('post_local', $arr);
633 Addon::callHooks('post_remote', $arr);
636 // This array field is used to trigger some automatic reactions
637 // It is mainly used in the "post_local" hook.
638 unset($arr['api_source']);
640 if (x($arr, 'cancel')) {
641 logger('post cancelled by addon.');
646 * Check for already added items.
647 * There is a timing issue here that sometimes creates double postings.
648 * An unique index would help - but the limitations of MySQL (maximum size of index values) prevent this.
650 if ($arr["uid"] == 0) {
651 $r = q("SELECT `id` FROM `item` WHERE `uri` = '%s' AND `uid` = 0 LIMIT 1", dbesc(trim($arr['uri'])));
652 if (DBM::is_result($r)) {
653 logger('Global item already stored. URI: '.$arr['uri'].' on network '.$arr['network'], LOGGER_DEBUG);
658 logger('' . print_r($arr,true), LOGGER_DATA);
661 $r = dba::insert('item', $arr);
663 // When the item was successfully stored we fetch the ID of the item.
664 if (DBM::is_result($r)) {
665 $current_post = dba::lastInsertId();
667 // This can happen - for example - if there are locking timeouts.
670 // Store the data into a spool file so that we can try again later.
672 // At first we restore the Diaspora signature that we removed above.
673 if (isset($encoded_signature)) {
674 $arr['dsprsig'] = $encoded_signature;
677 // Now we store the data in the spool directory
678 // We use "microtime" to keep the arrival order and "mt_rand" to avoid duplicates
679 $file = 'item-'.round(microtime(true) * 10000).'-'.mt_rand().'.msg';
681 $spoolpath = get_spoolpath();
682 if ($spoolpath != "") {
683 $spool = $spoolpath.'/'.$file;
684 file_put_contents($spool, json_encode($arr));
685 logger("Item wasn't stored - Item was spooled into file ".$file, LOGGER_DEBUG);
690 if ($current_post == 0) {
691 // This is one of these error messages that never should occur.
692 logger("couldn't find created item - we better quit now.");
697 // How much entries have we created?
698 // We wouldn't need this query when we could use an unique index - but MySQL has length problems with them.
699 $r = q("SELECT COUNT(*) AS `entries` FROM `item` WHERE `uri` = '%s' AND `uid` = %d AND `network` = '%s'",
702 dbesc($arr['network'])
705 if (!DBM::is_result($r)) {
706 // This shouldn't happen, since COUNT always works when the database connection is there.
707 logger("We couldn't count the stored entries. Very strange ...");
712 if ($r[0]["entries"] > 1) {
713 // There are duplicates. We delete our just created entry.
714 logger('Duplicated post occurred. uri = ' . $arr['uri'] . ' uid = ' . $arr['uid']);
716 // Yes, we could do a rollback here - but we are having many users with MyISAM.
717 dba::delete('item', ['id' => $current_post]);
720 } elseif ($r[0]["entries"] == 0) {
721 // This really should never happen since we quit earlier if there were problems.
722 logger("Something is terribly wrong. We haven't found our created entry.");
727 logger('created item '.$current_post);
728 self::updateContact($arr);
730 if (!$parent_id || ($arr['parent-uri'] === $arr['uri'])) {
731 $parent_id = $current_post;
735 dba::update('item', ['parent' => $parent_id], ['id' => $current_post]);
737 $arr['id'] = $current_post;
738 $arr['parent'] = $parent_id;
740 // update the commented timestamp on the parent
741 // Only update "commented" if it is really a comment
742 if (($arr['verb'] == ACTIVITY_POST) || !Config::get("system", "like_no_comment")) {
743 dba::update('item', ['commented' => DateTimeFormat::utcNow(), 'changed' => DateTimeFormat::utcNow()], ['id' => $parent_id]);
745 dba::update('item', ['changed' => DateTimeFormat::utcNow()], ['id' => $parent_id]);
750 * Friendica servers lower than 3.4.3-2 had double encoded the signature ...
751 * We can check for this condition when we decode and encode the stuff again.
753 if (base64_encode(base64_decode(base64_decode($dsprsig->signature))) == base64_decode($dsprsig->signature)) {
754 $dsprsig->signature = base64_decode($dsprsig->signature);
755 logger("Repaired double encoded signature from handle ".$dsprsig->signer, LOGGER_DEBUG);
758 dba::insert('sign', ['iid' => $current_post, 'signed_text' => $dsprsig->signed_text,
759 'signature' => $dsprsig->signature, 'signer' => $dsprsig->signer]);
762 $deleted = self::tagDeliver($arr['uid'], $current_post);
765 * current post can be deleted if is for a community page and no mention are
768 if (!$deleted && !$dontcache) {
769 $r = q('SELECT * FROM `item` WHERE `id` = %d', intval($current_post));
770 if (DBM::is_result($r) && (count($r) == 1)) {
772 Addon::callHooks('post_local_end', $r[0]);
774 Addon::callHooks('post_remote_end', $r[0]);
777 logger('new item not found in DB, id ' . $current_post);
781 if ($arr['parent-uri'] === $arr['uri']) {
782 self::addThread($current_post);
784 self::updateThread($parent_id);
790 * Due to deadlock issues with the "term" table we are doing these steps after the commit.
791 * This is not perfect - but a workable solution until we found the reason for the problem.
793 Term::insertFromTagFieldByItemId($current_post);
794 Term::insertFromFileFieldByItemId($current_post);
796 if ($arr['parent-uri'] === $arr['uri']) {
797 self::addShadow($current_post);
799 self::addShadowPost($current_post);
802 check_user_notification($current_post);
805 Worker::add(['priority' => PRIORITY_HIGH, 'dont_fork' => true], "Notifier", $notify_type, $current_post);
808 return $current_post;
812 * @brief Add a shadow entry for a given item id that is a thread starter
814 * We store every public item entry additionally with the user id "0".
815 * This is used for the community page and for the search.
816 * It is planned that in the future we will store public item entries only once.
818 * @param integer $itemid Item ID that should be added
820 public static function addShadow($itemid)
822 $fields = ['uid', 'wall', 'private', 'moderated', 'visible', 'contact-id', 'deleted', 'network', 'author-id', 'owner-id'];
823 $condition = ["`id` = ? AND (`parent` = ? OR `parent` = 0)", $itemid, $itemid];
824 $item = dba::selectFirst('item', $fields, $condition);
826 if (!DBM::is_result($item)) {
830 // is it already a copy?
831 if (($itemid == 0) || ($item['uid'] == 0)) {
835 // Is it a visible public post?
836 if (!$item["visible"] || $item["deleted"] || $item["moderated"] || $item["private"]) {
840 // is it an entry from a connector? Only add an entry for natively connected networks
841 if (!in_array($item["network"], [NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, ""])) {
845 // Is the public contact configured as hidden?
846 if (Contact::isHidden($item["owner-id"]) || Contact::isHidden($item["author-id"])) {
850 // Only do these checks if the post isn't a wall post
851 if (!$item["wall"]) {
852 // Check, if hide-friends is activated - then don't do a shadow entry
853 if (dba::exists('profile', ['is-default' => true, 'uid' => $item['uid'], 'hide-friends' => true])) {
857 // Check if the contact is hidden or blocked
858 if (!dba::exists('contact', ['hidden' => false, 'blocked' => false, 'id' => $item['contact-id']])) {
863 // Only add a shadow, if the profile isn't hidden
864 if (dba::exists('user', ['uid' => $item['uid'], 'hidewall' => true])) {
868 $item = dba::selectFirst('item', [], ['id' => $itemid]);
870 if (DBM::is_result($item) && ($item["allow_cid"] == '') && ($item["allow_gid"] == '') &&
871 ($item["deny_cid"] == '') && ($item["deny_gid"] == '')) {
873 if (!dba::exists('item', ['uri' => $item['uri'], 'uid' => 0])) {
874 // Preparing public shadow (removing user specific data)
879 $item['contact-id'] = Contact::getIdForURL($item['author-link'], 0);
881 if (in_array($item['type'], ["net-comment", "wall-comment"])) {
882 $item['type'] = 'remote-comment';
883 } elseif ($item['type'] == 'wall') {
884 $item['type'] = 'remote';
887 $public_shadow = self::insert($item, false, false, true);
889 logger("Stored public shadow for thread ".$itemid." under id ".$public_shadow, LOGGER_DEBUG);
895 * @brief Add a shadow entry for a given item id that is a comment
897 * This function does the same like the function above - but for comments
899 * @param integer $itemid Item ID that should be added
901 public static function addShadowPost($itemid)
903 $item = dba::selectFirst('item', [], ['id' => $itemid]);
904 if (!DBM::is_result($item)) {
908 // Is it a toplevel post?
909 if ($item['id'] == $item['parent']) {
910 self::addShadow($itemid);
914 // Is this a shadow entry?
915 if ($item['uid'] == 0)
918 // Is there a shadow parent?
919 if (!dba::exists('item', ['uri' => $item['parent-uri'], 'uid' => 0])) {
923 // Is there already a shadow entry?
924 if (dba::exists('item', ['uri' => $item['uri'], 'uid' => 0])) {
928 // Preparing public shadow (removing user specific data)
933 $item['contact-id'] = Contact::getIdForURL($item['author-link'], 0);
935 if (in_array($item['type'], ["net-comment", "wall-comment"])) {
936 $item['type'] = 'remote-comment';
937 } elseif ($item['type'] == 'wall') {
938 $item['type'] = 'remote';
941 $public_shadow = self::insert($item, false, false, true);
943 logger("Stored public shadow for comment ".$item['uri']." under id ".$public_shadow, LOGGER_DEBUG);
947 * Adds a "lang" specification in a "postopts" element of given $arr,
948 * if possible and not already present.
949 * Expects "body" element to exist in $arr.
951 private static function addLanguageInPostopts(&$arr)
953 if (x($arr, 'postopts')) {
954 if (strstr($arr['postopts'], 'lang=')) {
958 $postopts = $arr['postopts'];
963 $naked_body = preg_replace('/\[(.+?)\]/','', $arr['body']);
964 $l = new Text_LanguageDetect();
965 $lng = $l->detect($naked_body, 3);
967 if (sizeof($lng) > 0) {
968 if ($postopts != "") {
969 $postopts .= '&'; // arbitrary separator, to be reviewed
972 $postopts .= 'lang=';
975 foreach ($lng as $language => $score) {
976 $postopts .= $sep . $language . ";" . $score;
979 $arr['postopts'] = $postopts;
984 * @brief Creates an unique guid out of a given uri
986 * @param string $uri uri of an item entry
987 * @param string $host (Optional) hostname for the GUID prefix
988 * @return string unique guid
990 public static function guidFromUri($uri, $host = "")
992 // Our regular guid routine is using this kind of prefix as well
993 // We have to avoid that different routines could accidentally create the same value
994 $parsed = parse_url($uri);
996 // When the hostname isn't given, we take it from the uri
998 // Is it in the format data@host.tld?
999 if ((count($parsed) == 1) && strstr($uri, '@')) {
1000 $mailparts = explode('@', $uri);
1001 $host = array_pop($mailparts);
1003 $host = $parsed["host"];
1007 // We use a hash of the hostname as prefix for the guid
1008 $guid_prefix = hash("crc32", $host);
1010 // Remove the scheme to make sure that "https" and "http" doesn't make a difference
1011 unset($parsed["scheme"]);
1013 // Glue it together to be able to make a hash from it
1014 $host_id = implode("/", $parsed);
1016 // We could use any hash algorithm since it isn't a security issue
1017 $host_hash = hash("ripemd128", $host_id);
1019 return $guid_prefix.$host_hash;
1023 * @brief Set "success_update" and "last-item" to the date of the last time we heard from this contact
1025 * This can be used to filter for inactive contacts.
1026 * Only do this for public postings to avoid privacy problems, since poco data is public.
1027 * Don't set this value if it isn't from the owner (could be an author that we don't know)
1029 * @param array $arr Contains the just posted item record
1031 private static function updateContact($arr)
1033 // Unarchive the author
1034 $contact = dba::selectFirst('contact', [], ['id' => $arr["author-link"]]);
1035 if ($contact['term-date'] > NULL_DATE) {
1036 Contact::unmarkForArchival($contact);
1039 // Unarchive the contact if it is a toplevel posting
1040 if ($arr["parent-uri"] === $arr["uri"]) {
1041 $contact = dba::selectFirst('contact', [], ['id' => $arr["contact-id"]]);
1042 if ($contact['term-date'] > NULL_DATE) {
1043 Contact::unmarkForArchival($contact);
1047 $update = (!$arr['private'] && (($arr["author-link"] === $arr["owner-link"]) || ($arr["parent-uri"] === $arr["uri"])));
1049 // Is it a forum? Then we don't care about the rules from above
1050 if (!$update && ($arr["network"] == NETWORK_DFRN) && ($arr["parent-uri"] === $arr["uri"])) {
1051 $isforum = q("SELECT `forum` FROM `contact` WHERE `id` = %d AND `forum`",
1052 intval($arr['contact-id']));
1053 if (DBM::is_result($isforum)) {
1059 dba::update('contact', ['success_update' => $arr['received'], 'last-item' => $arr['received']],
1060 ['id' => $arr['contact-id']]);
1062 // Now do the same for the system wide contacts with uid=0
1063 if (!$arr['private']) {
1064 dba::update('contact', ['success_update' => $arr['received'], 'last-item' => $arr['received']],
1065 ['id' => $arr['owner-id']]);
1067 if ($arr['owner-id'] != $arr['author-id']) {
1068 dba::update('contact', ['success_update' => $arr['received'], 'last-item' => $arr['received']],
1069 ['id' => $arr['author-id']]);
1074 private static function setHashtags(&$item)
1077 $tags = get_tags($item["body"]);
1080 if (!count($tags)) {
1084 // This sorting is important when there are hashtags that are part of other hashtags
1085 // Otherwise there could be problems with hashtags like #test and #test2
1088 $URLSearchString = "^\[\]";
1090 // All hashtags should point to the home server if "local_tags" is activated
1091 if (Config::get('system', 'local_tags')) {
1092 $item["body"] = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
1093 "#[url=".System::baseUrl()."/search?tag=$2]$2[/url]", $item["body"]);
1095 $item["tag"] = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
1096 "#[url=".System::baseUrl()."/search?tag=$2]$2[/url]", $item["tag"]);
1099 // mask hashtags inside of url, bookmarks and attachments to avoid urls in urls
1100 $item["body"] = preg_replace_callback("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
1102 return ("[url=" . str_replace("#", "#", $match[1]) . "]" . str_replace("#", "#", $match[2]) . "[/url]");
1105 $item["body"] = preg_replace_callback("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism",
1107 return ("[bookmark=" . str_replace("#", "#", $match[1]) . "]" . str_replace("#", "#", $match[2]) . "[/bookmark]");
1110 $item["body"] = preg_replace_callback("/\[attachment (.*)\](.*?)\[\/attachment\]/ism",
1112 return ("[attachment " . str_replace("#", "#", $match[1]) . "]" . $match[2] . "[/attachment]");
1115 // Repair recursive urls
1116 $item["body"] = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
1117 "#$2", $item["body"]);
1119 foreach ($tags as $tag) {
1120 if ((strpos($tag, '#') !== 0) || strpos($tag, '[url=')) {
1124 $basetag = str_replace('_',' ',substr($tag,1));
1126 $newtag = '#[url=' . System::baseUrl() . '/search?tag=' . rawurlencode($basetag) . ']' . $basetag . '[/url]';
1128 $item["body"] = str_replace($tag, $newtag, $item["body"]);
1130 if (!stristr($item["tag"], "/search?tag=" . $basetag . "]" . $basetag . "[/url]")) {
1131 if (strlen($item["tag"])) {
1132 $item["tag"] = ','.$item["tag"];
1134 $item["tag"] = $newtag.$item["tag"];
1138 // Convert back the masked hashtags
1139 $item["body"] = str_replace("#", "#", $item["body"]);
1142 public static function getGuidById($id)
1144 $r = q("SELECT `guid` FROM `item` WHERE `id` = %d LIMIT 1", intval($id));
1145 if (DBM::is_result($r)) {
1146 return $r[0]["guid"];
1152 public static function getIdAndNickByGuid($guid, $uid = 0)
1158 $uid == local_user();
1161 // Does the given user have this item?
1163 $r = q("SELECT `item`.`id`, `user`.`nickname` FROM `item` INNER JOIN `user` ON `user`.`uid` = `item`.`uid`
1164 WHERE `item`.`visible` = 1 AND `item`.`deleted` = 0 AND `item`.`moderated` = 0
1165 AND `item`.`guid` = '%s' AND `item`.`uid` = %d", dbesc($guid), intval($uid));
1166 if (DBM::is_result($r)) {
1168 $nick = $r[0]["nickname"];
1172 // Or is it anywhere on the server?
1174 $r = q("SELECT `item`.`id`, `user`.`nickname` FROM `item` INNER JOIN `user` ON `user`.`uid` = `item`.`uid`
1175 WHERE `item`.`visible` = 1 AND `item`.`deleted` = 0 AND `item`.`moderated` = 0
1176 AND `item`.`allow_cid` = '' AND `item`.`allow_gid` = ''
1177 AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = ''
1178 AND `item`.`private` = 0 AND `item`.`wall` = 1
1179 AND `item`.`guid` = '%s'", dbesc($guid));
1180 if (DBM::is_result($r)) {
1182 $nick = $r[0]["nickname"];
1185 return ["nick" => $nick, "id" => $id];
1189 * look for mention tags and setup a second delivery chain for forum/community posts if appropriate
1191 * @param int $item_id
1192 * @return bool true if item was deleted, else false
1194 private static function tagDeliver($uid, $item_id)
1198 $u = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
1201 if (!DBM::is_result($u)) {
1205 $community_page = (($u[0]['page-flags'] == PAGE_COMMUNITY) ? true : false);
1206 $prvgroup = (($u[0]['page-flags'] == PAGE_PRVGROUP) ? true : false);
1208 $i = q("SELECT * FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1",
1212 if (!DBM::is_result($i)) {
1218 $link = normalise_link(System::baseUrl() . '/profile/' . $u[0]['nickname']);
1221 * Diaspora uses their own hardwired link URL in @-tags
1222 * instead of the one we supply with webfinger
1224 $dlink = normalise_link(System::baseUrl() . '/u/' . $u[0]['nickname']);
1226 $cnt = preg_match_all('/[\@\!]\[url\=(.*?)\](.*?)\[\/url\]/ism', $item['body'], $matches, PREG_SET_ORDER);
1228 foreach ($matches as $mtch) {
1229 if (link_compare($link, $mtch[1]) || link_compare($dlink, $mtch[1])) {
1231 logger('mention found: ' . $mtch[2]);
1237 if (($community_page || $prvgroup) &&
1238 !$item['wall'] && !$item['origin'] && ($item['id'] == $item['parent'])) {
1239 // mmh.. no mention.. community page or private group... no wall.. no origin.. top-post (not a comment)
1241 logger("no-mention top-level post to communuty or private group. delete.");
1242 dba::delete('item', ['id' => $item_id]);
1248 $arr = ['item' => $item, 'user' => $u[0], 'contact' => $r[0]];
1250 Addon::callHooks('tagged', $arr);
1252 if (!$community_page && !$prvgroup) {
1257 * tgroup delivery - setup a second delivery chain
1258 * prevent delivery looping - only proceed
1259 * if the message originated elsewhere and is a top-level post
1261 if ($item['wall'] || $item['origin'] || ($item['id'] != $item['parent'])) {
1265 // now change this copy of the post to a forum head message and deliver to all the tgroup members
1266 $c = q("SELECT `name`, `url`, `thumb` FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
1267 intval($u[0]['uid'])
1269 if (!DBM::is_result($c)) {
1273 // also reset all the privacy bits to the forum default permissions
1275 $private = ($u[0]['allow_cid'] || $u[0]['allow_gid'] || $u[0]['deny_cid'] || $u[0]['deny_gid']) ? 1 : 0;
1277 $forum_mode = (($prvgroup) ? 2 : 1);
1279 q("UPDATE `item` SET `wall` = 1, `origin` = 1, `forum_mode` = %d, `owner-name` = '%s', `owner-link` = '%s', `owner-avatar` = '%s',
1280 `private` = %d, `allow_cid` = '%s', `allow_gid` = '%s', `deny_cid` = '%s', `deny_gid` = '%s' WHERE `id` = %d",
1281 intval($forum_mode),
1282 dbesc($c[0]['name']),
1283 dbesc($c[0]['url']),
1284 dbesc($c[0]['thumb']),
1286 dbesc($u[0]['allow_cid']),
1287 dbesc($u[0]['allow_gid']),
1288 dbesc($u[0]['deny_cid']),
1289 dbesc($u[0]['deny_gid']),
1292 self::updateThread($item_id);
1294 Worker::add(['priority' => PRIORITY_HIGH, 'dont_fork' => true], 'Notifier', 'tgroup', $item_id);
1298 public static function isRemoteSelf($contact, &$datarray)
1302 if (!$contact['remote_self']) {
1306 // Prevent the forwarding of posts that are forwarded
1307 if ($datarray["extid"] == NETWORK_DFRN) {
1311 // Prevent to forward already forwarded posts
1312 if ($datarray["app"] == $a->get_hostname()) {
1316 // Only forward posts
1317 if ($datarray["verb"] != ACTIVITY_POST) {
1321 if (($contact['network'] != NETWORK_FEED) && $datarray['private']) {
1325 $datarray2 = $datarray;
1326 logger('remote-self start - Contact '.$contact['url'].' - '.$contact['remote_self'].' Item '.print_r($datarray, true), LOGGER_DEBUG);
1327 if ($contact['remote_self'] == 2) {
1328 $r = q("SELECT `id`,`url`,`name`,`thumb` FROM `contact` WHERE `uid` = %d AND `self`",
1329 intval($contact['uid']));
1330 if (DBM::is_result($r)) {
1331 $datarray['contact-id'] = $r[0]["id"];
1333 $datarray['owner-name'] = $r[0]["name"];
1334 $datarray['owner-link'] = $r[0]["url"];
1335 $datarray['owner-avatar'] = $r[0]["thumb"];
1337 $datarray['author-name'] = $datarray['owner-name'];
1338 $datarray['author-link'] = $datarray['owner-link'];
1339 $datarray['author-avatar'] = $datarray['owner-avatar'];
1341 unset($datarray['created']);
1342 unset($datarray['edited']);
1345 if ($contact['network'] != NETWORK_FEED) {
1346 $datarray["guid"] = get_guid(32);
1347 unset($datarray["plink"]);
1348 $datarray["uri"] = item_new_uri($a->get_hostname(), $contact['uid'], $datarray["guid"]);
1349 $datarray["parent-uri"] = $datarray["uri"];
1350 $datarray["extid"] = $contact['network'];
1351 $urlpart = parse_url($datarray2['author-link']);
1352 $datarray["app"] = $urlpart["host"];
1354 $datarray['private'] = 0;
1358 if ($contact['network'] != NETWORK_FEED) {
1359 // Store the original post
1360 $r = self::insert($datarray2, false, false);
1361 logger('remote-self post original item - Contact '.$contact['url'].' return '.$r.' Item '.print_r($datarray2, true), LOGGER_DEBUG);
1363 $datarray["app"] = "Feed";
1366 // Trigger automatic reactions for addons
1367 $datarray['api_source'] = true;
1369 // We have to tell the hooks who we are - this really should be improved
1370 $_SESSION["authenticated"] = true;
1371 $_SESSION["uid"] = $contact['uid'];
1380 * @param array $item
1384 public static function fixPrivatePhotos($s, $uid, $item = null, $cid = 0)
1386 if (Config::get('system', 'disable_embedded')) {
1390 logger('check for photos', LOGGER_DEBUG);
1391 $site = substr(System::baseUrl(), strpos(System::baseUrl(), '://'));
1396 $img_start = strpos($orig_body, '[img');
1397 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
1398 $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
1400 while (($img_st_close !== false) && ($img_len !== false)) {
1401 $img_st_close++; // make it point to AFTER the closing bracket
1402 $image = substr($orig_body, $img_start + $img_st_close, $img_len);
1404 logger('found photo ' . $image, LOGGER_DEBUG);
1406 if (stristr($image, $site . '/photo/')) {
1407 // Only embed locally hosted photos
1409 $i = basename($image);
1410 $i = str_replace(['.jpg', '.png', '.gif'], ['', '', ''], $i);
1411 $x = strpos($i, '-');
1414 $res = substr($i, $x + 1);
1415 $i = substr($i, 0, $x);
1416 $r = q("SELECT * FROM `photo` WHERE `resource-id` = '%s' AND `scale` = %d AND `uid` = %d",
1421 if (DBM::is_result($r)) {
1423 * Check to see if we should replace this photo link with an embedded image
1424 * 1. No need to do so if the photo is public
1425 * 2. If there's a contact-id provided, see if they're in the access list
1426 * for the photo. If so, embed it.
1427 * 3. Otherwise, if we have an item, see if the item permissions match the photo
1428 * permissions, regardless of order but first check to see if they're an exact
1429 * match to save some processing overhead.
1431 if (self::hasPermissions($r[0])) {
1433 $recips = self::enumeratePermissions($r[0]);
1434 if (in_array($cid, $recips)) {
1438 if (self::samePermissions($item, $r[0])) {
1444 $data = $r[0]['data'];
1445 $type = $r[0]['type'];
1447 // If a custom width and height were specified, apply before embedding
1448 if (preg_match("/\[img\=([0-9]*)x([0-9]*)\]/is", substr($orig_body, $img_start, $img_st_close), $match)) {
1449 logger('scaling photo', LOGGER_DEBUG);
1451 $width = intval($match[1]);
1452 $height = intval($match[2]);
1454 $Image = new Image($data, $type);
1455 if ($Image->isValid()) {
1456 $Image->scaleDown(max($width, $height));
1457 $data = $Image->asString();
1458 $type = $Image->getType();
1462 logger('replacing photo', LOGGER_DEBUG);
1463 $image = 'data:' . $type . ';base64,' . base64_encode($data);
1464 logger('replaced: ' . $image, LOGGER_DATA);
1470 $new_body = $new_body . substr($orig_body, 0, $img_start + $img_st_close) . $image . '[/img]';
1471 $orig_body = substr($orig_body, $img_start + $img_st_close + $img_len + strlen('[/img]'));
1472 if ($orig_body === false) {
1476 $img_start = strpos($orig_body, '[img');
1477 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
1478 $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
1481 $new_body = $new_body . $orig_body;
1486 private static function hasPermissions($obj)
1490 x($obj, 'allow_cid')
1492 x($obj, 'allow_gid')
1501 private static function samePermissions($obj1, $obj2)
1503 // first part is easy. Check that these are exactly the same.
1504 if (($obj1['allow_cid'] == $obj2['allow_cid'])
1505 && ($obj1['allow_gid'] == $obj2['allow_gid'])
1506 && ($obj1['deny_cid'] == $obj2['deny_cid'])
1507 && ($obj1['deny_gid'] == $obj2['deny_gid'])) {
1511 // This is harder. Parse all the permissions and compare the resulting set.
1512 $recipients1 = self::enumeratePermissions($obj1);
1513 $recipients2 = self::enumeratePermissions($obj2);
1517 /// @TODO Comparison of arrays, maybe use array_diff_assoc() here?
1518 return ($recipients1 == $recipients2);
1521 // returns an array of contact-ids that are allowed to see this object
1522 private static function enumeratePermissions($obj)
1524 $allow_people = expand_acl($obj['allow_cid']);
1525 $allow_groups = Group::expand(expand_acl($obj['allow_gid']));
1526 $deny_people = expand_acl($obj['deny_cid']);
1527 $deny_groups = Group::expand(expand_acl($obj['deny_gid']));
1528 $recipients = array_unique(array_merge($allow_people, $allow_groups));
1529 $deny = array_unique(array_merge($deny_people, $deny_groups));
1530 $recipients = array_diff($recipients, $deny);
1534 public static function getFeedTags($item)
1538 $cnt = preg_match_all('|\#\[url\=(.*?)\](.*?)\[\/url\]|', $item['tag'], $matches);
1540 for ($x = 0; $x < $cnt; $x ++) {
1541 if ($matches[1][$x]) {
1542 $ret[$matches[2][$x]] = ['#', $matches[1][$x], $matches[2][$x]];
1547 $cnt = preg_match_all('|\@\[url\=(.*?)\](.*?)\[\/url\]|', $item['tag'], $matches);
1549 for ($x = 0; $x < $cnt; $x ++) {
1550 if ($matches[1][$x]) {
1551 $ret[] = ['@', $matches[1][$x], $matches[2][$x]];
1558 public static function expire($uid, $days, $network = "", $force = false)
1560 if (!$uid || ($days < 1)) {
1565 * $expire_network_only = save your own wall posts
1566 * and just expire conversations started by others
1568 $expire_network_only = PConfig::get($uid,'expire', 'network_only');
1569 $sql_extra = (intval($expire_network_only) ? " AND wall = 0 " : "");
1571 if ($network != "") {
1572 $sql_extra .= sprintf(" AND network = '%s' ", dbesc($network));
1575 * There is an index "uid_network_received" but not "uid_network_created"
1576 * This avoids the creation of another index just for one purpose.
1577 * And it doesn't really matter wether to look at "received" or "created"
1579 $range = "AND `received` < UTC_TIMESTAMP() - INTERVAL %d DAY ";
1581 $range = "AND `created` < UTC_TIMESTAMP() - INTERVAL %d DAY ";
1584 $r = q("SELECT `file`, `resource-id`, `starred`, `type`, `id` FROM `item`
1585 WHERE `uid` = %d $range
1593 if (!DBM::is_result($r)) {
1597 $expire_items = PConfig::get($uid, 'expire', 'items', 1);
1599 // Forcing expiring of items - but not notes and marked items
1601 $expire_items = true;
1604 $expire_notes = PConfig::get($uid, 'expire', 'notes', 1);
1605 $expire_starred = PConfig::get($uid, 'expire', 'starred', 1);
1606 $expire_photos = PConfig::get($uid, 'expire', 'photos', 0);
1608 logger('User '.$uid.': expire: # items=' . count($r). "; expire items: $expire_items, expire notes: $expire_notes, expire starred: $expire_starred, expire photos: $expire_photos");
1610 foreach ($r as $item) {
1612 // don't expire filed items
1614 if (strpos($item['file'],'[') !== false) {
1618 // Only expire posts, not photos and photo comments
1620 if ($expire_photos == 0 && strlen($item['resource-id'])) {
1622 } elseif ($expire_starred == 0 && intval($item['starred'])) {
1624 } elseif ($expire_notes == 0 && $item['type'] == 'note') {
1626 } elseif ($expire_items == 0 && $item['type'] != 'note') {
1630 self::delete($item['id'], PRIORITY_LOW);
1634 /// @TODO: This query seems to be really slow
1635 public static function firstPostDate($uid, $wall = false)
1637 $r = q("SELECT `id`, `created` FROM `item`
1638 WHERE `uid` = %d AND `wall` = %d AND `deleted` = 0 AND `visible` = 1 AND `moderated` = 0
1640 ORDER BY `created` ASC LIMIT 1",
1642 intval($wall ? 1 : 0)
1644 if (DBM::is_result($r)) {
1645 return substr(DateTimeFormat::local($r[0]['created']),0,10);
1651 * @brief add/remove activity to an item
1653 * Toggle activities as like,dislike,attend of an item
1655 * @param string $item_id
1656 * @param string $verb
1657 * Activity verb. One of
1658 * like, unlike, dislike, undislike, attendyes, unattendyes,
1659 * attendno, unattendno, attendmaybe, unattendmaybe
1660 * @hook 'post_local_end'
1662 * 'post_id' => ID of posted item
1664 public static function performLike($item_id, $verb)
1666 if (!local_user() && !remote_user()) {
1673 $bodyverb = L10n::t('%1$s likes %2$s\'s %3$s');
1674 $activity = ACTIVITY_LIKE;
1678 $bodyverb = L10n::t('%1$s doesn\'t like %2$s\'s %3$s');
1679 $activity = ACTIVITY_DISLIKE;
1683 $bodyverb = L10n::t('%1$s is attending %2$s\'s %3$s');
1684 $activity = ACTIVITY_ATTEND;
1688 $bodyverb = L10n::t('%1$s is not attending %2$s\'s %3$s');
1689 $activity = ACTIVITY_ATTENDNO;
1692 case 'unattendmaybe':
1693 $bodyverb = L10n::t('%1$s may attend %2$s\'s %3$s');
1694 $activity = ACTIVITY_ATTENDMAYBE;
1697 logger('like: unknown verb ' . $verb . ' for item ' . $item_id);
1701 // Enable activity toggling instead of on/off
1702 $event_verb_flag = $activity === ACTIVITY_ATTEND || $activity === ACTIVITY_ATTENDNO || $activity === ACTIVITY_ATTENDMAYBE;
1704 logger('like: verb ' . $verb . ' item ' . $item_id);
1706 $item = dba::selectFirst('item', [], ['`id` = ? OR `uri` = ?', $item_id, $item_id]);
1707 if (!DBM::is_result($item)) {
1708 logger('like: unknown item ' . $item_id);
1712 $uid = $item['uid'];
1713 if (($uid == 0) && local_user()) {
1714 $uid = local_user();
1717 if (!can_write_wall($uid)) {
1718 logger('like: unable to write on wall ' . $uid);
1722 // Retrieves the local post owner
1723 $owner_self_contact = dba::selectFirst('contact', [], ['uid' => $uid, 'self' => true]);
1724 if (!DBM::is_result($owner_self_contact)) {
1725 logger('like: unknown owner ' . $uid);
1729 // Retrieve the current logged in user's public contact
1730 $author_id = public_contact();
1732 $author_contact = dba::selectFirst('contact', [], ['id' => $author_id]);
1733 if (!DBM::is_result($author_contact)) {
1734 logger('like: unknown author ' . $author_id);
1738 // Contact-id is the uid-dependant author contact
1739 if (local_user() == $uid) {
1740 $item_contact_id = $owner_self_contact['id'];
1741 $item_contact = $owner_self_contact;
1743 $item_contact_id = Contact::getIdForURL($author_contact['url'], $uid);
1744 $item_contact = dba::selectFirst('contact', [], ['id' => $item_contact_id]);
1745 if (!DBM::is_result($item_contact)) {
1746 logger('like: unknown item contact ' . $item_contact_id);
1751 // Look for an existing verb row
1752 // event participation are essentially radio toggles. If you make a subsequent choice,
1753 // we need to eradicate your first choice.
1754 if ($event_verb_flag) {
1755 $verbs = "'" . dbesc(ACTIVITY_ATTEND) . "', '" . dbesc(ACTIVITY_ATTENDNO) . "', '" . dbesc(ACTIVITY_ATTENDMAYBE) . "'";
1757 $verbs = "'".dbesc($activity)."'";
1760 $existing_like = q("SELECT `id`, `guid`, `verb` FROM `item`
1761 WHERE `verb` IN ($verbs)
1763 AND `author-id` = %d
1765 AND (`parent` = '%s' OR `parent-uri` = '%s' OR `thr-parent` = '%s')
1767 intval($author_contact['id']),
1768 intval($item['uid']),
1769 dbesc($item_id), dbesc($item_id), dbesc($item['uri'])
1772 // If it exists, mark it as deleted
1773 if (DBM::is_result($existing_like)) {
1774 $like_item = $existing_like[0];
1776 // Already voted, undo it
1777 $fields = ['deleted' => true, 'unseen' => true, 'changed' => DateTimeFormat::utcNow()];
1778 dba::update('item', $fields, ['id' => $like_item['id']]);
1780 // Clean up the Diaspora signatures for this like
1781 // Go ahead and do it even if Diaspora support is disabled. We still want to clean up
1782 // if it had been enabled in the past
1783 dba::delete('sign', ['iid' => $like_item['id']]);
1785 $like_item_id = $like_item['id'];
1786 Worker::add(PRIORITY_HIGH, "Notifier", "like", $like_item_id);
1788 if (!$event_verb_flag || $like_item['verb'] == $activity) {
1793 // Verb is "un-something", just trying to delete existing entries
1794 if (strpos($verb, 'un') === 0) {
1798 // Else or if event verb different from existing row, create a new item row
1799 $post_type = (($item['resource-id']) ? L10n::t('photo') : L10n::t('status'));
1800 if ($item['object-type'] === ACTIVITY_OBJ_EVENT) {
1801 $post_type = L10n::t('event');
1803 $objtype = $item['resource-id'] ? ACTIVITY_OBJ_IMAGE : ACTIVITY_OBJ_NOTE ;
1804 $link = xmlify('<link rel="alternate" type="text/html" href="' . System::baseUrl() . '/display/' . $owner_self_contact['nick'] . '/' . $item['id'] . '" />' . "\n") ;
1805 $body = $item['body'];
1810 <type>$objtype</type>
1812 <id>{$item['uri']}</id>
1815 <content>$body</content>
1819 $ulink = '[url=' . $author_contact['url'] . ']' . $author_contact['name'] . '[/url]';
1820 $alink = '[url=' . $item['author-link'] . ']' . $item['author-name'] . '[/url]';
1821 $plink = '[url=' . System::baseUrl() . '/display/' . $owner_self_contact['nick'] . '/' . $item['id'] . ']' . $post_type . '[/url]';
1824 'guid' => get_guid(32),
1825 'uri' => item_new_uri(self::getApp()->get_hostname(), $item['uid']),
1826 'uid' => $item['uid'],
1827 'contact-id' => $item_contact_id,
1828 'type' => 'activity',
1829 'wall' => $item['wall'],
1831 'gravity' => GRAVITY_LIKE,
1832 'parent' => $item['id'],
1833 'parent-uri' => $item['uri'],
1834 'thr-parent' => $item['uri'],
1835 'owner-id' => $item['owner-id'],
1836 'owner-name' => $item['owner-name'],
1837 'owner-link' => $item['owner-link'],
1838 'owner-avatar' => $item['owner-avatar'],
1839 'author-id' => $author_contact['id'],
1840 'author-name' => $author_contact['name'],
1841 'author-link' => $author_contact['url'],
1842 'author-avatar' => $author_contact['thumb'],
1843 'body' => sprintf($bodyverb, $ulink, $alink, $plink),
1844 'verb' => $activity,
1845 'object-type' => $objtype,
1847 'allow_cid' => $item['allow_cid'],
1848 'allow_gid' => $item['allow_gid'],
1849 'deny_cid' => $item['deny_cid'],
1850 'deny_gid' => $item['deny_gid'],
1855 $new_item_id = Item::insert($new_item);
1857 // @todo: Explain this block
1858 if (! $item['visible']) {
1859 q("UPDATE `item` SET `visible` = 1 WHERE `id` = %d",
1864 // Save the author information for the like in case we need to relay to Diaspora
1865 Diaspora::storeLikeSignature($item_contact, $new_item_id);
1867 $new_item['id'] = $new_item_id;
1869 Addon::callHooks('post_local_end', $new_item);
1871 Worker::add(PRIORITY_HIGH, "Notifier", "like", $new_item_id);
1876 private static function addThread($itemid, $onlyshadow = false)
1878 $items = q("SELECT `uid`, `created`, `edited`, `commented`, `received`, `changed`, `wall`, `private`, `pubmail`,
1879 `moderated`, `visible`, `spam`, `starred`, `bookmark`, `contact-id`, `gcontact-id`,
1880 `deleted`, `origin`, `forum_mode`, `mention`, `network`, `author-id`, `owner-id`
1881 FROM `item` WHERE `id` = %d AND (`parent` = %d OR `parent` = 0) LIMIT 1", intval($itemid), intval($itemid));
1888 $item['iid'] = $itemid;
1891 $result = dba::insert('thread', $item);
1893 logger("Add thread for item ".$itemid." - ".print_r($result, true), LOGGER_DEBUG);
1897 public static function updateThreadFromUri($itemuri, $uid)
1899 $messages = dba::select('item', ['id'], ['uri' => $itemuri, 'uid' => $uid]);
1901 if (DBM::is_result($messages)) {
1902 foreach ($messages as $message) {
1903 self::updateThread($message["id"]);
1908 public static function updateThread($itemid, $setmention = false)
1910 $items = q("SELECT `uid`, `guid`, `title`, `body`, `created`, `edited`, `commented`, `received`, `changed`, `wall`, `private`, `pubmail`, `moderated`, `visible`, `spam`, `starred`, `bookmark`, `contact-id`, `gcontact-id`,
1911 `deleted`, `origin`, `forum_mode`, `network`, `rendered-html`, `rendered-hash` FROM `item` WHERE `id` = %d AND (`parent` = %d OR `parent` = 0) LIMIT 1", intval($itemid), intval($itemid));
1913 if (!DBM::is_result($items)) {
1920 $item["mention"] = 1;
1925 foreach ($item as $field => $data)
1926 if (!in_array($field, ["guid", "title", "body", "rendered-html", "rendered-hash"])) {
1931 $sql .= "`".$field."` = '".dbesc($data)."'";
1934 $result = q("UPDATE `thread` SET ".$sql." WHERE `iid` = %d", intval($itemid));
1936 logger("Update thread for item ".$itemid." - guid ".$item["guid"]." - ".print_r($result, true)." ".print_r($item, true), LOGGER_DEBUG);
1938 // Updating a shadow item entry
1939 $items = dba::selectFirst('item', ['id'], ['guid' => $item['guid'], 'uid' => 0]);
1941 if (!DBM::is_result($items)) {
1945 $result = dba::update(
1947 ['title' => $item['title'], 'body' => $item['body'], 'rendered-html' => $item['rendered-html'], 'rendered-hash' => $item['rendered-hash']],
1948 ['id' => $items['id']]
1951 logger("Updating public shadow for post ".$items["id"]." - guid ".$item["guid"]." Result: ".print_r($result, true), LOGGER_DEBUG);
1954 public static function deleteThreadFromUri($itemuri, $uid)
1956 $messages = dba::select('item', ['id'], ['uri' => $itemuri, 'uid' => $uid]);
1958 if (DBM::is_result($messages)) {
1959 foreach ($messages as $message) {
1960 self::deleteThread($message["id"], $itemuri);
1965 public static function deleteThread($itemid, $itemuri = "")
1967 $item = dba::select('thread', ['uid'], ['iid' => $itemid]);
1969 if (!DBM::is_result($item)) {
1970 logger('No thread found for id '.$itemid, LOGGER_DEBUG);
1974 // Using dba::delete at this time could delete the associated item entries
1975 $result = dba::e("DELETE FROM `thread` WHERE `iid` = ?", $itemid);
1977 logger("deleteThread: Deleted thread for item ".$itemid." - ".print_r($result, true), LOGGER_DEBUG);
1979 if ($itemuri != "") {
1980 $r = q("SELECT `id` FROM `item` WHERE `uri` = '%s' AND NOT `deleted` AND NOT (`uid` IN (%d, 0))",
1982 intval($item["uid"])
1984 if (!DBM::is_result($r)) {
1985 dba::delete('item', ['uri' => $itemuri, 'uid' => 0]);
1986 logger("deleteThread: Deleted shadow for item ".$itemuri, LOGGER_DEBUG);