]> git.mxchange.org Git - friendica.git/blob - mod/item.php
0466c46d9d407e642cc56e76d05b226b03fc76f3
[friendica.git] / mod / item.php
1 <?php
2 /**
3  * @file mod/item.php
4  */
5
6 /*
7  * This is the POST destination for most all locally posted
8  * text stuff. This function handles status, wall-to-wall status,
9  * local comments, and remote coments that are posted on this site
10  * (as opposed to being delivered in a feed).
11  * Also processed here are posts and comments coming through the
12  * statusnet/twitter API.
13  *
14  * All of these become an "item" which is our basic unit of
15  * information.
16  */
17
18 use Friendica\App;
19 use Friendica\Content\Text\BBCode;
20 use Friendica\Content\Text\HTML;
21 use Friendica\Core\Addon;
22 use Friendica\Core\Config;
23 use Friendica\Core\L10n;
24 use Friendica\Core\System;
25 use Friendica\Core\Worker;
26 use Friendica\Database\DBA;
27 use Friendica\Model\Contact;
28 use Friendica\Model\Item;
29 use Friendica\Protocol\Diaspora;
30 use Friendica\Protocol\Email;
31 use Friendica\Util\DateTimeFormat;
32 use Friendica\Util\Emailer;
33
34 require_once 'include/enotify.php';
35 require_once 'include/text.php';
36 require_once 'include/items.php';
37
38 function item_post(App $a) {
39         if (!local_user() && !remote_user()) {
40                 return;
41         }
42
43         require_once 'include/security.php';
44
45         $uid = local_user();
46
47         if (x($_REQUEST, 'dropitems')) {
48                 $arr_drop = explode(',', $_REQUEST['dropitems']);
49                 drop_items($arr_drop);
50                 $json = ['success' => 1];
51                 echo json_encode($json);
52                 killme();
53         }
54
55         Addon::callHooks('post_local_start', $_REQUEST);
56
57         logger('postvars ' . print_r($_REQUEST,true), LOGGER_DATA);
58
59         $api_source = defaults($_REQUEST, 'api_source', false);
60
61         $message_id = ((x($_REQUEST, 'message_id') && $api_source) ? strip_tags($_REQUEST['message_id']) : '');
62
63         $return_path = defaults($_REQUEST, 'return', '');
64         $preview = intval(defaults($_REQUEST, 'preview', 0));
65
66         /*
67          * Check for doubly-submitted posts, and reject duplicates
68          * Note that we have to ignore previews, otherwise nothing will post
69          * after it's been previewed
70          */
71         if (!$preview && x($_REQUEST, 'post_id_random')) {
72                 if (x($_SESSION, 'post-random') && $_SESSION['post-random'] == $_REQUEST['post_id_random']) {
73                         logger("item post: duplicate post", LOGGER_DEBUG);
74                         item_post_return(System::baseUrl(), $api_source, $return_path);
75                 } else {
76                         $_SESSION['post-random'] = $_REQUEST['post_id_random'];
77                 }
78         }
79
80         // Is this a reply to something?
81         $thr_parent = intval(defaults($_REQUEST, 'parent', 0));
82         $thr_parent_uri = trim(defaults($_REQUEST, 'parent_uri', ''));
83
84         $thr_parent_contact = null;
85
86         $parent = 0;
87         $parent_item = null;
88         $parent_user = null;
89
90         $parent_contact = null;
91
92         $objecttype = null;
93         $profile_uid = defaults($_REQUEST, 'profile_uid', local_user());
94         $posttype = defaults($_REQUEST, 'post_type', Item::PT_ARTICLE);
95
96         if ($thr_parent || $thr_parent_uri) {
97                 if ($thr_parent) {
98                         $parent_item = Item::selectFirst([], ['id' => $thr_parent]);
99                 } elseif ($thr_parent_uri) {
100                         $parent_item = Item::selectFirst([], ['uri' => $thr_parent_uri, 'uid' => $profile_uid]);
101                 }
102
103                 // if this isn't the real parent of the conversation, find it
104                 if (DBA::isResult($parent_item)) {
105
106                         // The URI and the contact is taken from the direct parent which needn't to be the top parent
107                         $thr_parent_uri = $parent_item['uri'];
108                         $thr_parent_contact = Contact::getDetailsByURL($parent_item["author-link"]);
109
110                         if ($parent_item['id'] != $parent_item['parent']) {
111                                 $parent_item = Item::selectFirst(Item::ITEM_FIELDLIST, ['id' => $parent_item['parent']]);
112                         }
113                 }
114
115                 if (!DBA::isResult($parent_item)) {
116                         notice(L10n::t('Unable to locate original post.') . EOL);
117                         if (x($_REQUEST, 'return')) {
118                                 goaway($return_path);
119                         }
120                         killme();
121                 }
122
123                 $parent = $parent_item['id'];
124                 $parent_user = $parent_item['uid'];
125
126                 $parent_contact = Contact::getDetailsByURL($parent_item["author-link"]);
127
128                 $objecttype = ACTIVITY_OBJ_COMMENT;
129         }
130
131         if ($parent) {
132                 logger('mod_item: item_post parent=' . $parent);
133         }
134
135         $post_id     = intval(defaults($_REQUEST, 'post_id', 0));
136         $app         = strip_tags(defaults($_REQUEST, 'source', ''));
137         $extid       = strip_tags(defaults($_REQUEST, 'extid', ''));
138         $object      = defaults($_REQUEST, 'object', '');
139         $wall        = intval(defaults($_REQUEST, 'wall', 1));
140
141         // Ensure that the user id in a thread always stay the same
142         if (!is_null($parent_user) && in_array($parent_user, [local_user(), 0])) {
143                 $profile_uid = $parent_user;
144         }
145
146         // Check for multiple posts with the same message id (when the post was created via API)
147         if (($message_id != '') && ($profile_uid != 0)) {
148                 if (DBA::exists('item', ['uri' => $message_id, 'uid' => $profile_uid])) {
149                         logger("Message with URI ".$message_id." already exists for user ".$profile_uid, LOGGER_DEBUG);
150                         return;
151                 }
152         }
153
154         // Allow commenting if it is an answer to a public post
155         $allow_comment = local_user() && ($profile_uid == 0) && $parent && in_array($parent_item['network'], [NETWORK_OSTATUS, NETWORK_DIASPORA, NETWORK_DFRN]);
156
157         // Now check that valid personal details have been provided
158         if (!can_write_wall($profile_uid) && !$allow_comment) {
159                 notice(L10n::t('Permission denied.') . EOL) ;
160
161                 if (x($_REQUEST, 'return')) {
162                         goaway($return_path);
163                 }
164
165                 killme();
166         }
167
168         // Init post instance
169         $orig_post = null;
170
171         // is this an edited post?
172         if ($post_id > 0) {
173                 $orig_post = Item::selectFirst(Item::ITEM_FIELDLIST, ['id' => $post_id]);
174         }
175
176         $user = DBA::selectFirst('user', [], ['uid' => $profile_uid]);
177
178         if (!DBA::isResult($user) && !$parent) {
179                 return;
180         }
181
182         $categories = '';
183         $postopts = '';
184         $emailcc = '';
185
186         if (!empty($orig_post)) {
187                 $str_group_allow   = $orig_post['allow_gid'];
188                 $str_contact_allow = $orig_post['allow_cid'];
189                 $str_group_deny    = $orig_post['deny_gid'];
190                 $str_contact_deny  = $orig_post['deny_cid'];
191                 $location          = $orig_post['location'];
192                 $coord             = $orig_post['coord'];
193                 $verb              = $orig_post['verb'];
194                 $objecttype        = $orig_post['object-type'];
195                 $app               = $orig_post['app'];
196                 $categories        = $orig_post['file'];
197                 $title             = notags(trim($_REQUEST['title']));
198                 $body              = escape_tags(trim($_REQUEST['body']));
199                 $private           = $orig_post['private'];
200                 $pubmail_enabled   = $orig_post['pubmail'];
201                 $network           = $orig_post['network'];
202                 $guid              = $orig_post['guid'];
203                 $extid             = $orig_post['extid'];
204
205         } else {
206
207                 /*
208                  * if coming from the API and no privacy settings are set,
209                  * use the user default permissions - as they won't have
210                  * been supplied via a form.
211                  */
212                 if ($api_source
213                         && !array_key_exists('contact_allow', $_REQUEST)
214                         && !array_key_exists('group_allow', $_REQUEST)
215                         && !array_key_exists('contact_deny', $_REQUEST)
216                         && !array_key_exists('group_deny', $_REQUEST)) {
217                         $str_group_allow   = $user['allow_gid'];
218                         $str_contact_allow = $user['allow_cid'];
219                         $str_group_deny    = $user['deny_gid'];
220                         $str_contact_deny  = $user['deny_cid'];
221                 } else {
222                         // use the posted permissions
223                         $str_group_allow   = perms2str(defaults($_REQUEST, 'group_allow', ''));
224                         $str_contact_allow = perms2str(defaults($_REQUEST, 'contact_allow', ''));
225                         $str_group_deny    = perms2str(defaults($_REQUEST, 'group_deny', ''));
226                         $str_contact_deny  = perms2str(defaults($_REQUEST, 'contact_deny', ''));
227                 }
228
229                 $title             =      notags(trim(defaults($_REQUEST, 'title'   , '')));
230                 $location          =      notags(trim(defaults($_REQUEST, 'location', '')));
231                 $coord             =      notags(trim(defaults($_REQUEST, 'coord'   , '')));
232                 $verb              =      notags(trim(defaults($_REQUEST, 'verb'    , '')));
233                 $emailcc           =      notags(trim(defaults($_REQUEST, 'emailcc' , '')));
234                 $body              = escape_tags(trim(defaults($_REQUEST, 'body'    , '')));
235                 $network           =      notags(trim(defaults($_REQUEST, 'network' , NETWORK_DFRN)));
236                 $guid              =      System::createGUID(32);
237
238                 $postopts = defaults($_REQUEST, 'postopts', '');
239
240                 $private = ((strlen($str_group_allow) || strlen($str_contact_allow) || strlen($str_group_deny) || strlen($str_contact_deny)) ? 1 : 0);
241
242                 if ($user['hidewall']) {
243                         $private = 2;
244                 }
245
246                 // If this is a comment, set the permissions from the parent.
247
248                 if ($parent_item) {
249                         // for non native networks use the network of the original post as network of the item
250                         if (($parent_item['network'] != NETWORK_DIASPORA)
251                                 && ($parent_item['network'] != NETWORK_OSTATUS)
252                                 && ($network == "")) {
253                                 $network = $parent_item['network'];
254                         }
255
256                         $str_contact_allow = $parent_item['allow_cid'];
257                         $str_group_allow   = $parent_item['allow_gid'];
258                         $str_contact_deny  = $parent_item['deny_cid'];
259                         $str_group_deny    = $parent_item['deny_gid'];
260                         $private           = $parent_item['private'];
261
262                         $wall              = $parent_item['wall'];
263                 }
264
265                 $pubmail_enabled = defaults($_REQUEST, 'pubmail_enable', false) && !$private;
266
267                 // if using the API, we won't see pubmail_enable - figure out if it should be set
268                 if ($api_source && $profile_uid && $profile_uid == local_user() && !$private) {
269                         if (function_exists('imap_open') && !Config::get('system', 'imap_disabled')) {
270                                 $pubmail_enabled = DBA::exists('mailacct', ["`uid` = ? AND `server` != ? AND `pubmail`", local_user(), '']);
271                         }
272                 }
273
274                 if (!strlen($body)) {
275                         if ($preview) {
276                                 killme();
277                         }
278                         info(L10n::t('Empty post discarded.') . EOL);
279                         if (x($_REQUEST, 'return')) {
280                                 goaway($return_path);
281                         }
282                         killme();
283                 }
284         }
285
286         if (!empty($categories)) {
287                 // get the "fileas" tags for this post
288                 $filedas = file_tag_file_to_list($categories, 'file');
289         }
290         // save old and new categories, so we can determine what needs to be deleted from pconfig
291         $categories_old = $categories;
292         $categories = file_tag_list_to_file(trim(defaults($_REQUEST, 'category', '')), 'category');
293         $categories_new = $categories;
294         if (!empty($filedas)) {
295                 // append the fileas stuff to the new categories list
296                 $categories .= file_tag_list_to_file($filedas, 'file');
297         }
298
299         // get contact info for poster
300
301         $author = null;
302         $self   = false;
303         $contact_id = 0;
304
305         if (local_user() && ((local_user() == $profile_uid) || $allow_comment)) {
306                 $self = true;
307                 $author = DBA::selectFirst('contact', [], ['uid' => local_user(), 'self' => true]);
308         } elseif (remote_user()) {
309                 if (x($_SESSION, 'remote') && is_array($_SESSION['remote'])) {
310                         foreach ($_SESSION['remote'] as $v) {
311                                 if ($v['uid'] == $profile_uid) {
312                                         $contact_id = $v['cid'];
313                                         break;
314                                 }
315                         }
316                 }
317                 if ($contact_id) {
318                         $author = DBA::selectFirst('contact', [], ['id' => $contact_id]);
319                 }
320         }
321
322         if (DBA::isResult($author)) {
323                 $contact_id = $author['id'];
324         }
325
326         // get contact info for owner
327         if ($profile_uid == local_user() || $allow_comment) {
328                 $contact_record = $author;
329         } else {
330                 $contact_record = DBA::selectFirst('contact', [], ['uid' => $profile_uid, 'self' => true]);
331         }
332
333         // Look for any tags and linkify them
334         $str_tags = '';
335         $inform   = '';
336
337         $tags = get_tags($body);
338
339         // Add a tag if the parent contact is from OStatus (This will notify them during delivery)
340         if ($parent) {
341                 if ($thr_parent_contact['network'] == NETWORK_OSTATUS) {
342                         $contact = '@[url=' . $thr_parent_contact['url'] . ']' . $thr_parent_contact['nick'] . '[/url]';
343                         if (!stripos(implode($tags), '[url=' . $thr_parent_contact['url'] . ']')) {
344                                 $tags[] = $contact;
345                         }
346                 }
347
348                 if ($parent_contact['network'] == NETWORK_OSTATUS) {
349                         $contact = '@[url=' . $parent_contact['url'] . ']' . $parent_contact['nick'] . '[/url]';
350                         if (!stripos(implode($tags), '[url=' . $parent_contact['url'] . ']')) {
351                                 $tags[] = $contact;
352                         }
353                 }
354         }
355
356         $tagged = [];
357
358         $private_forum = false;
359         $only_to_forum = false;
360         $forum_contact = [];
361
362         if (count($tags)) {
363                 foreach ($tags as $tag) {
364                         $tag_type = substr($tag, 0, 1);
365
366                         if ($tag_type == '#') {
367                                 continue;
368                         }
369
370                         /*
371                          * If we already tagged 'Robert Johnson', don't try and tag 'Robert'.
372                          * Robert Johnson should be first in the $tags array
373                          */
374                         $fullnametagged = false;
375                         /// @TODO $tagged is initialized above if () block and is not filled, maybe old-lost code?
376                         foreach ($tagged as $nextTag) {
377                                 if (stristr($nextTag, $tag . ' ')) {
378                                         $fullnametagged = true;
379                                         break;
380                                 }
381                         }
382                         if ($fullnametagged) {
383                                 continue;
384                         }
385
386                         $success = handle_tag($a, $body, $inform, $str_tags, local_user() ? local_user() : $profile_uid, $tag, $network);
387                         if ($success['replaced']) {
388                                 $tagged[] = $tag;
389                         }
390                         // When the forum is private or the forum is addressed with a "!" make the post private
391                         if (is_array($success['contact']) && ($success['contact']['prv'] || ($tag_type == '!'))) {
392                                 $private_forum = $success['contact']['prv'];
393                                 $only_to_forum = ($tag_type == '!');
394                                 $private_id = $success['contact']['id'];
395                                 $forum_contact = $success['contact'];
396                         } elseif (is_array($success['contact']) && $success['contact']['forum'] &&
397                                 ($str_contact_allow == '<' . $success['contact']['id'] . '>')) {
398                                 $private_forum = false;
399                                 $only_to_forum = true;
400                                 $private_id = $success['contact']['id'];
401                                 $forum_contact = $success['contact'];
402                         }
403                 }
404         }
405
406         $original_contact_id = $contact_id;
407
408         if (!$parent && count($forum_contact) && ($private_forum || $only_to_forum)) {
409                 // we tagged a forum in a top level post. Now we change the post
410                 $private = $private_forum;
411
412                 $str_group_allow = '';
413                 $str_contact_deny = '';
414                 $str_group_deny = '';
415                 if ($private_forum) {
416                         $str_contact_allow = '<' . $private_id . '>';
417                 } else {
418                         $str_contact_allow = '';
419                 }
420                 $contact_id = $private_id;
421                 $contact_record = $forum_contact;
422                 $_REQUEST['origin'] = false;
423                 $wall = 0;
424         }
425
426         /*
427          * When a photo was uploaded into the message using the (profile wall) ajax
428          * uploader, The permissions are initially set to disallow anybody but the
429          * owner from seeing it. This is because the permissions may not yet have been
430          * set for the post. If it's private, the photo permissions should be set
431          * appropriately. But we didn't know the final permissions on the post until
432          * now. So now we'll look for links of uploaded messages that are in the
433          * post and set them to the same permissions as the post itself.
434          */
435
436         $match = null;
437
438         /// @todo these lines should be moved to Model/Photo
439         if (!$preview && preg_match_all("/\[img([\=0-9x]*?)\](.*?)\[\/img\]/",$body,$match)) {
440                 $images = $match[2];
441                 if (count($images)) {
442
443                         $objecttype = ACTIVITY_OBJ_IMAGE;
444
445                         foreach ($images as $image) {
446                                 if (!stristr($image, System::baseUrl() . '/photo/')) {
447                                         continue;
448                                 }
449                                 $image_uri = substr($image,strrpos($image,'/') + 1);
450                                 $image_uri = substr($image_uri,0, strpos($image_uri,'-'));
451                                 if (!strlen($image_uri)) {
452                                         continue;
453                                 }
454
455                                 // Ensure to only modify photos that you own
456                                 $srch = '<' . intval($original_contact_id) . '>';
457
458                                 $condition = ['allow_cid' => $srch, 'allow_gid' => '', 'deny_cid' => '', 'deny_gid' => '',
459                                                 'resource-id' => $image_uri, 'uid' => $profile_uid];
460                                 if (!DBA::exists('photo', $condition)) {
461                                         continue;
462                                 }
463
464                                 $fields = ['allow_cid' => $str_contact_allow, 'allow_gid' => $str_group_allow,
465                                                 'deny_cid' => $str_contact_deny, 'deny_gid' => $str_group_deny];
466                                 $condition = ['resource-id' => $image_uri, 'uid' => $profile_uid, 'album' => L10n::t('Wall Photos')];
467                                 DBA::update('photo', $fields, $condition);
468                         }
469                 }
470         }
471
472
473         /*
474          * Next link in any attachment references we find in the post.
475          */
476         $match = false;
477
478         /// @todo these lines should be moved to Model/Attach (Once it exists)
479         if (!$preview && preg_match_all("/\[attachment\](.*?)\[\/attachment\]/", $body, $match)) {
480                 $attaches = $match[1];
481                 if (count($attaches)) {
482                         foreach ($attaches as $attach) {
483                                 // Ensure to only modify attachments that you own
484                                 $srch = '<' . intval($original_contact_id) . '>';
485
486                                 $condition = ['allow_cid' => $srch, 'allow_gid' => '', 'deny_cid' => '', 'deny_gid' => '',
487                                                 'id' => $attach];
488                                 if (!DBA::exists('attach', $condition)) {
489                                         continue;
490                                 }
491
492                                 $fields = ['allow_cid' => $str_contact_allow, 'allow_gid' => $str_group_allow,
493                                                 'deny_cid' => $str_contact_deny, 'deny_gid' => $str_group_deny];
494                                 $condition = ['id' => $attach];
495                                 DBA::update('attach', $fields, $condition);
496                         }
497                 }
498         }
499
500         // embedded bookmark or attachment in post? set bookmark flag
501
502         $data = BBCode::getAttachmentData($body);
503         if ((preg_match_all("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/ism", $body, $match, PREG_SET_ORDER) || isset($data["type"]))
504                 && ($posttype != Item::PT_PERSONAL_NOTE)) {
505                 $posttype = Item::PT_PAGE;
506                 $objecttype = ACTIVITY_OBJ_BOOKMARK;
507         }
508
509         $body = bb_translate_video($body);
510
511
512         // Fold multi-line [code] sequences
513         $body = preg_replace('/\[\/code\]\s*\[code\]/ism', "\n", $body);
514
515         $body = BBCode::scaleExternalImages($body, false);
516
517         // Setting the object type if not defined before
518         if (!$objecttype) {
519                 $objecttype = ACTIVITY_OBJ_NOTE; // Default value
520                 $objectdata = BBCode::getAttachedData($body);
521
522                 if ($objectdata["type"] == "link") {
523                         $objecttype = ACTIVITY_OBJ_BOOKMARK;
524                 } elseif ($objectdata["type"] == "video") {
525                         $objecttype = ACTIVITY_OBJ_VIDEO;
526                 } elseif ($objectdata["type"] == "photo") {
527                         $objecttype = ACTIVITY_OBJ_IMAGE;
528                 }
529
530         }
531
532         $attachments = '';
533         $match = false;
534
535         if (preg_match_all('/(\[attachment\]([0-9]+)\[\/attachment\])/',$body,$match)) {
536                 foreach ($match[2] as $mtch) {
537                         $fields = ['id', 'filename', 'filesize', 'filetype'];
538                         $attachment = DBA::selectFirst('attach', $fields, ['id' => $mtch]);
539                         if (DBA::isResult($attachment)) {
540                                 if (strlen($attachments)) {
541                                         $attachments .= ',';
542                                 }
543                                 $attachments .= '[attach]href="' . System::baseUrl() . '/attach/' . $attachment['id'] .
544                                                 '" length="' . $attachment['filesize'] . '" type="' . $attachment['filetype'] .
545                                                 '" title="' . ($attachment['filename'] ? $attachment['filename'] : '') . '"[/attach]';
546                         }
547                         $body = str_replace($match[1],'',$body);
548                 }
549         }
550
551         if (!strlen($verb)) {
552                 $verb = ACTIVITY_POST;
553         }
554
555         if ($network == "") {
556                 $network = NETWORK_DFRN;
557         }
558
559         $gravity = ($parent ? GRAVITY_COMMENT : GRAVITY_PARENT);
560
561         // even if the post arrived via API we are considering that it
562         // originated on this site by default for determining relayability.
563
564         $origin = intval(defaults($_REQUEST, 'origin', 1));
565
566         $notify_type = ($parent ? 'comment-new' : 'wall-new');
567
568         $uri = ($message_id ? $message_id : Item::newURI($api_source ? $profile_uid : $uid, $guid));
569
570         // Fallback so that we alway have a parent uri
571         if (!$thr_parent_uri || !$parent) {
572                 $thr_parent_uri = $uri;
573         }
574
575         $datarray = [];
576         $datarray['uid']           = $profile_uid;
577         $datarray['wall']          = $wall;
578         $datarray['gravity']       = $gravity;
579         $datarray['network']       = $network;
580         $datarray['contact-id']    = $contact_id;
581         $datarray['owner-name']    = $contact_record['name'];
582         $datarray['owner-link']    = $contact_record['url'];
583         $datarray['owner-avatar']  = $contact_record['thumb'];
584         $datarray['owner-id']      = Contact::getIdForURL($datarray['owner-link']);
585         $datarray['author-name']   = $author['name'];
586         $datarray['author-link']   = $author['url'];
587         $datarray['author-avatar'] = $author['thumb'];
588         $datarray['author-id']     = Contact::getIdForURL($datarray['author-link']);
589         $datarray['created']       = DateTimeFormat::utcNow();
590         $datarray['edited']        = DateTimeFormat::utcNow();
591         $datarray['commented']     = DateTimeFormat::utcNow();
592         $datarray['received']      = DateTimeFormat::utcNow();
593         $datarray['changed']       = DateTimeFormat::utcNow();
594         $datarray['extid']         = $extid;
595         $datarray['guid']          = $guid;
596         $datarray['uri']           = $uri;
597         $datarray['title']         = $title;
598         $datarray['body']          = $body;
599         $datarray['app']           = $app;
600         $datarray['location']      = $location;
601         $datarray['coord']         = $coord;
602         $datarray['tag']           = $str_tags;
603         $datarray['file']          = $categories;
604         $datarray['inform']        = $inform;
605         $datarray['verb']          = $verb;
606         $datarray['post-type']     = $posttype;
607         $datarray['object-type']   = $objecttype;
608         $datarray['allow_cid']     = $str_contact_allow;
609         $datarray['allow_gid']     = $str_group_allow;
610         $datarray['deny_cid']      = $str_contact_deny;
611         $datarray['deny_gid']      = $str_group_deny;
612         $datarray['private']       = $private;
613         $datarray['pubmail']       = $pubmail_enabled;
614         $datarray['attach']        = $attachments;
615
616         // This is not a bug. The item store function changes 'parent-uri' to 'thr-parent' and fetches 'parent-uri' new. (We should change this)
617         $datarray['parent-uri']    = $thr_parent_uri;
618
619         $datarray['postopts']      = $postopts;
620         $datarray['origin']        = $origin;
621         $datarray['moderated']     = false;
622         $datarray['object']        = $object;
623
624         /*
625          * These fields are for the convenience of addons...
626          * 'self' if true indicates the owner is posting on their own wall
627          * If parent is 0 it is a top-level post.
628          */
629         $datarray['parent']        = $parent;
630         $datarray['self']          = $self;
631
632         // This triggers posts via API and the mirror functions
633         $datarray['api_source'] = $api_source;
634
635         // This field is for storing the raw conversation data
636         $datarray['protocol'] = PROTOCOL_DFRN;
637
638         $conversation = DBA::selectFirst('conversation', ['conversation-uri', 'conversation-href'], ['item-uri' => $datarray['parent-uri']]);
639         if (DBA::isResult($conversation)) {
640                 if ($conversation['conversation-uri'] != '') {
641                         $datarray['conversation-uri'] = $conversation['conversation-uri'];
642                 }
643                 if ($conversation['conversation-href'] != '') {
644                         $datarray['conversation-href'] = $conversation['conversation-href'];
645                 }
646         }
647
648         if ($orig_post) {
649                 $datarray['edit'] = true;
650         } else {
651                 $datarray['edit'] = false;
652         }
653
654         // Check for hashtags in the body and repair or add hashtag links
655         if ($preview || $orig_post) {
656                 Item::setHashtags($datarray);
657         }
658
659         // preview mode - prepare the body for display and send it via json
660         if ($preview) {
661                 require_once 'include/conversation.php';
662                 // We set the datarray ID to -1 because in preview mode the dataray
663                 // doesn't have an ID.
664                 $datarray["id"] = -1;
665                 $datarray["item_id"] = -1;
666                 $datarray["author-network"] = NETWORK_DFRN;
667
668                 $o = conversation($a,[array_merge($contact_record,$datarray)],'search', false, true);
669                 logger('preview: ' . $o);
670                 echo json_encode(['preview' => $o]);
671                 killme();
672         }
673
674         Addon::callHooks('post_local',$datarray);
675
676         if (x($datarray, 'cancel')) {
677                 logger('mod_item: post cancelled by addon.');
678                 if ($return_path) {
679                         goaway($return_path);
680                 }
681
682                 $json = ['cancel' => 1];
683                 if (x($_REQUEST, 'jsreload') && strlen($_REQUEST['jsreload'])) {
684                         $json['reload'] = System::baseUrl() . '/' . $_REQUEST['jsreload'];
685                 }
686
687                 echo json_encode($json);
688                 killme();
689         }
690
691         if ($orig_post) {
692
693                 // Fill the cache field
694                 // This could be done in Item::update as well - but we have to check for the existance of some fields.
695                 put_item_in_cache($datarray);
696
697                 $fields = [
698                         'title' => $datarray['title'],
699                         'body' => $datarray['body'],
700                         'tag' => $datarray['tag'],
701                         'attach' => $datarray['attach'],
702                         'file' => $datarray['file'],
703                         'rendered-html' => $datarray['rendered-html'],
704                         'rendered-hash' => $datarray['rendered-hash'],
705                         'edited' => DateTimeFormat::utcNow(),
706                         'changed' => DateTimeFormat::utcNow()];
707
708                 Item::update($fields, ['id' => $post_id]);
709
710                 // update filetags in pconfig
711                 file_tag_update_pconfig($uid,$categories_old,$categories_new,'category');
712
713                 if (x($_REQUEST, 'return') && strlen($return_path)) {
714                         logger('return: ' . $return_path);
715                         goaway($return_path);
716                 }
717                 killme();
718         } else {
719                 $post_id = 0;
720         }
721
722         unset($datarray['edit']);
723         unset($datarray['self']);
724         unset($datarray['api_source']);
725
726         $post_id = Item::insert($datarray);
727
728         if (!$post_id) {
729                 logger("Item wasn't stored.");
730                 goaway($return_path);
731         }
732
733         $datarray = Item::selectFirst(Item::ITEM_FIELDLIST, ['id' => $post_id]);
734
735         if (!DBA::isResult($datarray)) {
736                 logger("Item with id ".$post_id." couldn't be fetched.");
737                 goaway($return_path);
738         }
739
740         // update filetags in pconfig
741         file_tag_update_pconfig($uid, $categories_old, $categories_new, 'category');
742
743         // These notifications are sent if someone else is commenting other your wall
744         if ($parent) {
745                 if ($contact_record != $author) {
746                         notification([
747                                 'type'         => NOTIFY_COMMENT,
748                                 'notify_flags' => $user['notify-flags'],
749                                 'language'     => $user['language'],
750                                 'to_name'      => $user['username'],
751                                 'to_email'     => $user['email'],
752                                 'uid'          => $user['uid'],
753                                 'item'         => $datarray,
754                                 'link'         => System::baseUrl().'/display/'.urlencode($datarray['guid']),
755                                 'source_name'  => $datarray['author-name'],
756                                 'source_link'  => $datarray['author-link'],
757                                 'source_photo' => $datarray['author-avatar'],
758                                 'verb'         => ACTIVITY_POST,
759                                 'otype'        => 'item',
760                                 'parent'       => $parent,
761                                 'parent_uri'   => $parent_item['uri']
762                         ]);
763                 }
764
765                 // Store the comment signature information in case we need to relay to Diaspora
766                 Diaspora::storeCommentSignature($datarray, $author, ($self ? $user['prvkey'] : false), $post_id);
767         } else {
768                 if (($contact_record != $author) && !count($forum_contact)) {
769                         notification([
770                                 'type'         => NOTIFY_WALL,
771                                 'notify_flags' => $user['notify-flags'],
772                                 'language'     => $user['language'],
773                                 'to_name'      => $user['username'],
774                                 'to_email'     => $user['email'],
775                                 'uid'          => $user['uid'],
776                                 'item'         => $datarray,
777                                 'link'         => System::baseUrl().'/display/'.urlencode($datarray['guid']),
778                                 'source_name'  => $datarray['author-name'],
779                                 'source_link'  => $datarray['author-link'],
780                                 'source_photo' => $datarray['author-avatar'],
781                                 'verb'         => ACTIVITY_POST,
782                                 'otype'        => 'item'
783                         ]);
784                 }
785         }
786
787         Addon::callHooks('post_local_end', $datarray);
788
789         if (strlen($emailcc) && $profile_uid == local_user()) {
790                 $erecips = explode(',', $emailcc);
791                 if (count($erecips)) {
792                         foreach ($erecips as $recip) {
793                                 $addr = trim($recip);
794                                 if (!strlen($addr)) {
795                                         continue;
796                                 }
797                                 $disclaimer = '<hr />' . L10n::t('This message was sent to you by %s, a member of the Friendica social network.', $a->user['username'])
798                                         . '<br />';
799                                 $disclaimer .= L10n::t('You may visit them online at %s', System::baseUrl() . '/profile/' . $a->user['nickname']) . EOL;
800                                 $disclaimer .= L10n::t('Please contact the sender by replying to this post if you do not wish to receive these messages.') . EOL;
801                                 if (!$datarray['title']=='') {
802                                         $subject = Email::encodeHeader($datarray['title'], 'UTF-8');
803                                 } else {
804                                         $subject = Email::encodeHeader('[Friendica]' . ' ' . L10n::t('%s posted an update.', $a->user['username']), 'UTF-8');
805                                 }
806                                 $link = '<a href="' . System::baseUrl() . '/profile/' . $a->user['nickname'] . '"><img src="' . $author['thumb'] . '" alt="' . $a->user['username'] . '" /></a><br /><br />';
807                                 $html    = prepare_body($datarray);
808                                 $message = '<html><body>' . $link . $html . $disclaimer . '</body></html>';
809                                 $params =  [
810                                         'fromName' => $a->user['username'],
811                                         'fromEmail' => $a->user['email'],
812                                         'toEmail' => $addr,
813                                         'replyTo' => $a->user['email'],
814                                         'messageSubject' => $subject,
815                                         'htmlVersion' => $message,
816                                         'textVersion' => HTML::toPlaintext($html.$disclaimer)
817                                 ];
818                                 Emailer::send($params);
819                         }
820                 }
821         }
822
823         // Insert an item entry for UID=0 for global entries.
824         // We now do it in the background to save some time.
825         // This is important in interactive environments like the frontend or the API.
826         // We don't fork a new process since this is done anyway with the following command
827         Worker::add(['priority' => PRIORITY_HIGH, 'dont_fork' => true], "CreateShadowEntry", $post_id);
828
829         // Call the background process that is delivering the item to the receivers
830         Worker::add(PRIORITY_HIGH, "Notifier", $notify_type, $post_id);
831
832         logger('post_complete');
833
834         item_post_return(System::baseUrl(), $api_source, $return_path);
835         // NOTREACHED
836 }
837
838 function item_post_return($baseurl, $api_source, $return_path) {
839         // figure out how to return, depending on from whence we came
840
841         if ($api_source) {
842                 return;
843         }
844
845         if ($return_path) {
846                 goaway($return_path);
847         }
848
849         $json = ['success' => 1];
850         if (x($_REQUEST, 'jsreload') && strlen($_REQUEST['jsreload'])) {
851                 $json['reload'] = $baseurl . '/' . $_REQUEST['jsreload'];
852         }
853
854         logger('post_json: ' . print_r($json,true), LOGGER_DEBUG);
855
856         echo json_encode($json);
857         killme();
858 }
859
860
861
862 function item_content(App $a) {
863
864         if (!local_user() && !remote_user()) {
865                 return;
866         }
867
868         require_once 'include/security.php';
869
870         $o = '';
871         if (($a->argc == 3) && ($a->argv[1] === 'drop') && intval($a->argv[2])) {
872                 if (is_ajax()) {
873                         $o = Item::deleteForUser(['id' => $a->argv[2]], local_user());
874                 } else {
875                         $o = drop_item($a->argv[2]);
876                 }
877                 if (is_ajax()) {
878                         // ajax return: [<item id>, 0 (no perm) | <owner id>]
879                         echo json_encode([intval($a->argv[2]), intval($o)]);
880                         killme();
881                 }
882         }
883         return $o;
884 }
885
886 /**
887  * This function removes the tag $tag from the text $body and replaces it with
888  * the appropiate link.
889  *
890  * @param App $a Application instance @TODO is unused in this function's scope (excluding included files)
891  * @param unknown_type $body the text to replace the tag in
892  * @param string $inform a comma-seperated string containing everybody to inform
893  * @param string $str_tags string to add the tag to
894  * @param integer $profile_uid
895  * @param string $tag the tag to replace
896  * @param string $network The network of the post
897  *
898  * @return boolean true if replaced, false if not replaced
899  */
900 function handle_tag(App $a, &$body, &$inform, &$str_tags, $profile_uid, $tag, $network = "")
901 {
902         $replaced = false;
903         $r = null;
904         $tag_type = '@';
905
906         //is it a person tag?
907         if ((strpos($tag, '@') === 0) || (strpos($tag, '!') === 0)) {
908                 $tag_type = substr($tag, 0, 1);
909                 //is it already replaced?
910                 if (strpos($tag, '[url=')) {
911                         //append tag to str_tags
912                         if (!stristr($str_tags, $tag)) {
913                                 if (strlen($str_tags)) {
914                                         $str_tags .= ',';
915                                 }
916                                 $str_tags .= $tag;
917                         }
918
919                         // Checking for the alias that is used for OStatus
920                         $pattern = "/[@!]\[url\=(.*?)\](.*?)\[\/url\]/ism";
921                         if (preg_match($pattern, $tag, $matches)) {
922                                 $data = Contact::getDetailsByURL($matches[1]);
923                                 if ($data["alias"] != "") {
924                                         $newtag = '@[url=' . $data["alias"] . ']' . $data["nick"] . '[/url]';
925                                         if (!stripos($str_tags, '[url=' . $data["alias"] . ']')) {
926                                                 if (strlen($str_tags)) {
927                                                         $str_tags .= ',';
928                                                 }
929                                                 $str_tags .= $newtag;
930                                         }
931                                 }
932                         }
933
934                         return $replaced;
935                 }
936                 $stat = false;
937                 //get the person's name
938                 $name = substr($tag, 1);
939
940                 // Sometimes the tag detection doesn't seem to work right
941                 // This is some workaround
942                 $nameparts = explode(" ", $name);
943                 $name = $nameparts[0];
944
945                 // Try to detect the contact in various ways
946                 if (strpos($name, 'http://')) {
947                         // At first we have to ensure that the contact exists
948                         Contact::getIdForURL($name);
949
950                         // Now we should have something
951                         $contact = Contact::getDetailsByURL($name);
952                 } elseif (strpos($name, '@')) {
953                         // This function automatically probes when no entry was found
954                         $contact = Contact::getDetailsByAddr($name);
955                 } else {
956                         $contact = false;
957                         $fields = ['id', 'url', 'nick', 'name', 'alias', 'network'];
958
959                         if (strrpos($name, '+')) {
960                                 // Is it in format @nick+number?
961                                 $tagcid = intval(substr($name, strrpos($name, '+') + 1));
962                                 $contact = DBA::selectFirst('contact', $fields, ['id' => $tagcid, 'uid' => $profile_uid]);
963                         }
964
965                         // select someone by nick or attag in the current network
966                         if (!DBA::isResult($contact) && ($network != "")) {
967                                 $condition = ["(`nick` = ? OR `attag` = ?) AND `network` = ? AND `uid` = ?",
968                                                 $name, $name, $network, $profile_uid];
969                                 $contact = DBA::selectFirst('contact', $fields, $condition);
970                         }
971
972                         //select someone by name in the current network
973                         if (!DBA::isResult($contact) && ($network != "")) {
974                                 $condition = ['name' => $name, 'network' => $network, 'uid' => $profile_uid];
975                                 $contact = DBA::selectFirst('contact', $fields, $condition);
976                         }
977
978                         // select someone by nick or attag in any network
979                         if (!DBA::isResult($contact)) {
980                                 $condition = ["(`nick` = ? OR `attag` = ?) AND `uid` = ?", $name, $name, $profile_uid];
981                                 $contact = DBA::selectFirst('contact', $fields, $condition);
982                         }
983
984                         // select someone by name in any network
985                         if (!DBA::isResult($contact)) {
986                                 $condition = ['name' => $name, 'uid' => $profile_uid];
987                                 $contact = DBA::selectFirst('contact', $fields, $condition);
988                         }
989                 }
990
991                 if ($contact) {
992                         if (strlen($inform) && (isset($contact["notify"]) || isset($contact["id"]))) {
993                                 $inform .= ',';
994                         }
995
996                         if (isset($contact["id"])) {
997                                 $inform .= 'cid:' . $contact["id"];
998                         } elseif (isset($contact["notify"])) {
999                                 $inform  .= $contact["notify"];
1000                         }
1001
1002                         $profile = $contact["url"];
1003                         $alias   = $contact["alias"];
1004                         $newname = $contact["nick"];
1005                         if (($newname == "") || (($contact["network"] != NETWORK_OSTATUS) && ($contact["network"] != NETWORK_TWITTER)
1006                                 && ($contact["network"] != NETWORK_STATUSNET) && ($contact["network"] != NETWORK_APPNET))) {
1007                                 $newname = $contact["name"];
1008                         }
1009                 }
1010
1011                 //if there is an url for this persons profile
1012                 if (isset($profile) && ($newname != "")) {
1013                         $replaced = true;
1014                         // create profile link
1015                         $profile = str_replace(',', '%2c', $profile);
1016                         $newtag = $tag_type.'[url=' . $profile . ']' . $newname . '[/url]';
1017                         $body = str_replace($tag_type . $name, $newtag, $body);
1018                         // append tag to str_tags
1019                         if (!stristr($str_tags, $newtag)) {
1020                                 if (strlen($str_tags)) {
1021                                         $str_tags .= ',';
1022                                 }
1023                                 $str_tags .= $newtag;
1024                         }
1025
1026                         /*
1027                          * Status.Net seems to require the numeric ID URL in a mention if the person isn't
1028                          * subscribed to you. But the nickname URL is OK if they are. Grrr. We'll tag both.
1029                          */
1030                         if (strlen($alias)) {
1031                                 $newtag = '@[url=' . $alias . ']' . $newname . '[/url]';
1032                                 if (!stripos($str_tags, '[url=' . $alias . ']')) {
1033                                         if (strlen($str_tags)) {
1034                                                 $str_tags .= ',';
1035                                         }
1036                                         $str_tags .= $newtag;
1037                                 }
1038                         }
1039                 }
1040         }
1041
1042         return ['replaced' => $replaced, 'contact' => $contact];
1043 }