]> git.mxchange.org Git - friendica.git/blob - mod/item.php
moved get_guid to System::createGUID
[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
18 use Friendica\App;
19 use Friendica\Content\Text\BBCode;
20 use Friendica\Core\Addon;
21 use Friendica\Core\Config;
22 use Friendica\Core\L10n;
23 use Friendica\Core\System;
24 use Friendica\Core\Worker;
25 use Friendica\Database\DBM;
26 use Friendica\Model\Contact;
27 use Friendica\Model\Item;
28 use Friendica\Protocol\Diaspora;
29 use Friendica\Protocol\Email;
30 use Friendica\Util\DateTimeFormat;
31 use Friendica\Util\Emailer;
32
33 require_once 'include/enotify.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 = Item::selectFirst([], ['id' => $thr_parent]);
97                 } elseif ($thr_parent_uri) {
98                         $parent_item = Item::selectFirst([], ['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 = Item::selectFirst(Item::ITEM_FIELDLIST, ['id' => $parent_item['parent']]);
110                         }
111                 }
112
113                 if (!DBM::is_result($parent_item)) {
114                         notice(L10n::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(L10n::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 = Item::selectFirst(Item::ITEM_FIELDLIST, ['id' => $post_id]);
174         }
175
176         $user = dba::selectFirst('user', [], ['uid' => $profile_uid]);
177         if (!DBM::is_result($user) && !$parent) {
178                 return;
179         }
180
181         $categories = '';
182
183         if ($orig_post) {
184                 $str_group_allow   = $orig_post['allow_gid'];
185                 $str_contact_allow = $orig_post['allow_cid'];
186                 $str_group_deny    = $orig_post['deny_gid'];
187                 $str_contact_deny  = $orig_post['deny_cid'];
188                 $location          = $orig_post['location'];
189                 $coord             = $orig_post['coord'];
190                 $verb              = $orig_post['verb'];
191                 $objecttype        = $orig_post['object-type'];
192                 $emailcc           = $orig_post['emailcc'];
193                 $app               = $orig_post['app'];
194                 $categories        = $orig_post['file'];
195                 $title             = notags(trim($_REQUEST['title']));
196                 $body              = escape_tags(trim($_REQUEST['body']));
197                 $private           = $orig_post['private'];
198                 $pubmail_enabled   = $orig_post['pubmail'];
199                 $network           = $orig_post['network'];
200                 $guid              = $orig_post['guid'];
201                 $extid             = $orig_post['extid'];
202
203         } else {
204
205                 /*
206                  * if coming from the API and no privacy settings are set,
207                  * use the user default permissions - as they won't have
208                  * been supplied via a form.
209                  */
210                 /// @TODO use x($_REQUEST, 'foo') here
211                 if ($api_source
212                         && !array_key_exists('contact_allow', $_REQUEST)
213                         && !array_key_exists('group_allow', $_REQUEST)
214                         && !array_key_exists('contact_deny', $_REQUEST)
215                         && !array_key_exists('group_deny', $_REQUEST)) {
216                         $str_group_allow   = $user['allow_gid'];
217                         $str_contact_allow = $user['allow_cid'];
218                         $str_group_deny    = $user['deny_gid'];
219                         $str_contact_deny  = $user['deny_cid'];
220                 } else {
221                         // use the posted permissions
222                         $str_group_allow   = perms2str($_REQUEST['group_allow']);
223                         $str_contact_allow = perms2str($_REQUEST['contact_allow']);
224                         $str_group_deny    = perms2str($_REQUEST['group_deny']);
225                         $str_contact_deny  = perms2str($_REQUEST['contact_deny']);
226                 }
227
228                 $title             =      notags(trim(defaults($_REQUEST, 'title'   , '')));
229                 $location          =      notags(trim(defaults($_REQUEST, 'location', '')));
230                 $coord             =      notags(trim(defaults($_REQUEST, 'coord'   , '')));
231                 $verb              =      notags(trim(defaults($_REQUEST, 'verb'    , '')));
232                 $emailcc           =      notags(trim(defaults($_REQUEST, 'emailcc' , '')));
233                 $body              = escape_tags(trim(defaults($_REQUEST, 'body'    , '')));
234                 $network           =      notags(trim(defaults($_REQUEST, 'network' , NETWORK_DFRN)));
235                 $guid              =      System::createGUID(32);
236
237                 $postopts = defaults($_REQUEST, 'postopts', '');
238
239                 $private = ((strlen($str_group_allow) || strlen($str_contact_allow) || strlen($str_group_deny) || strlen($str_contact_deny)) ? 1 : 0);
240
241                 if ($user['hidewall']) {
242                         $private = 2;
243                 }
244
245                 // If this is a comment, set the permissions from the parent.
246
247                 if ($parent_item) {
248
249                         // for non native networks use the network of the original post as network of the item
250                         if (($parent_item['network'] != NETWORK_DIASPORA)
251                                 && ($parent_item['network'] != NETWORK_OSTATUS)
252                                 && ($network == "")) {
253                                 $network = $parent_item['network'];
254                         }
255
256                         $str_contact_allow = $parent_item['allow_cid'];
257                         $str_group_allow   = $parent_item['allow_gid'];
258                         $str_contact_deny  = $parent_item['deny_cid'];
259                         $str_group_deny    = $parent_item['deny_gid'];
260                         $private           = $parent_item['private'];
261                 }
262
263                 $pubmail_enabled = defaults($_REQUEST, 'pubmail_enable', false) && !$private;
264
265                 // if using the API, we won't see pubmail_enable - figure out if it should be set
266                 if ($api_source && $profile_uid && $profile_uid == local_user() && !$private) {
267                         if (function_exists('imap_open') && !Config::get('system', 'imap_disabled')) {
268                                 $pubmail_enabled = dba::exists('mailacct', ["`uid` = ? AND `server` != ? AND `pubmail`", local_user(), '']);
269                         }
270                 }
271
272                 if (!strlen($body)) {
273                         if ($preview) {
274                                 killme();
275                         }
276                         info(L10n::t('Empty post discarded.') . EOL);
277                         if (x($_REQUEST, 'return')) {
278                                 goaway($return_path);
279                         }
280                         killme();
281                 }
282         }
283
284         if (!empty($categories)) {
285                 // get the "fileas" tags for this post
286                 $filedas = file_tag_file_to_list($categories, 'file');
287         }
288         // save old and new categories, so we can determine what needs to be deleted from pconfig
289         $categories_old = $categories;
290         $categories = file_tag_list_to_file(trim(defaults($_REQUEST, 'category', '')), 'category');
291         $categories_new = $categories;
292         if (!empty($filedas)) {
293                 // append the fileas stuff to the new categories list
294                 $categories .= file_tag_list_to_file($filedas, 'file');
295         }
296
297         // get contact info for poster
298
299         $author = null;
300         $self   = false;
301         $contact_id = 0;
302
303         if (local_user() && ((local_user() == $profile_uid) || $allow_comment)) {
304                 $self = true;
305                 $author = dba::selectFirst('contact', [], ['uid' => local_user(), 'self' => true]);
306         } elseif (remote_user()) {
307                 if (x($_SESSION, 'remote') && is_array($_SESSION['remote'])) {
308                         foreach ($_SESSION['remote'] as $v) {
309                                 if ($v['uid'] == $profile_uid) {
310                                         $contact_id = $v['cid'];
311                                         break;
312                                 }
313                         }
314                 }
315                 if ($contact_id) {
316                         $author = dba::selectFirst('contact', [], ['id' => $contact_id]);
317                 }
318         }
319
320         if (DBM::is_result($author)) {
321                 $contact_id = $author['id'];
322         }
323
324         // get contact info for owner
325         if ($profile_uid == local_user() || $allow_comment) {
326                 $contact_record = $author;
327         } else {
328                 $contact_record = dba::selectFirst('contact', [], ['uid' => $profile_uid, 'self' => true]);
329         }
330
331         $post_type = notags(trim($_REQUEST['type']));
332
333         if ($post_type === 'net-comment' && $parent_item !== null) {
334                 if ($parent_item['wall'] == 1) {
335                         $post_type = 'wall-comment';
336                 } else {
337                         $post_type = 'remote-comment';
338                 }
339         }
340
341         // Look for any tags and linkify them
342         $str_tags = '';
343         $inform   = '';
344
345         $tags = get_tags($body);
346
347         // Add a tag if the parent contact is from OStatus (This will notify them during delivery)
348         if ($parent) {
349                 if ($thr_parent_contact['network'] == NETWORK_OSTATUS) {
350                         $contact = '@[url=' . $thr_parent_contact['url'] . ']' . $thr_parent_contact['nick'] . '[/url]';
351                         if (!stripos(implode($tags), '[url=' . $thr_parent_contact['url'] . ']')) {
352                                 $tags[] = $contact;
353                         }
354                 }
355
356                 if ($parent_contact['network'] == NETWORK_OSTATUS) {
357                         $contact = '@[url=' . $parent_contact['url'] . ']' . $parent_contact['nick'] . '[/url]';
358                         if (!stripos(implode($tags), '[url=' . $parent_contact['url'] . ']')) {
359                                 $tags[] = $contact;
360                         }
361                 }
362         }
363
364         $tagged = [];
365
366         $private_forum = false;
367         $only_to_forum = false;
368         $forum_contact = [];
369
370         if (count($tags)) {
371                 foreach ($tags as $tag) {
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' => L10n::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 = BBCode::getAttachmentData($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 = BBCode::scaleExternalImages($body, false);
523
524         // Setting the object type if not defined before
525         if (!$objecttype) {
526                 $objecttype = ACTIVITY_OBJ_NOTE; // Default value
527                 $objectdata = BBCode::getAttachedData($body);
528
529                 if ($objectdata["type"] == "link") {
530                         $objecttype = ACTIVITY_OBJ_BOOKMARK;
531                 } elseif ($objectdata["type"] == "video") {
532                         $objecttype = ACTIVITY_OBJ_VIDEO;
533                 } elseif ($objectdata["type"] == "photo") {
534                         $objecttype = ACTIVITY_OBJ_IMAGE;
535                 }
536
537         }
538
539         $attachments = '';
540         $match = false;
541
542         if (preg_match_all('/(\[attachment\]([0-9]+)\[\/attachment\])/',$body,$match)) {
543                 foreach ($match[2] as $mtch) {
544                         $fields = ['id', 'filename', 'filesize', 'filetype'];
545                         $attachment = dba::selectFirst('attach', $fields, ['id' => $mtch]);
546                         if (DBM::is_result($attachment)) {
547                                 if (strlen($attachments)) {
548                                         $attachments .= ',';
549                                 }
550                                 $attachments .= '[attach]href="' . System::baseUrl() . '/attach/' . $attachment['id'] .
551                                                 '" length="' . $attachment['filesize'] . '" type="' . $attachment['filetype'] .
552                                                 '" title="' . ($attachment['filename'] ? $attachment['filename'] : '') . '"[/attach]';
553                         }
554                         $body = str_replace($match[1],'',$body);
555                 }
556         }
557
558         $wall = 0;
559
560         if (($post_type === 'wall' || $post_type === 'wall-comment') && !count($forum_contact)) {
561                 $wall = 1;
562         }
563
564         if (!strlen($verb)) {
565                 $verb = ACTIVITY_POST;
566         }
567
568         if ($network == "") {
569                 $network = NETWORK_DFRN;
570         }
571
572         $gravity = ($parent ? GRAVITY_COMMENT : GRAVITY_PARENT);
573
574         // even if the post arrived via API we are considering that it
575         // originated on this site by default for determining relayability.
576
577         $origin = intval(defaults($_REQUEST, 'origin', 1));
578
579         $notify_type = ($parent ? 'comment-new' : 'wall-new');
580
581         $uri = ($message_id ? $message_id : Item::newURI($profile_uid, $guid));
582
583         // Fallback so that we alway have a parent uri
584         if (!$thr_parent_uri || !$parent) {
585                 $thr_parent_uri = $uri;
586         }
587
588         $datarray = [];
589         $datarray['uid']           = $profile_uid;
590         $datarray['type']          = $post_type;
591         $datarray['wall']          = $wall;
592         $datarray['gravity']       = $gravity;
593         $datarray['network']       = $network;
594         $datarray['contact-id']    = $contact_id;
595         $datarray['owner-name']    = $contact_record['name'];
596         $datarray['owner-link']    = $contact_record['url'];
597         $datarray['owner-avatar']  = $contact_record['thumb'];
598         $datarray['owner-id']      = Contact::getIdForURL($datarray['owner-link']);
599         $datarray['author-name']   = $author['name'];
600         $datarray['author-link']   = $author['url'];
601         $datarray['author-avatar'] = $author['thumb'];
602         $datarray['author-id']     = Contact::getIdForURL($datarray['author-link']);
603         $datarray['created']       = DateTimeFormat::utcNow();
604         $datarray['edited']        = DateTimeFormat::utcNow();
605         $datarray['commented']     = DateTimeFormat::utcNow();
606         $datarray['received']      = DateTimeFormat::utcNow();
607         $datarray['changed']       = DateTimeFormat::utcNow();
608         $datarray['extid']         = $extid;
609         $datarray['guid']          = $guid;
610         $datarray['uri']           = $uri;
611         $datarray['title']         = $title;
612         $datarray['body']          = $body;
613         $datarray['app']           = $app;
614         $datarray['location']      = $location;
615         $datarray['coord']         = $coord;
616         $datarray['tag']           = $str_tags;
617         $datarray['file']          = $categories;
618         $datarray['inform']        = $inform;
619         $datarray['verb']          = $verb;
620         $datarray['object-type']   = $objecttype;
621         $datarray['allow_cid']     = $str_contact_allow;
622         $datarray['allow_gid']     = $str_group_allow;
623         $datarray['deny_cid']      = $str_contact_deny;
624         $datarray['deny_gid']      = $str_group_deny;
625         $datarray['private']       = $private;
626         $datarray['pubmail']       = $pubmail_enabled;
627         $datarray['attach']        = $attachments;
628         $datarray['bookmark']      = intval($bookmark);
629
630         // This is not a bug. The item store function changes 'parent-uri' to 'thr-parent' and fetches 'parent-uri' new. (We should change this)
631         $datarray['parent-uri']    = $thr_parent_uri;
632
633         $datarray['postopts']      = $postopts;
634         $datarray['origin']        = $origin;
635         $datarray['moderated']     = false;
636         $datarray['object']        = $object;
637
638         /*
639          * These fields are for the convenience of addons...
640          * 'self' if true indicates the owner is posting on their own wall
641          * If parent is 0 it is a top-level post.
642          */
643         $datarray['parent']        = $parent;
644         $datarray['self']          = $self;
645
646         // This triggers posts via API and the mirror functions
647         $datarray['api_source'] = $api_source;
648
649         // This field is for storing the raw conversation data
650         $datarray['protocol'] = PROTOCOL_DFRN;
651
652         $conversation = dba::selectFirst('conversation', ['conversation-uri', 'conversation-href'], ['item-uri' => $datarray['parent-uri']]);
653         if (DBM::is_result($conversation)) {
654                 if ($r['conversation-uri'] != '') {
655                         $datarray['conversation-uri'] = $conversation['conversation-uri'];
656                 }
657                 if ($r['conversation-href'] != '') {
658                         $datarray['conversation-href'] = $conversation['conversation-href'];
659                 }
660         }
661
662         if ($orig_post) {
663                 $datarray['edit'] = true;
664         }
665
666         // Check for hashtags in the body and repair or add hashtag links
667         if ($preview || $orig_post) {
668                 Item::setHashtags($datarray);
669         }
670
671         // preview mode - prepare the body for display and send it via json
672         if ($preview) {
673                 require_once 'include/conversation.php';
674                 // We set the datarray ID to -1 because in preview mode the dataray
675                 // doesn't have an ID.
676                 $datarray["id"] = -1;
677                 $o = conversation($a,[array_merge($contact_record,$datarray)],'search', false, true);
678                 logger('preview: ' . $o);
679                 echo json_encode(['preview' => $o]);
680                 killme();
681         }
682
683         Addon::callHooks('post_local',$datarray);
684
685         if (x($datarray, 'cancel')) {
686                 logger('mod_item: post cancelled by addon.');
687                 if ($return_path) {
688                         goaway($return_path);
689                 }
690
691                 $json = ['cancel' => 1];
692                 if (x($_REQUEST, 'jsreload') && strlen($_REQUEST['jsreload'])) {
693                         $json['reload'] = System::baseUrl() . '/' . $_REQUEST['jsreload'];
694                 }
695
696                 echo json_encode($json);
697                 killme();
698         }
699
700         if ($orig_post) {
701
702                 // Fill the cache field
703                 // This could be done in Item::update as well - but we have to check for the existance of some fields.
704                 put_item_in_cache($datarray);
705
706                 $fields = [
707                         'title' => $datarray['title'],
708                         'body' => $datarray['body'],
709                         'tag' => $datarray['tag'],
710                         'attach' => $datarray['attach'],
711                         'file' => $datarray['file'],
712                         'rendered-html' => $datarray['rendered-html'],
713                         'rendered-hash' => $datarray['rendered-hash'],
714                         'edited' => DateTimeFormat::utcNow(),
715                         'changed' => DateTimeFormat::utcNow()];
716
717                 Item::update($fields, ['id' => $post_id]);
718
719                 // update filetags in pconfig
720                 file_tag_update_pconfig($uid,$categories_old,$categories_new,'category');
721
722                 if (x($_REQUEST, 'return') && strlen($return_path)) {
723                         logger('return: ' . $return_path);
724                         goaway($return_path);
725                 }
726                 killme();
727         } else {
728                 $post_id = 0;
729         }
730
731         unset($datarray['edit']);
732         unset($datarray['self']);
733         unset($datarray['api_source']);
734
735         $post_id = Item::insert($datarray);
736
737         if (!$post_id) {
738                 logger("Item wasn't stored.");
739                 goaway($return_path);
740         }
741
742         $datarray = Item::selectFirst(Item::ITEM_FIELDLIST, ['id' => $post_id]);
743
744         if (!DBM::is_result($datarray)) {
745                 logger("Item with id ".$post_id." couldn't be fetched.");
746                 goaway($return_path);
747         }
748
749         // update filetags in pconfig
750         file_tag_update_pconfig($uid, $categories_old, $categories_new, 'category');
751
752         // These notifications are sent if someone else is commenting other your wall
753         if ($parent) {
754                 if ($contact_record != $author) {
755                         notification([
756                                 'type'         => NOTIFY_COMMENT,
757                                 'notify_flags' => $user['notify-flags'],
758                                 'language'     => $user['language'],
759                                 'to_name'      => $user['username'],
760                                 'to_email'     => $user['email'],
761                                 'uid'          => $user['uid'],
762                                 'item'         => $datarray,
763                                 'link'         => System::baseUrl().'/display/'.urlencode($datarray['guid']),
764                                 'source_name'  => $datarray['author-name'],
765                                 'source_link'  => $datarray['author-link'],
766                                 'source_photo' => $datarray['author-avatar'],
767                                 'verb'         => ACTIVITY_POST,
768                                 'otype'        => 'item',
769                                 'parent'       => $parent,
770                                 'parent_uri'   => $parent_item['uri']
771                         ]);
772                 }
773
774                 // Store the comment signature information in case we need to relay to Diaspora
775                 Diaspora::storeCommentSignature($datarray, $author, ($self ? $user['prvkey'] : false), $post_id);
776         } else {
777                 if (($contact_record != $author) && !count($forum_contact)) {
778                         notification([
779                                 'type'         => NOTIFY_WALL,
780                                 'notify_flags' => $user['notify-flags'],
781                                 'language'     => $user['language'],
782                                 'to_name'      => $user['username'],
783                                 'to_email'     => $user['email'],
784                                 'uid'          => $user['uid'],
785                                 'item'         => $datarray,
786                                 'link'         => System::baseUrl().'/display/'.urlencode($datarray['guid']),
787                                 'source_name'  => $datarray['author-name'],
788                                 'source_link'  => $datarray['author-link'],
789                                 'source_photo' => $datarray['author-avatar'],
790                                 'verb'         => ACTIVITY_POST,
791                                 'otype'        => 'item'
792                         ]);
793                 }
794         }
795
796         Addon::callHooks('post_local_end', $datarray);
797
798         if (strlen($emailcc) && $profile_uid == local_user()) {
799                 $erecips = explode(',', $emailcc);
800                 if (count($erecips)) {
801                         foreach ($erecips as $recip) {
802                                 $addr = trim($recip);
803                                 if (!strlen($addr)) {
804                                         continue;
805                                 }
806                                 $disclaimer = '<hr />' . L10n::t('This message was sent to you by %s, a member of the Friendica social network.', $a->user['username'])
807                                         . '<br />';
808                                 $disclaimer .= L10n::t('You may visit them online at %s', System::baseUrl() . '/profile/' . $a->user['nickname']) . EOL;
809                                 $disclaimer .= L10n::t('Please contact the sender by replying to this post if you do not wish to receive these messages.') . EOL;
810                                 if (!$datarray['title']=='') {
811                                         $subject = Email::encodeHeader($datarray['title'], 'UTF-8');
812                                 } else {
813                                         $subject = Email::encodeHeader('[Friendica]' . ' ' . L10n::t('%s posted an update.', $a->user['username']), 'UTF-8');
814                                 }
815                                 $link = '<a href="' . System::baseUrl() . '/profile/' . $a->user['nickname'] . '"><img src="' . $author['thumb'] . '" alt="' . $a->user['username'] . '" /></a><br /><br />';
816                                 $html    = prepare_body($datarray);
817                                 $message = '<html><body>' . $link . $html . $disclaimer . '</body></html>';
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' => Friendica\Content\Text\HTML::toPlaintext($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::deleteForUser(['id' => $a->argv[2]], local_user());
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                                 $data = Contact::getDetailsByURL($matches[1]);
932                                 if ($data["alias"] != "") {
933                                         $newtag = '@[url=' . $data["alias"] . ']' . $data["nick"] . '[/url]';
934                                         if (!stripos($str_tags, '[url=' . $data["alias"] . ']')) {
935                                                 if (strlen($str_tags)) {
936                                                         $str_tags .= ',';
937                                                 }
938                                                 $str_tags .= $newtag;
939                                         }
940                                 }
941                         }
942
943                         return $replaced;
944                 }
945                 $stat = false;
946                 //get the person's name
947                 $name = substr($tag, 1);
948
949                 // Sometimes the tag detection doesn't seem to work right
950                 // This is some workaround
951                 $nameparts = explode(" ", $name);
952                 $name = $nameparts[0];
953
954                 // Try to detect the contact in various ways
955                 if (strpos($name, 'http://')) {
956                         // At first we have to ensure that the contact exists
957                         Contact::getIdForURL($name);
958
959                         // Now we should have something
960                         $contact = Contact::getDetailsByURL($name);
961                 } elseif (strpos($name, '@')) {
962                         // This function automatically probes when no entry was found
963                         $contact = Contact::getDetailsByAddr($name);
964                 } else {
965                         $contact = false;
966                         $fields = ['id', 'url', 'nick', 'name', 'alias', 'network'];
967
968                         if (strrpos($name, '+')) {
969                                 // Is it in format @nick+number?
970                                 $tagcid = intval(substr($name, strrpos($name, '+') + 1));
971                                 $contact = dba::selectFirst('contact', $fields, ['id' => $tagcid, 'uid' => $profile_uid]);
972                         }
973
974                         // select someone by nick or attag in the current network
975                         if (!DBM::is_result($contact) && ($network != "")) {
976                                 $condition = ["(`nick` = ? OR `attag` = ?) AND `network` = ? AND `uid` = ?",
977                                                 $name, $name, $network, $profile_uid];
978                                 $contact = dba::selectFirst('contact', $fields, $condition);
979                         }
980
981                         //select someone by name in the current network
982                         if (!DBM::is_result($contact) && ($network != "")) {
983                                 $condition = ['name' => $name, 'network' => $network, 'uid' => $profile_uid];
984                                 $contact = dba::selectFirst('contact', $fields, $condition);
985                         }
986
987                         // select someone by nick or attag in any network
988                         if (!DBM::is_result($contact)) {
989                                 $condition = ["(`nick` = ? OR `attag` = ?) AND `uid` = ?", $name, $name, $profile_uid];
990                                 $contact = dba::selectFirst('contact', $fields, $condition);
991                         }
992
993                         // select someone by name in any network
994                         if (!DBM::is_result($contact)) {
995                                 $condition = ['name' => $name, 'uid' => $profile_uid];
996                                 $contact = dba::selectFirst('contact', $fields, $condition);
997                         }
998                 }
999
1000                 if ($contact) {
1001                         if (strlen($inform) && (isset($contact["notify"]) || isset($contact["id"]))) {
1002                                 $inform .= ',';
1003                         }
1004
1005                         if (isset($contact["id"])) {
1006                                 $inform .= 'cid:' . $contact["id"];
1007                         } elseif (isset($contact["notify"])) {
1008                                 $inform  .= $contact["notify"];
1009                         }
1010
1011                         $profile = $contact["url"];
1012                         $alias   = $contact["alias"];
1013                         $newname = $contact["nick"];
1014                         if (($newname == "") || (($contact["network"] != NETWORK_OSTATUS) && ($contact["network"] != NETWORK_TWITTER)
1015                                 && ($contact["network"] != NETWORK_STATUSNET) && ($contact["network"] != NETWORK_APPNET))) {
1016                                 $newname = $contact["name"];
1017                         }
1018                 }
1019
1020                 //if there is an url for this persons profile
1021                 if (isset($profile) && ($newname != "")) {
1022                         $replaced = true;
1023                         // create profile link
1024                         $profile = str_replace(',', '%2c', $profile);
1025                         $newtag = $tag_type.'[url=' . $profile . ']' . $newname . '[/url]';
1026                         $body = str_replace($tag_type . $name, $newtag, $body);
1027                         // append tag to str_tags
1028                         if (!stristr($str_tags, $newtag)) {
1029                                 if (strlen($str_tags)) {
1030                                         $str_tags .= ',';
1031                                 }
1032                                 $str_tags .= $newtag;
1033                         }
1034
1035                         /*
1036                          * Status.Net seems to require the numeric ID URL in a mention if the person isn't
1037                          * subscribed to you. But the nickname URL is OK if they are. Grrr. We'll tag both.
1038                          */
1039                         if (strlen($alias)) {
1040                                 $newtag = '@[url=' . $alias . ']' . $newname . '[/url]';
1041                                 if (!stripos($str_tags, '[url=' . $alias . ']')) {
1042                                         if (strlen($str_tags)) {
1043                                                 $str_tags .= ',';
1044                                         }
1045                                         $str_tags .= $newtag;
1046                                 }
1047                         }
1048                 }
1049         }
1050
1051         return ['replaced' => $replaced, 'contact' => $contact];
1052 }