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