]> git.mxchange.org Git - friendica.git/blob - mod/item.php
Update more PHPDoc, including in include/
[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\Config;
23 use Friendica\Core\Hook;
24 use Friendica\Core\L10n;
25 use Friendica\Core\Logger;
26 use Friendica\Core\Protocol;
27 use Friendica\Core\System;
28 use Friendica\Core\Worker;
29 use Friendica\Database\DBA;
30 use Friendica\Model\Contact;
31 use Friendica\Model\Conversation;
32 use Friendica\Model\FileTag;
33 use Friendica\Model\Item;
34 use Friendica\Model\Photo;
35 use Friendica\Model\Attach;
36 use Friendica\Protocol\Diaspora;
37 use Friendica\Protocol\Email;
38 use Friendica\Util\DateTimeFormat;
39 use Friendica\Util\Emailer;
40 use Friendica\Util\Security;
41 use Friendica\Util\Strings;
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                 exit();
56         }
57
58         Hook::callAll('post_local_start', $_REQUEST);
59
60         Logger::log('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::log("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                         exit();
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::log('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::log("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                 exit();
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             = Strings::escapeTags(trim($_REQUEST['title']));
206                 $body              = Strings::escapeHtml(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             = Strings::escapeTags(trim(defaults($_REQUEST, 'title'   , '')));
238                 $location          = Strings::escapeTags(trim(defaults($_REQUEST, 'location', '')));
239                 $coord             = Strings::escapeTags(trim(defaults($_REQUEST, 'coord'   , '')));
240                 $verb              = Strings::escapeTags(trim(defaults($_REQUEST, 'verb'    , '')));
241                 $emailcc           = Strings::escapeTags(trim(defaults($_REQUEST, 'emailcc' , '')));
242                 $body              = Strings::escapeHtml(trim(defaults($_REQUEST, 'body'    , '')));
243                 $network           = Strings::escapeTags(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                                 exit();
285                         }
286                         info(L10n::t('Empty post discarded.') . EOL);
287                         if (!empty($_REQUEST['return'])) {
288                                 $a->internalRedirect($return_path);
289                         }
290                         exit();
291                 }
292         }
293
294         if (!empty($categories))
295         {
296                 // get the "fileas" tags for this post
297                 $filedas = FileTag::fileToList($categories, 'file');
298         }
299
300         // save old and new categories, so we can determine what needs to be deleted from pconfig
301         $categories_old = $categories;
302         $categories = FileTag::listToFile(trim(defaults($_REQUEST, 'category', '')), 'category');
303         $categories_new = $categories;
304
305         if (!empty($filedas))
306         {
307                 // append the fileas stuff to the new categories list
308                 $categories .= FileTag::listToFile($filedas, 'file');
309         }
310
311         // get contact info for poster
312
313         $author = null;
314         $self   = false;
315         $contact_id = 0;
316
317         if (local_user() && ((local_user() == $profile_uid) || $allow_comment)) {
318                 $self = true;
319                 $author = DBA::selectFirst('contact', [], ['uid' => local_user(), 'self' => true]);
320         } elseif (remote_user()) {
321                 if (!empty($_SESSION['remote']) && is_array($_SESSION['remote'])) {
322                         foreach ($_SESSION['remote'] as $v) {
323                                 if ($v['uid'] == $profile_uid) {
324                                         $contact_id = $v['cid'];
325                                         break;
326                                 }
327                         }
328                 }
329                 if ($contact_id) {
330                         $author = DBA::selectFirst('contact', [], ['id' => $contact_id]);
331                 }
332         }
333
334         if (DBA::isResult($author)) {
335                 $contact_id = $author['id'];
336         }
337
338         // get contact info for owner
339         if ($profile_uid == local_user() || $allow_comment) {
340                 $contact_record = $author;
341         } else {
342                 $contact_record = DBA::selectFirst('contact', [], ['uid' => $profile_uid, 'self' => true]);
343         }
344
345         // Look for any tags and linkify them
346         $str_tags = '';
347         $inform   = '';
348
349         $tags = BBCode::getTags($body);
350
351         // Add a tag if the parent contact is from ActivityPub or OStatus (This will notify them)
352         if ($parent && in_array($thr_parent_contact['network'], [Protocol::OSTATUS, Protocol::ACTIVITYPUB])) {
353                 $contact = '@[url=' . $thr_parent_contact['url'] . ']' . $thr_parent_contact['nick'] . '[/url]';
354                 if (!stripos(implode($tags), '[url=' . $thr_parent_contact['url'] . ']')) {
355                         $tags[] = $contact;
356                 }
357         }
358
359         $tagged = [];
360
361         $private_forum = false;
362         $only_to_forum = false;
363         $forum_contact = [];
364
365         if (count($tags)) {
366                 foreach ($tags as $tag) {
367                         $tag_type = substr($tag, 0, 1);
368
369                         if ($tag_type == '#') {
370                                 continue;
371                         }
372
373                         /*
374                          * If we already tagged 'Robert Johnson', don't try and tag 'Robert'.
375                          * Robert Johnson should be first in the $tags array
376                          */
377                         $fullnametagged = false;
378                         /// @TODO $tagged is initialized above if () block and is not filled, maybe old-lost code?
379                         foreach ($tagged as $nextTag) {
380                                 if (stristr($nextTag, $tag . ' ')) {
381                                         $fullnametagged = true;
382                                         break;
383                                 }
384                         }
385                         if ($fullnametagged) {
386                                 continue;
387                         }
388
389                         $success = handle_tag($a, $body, $inform, $str_tags, local_user() ? local_user() : $profile_uid, $tag, $network);
390                         if ($success['replaced']) {
391                                 $tagged[] = $tag;
392                         }
393                         // When the forum is private or the forum is addressed with a "!" make the post private
394                         if (is_array($success['contact']) && (!empty($success['contact']['prv']) || ($tag_type == '!'))) {
395                                 $private_forum = $success['contact']['prv'];
396                                 $only_to_forum = ($tag_type == '!');
397                                 $private_id = $success['contact']['id'];
398                                 $forum_contact = $success['contact'];
399                         } elseif (is_array($success['contact']) && !empty($success['contact']['forum']) &&
400                                 ($str_contact_allow == '<' . $success['contact']['id'] . '>')) {
401                                 $private_forum = false;
402                                 $only_to_forum = true;
403                                 $private_id = $success['contact']['id'];
404                                 $forum_contact = $success['contact'];
405                         }
406                 }
407         }
408
409         $original_contact_id = $contact_id;
410
411         if (!$parent && count($forum_contact) && ($private_forum || $only_to_forum)) {
412                 // we tagged a forum in a top level post. Now we change the post
413                 $private = $private_forum;
414
415                 $str_group_allow = '';
416                 $str_contact_deny = '';
417                 $str_group_deny = '';
418                 if ($private_forum) {
419                         $str_contact_allow = '<' . $private_id . '>';
420                 } else {
421                         $str_contact_allow = '';
422                 }
423                 $contact_id = $private_id;
424                 $contact_record = $forum_contact;
425                 $_REQUEST['origin'] = false;
426                 $wall = 0;
427         }
428
429         /*
430          * When a photo was uploaded into the message using the (profile wall) ajax
431          * uploader, The permissions are initially set to disallow anybody but the
432          * owner from seeing it. This is because the permissions may not yet have been
433          * set for the post. If it's private, the photo permissions should be set
434          * appropriately. But we didn't know the final permissions on the post until
435          * now. So now we'll look for links of uploaded messages that are in the
436          * post and set them to the same permissions as the post itself.
437          */
438
439         $match = null;
440
441         /// @todo these lines should be moved to Model/Photo
442         if (!$preview && preg_match_all("/\[img([\=0-9x]*?)\](.*?)\[\/img\]/",$body,$match)) {
443                 $images = $match[2];
444                 if (count($images)) {
445
446                         $objecttype = ACTIVITY_OBJ_IMAGE;
447
448                         foreach ($images as $image) {
449                                 if (!stristr($image, System::baseUrl() . '/photo/')) {
450                                         continue;
451                                 }
452                                 $image_uri = substr($image,strrpos($image,'/') + 1);
453                                 $image_uri = substr($image_uri,0, strpos($image_uri,'-'));
454                                 if (!strlen($image_uri)) {
455                                         continue;
456                                 }
457
458                                 // Ensure to only modify photos that you own
459                                 $srch = '<' . intval($original_contact_id) . '>';
460
461                                 $condition = [
462                                         'allow_cid' => $srch, 'allow_gid' => '', 'deny_cid' => '', 'deny_gid' => '',
463                                         'resource-id' => $image_uri, 'uid' => $profile_uid
464                                 ];
465                                 if (!Photo::exists($condition)) {
466                                         continue;
467                                 }
468
469                                 $fields = ['allow_cid' => $str_contact_allow, 'allow_gid' => $str_group_allow,
470                                                 'deny_cid' => $str_contact_deny, 'deny_gid' => $str_group_deny];
471                                 $condition = ['resource-id' => $image_uri, 'uid' => $profile_uid];
472                                 Photo::update($fields, $condition);
473                         }
474                 }
475         }
476
477
478         /*
479          * Next link in any attachment references we find in the post.
480          */
481         $match = false;
482
483         /// @todo these lines should be moved to Model/Attach (Once it exists)
484         if (!$preview && preg_match_all("/\[attachment\](.*?)\[\/attachment\]/", $body, $match)) {
485                 $attaches = $match[1];
486                 if (count($attaches)) {
487                         foreach ($attaches as $attach) {
488                                 // Ensure to only modify attachments that you own
489                                 $srch = '<' . intval($original_contact_id) . '>';
490
491                                 $condition = ['allow_cid' => $srch, 'allow_gid' => '', 'deny_cid' => '', 'deny_gid' => '',
492                                                 'id' => $attach];
493                                 if (!Attach::exists($condition)) {
494                                         continue;
495                                 }
496
497                                 $fields = ['allow_cid' => $str_contact_allow, 'allow_gid' => $str_group_allow,
498                                                 'deny_cid' => $str_contact_deny, 'deny_gid' => $str_group_deny];
499                                 $condition = ['id' => $attach];
500                                 Attach::update($fields, $condition);
501                         }
502                 }
503         }
504
505         // embedded bookmark or attachment in post? set bookmark flag
506
507         $data = BBCode::getAttachmentData($body);
508         if ((preg_match_all("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/ism", $body, $match, PREG_SET_ORDER) || isset($data["type"]))
509                 && ($posttype != Item::PT_PERSONAL_NOTE)) {
510                 $posttype = Item::PT_PAGE;
511                 $objecttype = ACTIVITY_OBJ_BOOKMARK;
512         }
513
514         $body = bb_translate_video($body);
515
516
517         // Fold multi-line [code] sequences
518         $body = preg_replace('/\[\/code\]\s*\[code\]/ism', "\n", $body);
519
520         $body = BBCode::scaleExternalImages($body, false);
521
522         // Setting the object type if not defined before
523         if (!$objecttype) {
524                 $objecttype = ACTIVITY_OBJ_NOTE; // Default value
525                 $objectdata = BBCode::getAttachedData($body);
526
527                 if ($objectdata["type"] == "link") {
528                         $objecttype = ACTIVITY_OBJ_BOOKMARK;
529                 } elseif ($objectdata["type"] == "video") {
530                         $objecttype = ACTIVITY_OBJ_VIDEO;
531                 } elseif ($objectdata["type"] == "photo") {
532                         $objecttype = ACTIVITY_OBJ_IMAGE;
533                 }
534
535         }
536
537         $attachments = '';
538         $match = false;
539
540         if (preg_match_all('/(\[attachment\]([0-9]+)\[\/attachment\])/',$body,$match)) {
541                 foreach ($match[2] as $mtch) {
542                         $fields = ['id', 'filename', 'filesize', 'filetype'];
543                         $attachment = Attach::selectFirst($fields, ['id' => $mtch]);
544                         if ($attachment !== false) {
545                                 if (strlen($attachments)) {
546                                         $attachments .= ',';
547                                 }
548                                 $attachments .= '[attach]href="' . System::baseUrl() . '/attach/' . $attachment['id'] .
549                                                 '" length="' . $attachment['filesize'] . '" type="' . $attachment['filetype'] .
550                                                 '" title="' . ($attachment['filename'] ? $attachment['filename'] : '') . '"[/attach]';
551                         }
552                         $body = str_replace($match[1],'',$body);
553                 }
554         }
555
556         if (!strlen($verb)) {
557                 $verb = ACTIVITY_POST;
558         }
559
560         if ($network == "") {
561                 $network = Protocol::DFRN;
562         }
563
564         $gravity = ($parent ? GRAVITY_COMMENT : GRAVITY_PARENT);
565
566         // even if the post arrived via API we are considering that it
567         // originated on this site by default for determining relayability.
568
569         // Don't use "defaults" here. It would turn 0 to 1
570         if (!isset($_REQUEST['origin'])) {
571                 $origin = 1;
572         } else {
573                 $origin = $_REQUEST['origin'];
574         }
575
576         $notify_type = ($parent ? 'comment-new' : 'wall-new');
577
578         $uri = ($message_id ? $message_id : Item::newURI($api_source ? $profile_uid : $uid, $guid));
579
580         // Fallback so that we alway have a parent uri
581         if (!$thr_parent_uri || !$parent) {
582                 $thr_parent_uri = $uri;
583         }
584
585         $datarray = [];
586         $datarray['uid']           = $profile_uid;
587         $datarray['wall']          = $wall;
588         $datarray['gravity']       = $gravity;
589         $datarray['network']       = $network;
590         $datarray['contact-id']    = $contact_id;
591         $datarray['owner-name']    = $contact_record['name'];
592         $datarray['owner-link']    = $contact_record['url'];
593         $datarray['owner-avatar']  = $contact_record['thumb'];
594         $datarray['owner-id']      = Contact::getIdForURL($datarray['owner-link']);
595         $datarray['author-name']   = $author['name'];
596         $datarray['author-link']   = $author['url'];
597         $datarray['author-avatar'] = $author['thumb'];
598         $datarray['author-id']     = Contact::getIdForURL($datarray['author-link']);
599         $datarray['created']       = DateTimeFormat::utcNow();
600         $datarray['edited']        = DateTimeFormat::utcNow();
601         $datarray['commented']     = DateTimeFormat::utcNow();
602         $datarray['received']      = DateTimeFormat::utcNow();
603         $datarray['changed']       = DateTimeFormat::utcNow();
604         $datarray['extid']         = $extid;
605         $datarray['guid']          = $guid;
606         $datarray['uri']           = $uri;
607         $datarray['title']         = $title;
608         $datarray['body']          = $body;
609         $datarray['app']           = $app;
610         $datarray['location']      = $location;
611         $datarray['coord']         = $coord;
612         $datarray['tag']           = $str_tags;
613         $datarray['file']          = $categories;
614         $datarray['inform']        = $inform;
615         $datarray['verb']          = $verb;
616         $datarray['post-type']     = $posttype;
617         $datarray['object-type']   = $objecttype;
618         $datarray['allow_cid']     = $str_contact_allow;
619         $datarray['allow_gid']     = $str_group_allow;
620         $datarray['deny_cid']      = $str_contact_deny;
621         $datarray['deny_gid']      = $str_group_deny;
622         $datarray['private']       = $private;
623         $datarray['pubmail']       = $pubmail_enabled;
624         $datarray['attach']        = $attachments;
625
626         // This is not a bug. The item store function changes 'parent-uri' to 'thr-parent' and fetches 'parent-uri' new. (We should change this)
627         $datarray['parent-uri']    = $thr_parent_uri;
628
629         $datarray['postopts']      = $postopts;
630         $datarray['origin']        = $origin;
631         $datarray['moderated']     = false;
632         $datarray['object']        = $object;
633
634         /*
635          * These fields are for the convenience of addons...
636          * 'self' if true indicates the owner is posting on their own wall
637          * If parent is 0 it is a top-level post.
638          */
639         $datarray['parent']        = $parent;
640         $datarray['self']          = $self;
641
642         // This triggers posts via API and the mirror functions
643         $datarray['api_source'] = $api_source;
644
645         // This field is for storing the raw conversation data
646         $datarray['protocol'] = Conversation::PARCEL_DFRN;
647
648         $conversation = DBA::selectFirst('conversation', ['conversation-uri', 'conversation-href'], ['item-uri' => $datarray['parent-uri']]);
649         if (DBA::isResult($conversation)) {
650                 if ($conversation['conversation-uri'] != '') {
651                         $datarray['conversation-uri'] = $conversation['conversation-uri'];
652                 }
653                 if ($conversation['conversation-href'] != '') {
654                         $datarray['conversation-href'] = $conversation['conversation-href'];
655                 }
656         }
657
658         if ($orig_post) {
659                 $datarray['edit'] = true;
660         } else {
661                 $datarray['edit'] = false;
662         }
663
664         // Check for hashtags in the body and repair or add hashtag links
665         if ($preview || $orig_post) {
666                 Item::setHashtags($datarray);
667         }
668
669         // preview mode - prepare the body for display and send it via json
670         if ($preview) {
671                 // We set the datarray ID to -1 because in preview mode the dataray
672                 // doesn't have an ID.
673                 $datarray["id"] = -1;
674                 $datarray["item_id"] = -1;
675                 $datarray["author-network"] = Protocol::DFRN;
676
677                 $o = conversation($a, [array_merge($contact_record, $datarray)], new Pager($a->query_string), 'search', false, true);
678                 Logger::log('preview: ' . $o);
679                 echo json_encode(['preview' => $o]);
680                 exit();
681         }
682
683         Hook::callAll('post_local',$datarray);
684
685         if (!empty($datarray['cancel'])) {
686                 Logger::log('mod_item: post cancelled by addon.');
687                 if ($return_path) {
688                         $a->internalRedirect($return_path);
689                 }
690
691                 $json = ['cancel' => 1];
692                 if (!empty($_REQUEST['jsreload'])) {
693                         $json['reload'] = System::baseUrl() . '/' . $_REQUEST['jsreload'];
694                 }
695
696                 echo json_encode($json);
697                 exit();
698         }
699
700         if ($orig_post) {
701                 // Fill the cache field
702                 // This could be done in Item::update as well - but we have to check for the existance of some fields.
703                 Item::putInCache($datarray);
704
705                 $fields = [
706                         'title' => $datarray['title'],
707                         'body' => $datarray['body'],
708                         'tag' => $datarray['tag'],
709                         'attach' => $datarray['attach'],
710                         'file' => $datarray['file'],
711                         'rendered-html' => $datarray['rendered-html'],
712                         'rendered-hash' => $datarray['rendered-hash'],
713                         'edited' => DateTimeFormat::utcNow(),
714                         'changed' => DateTimeFormat::utcNow()];
715
716                 Item::update($fields, ['id' => $post_id]);
717
718                 // update filetags in pconfig
719                 FileTag::updatePconfig($uid, $categories_old, $categories_new, 'category');
720
721                 if (!empty($_REQUEST['return']) && strlen($return_path)) {
722                         Logger::log('return: ' . $return_path);
723                         $a->internalRedirect($return_path);
724                 }
725                 exit();
726         } else {
727                 $post_id = 0;
728         }
729
730         unset($datarray['edit']);
731         unset($datarray['self']);
732         unset($datarray['api_source']);
733
734         if ($origin) {
735                 $signed = Diaspora::createCommentSignature($uid, $datarray);
736                 if (!empty($signed)) {
737                         $datarray['diaspora_signed_text'] = json_encode($signed);
738                 }
739         }
740
741         $post_id = Item::insert($datarray);
742
743         if (!$post_id) {
744                 Logger::log("Item wasn't stored.");
745                 $a->internalRedirect($return_path);
746         }
747
748         $datarray = Item::selectFirst(Item::ITEM_FIELDLIST, ['id' => $post_id]);
749
750         if (!DBA::isResult($datarray)) {
751                 Logger::log("Item with id ".$post_id." couldn't be fetched.");
752                 $a->internalRedirect($return_path);
753         }
754
755         // update filetags in pconfig
756         FileTag::updatePconfig($uid, $categories_old, $categories_new, 'category');
757
758         // These notifications are sent if someone else is commenting other your wall
759         if ($parent) {
760                 if ($contact_record != $author) {
761                         notification([
762                                 'type'         => NOTIFY_COMMENT,
763                                 'notify_flags' => $user['notify-flags'],
764                                 'language'     => $user['language'],
765                                 'to_name'      => $user['username'],
766                                 'to_email'     => $user['email'],
767                                 'uid'          => $user['uid'],
768                                 'item'         => $datarray,
769                                 'link'         => System::baseUrl().'/display/'.urlencode($datarray['guid']),
770                                 'source_name'  => $datarray['author-name'],
771                                 'source_link'  => $datarray['author-link'],
772                                 'source_photo' => $datarray['author-avatar'],
773                                 'verb'         => ACTIVITY_POST,
774                                 'otype'        => 'item',
775                                 'parent'       => $parent,
776                                 'parent_uri'   => $parent_item['uri']
777                         ]);
778                 }
779         } else {
780                 if (($contact_record != $author) && !count($forum_contact)) {
781                         notification([
782                                 'type'         => NOTIFY_WALL,
783                                 'notify_flags' => $user['notify-flags'],
784                                 'language'     => $user['language'],
785                                 'to_name'      => $user['username'],
786                                 'to_email'     => $user['email'],
787                                 'uid'          => $user['uid'],
788                                 'item'         => $datarray,
789                                 'link'         => System::baseUrl().'/display/'.urlencode($datarray['guid']),
790                                 'source_name'  => $datarray['author-name'],
791                                 'source_link'  => $datarray['author-link'],
792                                 'source_photo' => $datarray['author-avatar'],
793                                 'verb'         => ACTIVITY_POST,
794                                 'otype'        => 'item'
795                         ]);
796                 }
797         }
798
799         Hook::callAll('post_local_end', $datarray);
800
801         if (strlen($emailcc) && $profile_uid == local_user()) {
802                 $erecips = explode(',', $emailcc);
803                 if (count($erecips)) {
804                         foreach ($erecips as $recip) {
805                                 $addr = trim($recip);
806                                 if (!strlen($addr)) {
807                                         continue;
808                                 }
809                                 $disclaimer = '<hr />' . L10n::t('This message was sent to you by %s, a member of the Friendica social network.', $a->user['username'])
810                                         . '<br />';
811                                 $disclaimer .= L10n::t('You may visit them online at %s', System::baseUrl() . '/profile/' . $a->user['nickname']) . EOL;
812                                 $disclaimer .= L10n::t('Please contact the sender by replying to this post if you do not wish to receive these messages.') . EOL;
813                                 if (!$datarray['title']=='') {
814                                         $subject = Email::encodeHeader($datarray['title'], 'UTF-8');
815                                 } else {
816                                         $subject = Email::encodeHeader('[Friendica]' . ' ' . L10n::t('%s posted an update.', $a->user['username']), 'UTF-8');
817                                 }
818                                 $link = '<a href="' . System::baseUrl() . '/profile/' . $a->user['nickname'] . '"><img src="' . $author['thumb'] . '" alt="' . $a->user['username'] . '" /></a><br /><br />';
819                                 $html    = Item::prepareBody($datarray);
820                                 $message = '<html><body>' . $link . $html . $disclaimer . '</body></html>';
821                                 $params =  [
822                                         'fromName' => $a->user['username'],
823                                         'fromEmail' => $a->user['email'],
824                                         'toEmail' => $addr,
825                                         'replyTo' => $a->user['email'],
826                                         'messageSubject' => $subject,
827                                         'htmlVersion' => $message,
828                                         'textVersion' => HTML::toPlaintext($html.$disclaimer)
829                                 ];
830                                 Emailer::send($params);
831                         }
832                 }
833         }
834
835         // Insert an item entry for UID=0 for global entries.
836         // We now do it in the background to save some time.
837         // This is important in interactive environments like the frontend or the API.
838         // We don't fork a new process since this is done anyway with the following command
839         Worker::add(['priority' => PRIORITY_HIGH, 'dont_fork' => true], "CreateShadowEntry", $post_id);
840
841         // When we are doing some forum posting via ! we have to start the notifier manually.
842         // These kind of posts don't initiate the notifier call in the item class.
843         if ($only_to_forum) {
844                 Worker::add(PRIORITY_HIGH, "Notifier", $notify_type, $post_id);
845         }
846
847         Logger::log('post_complete');
848
849         if ($api_source) {
850                 return $post_id;
851         }
852
853         item_post_return(System::baseUrl(), $api_source, $return_path);
854         // NOTREACHED
855 }
856
857 function item_post_return($baseurl, $api_source, $return_path)
858 {
859         // figure out how to return, depending on from whence we came
860     $a = \get_app();
861
862         if ($api_source) {
863                 return;
864         }
865
866         if ($return_path) {
867                 $a->internalRedirect($return_path);
868         }
869
870         $json = ['success' => 1];
871         if (!empty($_REQUEST['jsreload'])) {
872                 $json['reload'] = $baseurl . '/' . $_REQUEST['jsreload'];
873         }
874
875         Logger::log('post_json: ' . print_r($json, true), Logger::DEBUG);
876
877         echo json_encode($json);
878         exit();
879 }
880
881 function item_content(App $a)
882 {
883         if (!local_user() && !remote_user()) {
884                 return;
885         }
886
887         $o = '';
888
889         if (($a->argc >= 3) && ($a->argv[1] === 'drop') && intval($a->argv[2])) {
890                 if ($a->isAjax()) {
891                         $o = Item::deleteForUser(['id' => $a->argv[2]], local_user());
892                 } else {
893                         if (!empty($a->argv[3])) {
894                                 $o = drop_item($a->argv[2], $a->argv[3]);
895                         }
896                         else {
897                                 $o = drop_item($a->argv[2]);
898                         }
899                 }
900
901                 if ($a->isAjax()) {
902                         // ajax return: [<item id>, 0 (no perm) | <owner id>]
903                         echo json_encode([intval($a->argv[2]), intval($o)]);
904                         exit();
905                 }
906         }
907
908         return $o;
909 }
910
911 /**
912  * This function removes the tag $tag from the text $body and replaces it with
913  * the appropriate link.
914  *
915  * @param App     $a
916  * @param string  $body     the text to replace the tag in
917  * @param string  $inform   a comma-seperated string containing everybody to inform
918  * @param string  $str_tags string to add the tag to
919  * @param integer $profile_uid
920  * @param string  $tag      the tag to replace
921  * @param string  $network  The network of the post
922  *
923  * @return array|bool ['replaced' => $replaced, 'contact' => $contact];
924  * @throws ImagickException
925  * @throws \Friendica\Network\HTTPException\InternalServerErrorException
926  */
927 function handle_tag(App $a, &$body, &$inform, &$str_tags, $profile_uid, $tag, $network = "")
928 {
929         $replaced = false;
930         $r = null;
931         $tag_type = '@';
932
933         //is it a person tag?
934         if ((strpos($tag, '@') === 0) || (strpos($tag, '!') === 0)) {
935                 $tag_type = substr($tag, 0, 1);
936                 //is it already replaced?
937                 if (strpos($tag, '[url=')) {
938                         //append tag to str_tags
939                         if (!stristr($str_tags, $tag)) {
940                                 if (strlen($str_tags)) {
941                                         $str_tags .= ',';
942                                 }
943                                 $str_tags .= $tag;
944                         }
945
946                         // Checking for the alias that is used for OStatus
947                         $pattern = "/[@!]\[url\=(.*?)\](.*?)\[\/url\]/ism";
948                         if (preg_match($pattern, $tag, $matches)) {
949                                 $data = Contact::getDetailsByURL($matches[1]);
950
951                                 if ($data["alias"] != "") {
952                                         $newtag = '@[url=' . $data["alias"] . ']' . $data["nick"] . '[/url]';
953
954                                         if (!stripos($str_tags, '[url=' . $data["alias"] . ']')) {
955                                                 if (strlen($str_tags)) {
956                                                         $str_tags .= ',';
957                                                 }
958
959                                                 $str_tags .= $newtag;
960                                         }
961                                 }
962                         }
963
964                         return $replaced;
965                 }
966
967                 $stat = false;
968                 //get the person's name
969                 $name = substr($tag, 1);
970
971                 // Sometimes the tag detection doesn't seem to work right
972                 // This is some workaround
973                 $nameparts = explode(" ", $name);
974                 $name = $nameparts[0];
975
976                 // Try to detect the contact in various ways
977                 if (strpos($name, 'http://')) {
978                         // At first we have to ensure that the contact exists
979                         Contact::getIdForURL($name);
980
981                         // Now we should have something
982                         $contact = Contact::getDetailsByURL($name);
983                 } elseif (strpos($name, '@')) {
984                         // This function automatically probes when no entry was found
985                         $contact = Contact::getDetailsByAddr($name);
986                 } else {
987                         $contact = false;
988                         $fields = ['id', 'url', 'nick', 'name', 'alias', 'network', 'forum', 'prv'];
989
990                         if (strrpos($name, '+')) {
991                                 // Is it in format @nick+number?
992                                 $tagcid = intval(substr($name, strrpos($name, '+') + 1));
993                                 $contact = DBA::selectFirst('contact', $fields, ['id' => $tagcid, 'uid' => $profile_uid]);
994                         }
995
996                         // select someone by nick or attag in the current network
997                         if (!DBA::isResult($contact) && ($network != "")) {
998                                 $condition = ["(`nick` = ? OR `attag` = ?) AND `network` = ? AND `uid` = ?",
999                                                 $name, $name, $network, $profile_uid];
1000                                 $contact = DBA::selectFirst('contact', $fields, $condition);
1001                         }
1002
1003                         //select someone by name in the current network
1004                         if (!DBA::isResult($contact) && ($network != "")) {
1005                                 $condition = ['name' => $name, 'network' => $network, 'uid' => $profile_uid];
1006                                 $contact = DBA::selectFirst('contact', $fields, $condition);
1007                         }
1008
1009                         // select someone by nick or attag in any network
1010                         if (!DBA::isResult($contact)) {
1011                                 $condition = ["(`nick` = ? OR `attag` = ?) AND `uid` = ?", $name, $name, $profile_uid];
1012                                 $contact = DBA::selectFirst('contact', $fields, $condition);
1013                         }
1014
1015                         // select someone by name in any network
1016                         if (!DBA::isResult($contact)) {
1017                                 $condition = ['name' => $name, 'uid' => $profile_uid];
1018                                 $contact = DBA::selectFirst('contact', $fields, $condition);
1019                         }
1020                 }
1021
1022                 // Check if $contact has been successfully loaded
1023                 if (DBA::isResult($contact)) {
1024                         if (strlen($inform) && (isset($contact["notify"]) || isset($contact["id"]))) {
1025                                 $inform .= ',';
1026                         }
1027
1028                         if (isset($contact["id"])) {
1029                                 $inform .= 'cid:' . $contact["id"];
1030                         } elseif (isset($contact["notify"])) {
1031                                 $inform  .= $contact["notify"];
1032                         }
1033
1034                         $profile = $contact["url"];
1035                         $alias   = $contact["alias"];
1036                         $newname = defaults($contact, "name", $contact["nick"]);
1037                 }
1038
1039                 //if there is an url for this persons profile
1040                 if (isset($profile) && ($newname != "")) {
1041                         $replaced = true;
1042                         // create profile link
1043                         $profile = str_replace(',', '%2c', $profile);
1044                         $newtag = $tag_type.'[url=' . $profile . ']' . $newname . '[/url]';
1045                         $body = str_replace($tag_type . $name, $newtag, $body);
1046                         // append tag to str_tags
1047                         if (!stristr($str_tags, $newtag)) {
1048                                 if (strlen($str_tags)) {
1049                                         $str_tags .= ',';
1050                                 }
1051                                 $str_tags .= $newtag;
1052                         }
1053
1054                         /*
1055                          * Status.Net seems to require the numeric ID URL in a mention if the person isn't
1056                          * subscribed to you. But the nickname URL is OK if they are. Grrr. We'll tag both.
1057                          */
1058                         if (strlen($alias)) {
1059                                 $newtag = '@[url=' . $alias . ']' . $newname . '[/url]';
1060                                 if (!stripos($str_tags, '[url=' . $alias . ']')) {
1061                                         if (strlen($str_tags)) {
1062                                                 $str_tags .= ',';
1063                                         }
1064                                         $str_tags .= $newtag;
1065                                 }
1066                         }
1067                 }
1068         }
1069
1070         return ['replaced' => $replaced, 'contact' => $contact];
1071 }