]> git.mxchange.org Git - friendica.git/blob - src/Model/Item.php
Merge pull request #4376 from MrPetovan/task/3878-move-include-like-to-src
[friendica.git] / src / Model / Item.php
1 <?php
2
3 /**
4  * @file src/Model/Item.php
5  */
6
7 namespace Friendica\Model;
8
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 dba;
26 use Text_LanguageDetect;
27
28 require_once 'boot.php';
29 require_once 'include/tags.php';
30 require_once 'include/threads.php';
31 require_once 'include/items.php';
32 require_once 'include/text.php';
33
34 class Item extends BaseObject
35 {
36         /**
37          * @brief Update existing item entries
38          *
39          * @param array $fields The fields that are to be changed
40          * @param array $condition The condition for finding the item entries
41          *
42          * In the future we may have to change permissions as well.
43          * Then we had to add the user id as third parameter.
44          *
45          * A return value of "0" doesn't mean an error - but that 0 rows had been changed.
46          *
47          * @return integer|boolean number of affected rows - or "false" if there was an error
48          */
49         public static function update(array $fields, array $condition)
50         {
51                 if (empty($condition) || empty($fields)) {
52                         return false;
53                 }
54
55                 $success = dba::update('item', $fields, $condition);
56
57                 if (!$success) {
58                         return false;
59                 }
60
61                 $rows = dba::affected_rows();
62
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']) {
69                                 continue;
70                         }
71
72                         create_tags_from_item($item['id']);
73                         Term::createFromItem($item['id']);
74                         update_thread($item['id']);
75
76                         Worker::add(PRIORITY_HIGH, "Notifier", 'edit_post', $item['id']);
77                 }
78
79                 return $rows;
80         }
81
82         /**
83          * @brief Delete an item and notify others about it - if it was ours
84          *
85          * @param integer $item_id Item ID that should be delete
86          *
87          * @return $boolean success
88          */
89         public static function delete($item_id, $priority = PRIORITY_HIGH)
90         {
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)) {
95                         return false;
96                 }
97
98                 if ($item['deleted']) {
99                         return false;
100                 }
101
102                 $parent = dba::selectFirst('item', ['origin'], ['id' => $item['parent']]);
103                 if (!DBM::is_result($parent)) {
104                         $parent = ['origin' => false];
105                 }
106
107                 logger('delete item: ' . $item['id'], LOGGER_DEBUG);
108
109                 // clean up categories and tags so they don't end up as orphans
110
111                 $matches = false;
112                 $cnt = preg_match_all('/<(.*?)>/', $item['file'], $matches, PREG_SET_ORDER);
113                 if ($cnt) {
114                         foreach ($matches as $mtch) {
115                                 file_tag_unsave_file($item['uid'], $item['id'], $mtch[1],true);
116                         }
117                 }
118
119                 $matches = false;
120
121                 $cnt = preg_match_all('/\[(.*?)\]/', $item['file'], $matches, PREG_SET_ORDER);
122                 if ($cnt) {
123                         foreach ($matches as $mtch) {
124                                 file_tag_unsave_file($item['uid'], $item['id'], $mtch[1],false);
125                         }
126                 }
127
128                 /*
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.
133                  */
134                 if (strlen($item['resource-id'])) {
135                         dba::delete('photo', ['resource-id' => $item['resource-id'], 'uid' => $item['uid']]);
136                 }
137
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']]);
141                 }
142
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']]);
147                 }
148
149                 // Set the item to "deleted"
150                 dba::update('item', ['deleted' => true, 'title' => '', 'body' => '',
151                                         'edited' => datetime_convert(), 'changed' => datetime_convert()],
152                                 ['id' => $item['id']]);
153
154                 create_tags_from_item($item['id']);
155                 Term::createFromItem($item['id']);
156                 delete_thread($item['id'], $item['parent-uri']);
157
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);
163                         }
164                 }
165
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']));
169                 }
170
171                 return true;
172         }
173
174         public static function insert($arr, $force_parent = false, $notify = false, $dontcache = false)
175         {
176                 $a = get_app();
177
178                 // If it is a posting where users should get notifications, then define it as wall posting
179                 if ($notify) {
180                         $arr['wall'] = 1;
181                         $arr['type'] = 'wall';
182                         $arr['origin'] = 1;
183                         $arr['network'] = NETWORK_DFRN;
184                         $arr['protocol'] = PROTOCOL_DFRN;
185
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());
194                                 }
195                         }
196                 } else {
197                         $arr['network'] = trim(defaults($arr, 'network', NETWORK_PHANTOM));
198                 }
199
200                 if ($notify) {
201                         $guid_prefix = "";
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']);
206                 } else {
207                         $parsed = parse_url($arr["author-link"]);
208                         $guid_prefix = hash("crc32", $parsed["host"]);
209                 }
210
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']))));
213
214                 // Store conversation data
215                 $arr = Conversation::insert($arr);
216
217                 /*
218                  * If a Diaspora signature structure was passed in, pull it out of the
219                  * item array and set it aside for later storage.
220                  */
221
222                 $dsprsig = null;
223                 if (x($arr, 'dsprsig')) {
224                         $encoded_signature = $arr['dsprsig'];
225                         $dsprsig = json_decode(base64_decode($arr['dsprsig']));
226                         unset($arr['dsprsig']);
227                 }
228
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']);
236                         }
237                 }
238
239                 if (x($arr, 'gravity')) {
240                         $arr['gravity'] = intval($arr['gravity']);
241                 } elseif ($arr['parent-uri'] === $arr['uri']) {
242                         $arr['gravity'] = 0;
243                 } elseif (activity_match($arr['verb'],ACTIVITY_POST)) {
244                         $arr['gravity'] = 6;
245                 } else {
246                         $arr['gravity'] = 6;   // extensible catchall
247                 }
248
249                 $arr['type'] = defaults($arr, 'type', 'remote');
250
251                 $uid = intval($arr['uid']);
252
253                 // check for create date and expire time
254                 $expire_interval = Config::get('system', 'dbclean-expire-days', 0);
255
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'];
259                 }
260
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);
266                                 return 0;
267                         }
268                 }
269
270                 /*
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)
274                  */
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'])),
278                                         intval($uid),
279                                         dbesc(NETWORK_DIASPORA),
280                                         dbesc(NETWORK_DFRN),
281                                         dbesc(NETWORK_OSTATUS)
282                                 );
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
285                                 if ($uid != 0) {
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']);
287                                 }
288
289                                 return $r[0]["id"];
290                         }
291                 }
292
293                 self::addLanguageInPostopts($arr);
294
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) ? datetime_convert('UTC','UTC', $arr['received']) : datetime_convert());
304                 $arr['created']       = ((x($arr, 'created') !== false) ? datetime_convert('UTC','UTC', $arr['created']) : $arr['received']);
305                 $arr['edited']        = ((x($arr, 'edited') !== false) ? datetime_convert('UTC','UTC', $arr['edited']) : $arr['created']);
306                 $arr['changed']       = ((x($arr, 'changed') !== false) ? datetime_convert('UTC','UTC', $arr['changed']) : $arr['created']);
307                 $arr['commented']     = ((x($arr, 'commented') !== false) ? datetime_convert('UTC','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);
312                 $arr['deleted']       = 0;
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', ''));
336
337                 // When there is no content then we don't post it
338                 if ($arr['body'].$arr['title'] == '') {
339                         return 0;
340                 }
341
342                 // Items cannot be stored before they happen ...
343                 if ($arr['created'] > datetime_convert()) {
344                         $arr['created'] = datetime_convert();
345                 }
346
347                 // We haven't invented time travel by now.
348                 if ($arr['edited'] > datetime_convert()) {
349                         $arr['edited'] = datetime_convert();
350                 }
351
352                 if (($arr['author-link'] == "") && ($arr['owner-link'] == "")) {
353                         logger("Both author-link and owner-link are empty. Called by: " . System::callstack(), LOGGER_DEBUG);
354                 }
355
356                 if ($arr['plink'] == "") {
357                         $arr['plink'] = System::baseUrl() . '/display/' . urlencode($arr['guid']);
358                 }
359
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'])),
364                                 intval($arr['uid'])
365                         );
366
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']))
371                                 );
372                         }
373
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']),
377                                         intval($arr['uid'])
378                                 );
379                         }
380
381                         if (DBM::is_result($r)) {
382                                 $arr['network'] = $r[0]["network"];
383                         }
384
385                         // Fallback to friendica (why is it empty in some cases?)
386                         if ($arr['network'] == "") {
387                                 $arr['network'] = NETWORK_DFRN;
388                         }
389
390                         logger("Set network to " . $arr["network"] . " for " . $arr["uri"], LOGGER_DEBUG);
391                 }
392
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) {
395                         /*
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")
398                          */
399                         if ($arr['parent-uri'] != $arr['uri']) {
400                                 $arr["contact-id"] = Contact::getIdForURL($arr['author-link'], $uid);
401                         }
402
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);
406                         }
407
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));
411
412                                 if (DBM::is_result($r)) {
413                                         $arr["contact-id"] = $r[0]["id"];
414                                 }
415                         }
416
417                         logger("Contact-id was missing for post ".$arr["guid"]." from user id ".$uid." - now set to ".$arr["contact-id"], LOGGER_DEBUG);
418                 }
419
420                 if (!x($arr, "gcontact-id")) {
421                         /*
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.
425                          */
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']]);
429                         } else {
430                                 $arr["gcontact-id"] = GContact::getId(["url" => $arr['author-link'], "network" => $arr['network'],
431                                                                          "photo" => $arr['author-avatar'], "name" => $arr['author-name']]);
432                         }
433                 }
434
435                 if ($arr["author-id"] == 0) {
436                         $arr["author-id"] = Contact::getIdForURL($arr["author-link"], 0);
437                 }
438
439                 if (Contact::isBlocked($arr["author-id"])) {
440                         logger('Contact '.$arr["author-id"].' is blocked, item '.$arr["uri"].' will not be stored');
441                         return 0;
442                 }
443
444                 if ($arr["owner-id"] == 0) {
445                         $arr["owner-id"] = Contact::getIdForURL($arr["owner-link"], 0);
446                 }
447
448                 if (Contact::isBlocked($arr["owner-id"])) {
449                         logger('Contact '.$arr["owner-id"].' is blocked, item '.$arr["uri"].' will not be stored');
450                         return 0;
451                 }
452
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']));
458
459                         if (DBM::is_result($r)) {
460                                 logger('found item with guid '.$arr['guid'].' for user '.$arr['uid'].' on network '.$arr['network'], LOGGER_DEBUG);
461                                 return 0;
462                         }
463                 }
464
465                 // Check for hashtags in the body and repair or add hashtag links
466                 self::setHashtags($arr);
467
468                 $arr['thr-parent'] = $arr['parent-uri'];
469
470                 if ($arr['parent-uri'] === $arr['uri']) {
471                         $parent_id = 0;
472                         $parent_deleted = 0;
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';
478                 } else {
479
480                         // find the parent and snarf the item id and ACLs
481                         // and anything else we need to inherit
482
483                         $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d ORDER BY `id` ASC LIMIT 1",
484                                 dbesc($arr['parent-uri']),
485                                 intval($arr['uid'])
486                         );
487
488                         if (DBM::is_result($r)) {
489
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.
493
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']),
500                                                 intval($arr['uid'])
501                                         );
502
503                                         if (DBM::is_result($z)) {
504                                                 $r = $z;
505                                         }
506                                 }
507
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';
516
517                                 /*
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.
521                                  */
522                                 if ($r[0]['private']) {
523                                         $arr['private'] = $r[0]['private'];
524                                 }
525
526                                 /*
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.
530                                  */
531                                 if ((intval($r[0]['forum_mode']) == 1) && $r[0]['private']) {
532                                         $arr['private'] = 0;
533                                 }
534
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);
544                                         }
545                                 }
546                         } else {
547                                 /*
548                                  * Allow one to see reply tweets from status.net even when
549                                  * we don't have or can't see the original post.
550                                  */
551                                 if ($force_parent) {
552                                         logger('$force_parent=true, reply converted to top-level post.');
553                                         $parent_id = 0;
554                                         $arr['parent-uri'] = $arr['uri'];
555                                         $arr['gravity'] = 0;
556                                 } else {
557                                         logger('item parent '.$arr['parent-uri'].' for '.$arr['uid'].' was not found - ignoring item');
558                                         return 0;
559                                 }
560
561                                 $parent_deleted = 0;
562                         }
563                 }
564
565                 $r = q("SELECT `id` FROM `item` WHERE `uri` = '%s' AND `network` IN ('%s', '%s') AND `uid` = %d LIMIT 1",
566                         dbesc($arr['uri']),
567                         dbesc($arr['network']),
568                         dbesc(NETWORK_DFRN),
569                         intval($arr['uid'])
570                 );
571                 if (DBM::is_result($r)) {
572                         logger('duplicated item with the same uri found. '.print_r($arr,true));
573                         return 0;
574                 }
575
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",
579                                 dbesc($arr['guid']),
580                                 intval($arr['uid'])
581                         );
582                         if (DBM::is_result($r)) {
583                                 logger('duplicated item with the same guid found. '.print_r($arr,true));
584                                 return 0;
585                         }
586                 } else {
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",
589                                 dbesc($arr['body']),
590                                 dbesc($arr['network']),
591                                 dbesc($arr['created']),
592                                 intval($arr['contact-id']),
593                                 intval($arr['uid'])
594                         );
595                         if (DBM::is_result($r)) {
596                                 logger('duplicated item with the same body found. '.print_r($arr,true));
597                                 return 0;
598                         }
599                 }
600
601                 // Is this item available in the global items (with uid=0)?
602                 if ($arr["uid"] == 0) {
603                         $arr["global"] = true;
604
605                         // Set the global flag on all items if this was a global item entry
606                         dba::update('item', ['global' => true], ['uri' => $arr["uri"]]);
607                 } else {
608                         $isglobal = q("SELECT `global` FROM `item` WHERE `uid` = 0 AND `uri` = '%s'", dbesc($arr["uri"]));
609
610                         $arr["global"] = (DBM::is_result($isglobal) && count($isglobal) > 0);
611                 }
612
613                 // ACL settings
614                 if (strlen($allow_cid) || strlen($allow_gid) || strlen($deny_cid) || strlen($deny_gid)) {
615                         $private = 1;
616                 } else {
617                         $private = $arr['private'];
618                 }
619
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;
626
627                 // Fill the cache field
628                 put_item_in_cache($arr);
629
630                 if ($notify) {
631                         Addon::callHooks('post_local', $arr);
632                 } else {
633                         Addon::callHooks('post_remote', $arr);
634                 }
635
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']);
639
640                 if (x($arr, 'cancel')) {
641                         logger('post cancelled by addon.');
642                         return 0;
643                 }
644
645                 /*
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.
649                  */
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);
654                                 return 0;
655                         }
656                 }
657
658                 logger('' . print_r($arr,true), LOGGER_DATA);
659
660                 dba::transaction();
661                 $r = dba::insert('item', $arr);
662
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();
666                 } else {
667                         // This can happen - for example - if there are locking timeouts.
668                         dba::rollback();
669
670                         // Store the data into a spool file so that we can try again later.
671
672                         // At first we restore the Diaspora signature that we removed above.
673                         if (isset($encoded_signature)) {
674                                 $arr['dsprsig'] = $encoded_signature;
675                         }
676
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';
680
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);
686                         }
687                         return 0;
688                 }
689
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.");
693                         dba::rollback();
694                         return 0;
695                 }
696
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'",
700                         dbesc($arr['uri']),
701                         intval($arr['uid']),
702                         dbesc($arr['network'])
703                 );
704
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 ...");
708                         dba::rollback();
709                         return 0;
710                 }
711
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']);
715
716                         // Yes, we could do a rollback here - but we are having many users with MyISAM.
717                         dba::delete('item', ['id' => $current_post]);
718                         dba::commit();
719                         return 0;
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.");
723                         dba::rollback();
724                         return 0;
725                 }
726
727                 logger('created item '.$current_post);
728                 self::updateContact($arr);
729
730                 if (!$parent_id || ($arr['parent-uri'] === $arr['uri'])) {
731                         $parent_id = $current_post;
732                 }
733
734                 // Set parent id
735                 dba::update('item', ['parent' => $parent_id], ['id' => $current_post]);
736
737                 $arr['id'] = $current_post;
738                 $arr['parent'] = $parent_id;
739
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' => datetime_convert(), 'changed' => datetime_convert()], ['id' => $parent_id]);
744                 } else {
745                         dba::update('item', ['changed' => datetime_convert()], ['id' => $parent_id]);
746                 }
747
748                 if ($dsprsig) {
749                         /*
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.
752                          */
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);
756                         }
757
758                         dba::insert('sign', ['iid' => $current_post, 'signed_text' => $dsprsig->signed_text,
759                                                 'signature' => $dsprsig->signature, 'signer' => $dsprsig->signer]);
760                 }
761
762                 $deleted = self::tagDeliver($arr['uid'], $current_post);
763
764                 /*
765                  * current post can be deleted if is for a community page and no mention are
766                  * in it.
767                  */
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)) {
771                                 if ($notify) {
772                                         Addon::callHooks('post_local_end', $r[0]);
773                                 } else {
774                                         Addon::callHooks('post_remote_end', $r[0]);
775                                 }
776                         } else {
777                                 logger('new item not found in DB, id ' . $current_post);
778                         }
779                 }
780
781                 if ($arr['parent-uri'] === $arr['uri']) {
782                         add_thread($current_post);
783                 } else {
784                         update_thread($parent_id);
785                 }
786
787                 dba::commit();
788
789                 /*
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.
792                  */
793                 create_tags_from_item($current_post);
794                 Term::createFromItem($current_post);
795
796                 if ($arr['parent-uri'] === $arr['uri']) {
797                         self::addShadow($current_post);
798                 } else {
799                         self::addShadowPost($current_post);
800                 }
801
802                 check_user_notification($current_post);
803
804                 if ($notify) {
805                         Worker::add(['priority' => PRIORITY_HIGH, 'dont_fork' => true], "Notifier", $notify_type, $current_post);
806                 }
807
808                 return $current_post;
809         }
810
811         /**
812          * @brief Add a shadow entry for a given item id that is a thread starter
813          *
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.
817          *
818          * @param integer $itemid Item ID that should be added
819          */
820         public static function addShadow($itemid)
821         {
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);
825
826                 if (!DBM::is_result($item)) {
827                         return;
828                 }
829
830                 // is it already a copy?
831                 if (($itemid == 0) || ($item['uid'] == 0)) {
832                         return;
833                 }
834
835                 // Is it a visible public post?
836                 if (!$item["visible"] || $item["deleted"] || $item["moderated"] || $item["private"]) {
837                         return;
838                 }
839
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, ""])) {
842                         return;
843                 }
844
845                 // Is the public contact configured as hidden?
846                 if (Contact::isHidden($item["owner-id"]) || Contact::isHidden($item["author-id"])) {
847                         return;
848                 }
849
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])) {
854                                 return;
855                         }
856
857                         // Check if the contact is hidden or blocked
858                         if (!dba::exists('contact', ['hidden' => false, 'blocked' => false, 'id' => $item['contact-id']])) {
859                                 return;
860                         }
861                 }
862
863                 // Only add a shadow, if the profile isn't hidden
864                 if (dba::exists('user', ['uid' => $item['uid'], 'hidewall' => true])) {
865                         return;
866                 }
867
868                 $item = dba::selectFirst('item', [], ['id' => $itemid]);
869
870                 if (DBM::is_result($item) && ($item["allow_cid"] == '')  && ($item["allow_gid"] == '') &&
871                         ($item["deny_cid"] == '') && ($item["deny_gid"] == '')) {
872
873                         if (!dba::exists('item', ['uri' => $item['uri'], 'uid' => 0])) {
874                                 // Preparing public shadow (removing user specific data)
875                                 unset($item['id']);
876                                 $item['uid'] = 0;
877                                 $item['origin'] = 0;
878                                 $item['wall'] = 0;
879                                 $item['contact-id'] = Contact::getIdForURL($item['author-link'], 0);
880
881                                 if (in_array($item['type'], ["net-comment", "wall-comment"])) {
882                                         $item['type'] = 'remote-comment';
883                                 } elseif ($item['type'] == 'wall') {
884                                         $item['type'] = 'remote';
885                                 }
886
887                                 $public_shadow = self::insert($item, false, false, true);
888
889                                 logger("Stored public shadow for thread ".$itemid." under id ".$public_shadow, LOGGER_DEBUG);
890                         }
891                 }
892         }
893
894         /**
895          * @brief Add a shadow entry for a given item id that is a comment
896          *
897          * This function does the same like the function above - but for comments
898          *
899          * @param integer $itemid Item ID that should be added
900          */
901         public static function addShadowPost($itemid)
902         {
903                 $item = dba::selectFirst('item', [], ['id' => $itemid]);
904                 if (!DBM::is_result($item)) {
905                         return;
906                 }
907
908                 // Is it a toplevel post?
909                 if ($item['id'] == $item['parent']) {
910                         self::addShadow($itemid);
911                         return;
912                 }
913
914                 // Is this a shadow entry?
915                 if ($item['uid'] == 0)
916                         return;
917
918                 // Is there a shadow parent?
919                 if (!dba::exists('item', ['uri' => $item['parent-uri'], 'uid' => 0])) {
920                         return;
921                 }
922
923                 // Is there already a shadow entry?
924                 if (dba::exists('item', ['uri' => $item['uri'], 'uid' => 0])) {
925                         return;
926                 }
927
928                 // Preparing public shadow (removing user specific data)
929                 unset($item['id']);
930                 $item['uid'] = 0;
931                 $item['origin'] = 0;
932                 $item['wall'] = 0;
933                 $item['contact-id'] = Contact::getIdForURL($item['author-link'], 0);
934
935                 if (in_array($item['type'], ["net-comment", "wall-comment"])) {
936                         $item['type'] = 'remote-comment';
937                 } elseif ($item['type'] == 'wall') {
938                         $item['type'] = 'remote';
939                 }
940
941                 $public_shadow = self::insert($item, false, false, true);
942
943                 logger("Stored public shadow for comment ".$item['uri']." under id ".$public_shadow, LOGGER_DEBUG);
944         }
945
946          /**
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.
950          */
951         private static function addLanguageInPostopts(&$arr)
952         {
953                 if (x($arr, 'postopts')) {
954                         if (strstr($arr['postopts'], 'lang=')) {
955                                 // do not override
956                                 return;
957                         }
958                         $postopts = $arr['postopts'];
959                 } else {
960                         $postopts = "";
961                 }
962
963                 $naked_body = preg_replace('/\[(.+?)\]/','', $arr['body']);
964                 $l = new Text_LanguageDetect();
965                 $lng = $l->detect($naked_body, 3);
966
967                 if (sizeof($lng) > 0) {
968                         if ($postopts != "") {
969                                 $postopts .= '&'; // arbitrary separator, to be reviewed
970                         }
971
972                         $postopts .= 'lang=';
973                         $sep = "";
974
975                         foreach ($lng as $language => $score) {
976                                 $postopts .= $sep . $language . ";" . $score;
977                                 $sep = ':';
978                         }
979                         $arr['postopts'] = $postopts;
980                 }
981         }
982
983         /**
984          * @brief Creates an unique guid out of a given uri
985          *
986          * @param string $uri uri of an item entry
987          * @param string $host (Optional) hostname for the GUID prefix
988          * @return string unique guid
989          */
990         public static function guidFromUri($uri, $host = "")
991         {
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);
995
996                 // When the hostname isn't given, we take it from the uri
997                 if ($host == "") {
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);
1002                         } else {
1003                                 $host = $parsed["host"];
1004                         }
1005                 }
1006
1007                 // We use a hash of the hostname as prefix for the guid
1008                 $guid_prefix = hash("crc32", $host);
1009
1010                 // Remove the scheme to make sure that "https" and "http" doesn't make a difference
1011                 unset($parsed["scheme"]);
1012
1013                 // Glue it together to be able to make a hash from it
1014                 $host_id = implode("/", $parsed);
1015
1016                 // We could use any hash algorithm since it isn't a security issue
1017                 $host_hash = hash("ripemd128", $host_id);
1018
1019                 return $guid_prefix.$host_hash;
1020         }
1021
1022         /**
1023          * @brief Set "success_update" and "last-item" to the date of the last time we heard from this contact
1024          *
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)
1028          *
1029          * @param array $arr Contains the just posted item record
1030          */
1031         private static function updateContact($arr)
1032         {
1033                 // Unarchive the author
1034                 $contact = dba::selectFirst('contact', [], ['id' => $arr["author-link"]]);
1035                 if ($contact['term-date'] > NULL_DATE) {
1036                          Contact::unmarkForArchival($contact);
1037                 }
1038
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);
1044                         }
1045                 }
1046
1047                 $update = (!$arr['private'] && (($arr["author-link"] === $arr["owner-link"]) || ($arr["parent-uri"] === $arr["uri"])));
1048
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)) {
1054                                 $update = true;
1055                         }
1056                 }
1057
1058                 if ($update) {
1059                         dba::update('contact', ['success_update' => $arr['received'], 'last-item' => $arr['received']],
1060                                 ['id' => $arr['contact-id']]);
1061                 }
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']]);
1066
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']]);
1070                         }
1071                 }
1072         }
1073
1074         private static function setHashtags(&$item)
1075         {
1076
1077                 $tags = get_tags($item["body"]);
1078
1079                 // No hashtags?
1080                 if (!count($tags)) {
1081                         return false;
1082                 }
1083
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
1086                 rsort($tags);
1087
1088                 $URLSearchString = "^\[\]";
1089
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"]);
1094
1095                         $item["tag"] = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
1096                                         "#[url=".System::baseUrl()."/search?tag=$2]$2[/url]", $item["tag"]);
1097                 }
1098
1099                 // mask hashtags inside of url, bookmarks and attachments to avoid urls in urls
1100                 $item["body"] = preg_replace_callback("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
1101                         function ($match) {
1102                                 return ("[url=" . str_replace("#", "&num;", $match[1]) . "]" . str_replace("#", "&num;", $match[2]) . "[/url]");
1103                         }, $item["body"]);
1104
1105                 $item["body"] = preg_replace_callback("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism",
1106                         function ($match) {
1107                                 return ("[bookmark=" . str_replace("#", "&num;", $match[1]) . "]" . str_replace("#", "&num;", $match[2]) . "[/bookmark]");
1108                         }, $item["body"]);
1109
1110                 $item["body"] = preg_replace_callback("/\[attachment (.*)\](.*?)\[\/attachment\]/ism",
1111                         function ($match) {
1112                                 return ("[attachment " . str_replace("#", "&num;", $match[1]) . "]" . $match[2] . "[/attachment]");
1113                         }, $item["body"]);
1114
1115                 // Repair recursive urls
1116                 $item["body"] = preg_replace("/&num;\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
1117                                 "&num;$2", $item["body"]);
1118
1119                 foreach ($tags as $tag) {
1120                         if ((strpos($tag, '#') !== 0) || strpos($tag, '[url=')) {
1121                                 continue;
1122                         }
1123
1124                         $basetag = str_replace('_',' ',substr($tag,1));
1125
1126                         $newtag = '#[url=' . System::baseUrl() . '/search?tag=' . rawurlencode($basetag) . ']' . $basetag . '[/url]';
1127
1128                         $item["body"] = str_replace($tag, $newtag, $item["body"]);
1129
1130                         if (!stristr($item["tag"], "/search?tag=" . $basetag . "]" . $basetag . "[/url]")) {
1131                                 if (strlen($item["tag"])) {
1132                                         $item["tag"] = ','.$item["tag"];
1133                                 }
1134                                 $item["tag"] = $newtag.$item["tag"];
1135                         }
1136                 }
1137
1138                 // Convert back the masked hashtags
1139                 $item["body"] = str_replace("&num;", "#", $item["body"]);
1140         }
1141
1142         public static function getGuidById($id)
1143         {
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"];
1147                 } else {
1148                         return "";
1149                 }
1150         }
1151
1152         public static function getIdAndNickByGuid($guid, $uid = 0)
1153         {
1154                 $nick = "";
1155                 $id = 0;
1156
1157                 if ($uid == 0) {
1158                         $uid == local_user();
1159                 }
1160
1161                 // Does the given user have this item?
1162                 if ($uid) {
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)) {
1167                                 $id = $r[0]["id"];
1168                                 $nick = $r[0]["nickname"];
1169                         }
1170                 }
1171
1172                 // Or is it anywhere on the server?
1173                 if ($nick == "") {
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)) {
1181                                 $id = $r[0]["id"];
1182                                 $nick = $r[0]["nickname"];
1183                         }
1184                 }
1185                 return ["nick" => $nick, "id" => $id];
1186         }
1187
1188         /**
1189          * look for mention tags and setup a second delivery chain for forum/community posts if appropriate
1190          * @param int $uid
1191          * @param int $item_id
1192          * @return bool true if item was deleted, else false
1193          */
1194         private static function tagDeliver($uid, $item_id)
1195         {
1196                 $mention = false;
1197
1198                 $u = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
1199                         intval($uid)
1200                 );
1201                 if (!DBM::is_result($u)) {
1202                         return;
1203                 }
1204
1205                 $community_page = (($u[0]['page-flags'] == PAGE_COMMUNITY) ? true : false);
1206                 $prvgroup = (($u[0]['page-flags'] == PAGE_PRVGROUP) ? true : false);
1207
1208                 $i = q("SELECT * FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1",
1209                         intval($item_id),
1210                         intval($uid)
1211                 );
1212                 if (!DBM::is_result($i)) {
1213                         return;
1214                 }
1215
1216                 $item = $i[0];
1217
1218                 $link = normalise_link(System::baseUrl() . '/profile/' . $u[0]['nickname']);
1219
1220                 /*
1221                  * Diaspora uses their own hardwired link URL in @-tags
1222                  * instead of the one we supply with webfinger
1223                  */
1224                 $dlink = normalise_link(System::baseUrl() . '/u/' . $u[0]['nickname']);
1225
1226                 $cnt = preg_match_all('/[\@\!]\[url\=(.*?)\](.*?)\[\/url\]/ism', $item['body'], $matches, PREG_SET_ORDER);
1227                 if ($cnt) {
1228                         foreach ($matches as $mtch) {
1229                                 if (link_compare($link, $mtch[1]) || link_compare($dlink, $mtch[1])) {
1230                                         $mention = true;
1231                                         logger('mention found: ' . $mtch[2]);
1232                                 }
1233                         }
1234                 }
1235
1236                 if (!$mention) {
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)
1240                                 // delete it!
1241                                 logger("no-mention top-level post to communuty or private group. delete.");
1242                                 dba::delete('item', ['id' => $item_id]);
1243                                 return true;
1244                         }
1245                         return;
1246                 }
1247
1248                 $arr = ['item' => $item, 'user' => $u[0], 'contact' => $r[0]];
1249
1250                 Addon::callHooks('tagged', $arr);
1251
1252                 if (!$community_page && !$prvgroup) {
1253                         return;
1254                 }
1255
1256                 /*
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
1260                  */
1261                 if ($item['wall'] || $item['origin'] || ($item['id'] != $item['parent'])) {
1262                         return;
1263                 }
1264
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'])
1268                 );
1269                 if (!DBM::is_result($c)) {
1270                         return;
1271                 }
1272
1273                 // also reset all the privacy bits to the forum default permissions
1274
1275                 $private = ($u[0]['allow_cid'] || $u[0]['allow_gid'] || $u[0]['deny_cid'] || $u[0]['deny_gid']) ? 1 : 0;
1276
1277                 $forum_mode = (($prvgroup) ? 2 : 1);
1278
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']),
1285                         intval($private),
1286                         dbesc($u[0]['allow_cid']),
1287                         dbesc($u[0]['allow_gid']),
1288                         dbesc($u[0]['deny_cid']),
1289                         dbesc($u[0]['deny_gid']),
1290                         intval($item_id)
1291                 );
1292                 update_thread($item_id);
1293
1294                 Worker::add(['priority' => PRIORITY_HIGH, 'dont_fork' => true], 'Notifier', 'tgroup', $item_id);
1295
1296         }
1297
1298         public static function isRemoteSelf($contact, &$datarray)
1299         {
1300                 $a = get_app();
1301
1302                 if (!$contact['remote_self']) {
1303                         return false;
1304                 }
1305
1306                 // Prevent the forwarding of posts that are forwarded
1307                 if ($datarray["extid"] == NETWORK_DFRN) {
1308                         return false;
1309                 }
1310
1311                 // Prevent to forward already forwarded posts
1312                 if ($datarray["app"] == $a->get_hostname()) {
1313                         return false;
1314                 }
1315
1316                 // Only forward posts
1317                 if ($datarray["verb"] != ACTIVITY_POST) {
1318                         return false;
1319                 }
1320
1321                 if (($contact['network'] != NETWORK_FEED) && $datarray['private']) {
1322                         return false;
1323                 }
1324
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"];
1332
1333                                 $datarray['owner-name'] = $r[0]["name"];
1334                                 $datarray['owner-link'] = $r[0]["url"];
1335                                 $datarray['owner-avatar'] = $r[0]["thumb"];
1336
1337                                 $datarray['author-name']   = $datarray['owner-name'];
1338                                 $datarray['author-link']   = $datarray['owner-link'];
1339                                 $datarray['author-avatar'] = $datarray['owner-avatar'];
1340
1341                                 unset($datarray['created']);
1342                                 unset($datarray['edited']);
1343                         }
1344
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"];
1353                         } else {
1354                                 $datarray['private'] = 0;
1355                         }
1356                 }
1357
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);
1362                 } else {
1363                         $datarray["app"] = "Feed";
1364                 }
1365
1366                 // Trigger automatic reactions for addons
1367                 $datarray['api_source'] = true;
1368
1369                 // We have to tell the hooks who we are - this really should be improved
1370                 $_SESSION["authenticated"] = true;
1371                 $_SESSION["uid"] = $contact['uid'];
1372
1373                 return true;
1374         }
1375
1376         /**
1377          *
1378          * @param string $s
1379          * @param int    $uid
1380          * @param array  $item
1381          * @param int    $cid
1382          * @return string
1383          */
1384         public static function fixPrivatePhotos($s, $uid, $item = null, $cid = 0)
1385         {
1386                 if (Config::get('system', 'disable_embedded')) {
1387                         return $s;
1388                 }
1389
1390                 logger('check for photos', LOGGER_DEBUG);
1391                 $site = substr(System::baseUrl(), strpos(System::baseUrl(), '://'));
1392
1393                 $orig_body = $s;
1394                 $new_body = '';
1395
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);
1399
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);
1403
1404                         logger('found photo ' . $image, LOGGER_DEBUG);
1405
1406                         if (stristr($image, $site . '/photo/')) {
1407                                 // Only embed locally hosted photos
1408                                 $replace = false;
1409                                 $i = basename($image);
1410                                 $i = str_replace(['.jpg', '.png', '.gif'], ['', '', ''], $i);
1411                                 $x = strpos($i, '-');
1412
1413                                 if ($x) {
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",
1417                                                 dbesc($i),
1418                                                 intval($res),
1419                                                 intval($uid)
1420                                         );
1421                                         if (DBM::is_result($r)) {
1422                                                 /*
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.
1430                                                  */
1431                                                 if (self::hasPermissions($r[0])) {
1432                                                         if ($cid) {
1433                                                                 $recips = self::enumeratePermissions($r[0]);
1434                                                                 if (in_array($cid, $recips)) {
1435                                                                         $replace = true;
1436                                                                 }
1437                                                         } elseif ($item) {
1438                                                                 if (self::samePermissions($item, $r[0])) {
1439                                                                         $replace = true;
1440                                                                 }
1441                                                         }
1442                                                 }
1443                                                 if ($replace) {
1444                                                         $data = $r[0]['data'];
1445                                                         $type = $r[0]['type'];
1446
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);
1450
1451                                                                 $width = intval($match[1]);
1452                                                                 $height = intval($match[2]);
1453
1454                                                                 $Image = new Image($data, $type);
1455                                                                 if ($Image->isValid()) {
1456                                                                         $Image->scaleDown(max($width, $height));
1457                                                                         $data = $Image->asString();
1458                                                                         $type = $Image->getType();
1459                                                                 }
1460                                                         }
1461
1462                                                         logger('replacing photo', LOGGER_DEBUG);
1463                                                         $image = 'data:' . $type . ';base64,' . base64_encode($data);
1464                                                         logger('replaced: ' . $image, LOGGER_DATA);
1465                                                 }
1466                                         }
1467                                 }
1468                         }
1469
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) {
1473                                 $orig_body = '';
1474                         }
1475
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);
1479                 }
1480
1481                 $new_body = $new_body . $orig_body;
1482
1483                 return $new_body;
1484         }
1485
1486         private static function hasPermissions($obj)
1487         {
1488                 return (
1489                         (
1490                                 x($obj, 'allow_cid')
1491                         ) || (
1492                                 x($obj, 'allow_gid')
1493                         ) || (
1494                                 x($obj, 'deny_cid')
1495                         ) || (
1496                                 x($obj, 'deny_gid')
1497                         )
1498                 );
1499         }
1500
1501         private static function samePermissions($obj1, $obj2)
1502         {
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'])) {
1508                         return true;
1509                 }
1510
1511                 // This is harder. Parse all the permissions and compare the resulting set.
1512                 $recipients1 = self::enumeratePermissions($obj1);
1513                 $recipients2 = self::enumeratePermissions($obj2);
1514                 sort($recipients1);
1515                 sort($recipients2);
1516
1517                 /// @TODO Comparison of arrays, maybe use array_diff_assoc() here?
1518                 return ($recipients1 == $recipients2);
1519         }
1520
1521         // returns an array of contact-ids that are allowed to see this object
1522         private static function enumeratePermissions($obj)
1523         {
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);
1531                 return $recipients;
1532         }
1533
1534         public static function getFeedTags($item)
1535         {
1536                 $ret = [];
1537                 $matches = false;
1538                 $cnt = preg_match_all('|\#\[url\=(.*?)\](.*?)\[\/url\]|', $item['tag'], $matches);
1539                 if ($cnt) {
1540                         for ($x = 0; $x < $cnt; $x ++) {
1541                                 if ($matches[1][$x]) {
1542                                         $ret[$matches[2][$x]] = ['#', $matches[1][$x], $matches[2][$x]];
1543                                 }
1544                         }
1545                 }
1546                 $matches = false;
1547                 $cnt = preg_match_all('|\@\[url\=(.*?)\](.*?)\[\/url\]|', $item['tag'], $matches);
1548                 if ($cnt) {
1549                         for ($x = 0; $x < $cnt; $x ++) {
1550                                 if ($matches[1][$x]) {
1551                                         $ret[] = ['@', $matches[1][$x], $matches[2][$x]];
1552                                 }
1553                         }
1554                 }
1555                 return $ret;
1556         }
1557
1558         public static function expire($uid, $days, $network = "", $force = false)
1559         {
1560                 if (!$uid || ($days < 1)) {
1561                         return;
1562                 }
1563
1564                 /*
1565                  * $expire_network_only = save your own wall posts
1566                  * and just expire conversations started by others
1567                  */
1568                 $expire_network_only = PConfig::get($uid,'expire', 'network_only');
1569                 $sql_extra = (intval($expire_network_only) ? " AND wall = 0 " : "");
1570
1571                 if ($network != "") {
1572                         $sql_extra .= sprintf(" AND network = '%s' ", dbesc($network));
1573
1574                         /*
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"
1578                          */
1579                         $range = "AND `received` < UTC_TIMESTAMP() - INTERVAL %d DAY ";
1580                 } else {
1581                         $range = "AND `created` < UTC_TIMESTAMP() - INTERVAL %d DAY ";
1582                 }
1583
1584                 $r = q("SELECT `file`, `resource-id`, `starred`, `type`, `id` FROM `item`
1585                         WHERE `uid` = %d $range
1586                         AND `id` = `parent`
1587                         $sql_extra
1588                         AND `deleted` = 0",
1589                         intval($uid),
1590                         intval($days)
1591                 );
1592
1593                 if (!DBM::is_result($r)) {
1594                         return;
1595                 }
1596
1597                 $expire_items = PConfig::get($uid, 'expire', 'items', 1);
1598
1599                 // Forcing expiring of items - but not notes and marked items
1600                 if ($force) {
1601                         $expire_items = true;
1602                 }
1603
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);
1607
1608                 logger('User '.$uid.': expire: # items=' . count($r). "; expire items: $expire_items, expire notes: $expire_notes, expire starred: $expire_starred, expire photos: $expire_photos");
1609
1610                 foreach ($r as $item) {
1611
1612                         // don't expire filed items
1613
1614                         if (strpos($item['file'],'[') !== false) {
1615                                 continue;
1616                         }
1617
1618                         // Only expire posts, not photos and photo comments
1619
1620                         if ($expire_photos == 0 && strlen($item['resource-id'])) {
1621                                 continue;
1622                         } elseif ($expire_starred == 0 && intval($item['starred'])) {
1623                                 continue;
1624                         } elseif ($expire_notes == 0 && $item['type'] == 'note') {
1625                                 continue;
1626                         } elseif ($expire_items == 0 && $item['type'] != 'note') {
1627                                 continue;
1628                         }
1629
1630                         self::delete($item['id'], PRIORITY_LOW);
1631                 }
1632         }
1633
1634         /// @TODO: This query seems to be really slow
1635         public static function firstPostDate($uid, $wall = false)
1636         {
1637                 $r = q("SELECT `id`, `created` FROM `item`
1638                         WHERE `uid` = %d AND `wall` = %d AND `deleted` = 0 AND `visible` = 1 AND `moderated` = 0
1639                         AND `id` = `parent`
1640                         ORDER BY `created` ASC LIMIT 1",
1641                         intval($uid),
1642                         intval($wall ? 1 : 0)
1643                 );
1644                 if (DBM::is_result($r)) {
1645                         return substr(datetime_convert('',date_default_timezone_get(), $r[0]['created']),0,10);
1646                 }
1647                 return false;
1648         }
1649
1650         /**
1651          * @brief add/remove activity to an item
1652          *
1653          * Toggle activities as like,dislike,attend of an item
1654          *
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'
1661          *              array $arr
1662          *                      'post_id' => ID of posted item
1663          */
1664         public static function performLike($item_id, $verb)
1665         {
1666                 if (!local_user() && !remote_user()) {
1667                         return false;
1668                 }
1669
1670                 switch ($verb) {
1671                         case 'like':
1672                         case 'unlike':
1673                                 $bodyverb = L10n::t('%1$s likes %2$s\'s %3$s');
1674                                 $activity = ACTIVITY_LIKE;
1675                                 break;
1676                         case 'dislike':
1677                         case 'undislike':
1678                                 $bodyverb = L10n::t('%1$s doesn\'t like %2$s\'s %3$s');
1679                                 $activity = ACTIVITY_DISLIKE;
1680                                 break;
1681                         case 'attendyes':
1682                         case 'unattendyes':
1683                                 $bodyverb = L10n::t('%1$s is attending %2$s\'s %3$s');
1684                                 $activity = ACTIVITY_ATTEND;
1685                                 break;
1686                         case 'attendno':
1687                         case 'unattendno':
1688                                 $bodyverb = L10n::t('%1$s is not attending %2$s\'s %3$s');
1689                                 $activity = ACTIVITY_ATTENDNO;
1690                                 break;
1691                         case 'attendmaybe':
1692                         case 'unattendmaybe':
1693                                 $bodyverb = L10n::t('%1$s may attend %2$s\'s %3$s');
1694                                 $activity = ACTIVITY_ATTENDMAYBE;
1695                                 break;
1696                         default:
1697                                 logger('like: unknown verb ' . $verb . ' for item ' . $item_id);
1698                                 return false;
1699                 }
1700
1701                 // Enable activity toggling instead of on/off
1702                 $event_verb_flag = $activity === ACTIVITY_ATTEND || $activity === ACTIVITY_ATTENDNO || $activity === ACTIVITY_ATTENDMAYBE;
1703
1704                 logger('like: verb ' . $verb . ' item ' . $item_id);
1705
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);
1709                         return false;
1710                 }
1711
1712                 $uid = $item['uid'];
1713                 if (($uid == 0) && local_user()) {
1714                         $uid = local_user();
1715                 }
1716
1717                 if (!can_write_wall($uid)) {
1718                         logger('like: unable to write on wall ' . $uid);
1719                         return false;
1720                 }
1721
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);
1726                         return false;
1727                 }
1728
1729                 // Retrieve the current logged in user's public contact
1730                 $author_id = public_contact();
1731
1732                 $author_contact = dba::selectFirst('contact', [], ['id' => $author_id]);
1733                 if (!DBM::is_result($author_contact)) {
1734                         logger('like: unknown author ' . $author_id);
1735                         return false;
1736                 }
1737
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;
1742                 } else {
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);
1747                                 return false;
1748                         }
1749                 }
1750
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) . "'";
1756                 } else {
1757                         $verbs = "'".dbesc($activity)."'";
1758                 }
1759
1760                 $existing_like = q("SELECT `id`, `guid`, `verb` FROM `item`
1761                         WHERE `verb` IN ($verbs)
1762                         AND `deleted` = 0
1763                         AND `author-id` = %d
1764                         AND `uid` = %d
1765                         AND (`parent` = '%s' OR `parent-uri` = '%s' OR `thr-parent` = '%s')
1766                         LIMIT 1",
1767                         intval($author_contact['id']),
1768                         intval($item['uid']),
1769                         dbesc($item_id), dbesc($item_id), dbesc($item['uri'])
1770                 );
1771
1772                 // If it exists, mark it as deleted
1773                 if (DBM::is_result($existing_like)) {
1774                         $like_item = $existing_like[0];
1775
1776                         // Already voted, undo it
1777                         $fields = ['deleted' => true, 'unseen' => true, 'changed' => datetime_convert()];
1778                         dba::update('item', $fields, ['id' => $like_item['id']]);
1779
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']]);
1784
1785                         $like_item_id = $like_item['id'];
1786                         Worker::add(PRIORITY_HIGH, "Notifier", "like", $like_item_id);
1787
1788                         if (!$event_verb_flag || $like_item['verb'] == $activity) {
1789                                 return true;
1790                         }
1791                 }
1792
1793                 // Verb is "un-something", just trying to delete existing entries
1794                 if (strpos($verb, 'un') === 0) {
1795                         return true;
1796                 }
1797
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');
1802                 }
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'];
1806
1807                 $obj = <<< EOT
1808
1809                 <object>
1810                         <type>$objtype</type>
1811                         <local>1</local>
1812                         <id>{$item['uri']}</id>
1813                         <link>$link</link>
1814                         <title></title>
1815                         <content>$body</content>
1816                 </object>
1817 EOT;
1818
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]';
1822
1823                 $new_item = [
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'],
1830                         'origin'        => 1,
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,
1846                         'object'        => $obj,
1847                         'allow_cid'     => $item['allow_cid'],
1848                         'allow_gid'     => $item['allow_gid'],
1849                         'deny_cid'      => $item['deny_cid'],
1850                         'deny_gid'      => $item['deny_gid'],
1851                         'visible'       => 1,
1852                         'unseen'        => 1,
1853                 ];
1854
1855                 $new_item_id = Item::insert($new_item);
1856
1857                 // @todo: Explain this block
1858                 if (! $item['visible']) {
1859                         q("UPDATE `item` SET `visible` = 1 WHERE `id` = %d",
1860                                 intval($item['id'])
1861                         );
1862                 }
1863
1864                 // Save the author information for the like in case we need to relay to Diaspora
1865                 Diaspora::storeLikeSignature($item_contact, $new_item_id);
1866
1867                 $new_item['id'] = $new_item_id;
1868
1869                 Addon::callHooks('post_local_end', $new_item);
1870
1871                 Worker::add(PRIORITY_HIGH, "Notifier", "like", $new_item_id);
1872
1873                 return true;
1874         }
1875 }