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