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