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