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