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