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