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