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