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