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