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