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