]> git.mxchange.org Git - friendica.git/blob - mod/item.php
Move remaining functions
[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 use Friendica\App;
18 use Friendica\Content\Text\BBCode;
19 use Friendica\Core\Addon;
20 use Friendica\Core\Config;
21 use Friendica\Core\L10n;
22 use Friendica\Core\System;
23 use Friendica\Core\Worker;
24 use Friendica\Database\DBM;
25 use Friendica\Model\Contact;
26 use Friendica\Model\GContact;
27 use Friendica\Model\Item;
28 use Friendica\Network\Probe;
29 use Friendica\Protocol\Diaspora;
30 use Friendica\Protocol\Email;
31 use Friendica\Util\Emailer;
32 use Friendica\Util\Network;
33
34 require_once 'include/enotify.php';
35 require_once 'include/tags.php';
36 require_once 'include/threads.php';
37 require_once 'include/text.php';
38 require_once 'include/items.php';
39
40 function item_post(App $a) {
41         if (!local_user() && !remote_user()) {
42                 return;
43         }
44
45         require_once 'include/security.php';
46
47         $uid = local_user();
48
49         if (x($_REQUEST, 'dropitems')) {
50                 $arr_drop = explode(',', $_REQUEST['dropitems']);
51                 drop_items($arr_drop);
52                 $json = ['success' => 1];
53                 echo json_encode($json);
54                 killme();
55         }
56
57         Addon::callHooks('post_local_start', $_REQUEST);
58
59         logger('postvars ' . print_r($_REQUEST,true), LOGGER_DATA);
60
61         $api_source = defaults($_REQUEST, 'api_source', false);
62
63         $message_id = ((x($_REQUEST, 'message_id') && $api_source) ? strip_tags($_REQUEST['message_id']) : '');
64
65         $return_path = defaults($_REQUEST, 'return', '');
66         $preview = intval(defaults($_REQUEST, 'preview', 0));
67
68         /*
69          * Check for doubly-submitted posts, and reject duplicates
70          * Note that we have to ignore previews, otherwise nothing will post
71          * after it's been previewed
72          */
73         if (!$preview && x($_REQUEST, 'post_id_random')) {
74                 if (x($_SESSION, 'post-random') && $_SESSION['post-random'] == $_REQUEST['post_id_random']) {
75                         logger("item post: duplicate post", LOGGER_DEBUG);
76                         item_post_return(System::baseUrl(), $api_source, $return_path);
77                 } else {
78                         $_SESSION['post-random'] = $_REQUEST['post_id_random'];
79                 }
80         }
81
82         // Is this a reply to something?
83         $thr_parent = intval(defaults($_REQUEST, 'parent', 0));
84         $thr_parent_uri = trim(defaults($_REQUEST, 'parent_uri', ''));
85
86         $thr_parent_contact = null;
87
88         $parent = 0;
89         $parent_item = null;
90         $parent_user = null;
91
92         $parent_contact = null;
93
94         $objecttype = null;
95         $profile_uid = defaults($_REQUEST, 'profile_uid', local_user());
96
97         if ($thr_parent || $thr_parent_uri) {
98                 if ($thr_parent) {
99                         $parent_item = dba::selectFirst('item', [], ['id' => $thr_parent]);
100                 } elseif ($thr_parent_uri) {
101                         $parent_item = dba::selectFirst('item', [], ['uri' => $thr_parent_uri, 'uid' => $profile_uid]);
102                 }
103
104                 // if this isn't the real parent of the conversation, find it
105                 if (DBM::is_result($parent_item)) {
106
107                         // The URI and the contact is taken from the direct parent which needn't to be the top parent
108                         $thr_parent_uri = $parent_item['uri'];
109                         $thr_parent_contact = Contact::getDetailsByURL($parent_item["author-link"]);
110
111                         if ($parent_item['id'] != $parent_item['parent']) {
112                                 $parent_item = dba::selectFirst('item', [], ['id' => $parent_item['parent']]);
113                         }
114                 }
115
116                 if (!DBM::is_result($parent_item)) {
117                         notice(L10n::t('Unable to locate original post.') . EOL);
118                         if (x($_REQUEST, 'return')) {
119                                 goaway($return_path);
120                         }
121                         killme();
122                 }
123
124                 $parent = $parent_item['id'];
125                 $parent_user = $parent_item['uid'];
126
127                 $parent_contact = Contact::getDetailsByURL($parent_item["author-link"]);
128
129                 $objecttype = ACTIVITY_OBJ_COMMENT;
130
131                 if (!x($_REQUEST, 'type')) {
132                         $_REQUEST['type'] = 'net-comment';
133                 }
134         }
135
136         if ($parent) {
137                 logger('mod_item: item_post parent=' . $parent);
138         }
139
140         $post_id     = intval(defaults($_REQUEST, 'post_id', 0));
141         $app         = strip_tags(defaults($_REQUEST, 'source', ''));
142         $extid       = strip_tags(defaults($_REQUEST, 'extid', ''));
143         $object      = defaults($_REQUEST, 'object', '');
144
145         // Ensure that the user id in a thread always stay the same
146         if (!is_null($parent_user) && in_array($parent_user, [local_user(), 0])) {
147                 $profile_uid = $parent_user;
148         }
149
150         // Check for multiple posts with the same message id (when the post was created via API)
151         if (($message_id != '') && ($profile_uid != 0)) {
152                 if (dba::exists('item', ['uri' => $message_id, 'uid' => $profile_uid])) {
153                         logger("Message with URI ".$message_id." already exists for user ".$profile_uid, LOGGER_DEBUG);
154                         return;
155                 }
156         }
157
158         // Allow commenting if it is an answer to a public post
159         $allow_comment = local_user() && ($profile_uid == 0) && $parent && in_array($parent_item['network'], [NETWORK_OSTATUS, NETWORK_DIASPORA, NETWORK_DFRN]);
160
161         // Now check that valid personal details have been provided
162         if (!can_write_wall($profile_uid) && !$allow_comment) {
163                 notice(L10n::t('Permission denied.') . EOL) ;
164                 if (x($_REQUEST, 'return')) {
165                         goaway($return_path);
166                 }
167                 killme();
168         }
169
170
171         // is this an edited post?
172
173         $orig_post = null;
174
175         if ($post_id) {
176                 $orig_post = dba::selectFirst('item', [], ['id' => $post_id]);
177         }
178
179         $user = dba::selectFirst('user', [], ['uid' => $profile_uid]);
180         if (!DBM::is_result($user) && !$parent) {
181                 return;
182         }
183
184         if ($orig_post) {
185                 $str_group_allow   = $orig_post['allow_gid'];
186                 $str_contact_allow = $orig_post['allow_cid'];
187                 $str_group_deny    = $orig_post['deny_gid'];
188                 $str_contact_deny  = $orig_post['deny_cid'];
189                 $location          = $orig_post['location'];
190                 $coord             = $orig_post['coord'];
191                 $verb              = $orig_post['verb'];
192                 $objecttype        = $orig_post['object-type'];
193                 $emailcc           = $orig_post['emailcc'];
194                 $app               = $orig_post['app'];
195                 $categories        = $orig_post['file'];
196                 $title             = notags(trim($_REQUEST['title']));
197                 $body              = escape_tags(trim($_REQUEST['body']));
198                 $private           = $orig_post['private'];
199                 $pubmail_enabled   = $orig_post['pubmail'];
200                 $network           = $orig_post['network'];
201                 $guid              = $orig_post['guid'];
202                 $extid             = $orig_post['extid'];
203
204         } else {
205
206                 /*
207                  * if coming from the API and no privacy settings are set,
208                  * use the user default permissions - as they won't have
209                  * been supplied via a form.
210                  */
211                 /// @TODO use x($_REQUEST, 'foo') here
212                 if ($api_source
213                         && !array_key_exists('contact_allow', $_REQUEST)
214                         && !array_key_exists('group_allow', $_REQUEST)
215                         && !array_key_exists('contact_deny', $_REQUEST)
216                         && !array_key_exists('group_deny', $_REQUEST)) {
217                         $str_group_allow   = $user['allow_gid'];
218                         $str_contact_allow = $user['allow_cid'];
219                         $str_group_deny    = $user['deny_gid'];
220                         $str_contact_deny  = $user['deny_cid'];
221                 } else {
222                         // use the posted permissions
223                         $str_group_allow   = perms2str($_REQUEST['group_allow']);
224                         $str_contact_allow = perms2str($_REQUEST['contact_allow']);
225                         $str_group_deny    = perms2str($_REQUEST['group_deny']);
226                         $str_contact_deny  = perms2str($_REQUEST['contact_deny']);
227                 }
228
229                 $title             = notags(trim($_REQUEST['title']));
230                 $location          = notags(trim($_REQUEST['location']));
231                 $coord             = notags(trim($_REQUEST['coord']));
232                 $verb              = notags(trim($_REQUEST['verb']));
233                 $emailcc           = notags(trim($_REQUEST['emailcc']));
234                 $body              = escape_tags(trim($_REQUEST['body']));
235                 $network           = notags(trim($_REQUEST['network']));
236                 $guid              = get_guid(32);
237
238                 $postopts = defaults($_REQUEST, 'postopts', '');
239
240                 $private = ((strlen($str_group_allow) || strlen($str_contact_allow) || strlen($str_group_deny) || strlen($str_contact_deny)) ? 1 : 0);
241
242                 if ($user['hidewall']) {
243                         $private = 2;
244                 }
245
246                 // If this is a comment, set the permissions from the parent.
247
248                 if ($parent_item) {
249
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 (strlen($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($_REQUEST['category']), 'category');
292         $categories_new = $categories;
293         if (strlen($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 = Network::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 ? 6 : 0);
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_new_uri($a->get_hostname(), $profile_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'], 0);
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'], 0);
604         $datarray['created']       = datetime_convert();
605         $datarray['edited']        = datetime_convert();
606         $datarray['commented']     = datetime_convert();
607         $datarray['received']      = datetime_convert();
608         $datarray['changed']       = datetime_convert();
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['gcontact-id']   = GContact::getId(["url" => $datarray['author-link'], "network" => $datarray['network'],
638                                                         "photo" => $datarray['author-avatar'], "name" => $datarray['author-name']]);
639         $datarray['object']        = $object;
640
641         /*
642          * These fields are for the convenience of addons...
643          * 'self' if true indicates the owner is posting on their own wall
644          * If parent is 0 it is a top-level post.
645          */
646         $datarray['parent']        = $parent;
647         $datarray['self']          = $self;
648
649         // This triggers posts via API and the mirror functions
650         $datarray['api_source'] = $api_source;
651
652         // This field is for storing the raw conversation data
653         $datarray['protocol'] = PROTOCOL_DFRN;
654
655         $r = dba::fetch_first("SELECT `conversation-uri`, `conversation-href` FROM `conversation` WHERE `item-uri` = ?", $datarray['parent-uri']);
656         if (DBM::is_result($r)) {
657                 if ($r['conversation-uri'] != '') {
658                         $datarray['conversation-uri'] = $r['conversation-uri'];
659                 }
660                 if ($r['conversation-href'] != '') {
661                         $datarray['conversation-href'] = $r['conversation-href'];
662                 }
663         }
664
665         if ($orig_post) {
666                 $datarray['edit'] = true;
667         }
668
669         // preview mode - prepare the body for display and send it via json
670         if ($preview) {
671                 require_once 'include/conversation.php';
672                 // We set the datarray ID to -1 because in preview mode the dataray
673                 // doesn't have an ID.
674                 $datarray["id"] = -1;
675                 $o = conversation($a,[array_merge($contact_record,$datarray)],'search', false, true);
676                 logger('preview: ' . $o);
677                 echo json_encode(['preview' => $o]);
678                 killme();
679         }
680
681         Addon::callHooks('post_local',$datarray);
682
683         if (x($datarray, 'cancel')) {
684                 logger('mod_item: post cancelled by addon.');
685                 if ($return_path) {
686                         goaway($return_path);
687                 }
688
689                 $json = ['cancel' => 1];
690                 if (x($_REQUEST, 'jsreload') && strlen($_REQUEST['jsreload'])) {
691                         $json['reload'] = System::baseUrl() . '/' . $_REQUEST['jsreload'];
692                 }
693
694                 echo json_encode($json);
695                 killme();
696         }
697
698         if ($orig_post) {
699
700                 // Fill the cache field
701                 // This could be done in Item::update as well - but we have to check for the existance of some fields.
702                 put_item_in_cache($datarray);
703
704                 $fields = [
705                         'title' => $datarray['title'],
706                         'body' => $datarray['body'],
707                         'tag' => $datarray['tag'],
708                         'attach' => $datarray['attach'],
709                         'file' => $datarray['file'],
710                         'rendered-html' => $datarray['rendered-html'],
711                         'rendered-hash' => $datarray['rendered-hash'],
712                         'edited' => datetime_convert(),
713                         'changed' => datetime_convert()];
714
715                 Item::update($fields, ['id' => $post_id]);
716
717                 // update filetags in pconfig
718                 file_tag_update_pconfig($uid,$categories_old,$categories_new,'category');
719
720                 if (x($_REQUEST, 'return') && strlen($return_path)) {
721                         logger('return: ' . $return_path);
722                         goaway($return_path);
723                 }
724                 killme();
725         } else {
726                 $post_id = 0;
727         }
728
729         unset($datarray['edit']);
730         unset($datarray['self']);
731         unset($datarray['api_source']);
732
733         $post_id = item_store($datarray);
734
735         if (!$post_id) {
736                 logger("Item wasn't stored.");
737                 goaway($return_path);
738         }
739
740         $datarray = dba::selectFirst('item', [], ['id' => $post_id]);
741
742         if (!DBM::is_result($datarray)) {
743                 logger("Item with id ".$post_id." couldn't be fetched.");
744                 goaway($return_path);
745         }
746
747         // update filetags in pconfig
748         file_tag_update_pconfig($uid, $categories_old, $categories_new, 'category');
749
750         // These notifications are sent if someone else is commenting other your wall
751         if ($parent) {
752                 if ($contact_record != $author) {
753                         notification([
754                                 'type'         => NOTIFY_COMMENT,
755                                 'notify_flags' => $user['notify-flags'],
756                                 'language'     => $user['language'],
757                                 'to_name'      => $user['username'],
758                                 'to_email'     => $user['email'],
759                                 'uid'          => $user['uid'],
760                                 'item'         => $datarray,
761                                 'link'         => System::baseUrl().'/display/'.urlencode($datarray['guid']),
762                                 'source_name'  => $datarray['author-name'],
763                                 'source_link'  => $datarray['author-link'],
764                                 'source_photo' => $datarray['author-avatar'],
765                                 'verb'         => ACTIVITY_POST,
766                                 'otype'        => 'item',
767                                 'parent'       => $parent,
768                                 'parent_uri'   => $parent_item['uri']
769                         ]);
770                 }
771
772                 // Store the comment signature information in case we need to relay to Diaspora
773                 Diaspora::storeCommentSignature($datarray, $author, ($self ? $user['prvkey'] : false), $post_id);
774         } else {
775                 if (($contact_record != $author) && !count($forum_contact)) {
776                         notification([
777                                 'type'         => NOTIFY_WALL,
778                                 'notify_flags' => $user['notify-flags'],
779                                 'language'     => $user['language'],
780                                 'to_name'      => $user['username'],
781                                 'to_email'     => $user['email'],
782                                 'uid'          => $user['uid'],
783                                 'item'         => $datarray,
784                                 'link'         => System::baseUrl().'/display/'.urlencode($datarray['guid']),
785                                 'source_name'  => $datarray['author-name'],
786                                 'source_link'  => $datarray['author-link'],
787                                 'source_photo' => $datarray['author-avatar'],
788                                 'verb'         => ACTIVITY_POST,
789                                 'otype'        => 'item'
790                         ]);
791                 }
792         }
793
794         Addon::callHooks('post_local_end', $datarray);
795
796         if (strlen($emailcc) && $profile_uid == local_user()) {
797                 $erecips = explode(',', $emailcc);
798                 if (count($erecips)) {
799                         foreach ($erecips as $recip) {
800                                 $addr = trim($recip);
801                                 if (!strlen($addr)) {
802                                         continue;
803                                 }
804                                 $disclaimer = '<hr />' . L10n::t('This message was sent to you by %s, a member of the Friendica social network.', $a->user['username'])
805                                         . '<br />';
806                                 $disclaimer .= L10n::t('You may visit them online at %s', System::baseUrl() . '/profile/' . $a->user['nickname']) . EOL;
807                                 $disclaimer .= L10n::t('Please contact the sender by replying to this post if you do not wish to receive these messages.') . EOL;
808                                 if (!$datarray['title']=='') {
809                                         $subject = Email::encodeHeader($datarray['title'], 'UTF-8');
810                                 } else {
811                                         $subject = Email::encodeHeader('[Friendica]' . ' ' . L10n::t('%s posted an update.', $a->user['username']), 'UTF-8');
812                                 }
813                                 $link = '<a href="' . System::baseUrl() . '/profile/' . $a->user['nickname'] . '"><img src="' . $author['thumb'] . '" alt="' . $a->user['username'] . '" /></a><br /><br />';
814                                 $html    = prepare_body($datarray);
815                                 $message = '<html><body>' . $link . $html . $disclaimer . '</body></html>';
816                                 include_once 'include/html2plain.php';
817                                 $params =  [
818                                         'fromName' => $a->user['username'],
819                                         'fromEmail' => $a->user['email'],
820                                         'toEmail' => $addr,
821                                         'replyTo' => $a->user['email'],
822                                         'messageSubject' => $subject,
823                                         'htmlVersion' => $message,
824                                         'textVersion' => html2plain($html.$disclaimer)
825                                 ];
826                                 Emailer::send($params);
827                         }
828                 }
829         }
830
831         // Insert an item entry for UID=0 for global entries.
832         // We now do it in the background to save some time.
833         // This is important in interactive environments like the frontend or the API.
834         // We don't fork a new process since this is done anyway with the following command
835         Worker::add(['priority' => PRIORITY_HIGH, 'dont_fork' => true], "CreateShadowEntry", $post_id);
836
837         // Call the background process that is delivering the item to the receivers
838         Worker::add(PRIORITY_HIGH, "Notifier", $notify_type, $post_id);
839
840         logger('post_complete');
841
842         item_post_return(System::baseUrl(), $api_source, $return_path);
843         // NOTREACHED
844 }
845
846 function item_post_return($baseurl, $api_source, $return_path) {
847         // figure out how to return, depending on from whence we came
848
849         if ($api_source) {
850                 return;
851         }
852
853         if ($return_path) {
854                 goaway($return_path);
855         }
856
857         $json = ['success' => 1];
858         if (x($_REQUEST, 'jsreload') && strlen($_REQUEST['jsreload'])) {
859                 $json['reload'] = $baseurl . '/' . $_REQUEST['jsreload'];
860         }
861
862         logger('post_json: ' . print_r($json,true), LOGGER_DEBUG);
863
864         echo json_encode($json);
865         killme();
866 }
867
868
869
870 function item_content(App $a) {
871
872         if (!local_user() && !remote_user()) {
873                 return;
874         }
875
876         require_once 'include/security.php';
877
878         $o = '';
879         if (($a->argc == 3) && ($a->argv[1] === 'drop') && intval($a->argv[2])) {
880                 if (is_ajax()) {
881                         $o = Item::delete($a->argv[2]);
882                 } else {
883                         $o = drop_item($a->argv[2]);
884                 }
885                 if (is_ajax()) {
886                         // ajax return: [<item id>, 0 (no perm) | <owner id>]
887                         echo json_encode([intval($a->argv[2]), intval($o)]);
888                         killme();
889                 }
890         }
891         return $o;
892 }
893
894 /**
895  * This function removes the tag $tag from the text $body and replaces it with
896  * the appropiate link.
897  *
898  * @param App $a Application instance @TODO is unused in this function's scope (excluding included files)
899  * @param unknown_type $body the text to replace the tag in
900  * @param string $inform a comma-seperated string containing everybody to inform
901  * @param string $str_tags string to add the tag to
902  * @param integer $profile_uid
903  * @param string $tag the tag to replace
904  * @param string $network The network of the post
905  *
906  * @return boolean true if replaced, false if not replaced
907  */
908 function handle_tag(App $a, &$body, &$inform, &$str_tags, $profile_uid, $tag, $network = "")
909 {
910         $replaced = false;
911         $r = null;
912         $tag_type = '@';
913
914         //is it a person tag?
915         if ((strpos($tag, '@') === 0) || (strpos($tag, '!') === 0)) {
916                 $tag_type = substr($tag, 0, 1);
917                 //is it already replaced?
918                 if (strpos($tag, '[url=')) {
919                         //append tag to str_tags
920                         if (!stristr($str_tags, $tag)) {
921                                 if (strlen($str_tags)) {
922                                         $str_tags .= ',';
923                                 }
924                                 $str_tags .= $tag;
925                         }
926
927                         // Checking for the alias that is used for OStatus
928                         $pattern = "/[@!]\[url\=(.*?)\](.*?)\[\/url\]/ism";
929                         if (preg_match($pattern, $tag, $matches)) {
930                                 $data = Contact::getDetailsByURL($matches[1]);
931                                 if ($data["alias"] != "") {
932                                         $newtag = '@[url=' . $data["alias"] . ']' . $data["nick"] . '[/url]';
933                                         if (!stripos($str_tags, '[url=' . $data["alias"] . ']')) {
934                                                 if (strlen($str_tags)) {
935                                                         $str_tags .= ',';
936                                                 }
937                                                 $str_tags .= $newtag;
938                                         }
939                                 }
940                         }
941
942                         return $replaced;
943                 }
944                 $stat = false;
945                 //get the person's name
946                 $name = substr($tag, 1);
947
948                 // Sometimes the tag detection doesn't seem to work right
949                 // This is some workaround
950                 $nameparts = explode(" ", $name);
951                 $name = $nameparts[0];
952
953                 // Try to detect the contact in various ways
954                 if (strpos($name, 'http://')) {
955                         // At first we have to ensure that the contact exists
956                         Contact::getIdForURL($name);
957
958                         // Now we should have something
959                         $contact = Contact::getDetailsByURL($name);
960                 } elseif (strpos($name, '@')) {
961                         // This function automatically probes when no entry was found
962                         $contact = Contact::getDetailsByAddr($name);
963                 } else {
964                         $contact = false;
965                         $fields = ['id', 'url', 'nick', 'name', 'alias', 'network'];
966
967                         if (strrpos($name, '+')) {
968                                 // Is it in format @nick+number?
969                                 $tagcid = intval(substr($name, strrpos($name, '+') + 1));
970                                 $contact = dba::selectFirst('contact', $fields, ['id' => $tagcid, 'uid' => $profile_uid]);
971                         }
972
973                         // select someone by nick or attag in the current network
974                         if (!DBM::is_result($contact) && ($network != "")) {
975                                 $condition = ["(`nick` = ? OR `attag` = ?) AND `network` = ? AND `uid` = ?",
976                                                 $name, $name, $network, $profile_uid];
977                                 $contact = dba::selectFirst('contact', $fields, $condition);
978                         }
979
980                         //select someone by name in the current network
981                         if (!DBM::is_result($contact) && ($network != "")) {
982                                 $condition = ['name' => $name, 'network' => $network, 'uid' => $profile_uid];
983                                 $contact = dba::selectFirst('contact', $fields, $condition);
984                         }
985
986                         // select someone by nick or attag in any network
987                         if (!DBM::is_result($contact)) {
988                                 $condition = ["(`nick` = ? OR `attag` = ?) AND `uid` = ?", $name, $name, $profile_uid];
989                                 $contact = dba::selectFirst('contact', $fields, $condition);
990                         }
991
992                         // select someone by name in any network
993                         if (!DBM::is_result($contact)) {
994                                 $condition = ['name' => $name, 'uid' => $profile_uid];
995                                 $contact = dba::selectFirst('contact', $fields, $condition);
996                         }
997                 }
998
999                 if ($contact) {
1000                         if (strlen($inform) && (isset($contact["notify"]) || isset($contact["id"]))) {
1001                                 $inform .= ',';
1002                         }
1003
1004                         if (isset($contact["id"])) {
1005                                 $inform .= 'cid:' . $contact["id"];
1006                         } elseif (isset($contact["notify"])) {
1007                                 $inform  .= $contact["notify"];
1008                         }
1009
1010                         $profile = $contact["url"];
1011                         $alias   = $contact["alias"];
1012                         $newname = $contact["nick"];
1013                         if (($newname == "") || (($contact["network"] != NETWORK_OSTATUS) && ($contact["network"] != NETWORK_TWITTER)
1014                                 && ($contact["network"] != NETWORK_STATUSNET) && ($contact["network"] != NETWORK_APPNET))) {
1015                                 $newname = $contact["name"];
1016                         }
1017                 }
1018
1019                 //if there is an url for this persons profile
1020                 if (isset($profile) && ($newname != "")) {
1021                         $replaced = true;
1022                         // create profile link
1023                         $profile = str_replace(',', '%2c', $profile);
1024                         $newtag = $tag_type.'[url=' . $profile . ']' . $newname . '[/url]';
1025                         $body = str_replace($tag_type . $name, $newtag, $body);
1026                         // append tag to str_tags
1027                         if (!stristr($str_tags, $newtag)) {
1028                                 if (strlen($str_tags)) {
1029                                         $str_tags .= ',';
1030                                 }
1031                                 $str_tags .= $newtag;
1032                         }
1033
1034                         /*
1035                          * Status.Net seems to require the numeric ID URL in a mention if the person isn't
1036                          * subscribed to you. But the nickname URL is OK if they are. Grrr. We'll tag both.
1037                          */
1038                         if (strlen($alias)) {
1039                                 $newtag = '@[url=' . $alias . ']' . $newname . '[/url]';
1040                                 if (!stripos($str_tags, '[url=' . $alias . ']')) {
1041                                         if (strlen($str_tags)) {
1042                                                 $str_tags .= ',';
1043                                         }
1044                                         $str_tags .= $newtag;
1045                                 }
1046                         }
1047                 }
1048         }
1049
1050         return ['replaced' => $replaced, 'contact' => $contact];
1051 }