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