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