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