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