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