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