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