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