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