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