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