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