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