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