]> git.mxchange.org Git - friendica.git/blob - mod/item.php
Some safety precautions
[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         /// @todo these lines should be moved to Model/Photo
444         if (!$preview && preg_match_all("/\[img([\=0-9x]*?)\](.*?)\[\/img\]/",$body,$match)) {
445                 $images = $match[2];
446                 if (count($images)) {
447
448                         $objecttype = ACTIVITY_OBJ_IMAGE;
449
450                         foreach ($images as $image) {
451                                 if (!stristr($image, System::baseUrl() . '/photo/')) {
452                                         continue;
453                                 }
454                                 $image_uri = substr($image,strrpos($image,'/') + 1);
455                                 $image_uri = substr($image_uri,0, strpos($image_uri,'-'));
456                                 if (!strlen($image_uri)) {
457                                         continue;
458                                 }
459
460                                 // Ensure to only modify photos that you own
461                                 $srch = '<' . intval($original_contact_id) . '>';
462
463                                 $condition = ['allow_cid' => $srch, 'allow_gid' => '', 'deny_cid' => '', 'deny_gid' => '',
464                                                 'resource-id' => $image_uri, 'uid' => $profile_uid];
465                                 if (!dba::exists('photo', $condition)) {
466                                         continue;
467                                 }
468
469                                 $fields = ['allow_cid' => $str_contact_allow, 'allow_gid' => $str_group_allow,
470                                                 'deny_cid' => $str_contact_deny, 'deny_gid' => $str_group_deny];
471                                 $condition = ['resource-id' => $image_uri, 'uid' => $profile_uid, 'album' => t('Wall Photos')];
472                                 dba::update('photo', $fields, $condition);
473                         }
474                 }
475         }
476
477
478         /*
479          * Next link in any attachment references we find in the post.
480          */
481         $match = false;
482
483         /// @todo these lines should be moved to Model/Attach (Once it exists)
484         if (!$preview && preg_match_all("/\[attachment\](.*?)\[\/attachment\]/", $body, $match)) {
485                 $attaches = $match[1];
486                 if (count($attaches)) {
487                         foreach ($attaches as $attach) {
488                                 // Ensure to only modify attachments that you own
489                                 $srch = '<' . intval($original_contact_id) . '>';
490
491                                 $condition = ['allow_cid' => $srch, 'allow_gid' => '', 'deny_cid' => '', 'deny_gid' => '',
492                                                 'id' => $attach];
493                                 if (!dba::exists('attach', $condition)) {
494                                         continue;
495                                 }
496
497                                 $fields = ['allow_cid' => $str_contact_allow, 'allow_gid' => $str_group_allow,
498                                                 'deny_cid' => $str_contact_deny, 'deny_gid' => $str_group_deny];
499                                 $condition = ['id' => $attach];
500                                 dba::update('attach', $fields, $condition);
501                         }
502                 }
503         }
504
505         // embedded bookmark or attachment in post? set bookmark flag
506
507         $bookmark = 0;
508         $data = get_attachment_data($body);
509         if (preg_match_all("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/ism", $body, $match, PREG_SET_ORDER) || isset($data["type"])) {
510                 $objecttype = ACTIVITY_OBJ_BOOKMARK;
511                 $bookmark = 1;
512         }
513
514         $body = bb_translate_video($body);
515
516
517         // Fold multi-line [code] sequences
518         $body = preg_replace('/\[\/code\]\s*\[code\]/ism', "\n", $body);
519
520         $body = scale_external_images($body, false);
521
522         // Setting the object type if not defined before
523         if (!$objecttype) {
524                 $objecttype = ACTIVITY_OBJ_NOTE; // Default value
525                 require_once 'include/plaintext.php';
526                 $objectdata = get_attached_data($body);
527
528                 if ($objectdata["type"] == "link") {
529                         $objecttype = ACTIVITY_OBJ_BOOKMARK;
530                 } elseif ($objectdata["type"] == "video") {
531                         $objecttype = ACTIVITY_OBJ_VIDEO;
532                 } elseif ($objectdata["type"] == "photo") {
533                         $objecttype = ACTIVITY_OBJ_IMAGE;
534                 }
535
536         }
537
538         $attachments = '';
539         $match = false;
540
541         if (preg_match_all('/(\[attachment\]([0-9]+)\[\/attachment\])/',$body,$match)) {
542                 foreach ($match[2] as $mtch) {
543                         $fields = ['id', 'filename', 'filesize', 'filetype'];
544                         $attachment = dba::selectFirst('attach', $fields, ['id' => $mtch]);
545                         if (DBM::is_result($attachment)) {
546                                 if (strlen($attachments)) {
547                                         $attachments .= ',';
548                                 }
549                                 $attachments .= '[attach]href="' . System::baseUrl() . '/attach/' . $attachment['id'] .
550                                                 '" length="' . $attachment['filesize'] . '" type="' . $attachment['filetype'] .
551                                                 '" title="' . ($attachment['filename'] ? $attachment['filename'] : '') . '"[/attach]';
552                         }
553                         $body = str_replace($match[1],'',$body);
554                 }
555         }
556
557         $wall = 0;
558
559         if (($post_type === 'wall' || $post_type === 'wall-comment') && !count($forum_contact)) {
560                 $wall = 1;
561         }
562
563         if (!strlen($verb)) {
564                 $verb = ACTIVITY_POST;
565         }
566
567         if ($network == "") {
568                 $network = NETWORK_DFRN;
569         }
570
571         $gravity = ($parent ? 6 : 0);
572
573         // even if the post arrived via API we are considering that it
574         // originated on this site by default for determining relayability.
575
576         $origin = intval(defaults($_REQUEST, 'origin', 1));
577
578         $notify_type = ($parent ? 'comment-new' : 'wall-new');
579
580         $uri = ($message_id ? $message_id : item_new_uri($a->get_hostname(), $profile_uid, $guid));
581
582         // Fallback so that we alway have a parent uri
583         if (!$thr_parent_uri || !$parent) {
584                 $thr_parent_uri = $uri;
585         }
586
587         $datarray = [];
588         $datarray['uid']           = $profile_uid;
589         $datarray['type']          = $post_type;
590         $datarray['wall']          = $wall;
591         $datarray['gravity']       = $gravity;
592         $datarray['network']       = $network;
593         $datarray['contact-id']    = $contact_id;
594         $datarray['owner-name']    = $contact_record['name'];
595         $datarray['owner-link']    = $contact_record['url'];
596         $datarray['owner-avatar']  = $contact_record['thumb'];
597         $datarray['owner-id']      = Contact::getIdForURL($datarray['owner-link'], 0);
598         $datarray['author-name']   = $author['name'];
599         $datarray['author-link']   = $author['url'];
600         $datarray['author-avatar'] = $author['thumb'];
601         $datarray['author-id']     = Contact::getIdForURL($datarray['author-link'], 0);
602         $datarray['created']       = datetime_convert();
603         $datarray['edited']        = datetime_convert();
604         $datarray['commented']     = datetime_convert();
605         $datarray['received']      = datetime_convert();
606         $datarray['changed']       = datetime_convert();
607         $datarray['extid']         = $extid;
608         $datarray['guid']          = $guid;
609         $datarray['uri']           = $uri;
610         $datarray['title']         = $title;
611         $datarray['body']          = $body;
612         $datarray['app']           = $app;
613         $datarray['location']      = $location;
614         $datarray['coord']         = $coord;
615         $datarray['tag']           = $str_tags;
616         $datarray['file']          = $categories;
617         $datarray['inform']        = $inform;
618         $datarray['verb']          = $verb;
619         $datarray['object-type']   = $objecttype;
620         $datarray['allow_cid']     = $str_contact_allow;
621         $datarray['allow_gid']     = $str_group_allow;
622         $datarray['deny_cid']      = $str_contact_deny;
623         $datarray['deny_gid']      = $str_group_deny;
624         $datarray['private']       = $private;
625         $datarray['pubmail']       = $pubmail_enabled;
626         $datarray['attach']        = $attachments;
627         $datarray['bookmark']      = intval($bookmark);
628
629         // This is not a bug. The item store function changes 'parent-uri' to 'thr-parent' and fetches 'parent-uri' new. (We should change this)
630         $datarray['parent-uri']    = $thr_parent_uri;
631
632         $datarray['postopts']      = $postopts;
633         $datarray['origin']        = $origin;
634         $datarray['moderated']     = false;
635         $datarray['gcontact-id']   = GContact::getId(["url" => $datarray['author-link'], "network" => $datarray['network'],
636                                                         "photo" => $datarray['author-avatar'], "name" => $datarray['author-name']]);
637         $datarray['object']        = $object;
638
639         /*
640          * These fields are for the convenience of plugins...
641          * 'self' if true indicates the owner is posting on their own wall
642          * If parent is 0 it is a top-level post.
643          */
644         $datarray['parent']        = $parent;
645         $datarray['self']          = $self;
646
647         // This triggers posts via API and the mirror functions
648         $datarray['api_source'] = $api_source;
649
650         // This field is for storing the raw conversation data
651         $datarray['protocol'] = PROTOCOL_DFRN;
652
653         $r = dba::fetch_first("SELECT `conversation-uri`, `conversation-href` FROM `conversation` WHERE `item-uri` = ?", $datarray['parent-uri']);
654         if (DBM::is_result($r)) {
655                 if ($r['conversation-uri'] != '') {
656                         $datarray['conversation-uri'] = $r['conversation-uri'];
657                 }
658                 if ($r['conversation-href'] != '') {
659                         $datarray['conversation-href'] = $r['conversation-href'];
660                 }
661         }
662
663         if ($orig_post) {
664                 $datarray['edit'] = true;
665         }
666
667         // Search for hashtags
668         item_body_set_hashtags($datarray);
669
670         // preview mode - prepare the body for display and send it via json
671         if ($preview) {
672                 require_once 'include/conversation.php';
673                 // We set the datarray ID to -1 because in preview mode the dataray
674                 // doesn't have an ID.
675                 $datarray["id"] = -1;
676                 $o = conversation($a,[array_merge($contact_record,$datarray)],'search', false, true);
677                 logger('preview: ' . $o);
678                 echo json_encode(['preview' => $o]);
679                 killme();
680         }
681
682         call_hooks('post_local',$datarray);
683
684         if (x($datarray, 'cancel')) {
685                 logger('mod_item: post cancelled by plugin.');
686                 if ($return_path) {
687                         goaway($return_path);
688                 }
689
690                 $json = ['cancel' => 1];
691                 if (x($_REQUEST, 'jsreload') && strlen($_REQUEST['jsreload'])) {
692                         $json['reload'] = System::baseUrl() . '/' . $_REQUEST['jsreload'];
693                 }
694
695                 echo json_encode($json);
696                 killme();
697         }
698
699         if ($orig_post) {
700
701                 // Fill the cache field
702                 // This could be done in Item::update as well - but we have to check for the existance of some fields.
703                 put_item_in_cache($datarray);
704
705                 $fields = [
706                         'title' => $datarray['title'],
707                         'body' => $datarray['body'],
708                         'tag' => $datarray['tag'],
709                         'attach' => $datarray['attach'],
710                         'file' => $datarray['file'],
711                         'rendered-html' => $datarray['rendered-html'],
712                         'rendered-hash' => $datarray['rendered-hash'],
713                         'edited' => datetime_convert(),
714                         'changed' => datetime_convert()];
715
716                 Item::update($fields, ['id' => $post_id]);
717
718                 // update filetags in pconfig
719                 file_tag_update_pconfig($uid,$categories_old,$categories_new,'category');
720
721                 if (x($_REQUEST, 'return') && strlen($return_path)) {
722                         logger('return: ' . $return_path);
723                         goaway($return_path);
724                 }
725                 killme();
726         } else {
727                 $post_id = 0;
728         }
729
730         unset($datarray['edit']);
731         unset($datarray['self']);
732         unset($datarray['api_source']);
733
734         $post_id = item_store($datarray);
735
736         if (!$post_id) {
737                 logger("Item wasn't stored.");
738                 goaway($return_path);
739         }
740
741         $datarray = dba::selectFirst('item', [], ['id' => $post_id]);
742
743         if (!DBM::is_result($datarray)) {
744                 logger("Item with id ".$post_id." couldn't be fetched.");
745                 goaway($return_path);
746         }
747
748         // update filetags in pconfig
749         file_tag_update_pconfig($uid, $categories_old, $categories_new, 'category');
750
751         // These notifications are sent if someone else is commenting other your wall
752         if ($parent) {
753                 if ($contact_record != $author) {
754                         notification([
755                                 'type'         => NOTIFY_COMMENT,
756                                 'notify_flags' => $user['notify-flags'],
757                                 'language'     => $user['language'],
758                                 'to_name'      => $user['username'],
759                                 'to_email'     => $user['email'],
760                                 'uid'          => $user['uid'],
761                                 'item'         => $datarray,
762                                 'link'         => System::baseUrl().'/display/'.urlencode($datarray['guid']),
763                                 'source_name'  => $datarray['author-name'],
764                                 'source_link'  => $datarray['author-link'],
765                                 'source_photo' => $datarray['author-avatar'],
766                                 'verb'         => ACTIVITY_POST,
767                                 'otype'        => 'item',
768                                 'parent'       => $parent,
769                                 'parent_uri'   => $parent_item['uri']
770                         ]);
771                 }
772
773                 // Store the comment signature information in case we need to relay to Diaspora
774                 Diaspora::storeCommentSignature($datarray, $author, ($self ? $user['prvkey'] : false), $post_id);
775         } else {
776                 if (($contact_record != $author) && !count($forum_contact)) {
777                         notification([
778                                 'type'         => NOTIFY_WALL,
779                                 'notify_flags' => $user['notify-flags'],
780                                 'language'     => $user['language'],
781                                 'to_name'      => $user['username'],
782                                 'to_email'     => $user['email'],
783                                 'uid'          => $user['uid'],
784                                 'item'         => $datarray,
785                                 'link'         => System::baseUrl().'/display/'.urlencode($datarray['guid']),
786                                 'source_name'  => $datarray['author-name'],
787                                 'source_link'  => $datarray['author-link'],
788                                 'source_photo' => $datarray['author-avatar'],
789                                 'verb'         => ACTIVITY_POST,
790                                 'otype'        => 'item'
791                         ]);
792                 }
793         }
794
795         call_hooks('post_local_end', $datarray);
796
797         if (strlen($emailcc) && $profile_uid == local_user()) {
798                 $erecips = explode(',', $emailcc);
799                 if (count($erecips)) {
800                         foreach ($erecips as $recip) {
801                                 $addr = trim($recip);
802                                 if (!strlen($addr)) {
803                                         continue;
804                                 }
805                                 $disclaimer = '<hr />' . sprintf(t('This message was sent to you by %s, a member of the Friendica social network.'), $a->user['username'])
806                                         . '<br />';
807                                 $disclaimer .= sprintf(t('You may visit them online at %s'), System::baseUrl() . '/profile/' . $a->user['nickname']) . EOL;
808                                 $disclaimer .= t('Please contact the sender by replying to this post if you do not wish to receive these messages.') . EOL;
809                                 if (!$datarray['title']=='') {
810                                         $subject = Email::encodeHeader($datarray['title'], 'UTF-8');
811                                 } else {
812                                         $subject = Email::encodeHeader('[Friendica]' . ' ' . sprintf(t('%s posted an update.'), $a->user['username']), 'UTF-8');
813                                 }
814                                 $link = '<a href="' . System::baseUrl() . '/profile/' . $a->user['nickname'] . '"><img src="' . $author['thumb'] . '" alt="' . $a->user['username'] . '" /></a><br /><br />';
815                                 $html    = prepare_body($datarray);
816                                 $message = '<html><body>' . $link . $html . $disclaimer . '</body></html>';
817                                 include_once 'include/html2plain.php';
818                                 $params =  [
819                                         'fromName' => $a->user['username'],
820                                         'fromEmail' => $a->user['email'],
821                                         'toEmail' => $addr,
822                                         'replyTo' => $a->user['email'],
823                                         'messageSubject' => $subject,
824                                         'htmlVersion' => $message,
825                                         'textVersion' => html2plain($html.$disclaimer)
826                                 ];
827                                 Emailer::send($params);
828                         }
829                 }
830         }
831
832         // Insert an item entry for UID=0 for global entries.
833         // We now do it in the background to save some time.
834         // This is important in interactive environments like the frontend or the API.
835         // We don't fork a new process since this is done anyway with the following command
836         Worker::add(['priority' => PRIORITY_HIGH, 'dont_fork' => true], "CreateShadowEntry", $post_id);
837
838         // Call the background process that is delivering the item to the receivers
839         Worker::add(PRIORITY_HIGH, "Notifier", $notify_type, $post_id);
840
841         logger('post_complete');
842
843         item_post_return(System::baseUrl(), $api_source, $return_path);
844         // NOTREACHED
845 }
846
847 function item_post_return($baseurl, $api_source, $return_path) {
848         // figure out how to return, depending on from whence we came
849
850         if ($api_source) {
851                 return;
852         }
853
854         if ($return_path) {
855                 goaway($return_path);
856         }
857
858         $json = ['success' => 1];
859         if (x($_REQUEST, 'jsreload') && strlen($_REQUEST['jsreload'])) {
860                 $json['reload'] = $baseurl . '/' . $_REQUEST['jsreload'];
861         }
862
863         logger('post_json: ' . print_r($json,true), LOGGER_DEBUG);
864
865         echo json_encode($json);
866         killme();
867 }
868
869
870
871 function item_content(App $a) {
872
873         if (!local_user() && !remote_user()) {
874                 return;
875         }
876
877         require_once 'include/security.php';
878
879         $o = '';
880         if (($a->argc == 3) && ($a->argv[1] === 'drop') && intval($a->argv[2])) {
881                 if (is_ajax()) {
882                         $o = Item::delete($a->argv[2]);
883                 } else {
884                         $o = drop_item($a->argv[2]);
885                 }
886                 if (is_ajax()) {
887                         // ajax return: [<item id>, 0 (no perm) | <owner id>]
888                         echo json_encode([intval($a->argv[2]), intval($o)]);
889                         killme();
890                 }
891         }
892         return $o;
893 }
894
895 /**
896  * This function removes the tag $tag from the text $body and replaces it with
897  * the appropiate link.
898  *
899  * @param App $a Application instance @TODO is unused in this function's scope (excluding included files)
900  * @param unknown_type $body the text to replace the tag in
901  * @param string $inform a comma-seperated string containing everybody to inform
902  * @param string $str_tags string to add the tag to
903  * @param integer $profile_uid
904  * @param string $tag the tag to replace
905  * @param string $network The network of the post
906  *
907  * @return boolean true if replaced, false if not replaced
908  */
909 function handle_tag(App $a, &$body, &$inform, &$str_tags, $profile_uid, $tag, $network = "")
910 {
911         $replaced = false;
912         $r = null;
913         $tag_type = '@';
914
915         //is it a person tag?
916         if ((strpos($tag, '@') === 0) || (strpos($tag, '!') === 0)) {
917                 $tag_type = substr($tag, 0, 1);
918                 //is it already replaced?
919                 if (strpos($tag, '[url=')) {
920                         //append tag to str_tags
921                         if (!stristr($str_tags, $tag)) {
922                                 if (strlen($str_tags)) {
923                                         $str_tags .= ',';
924                                 }
925                                 $str_tags .= $tag;
926                         }
927
928                         // Checking for the alias that is used for OStatus
929                         $pattern = "/[@!]\[url\=(.*?)\](.*?)\[\/url\]/ism";
930                         if (preg_match($pattern, $tag, $matches)) {
931
932                                 $r = q("SELECT `alias`, `name` FROM `contact` WHERE `nurl` = '%s' AND `alias` != '' AND `uid` = 0",
933                                         normalise_link($matches[1]));
934                                 if (!DBM::is_result($r)) {
935                                         $r = q("SELECT `alias`, `name` FROM `gcontact` WHERE `nurl` = '%s' AND `alias` != ''",
936                                                 normalise_link($matches[1]));
937                                 }
938                                 if (DBM::is_result($r)) {
939                                         $data = $r[0];
940                                 } else {
941                                         $data = Probe::uri($matches[1]);
942                                 }
943
944                                 if ($data["alias"] != "") {
945                                         $newtag = '@[url=' . $data["alias"] . ']' . $data["name"] . '[/url]';
946                                         if (!stristr($str_tags, $newtag)) {
947                                                 if (strlen($str_tags)) {
948                                                         $str_tags .= ',';
949                                                 }
950                                                 $str_tags .= $newtag;
951                                         }
952                                 }
953                         }
954
955                         return $replaced;
956                 }
957                 $stat = false;
958                 //get the person's name
959                 $name = substr($tag, 1);
960
961                 // Sometimes the tag detection doesn't seem to work right
962                 // This is some workaround
963                 $nameparts = explode(" ", $name);
964                 $name = $nameparts[0];
965
966                 // Try to detect the contact in various ways
967                 if ((strpos($name, '@')) || (strpos($name, 'http://'))) {
968                         // Is it in format @user@domain.tld or @http://domain.tld/...?
969
970                         // First check the contact table for the address
971                         $r = q("SELECT `id`, `url`, `nick`, `name`, `alias`, `network`, `notify`, `forum`, `prv` FROM `contact`
972                                 WHERE `addr` = '%s' AND `uid` = %d AND
973                                         (`network` != '%s' OR (`notify` != '' AND `alias` != ''))
974                                 LIMIT 1",
975                                         dbesc($name),
976                                         intval($profile_uid),
977                                         dbesc(NETWORK_OSTATUS)
978                         );
979
980                         // Then check in the contact table for the url
981                         if (!DBM::is_result($r)) {
982                                 $r = q("SELECT `id`, `url`, `nick`, `name`, `alias`, `network`, `notify`, `forum`, `prv` FROM `contact`
983                                         WHERE `nurl` = '%s' AND `uid` = %d AND
984                                                 (`network` != '%s' OR (`notify` != '' AND `alias` != ''))
985                                         LIMIT 1",
986                                                 dbesc(normalise_link($name)),
987                                                 intval($profile_uid),
988                                                 dbesc(NETWORK_OSTATUS)
989                                 );
990                         }
991
992                         // Then check in the global contacts for the address
993                         if (!DBM::is_result($r)) {
994                                 $r = q("SELECT `url`, `nick`, `name`, `alias`, `network`, `notify` FROM `gcontact`
995                                         WHERE `addr` = '%s' AND (`network` != '%s' OR (`notify` != '' AND `alias` != ''))
996                                         LIMIT 1",
997                                                 dbesc($name),
998                                                 dbesc(NETWORK_OSTATUS)
999                                 );
1000                         }
1001
1002                         // Then check in the global contacts for the url
1003                         if (!DBM::is_result($r)) {
1004                                 $r = q("SELECT `url`, `nick`, `name`, `alias`, `network`, `notify` FROM `gcontact`
1005                                         WHERE `nurl` = '%s' AND (`network` != '%s' OR (`notify` != '' AND `alias` != ''))
1006                                         LIMIT 1",
1007                                                 dbesc(normalise_link($name)),
1008                                                 dbesc(NETWORK_OSTATUS)
1009                                 );
1010                         }
1011
1012                         if (!DBM::is_result($r)) {
1013                                 $probed = Probe::uri($name);
1014                                 if ($result['network'] != NETWORK_PHANTOM) {
1015                                         GContact::update($probed);
1016                                         $r = q("SELECT `url`, `name`, `nick`, `network`, `alias`, `notify` FROM `gcontact` WHERE `nurl` = '%s' LIMIT 1",
1017                                                 dbesc(normalise_link($probed["url"])));
1018                                 }
1019                         }
1020                 } else {
1021                         $r = false;
1022                         if (strrpos($name, '+')) {
1023                                 // Is it in format @nick+number?
1024                                 $tagcid = intval(substr($name, strrpos($name, '+') + 1));
1025
1026                                 $r = q("SELECT `id`, `url`, `nick`, `name`, `alias`, `network` FROM `contact` WHERE `id` = %d AND `uid` = %d LIMIT 1",
1027                                                 intval($tagcid),
1028                                                 intval($profile_uid)
1029                                 );
1030                         }
1031
1032                         // select someone by attag or nick and the name passed in the current network
1033                         if (!DBM::is_result($r) && ($network != ""))
1034                                 $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",
1035                                                 dbesc($name),
1036                                                 dbesc($name),
1037                                                 dbesc($network),
1038                                                 intval($profile_uid)
1039                                 );
1040
1041                         //select someone from this user's contacts by name in the current network
1042                         if (!DBM::is_result($r) && ($network != "")) {
1043                                 $r = q("SELECT `id`, `url`, `nick`, `name`, `alias`, `network` FROM `contact` WHERE `name` = '%s' AND `network` = '%s' AND `uid` = %d LIMIT 1",
1044                                                 dbesc($name),
1045                                                 dbesc($network),
1046                                                 intval($profile_uid)
1047                                 );
1048                         }
1049
1050                         // select someone by attag or nick and the name passed in
1051                         if (!DBM::is_result($r)) {
1052                                 $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",
1053                                                 dbesc($name),
1054                                                 dbesc($name),
1055                                                 intval($profile_uid)
1056                                 );
1057                         }
1058
1059                         // select someone from this user's contacts by name
1060                         if (!DBM::is_result($r)) {
1061                                 $r = q("SELECT `id`, `url`, `nick`, `name`, `alias`, `network` FROM `contact` WHERE `name` = '%s' AND `uid` = %d LIMIT 1",
1062                                                 dbesc($name),
1063                                                 intval($profile_uid)
1064                                 );
1065                         }
1066                 }
1067
1068                 if (DBM::is_result($r)) {
1069                         if (strlen($inform) && (isset($r[0]["notify"]) || isset($r[0]["id"]))) {
1070                                 $inform .= ',';
1071                         }
1072
1073                         if (isset($r[0]["id"])) {
1074                                 $inform .= 'cid:' . $r[0]["id"];
1075                         } elseif (isset($r[0]["notify"])) {
1076                                 $inform  .= $r[0]["notify"];
1077                         }
1078
1079                         $profile = $r[0]["url"];
1080                         $alias   = $r[0]["alias"];
1081                         $newname = $r[0]["nick"];
1082                         if (($newname == "") || (($r[0]["network"] != NETWORK_OSTATUS) && ($r[0]["network"] != NETWORK_TWITTER)
1083                                 && ($r[0]["network"] != NETWORK_STATUSNET) && ($r[0]["network"] != NETWORK_APPNET))) {
1084                                 $newname = $r[0]["name"];
1085                         }
1086                 }
1087
1088                 //if there is an url for this persons profile
1089                 if (isset($profile) && ($newname != "")) {
1090                         $replaced = true;
1091                         // create profile link
1092                         $profile = str_replace(',', '%2c', $profile);
1093                         $newtag = $tag_type.'[url=' . $profile . ']' . $newname . '[/url]';
1094                         $body = str_replace($tag_type . $name, $newtag, $body);
1095                         // append tag to str_tags
1096                         if (!stristr($str_tags, $newtag)) {
1097                                 if (strlen($str_tags)) {
1098                                         $str_tags .= ',';
1099                                 }
1100                                 $str_tags .= $newtag;
1101                         }
1102
1103                         /*
1104                          * Status.Net seems to require the numeric ID URL in a mention if the person isn't
1105                          * subscribed to you. But the nickname URL is OK if they are. Grrr. We'll tag both.
1106                          */
1107                         if (strlen($alias)) {
1108                                 $newtag = '@[url=' . $alias . ']' . $newname . '[/url]';
1109                                 if (!stristr($str_tags, $newtag)) {
1110                                         if (strlen($str_tags)) {
1111                                                 $str_tags .= ',';
1112                                         }
1113                                         $str_tags .= $newtag;
1114                                 }
1115                         }
1116                 }
1117         }
1118
1119         return ['replaced' => $replaced, 'contact' => $r[0]];
1120 }