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