]> git.mxchange.org Git - friendica.git/blob - mod/item.php
Change plugin to addon
[friendica.git] / mod / item.php
1 <?php
2 /**
3  * @file mod/item.php
4  */
5
6 /*
7  * This is the POST destination for most all locally posted
8  * text stuff. This function handles status, wall-to-wall status,
9  * local comments, and remote coments that are posted on this site
10  * (as opposed to being delivered in a feed).
11  * Also processed here are posts and comments coming through the
12  * statusnet/twitter API.
13  *
14  * All of these become an "item" which is our basic unit of
15  * information.
16  */
17 use Friendica\App;
18 use Friendica\Core\Addon;
19 use Friendica\Core\Config;
20 use Friendica\Core\System;
21 use Friendica\Core\Worker;
22 use Friendica\Database\DBM;
23 use Friendica\Model\Contact;
24 use Friendica\Model\GContact;
25 use Friendica\Model\Item;
26 use Friendica\Network\Probe;
27 use Friendica\Protocol\Diaspora;
28 use Friendica\Protocol\Email;
29 use Friendica\Util\Emailer;
30
31 require_once 'include/enotify.php';
32 require_once 'include/tags.php';
33 require_once 'include/threads.php';
34 require_once 'include/text.php';
35 require_once 'include/items.php';
36
37 function item_post(App $a) {
38         if (!local_user() && !remote_user()) {
39                 return;
40         }
41
42         require_once 'include/security.php';
43
44         $uid = local_user();
45
46         if (x($_REQUEST, 'dropitems')) {
47                 $arr_drop = explode(',', $_REQUEST['dropitems']);
48                 drop_items($arr_drop);
49                 $json = ['success' => 1];
50                 echo json_encode($json);
51                 killme();
52         }
53
54         Addon::callHooks('post_local_start', $_REQUEST);
55         // logger('postinput ' . file_get_contents('php://input'));
56         logger('postvars ' . print_r($_REQUEST,true), LOGGER_DATA);
57
58         $api_source = x($_REQUEST, 'api_source') && $_REQUEST['api_source'];
59
60         $message_id = ((x($_REQUEST, 'message_id') && $api_source) ? strip_tags($_REQUEST['message_id']) : '');
61
62         $return_path = (x($_REQUEST, 'return') ? $_REQUEST['return'] : '');
63         $preview = (x($_REQUEST, 'preview') ? intval($_REQUEST['preview']) : 0);
64
65         /*
66          * Check for doubly-submitted posts, and reject duplicates
67          * Note that we have to ignore previews, otherwise nothing will post
68          * after it's been previewed
69          */
70         if (!$preview && x($_REQUEST, 'post_id_random')) {
71                 if (x($_SESSION, 'post-random') && $_SESSION['post-random'] == $_REQUEST['post_id_random']) {
72                         logger("item post: duplicate post", LOGGER_DEBUG);
73                         item_post_return(System::baseUrl(), $api_source, $return_path);
74                 } else {
75                         $_SESSION['post-random'] = $_REQUEST['post_id_random'];
76                 }
77         }
78
79         // Is this a reply to something?
80         $parent = (x($_REQUEST, 'parent') ? intval($_REQUEST['parent']) : 0);
81         $parent_uri = (x($_REQUEST, 'parent_uri') ? trim($_REQUEST['parent_uri']) : '');
82
83         $parent_item = null;
84         $parent_contact = null;
85         $parid = 0;
86         $r = false;
87         $objecttype = null;
88         $parent_user = null;
89
90         if ($parent || $parent_uri) {
91
92                 $objecttype = ACTIVITY_OBJ_COMMENT;
93
94                 if (!x($_REQUEST, 'type')) {
95                         $_REQUEST['type'] = 'net-comment';
96                 }
97
98                 if ($parent) {
99                         $r = q("SELECT * FROM `item` WHERE `id` = %d LIMIT 1",
100                                 intval($parent)
101                         );
102                 } elseif ($parent_uri && local_user()) {
103                         // This is coming from an API source, and we are logged in
104                         $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
105                                 dbesc($parent_uri),
106                                 intval(local_user())
107                         );
108
109                         // if this isn't the real parent of the conversation, find it
110                         if (DBM::is_result($r)) {
111                                 $parid = $r[0]['parent'];
112                                 if ($r[0]['id'] != $r[0]['parent']) {
113                                         $r = q("SELECT * FROM `item` WHERE `id` = `parent` AND `parent` = %d LIMIT 1",
114                                                 intval($parid)
115                                         );
116                                 }
117                         }
118                 }
119
120                 if (!DBM::is_result($r)) {
121                         notice(t('Unable to locate original post.') . EOL);
122                         if (x($_REQUEST, 'return')) {
123                                 goaway($return_path);
124                         }
125                         killme();
126                 }
127                 $parent_item = $r[0];
128                 $parent = $parent_item['id'];
129                 $parent_uri = $parent_item['uri'];
130                 $parent_user = $parent_item['uid'];
131
132                 if ($parent_item['contact-id']) {
133                         $r = q("SELECT * FROM `contact` WHERE `id` = %d LIMIT 1",
134                                 intval($parent_item['contact-id'])
135                         );
136                         if (DBM::is_result($r)) {
137                                 $parent_contact = $r[0];
138                         }
139
140                         // If the contact id doesn't fit with the contact, then set the contact to null
141                         $thrparent = q("SELECT `author-link`, `network` FROM `item` WHERE `uri` = '%s' LIMIT 1", dbesc($parent_uri));
142                         if (DBM::is_result($thrparent) && ($thrparent[0]["network"] === NETWORK_OSTATUS)
143                                 && (normalise_link($parent_contact["url"]) != normalise_link($thrparent[0]["author-link"]))) {
144                                 $parent_contact = Contact::getDetailsByURL($thrparent[0]["author-link"]);
145
146                                 if (!isset($parent_contact["nick"])) {
147                                         $probed_contact = Probe::uri($thrparent[0]["author-link"]);
148                                         if ($probed_contact["network"] != NETWORK_FEED) {
149                                                 $parent_contact = $probed_contact;
150                                                 $parent_contact["nurl"] = normalise_link($probed_contact["url"]);
151                                                 $parent_contact["thumb"] = $probed_contact["photo"];
152                                                 $parent_contact["micro"] = $probed_contact["photo"];
153                                                 $parent_contact["addr"] = $probed_contact["addr"];
154                                         }
155                                 }
156                                 logger('no contact found: ' . print_r($thrparent, true), LOGGER_DEBUG);
157                         } else {
158                                 logger('parent contact: ' . print_r($parent_contact, true), LOGGER_DEBUG);
159                         }
160
161                         if ($parent_contact["nick"] == "") {
162                                 $parent_contact["nick"] = $parent_contact["name"];
163                         }
164                 }
165         }
166
167         if ($parent) {
168                 logger('mod_item: item_post parent=' . $parent);
169         }
170
171         $profile_uid = (x($_REQUEST, 'profile_uid') ? intval($_REQUEST['profile_uid']) : 0);
172         $post_id     = (x($_REQUEST, 'post_id')     ? intval($_REQUEST['post_id'])     : 0);
173         $app         = (x($_REQUEST, 'source')      ? strip_tags($_REQUEST['source'])  : '');
174         $extid       = (x($_REQUEST, 'extid')       ? strip_tags($_REQUEST['extid'])   : '');
175         $object      = (x($_REQUEST, 'object')      ? $_REQUEST['object']              : '');
176
177         // Ensure that the user id in a thread always stay the same
178         if (!is_null($parent_user) && in_array($parent_user, [local_user(), 0])) {
179                 $profile_uid = $parent_user;
180         }
181
182         // Check for multiple posts with the same message id (when the post was created via API)
183         if (($message_id != '') && ($profile_uid != 0)) {
184                 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
185                         dbesc($message_id),
186                         intval($profile_uid)
187                 );
188
189                 if (DBM::is_result($r)) {
190                         logger("Message with URI ".$message_id." already exists for user ".$profile_uid, LOGGER_DEBUG);
191                         return;
192                 }
193         }
194
195         // Allow commenting if it is an answer to a public post
196         $allow_comment = local_user() && ($profile_uid == 0) && $parent && in_array($parent_item['network'], [NETWORK_OSTATUS, NETWORK_DIASPORA, NETWORK_DFRN]);
197
198         // Now check that valid personal details have been provided
199         if (!can_write_wall($profile_uid) && !$allow_comment) {
200                 notice(t('Permission denied.') . EOL) ;
201                 if (x($_REQUEST, 'return')) {
202                         goaway($return_path);
203                 }
204                 killme();
205         }
206
207
208         // is this an edited post?
209
210         $orig_post = null;
211
212         if ($post_id) {
213                 $i = q("SELECT * FROM `item` WHERE `uid` = %d AND `id` = %d LIMIT 1",
214                         intval($profile_uid),
215                         intval($post_id)
216                 );
217                 if (!DBM::is_result($i)) {
218                         killme();
219                 }
220                 $orig_post = $i[0];
221         }
222
223         $user = null;
224
225         $r = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
226                 intval($profile_uid)
227         );
228         if (DBM::is_result($r)) {
229                 $user = $r[0];
230         }
231
232         if ($orig_post) {
233                 $str_group_allow   = $orig_post['allow_gid'];
234                 $str_contact_allow = $orig_post['allow_cid'];
235                 $str_group_deny    = $orig_post['deny_gid'];
236                 $str_contact_deny  = $orig_post['deny_cid'];
237                 $location          = $orig_post['location'];
238                 $coord             = $orig_post['coord'];
239                 $verb              = $orig_post['verb'];
240                 $objecttype        = $orig_post['object-type'];
241                 $emailcc           = $orig_post['emailcc'];
242                 $app               = $orig_post['app'];
243                 $categories        = $orig_post['file'];
244                 $title             = notags(trim($_REQUEST['title']));
245                 $body              = escape_tags(trim($_REQUEST['body']));
246                 $private           = $orig_post['private'];
247                 $pubmail_enable    = $orig_post['pubmail'];
248                 $network           = $orig_post['network'];
249                 $guid              = $orig_post['guid'];
250                 $extid             = $orig_post['extid'];
251
252         } else {
253
254                 /*
255                  * if coming from the API and no privacy settings are set,
256                  * use the user default permissions - as they won't have
257                  * been supplied via a form.
258                  */
259                 /// @TODO use x($_REQUEST, 'foo') here
260                 if ($api_source
261                         && !array_key_exists('contact_allow', $_REQUEST)
262                         && !array_key_exists('group_allow', $_REQUEST)
263                         && !array_key_exists('contact_deny', $_REQUEST)
264                         && !array_key_exists('group_deny', $_REQUEST)) {
265                         $str_group_allow   = $user['allow_gid'];
266                         $str_contact_allow = $user['allow_cid'];
267                         $str_group_deny    = $user['deny_gid'];
268                         $str_contact_deny  = $user['deny_cid'];
269                 } else {
270
271                         // use the posted permissions
272
273                         $str_group_allow   = perms2str($_REQUEST['group_allow']);
274                         $str_contact_allow = perms2str($_REQUEST['contact_allow']);
275                         $str_group_deny    = perms2str($_REQUEST['group_deny']);
276                         $str_contact_deny  = perms2str($_REQUEST['contact_deny']);
277                 }
278
279                 $title             = notags(trim($_REQUEST['title']));
280                 $location          = notags(trim($_REQUEST['location']));
281                 $coord             = notags(trim($_REQUEST['coord']));
282                 $verb              = notags(trim($_REQUEST['verb']));
283                 $emailcc           = notags(trim($_REQUEST['emailcc']));
284                 $body              = escape_tags(trim($_REQUEST['body']));
285                 $network           = notags(trim($_REQUEST['network']));
286                 $guid              = get_guid(32);
287
288                 item_add_language_opt($_REQUEST);
289                 $postopts = $_REQUEST['postopts'] ? $_REQUEST['postopts'] : "";
290
291                 $private = ((strlen($str_group_allow) || strlen($str_contact_allow) || strlen($str_group_deny) || strlen($str_contact_deny)) ? 1 : 0);
292
293                 if ($user['hidewall']) {
294                         $private = 2;
295                 }
296
297                 // If this is a comment, set the permissions from the parent.
298
299                 if ($parent_item) {
300
301                         // for non native networks use the network of the original post as network of the item
302                         if (($parent_item['network'] != NETWORK_DIASPORA)
303                                 && ($parent_item['network'] != NETWORK_OSTATUS)
304                                 && ($network == "")) {
305                                 $network = $parent_item['network'];
306                         }
307
308                         $str_contact_allow = $parent_item['allow_cid'];
309                         $str_group_allow   = $parent_item['allow_gid'];
310                         $str_contact_deny  = $parent_item['deny_cid'];
311                         $str_group_deny    = $parent_item['deny_gid'];
312                         $private           = $parent_item['private'];
313                 }
314
315                 $pubmail_enable    = ((x($_REQUEST, 'pubmail_enable') && intval($_REQUEST['pubmail_enable']) && !$private) ? 1 : 0);
316
317                 // if using the API, we won't see pubmail_enable - figure out if it should be set
318
319                 if ($api_source && $profile_uid && $profile_uid == local_user() && !$private) {
320                         $mail_disabled = ((function_exists('imap_open') && !Config::get('system', 'imap_disabled')) ? 0 : 1);
321                         if (!$mail_disabled) {
322                                 /// @TODO Check if only pubmail is loaded, * loads all columns
323                                 $r = q("SELECT * FROM `mailacct` WHERE `uid` = %d AND `server` != '' LIMIT 1",
324                                         intval(local_user())
325                                 );
326                                 if (DBM::is_result($r) && intval($r[0]['pubmail'])) {
327                                         $pubmail_enabled = true;
328                                 }
329                         }
330                 }
331
332                 if (!strlen($body)) {
333                         if ($preview) {
334                                 killme();
335                         }
336                         info(t('Empty post discarded.') . EOL);
337                         if (x($_REQUEST, 'return')) {
338                                 goaway($return_path);
339                         }
340                         killme();
341                 }
342         }
343
344         if (strlen($categories)) {
345                 // get the "fileas" tags for this post
346                 $filedas = file_tag_file_to_list($categories, 'file');
347         }
348         // save old and new categories, so we can determine what needs to be deleted from pconfig
349         $categories_old = $categories;
350         $categories = file_tag_list_to_file(trim($_REQUEST['category']), 'category');
351         $categories_new = $categories;
352         if (strlen($filedas)) {
353                 // append the fileas stuff to the new categories list
354                 $categories .= file_tag_list_to_file($filedas, 'file');
355         }
356
357         // get contact info for poster
358
359         $author = null;
360         $self   = false;
361         $contact_id = 0;
362
363         if (local_user() && ((local_user() == $profile_uid) || $allow_comment)) {
364                 $self = true;
365                 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `self` LIMIT 1",
366                         intval($_SESSION['uid']));
367         } elseif (remote_user()) {
368                 if (x($_SESSION, 'remote') && is_array($_SESSION['remote'])) {
369                         foreach ($_SESSION['remote'] as $v) {
370                                 if ($v['uid'] == $profile_uid) {
371                                         $contact_id = $v['cid'];
372                                         break;
373                                 }
374                         }
375                 }
376                 if ($contact_id) {
377                         $r = q("SELECT * FROM `contact` WHERE `id` = %d LIMIT 1",
378                                 intval($contact_id)
379                         );
380                 }
381         }
382
383         if (DBM::is_result($r)) {
384                 $author = $r[0];
385                 $contact_id = $author['id'];
386         }
387
388         // get contact info for owner
389
390         if ($profile_uid == local_user() || $allow_comment) {
391                 $contact_record = $author;
392         } else {
393                 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `self` LIMIT 1",
394                         intval($profile_uid)
395                 );
396                 if (DBM::is_result($r)) {
397                         $contact_record = $r[0];
398                 }
399         }
400
401         $post_type = notags(trim($_REQUEST['type']));
402
403         if ($post_type === 'net-comment' && $parent_item !== null) {
404                 if ($parent_item['wall'] == 1) {
405                         $post_type = 'wall-comment';
406                 } else {
407                         $post_type = 'remote-comment';
408                 }
409         }
410
411         // Look for any tags and linkify them
412         $str_tags = '';
413         $inform   = '';
414
415         $tags = get_tags($body);
416
417         /*
418          * add a statusnet style reply tag if the original post was from there
419          * and we are replying, and there isn't one already
420          */
421         if ($parent && ($parent_contact['network'] == NETWORK_OSTATUS)) {
422                 $contact = '@[url=' . $parent_contact['url'] . ']' . $parent_contact['nick'] . '[/url]';
423
424                 if (!in_array($contact, $tags)) {
425                         $body = $contact . ' ' . $body;
426                         $tags[] = $contact;
427                 }
428
429                 $toplevel_contact = "";
430                 $toplevel_parent = q("SELECT `contact`.* FROM `contact`
431                                                 INNER JOIN `item` ON `item`.`contact-id` = `contact`.`id` AND `contact`.`url` = `item`.`author-link`
432                                                 WHERE `item`.`id` = `item`.`parent` AND `item`.`parent` = %d", intval($parent));
433                 if (DBM::is_result($toplevel_parent)) {
434                         if (!empty($toplevel_parent[0]['addr'])) {
435                                 $toplevel_contact = '@' . $toplevel_parent[0]['addr'];
436                         } else {
437                                 $toplevel_contact = '@' . $toplevel_parent[0]['nick'] . '+' . $toplevel_parent[0]['id'];
438                         }
439                 } else {
440                         $toplevel_parent = q("SELECT `author-link`, `author-name` FROM `item` WHERE `id` = `parent` AND `parent` = %d", intval($parent));
441                         $toplevel_contact = '@[url=' . $toplevel_parent[0]['author-link'] . ']' . $toplevel_parent[0]['author-name'] . '[/url]';
442                 }
443
444                 if (!in_array($toplevel_contact, $tags)) {
445                         $tags[] = $toplevel_contact;
446                 }
447         }
448
449         $tagged = [];
450
451         $private_forum = false;
452         $only_to_forum = false;
453         $forum_contact = [];
454
455         if (count($tags)) {
456                 foreach ($tags as $tag) {
457
458                         $tag_type = substr($tag, 0, 1);
459
460                         if ($tag_type == '#') {
461                                 continue;
462                         }
463
464                         /*
465                          * If we already tagged 'Robert Johnson', don't try and tag 'Robert'.
466                          * Robert Johnson should be first in the $tags array
467                          */
468                         $fullnametagged = false;
469                         /// @TODO $tagged is initialized above if () block and is not filled, maybe old-lost code?
470                         foreach ($tagged as $nextTag) {
471                                 if (stristr($nextTag, $tag . ' ')) {
472                                         $fullnametagged = true;
473                                         break;
474                                 }
475                         }
476                         if ($fullnametagged) {
477                                 continue;
478                         }
479
480                         $success = handle_tag($a, $body, $inform, $str_tags, local_user() ? local_user() : $profile_uid, $tag, $network);
481                         if ($success['replaced']) {
482                                 $tagged[] = $tag;
483                         }
484                         // When the forum is private or the forum is addressed with a "!" make the post private
485                         if (is_array($success['contact']) && ($success['contact']['prv'] || ($tag_type == '!'))) {
486                                 $private_forum = $success['contact']['prv'];
487                                 $only_to_forum = ($tag_type == '!');
488                                 $private_id = $success['contact']['id'];
489                                 $forum_contact = $success['contact'];
490                         } elseif (is_array($success['contact']) && $success['contact']['forum'] &&
491                                 ($str_contact_allow == '<' . $success['contact']['id'] . '>')) {
492                                 $private_forum = false;
493                                 $only_to_forum = true;
494                                 $private_id = $success['contact']['id'];
495                                 $forum_contact = $success['contact'];
496                         }
497                 }
498         }
499
500         $original_contact_id = $contact_id;
501
502         if (!$parent && count($forum_contact) && ($private_forum || $only_to_forum)) {
503                 // we tagged a forum in a top level post. Now we change the post
504                 $private = $private_forum;
505
506                 $str_group_allow = '';
507                 $str_contact_deny = '';
508                 $str_group_deny = '';
509                 if ($private_forum) {
510                         $str_contact_allow = '<' . $private_id . '>';
511                 } else {
512                         $str_contact_allow = '';
513                 }
514                 $contact_id = $private_id;
515                 $contact_record = $forum_contact;
516                 $_REQUEST['origin'] = false;
517         }
518
519         /*
520          * When a photo was uploaded into the message using the (profile wall) ajax
521          * uploader, The permissions are initially set to disallow anybody but the
522          * owner from seeing it. This is because the permissions may not yet have been
523          * set for the post. If it's private, the photo permissions should be set
524          * appropriately. But we didn't know the final permissions on the post until
525          * now. So now we'll look for links of uploaded messages that are in the
526          * post and set them to the same permissions as the post itself.
527          */
528
529         $match = null;
530
531         if (!$preview && preg_match_all("/\[img([\=0-9x]*?)\](.*?)\[\/img\]/",$body,$match)) {
532                 $images = $match[2];
533                 if (count($images)) {
534
535                         $objecttype = ACTIVITY_OBJ_IMAGE;
536
537                         foreach ($images as $image) {
538                                 if (!stristr($image, System::baseUrl() . '/photo/')) {
539                                         continue;
540                                 }
541                                 $image_uri = substr($image,strrpos($image,'/') + 1);
542                                 $image_uri = substr($image_uri,0, strpos($image_uri,'-'));
543                                 if (!strlen($image_uri)) {
544                                         continue;
545                                 }
546                                 $srch = '<' . intval($original_contact_id) . '>';
547
548                                 $r = q("SELECT `id` FROM `photo` WHERE `allow_cid` = '%s' AND `allow_gid` = '' AND `deny_cid` = '' AND `deny_gid` = ''
549                                         AND `resource-id` = '%s' AND `uid` = %d LIMIT 1",
550                                         dbesc($srch),
551                                         dbesc($image_uri),
552                                         intval($profile_uid)
553                                 );
554
555                                 if (!DBM::is_result($r)) {
556                                         continue;
557                                 }
558
559                                 $r = q("UPDATE `photo` SET `allow_cid` = '%s', `allow_gid` = '%s', `deny_cid` = '%s', `deny_gid` = '%s'
560                                         WHERE `resource-id` = '%s' AND `uid` = %d AND `album` = '%s' ",
561                                         dbesc($str_contact_allow),
562                                         dbesc($str_group_allow),
563                                         dbesc($str_contact_deny),
564                                         dbesc($str_group_deny),
565                                         dbesc($image_uri),
566                                         intval($profile_uid),
567                                         dbesc(t('Wall Photos'))
568                                 );
569                         }
570                 }
571         }
572
573
574         /*
575          * Next link in any attachment references we find in the post.
576          */
577         $match = false;
578
579         if (!$preview && preg_match_all("/\[attachment\](.*?)\[\/attachment\]/", $body, $match)) {
580                 $attaches = $match[1];
581                 if (count($attaches)) {
582                         foreach ($attaches as $attach) {
583                                 $r = q("SELECT * FROM `attach` WHERE `uid` = %d AND `id` = %d LIMIT 1",
584                                         intval($profile_uid),
585                                         intval($attach)
586                                 );
587                                 if (DBM::is_result($r)) {
588                                         $r = q("UPDATE `attach` SET `allow_cid` = '%s', `allow_gid` = '%s', `deny_cid` = '%s', `deny_gid` = '%s'
589                                                 WHERE `uid` = %d AND `id` = %d",
590                                                 dbesc($str_contact_allow),
591                                                 dbesc($str_group_allow),
592                                                 dbesc($str_contact_deny),
593                                                 dbesc($str_group_deny),
594                                                 intval($profile_uid),
595                                                 intval($attach)
596                                         );
597                                 }
598                         }
599                 }
600         }
601
602         // embedded bookmark or attachment in post? set bookmark flag
603
604         $bookmark = 0;
605         $data = get_attachment_data($body);
606         if (preg_match_all("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/ism", $body, $match, PREG_SET_ORDER) || isset($data["type"])) {
607                 $objecttype = ACTIVITY_OBJ_BOOKMARK;
608                 $bookmark = 1;
609         }
610
611         $body = bb_translate_video($body);
612
613
614         // Fold multi-line [code] sequences
615         $body = preg_replace('/\[\/code\]\s*\[code\]/ism', "\n", $body);
616
617         $body = scale_external_images($body, false);
618
619         // Setting the object type if not defined before
620         if (!$objecttype) {
621                 $objecttype = ACTIVITY_OBJ_NOTE; // Default value
622                 require_once 'include/plaintext.php';
623                 $objectdata = get_attached_data($body);
624
625                 if ($objectdata["type"] == "link") {
626                         $objecttype = ACTIVITY_OBJ_BOOKMARK;
627                 } elseif ($objectdata["type"] == "video") {
628                         $objecttype = ACTIVITY_OBJ_VIDEO;
629                 } elseif ($objectdata["type"] == "photo") {
630                         $objecttype = ACTIVITY_OBJ_IMAGE;
631                 }
632
633         }
634
635         $attachments = '';
636         $match = false;
637
638         if (preg_match_all('/(\[attachment\]([0-9]+)\[\/attachment\])/',$body,$match)) {
639                 foreach ($match[2] as $mtch) {
640                         $r = q("SELECT `id`,`filename`,`filesize`,`filetype` FROM `attach` WHERE `uid` = %d AND `id` = %d LIMIT 1",
641                                 intval($profile_uid),
642                                 intval($mtch)
643                         );
644                         if (DBM::is_result($r)) {
645                                 if (strlen($attachments)) {
646                                         $attachments .= ',';
647                                 }
648                                 $attachments .= '[attach]href="' . System::baseUrl() . '/attach/' . $r[0]['id'] . '" length="' . $r[0]['filesize'] . '" type="' . $r[0]['filetype'] . '" title="' . (($r[0]['filename']) ? $r[0]['filename'] : '') . '"[/attach]';
649                         }
650                         $body = str_replace($match[1],'',$body);
651                 }
652         }
653
654         $wall = 0;
655
656         if (($post_type === 'wall' || $post_type === 'wall-comment') && !count($forum_contact)) {
657                 $wall = 1;
658         }
659
660         if (!strlen($verb)) {
661                 $verb = ACTIVITY_POST;
662         }
663
664         if ($network == "") {
665                 $network = NETWORK_DFRN;
666         }
667
668         $gravity = ($parent ? 6 : 0);
669
670         // even if the post arrived via API we are considering that it
671         // originated on this site by default for determining relayability.
672
673         $origin = (x($_REQUEST, 'origin') ? intval($_REQUEST['origin']) : 1);
674
675         $notify_type = ($parent ? 'comment-new' : 'wall-new');
676
677         $uri = ($message_id ? $message_id : item_new_uri($a->get_hostname(), $profile_uid, $guid));
678
679         // Fallback so that we alway have a parent uri
680         if (!$parent_uri || !$parent) {
681                 $parent_uri = $uri;
682         }
683
684         $datarray = [];
685         $datarray['uid']           = $profile_uid;
686         $datarray['type']          = $post_type;
687         $datarray['wall']          = $wall;
688         $datarray['gravity']       = $gravity;
689         $datarray['network']       = $network;
690         $datarray['contact-id']    = $contact_id;
691         $datarray['owner-name']    = $contact_record['name'];
692         $datarray['owner-link']    = $contact_record['url'];
693         $datarray['owner-avatar']  = $contact_record['thumb'];
694         $datarray['owner-id']      = Contact::getIdForURL($datarray['owner-link'], 0);
695         $datarray['author-name']   = $author['name'];
696         $datarray['author-link']   = $author['url'];
697         $datarray['author-avatar'] = $author['thumb'];
698         $datarray['author-id']     = Contact::getIdForURL($datarray['author-link'], 0);
699         $datarray['created']       = datetime_convert();
700         $datarray['edited']        = datetime_convert();
701         $datarray['commented']     = datetime_convert();
702         $datarray['received']      = datetime_convert();
703         $datarray['changed']       = datetime_convert();
704         $datarray['extid']         = $extid;
705         $datarray['guid']          = $guid;
706         $datarray['uri']           = $uri;
707         $datarray['title']         = $title;
708         $datarray['body']          = $body;
709         $datarray['app']           = $app;
710         $datarray['location']      = $location;
711         $datarray['coord']         = $coord;
712         $datarray['tag']           = $str_tags;
713         $datarray['file']          = $categories;
714         $datarray['inform']        = $inform;
715         $datarray['verb']          = $verb;
716         $datarray['object-type']   = $objecttype;
717         $datarray['allow_cid']     = $str_contact_allow;
718         $datarray['allow_gid']     = $str_group_allow;
719         $datarray['deny_cid']      = $str_contact_deny;
720         $datarray['deny_gid']      = $str_group_deny;
721         $datarray['private']       = $private;
722         $datarray['pubmail']       = $pubmail_enable;
723         $datarray['attach']        = $attachments;
724         $datarray['bookmark']      = intval($bookmark);
725         $datarray['parent-uri']    = $parent_uri;
726         $datarray['postopts']      = $postopts;
727         $datarray['origin']        = $origin;
728         $datarray['moderated']     = false;
729         $datarray['gcontact-id']   = GContact::getId(["url" => $datarray['author-link'], "network" => $datarray['network'],
730                                                         "photo" => $datarray['author-avatar'], "name" => $datarray['author-name']]);
731         $datarray['object']        = $object;
732
733         /*
734          * These fields are for the convenience of addons...
735          * 'self' if true indicates the owner is posting on their own wall
736          * If parent is 0 it is a top-level post.
737          */
738         $datarray['parent']        = $parent;
739         $datarray['self']          = $self;
740
741         // This triggers posts via API and the mirror functions
742         $datarray['api_source'] = $api_source;
743
744         // This field is for storing the raw conversation data
745         $datarray['protocol'] = PROTOCOL_DFRN;
746
747         $r = dba::fetch_first("SELECT `conversation-uri`, `conversation-href` FROM `conversation` WHERE `item-uri` = ?", $datarray['parent-uri']);
748         if (DBM::is_result($r)) {
749                 if ($r['conversation-uri'] != '') {
750                         $datarray['conversation-uri'] = $r['conversation-uri'];
751                 }
752                 if ($r['conversation-href'] != '') {
753                         $datarray['conversation-href'] = $r['conversation-href'];
754                 }
755         }
756
757         if ($orig_post) {
758                 $datarray['edit'] = true;
759         }
760
761         // Search for hashtags
762         item_body_set_hashtags($datarray);
763
764         // preview mode - prepare the body for display and send it via json
765         if ($preview) {
766                 require_once 'include/conversation.php';
767                 // We set the datarray ID to -1 because in preview mode the dataray
768                 // doesn't have an ID.
769                 $datarray["id"] = -1;
770                 $o = conversation($a,[array_merge($contact_record,$datarray)],'search', false, true);
771                 logger('preview: ' . $o);
772                 echo json_encode(['preview' => $o]);
773                 killme();
774         }
775
776         Addon::callHooks('post_local',$datarray);
777
778         if (x($datarray, 'cancel')) {
779                 logger('mod_item: post cancelled by addon.');
780                 if ($return_path) {
781                         goaway($return_path);
782                 }
783
784                 $json = ['cancel' => 1];
785                 if (x($_REQUEST, 'jsreload') && strlen($_REQUEST['jsreload'])) {
786                         $json['reload'] = System::baseUrl() . '/' . $_REQUEST['jsreload'];
787                 }
788
789                 echo json_encode($json);
790                 killme();
791         }
792
793         if ($orig_post) {
794
795                 // Fill the cache field
796                 // This could be done in Item::update as well - but we have to check for the existance of some fields.
797                 put_item_in_cache($datarray);
798
799                 $fields = [
800                         'title' => $datarray['title'],
801                         'body' => $datarray['body'],
802                         'tag' => $datarray['tag'],
803                         'attach' => $datarray['attach'],
804                         'file' => $datarray['file'],
805                         'rendered-html' => $datarray['rendered-html'],
806                         'rendered-hash' => $datarray['rendered-hash'],
807                         'edited' => datetime_convert(),
808                         'changed' => datetime_convert()];
809
810                 Item::update($fields, ['id' => $post_id]);
811
812                 // update filetags in pconfig
813                 file_tag_update_pconfig($uid,$categories_old,$categories_new,'category');
814
815                 if (x($_REQUEST, 'return') && strlen($return_path)) {
816                         logger('return: ' . $return_path);
817                         goaway($return_path);
818                 }
819                 killme();
820         } else {
821                 $post_id = 0;
822         }
823
824         unset($datarray['edit']);
825         unset($datarray['self']);
826         unset($datarray['api_source']);
827
828         $post_id = item_store($datarray);
829
830         if (!$post_id) {
831                 logger("Item wasn't stored.");
832                 goaway($return_path);
833         }
834
835         $datarray = dba::selectFirst('item', [], ['id' => $post_id]);
836
837         if (!DBM::is_result($datarray)) {
838                 logger("Item with id ".$post_id." couldn't be fetched.");
839                 goaway($return_path);
840         }
841
842         // update filetags in pconfig
843         file_tag_update_pconfig($uid, $categories_old, $categories_new, 'category');
844
845         // These notifications are sent if someone else is commenting other your wall
846         if ($parent) {
847                 if ($contact_record != $author) {
848                         notification([
849                                 'type'         => NOTIFY_COMMENT,
850                                 'notify_flags' => $user['notify-flags'],
851                                 'language'     => $user['language'],
852                                 'to_name'      => $user['username'],
853                                 'to_email'     => $user['email'],
854                                 'uid'          => $user['uid'],
855                                 'item'         => $datarray,
856                                 'link'         => System::baseUrl().'/display/'.urlencode($datarray['guid']),
857                                 'source_name'  => $datarray['author-name'],
858                                 'source_link'  => $datarray['author-link'],
859                                 'source_photo' => $datarray['author-avatar'],
860                                 'verb'         => ACTIVITY_POST,
861                                 'otype'        => 'item',
862                                 'parent'       => $parent,
863                                 'parent_uri'   => $parent_item['uri']
864                         ]);
865                 }
866
867                 // Store the comment signature information in case we need to relay to Diaspora
868                 Diaspora::storeCommentSignature($datarray, $author, ($self ? $user['prvkey'] : false), $post_id);
869         } else {
870                 if (($contact_record != $author) && !count($forum_contact)) {
871                         notification([
872                                 'type'         => NOTIFY_WALL,
873                                 'notify_flags' => $user['notify-flags'],
874                                 'language'     => $user['language'],
875                                 'to_name'      => $user['username'],
876                                 'to_email'     => $user['email'],
877                                 'uid'          => $user['uid'],
878                                 'item'         => $datarray,
879                                 'link'         => System::baseUrl().'/display/'.urlencode($datarray['guid']),
880                                 'source_name'  => $datarray['author-name'],
881                                 'source_link'  => $datarray['author-link'],
882                                 'source_photo' => $datarray['author-avatar'],
883                                 'verb'         => ACTIVITY_POST,
884                                 'otype'        => 'item'
885                         ]);
886                 }
887         }
888
889         Addon::callHooks('post_local_end', $datarray);
890
891         if (strlen($emailcc) && $profile_uid == local_user()) {
892                 $erecips = explode(',', $emailcc);
893                 if (count($erecips)) {
894                         foreach ($erecips as $recip) {
895                                 $addr = trim($recip);
896                                 if (!strlen($addr)) {
897                                         continue;
898                                 }
899                                 $disclaimer = '<hr />' . sprintf(t('This message was sent to you by %s, a member of the Friendica social network.'), $a->user['username'])
900                                         . '<br />';
901                                 $disclaimer .= sprintf(t('You may visit them online at %s'), System::baseUrl() . '/profile/' . $a->user['nickname']) . EOL;
902                                 $disclaimer .= t('Please contact the sender by replying to this post if you do not wish to receive these messages.') . EOL;
903                                 if (!$datarray['title']=='') {
904                                         $subject = Email::encodeHeader($datarray['title'], 'UTF-8');
905                                 } else {
906                                         $subject = Email::encodeHeader('[Friendica]' . ' ' . sprintf(t('%s posted an update.'), $a->user['username']), 'UTF-8');
907                                 }
908                                 $link = '<a href="' . System::baseUrl() . '/profile/' . $a->user['nickname'] . '"><img src="' . $author['thumb'] . '" alt="' . $a->user['username'] . '" /></a><br /><br />';
909                                 $html    = prepare_body($datarray);
910                                 $message = '<html><body>' . $link . $html . $disclaimer . '</body></html>';
911                                 include_once 'include/html2plain.php';
912                                 $params =  [
913                                         'fromName' => $a->user['username'],
914                                         'fromEmail' => $a->user['email'],
915                                         'toEmail' => $addr,
916                                         'replyTo' => $a->user['email'],
917                                         'messageSubject' => $subject,
918                                         'htmlVersion' => $message,
919                                         'textVersion' => html2plain($html.$disclaimer)
920                                 ];
921                                 Emailer::send($params);
922                         }
923                 }
924         }
925
926         // Insert an item entry for UID=0 for global entries.
927         // We now do it in the background to save some time.
928         // This is important in interactive environments like the frontend or the API.
929         // We don't fork a new process since this is done anyway with the following command
930         Worker::add(['priority' => PRIORITY_HIGH, 'dont_fork' => true], "CreateShadowEntry", $post_id);
931
932         // Call the background process that is delivering the item to the receivers
933         Worker::add(PRIORITY_HIGH, "Notifier", $notify_type, $post_id);
934
935         logger('post_complete');
936
937         item_post_return(System::baseUrl(), $api_source, $return_path);
938         // NOTREACHED
939 }
940
941 function item_post_return($baseurl, $api_source, $return_path) {
942         // figure out how to return, depending on from whence we came
943
944         if ($api_source) {
945                 return;
946         }
947
948         if ($return_path) {
949                 goaway($return_path);
950         }
951
952         $json = ['success' => 1];
953         if (x($_REQUEST, 'jsreload') && strlen($_REQUEST['jsreload'])) {
954                 $json['reload'] = $baseurl . '/' . $_REQUEST['jsreload'];
955         }
956
957         logger('post_json: ' . print_r($json,true), LOGGER_DEBUG);
958
959         echo json_encode($json);
960         killme();
961 }
962
963
964
965 function item_content(App $a) {
966
967         if (!local_user() && !remote_user()) {
968                 return;
969         }
970
971         require_once 'include/security.php';
972
973         $o = '';
974         if (($a->argc == 3) && ($a->argv[1] === 'drop') && intval($a->argv[2])) {
975                 if (is_ajax()) {
976                         $o = Item::delete($a->argv[2]);
977                 } else {
978                         $o = drop_item($a->argv[2]);
979                 }
980                 if (is_ajax()) {
981                         // ajax return: [<item id>, 0 (no perm) | <owner id>]
982                         echo json_encode([intval($a->argv[2]), intval($o)]);
983                         killme();
984                 }
985         }
986         return $o;
987 }
988
989 /**
990  * This function removes the tag $tag from the text $body and replaces it with
991  * the appropiate link.
992  *
993  * @param App $a Application instance @TODO is unused in this function's scope (excluding included files)
994  * @param unknown_type $body the text to replace the tag in
995  * @param string $inform a comma-seperated string containing everybody to inform
996  * @param string $str_tags string to add the tag to
997  * @param integer $profile_uid
998  * @param string $tag the tag to replace
999  * @param string $network The network of the post
1000  *
1001  * @return boolean true if replaced, false if not replaced
1002  */
1003 function handle_tag(App $a, &$body, &$inform, &$str_tags, $profile_uid, $tag, $network = "")
1004 {
1005         $replaced = false;
1006         $r = null;
1007         $tag_type = '@';
1008
1009         //is it a person tag?
1010         if ((strpos($tag, '@') === 0) || (strpos($tag, '!') === 0)) {
1011                 $tag_type = substr($tag, 0, 1);
1012                 //is it already replaced?
1013                 if (strpos($tag, '[url=')) {
1014                         //append tag to str_tags
1015                         if (!stristr($str_tags, $tag)) {
1016                                 if (strlen($str_tags)) {
1017                                         $str_tags .= ',';
1018                                 }
1019                                 $str_tags .= $tag;
1020                         }
1021
1022                         // Checking for the alias that is used for OStatus
1023                         $pattern = "/[@!]\[url\=(.*?)\](.*?)\[\/url\]/ism";
1024                         if (preg_match($pattern, $tag, $matches)) {
1025
1026                                 $r = q("SELECT `alias`, `name` FROM `contact` WHERE `nurl` = '%s' AND `alias` != '' AND `uid` = 0",
1027                                         normalise_link($matches[1]));
1028                                 if (!DBM::is_result($r)) {
1029                                         $r = q("SELECT `alias`, `name` FROM `gcontact` WHERE `nurl` = '%s' AND `alias` != ''",
1030                                                 normalise_link($matches[1]));
1031                                 }
1032                                 if (DBM::is_result($r)) {
1033                                         $data = $r[0];
1034                                 } else {
1035                                         $data = Probe::uri($matches[1]);
1036                                 }
1037
1038                                 if ($data["alias"] != "") {
1039                                         $newtag = '@[url=' . $data["alias"] . ']' . $data["name"] . '[/url]';
1040                                         if (!stristr($str_tags, $newtag)) {
1041                                                 if (strlen($str_tags)) {
1042                                                         $str_tags .= ',';
1043                                                 }
1044                                                 $str_tags .= $newtag;
1045                                         }
1046                                 }
1047                         }
1048
1049                         return $replaced;
1050                 }
1051                 $stat = false;
1052                 //get the person's name
1053                 $name = substr($tag, 1);
1054
1055                 // Sometimes the tag detection doesn't seem to work right
1056                 // This is some workaround
1057                 $nameparts = explode(" ", $name);
1058                 $name = $nameparts[0];
1059
1060                 // Try to detect the contact in various ways
1061                 if ((strpos($name, '@')) || (strpos($name, 'http://'))) {
1062                         // Is it in format @user@domain.tld or @http://domain.tld/...?
1063
1064                         // First check the contact table for the address
1065                         $r = q("SELECT `id`, `url`, `nick`, `name`, `alias`, `network`, `notify`, `forum`, `prv` FROM `contact`
1066                                 WHERE `addr` = '%s' AND `uid` = %d AND
1067                                         (`network` != '%s' OR (`notify` != '' AND `alias` != ''))
1068                                 LIMIT 1",
1069                                         dbesc($name),
1070                                         intval($profile_uid),
1071                                         dbesc(NETWORK_OSTATUS)
1072                         );
1073
1074                         // Then check in the contact table for the url
1075                         if (!DBM::is_result($r)) {
1076                                 $r = q("SELECT `id`, `url`, `nick`, `name`, `alias`, `network`, `notify`, `forum`, `prv` FROM `contact`
1077                                         WHERE `nurl` = '%s' AND `uid` = %d AND
1078                                                 (`network` != '%s' OR (`notify` != '' AND `alias` != ''))
1079                                         LIMIT 1",
1080                                                 dbesc(normalise_link($name)),
1081                                                 intval($profile_uid),
1082                                                 dbesc(NETWORK_OSTATUS)
1083                                 );
1084                         }
1085
1086                         // Then check in the global contacts for the address
1087                         if (!DBM::is_result($r)) {
1088                                 $r = q("SELECT `url`, `nick`, `name`, `alias`, `network`, `notify` FROM `gcontact`
1089                                         WHERE `addr` = '%s' AND (`network` != '%s' OR (`notify` != '' AND `alias` != ''))
1090                                         LIMIT 1",
1091                                                 dbesc($name),
1092                                                 dbesc(NETWORK_OSTATUS)
1093                                 );
1094                         }
1095
1096                         // Then check in the global contacts for the url
1097                         if (!DBM::is_result($r)) {
1098                                 $r = q("SELECT `url`, `nick`, `name`, `alias`, `network`, `notify` FROM `gcontact`
1099                                         WHERE `nurl` = '%s' AND (`network` != '%s' OR (`notify` != '' AND `alias` != ''))
1100                                         LIMIT 1",
1101                                                 dbesc(normalise_link($name)),
1102                                                 dbesc(NETWORK_OSTATUS)
1103                                 );
1104                         }
1105
1106                         if (!DBM::is_result($r)) {
1107                                 $probed = Probe::uri($name);
1108                                 if ($result['network'] != NETWORK_PHANTOM) {
1109                                         GContact::update($probed);
1110                                         $r = q("SELECT `url`, `name`, `nick`, `network`, `alias`, `notify` FROM `gcontact` WHERE `nurl` = '%s' LIMIT 1",
1111                                                 dbesc(normalise_link($probed["url"])));
1112                                 }
1113                         }
1114                 } else {
1115                         $r = false;
1116                         if (strrpos($name, '+')) {
1117                                 // Is it in format @nick+number?
1118                                 $tagcid = intval(substr($name, strrpos($name, '+') + 1));
1119
1120                                 $r = q("SELECT `id`, `url`, `nick`, `name`, `alias`, `network` FROM `contact` WHERE `id` = %d AND `uid` = %d LIMIT 1",
1121                                                 intval($tagcid),
1122                                                 intval($profile_uid)
1123                                 );
1124                         }
1125
1126                         // select someone by attag or nick and the name passed in the current network
1127                         if (!DBM::is_result($r) && ($network != ""))
1128                                 $r = q("SELECT `id`, `url`, `nick`, `name`, `alias`, `network` FROM `contact` WHERE `attag` = '%s' OR `nick` = '%s' AND `network` = '%s' AND `uid` = %d ORDER BY `attag` DESC LIMIT 1",
1129                                                 dbesc($name),
1130                                                 dbesc($name),
1131                                                 dbesc($network),
1132                                                 intval($profile_uid)
1133                                 );
1134
1135                         //select someone from this user's contacts by name in the current network
1136                         if (!DBM::is_result($r) && ($network != "")) {
1137                                 $r = q("SELECT `id`, `url`, `nick`, `name`, `alias`, `network` FROM `contact` WHERE `name` = '%s' AND `network` = '%s' AND `uid` = %d LIMIT 1",
1138                                                 dbesc($name),
1139                                                 dbesc($network),
1140                                                 intval($profile_uid)
1141                                 );
1142                         }
1143
1144                         // select someone by attag or nick and the name passed in
1145                         if (!DBM::is_result($r)) {
1146                                 $r = q("SELECT `id`, `url`, `nick`, `name`, `alias`, `network` FROM `contact` WHERE `attag` = '%s' OR `nick` = '%s' AND `uid` = %d ORDER BY `attag` DESC LIMIT 1",
1147                                                 dbesc($name),
1148                                                 dbesc($name),
1149                                                 intval($profile_uid)
1150                                 );
1151                         }
1152
1153                         // select someone from this user's contacts by name
1154                         if (!DBM::is_result($r)) {
1155                                 $r = q("SELECT `id`, `url`, `nick`, `name`, `alias`, `network` FROM `contact` WHERE `name` = '%s' AND `uid` = %d LIMIT 1",
1156                                                 dbesc($name),
1157                                                 intval($profile_uid)
1158                                 );
1159                         }
1160                 }
1161
1162                 if (DBM::is_result($r)) {
1163                         if (strlen($inform) && (isset($r[0]["notify"]) || isset($r[0]["id"]))) {
1164                                 $inform .= ',';
1165                         }
1166
1167                         if (isset($r[0]["id"])) {
1168                                 $inform .= 'cid:' . $r[0]["id"];
1169                         } elseif (isset($r[0]["notify"])) {
1170                                 $inform  .= $r[0]["notify"];
1171                         }
1172
1173                         $profile = $r[0]["url"];
1174                         $alias   = $r[0]["alias"];
1175                         $newname = $r[0]["nick"];
1176                         if (($newname == "") || (($r[0]["network"] != NETWORK_OSTATUS) && ($r[0]["network"] != NETWORK_TWITTER)
1177                                 && ($r[0]["network"] != NETWORK_STATUSNET) && ($r[0]["network"] != NETWORK_APPNET))) {
1178                                 $newname = $r[0]["name"];
1179                         }
1180                 }
1181
1182                 //if there is an url for this persons profile
1183                 if (isset($profile) && ($newname != "")) {
1184                         $replaced = true;
1185                         // create profile link
1186                         $profile = str_replace(',', '%2c', $profile);
1187                         $newtag = $tag_type.'[url=' . $profile . ']' . $newname . '[/url]';
1188                         $body = str_replace($tag_type . $name, $newtag, $body);
1189                         // append tag to str_tags
1190                         if (!stristr($str_tags, $newtag)) {
1191                                 if (strlen($str_tags)) {
1192                                         $str_tags .= ',';
1193                                 }
1194                                 $str_tags .= $newtag;
1195                         }
1196
1197                         /*
1198                          * Status.Net seems to require the numeric ID URL in a mention if the person isn't
1199                          * subscribed to you. But the nickname URL is OK if they are. Grrr. We'll tag both.
1200                          */
1201                         if (strlen($alias)) {
1202                                 $newtag = '@[url=' . $alias . ']' . $newname . '[/url]';
1203                                 if (!stristr($str_tags, $newtag)) {
1204                                         if (strlen($str_tags)) {
1205                                                 $str_tags .= ',';
1206                                         }
1207                                         $str_tags .= $newtag;
1208                                 }
1209                         }
1210                 }
1211         }
1212
1213         return ['replaced' => $replaced, 'contact' => $r[0]];
1214 }