]> git.mxchange.org Git - friendica.git/blob - mod/item.php
cbe338c4f89f7a0f4590dcc2b1678b5099d55190
[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) && ($thrparent[0]["network"] === NETWORK_OSTATUS)
143                                 && (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 != '') && ($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                                 && ($parent_item['network'] != NETWORK_OSTATUS)
313                                 && ($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) || 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 && ($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         dba::transaction();
813
814         $r = q("INSERT INTO `item` (`guid`, `extid`, `uid`,`type`,`wall`,`gravity`, `network`, `contact-id`,
815                                         `owner-name`,`owner-link`,`owner-avatar`, `owner-id`,
816                                         `author-name`, `author-link`, `author-avatar`, `author-id`,
817                                         `created`, `edited`, `commented`, `received`, `changed`,
818                                         `uri`, `thr-parent`, `title`, `body`, `app`, `location`, `coord`,
819                                         `tag`, `inform`, `verb`, `object-type`, `postopts`,
820                                         `allow_cid`, `allow_gid`, `deny_cid`, `deny_gid`, `private`,
821                                         `pubmail`, `attach`, `bookmark`,`origin`, `moderated`, `file`,
822                                         `rendered-html`, `rendered-hash`, `gcontact-id`, `object`,
823                                         `parent`, `parent-uri`, `plink`, `last-child`, `visible`)
824                 VALUES('%s', '%s', %d, '%s', %d, %d, '%s', %d,
825                         '%s', '%s', '%s', %d,
826                         '%s', '%s', '%s', %d,
827                         '%s', '%s', '%s', '%s', '%s',
828                         '%s', '%s', '%s', '%s', '%s', '%s', '%s',
829                         '%s', '%s', '%s', '%s', '%s',
830                         '%s', '%s', '%s', '%s', %d,
831                         %d, '%s', %d, %d, %d, '%s',
832                         '%s', '%s', %d, '%s',
833                         %d, '%s', '%s', %d, %d)",
834                 dbesc($datarray['guid']),
835                 dbesc($datarray['extid']),
836                 intval($datarray['uid']),
837                 dbesc($datarray['type']),
838                 intval($datarray['wall']),
839                 intval($datarray['gravity']),
840                 dbesc($datarray['network']),
841                 intval($datarray['contact-id']),
842                 dbesc($datarray['owner-name']),
843                 dbesc($datarray['owner-link']),
844                 dbesc($datarray['owner-avatar']),
845                 intval($datarray['owner-id']),
846                 dbesc($datarray['author-name']),
847                 dbesc($datarray['author-link']),
848                 dbesc($datarray['author-avatar']),
849                 intval($datarray['author-id']),
850                 dbesc($datarray['created']),
851                 dbesc($datarray['edited']),
852                 dbesc($datarray['commented']),
853                 dbesc($datarray['received']),
854                 dbesc($datarray['changed']),
855                 dbesc($datarray['uri']),
856                 dbesc($datarray['thr-parent']),
857                 dbesc($datarray['title']),
858                 dbesc($datarray['body']),
859                 dbesc($datarray['app']),
860                 dbesc($datarray['location']),
861                 dbesc($datarray['coord']),
862                 dbesc($datarray['tag']),
863                 dbesc($datarray['inform']),
864                 dbesc($datarray['verb']),
865                 dbesc($datarray['object-type']),
866                 dbesc($datarray['postopts']),
867                 dbesc($datarray['allow_cid']),
868                 dbesc($datarray['allow_gid']),
869                 dbesc($datarray['deny_cid']),
870                 dbesc($datarray['deny_gid']),
871                 intval($datarray['private']),
872                 intval($datarray['pubmail']),
873                 dbesc($datarray['attach']),
874                 intval($datarray['bookmark']),
875                 intval($datarray['origin']),
876                 intval($datarray['moderated']),
877                 dbesc($datarray['file']),
878                 dbesc($datarray['rendered-html']),
879                 dbesc($datarray['rendered-hash']),
880                 intval($datarray['gcontact-id']),
881                 dbesc($datarray['object']),
882                 intval($datarray['parent']),
883                 dbesc($datarray['parent-uri']),
884                 dbesc($datarray['plink']),
885                 intval($datarray['last-child']),
886                 intval($datarray['visible'])
887         );
888
889         if (dbm::is_result($r)) {
890                 $post_id = dba::lastInsertId();
891         } else {
892                 logger('mod_item: unable to create post.');
893                 $post_id = 0;
894         }
895
896         if ($post_id == 0) {
897                 dba::commit();
898                 logger('mod_item: unable to retrieve post that was just stored.');
899                 notice(t('System error. Post not saved.') . EOL);
900                 goaway($return_path);
901                 // NOTREACHED
902         }
903
904         logger('mod_item: saved item ' . $post_id);
905
906         $datarray["id"] = $post_id;
907
908         item_set_last_item($datarray);
909
910         // update filetags in pconfig
911         file_tag_update_pconfig($uid,$categories_old,$categories_new,'category');
912
913         if ($parent) {
914
915                 // This item is the last leaf and gets the comment box, clear any ancestors
916                 $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent` = %d AND `last-child` AND `id` != %d",
917                         dbesc(datetime_convert()),
918                         intval($parent),
919                         intval($post_id)
920                 );
921
922                 // update the commented timestamp on the parent
923                 q("UPDATE `item` SET `visible` = 1, `commented` = '%s', `changed` = '%s' WHERE `id` = %d",
924                         dbesc(datetime_convert()),
925                         dbesc(datetime_convert()),
926                         intval($parent)
927                 );
928
929                 if ($contact_record != $author) {
930                         notification(array(
931                                 'type'         => NOTIFY_COMMENT,
932                                 'notify_flags' => $user['notify-flags'],
933                                 'language'     => $user['language'],
934                                 'to_name'      => $user['username'],
935                                 'to_email'     => $user['email'],
936                                 'uid'          => $user['uid'],
937                                 'item'         => $datarray,
938                                 'link'         => App::get_baseurl().'/display/'.urlencode($datarray['guid']),
939                                 'source_name'  => $datarray['author-name'],
940                                 'source_link'  => $datarray['author-link'],
941                                 'source_photo' => $datarray['author-avatar'],
942                                 'verb'         => ACTIVITY_POST,
943                                 'otype'        => 'item',
944                                 'parent'       => $parent,
945                                 'parent_uri'   => $parent_item['uri']
946                         ));
947
948                 }
949
950
951                 // Store the comment signature information in case we need to relay to Diaspora
952                 Diaspora::store_comment_signature($datarray, $author, ($self ? $user['prvkey'] : false), $post_id);
953
954         } else {
955                 $parent = $post_id;
956
957                 $r = q("UPDATE `item` SET `parent` = %d WHERE `id` = %d",
958                         intval($parent),
959                         intval($post_id));
960
961                 if ($contact_record != $author) {
962                         notification(array(
963                                 'type'         => NOTIFY_WALL,
964                                 'notify_flags' => $user['notify-flags'],
965                                 'language'     => $user['language'],
966                                 'to_name'      => $user['username'],
967                                 'to_email'     => $user['email'],
968                                 'uid'          => $user['uid'],
969                                 'item'         => $datarray,
970                                 'link'         => App::get_baseurl().'/display/'.urlencode($datarray['guid']),
971                                 'source_name'  => $datarray['author-name'],
972                                 'source_link'  => $datarray['author-link'],
973                                 'source_photo' => $datarray['author-avatar'],
974                                 'verb'         => ACTIVITY_POST,
975                                 'otype'        => 'item'
976                         ));
977                 }
978         }
979
980         call_hooks('post_local_end', $datarray);
981
982         if (strlen($emailcc) && $profile_uid == local_user()) {
983                 $erecips = explode(',', $emailcc);
984                 if (count($erecips)) {
985                         foreach ($erecips as $recip) {
986                                 $addr = trim($recip);
987                                 if (! strlen($addr)) {
988                                         continue;
989                                 }
990                                 $disclaimer = '<hr />' . sprintf( t('This message was sent to you by %s, a member of the Friendica social network.'), $a->user['username'])
991                                         . '<br />';
992                                 $disclaimer .= sprintf( t('You may visit them online at %s'), App::get_baseurl() . '/profile/' . $a->user['nickname']) . EOL;
993                                 $disclaimer .= t('Please contact the sender by replying to this post if you do not wish to receive these messages.') . EOL;
994                                 if (!$datarray['title']=='') {
995                                         $subject = email_header_encode($datarray['title'], 'UTF-8');
996                                 } else {
997                                         $subject = email_header_encode('[Friendica]' . ' ' . sprintf( t('%s posted an update.'), $a->user['username']), 'UTF-8');
998                                 }
999                                 $link = '<a href="' . App::get_baseurl() . '/profile/' . $a->user['nickname'] . '"><img src="' . $author['thumb'] . '" alt="' . $a->user['username'] . '" /></a><br /><br />';
1000                                 $html    = prepare_body($datarray);
1001                                 $message = '<html><body>' . $link . $html . $disclaimer . '</body></html>';
1002                                 include_once 'include/html2plain.php';
1003                                 $params = array (
1004                                     'fromName' => $a->user['username'],
1005                                     'fromEmail' => $a->user['email'],
1006                                     'toEmail' => $addr,
1007                                     'replyTo' => $a->user['email'],
1008                                     'messageSubject' => $subject,
1009                                     'htmlVersion' => $message,
1010                                     'textVersion' => html2plain($html.$disclaimer),
1011                                 );
1012                                 Emailer::send($params);
1013                         }
1014                 }
1015         }
1016
1017         if ($post_id == $parent) {
1018                 add_thread($post_id);
1019         } else {
1020                 update_thread($parent, true);
1021         }
1022
1023         dba::commit();
1024
1025         create_tags_from_item($post_id);
1026         create_files_from_item($post_id);
1027
1028         // Insert an item entry for UID=0 for global entries.
1029         // We now do it in the background to save some time.
1030         // This is important in interactive environments like the frontend or the API.
1031         // We don't fork a new process since this is done anyway with the following command
1032         proc_run(array('priority' => PRIORITY_HIGH, 'dont_fork' => true), "include/create_shadowentry.php", $post_id);
1033
1034         // Call the background process that is delivering the item to the receivers
1035         proc_run(PRIORITY_HIGH, "include/notifier.php", $notify_type, $post_id);
1036
1037         logger('post_complete');
1038
1039         item_post_return(App::get_baseurl(), $api_source, $return_path);
1040         // NOTREACHED
1041 }
1042
1043 function item_post_return($baseurl, $api_source, $return_path) {
1044         // figure out how to return, depending on from whence we came
1045
1046         if ($api_source) {
1047                 return;
1048         }
1049
1050         if ($return_path) {
1051                 goaway($return_path);
1052         }
1053
1054         $json = array('success' => 1);
1055         if (x($_REQUEST, 'jsreload') && strlen($_REQUEST['jsreload'])) {
1056                 $json['reload'] = $baseurl . '/' . $_REQUEST['jsreload'];
1057         }
1058
1059         logger('post_json: ' . print_r($json,true), LOGGER_DEBUG);
1060
1061         echo json_encode($json);
1062         killme();
1063 }
1064
1065
1066
1067 function item_content(App $a) {
1068
1069         if ((! local_user()) && (! remote_user())) {
1070                 return;
1071         }
1072
1073         require_once 'include/security.php';
1074
1075         $o = '';
1076         if (($a->argc == 3) && ($a->argv[1] === 'drop') && intval($a->argv[2])) {
1077                 $o = drop_item($a->argv[2], !is_ajax());
1078                 if (is_ajax()) {
1079                         // ajax return: [<item id>, 0 (no perm) | <owner id>]
1080                         echo json_encode(array(intval($a->argv[2]), intval($o)));
1081                         killme();
1082                 }
1083         }
1084         return $o;
1085 }
1086
1087 /**
1088  * This function removes the tag $tag from the text $body and replaces it with
1089  * the appropiate link.
1090  *
1091  * @param App $a Application instance @TODO is unused in this function's scope (excluding included files)
1092  * @param unknown_type $body the text to replace the tag in
1093  * @param string $inform a comma-seperated string containing everybody to inform
1094  * @param string $str_tags string to add the tag to
1095  * @param integer $profile_uid
1096  * @param string $tag the tag to replace
1097  * @param string $network The network of the post
1098  *
1099  * @return boolean true if replaced, false if not replaced
1100  */
1101 function handle_tag(App $a, &$body, &$inform, &$str_tags, $profile_uid, $tag, $network = "") {
1102         require_once 'include/socgraph.php';
1103
1104         $replaced = false;
1105         $r = null;
1106
1107         //is it a person tag?
1108         if (strpos($tag, '@') === 0) {
1109                 //is it already replaced?
1110                 if (strpos($tag, '[url=')) {
1111                         //append tag to str_tags
1112                         if (!stristr($str_tags, $tag)) {
1113                                 if (strlen($str_tags)) {
1114                                         $str_tags .= ',';
1115                                 }
1116                                 $str_tags .= $tag;
1117                         }
1118
1119                         // Checking for the alias that is used for OStatus
1120                         $pattern = "/@\[url\=(.*?)\](.*?)\[\/url\]/ism";
1121                         if (preg_match($pattern, $tag, $matches)) {
1122
1123                                 $r = q("SELECT `alias`, `name` FROM `contact` WHERE `nurl` = '%s' AND `alias` != '' AND `uid` = 0",
1124                                         normalise_link($matches[1]));
1125                                 if (!dbm::is_result($r)) {
1126                                         $r = q("SELECT `alias`, `name` FROM `gcontact` WHERE `nurl` = '%s' AND `alias` != ''",
1127                                                 normalise_link($matches[1]));
1128                                 }
1129                                 if (dbm::is_result($r)) {
1130                                         $data = $r[0];
1131                                 } else {
1132                                         $data = probe_url($matches[1]);
1133                                 }
1134
1135                                 if ($data["alias"] != "") {
1136                                         $newtag = '@[url=' . $data["alias"] . ']' . $data["name"] . '[/url]';
1137                                         if (!stristr($str_tags, $newtag)) {
1138                                                 if (strlen($str_tags)) {
1139                                                         $str_tags .= ',';
1140                                                 }
1141                                                 $str_tags .= $newtag;
1142                                         }
1143                                 }
1144                         }
1145
1146                         return $replaced;
1147                 }
1148                 $stat = false;
1149                 //get the person's name
1150                 $name = substr($tag, 1);
1151
1152                 // Sometimes the tag detection doesn't seem to work right
1153                 // This is some workaround
1154                 $nameparts = explode(" ", $name);
1155                 $name = $nameparts[0];
1156
1157                 // Try to detect the contact in various ways
1158                 if ((strpos($name, '@')) || (strpos($name, 'http://'))) {
1159                         // Is it in format @user@domain.tld or @http://domain.tld/...?
1160
1161                         // First check the contact table for the address
1162                         $r = q("SELECT `id`, `url`, `nick`, `name`, `alias`, `network`, `notify` FROM `contact`
1163                                 WHERE `addr` = '%s' AND `uid` = %d AND
1164                                         (`network` != '%s' OR (`notify` != '' AND `alias` != ''))
1165                                 LIMIT 1",
1166                                         dbesc($name),
1167                                         intval($profile_uid),
1168                                         dbesc(NETWORK_OSTATUS)
1169                         );
1170
1171                         // Then check in the contact table for the url
1172                         if (!dbm::is_result($r)) {
1173                                 $r = q("SELECT `id`, `url`, `nick`, `name`, `alias`, `network`, `notify` FROM `contact`
1174                                         WHERE `nurl` = '%s' AND `uid` = %d AND
1175                                                 (`network` != '%s' OR (`notify` != '' AND `alias` != ''))
1176                                         LIMIT 1",
1177                                                 dbesc(normalise_link($name)),
1178                                                 intval($profile_uid),
1179                                                 dbesc(NETWORK_OSTATUS)
1180                                 );
1181                         }
1182
1183                         // Then check in the global contacts for the address
1184                         if (!dbm::is_result($r)) {
1185                                 $r = q("SELECT `url`, `nick`, `name`, `alias`, `network`, `notify` FROM `gcontact`
1186                                         WHERE `addr` = '%s' AND (`network` != '%s' OR (`notify` != '' AND `alias` != ''))
1187                                         LIMIT 1",
1188                                                 dbesc($name),
1189                                                 dbesc(NETWORK_OSTATUS)
1190                                 );
1191                         }
1192
1193                         // Then check in the global contacts for the url
1194                         if (!dbm::is_result($r)) {
1195                                 $r = q("SELECT `url`, `nick`, `name`, `alias`, `network`, `notify` FROM `gcontact`
1196                                         WHERE `nurl` = '%s' AND (`network` != '%s' OR (`notify` != '' AND `alias` != ''))
1197                                         LIMIT 1",
1198                                                 dbesc(normalise_link($name)),
1199                                                 dbesc(NETWORK_OSTATUS)
1200                                 );
1201                         }
1202
1203                         if (!dbm::is_result($r)) {
1204                                 $probed = probe_url($name);
1205                                 if ($result['network'] != NETWORK_PHANTOM) {
1206                                         update_gcontact($probed);
1207                                         $r = q("SELECT `url`, `name`, `nick`, `network`, `alias`, `notify` FROM `gcontact` WHERE `nurl` = '%s' LIMIT 1",
1208                                                 dbesc(normalise_link($probed["url"])));
1209                                 }
1210                         }
1211                 } else {
1212                         $r = false;
1213                         if (strrpos($name, '+')) {
1214                                 // Is it in format @nick+number?
1215                                 $tagcid = intval(substr($name, strrpos($name, '+') + 1));
1216
1217                                 $r = q("SELECT `id`, `url`, `nick`, `name`, `alias`, `network` FROM `contact` WHERE `id` = %d AND `uid` = %d LIMIT 1",
1218                                                 intval($tagcid),
1219                                                 intval($profile_uid)
1220                                 );
1221                         }
1222
1223                         // select someone by attag or nick and the name passed in the current network
1224                         if(!dbm::is_result($r) && ($network != ""))
1225                                 $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",
1226                                                 dbesc($name),
1227                                                 dbesc($name),
1228                                                 dbesc($network),
1229                                                 intval($profile_uid)
1230                                 );
1231
1232                         //select someone from this user's contacts by name in the current network
1233                         if (!dbm::is_result($r) && ($network != "")) {
1234                                 $r = q("SELECT `id`, `url`, `nick`, `name`, `alias`, `network` FROM `contact` WHERE `name` = '%s' AND `network` = '%s' AND `uid` = %d LIMIT 1",
1235                                                 dbesc($name),
1236                                                 dbesc($network),
1237                                                 intval($profile_uid)
1238                                 );
1239                         }
1240
1241                         // select someone by attag or nick and the name passed in
1242                         if(!dbm::is_result($r)) {
1243                                 $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",
1244                                                 dbesc($name),
1245                                                 dbesc($name),
1246                                                 intval($profile_uid)
1247                                 );
1248                         }
1249
1250                         // select someone from this user's contacts by name
1251                         if(!dbm::is_result($r)) {
1252                                 $r = q("SELECT `id`, `url`, `nick`, `name`, `alias`, `network` FROM `contact` WHERE `name` = '%s' AND `uid` = %d LIMIT 1",
1253                                                 dbesc($name),
1254                                                 intval($profile_uid)
1255                                 );
1256                         }
1257                 }
1258
1259                 if (dbm::is_result($r)) {
1260                         if (strlen($inform) && (isset($r[0]["notify"]) || isset($r[0]["id"]))) {
1261                                 $inform .= ',';
1262                         }
1263
1264                         if (isset($r[0]["id"])) {
1265                                 $inform .= 'cid:' . $r[0]["id"];
1266                         } elseif (isset($r[0]["notify"])) {
1267                                 $inform  .= $r[0]["notify"];
1268                         }
1269
1270                         $profile = $r[0]["url"];
1271                         $alias   = $r[0]["alias"];
1272                         $newname = $r[0]["nick"];
1273                         if (($newname == "") || (($r[0]["network"] != NETWORK_OSTATUS) && ($r[0]["network"] != NETWORK_TWITTER)
1274                                 && ($r[0]["network"] != NETWORK_STATUSNET) && ($r[0]["network"] != NETWORK_APPNET))) {
1275                                 $newname = $r[0]["name"];
1276                         }
1277                 }
1278
1279                 //if there is an url for this persons profile
1280                 if (isset($profile) && ($newname != "")) {
1281
1282                         $replaced = true;
1283                         // create profile link
1284                         $profile = str_replace(',', '%2c', $profile);
1285                         $newtag = '@[url=' . $profile . ']' . $newname . '[/url]';
1286                         $body = str_replace('@' . $name, $newtag, $body);
1287                         // append tag to str_tags
1288                         if (! stristr($str_tags, $newtag)) {
1289                                 if (strlen($str_tags)) {
1290                                         $str_tags .= ',';
1291                                 }
1292                                 $str_tags .= $newtag;
1293                         }
1294
1295                         /*
1296                          * Status.Net seems to require the numeric ID URL in a mention if the person isn't
1297                          * subscribed to you. But the nickname URL is OK if they are. Grrr. We'll tag both.
1298                          */
1299                         if (strlen($alias)) {
1300                                 $newtag = '@[url=' . $alias . ']' . $newname . '[/url]';
1301                                 if (! stristr($str_tags, $newtag)) {
1302                                         if (strlen($str_tags)) {
1303                                                 $str_tags .= ',';
1304                                         }
1305                                         $str_tags .= $newtag;
1306                                 }
1307                         }
1308                 }
1309         }
1310
1311         return array('replaced' => $replaced, 'contact' => $r[0]);
1312 }