]> git.mxchange.org Git - friendica.git/blob - src/Model/Item.php
Merge pull request #4387 from MrPetovan/task/3878-move-datetime-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 Friendica\Util\DateTimeFormat;
26 use dba;
27 use Text_LanguageDetect;
28
29 require_once 'boot.php';
30 require_once 'include/tags.php';
31 require_once 'include/threads.php';
32 require_once 'include/items.php';
33 require_once 'include/text.php';
34
35 class Item extends BaseObject
36 {
37         /**
38          * @brief Update existing item entries
39          *
40          * @param array $fields The fields that are to be changed
41          * @param array $condition The condition for finding the item entries
42          *
43          * In the future we may have to change permissions as well.
44          * Then we had to add the user id as third parameter.
45          *
46          * A return value of "0" doesn't mean an error - but that 0 rows had been changed.
47          *
48          * @return integer|boolean number of affected rows - or "false" if there was an error
49          */
50         public static function update(array $fields, array $condition)
51         {
52                 if (empty($condition) || empty($fields)) {
53                         return false;
54                 }
55
56                 $success = dba::update('item', $fields, $condition);
57
58                 if (!$success) {
59                         return false;
60                 }
61
62                 $rows = dba::affected_rows();
63
64                 // We cannot simply expand the condition to check for origin entries
65                 // The condition needn't to be a simple array but could be a complex condition.
66                 $items = dba::select('item', ['id', 'origin'], $condition);
67                 while ($item = dba::fetch($items)) {
68                         // We only need to notfiy others when it is an original entry from us
69                         if (!$item['origin']) {
70                                 continue;
71                         }
72
73                         create_tags_from_item($item['id']);
74                         Term::createFromItem($item['id']);
75                         update_thread($item['id']);
76
77                         Worker::add(PRIORITY_HIGH, "Notifier", 'edit_post', $item['id']);
78                 }
79
80                 return $rows;
81         }
82
83         /**
84          * @brief Delete an item and notify others about it - if it was ours
85          *
86          * @param integer $item_id Item ID that should be delete
87          *
88          * @return $boolean success
89          */
90         public static function delete($item_id, $priority = PRIORITY_HIGH)
91         {
92                 // locate item to be deleted
93                 $fields = ['id', 'uid', 'parent', 'parent-uri', 'origin', 'deleted', 'file', 'resource-id', 'event-id', 'attach'];
94                 $item = dba::selectFirst('item', $fields, ['id' => $item_id]);
95                 if (!DBM::is_result($item)) {
96                         return false;
97                 }
98
99                 if ($item['deleted']) {
100                         return false;
101                 }
102
103                 $parent = dba::selectFirst('item', ['origin'], ['id' => $item['parent']]);
104                 if (!DBM::is_result($parent)) {
105                         $parent = ['origin' => false];
106                 }
107
108                 logger('delete item: ' . $item['id'], LOGGER_DEBUG);
109
110                 // clean up categories and tags so they don't end up as orphans
111
112                 $matches = false;
113                 $cnt = preg_match_all('/<(.*?)>/', $item['file'], $matches, PREG_SET_ORDER);
114                 if ($cnt) {
115                         foreach ($matches as $mtch) {
116                                 file_tag_unsave_file($item['uid'], $item['id'], $mtch[1],true);
117                         }
118                 }
119
120                 $matches = false;
121
122                 $cnt = preg_match_all('/\[(.*?)\]/', $item['file'], $matches, PREG_SET_ORDER);
123                 if ($cnt) {
124                         foreach ($matches as $mtch) {
125                                 file_tag_unsave_file($item['uid'], $item['id'], $mtch[1],false);
126                         }
127                 }
128
129                 /*
130                  * If item is a link to a photo resource, nuke all the associated photos
131                  * (visitors will not have photo resources)
132                  * This only applies to photos uploaded from the photos page. Photos inserted into a post do not
133                  * generate a resource-id and therefore aren't intimately linked to the item.
134                  */
135                 if (strlen($item['resource-id'])) {
136                         dba::delete('photo', ['resource-id' => $item['resource-id'], 'uid' => $item['uid']]);
137                 }
138
139                 // If item is a link to an event, nuke the event record.
140                 if (intval($item['event-id'])) {
141                         dba::delete('event', ['id' => $item['event-id'], 'uid' => $item['uid']]);
142                 }
143
144                 // If item has attachments, drop them
145                 foreach (explode(", ", $item['attach']) as $attach) {
146                         preg_match("|attach/(\d+)|", $attach, $matches);
147                         dba::delete('attach', ['id' => $matches[1], 'uid' => $item['uid']]);
148                 }
149
150                 // Set the item to "deleted"
151                 dba::update('item', ['deleted' => true, 'title' => '', 'body' => '',
152                                         'edited' => DateTimeFormat::utcNow(), 'changed' => DateTimeFormat::utcNow()],
153                                 ['id' => $item['id']]);
154
155                 create_tags_from_item($item['id']);
156                 Term::createFromItem($item['id']);
157                 delete_thread($item['id'], $item['parent-uri']);
158
159                 // If it's the parent of a comment thread, kill all the kids
160                 if ($item['id'] == $item['parent']) {
161                         $items = dba::select('item', ['id'], ['parent' => $item['parent']]);
162                         while ($row = dba::fetch($items)) {
163                                 self::delete($row['id'], $priority);
164                         }
165                 }
166
167                 // send the notification upstream/downstream
168                 if ($item['origin'] || $parent['origin']) {
169                         Worker::add(['priority' => $priority, 'dont_fork' => true], "Notifier", "drop", intval($item['id']));
170                 }
171
172                 return true;
173         }
174
175         public static function insert($arr, $force_parent = false, $notify = false, $dontcache = false)
176         {
177                 $a = get_app();
178
179                 // If it is a posting where users should get notifications, then define it as wall posting
180                 if ($notify) {
181                         $arr['wall'] = 1;
182                         $arr['type'] = 'wall';
183                         $arr['origin'] = 1;
184                         $arr['network'] = NETWORK_DFRN;
185                         $arr['protocol'] = PROTOCOL_DFRN;
186
187                         // We have to avoid duplicates. So we create the GUID in form of a hash of the plink or uri.
188                         // In difference to the call to "self::guidFromUri" several lines below we add the hash of our own host.
189                         // This is done because our host is the original creator of the post.
190                         if (!isset($arr['guid'])) {
191                                 if (isset($arr['plink'])) {
192                                         $arr['guid'] = self::guidFromUri($arr['plink'], $a->get_hostname());
193                                 } elseif (isset($arr['uri'])) {
194                                         $arr['guid'] = self::guidFromUri($arr['uri'], $a->get_hostname());
195                                 }
196                         }
197                 } else {
198                         $arr['network'] = trim(defaults($arr, 'network', NETWORK_PHANTOM));
199                 }
200
201                 if ($notify) {
202                         $guid_prefix = "";
203                 } elseif ((trim($arr['guid']) == "") && (trim($arr['plink']) != "")) {
204                         $arr['guid'] = self::guidFromUri($arr['plink']);
205                 } elseif ((trim($arr['guid']) == "") && (trim($arr['uri']) != "")) {
206                         $arr['guid'] = self::guidFromUri($arr['uri']);
207                 } else {
208                         $parsed = parse_url($arr["author-link"]);
209                         $guid_prefix = hash("crc32", $parsed["host"]);
210                 }
211
212                 $arr['guid'] = notags(trim(defaults($arr, 'guid', get_guid(32, $guid_prefix))));
213                 $arr['uri'] = notags(trim(defaults($arr, 'uri', item_new_uri($a->get_hostname(), $uid, $arr['guid']))));
214
215                 // Store conversation data
216                 $arr = Conversation::insert($arr);
217
218                 /*
219                  * If a Diaspora signature structure was passed in, pull it out of the
220                  * item array and set it aside for later storage.
221                  */
222
223                 $dsprsig = null;
224                 if (x($arr, 'dsprsig')) {
225                         $encoded_signature = $arr['dsprsig'];
226                         $dsprsig = json_decode(base64_decode($arr['dsprsig']));
227                         unset($arr['dsprsig']);
228                 }
229
230                 // Converting the plink
231                 /// @TODO Check if this is really still needed
232                 if ($arr['network'] == NETWORK_OSTATUS) {
233                         if (isset($arr['plink'])) {
234                                 $arr['plink'] = OStatus::convertHref($arr['plink']);
235                         } elseif (isset($arr['uri'])) {
236                                 $arr['plink'] = OStatus::convertHref($arr['uri']);
237                         }
238                 }
239
240                 if (x($arr, 'gravity')) {
241                         $arr['gravity'] = intval($arr['gravity']);
242                 } elseif ($arr['parent-uri'] === $arr['uri']) {
243                         $arr['gravity'] = 0;
244                 } elseif (activity_match($arr['verb'],ACTIVITY_POST)) {
245                         $arr['gravity'] = 6;
246                 } else {
247                         $arr['gravity'] = 6;   // extensible catchall
248                 }
249
250                 $arr['type'] = defaults($arr, 'type', 'remote');
251
252                 $uid = intval($arr['uid']);
253
254                 // check for create date and expire time
255                 $expire_interval = Config::get('system', 'dbclean-expire-days', 0);
256
257                 $user = dba::selectFirst('user', ['expire'], ['uid' => $uid]);
258                 if (DBM::is_result($user) && ($user['expire'] > 0) && (($user['expire'] < $expire_interval) || ($expire_interval == 0))) {
259                         $expire_interval = $user['expire'];
260                 }
261
262                 if (($expire_interval > 0) && !empty($arr['created'])) {
263                         $expire_date = time() - ($expire_interval * 86400);
264                         $created_date = strtotime($arr['created']);
265                         if ($created_date < $expire_date) {
266                                 logger('item-store: item created ('.date('c', $created_date).') before expiration time ('.date('c', $expire_date).'). ignored. ' . print_r($arr,true), LOGGER_DEBUG);
267                                 return 0;
268                         }
269                 }
270
271                 /*
272                  * Do we already have this item?
273                  * We have to check several networks since Friendica posts could be repeated
274                  * via OStatus (maybe Diasporsa as well)
275                  */
276                 if (in_array($arr['network'], [NETWORK_DIASPORA, NETWORK_DFRN, NETWORK_OSTATUS, ""])) {
277                         $r = q("SELECT `id`, `network` FROM `item` WHERE `uri` = '%s' AND `uid` = %d AND `network` IN ('%s', '%s', '%s')  LIMIT 1",
278                                         dbesc(trim($arr['uri'])),
279                                         intval($uid),
280                                         dbesc(NETWORK_DIASPORA),
281                                         dbesc(NETWORK_DFRN),
282                                         dbesc(NETWORK_OSTATUS)
283                                 );
284                         if (DBM::is_result($r)) {
285                                 // We only log the entries with a different user id than 0. Otherwise we would have too many false positives
286                                 if ($uid != 0) {
287                                         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']);
288                                 }
289
290                                 return $r[0]["id"];
291                         }
292                 }
293
294                 self::addLanguageInPostopts($arr);
295
296                 $arr['wall']          = intval(defaults($arr, 'wall', 0));
297                 $arr['extid']         = trim(defaults($arr, 'extid', ''));
298                 $arr['author-name']   = trim(defaults($arr, 'author-name', ''));
299                 $arr['author-link']   = trim(defaults($arr, 'author-link', ''));
300                 $arr['author-avatar'] = trim(defaults($arr, 'author-avatar', ''));
301                 $arr['owner-name']    = trim(defaults($arr, 'owner-name', ''));
302                 $arr['owner-link']    = trim(defaults($arr, 'owner-link', ''));
303                 $arr['owner-avatar']  = trim(defaults($arr, 'owner-avatar', ''));
304                 $arr['received']      = ((x($arr, 'received') !== false) ? DateTimeFormat::utc($arr['received']) : DateTimeFormat::utcNow());
305                 $arr['created']       = ((x($arr, 'created') !== false) ? DateTimeFormat::utc($arr['created']) : $arr['received']);
306                 $arr['edited']        = ((x($arr, 'edited') !== false) ? DateTimeFormat::utc($arr['edited']) : $arr['created']);
307                 $arr['changed']       = ((x($arr, 'changed') !== false) ? DateTimeFormat::utc($arr['changed']) : $arr['created']);
308                 $arr['commented']     = ((x($arr, 'commented') !== false) ? DateTimeFormat::utc($arr['commented']) : $arr['created']);
309                 $arr['title']         = trim(defaults($arr, 'title', ''));
310                 $arr['location']      = trim(defaults($arr, 'location', ''));
311                 $arr['coord']         = trim(defaults($arr, 'coord', ''));
312                 $arr['visible']       = ((x($arr, 'visible') !== false) ? intval($arr['visible'])         : 1);
313                 $arr['deleted']       = 0;
314                 $arr['parent-uri']    = trim(defaults($arr, 'parent-uri', $arr['uri']));
315                 $arr['verb']          = trim(defaults($arr, 'verb', ''));
316                 $arr['object-type']   = trim(defaults($arr, 'object-type', ''));
317                 $arr['object']        = trim(defaults($arr, 'object', ''));
318                 $arr['target-type']   = trim(defaults($arr, 'target-type', ''));
319                 $arr['target']        = trim(defaults($arr, 'target', ''));
320                 $arr['plink']         = trim(defaults($arr, 'plink', ''));
321                 $arr['allow_cid']     = trim(defaults($arr, 'allow_cid', ''));
322                 $arr['allow_gid']     = trim(defaults($arr, 'allow_gid', ''));
323                 $arr['deny_cid']      = trim(defaults($arr, 'deny_cid', ''));
324                 $arr['deny_gid']      = trim(defaults($arr, 'deny_gid', ''));
325                 $arr['private']       = intval(defaults($arr, 'private', 0));
326                 $arr['bookmark']      = intval(defaults($arr, 'bookmark', 0));
327                 $arr['body']          = trim(defaults($arr, 'body', ''));
328                 $arr['tag']           = trim(defaults($arr, 'tag', ''));
329                 $arr['attach']        = trim(defaults($arr, 'attach', ''));
330                 $arr['app']           = trim(defaults($arr, 'app', ''));
331                 $arr['origin']        = intval(defaults($arr, 'origin', 0));
332                 $arr['postopts']      = trim(defaults($arr, 'postopts', ''));
333                 $arr['resource-id']   = trim(defaults($arr, 'resource-id', ''));
334                 $arr['event-id']      = intval(defaults($arr, 'event-id', 0));
335                 $arr['inform']        = trim(defaults($arr, 'inform', ''));
336                 $arr['file']          = trim(defaults($arr, 'file', ''));
337
338                 // When there is no content then we don't post it
339                 if ($arr['body'].$arr['title'] == '') {
340                         return 0;
341                 }
342
343                 // Items cannot be stored before they happen ...
344                 if ($arr['created'] > DateTimeFormat::utcNow()) {
345                         $arr['created'] = DateTimeFormat::utcNow();
346                 }
347
348                 // We haven't invented time travel by now.
349                 if ($arr['edited'] > DateTimeFormat::utcNow()) {
350                         $arr['edited'] = DateTimeFormat::utcNow();
351                 }
352
353                 if (($arr['author-link'] == "") && ($arr['owner-link'] == "")) {
354                         logger("Both author-link and owner-link are empty. Called by: " . System::callstack(), LOGGER_DEBUG);
355                 }
356
357                 if ($arr['plink'] == "") {
358                         $arr['plink'] = System::baseUrl() . '/display/' . urlencode($arr['guid']);
359                 }
360
361                 if ($arr['network'] == NETWORK_PHANTOM) {
362                         $r = q("SELECT `network` FROM `contact` WHERE `network` IN ('%s', '%s', '%s') AND `nurl` = '%s' AND `uid` = %d LIMIT 1",
363                                 dbesc(NETWORK_DFRN), dbesc(NETWORK_DIASPORA), dbesc(NETWORK_OSTATUS),
364                                 dbesc(normalise_link($arr['author-link'])),
365                                 intval($arr['uid'])
366                         );
367
368                         if (!DBM::is_result($r)) {
369                                 $r = q("SELECT `network` FROM `gcontact` WHERE `network` IN ('%s', '%s', '%s') AND `nurl` = '%s' LIMIT 1",
370                                         dbesc(NETWORK_DFRN), dbesc(NETWORK_DIASPORA), dbesc(NETWORK_OSTATUS),
371                                         dbesc(normalise_link($arr['author-link']))
372                                 );
373                         }
374
375                         if (!DBM::is_result($r)) {
376                                 $r = q("SELECT `network` FROM `contact` WHERE `id` = %d AND `uid` = %d LIMIT 1",
377                                         intval($arr['contact-id']),
378                                         intval($arr['uid'])
379                                 );
380                         }
381
382                         if (DBM::is_result($r)) {
383                                 $arr['network'] = $r[0]["network"];
384                         }
385
386                         // Fallback to friendica (why is it empty in some cases?)
387                         if ($arr['network'] == "") {
388                                 $arr['network'] = NETWORK_DFRN;
389                         }
390
391                         logger("Set network to " . $arr["network"] . " for " . $arr["uri"], LOGGER_DEBUG);
392                 }
393
394                 // The contact-id should be set before "self::insert" was called - but there seems to be some issues
395                 if ($arr["contact-id"] == 0) {
396                         /*
397                          * First we are looking for a suitable contact that matches with the author of the post
398                          * This is done only for comments (See below explanation at "gcontact-id")
399                          */
400                         if ($arr['parent-uri'] != $arr['uri']) {
401                                 $arr["contact-id"] = Contact::getIdForURL($arr['author-link'], $uid);
402                         }
403
404                         // If not present then maybe the owner was found
405                         if ($arr["contact-id"] == 0) {
406                                 $arr["contact-id"] = Contact::getIdForURL($arr['owner-link'], $uid);
407                         }
408
409                         // Still missing? Then use the "self" contact of the current user
410                         if ($arr["contact-id"] == 0) {
411                                 $r = q("SELECT `id` FROM `contact` WHERE `self` AND `uid` = %d", intval($uid));
412
413                                 if (DBM::is_result($r)) {
414                                         $arr["contact-id"] = $r[0]["id"];
415                                 }
416                         }
417
418                         logger("Contact-id was missing for post ".$arr["guid"]." from user id ".$uid." - now set to ".$arr["contact-id"], LOGGER_DEBUG);
419                 }
420
421                 if (!x($arr, "gcontact-id")) {
422                         /*
423                          * The gcontact should mostly behave like the contact. But is is supposed to be global for the system.
424                          * This means that wall posts, repeated posts, etc. should have the gcontact id of the owner.
425                          * On comments the author is the better choice.
426                          */
427                         if ($arr['parent-uri'] === $arr['uri']) {
428                                 $arr["gcontact-id"] = GContact::getId(["url" => $arr['owner-link'], "network" => $arr['network'],
429                                                                          "photo" => $arr['owner-avatar'], "name" => $arr['owner-name']]);
430                         } else {
431                                 $arr["gcontact-id"] = GContact::getId(["url" => $arr['author-link'], "network" => $arr['network'],
432                                                                          "photo" => $arr['author-avatar'], "name" => $arr['author-name']]);
433                         }
434                 }
435
436                 if ($arr["author-id"] == 0) {
437                         $arr["author-id"] = Contact::getIdForURL($arr["author-link"], 0);
438                 }
439
440                 if (Contact::isBlocked($arr["author-id"])) {
441                         logger('Contact '.$arr["author-id"].' is blocked, item '.$arr["uri"].' will not be stored');
442                         return 0;
443                 }
444
445                 if ($arr["owner-id"] == 0) {
446                         $arr["owner-id"] = Contact::getIdForURL($arr["owner-link"], 0);
447                 }
448
449                 if (Contact::isBlocked($arr["owner-id"])) {
450                         logger('Contact '.$arr["owner-id"].' is blocked, item '.$arr["uri"].' will not be stored');
451                         return 0;
452                 }
453
454                 if ($arr['guid'] != "") {
455                         // Checking if there is already an item with the same guid
456                         logger('checking for an item for user '.$arr['uid'].' on network '.$arr['network'].' with the guid '.$arr['guid'], LOGGER_DEBUG);
457                         $r = q("SELECT `guid` FROM `item` WHERE `guid` = '%s' AND `network` = '%s' AND `uid` = '%d' LIMIT 1",
458                                 dbesc($arr['guid']), dbesc($arr['network']), intval($arr['uid']));
459
460                         if (DBM::is_result($r)) {
461                                 logger('found item with guid '.$arr['guid'].' for user '.$arr['uid'].' on network '.$arr['network'], LOGGER_DEBUG);
462                                 return 0;
463                         }
464                 }
465
466                 // Check for hashtags in the body and repair or add hashtag links
467                 self::setHashtags($arr);
468
469                 $arr['thr-parent'] = $arr['parent-uri'];
470
471                 if ($arr['parent-uri'] === $arr['uri']) {
472                         $parent_id = 0;
473                         $parent_deleted = 0;
474                         $allow_cid = $arr['allow_cid'];
475                         $allow_gid = $arr['allow_gid'];
476                         $deny_cid  = $arr['deny_cid'];
477                         $deny_gid  = $arr['deny_gid'];
478                         $notify_type = 'wall-new';
479                 } else {
480
481                         // find the parent and snarf the item id and ACLs
482                         // and anything else we need to inherit
483
484                         $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d ORDER BY `id` ASC LIMIT 1",
485                                 dbesc($arr['parent-uri']),
486                                 intval($arr['uid'])
487                         );
488
489                         if (DBM::is_result($r)) {
490
491                                 // is the new message multi-level threaded?
492                                 // even though we don't support it now, preserve the info
493                                 // and re-attach to the conversation parent.
494
495                                 if ($r[0]['uri'] != $r[0]['parent-uri']) {
496                                         $arr['parent-uri'] = $r[0]['parent-uri'];
497                                         $z = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `parent-uri` = '%s' AND `uid` = %d
498                                                 ORDER BY `id` ASC LIMIT 1",
499                                                 dbesc($r[0]['parent-uri']),
500                                                 dbesc($r[0]['parent-uri']),
501                                                 intval($arr['uid'])
502                                         );
503
504                                         if (DBM::is_result($z)) {
505                                                 $r = $z;
506                                         }
507                                 }
508
509                                 $parent_id      = $r[0]['id'];
510                                 $parent_deleted = $r[0]['deleted'];
511                                 $allow_cid      = $r[0]['allow_cid'];
512                                 $allow_gid      = $r[0]['allow_gid'];
513                                 $deny_cid       = $r[0]['deny_cid'];
514                                 $deny_gid       = $r[0]['deny_gid'];
515                                 $arr['wall']    = $r[0]['wall'];
516                                 $notify_type    = 'comment-new';
517
518                                 /*
519                                  * If the parent is private, force privacy for the entire conversation
520                                  * This differs from the above settings as it subtly allows comments from
521                                  * email correspondents to be private even if the overall thread is not.
522                                  */
523                                 if ($r[0]['private']) {
524                                         $arr['private'] = $r[0]['private'];
525                                 }
526
527                                 /*
528                                  * Edge case. We host a public forum that was originally posted to privately.
529                                  * The original author commented, but as this is a comment, the permissions
530                                  * weren't fixed up so it will still show the comment as private unless we fix it here.
531                                  */
532                                 if ((intval($r[0]['forum_mode']) == 1) && $r[0]['private']) {
533                                         $arr['private'] = 0;
534                                 }
535
536                                 // If its a post from myself then tag the thread as "mention"
537                                 logger("Checking if parent ".$parent_id." has to be tagged as mention for user ".$arr['uid'], LOGGER_DEBUG);
538                                 $u = q("SELECT `nickname` FROM `user` WHERE `uid` = %d", intval($arr['uid']));
539                                 if (DBM::is_result($u)) {
540                                         $self = normalise_link(System::baseUrl() . '/profile/' . $u[0]['nickname']);
541                                         logger("'myself' is ".$self." for parent ".$parent_id." checking against ".$arr['author-link']." and ".$arr['owner-link'], LOGGER_DEBUG);
542                                         if ((normalise_link($arr['author-link']) == $self) || (normalise_link($arr['owner-link']) == $self)) {
543                                                 dba::update('thread', ['mention' => true], ['iid' => $parent_id]);
544                                                 logger("tagged thread ".$parent_id." as mention for user ".$self, LOGGER_DEBUG);
545                                         }
546                                 }
547                         } else {
548                                 /*
549                                  * Allow one to see reply tweets from status.net even when
550                                  * we don't have or can't see the original post.
551                                  */
552                                 if ($force_parent) {
553                                         logger('$force_parent=true, reply converted to top-level post.');
554                                         $parent_id = 0;
555                                         $arr['parent-uri'] = $arr['uri'];
556                                         $arr['gravity'] = 0;
557                                 } else {
558                                         logger('item parent '.$arr['parent-uri'].' for '.$arr['uid'].' was not found - ignoring item');
559                                         return 0;
560                                 }
561
562                                 $parent_deleted = 0;
563                         }
564                 }
565
566                 $r = q("SELECT `id` FROM `item` WHERE `uri` = '%s' AND `network` IN ('%s', '%s') AND `uid` = %d LIMIT 1",
567                         dbesc($arr['uri']),
568                         dbesc($arr['network']),
569                         dbesc(NETWORK_DFRN),
570                         intval($arr['uid'])
571                 );
572                 if (DBM::is_result($r)) {
573                         logger('duplicated item with the same uri found. '.print_r($arr,true));
574                         return 0;
575                 }
576
577                 // On Friendica and Diaspora the GUID is unique
578                 if (in_array($arr['network'], [NETWORK_DFRN, NETWORK_DIASPORA])) {
579                         $r = q("SELECT `id` FROM `item` WHERE `guid` = '%s' AND `uid` = %d LIMIT 1",
580                                 dbesc($arr['guid']),
581                                 intval($arr['uid'])
582                         );
583                         if (DBM::is_result($r)) {
584                                 logger('duplicated item with the same guid found. '.print_r($arr,true));
585                                 return 0;
586                         }
587                 } else {
588                         // Check for an existing post with the same content. There seems to be a problem with OStatus.
589                         $r = q("SELECT `id` FROM `item` WHERE `body` = '%s' AND `network` = '%s' AND `created` = '%s' AND `contact-id` = %d AND `uid` = %d LIMIT 1",
590                                 dbesc($arr['body']),
591                                 dbesc($arr['network']),
592                                 dbesc($arr['created']),
593                                 intval($arr['contact-id']),
594                                 intval($arr['uid'])
595                         );
596                         if (DBM::is_result($r)) {
597                                 logger('duplicated item with the same body found. '.print_r($arr,true));
598                                 return 0;
599                         }
600                 }
601
602                 // Is this item available in the global items (with uid=0)?
603                 if ($arr["uid"] == 0) {
604                         $arr["global"] = true;
605
606                         // Set the global flag on all items if this was a global item entry
607                         dba::update('item', ['global' => true], ['uri' => $arr["uri"]]);
608                 } else {
609                         $isglobal = q("SELECT `global` FROM `item` WHERE `uid` = 0 AND `uri` = '%s'", dbesc($arr["uri"]));
610
611                         $arr["global"] = (DBM::is_result($isglobal) && count($isglobal) > 0);
612                 }
613
614                 // ACL settings
615                 if (strlen($allow_cid) || strlen($allow_gid) || strlen($deny_cid) || strlen($deny_gid)) {
616                         $private = 1;
617                 } else {
618                         $private = $arr['private'];
619                 }
620
621                 $arr["allow_cid"] = $allow_cid;
622                 $arr["allow_gid"] = $allow_gid;
623                 $arr["deny_cid"] = $deny_cid;
624                 $arr["deny_gid"] = $deny_gid;
625                 $arr["private"] = $private;
626                 $arr["deleted"] = $parent_deleted;
627
628                 // Fill the cache field
629                 put_item_in_cache($arr);
630
631                 if ($notify) {
632                         Addon::callHooks('post_local', $arr);
633                 } else {
634                         Addon::callHooks('post_remote', $arr);
635                 }
636
637                 // This array field is used to trigger some automatic reactions
638                 // It is mainly used in the "post_local" hook.
639                 unset($arr['api_source']);
640
641                 if (x($arr, 'cancel')) {
642                         logger('post cancelled by addon.');
643                         return 0;
644                 }
645
646                 /*
647                  * Check for already added items.
648                  * There is a timing issue here that sometimes creates double postings.
649                  * An unique index would help - but the limitations of MySQL (maximum size of index values) prevent this.
650                  */
651                 if ($arr["uid"] == 0) {
652                         $r = q("SELECT `id` FROM `item` WHERE `uri` = '%s' AND `uid` = 0 LIMIT 1", dbesc(trim($arr['uri'])));
653                         if (DBM::is_result($r)) {
654                                 logger('Global item already stored. URI: '.$arr['uri'].' on network '.$arr['network'], LOGGER_DEBUG);
655                                 return 0;
656                         }
657                 }
658
659                 logger('' . print_r($arr,true), LOGGER_DATA);
660
661                 dba::transaction();
662                 $r = dba::insert('item', $arr);
663
664                 // When the item was successfully stored we fetch the ID of the item.
665                 if (DBM::is_result($r)) {
666                         $current_post = dba::lastInsertId();
667                 } else {
668                         // This can happen - for example - if there are locking timeouts.
669                         dba::rollback();
670
671                         // Store the data into a spool file so that we can try again later.
672
673                         // At first we restore the Diaspora signature that we removed above.
674                         if (isset($encoded_signature)) {
675                                 $arr['dsprsig'] = $encoded_signature;
676                         }
677
678                         // Now we store the data in the spool directory
679                         // We use "microtime" to keep the arrival order and "mt_rand" to avoid duplicates
680                         $file = 'item-'.round(microtime(true) * 10000).'-'.mt_rand().'.msg';
681
682                         $spoolpath = get_spoolpath();
683                         if ($spoolpath != "") {
684                                 $spool = $spoolpath.'/'.$file;
685                                 file_put_contents($spool, json_encode($arr));
686                                 logger("Item wasn't stored - Item was spooled into file ".$file, LOGGER_DEBUG);
687                         }
688                         return 0;
689                 }
690
691                 if ($current_post == 0) {
692                         // This is one of these error messages that never should occur.
693                         logger("couldn't find created item - we better quit now.");
694                         dba::rollback();
695                         return 0;
696                 }
697
698                 // How much entries have we created?
699                 // We wouldn't need this query when we could use an unique index - but MySQL has length problems with them.
700                 $r = q("SELECT COUNT(*) AS `entries` FROM `item` WHERE `uri` = '%s' AND `uid` = %d AND `network` = '%s'",
701                         dbesc($arr['uri']),
702                         intval($arr['uid']),
703                         dbesc($arr['network'])
704                 );
705
706                 if (!DBM::is_result($r)) {
707                         // This shouldn't happen, since COUNT always works when the database connection is there.
708                         logger("We couldn't count the stored entries. Very strange ...");
709                         dba::rollback();
710                         return 0;
711                 }
712
713                 if ($r[0]["entries"] > 1) {
714                         // There are duplicates. We delete our just created entry.
715                         logger('Duplicated post occurred. uri = ' . $arr['uri'] . ' uid = ' . $arr['uid']);
716
717                         // Yes, we could do a rollback here - but we are having many users with MyISAM.
718                         dba::delete('item', ['id' => $current_post]);
719                         dba::commit();
720                         return 0;
721                 } elseif ($r[0]["entries"] == 0) {
722                         // This really should never happen since we quit earlier if there were problems.
723                         logger("Something is terribly wrong. We haven't found our created entry.");
724                         dba::rollback();
725                         return 0;
726                 }
727
728                 logger('created item '.$current_post);
729                 self::updateContact($arr);
730
731                 if (!$parent_id || ($arr['parent-uri'] === $arr['uri'])) {
732                         $parent_id = $current_post;
733                 }
734
735                 // Set parent id
736                 dba::update('item', ['parent' => $parent_id], ['id' => $current_post]);
737
738                 $arr['id'] = $current_post;
739                 $arr['parent'] = $parent_id;
740
741                 // update the commented timestamp on the parent
742                 // Only update "commented" if it is really a comment
743                 if (($arr['verb'] == ACTIVITY_POST) || !Config::get("system", "like_no_comment")) {
744                         dba::update('item', ['commented' => DateTimeFormat::utcNow(), 'changed' => DateTimeFormat::utcNow()], ['id' => $parent_id]);
745                 } else {
746                         dba::update('item', ['changed' => DateTimeFormat::utcNow()], ['id' => $parent_id]);
747                 }
748
749                 if ($dsprsig) {
750                         /*
751                          * Friendica servers lower than 3.4.3-2 had double encoded the signature ...
752                          * We can check for this condition when we decode and encode the stuff again.
753                          */
754                         if (base64_encode(base64_decode(base64_decode($dsprsig->signature))) == base64_decode($dsprsig->signature)) {
755                                 $dsprsig->signature = base64_decode($dsprsig->signature);
756                                 logger("Repaired double encoded signature from handle ".$dsprsig->signer, LOGGER_DEBUG);
757                         }
758
759                         dba::insert('sign', ['iid' => $current_post, 'signed_text' => $dsprsig->signed_text,
760                                                 'signature' => $dsprsig->signature, 'signer' => $dsprsig->signer]);
761                 }
762
763                 $deleted = self::tagDeliver($arr['uid'], $current_post);
764
765                 /*
766                  * current post can be deleted if is for a community page and no mention are
767                  * in it.
768                  */
769                 if (!$deleted && !$dontcache) {
770                         $r = q('SELECT * FROM `item` WHERE `id` = %d', intval($current_post));
771                         if (DBM::is_result($r) && (count($r) == 1)) {
772                                 if ($notify) {
773                                         Addon::callHooks('post_local_end', $r[0]);
774                                 } else {
775                                         Addon::callHooks('post_remote_end', $r[0]);
776                                 }
777                         } else {
778                                 logger('new item not found in DB, id ' . $current_post);
779                         }
780                 }
781
782                 if ($arr['parent-uri'] === $arr['uri']) {
783                         add_thread($current_post);
784                 } else {
785                         update_thread($parent_id);
786                 }
787
788                 dba::commit();
789
790                 /*
791                  * Due to deadlock issues with the "term" table we are doing these steps after the commit.
792                  * This is not perfect - but a workable solution until we found the reason for the problem.
793                  */
794                 create_tags_from_item($current_post);
795                 Term::createFromItem($current_post);
796
797                 if ($arr['parent-uri'] === $arr['uri']) {
798                         self::addShadow($current_post);
799                 } else {
800                         self::addShadowPost($current_post);
801                 }
802
803                 check_user_notification($current_post);
804
805                 if ($notify) {
806                         Worker::add(['priority' => PRIORITY_HIGH, 'dont_fork' => true], "Notifier", $notify_type, $current_post);
807                 }
808
809                 return $current_post;
810         }
811
812         /**
813          * @brief Add a shadow entry for a given item id that is a thread starter
814          *
815          * We store every public item entry additionally with the user id "0".
816          * This is used for the community page and for the search.
817          * It is planned that in the future we will store public item entries only once.
818          *
819          * @param integer $itemid Item ID that should be added
820          */
821         public static function addShadow($itemid)
822         {
823                 $fields = ['uid', 'wall', 'private', 'moderated', 'visible', 'contact-id', 'deleted', 'network', 'author-id', 'owner-id'];
824                 $condition = ["`id` = ? AND (`parent` = ? OR `parent` = 0)", $itemid, $itemid];
825                 $item = dba::selectFirst('item', $fields, $condition);
826
827                 if (!DBM::is_result($item)) {
828                         return;
829                 }
830
831                 // is it already a copy?
832                 if (($itemid == 0) || ($item['uid'] == 0)) {
833                         return;
834                 }
835
836                 // Is it a visible public post?
837                 if (!$item["visible"] || $item["deleted"] || $item["moderated"] || $item["private"]) {
838                         return;
839                 }
840
841                 // is it an entry from a connector? Only add an entry for natively connected networks
842                 if (!in_array($item["network"], [NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, ""])) {
843                         return;
844                 }
845
846                 // Is the public contact configured as hidden?
847                 if (Contact::isHidden($item["owner-id"]) || Contact::isHidden($item["author-id"])) {
848                         return;
849                 }
850
851                 // Only do these checks if the post isn't a wall post
852                 if (!$item["wall"]) {
853                         // Check, if hide-friends is activated - then don't do a shadow entry
854                         if (dba::exists('profile', ['is-default' => true, 'uid' => $item['uid'], 'hide-friends' => true])) {
855                                 return;
856                         }
857
858                         // Check if the contact is hidden or blocked
859                         if (!dba::exists('contact', ['hidden' => false, 'blocked' => false, 'id' => $item['contact-id']])) {
860                                 return;
861                         }
862                 }
863
864                 // Only add a shadow, if the profile isn't hidden
865                 if (dba::exists('user', ['uid' => $item['uid'], 'hidewall' => true])) {
866                         return;
867                 }
868
869                 $item = dba::selectFirst('item', [], ['id' => $itemid]);
870
871                 if (DBM::is_result($item) && ($item["allow_cid"] == '')  && ($item["allow_gid"] == '') &&
872                         ($item["deny_cid"] == '') && ($item["deny_gid"] == '')) {
873
874                         if (!dba::exists('item', ['uri' => $item['uri'], 'uid' => 0])) {
875                                 // Preparing public shadow (removing user specific data)
876                                 unset($item['id']);
877                                 $item['uid'] = 0;
878                                 $item['origin'] = 0;
879                                 $item['wall'] = 0;
880                                 $item['contact-id'] = Contact::getIdForURL($item['author-link'], 0);
881
882                                 if (in_array($item['type'], ["net-comment", "wall-comment"])) {
883                                         $item['type'] = 'remote-comment';
884                                 } elseif ($item['type'] == 'wall') {
885                                         $item['type'] = 'remote';
886                                 }
887
888                                 $public_shadow = self::insert($item, false, false, true);
889
890                                 logger("Stored public shadow for thread ".$itemid." under id ".$public_shadow, LOGGER_DEBUG);
891                         }
892                 }
893         }
894
895         /**
896          * @brief Add a shadow entry for a given item id that is a comment
897          *
898          * This function does the same like the function above - but for comments
899          *
900          * @param integer $itemid Item ID that should be added
901          */
902         public static function addShadowPost($itemid)
903         {
904                 $item = dba::selectFirst('item', [], ['id' => $itemid]);
905                 if (!DBM::is_result($item)) {
906                         return;
907                 }
908
909                 // Is it a toplevel post?
910                 if ($item['id'] == $item['parent']) {
911                         self::addShadow($itemid);
912                         return;
913                 }
914
915                 // Is this a shadow entry?
916                 if ($item['uid'] == 0)
917                         return;
918
919                 // Is there a shadow parent?
920                 if (!dba::exists('item', ['uri' => $item['parent-uri'], 'uid' => 0])) {
921                         return;
922                 }
923
924                 // Is there already a shadow entry?
925                 if (dba::exists('item', ['uri' => $item['uri'], 'uid' => 0])) {
926                         return;
927                 }
928
929                 // Preparing public shadow (removing user specific data)
930                 unset($item['id']);
931                 $item['uid'] = 0;
932                 $item['origin'] = 0;
933                 $item['wall'] = 0;
934                 $item['contact-id'] = Contact::getIdForURL($item['author-link'], 0);
935
936                 if (in_array($item['type'], ["net-comment", "wall-comment"])) {
937                         $item['type'] = 'remote-comment';
938                 } elseif ($item['type'] == 'wall') {
939                         $item['type'] = 'remote';
940                 }
941
942                 $public_shadow = self::insert($item, false, false, true);
943
944                 logger("Stored public shadow for comment ".$item['uri']." under id ".$public_shadow, LOGGER_DEBUG);
945         }
946
947          /**
948          * Adds a "lang" specification in a "postopts" element of given $arr,
949          * if possible and not already present.
950          * Expects "body" element to exist in $arr.
951          */
952         private static function addLanguageInPostopts(&$arr)
953         {
954                 if (x($arr, 'postopts')) {
955                         if (strstr($arr['postopts'], 'lang=')) {
956                                 // do not override
957                                 return;
958                         }
959                         $postopts = $arr['postopts'];
960                 } else {
961                         $postopts = "";
962                 }
963
964                 $naked_body = preg_replace('/\[(.+?)\]/','', $arr['body']);
965                 $l = new Text_LanguageDetect();
966                 $lng = $l->detect($naked_body, 3);
967
968                 if (sizeof($lng) > 0) {
969                         if ($postopts != "") {
970                                 $postopts .= '&'; // arbitrary separator, to be reviewed
971                         }
972
973                         $postopts .= 'lang=';
974                         $sep = "";
975
976                         foreach ($lng as $language => $score) {
977                                 $postopts .= $sep . $language . ";" . $score;
978                                 $sep = ':';
979                         }
980                         $arr['postopts'] = $postopts;
981                 }
982         }
983
984         /**
985          * @brief Creates an unique guid out of a given uri
986          *
987          * @param string $uri uri of an item entry
988          * @param string $host (Optional) hostname for the GUID prefix
989          * @return string unique guid
990          */
991         public static function guidFromUri($uri, $host = "")
992         {
993                 // Our regular guid routine is using this kind of prefix as well
994                 // We have to avoid that different routines could accidentally create the same value
995                 $parsed = parse_url($uri);
996
997                 // When the hostname isn't given, we take it from the uri
998                 if ($host == "") {
999                         // Is it in the format data@host.tld?
1000                         if ((count($parsed) == 1) && strstr($uri, '@')) {
1001                                 $mailparts = explode('@', $uri);
1002                                 $host = array_pop($mailparts);
1003                         } else {
1004                                 $host = $parsed["host"];
1005                         }
1006                 }
1007
1008                 // We use a hash of the hostname as prefix for the guid
1009                 $guid_prefix = hash("crc32", $host);
1010
1011                 // Remove the scheme to make sure that "https" and "http" doesn't make a difference
1012                 unset($parsed["scheme"]);
1013
1014                 // Glue it together to be able to make a hash from it
1015                 $host_id = implode("/", $parsed);
1016
1017                 // We could use any hash algorithm since it isn't a security issue
1018                 $host_hash = hash("ripemd128", $host_id);
1019
1020                 return $guid_prefix.$host_hash;
1021         }
1022
1023         /**
1024          * @brief Set "success_update" and "last-item" to the date of the last time we heard from this contact
1025          *
1026          * This can be used to filter for inactive contacts.
1027          * Only do this for public postings to avoid privacy problems, since poco data is public.
1028          * Don't set this value if it isn't from the owner (could be an author that we don't know)
1029          *
1030          * @param array $arr Contains the just posted item record
1031          */
1032         private static function updateContact($arr)
1033         {
1034                 // Unarchive the author
1035                 $contact = dba::selectFirst('contact', [], ['id' => $arr["author-link"]]);
1036                 if ($contact['term-date'] > NULL_DATE) {
1037                          Contact::unmarkForArchival($contact);
1038                 }
1039
1040                 // Unarchive the contact if it is a toplevel posting
1041                 if ($arr["parent-uri"] === $arr["uri"]) {
1042                         $contact = dba::selectFirst('contact', [], ['id' => $arr["contact-id"]]);
1043                         if ($contact['term-date'] > NULL_DATE) {
1044                                  Contact::unmarkForArchival($contact);
1045                         }
1046                 }
1047
1048                 $update = (!$arr['private'] && (($arr["author-link"] === $arr["owner-link"]) || ($arr["parent-uri"] === $arr["uri"])));
1049
1050                 // Is it a forum? Then we don't care about the rules from above
1051                 if (!$update && ($arr["network"] == NETWORK_DFRN) && ($arr["parent-uri"] === $arr["uri"])) {
1052                         $isforum = q("SELECT `forum` FROM `contact` WHERE `id` = %d AND `forum`",
1053                                         intval($arr['contact-id']));
1054                         if (DBM::is_result($isforum)) {
1055                                 $update = true;
1056                         }
1057                 }
1058
1059                 if ($update) {
1060                         dba::update('contact', ['success_update' => $arr['received'], 'last-item' => $arr['received']],
1061                                 ['id' => $arr['contact-id']]);
1062                 }
1063                 // Now do the same for the system wide contacts with uid=0
1064                 if (!$arr['private']) {
1065                         dba::update('contact', ['success_update' => $arr['received'], 'last-item' => $arr['received']],
1066                                 ['id' => $arr['owner-id']]);
1067
1068                         if ($arr['owner-id'] != $arr['author-id']) {
1069                                 dba::update('contact', ['success_update' => $arr['received'], 'last-item' => $arr['received']],
1070                                         ['id' => $arr['author-id']]);
1071                         }
1072                 }
1073         }
1074
1075         private static function setHashtags(&$item)
1076         {
1077
1078                 $tags = get_tags($item["body"]);
1079
1080                 // No hashtags?
1081                 if (!count($tags)) {
1082                         return false;
1083                 }
1084
1085                 // This sorting is important when there are hashtags that are part of other hashtags
1086                 // Otherwise there could be problems with hashtags like #test and #test2
1087                 rsort($tags);
1088
1089                 $URLSearchString = "^\[\]";
1090
1091                 // All hashtags should point to the home server if "local_tags" is activated
1092                 if (Config::get('system', 'local_tags')) {
1093                         $item["body"] = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
1094                                         "#[url=".System::baseUrl()."/search?tag=$2]$2[/url]", $item["body"]);
1095
1096                         $item["tag"] = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
1097                                         "#[url=".System::baseUrl()."/search?tag=$2]$2[/url]", $item["tag"]);
1098                 }
1099
1100                 // mask hashtags inside of url, bookmarks and attachments to avoid urls in urls
1101                 $item["body"] = preg_replace_callback("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
1102                         function ($match) {
1103                                 return ("[url=" . str_replace("#", "&num;", $match[1]) . "]" . str_replace("#", "&num;", $match[2]) . "[/url]");
1104                         }, $item["body"]);
1105
1106                 $item["body"] = preg_replace_callback("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism",
1107                         function ($match) {
1108                                 return ("[bookmark=" . str_replace("#", "&num;", $match[1]) . "]" . str_replace("#", "&num;", $match[2]) . "[/bookmark]");
1109                         }, $item["body"]);
1110
1111                 $item["body"] = preg_replace_callback("/\[attachment (.*)\](.*?)\[\/attachment\]/ism",
1112                         function ($match) {
1113                                 return ("[attachment " . str_replace("#", "&num;", $match[1]) . "]" . $match[2] . "[/attachment]");
1114                         }, $item["body"]);
1115
1116                 // Repair recursive urls
1117                 $item["body"] = preg_replace("/&num;\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
1118                                 "&num;$2", $item["body"]);
1119
1120                 foreach ($tags as $tag) {
1121                         if ((strpos($tag, '#') !== 0) || strpos($tag, '[url=')) {
1122                                 continue;
1123                         }
1124
1125                         $basetag = str_replace('_',' ',substr($tag,1));
1126
1127                         $newtag = '#[url=' . System::baseUrl() . '/search?tag=' . rawurlencode($basetag) . ']' . $basetag . '[/url]';
1128
1129                         $item["body"] = str_replace($tag, $newtag, $item["body"]);
1130
1131                         if (!stristr($item["tag"], "/search?tag=" . $basetag . "]" . $basetag . "[/url]")) {
1132                                 if (strlen($item["tag"])) {
1133                                         $item["tag"] = ','.$item["tag"];
1134                                 }
1135                                 $item["tag"] = $newtag.$item["tag"];
1136                         }
1137                 }
1138
1139                 // Convert back the masked hashtags
1140                 $item["body"] = str_replace("&num;", "#", $item["body"]);
1141         }
1142
1143         public static function getGuidById($id)
1144         {
1145                 $r = q("SELECT `guid` FROM `item` WHERE `id` = %d LIMIT 1", intval($id));
1146                 if (DBM::is_result($r)) {
1147                         return $r[0]["guid"];
1148                 } else {
1149                         return "";
1150                 }
1151         }
1152
1153         public static function getIdAndNickByGuid($guid, $uid = 0)
1154         {
1155                 $nick = "";
1156                 $id = 0;
1157
1158                 if ($uid == 0) {
1159                         $uid == local_user();
1160                 }
1161
1162                 // Does the given user have this item?
1163                 if ($uid) {
1164                         $r = q("SELECT `item`.`id`, `user`.`nickname` FROM `item` INNER JOIN `user` ON `user`.`uid` = `item`.`uid`
1165                                 WHERE `item`.`visible` = 1 AND `item`.`deleted` = 0 AND `item`.`moderated` = 0
1166                                         AND `item`.`guid` = '%s' AND `item`.`uid` = %d", dbesc($guid), intval($uid));
1167                         if (DBM::is_result($r)) {
1168                                 $id = $r[0]["id"];
1169                                 $nick = $r[0]["nickname"];
1170                         }
1171                 }
1172
1173                 // Or is it anywhere on the server?
1174                 if ($nick == "") {
1175                         $r = q("SELECT `item`.`id`, `user`.`nickname` FROM `item` INNER JOIN `user` ON `user`.`uid` = `item`.`uid`
1176                                 WHERE `item`.`visible` = 1 AND `item`.`deleted` = 0 AND `item`.`moderated` = 0
1177                                         AND `item`.`allow_cid` = ''  AND `item`.`allow_gid` = ''
1178                                         AND `item`.`deny_cid`  = '' AND `item`.`deny_gid`  = ''
1179                                         AND `item`.`private` = 0 AND `item`.`wall` = 1
1180                                         AND `item`.`guid` = '%s'", dbesc($guid));
1181                         if (DBM::is_result($r)) {
1182                                 $id = $r[0]["id"];
1183                                 $nick = $r[0]["nickname"];
1184                         }
1185                 }
1186                 return ["nick" => $nick, "id" => $id];
1187         }
1188
1189         /**
1190          * look for mention tags and setup a second delivery chain for forum/community posts if appropriate
1191          * @param int $uid
1192          * @param int $item_id
1193          * @return bool true if item was deleted, else false
1194          */
1195         private static function tagDeliver($uid, $item_id)
1196         {
1197                 $mention = false;
1198
1199                 $u = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
1200                         intval($uid)
1201                 );
1202                 if (!DBM::is_result($u)) {
1203                         return;
1204                 }
1205
1206                 $community_page = (($u[0]['page-flags'] == PAGE_COMMUNITY) ? true : false);
1207                 $prvgroup = (($u[0]['page-flags'] == PAGE_PRVGROUP) ? true : false);
1208
1209                 $i = q("SELECT * FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1",
1210                         intval($item_id),
1211                         intval($uid)
1212                 );
1213                 if (!DBM::is_result($i)) {
1214                         return;
1215                 }
1216
1217                 $item = $i[0];
1218
1219                 $link = normalise_link(System::baseUrl() . '/profile/' . $u[0]['nickname']);
1220
1221                 /*
1222                  * Diaspora uses their own hardwired link URL in @-tags
1223                  * instead of the one we supply with webfinger
1224                  */
1225                 $dlink = normalise_link(System::baseUrl() . '/u/' . $u[0]['nickname']);
1226
1227                 $cnt = preg_match_all('/[\@\!]\[url\=(.*?)\](.*?)\[\/url\]/ism', $item['body'], $matches, PREG_SET_ORDER);
1228                 if ($cnt) {
1229                         foreach ($matches as $mtch) {
1230                                 if (link_compare($link, $mtch[1]) || link_compare($dlink, $mtch[1])) {
1231                                         $mention = true;
1232                                         logger('mention found: ' . $mtch[2]);
1233                                 }
1234                         }
1235                 }
1236
1237                 if (!$mention) {
1238                         if (($community_page || $prvgroup) &&
1239                                   !$item['wall'] && !$item['origin'] && ($item['id'] == $item['parent'])) {
1240                                 // mmh.. no mention.. community page or private group... no wall.. no origin.. top-post (not a comment)
1241                                 // delete it!
1242                                 logger("no-mention top-level post to communuty or private group. delete.");
1243                                 dba::delete('item', ['id' => $item_id]);
1244                                 return true;
1245                         }
1246                         return;
1247                 }
1248
1249                 $arr = ['item' => $item, 'user' => $u[0], 'contact' => $r[0]];
1250
1251                 Addon::callHooks('tagged', $arr);
1252
1253                 if (!$community_page && !$prvgroup) {
1254                         return;
1255                 }
1256
1257                 /*
1258                  * tgroup delivery - setup a second delivery chain
1259                  * prevent delivery looping - only proceed
1260                  * if the message originated elsewhere and is a top-level post
1261                  */
1262                 if ($item['wall'] || $item['origin'] || ($item['id'] != $item['parent'])) {
1263                         return;
1264                 }
1265
1266                 // now change this copy of the post to a forum head message and deliver to all the tgroup members
1267                 $c = q("SELECT `name`, `url`, `thumb` FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
1268                         intval($u[0]['uid'])
1269                 );
1270                 if (!DBM::is_result($c)) {
1271                         return;
1272                 }
1273
1274                 // also reset all the privacy bits to the forum default permissions
1275
1276                 $private = ($u[0]['allow_cid'] || $u[0]['allow_gid'] || $u[0]['deny_cid'] || $u[0]['deny_gid']) ? 1 : 0;
1277
1278                 $forum_mode = (($prvgroup) ? 2 : 1);
1279
1280                 q("UPDATE `item` SET `wall` = 1, `origin` = 1, `forum_mode` = %d, `owner-name` = '%s', `owner-link` = '%s', `owner-avatar` = '%s',
1281                         `private` = %d, `allow_cid` = '%s', `allow_gid` = '%s', `deny_cid` = '%s', `deny_gid` = '%s'  WHERE `id` = %d",
1282                         intval($forum_mode),
1283                         dbesc($c[0]['name']),
1284                         dbesc($c[0]['url']),
1285                         dbesc($c[0]['thumb']),
1286                         intval($private),
1287                         dbesc($u[0]['allow_cid']),
1288                         dbesc($u[0]['allow_gid']),
1289                         dbesc($u[0]['deny_cid']),
1290                         dbesc($u[0]['deny_gid']),
1291                         intval($item_id)
1292                 );
1293                 update_thread($item_id);
1294
1295                 Worker::add(['priority' => PRIORITY_HIGH, 'dont_fork' => true], 'Notifier', 'tgroup', $item_id);
1296
1297         }
1298
1299         public static function isRemoteSelf($contact, &$datarray)
1300         {
1301                 $a = get_app();
1302
1303                 if (!$contact['remote_self']) {
1304                         return false;
1305                 }
1306
1307                 // Prevent the forwarding of posts that are forwarded
1308                 if ($datarray["extid"] == NETWORK_DFRN) {
1309                         return false;
1310                 }
1311
1312                 // Prevent to forward already forwarded posts
1313                 if ($datarray["app"] == $a->get_hostname()) {
1314                         return false;
1315                 }
1316
1317                 // Only forward posts
1318                 if ($datarray["verb"] != ACTIVITY_POST) {
1319                         return false;
1320                 }
1321
1322                 if (($contact['network'] != NETWORK_FEED) && $datarray['private']) {
1323                         return false;
1324                 }
1325
1326                 $datarray2 = $datarray;
1327                 logger('remote-self start - Contact '.$contact['url'].' - '.$contact['remote_self'].' Item '.print_r($datarray, true), LOGGER_DEBUG);
1328                 if ($contact['remote_self'] == 2) {
1329                         $r = q("SELECT `id`,`url`,`name`,`thumb` FROM `contact` WHERE `uid` = %d AND `self`",
1330                                 intval($contact['uid']));
1331                         if (DBM::is_result($r)) {
1332                                 $datarray['contact-id'] = $r[0]["id"];
1333
1334                                 $datarray['owner-name'] = $r[0]["name"];
1335                                 $datarray['owner-link'] = $r[0]["url"];
1336                                 $datarray['owner-avatar'] = $r[0]["thumb"];
1337
1338                                 $datarray['author-name']   = $datarray['owner-name'];
1339                                 $datarray['author-link']   = $datarray['owner-link'];
1340                                 $datarray['author-avatar'] = $datarray['owner-avatar'];
1341
1342                                 unset($datarray['created']);
1343                                 unset($datarray['edited']);
1344                         }
1345
1346                         if ($contact['network'] != NETWORK_FEED) {
1347                                 $datarray["guid"] = get_guid(32);
1348                                 unset($datarray["plink"]);
1349                                 $datarray["uri"] = item_new_uri($a->get_hostname(), $contact['uid'], $datarray["guid"]);
1350                                 $datarray["parent-uri"] = $datarray["uri"];
1351                                 $datarray["extid"] = $contact['network'];
1352                                 $urlpart = parse_url($datarray2['author-link']);
1353                                 $datarray["app"] = $urlpart["host"];
1354                         } else {
1355                                 $datarray['private'] = 0;
1356                         }
1357                 }
1358
1359                 if ($contact['network'] != NETWORK_FEED) {
1360                         // Store the original post
1361                         $r = self::insert($datarray2, false, false);
1362                         logger('remote-self post original item - Contact '.$contact['url'].' return '.$r.' Item '.print_r($datarray2, true), LOGGER_DEBUG);
1363                 } else {
1364                         $datarray["app"] = "Feed";
1365                 }
1366
1367                 // Trigger automatic reactions for addons
1368                 $datarray['api_source'] = true;
1369
1370                 // We have to tell the hooks who we are - this really should be improved
1371                 $_SESSION["authenticated"] = true;
1372                 $_SESSION["uid"] = $contact['uid'];
1373
1374                 return true;
1375         }
1376
1377         /**
1378          *
1379          * @param string $s
1380          * @param int    $uid
1381          * @param array  $item
1382          * @param int    $cid
1383          * @return string
1384          */
1385         public static function fixPrivatePhotos($s, $uid, $item = null, $cid = 0)
1386         {
1387                 if (Config::get('system', 'disable_embedded')) {
1388                         return $s;
1389                 }
1390
1391                 logger('check for photos', LOGGER_DEBUG);
1392                 $site = substr(System::baseUrl(), strpos(System::baseUrl(), '://'));
1393
1394                 $orig_body = $s;
1395                 $new_body = '';
1396
1397                 $img_start = strpos($orig_body, '[img');
1398                 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
1399                 $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
1400
1401                 while (($img_st_close !== false) && ($img_len !== false)) {
1402                         $img_st_close++; // make it point to AFTER the closing bracket
1403                         $image = substr($orig_body, $img_start + $img_st_close, $img_len);
1404
1405                         logger('found photo ' . $image, LOGGER_DEBUG);
1406
1407                         if (stristr($image, $site . '/photo/')) {
1408                                 // Only embed locally hosted photos
1409                                 $replace = false;
1410                                 $i = basename($image);
1411                                 $i = str_replace(['.jpg', '.png', '.gif'], ['', '', ''], $i);
1412                                 $x = strpos($i, '-');
1413
1414                                 if ($x) {
1415                                         $res = substr($i, $x + 1);
1416                                         $i = substr($i, 0, $x);
1417                                         $r = q("SELECT * FROM `photo` WHERE `resource-id` = '%s' AND `scale` = %d AND `uid` = %d",
1418                                                 dbesc($i),
1419                                                 intval($res),
1420                                                 intval($uid)
1421                                         );
1422                                         if (DBM::is_result($r)) {
1423                                                 /*
1424                                                  * Check to see if we should replace this photo link with an embedded image
1425                                                  * 1. No need to do so if the photo is public
1426                                                  * 2. If there's a contact-id provided, see if they're in the access list
1427                                                  *    for the photo. If so, embed it.
1428                                                  * 3. Otherwise, if we have an item, see if the item permissions match the photo
1429                                                  *    permissions, regardless of order but first check to see if they're an exact
1430                                                  *    match to save some processing overhead.
1431                                                  */
1432                                                 if (self::hasPermissions($r[0])) {
1433                                                         if ($cid) {
1434                                                                 $recips = self::enumeratePermissions($r[0]);
1435                                                                 if (in_array($cid, $recips)) {
1436                                                                         $replace = true;
1437                                                                 }
1438                                                         } elseif ($item) {
1439                                                                 if (self::samePermissions($item, $r[0])) {
1440                                                                         $replace = true;
1441                                                                 }
1442                                                         }
1443                                                 }
1444                                                 if ($replace) {
1445                                                         $data = $r[0]['data'];
1446                                                         $type = $r[0]['type'];
1447
1448                                                         // If a custom width and height were specified, apply before embedding
1449                                                         if (preg_match("/\[img\=([0-9]*)x([0-9]*)\]/is", substr($orig_body, $img_start, $img_st_close), $match)) {
1450                                                                 logger('scaling photo', LOGGER_DEBUG);
1451
1452                                                                 $width = intval($match[1]);
1453                                                                 $height = intval($match[2]);
1454
1455                                                                 $Image = new Image($data, $type);
1456                                                                 if ($Image->isValid()) {
1457                                                                         $Image->scaleDown(max($width, $height));
1458                                                                         $data = $Image->asString();
1459                                                                         $type = $Image->getType();
1460                                                                 }
1461                                                         }
1462
1463                                                         logger('replacing photo', LOGGER_DEBUG);
1464                                                         $image = 'data:' . $type . ';base64,' . base64_encode($data);
1465                                                         logger('replaced: ' . $image, LOGGER_DATA);
1466                                                 }
1467                                         }
1468                                 }
1469                         }
1470
1471                         $new_body = $new_body . substr($orig_body, 0, $img_start + $img_st_close) . $image . '[/img]';
1472                         $orig_body = substr($orig_body, $img_start + $img_st_close + $img_len + strlen('[/img]'));
1473                         if ($orig_body === false) {
1474                                 $orig_body = '';
1475                         }
1476
1477                         $img_start = strpos($orig_body, '[img');
1478                         $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
1479                         $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
1480                 }
1481
1482                 $new_body = $new_body . $orig_body;
1483
1484                 return $new_body;
1485         }
1486
1487         private static function hasPermissions($obj)
1488         {
1489                 return (
1490                         (
1491                                 x($obj, 'allow_cid')
1492                         ) || (
1493                                 x($obj, 'allow_gid')
1494                         ) || (
1495                                 x($obj, 'deny_cid')
1496                         ) || (
1497                                 x($obj, 'deny_gid')
1498                         )
1499                 );
1500         }
1501
1502         private static function samePermissions($obj1, $obj2)
1503         {
1504                 // first part is easy. Check that these are exactly the same.
1505                 if (($obj1['allow_cid'] == $obj2['allow_cid'])
1506                         && ($obj1['allow_gid'] == $obj2['allow_gid'])
1507                         && ($obj1['deny_cid'] == $obj2['deny_cid'])
1508                         && ($obj1['deny_gid'] == $obj2['deny_gid'])) {
1509                         return true;
1510                 }
1511
1512                 // This is harder. Parse all the permissions and compare the resulting set.
1513                 $recipients1 = self::enumeratePermissions($obj1);
1514                 $recipients2 = self::enumeratePermissions($obj2);
1515                 sort($recipients1);
1516                 sort($recipients2);
1517
1518                 /// @TODO Comparison of arrays, maybe use array_diff_assoc() here?
1519                 return ($recipients1 == $recipients2);
1520         }
1521
1522         // returns an array of contact-ids that are allowed to see this object
1523         private static function enumeratePermissions($obj)
1524         {
1525                 $allow_people = expand_acl($obj['allow_cid']);
1526                 $allow_groups = Group::expand(expand_acl($obj['allow_gid']));
1527                 $deny_people  = expand_acl($obj['deny_cid']);
1528                 $deny_groups  = Group::expand(expand_acl($obj['deny_gid']));
1529                 $recipients   = array_unique(array_merge($allow_people, $allow_groups));
1530                 $deny         = array_unique(array_merge($deny_people, $deny_groups));
1531                 $recipients   = array_diff($recipients, $deny);
1532                 return $recipients;
1533         }
1534
1535         public static function getFeedTags($item)
1536         {
1537                 $ret = [];
1538                 $matches = false;
1539                 $cnt = preg_match_all('|\#\[url\=(.*?)\](.*?)\[\/url\]|', $item['tag'], $matches);
1540                 if ($cnt) {
1541                         for ($x = 0; $x < $cnt; $x ++) {
1542                                 if ($matches[1][$x]) {
1543                                         $ret[$matches[2][$x]] = ['#', $matches[1][$x], $matches[2][$x]];
1544                                 }
1545                         }
1546                 }
1547                 $matches = false;
1548                 $cnt = preg_match_all('|\@\[url\=(.*?)\](.*?)\[\/url\]|', $item['tag'], $matches);
1549                 if ($cnt) {
1550                         for ($x = 0; $x < $cnt; $x ++) {
1551                                 if ($matches[1][$x]) {
1552                                         $ret[] = ['@', $matches[1][$x], $matches[2][$x]];
1553                                 }
1554                         }
1555                 }
1556                 return $ret;
1557         }
1558
1559         public static function expire($uid, $days, $network = "", $force = false)
1560         {
1561                 if (!$uid || ($days < 1)) {
1562                         return;
1563                 }
1564
1565                 /*
1566                  * $expire_network_only = save your own wall posts
1567                  * and just expire conversations started by others
1568                  */
1569                 $expire_network_only = PConfig::get($uid,'expire', 'network_only');
1570                 $sql_extra = (intval($expire_network_only) ? " AND wall = 0 " : "");
1571
1572                 if ($network != "") {
1573                         $sql_extra .= sprintf(" AND network = '%s' ", dbesc($network));
1574
1575                         /*
1576                          * There is an index "uid_network_received" but not "uid_network_created"
1577                          * This avoids the creation of another index just for one purpose.
1578                          * And it doesn't really matter wether to look at "received" or "created"
1579                          */
1580                         $range = "AND `received` < UTC_TIMESTAMP() - INTERVAL %d DAY ";
1581                 } else {
1582                         $range = "AND `created` < UTC_TIMESTAMP() - INTERVAL %d DAY ";
1583                 }
1584
1585                 $r = q("SELECT `file`, `resource-id`, `starred`, `type`, `id` FROM `item`
1586                         WHERE `uid` = %d $range
1587                         AND `id` = `parent`
1588                         $sql_extra
1589                         AND `deleted` = 0",
1590                         intval($uid),
1591                         intval($days)
1592                 );
1593
1594                 if (!DBM::is_result($r)) {
1595                         return;
1596                 }
1597
1598                 $expire_items = PConfig::get($uid, 'expire', 'items', 1);
1599
1600                 // Forcing expiring of items - but not notes and marked items
1601                 if ($force) {
1602                         $expire_items = true;
1603                 }
1604
1605                 $expire_notes = PConfig::get($uid, 'expire', 'notes', 1);
1606                 $expire_starred = PConfig::get($uid, 'expire', 'starred', 1);
1607                 $expire_photos = PConfig::get($uid, 'expire', 'photos', 0);
1608
1609                 logger('User '.$uid.': expire: # items=' . count($r). "; expire items: $expire_items, expire notes: $expire_notes, expire starred: $expire_starred, expire photos: $expire_photos");
1610
1611                 foreach ($r as $item) {
1612
1613                         // don't expire filed items
1614
1615                         if (strpos($item['file'],'[') !== false) {
1616                                 continue;
1617                         }
1618
1619                         // Only expire posts, not photos and photo comments
1620
1621                         if ($expire_photos == 0 && strlen($item['resource-id'])) {
1622                                 continue;
1623                         } elseif ($expire_starred == 0 && intval($item['starred'])) {
1624                                 continue;
1625                         } elseif ($expire_notes == 0 && $item['type'] == 'note') {
1626                                 continue;
1627                         } elseif ($expire_items == 0 && $item['type'] != 'note') {
1628                                 continue;
1629                         }
1630
1631                         self::delete($item['id'], PRIORITY_LOW);
1632                 }
1633         }
1634
1635         /// @TODO: This query seems to be really slow
1636         public static function firstPostDate($uid, $wall = false)
1637         {
1638                 $r = q("SELECT `id`, `created` FROM `item`
1639                         WHERE `uid` = %d AND `wall` = %d AND `deleted` = 0 AND `visible` = 1 AND `moderated` = 0
1640                         AND `id` = `parent`
1641                         ORDER BY `created` ASC LIMIT 1",
1642                         intval($uid),
1643                         intval($wall ? 1 : 0)
1644                 );
1645                 if (DBM::is_result($r)) {
1646                         return substr(DateTimeFormat::local($r[0]['created']),0,10);
1647                 }
1648                 return false;
1649         }
1650
1651         /**
1652          * @brief add/remove activity to an item
1653          *
1654          * Toggle activities as like,dislike,attend of an item
1655          *
1656          * @param string $item_id
1657          * @param string $verb
1658          *              Activity verb. One of
1659          *                      like, unlike, dislike, undislike, attendyes, unattendyes,
1660          *                      attendno, unattendno, attendmaybe, unattendmaybe
1661          * @hook 'post_local_end'
1662          *              array $arr
1663          *                      'post_id' => ID of posted item
1664          */
1665         public static function performLike($item_id, $verb)
1666         {
1667                 if (!local_user() && !remote_user()) {
1668                         return false;
1669                 }
1670
1671                 switch ($verb) {
1672                         case 'like':
1673                         case 'unlike':
1674                                 $bodyverb = L10n::t('%1$s likes %2$s\'s %3$s');
1675                                 $activity = ACTIVITY_LIKE;
1676                                 break;
1677                         case 'dislike':
1678                         case 'undislike':
1679                                 $bodyverb = L10n::t('%1$s doesn\'t like %2$s\'s %3$s');
1680                                 $activity = ACTIVITY_DISLIKE;
1681                                 break;
1682                         case 'attendyes':
1683                         case 'unattendyes':
1684                                 $bodyverb = L10n::t('%1$s is attending %2$s\'s %3$s');
1685                                 $activity = ACTIVITY_ATTEND;
1686                                 break;
1687                         case 'attendno':
1688                         case 'unattendno':
1689                                 $bodyverb = L10n::t('%1$s is not attending %2$s\'s %3$s');
1690                                 $activity = ACTIVITY_ATTENDNO;
1691                                 break;
1692                         case 'attendmaybe':
1693                         case 'unattendmaybe':
1694                                 $bodyverb = L10n::t('%1$s may attend %2$s\'s %3$s');
1695                                 $activity = ACTIVITY_ATTENDMAYBE;
1696                                 break;
1697                         default:
1698                                 logger('like: unknown verb ' . $verb . ' for item ' . $item_id);
1699                                 return false;
1700                 }
1701
1702                 // Enable activity toggling instead of on/off
1703                 $event_verb_flag = $activity === ACTIVITY_ATTEND || $activity === ACTIVITY_ATTENDNO || $activity === ACTIVITY_ATTENDMAYBE;
1704
1705                 logger('like: verb ' . $verb . ' item ' . $item_id);
1706
1707                 $item = dba::selectFirst('item', [], ['`id` = ? OR `uri` = ?', $item_id, $item_id]);
1708                 if (!DBM::is_result($item)) {
1709                         logger('like: unknown item ' . $item_id);
1710                         return false;
1711                 }
1712
1713                 $uid = $item['uid'];
1714                 if (($uid == 0) && local_user()) {
1715                         $uid = local_user();
1716                 }
1717
1718                 if (!can_write_wall($uid)) {
1719                         logger('like: unable to write on wall ' . $uid);
1720                         return false;
1721                 }
1722
1723                 // Retrieves the local post owner
1724                 $owner_self_contact = dba::selectFirst('contact', [], ['uid' => $uid, 'self' => true]);
1725                 if (!DBM::is_result($owner_self_contact)) {
1726                         logger('like: unknown owner ' . $uid);
1727                         return false;
1728                 }
1729
1730                 // Retrieve the current logged in user's public contact
1731                 $author_id = public_contact();
1732
1733                 $author_contact = dba::selectFirst('contact', [], ['id' => $author_id]);
1734                 if (!DBM::is_result($author_contact)) {
1735                         logger('like: unknown author ' . $author_id);
1736                         return false;
1737                 }
1738
1739                 // Contact-id is the uid-dependant author contact
1740                 if (local_user() == $uid) {
1741                         $item_contact_id = $owner_self_contact['id'];
1742                         $item_contact = $owner_self_contact;
1743                 } else {
1744                         $item_contact_id = Contact::getIdForURL($author_contact['url'], $uid);
1745                         $item_contact = dba::selectFirst('contact', [], ['id' => $item_contact_id]);
1746                         if (!DBM::is_result($item_contact)) {
1747                                 logger('like: unknown item contact ' . $item_contact_id);
1748                                 return false;
1749                         }
1750                 }
1751
1752                 // Look for an existing verb row
1753                 // event participation are essentially radio toggles. If you make a subsequent choice,
1754                 // we need to eradicate your first choice.
1755                 if ($event_verb_flag) {
1756                         $verbs = "'" . dbesc(ACTIVITY_ATTEND) . "', '" . dbesc(ACTIVITY_ATTENDNO) . "', '" . dbesc(ACTIVITY_ATTENDMAYBE) . "'";
1757                 } else {
1758                         $verbs = "'".dbesc($activity)."'";
1759                 }
1760
1761                 $existing_like = q("SELECT `id`, `guid`, `verb` FROM `item`
1762                         WHERE `verb` IN ($verbs)
1763                         AND `deleted` = 0
1764                         AND `author-id` = %d
1765                         AND `uid` = %d
1766                         AND (`parent` = '%s' OR `parent-uri` = '%s' OR `thr-parent` = '%s')
1767                         LIMIT 1",
1768                         intval($author_contact['id']),
1769                         intval($item['uid']),
1770                         dbesc($item_id), dbesc($item_id), dbesc($item['uri'])
1771                 );
1772
1773                 // If it exists, mark it as deleted
1774                 if (DBM::is_result($existing_like)) {
1775                         $like_item = $existing_like[0];
1776
1777                         // Already voted, undo it
1778                         $fields = ['deleted' => true, 'unseen' => true, 'changed' => DateTimeFormat::utcNow()];
1779                         dba::update('item', $fields, ['id' => $like_item['id']]);
1780
1781                         // Clean up the Diaspora signatures for this like
1782                         // Go ahead and do it even if Diaspora support is disabled. We still want to clean up
1783                         // if it had been enabled in the past
1784                         dba::delete('sign', ['iid' => $like_item['id']]);
1785
1786                         $like_item_id = $like_item['id'];
1787                         Worker::add(PRIORITY_HIGH, "Notifier", "like", $like_item_id);
1788
1789                         if (!$event_verb_flag || $like_item['verb'] == $activity) {
1790                                 return true;
1791                         }
1792                 }
1793
1794                 // Verb is "un-something", just trying to delete existing entries
1795                 if (strpos($verb, 'un') === 0) {
1796                         return true;
1797                 }
1798
1799                 // Else or if event verb different from existing row, create a new item row
1800                 $post_type = (($item['resource-id']) ? L10n::t('photo') : L10n::t('status'));
1801                 if ($item['object-type'] === ACTIVITY_OBJ_EVENT) {
1802                         $post_type = L10n::t('event');
1803                 }
1804                 $objtype = $item['resource-id'] ? ACTIVITY_OBJ_IMAGE : ACTIVITY_OBJ_NOTE ;
1805                 $link = xmlify('<link rel="alternate" type="text/html" href="' . System::baseUrl() . '/display/' . $owner_self_contact['nick'] . '/' . $item['id'] . '" />' . "\n") ;
1806                 $body = $item['body'];
1807
1808                 $obj = <<< EOT
1809
1810                 <object>
1811                         <type>$objtype</type>
1812                         <local>1</local>
1813                         <id>{$item['uri']}</id>
1814                         <link>$link</link>
1815                         <title></title>
1816                         <content>$body</content>
1817                 </object>
1818 EOT;
1819
1820                 $ulink = '[url=' . $author_contact['url'] . ']' . $author_contact['name'] . '[/url]';
1821                 $alink = '[url=' . $item['author-link'] . ']' . $item['author-name'] . '[/url]';
1822                 $plink = '[url=' . System::baseUrl() . '/display/' . $owner_self_contact['nick'] . '/' . $item['id'] . ']' . $post_type . '[/url]';
1823
1824                 $new_item = [
1825                         'guid'          => get_guid(32),
1826                         'uri'           => item_new_uri(self::getApp()->get_hostname(), $item['uid']),
1827                         'uid'           => $item['uid'],
1828                         'contact-id'    => $item_contact_id,
1829                         'type'          => 'activity',
1830                         'wall'          => $item['wall'],
1831                         'origin'        => 1,
1832                         'gravity'       => GRAVITY_LIKE,
1833                         'parent'        => $item['id'],
1834                         'parent-uri'    => $item['uri'],
1835                         'thr-parent'    => $item['uri'],
1836                         'owner-id'      => $item['owner-id'],
1837                         'owner-name'    => $item['owner-name'],
1838                         'owner-link'    => $item['owner-link'],
1839                         'owner-avatar'  => $item['owner-avatar'],
1840                         'author-id'     => $author_contact['id'],
1841                         'author-name'   => $author_contact['name'],
1842                         'author-link'   => $author_contact['url'],
1843                         'author-avatar' => $author_contact['thumb'],
1844                         'body'          => sprintf($bodyverb, $ulink, $alink, $plink),
1845                         'verb'          => $activity,
1846                         'object-type'   => $objtype,
1847                         'object'        => $obj,
1848                         'allow_cid'     => $item['allow_cid'],
1849                         'allow_gid'     => $item['allow_gid'],
1850                         'deny_cid'      => $item['deny_cid'],
1851                         'deny_gid'      => $item['deny_gid'],
1852                         'visible'       => 1,
1853                         'unseen'        => 1,
1854                 ];
1855
1856                 $new_item_id = Item::insert($new_item);
1857
1858                 // @todo: Explain this block
1859                 if (! $item['visible']) {
1860                         q("UPDATE `item` SET `visible` = 1 WHERE `id` = %d",
1861                                 intval($item['id'])
1862                         );
1863                 }
1864
1865                 // Save the author information for the like in case we need to relay to Diaspora
1866                 Diaspora::storeLikeSignature($item_contact, $new_item_id);
1867
1868                 $new_item['id'] = $new_item_id;
1869
1870                 Addon::callHooks('post_local_end', $new_item);
1871
1872                 Worker::add(PRIORITY_HIGH, "Notifier", "like", $new_item_id);
1873
1874                 return true;
1875         }
1876 }