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