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