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