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