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.
14 * All of these become an "item" which is our basic unit of
18 use Friendica\Core\Config;
19 use Friendica\Core\System;
20 use Friendica\Core\Worker;
21 use Friendica\Database\DBM;
22 use Friendica\Model\Contact;
23 use Friendica\Model\GContact;
24 use Friendica\Model\Item;
25 use Friendica\Network\Probe;
26 use Friendica\Protocol\Diaspora;
27 use Friendica\Protocol\Email;
28 use Friendica\Util\Emailer;
30 require_once 'include/enotify.php';
31 require_once 'include/tags.php';
32 require_once 'include/threads.php';
33 require_once 'include/text.php';
34 require_once 'include/items.php';
36 function item_post(App $a) {
37 if (!local_user() && !remote_user() && !x($_REQUEST, 'commenter')) {
41 require_once 'include/security.php';
45 if (x($_REQUEST, 'dropitems')) {
46 $arr_drop = explode(',', $_REQUEST['dropitems']);
47 drop_items($arr_drop);
48 $json = array('success' => 1);
49 echo json_encode($json);
53 call_hooks('post_local_start', $_REQUEST);
54 // logger('postinput ' . file_get_contents('php://input'));
55 logger('postvars ' . print_r($_REQUEST,true), LOGGER_DATA);
57 $api_source = x($_REQUEST, 'api_source') && $_REQUEST['api_source'];
59 $message_id = ((x($_REQUEST, 'message_id') && $api_source) ? strip_tags($_REQUEST['message_id']) : '');
61 $return_path = (x($_REQUEST, 'return') ? $_REQUEST['return'] : '');
62 $preview = (x($_REQUEST, 'preview') ? intval($_REQUEST['preview']) : 0);
65 * Check for doubly-submitted posts, and reject duplicates
66 * Note that we have to ignore previews, otherwise nothing will post
67 * after it's been previewed
69 if (!$preview && x($_REQUEST, 'post_id_random')) {
70 if (x($_SESSION, 'post-random') && $_SESSION['post-random'] == $_REQUEST['post_id_random']) {
71 logger("item post: duplicate post", LOGGER_DEBUG);
72 item_post_return(System::baseUrl(), $api_source, $return_path);
74 $_SESSION['post-random'] = $_REQUEST['post_id_random'];
78 // Is this a reply to something?
79 $parent = (x($_REQUEST, 'parent') ? intval($_REQUEST['parent']) : 0);
80 $parent_uri = (x($_REQUEST, 'parent_uri') ? trim($_REQUEST['parent_uri']) : '');
83 $parent_contact = null;
89 if ($parent || $parent_uri) {
91 $objecttype = ACTIVITY_OBJ_COMMENT;
93 if (!x($_REQUEST, 'type')) {
94 $_REQUEST['type'] = 'net-comment';
98 $r = q("SELECT * FROM `item` WHERE `id` = %d LIMIT 1",
101 } elseif ($parent_uri && local_user()) {
102 // This is coming from an API source, and we are logged in
103 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
109 // if this isn't the real parent of the conversation, find it
110 if (DBM::is_result($r)) {
111 $parid = $r[0]['parent'];
112 $parent_uri = $r[0]['uri'];
113 if ($r[0]['id'] != $r[0]['parent']) {
114 $r = q("SELECT * FROM `item` WHERE `id` = `parent` AND `parent` = %d LIMIT 1",
120 if (!DBM::is_result($r)) {
121 notice(t('Unable to locate original post.') . EOL);
122 if (x($_REQUEST, 'return')) {
123 goaway($return_path);
127 $parent_item = $r[0];
128 $parent = $r[0]['id'];
130 // multi-level threading - preserve the info but re-parent to our single level threading
131 $thr_parent = $parent_uri;
133 if ($parent_item['contact-id'] && $uid) {
134 $r = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d LIMIT 1",
135 intval($parent_item['contact-id']),
138 if (DBM::is_result($r)) {
139 $parent_contact = $r[0];
142 // If the contact id doesn't fit with the contact, then set the contact to null
143 $thrparent = q("SELECT `author-link`, `network` FROM `item` WHERE `uri` = '%s' LIMIT 1", dbesc($thr_parent));
144 if (DBM::is_result($thrparent) && ($thrparent[0]["network"] === NETWORK_OSTATUS)
145 && (normalise_link($parent_contact["url"]) != normalise_link($thrparent[0]["author-link"]))) {
146 $parent_contact = Contact::getDetailsByURL($thrparent[0]["author-link"]);
148 if (!isset($parent_contact["nick"])) {
149 $probed_contact = Probe::uri($thrparent[0]["author-link"]);
150 if ($probed_contact["network"] != NETWORK_FEED) {
151 $parent_contact = $probed_contact;
152 $parent_contact["nurl"] = normalise_link($probed_contact["url"]);
153 $parent_contact["thumb"] = $probed_contact["photo"];
154 $parent_contact["micro"] = $probed_contact["photo"];
155 $parent_contact["addr"] = $probed_contact["addr"];
158 logger('no contact found: ' . print_r($thrparent, true), LOGGER_DEBUG);
160 logger('parent contact: ' . print_r($parent_contact, true), LOGGER_DEBUG);
163 if ($parent_contact["nick"] == "") {
164 $parent_contact["nick"] = $parent_contact["name"];
170 logger('mod_item: item_post parent=' . $parent);
173 $profile_uid = (x($_REQUEST, 'profile_uid') ? intval($_REQUEST['profile_uid']) : 0);
174 $post_id = (x($_REQUEST, 'post_id') ? intval($_REQUEST['post_id']) : 0);
175 $app = (x($_REQUEST, 'source') ? strip_tags($_REQUEST['source']) : '');
176 $extid = (x($_REQUEST, 'extid') ? strip_tags($_REQUEST['extid']) : '');
177 $object = (x($_REQUEST, 'object') ? $_REQUEST['object'] : '');
179 // Check for multiple posts with the same message id (when the post was created via API)
180 if (($message_id != '') && ($profile_uid != 0)) {
181 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
186 if (DBM::is_result($r)) {
187 logger("Message with URI ".$message_id." already exists for user ".$profile_uid, LOGGER_DEBUG);
192 $allow_moderated = false;
194 // here is where we are going to check for permission to post a moderated comment.
196 // First check that the parent exists and it is a wall item.
198 if (x($_REQUEST, 'commenter') && (!$parent || !$parent_item['wall'])) {
199 notice(t('Permission denied.') . EOL) ;
200 if (x($_REQUEST, 'return')) {
201 goaway($return_path);
206 // Allow commenting if it is an answer to a public post
207 $allow_comment = ($profile_uid == 0) && $parent && in_array($parent_item['network'], [NETWORK_OSTATUS, NETWORK_DIASPORA, NETWORK_DFRN]);
210 * Now check that it is a page_type of PAGE_BLOG, and that valid personal details
211 * have been provided, and run any anti-spam plugins
213 if (!(can_write_wall($profile_uid) || $allow_comment) && !$allow_moderated) {
214 notice(t('Permission denied.') . EOL) ;
215 if (x($_REQUEST, 'return')) {
216 goaway($return_path);
222 // is this an edited post?
227 $i = q("SELECT * FROM `item` WHERE `uid` = %d AND `id` = %d LIMIT 1",
228 intval($profile_uid),
231 if (!DBM::is_result($i)) {
239 $r = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
242 if (DBM::is_result($r)) {
247 $str_group_allow = $orig_post['allow_gid'];
248 $str_contact_allow = $orig_post['allow_cid'];
249 $str_group_deny = $orig_post['deny_gid'];
250 $str_contact_deny = $orig_post['deny_cid'];
251 $location = $orig_post['location'];
252 $coord = $orig_post['coord'];
253 $verb = $orig_post['verb'];
254 $objecttype = $orig_post['object-type'];
255 $emailcc = $orig_post['emailcc'];
256 $app = $orig_post['app'];
257 $categories = $orig_post['file'];
258 $title = notags(trim($_REQUEST['title']));
259 $body = escape_tags(trim($_REQUEST['body']));
260 $private = $orig_post['private'];
261 $pubmail_enable = $orig_post['pubmail'];
262 $network = $orig_post['network'];
263 $guid = $orig_post['guid'];
264 $extid = $orig_post['extid'];
269 * if coming from the API and no privacy settings are set,
270 * use the user default permissions - as they won't have
271 * been supplied via a form.
273 /// @TODO use x($_REQUEST, 'foo') here
275 && !array_key_exists('contact_allow', $_REQUEST)
276 && !array_key_exists('group_allow', $_REQUEST)
277 && !array_key_exists('contact_deny', $_REQUEST)
278 && !array_key_exists('group_deny', $_REQUEST)) {
279 $str_group_allow = $user['allow_gid'];
280 $str_contact_allow = $user['allow_cid'];
281 $str_group_deny = $user['deny_gid'];
282 $str_contact_deny = $user['deny_cid'];
285 // use the posted permissions
287 $str_group_allow = perms2str($_REQUEST['group_allow']);
288 $str_contact_allow = perms2str($_REQUEST['contact_allow']);
289 $str_group_deny = perms2str($_REQUEST['group_deny']);
290 $str_contact_deny = perms2str($_REQUEST['contact_deny']);
293 $title = notags(trim($_REQUEST['title']));
294 $location = notags(trim($_REQUEST['location']));
295 $coord = notags(trim($_REQUEST['coord']));
296 $verb = notags(trim($_REQUEST['verb']));
297 $emailcc = notags(trim($_REQUEST['emailcc']));
298 $body = escape_tags(trim($_REQUEST['body']));
299 $network = notags(trim($_REQUEST['network']));
300 $guid = get_guid(32);
302 item_add_language_opt($_REQUEST);
303 $postopts = $_REQUEST['postopts'] ? $_REQUEST['postopts'] : "";
305 $private = ((strlen($str_group_allow) || strlen($str_contact_allow) || strlen($str_group_deny) || strlen($str_contact_deny)) ? 1 : 0);
307 if ($user['hidewall']) {
311 // If this is a comment, set the permissions from the parent.
315 // for non native networks use the network of the original post as network of the item
316 if (($parent_item['network'] != NETWORK_DIASPORA)
317 && ($parent_item['network'] != NETWORK_OSTATUS)
318 && ($network == "")) {
319 $network = $parent_item['network'];
322 $str_contact_allow = $parent_item['allow_cid'];
323 $str_group_allow = $parent_item['allow_gid'];
324 $str_contact_deny = $parent_item['deny_cid'];
325 $str_group_deny = $parent_item['deny_gid'];
326 $private = $parent_item['private'];
329 $pubmail_enable = ((x($_REQUEST, 'pubmail_enable') && intval($_REQUEST['pubmail_enable']) && !$private) ? 1 : 0);
331 // if using the API, we won't see pubmail_enable - figure out if it should be set
333 if ($api_source && $profile_uid && $profile_uid == local_user() && !$private) {
334 $mail_disabled = ((function_exists('imap_open') && !Config::get('system', 'imap_disabled')) ? 0 : 1);
335 if (!$mail_disabled) {
336 /// @TODO Check if only pubmail is loaded, * loads all columns
337 $r = q("SELECT * FROM `mailacct` WHERE `uid` = %d AND `server` != '' LIMIT 1",
340 if (DBM::is_result($r) && intval($r[0]['pubmail'])) {
341 $pubmail_enabled = true;
346 if (!strlen($body)) {
350 info(t('Empty post discarded.') . EOL);
351 if (x($_REQUEST, 'return')) {
352 goaway($return_path);
358 if (strlen($categories)) {
359 // get the "fileas" tags for this post
360 $filedas = file_tag_file_to_list($categories, 'file');
362 // save old and new categories, so we can determine what needs to be deleted from pconfig
363 $categories_old = $categories;
364 $categories = file_tag_list_to_file(trim($_REQUEST['category']), 'category');
365 $categories_new = $categories;
366 if (strlen($filedas)) {
367 // append the fileas stuff to the new categories list
368 $categories .= file_tag_list_to_file($filedas, 'file');
371 // get contact info for poster
377 if (local_user() && ((local_user() == $profile_uid) || $allow_comment)) {
379 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `self` LIMIT 1",
380 intval($_SESSION['uid']));
381 } elseif (remote_user()) {
382 if (x($_SESSION, 'remote') && is_array($_SESSION['remote'])) {
383 foreach ($_SESSION['remote'] as $v) {
384 if ($v['uid'] == $profile_uid) {
385 $contact_id = $v['cid'];
391 $r = q("SELECT * FROM `contact` WHERE `id` = %d LIMIT 1",
397 if (DBM::is_result($r)) {
399 $contact_id = $author['id'];
402 // get contact info for owner
404 if ($profile_uid == local_user() || $allow_comment) {
405 $contact_record = $author;
407 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `self` LIMIT 1",
410 if (DBM::is_result($r)) {
411 $contact_record = $r[0];
415 $post_type = notags(trim($_REQUEST['type']));
417 if ($post_type === 'net-comment' && $parent_item !== null) {
418 if ($parent_item['wall'] == 1) {
419 $post_type = 'wall-comment';
421 $post_type = 'remote-comment';
425 // Look for any tags and linkify them
429 $tags = get_tags($body);
432 * add a statusnet style reply tag if the original post was from there
433 * and we are replying, and there isn't one already
435 if ($parent && ($parent_contact['network'] == NETWORK_OSTATUS)) {
436 $contact = '@[url=' . $parent_contact['url'] . ']' . $parent_contact['nick'] . '[/url]';
438 if (!in_array($contact, $tags)) {
439 $body = $contact . ' ' . $body;
443 $toplevel_contact = "";
444 $toplevel_parent = q("SELECT `contact`.* FROM `contact`
445 INNER JOIN `item` ON `item`.`contact-id` = `contact`.`id` AND `contact`.`url` = `item`.`author-link`
446 WHERE `item`.`id` = `item`.`parent` AND `item`.`parent` = %d", intval($parent));
447 if (DBM::is_result($toplevel_parent)) {
448 if (!empty($toplevel_parent[0]['addr'])) {
449 $toplevel_contact = '@' . $toplevel_parent[0]['addr'];
451 $toplevel_contact = '@' . $toplevel_parent[0]['nick'] . '+' . $toplevel_parent[0]['id'];
454 $toplevel_parent = q("SELECT `author-link`, `author-name` FROM `item` WHERE `id` = `parent` AND `parent` = %d", intval($parent));
455 $toplevel_contact = '@[url=' . $toplevel_parent[0]['author-link'] . ']' . $toplevel_parent[0]['author-name'] . '[/url]';
458 if (!in_array($toplevel_contact, $tags)) {
459 $tags[] = $toplevel_contact;
465 $private_forum = false;
466 $only_to_forum = false;
467 $forum_contact = array();
470 foreach ($tags as $tag) {
472 $tag_type = substr($tag, 0, 1);
474 if ($tag_type == '#') {
479 * If we already tagged 'Robert Johnson', don't try and tag 'Robert'.
480 * Robert Johnson should be first in the $tags array
482 $fullnametagged = false;
483 /// @TODO $tagged is initialized above if () block and is not filled, maybe old-lost code?
484 foreach ($tagged as $nextTag) {
485 if (stristr($nextTag, $tag . ' ')) {
486 $fullnametagged = true;
490 if ($fullnametagged) {
494 $success = handle_tag($a, $body, $inform, $str_tags, local_user() ? local_user() : $profile_uid, $tag, $network);
495 if ($success['replaced']) {
498 // When the forum is private or the forum is addressed with a "!" make the post private
499 if (is_array($success['contact']) && ($success['contact']['prv'] || ($tag_type == '!'))) {
500 $private_forum = $success['contact']['prv'];
501 $only_to_forum = ($tag_type == '!');
502 $private_id = $success['contact']['id'];
503 $forum_contact = $success['contact'];
504 } elseif (is_array($success['contact']) && $success['contact']['forum'] &&
505 ($str_contact_allow == '<' . $success['contact']['id'] . '>')) {
506 $private_forum = false;
507 $only_to_forum = true;
508 $private_id = $success['contact']['id'];
509 $forum_contact = $success['contact'];
514 $original_contact_id = $contact_id;
516 if (!$parent && count($forum_contact) && ($private_forum || $only_to_forum)) {
517 // we tagged a forum in a top level post. Now we change the post
518 $private = $private_forum;
520 $str_group_allow = '';
521 $str_contact_deny = '';
522 $str_group_deny = '';
523 if ($private_forum) {
524 $str_contact_allow = '<' . $private_id . '>';
526 $str_contact_allow = '';
528 $contact_id = $private_id;
529 $contact_record = $forum_contact;
530 $_REQUEST['origin'] = false;
534 * When a photo was uploaded into the message using the (profile wall) ajax
535 * uploader, The permissions are initially set to disallow anybody but the
536 * owner from seeing it. This is because the permissions may not yet have been
537 * set for the post. If it's private, the photo permissions should be set
538 * appropriately. But we didn't know the final permissions on the post until
539 * now. So now we'll look for links of uploaded messages that are in the
540 * post and set them to the same permissions as the post itself.
545 if (!$preview && preg_match_all("/\[img([\=0-9x]*?)\](.*?)\[\/img\]/",$body,$match)) {
547 if (count($images)) {
549 $objecttype = ACTIVITY_OBJ_IMAGE;
551 foreach ($images as $image) {
552 if (!stristr($image, System::baseUrl() . '/photo/')) {
555 $image_uri = substr($image,strrpos($image,'/') + 1);
556 $image_uri = substr($image_uri,0, strpos($image_uri,'-'));
557 if (!strlen($image_uri)) {
560 $srch = '<' . intval($original_contact_id) . '>';
562 $r = q("SELECT `id` FROM `photo` WHERE `allow_cid` = '%s' AND `allow_gid` = '' AND `deny_cid` = '' AND `deny_gid` = ''
563 AND `resource-id` = '%s' AND `uid` = %d LIMIT 1",
569 if (!DBM::is_result($r)) {
573 $r = q("UPDATE `photo` SET `allow_cid` = '%s', `allow_gid` = '%s', `deny_cid` = '%s', `deny_gid` = '%s'
574 WHERE `resource-id` = '%s' AND `uid` = %d AND `album` = '%s' ",
575 dbesc($str_contact_allow),
576 dbesc($str_group_allow),
577 dbesc($str_contact_deny),
578 dbesc($str_group_deny),
580 intval($profile_uid),
581 dbesc(t('Wall Photos'))
589 * Next link in any attachment references we find in the post.
593 if (!$preview && preg_match_all("/\[attachment\](.*?)\[\/attachment\]/", $body, $match)) {
594 $attaches = $match[1];
595 if (count($attaches)) {
596 foreach ($attaches as $attach) {
597 $r = q("SELECT * FROM `attach` WHERE `uid` = %d AND `id` = %d LIMIT 1",
598 intval($profile_uid),
601 if (DBM::is_result($r)) {
602 $r = q("UPDATE `attach` SET `allow_cid` = '%s', `allow_gid` = '%s', `deny_cid` = '%s', `deny_gid` = '%s'
603 WHERE `uid` = %d AND `id` = %d",
604 dbesc($str_contact_allow),
605 dbesc($str_group_allow),
606 dbesc($str_contact_deny),
607 dbesc($str_group_deny),
608 intval($profile_uid),
616 // embedded bookmark or attachment in post? set bookmark flag
619 $data = get_attachment_data($body);
620 if (preg_match_all("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/ism", $body, $match, PREG_SET_ORDER) || isset($data["type"])) {
621 $objecttype = ACTIVITY_OBJ_BOOKMARK;
625 $body = bb_translate_video($body);
628 // Fold multi-line [code] sequences
629 $body = preg_replace('/\[\/code\]\s*\[code\]/ism', "\n", $body);
631 $body = scale_external_images($body, false);
633 // Setting the object type if not defined before
635 $objecttype = ACTIVITY_OBJ_NOTE; // Default value
636 require_once 'include/plaintext.php';
637 $objectdata = get_attached_data($body);
639 if ($objectdata["type"] == "link") {
640 $objecttype = ACTIVITY_OBJ_BOOKMARK;
641 } elseif ($objectdata["type"] == "video") {
642 $objecttype = ACTIVITY_OBJ_VIDEO;
643 } elseif ($objectdata["type"] == "photo") {
644 $objecttype = ACTIVITY_OBJ_IMAGE;
652 if (preg_match_all('/(\[attachment\]([0-9]+)\[\/attachment\])/',$body,$match)) {
653 foreach ($match[2] as $mtch) {
654 $r = q("SELECT `id`,`filename`,`filesize`,`filetype` FROM `attach` WHERE `uid` = %d AND `id` = %d LIMIT 1",
655 intval($profile_uid),
658 if (DBM::is_result($r)) {
659 if (strlen($attachments)) {
662 $attachments .= '[attach]href="' . System::baseUrl() . '/attach/' . $r[0]['id'] . '" length="' . $r[0]['filesize'] . '" type="' . $r[0]['filetype'] . '" title="' . (($r[0]['filename']) ? $r[0]['filename'] : '') . '"[/attach]';
664 $body = str_replace($match[1],'',$body);
670 if (($post_type === 'wall' || $post_type === 'wall-comment') && !count($forum_contact)) {
674 if (!strlen($verb)) {
675 $verb = ACTIVITY_POST;
678 if ($network == "") {
679 $network = NETWORK_DFRN;
682 $gravity = ($parent ? 6 : 0);
684 // even if the post arrived via API we are considering that it
685 // originated on this site by default for determining relayability.
687 $origin = (x($_REQUEST, 'origin') ? intval($_REQUEST['origin']) : 1);
689 $notify_type = ($parent ? 'comment-new' : 'wall-new');
691 $uri = ($message_id ? $message_id : item_new_uri($a->get_hostname(),$profile_uid, $guid));
693 // Fallback so that we alway have a thr-parent
699 $datarray['uid'] = $profile_uid;
700 $datarray['type'] = $post_type;
701 $datarray['wall'] = $wall;
702 $datarray['gravity'] = $gravity;
703 $datarray['network'] = $network;
704 $datarray['contact-id'] = $contact_id;
705 $datarray['owner-name'] = $contact_record['name'];
706 $datarray['owner-link'] = $contact_record['url'];
707 $datarray['owner-avatar'] = $contact_record['thumb'];
708 $datarray['owner-id'] = Contact::getIdForURL($datarray['owner-link'], 0);
709 $datarray['author-name'] = $author['name'];
710 $datarray['author-link'] = $author['url'];
711 $datarray['author-avatar'] = $author['thumb'];
712 $datarray['author-id'] = Contact::getIdForURL($datarray['author-link'], 0);
713 $datarray['created'] = datetime_convert();
714 $datarray['edited'] = datetime_convert();
715 $datarray['commented'] = datetime_convert();
716 $datarray['received'] = datetime_convert();
717 $datarray['changed'] = datetime_convert();
718 $datarray['extid'] = $extid;
719 $datarray['guid'] = $guid;
720 $datarray['uri'] = $uri;
721 $datarray['title'] = $title;
722 $datarray['body'] = $body;
723 $datarray['app'] = $app;
724 $datarray['location'] = $location;
725 $datarray['coord'] = $coord;
726 $datarray['tag'] = $str_tags;
727 $datarray['file'] = $categories;
728 $datarray['inform'] = $inform;
729 $datarray['verb'] = $verb;
730 $datarray['object-type'] = $objecttype;
731 $datarray['allow_cid'] = $str_contact_allow;
732 $datarray['allow_gid'] = $str_group_allow;
733 $datarray['deny_cid'] = $str_contact_deny;
734 $datarray['deny_gid'] = $str_group_deny;
735 $datarray['private'] = $private;
736 $datarray['pubmail'] = $pubmail_enable;
737 $datarray['attach'] = $attachments;
738 $datarray['bookmark'] = intval($bookmark);
739 $datarray['thr-parent'] = $thr_parent;
740 $datarray['postopts'] = $postopts;
741 $datarray['origin'] = $origin;
742 $datarray['moderated'] = $allow_moderated;
743 $datarray['gcontact-id'] = GContact::getId(array("url" => $datarray['author-link'], "network" => $datarray['network'],
744 "photo" => $datarray['author-avatar'], "name" => $datarray['author-name']));
745 $datarray['object'] = $object;
748 * These fields are for the convenience of plugins...
749 * 'self' if true indicates the owner is posting on their own wall
750 * If parent is 0 it is a top-level post.
752 $datarray['parent'] = $parent;
753 $datarray['self'] = $self;
755 // This triggers posts via API and the mirror functions
756 $datarray['api_source'] = $api_source;
758 $datarray['parent-uri'] = ($parent == 0) ? $uri : $parent_item['uri'];
759 $datarray['plink'] = System::baseUrl() . '/display/' . urlencode($datarray['guid']);
760 $datarray['last-child'] = 1;
761 $datarray['visible'] = 1;
763 $datarray['protocol'] = PROTOCOL_DFRN;
765 $r = dba::fetch_first("SELECT `conversation-uri`, `conversation-href` FROM `conversation` WHERE `item-uri` = ?", $datarray['parent-uri']);
766 if (DBM::is_result($r)) {
767 if ($r['conversation-uri'] != '') {
768 $datarray['conversation-uri'] = $r['conversation-uri'];
770 if ($r['conversation-href'] != '') {
771 $datarray['conversation-href'] = $r['conversation-href'];
776 $datarray['edit'] = true;
779 // Search for hashtags
780 item_body_set_hashtags($datarray);
782 // preview mode - prepare the body for display and send it via json
784 require_once 'include/conversation.php';
785 // We set the datarray ID to -1 because in preview mode the dataray
786 // doesn't have an ID.
787 $datarray["id"] = -1;
788 $o = conversation($a,array(array_merge($contact_record,$datarray)),'search', false, true);
789 logger('preview: ' . $o);
790 echo json_encode(array('preview' => $o));
794 call_hooks('post_local',$datarray);
796 if (x($datarray, 'cancel')) {
797 logger('mod_item: post cancelled by plugin.');
799 goaway($return_path);
802 $json = array('cancel' => 1);
803 if (x($_REQUEST, 'jsreload') && strlen($_REQUEST['jsreload'])) {
804 $json['reload'] = System::baseUrl() . '/' . $_REQUEST['jsreload'];
807 echo json_encode($json);
813 // Fill the cache field
814 // This could be done in Item::update as well - but we have to check for the existance of some fields.
815 put_item_in_cache($datarray);
818 'title' => $datarray['title'],
819 'body' => $datarray['body'],
820 'tag' => $datarray['tag'],
821 'attach' => $datarray['attach'],
822 'file' => $datarray['file'],
823 'rendered-html' => $datarray['rendered-html'],
824 'rendered-hash' => $datarray['rendered-hash'],
825 'edited' => datetime_convert(),
826 'changed' => datetime_convert());
828 Item::update($fields, ['id' => $post_id]);
830 // update filetags in pconfig
831 file_tag_update_pconfig($uid,$categories_old,$categories_new,'category');
833 if (x($_REQUEST, 'return') && strlen($return_path)) {
834 logger('return: ' . $return_path);
835 goaway($return_path);
842 unset($datarray['edit']);
843 unset($datarray['self']);
844 unset($datarray['api_source']);
846 $post_id = item_store($datarray);
848 $datarray["id"] = $post_id;
850 // update filetags in pconfig
851 file_tag_update_pconfig($uid, $categories_old, $categories_new, 'category');
853 // These notifications are sent if someone else is commenting other your wall
855 if ($contact_record != $author) {
857 'type' => NOTIFY_COMMENT,
858 'notify_flags' => $user['notify-flags'],
859 'language' => $user['language'],
860 'to_name' => $user['username'],
861 'to_email' => $user['email'],
862 'uid' => $user['uid'],
864 'link' => System::baseUrl().'/display/'.urlencode($datarray['guid']),
865 'source_name' => $datarray['author-name'],
866 'source_link' => $datarray['author-link'],
867 'source_photo' => $datarray['author-avatar'],
868 'verb' => ACTIVITY_POST,
871 'parent_uri' => $parent_item['uri']
875 // Store the comment signature information in case we need to relay to Diaspora
876 Diaspora::storeCommentSignature($datarray, $author, ($self ? $user['prvkey'] : false), $post_id);
878 if (($contact_record != $author) && !count($forum_contact)) {
880 'type' => NOTIFY_WALL,
881 'notify_flags' => $user['notify-flags'],
882 'language' => $user['language'],
883 'to_name' => $user['username'],
884 'to_email' => $user['email'],
885 'uid' => $user['uid'],
887 'link' => System::baseUrl().'/display/'.urlencode($datarray['guid']),
888 'source_name' => $datarray['author-name'],
889 'source_link' => $datarray['author-link'],
890 'source_photo' => $datarray['author-avatar'],
891 'verb' => ACTIVITY_POST,
897 call_hooks('post_local_end', $datarray);
899 if (strlen($emailcc) && $profile_uid == local_user()) {
900 $erecips = explode(',', $emailcc);
901 if (count($erecips)) {
902 foreach ($erecips as $recip) {
903 $addr = trim($recip);
904 if (!strlen($addr)) {
907 $disclaimer = '<hr />' . sprintf(t('This message was sent to you by %s, a member of the Friendica social network.'), $a->user['username'])
909 $disclaimer .= sprintf(t('You may visit them online at %s'), System::baseUrl() . '/profile/' . $a->user['nickname']) . EOL;
910 $disclaimer .= t('Please contact the sender by replying to this post if you do not wish to receive these messages.') . EOL;
911 if (!$datarray['title']=='') {
912 $subject = Email::encodeHeader($datarray['title'], 'UTF-8');
914 $subject = Email::encodeHeader('[Friendica]' . ' ' . sprintf(t('%s posted an update.'), $a->user['username']), 'UTF-8');
916 $link = '<a href="' . System::baseUrl() . '/profile/' . $a->user['nickname'] . '"><img src="' . $author['thumb'] . '" alt="' . $a->user['username'] . '" /></a><br /><br />';
917 $html = prepare_body($datarray);
918 $message = '<html><body>' . $link . $html . $disclaimer . '</body></html>';
919 include_once 'include/html2plain.php';
921 'fromName' => $a->user['username'],
922 'fromEmail' => $a->user['email'],
924 'replyTo' => $a->user['email'],
925 'messageSubject' => $subject,
926 'htmlVersion' => $message,
927 'textVersion' => html2plain($html.$disclaimer)
929 Emailer::send($params);
934 // Insert an item entry for UID=0 for global entries.
935 // We now do it in the background to save some time.
936 // This is important in interactive environments like the frontend or the API.
937 // We don't fork a new process since this is done anyway with the following command
938 Worker::add(array('priority' => PRIORITY_HIGH, 'dont_fork' => true), "CreateShadowEntry", $post_id);
940 // Call the background process that is delivering the item to the receivers
941 Worker::add(PRIORITY_HIGH, "Notifier", $notify_type, $post_id);
943 logger('post_complete');
945 item_post_return(System::baseUrl(), $api_source, $return_path);
949 function item_post_return($baseurl, $api_source, $return_path) {
950 // figure out how to return, depending on from whence we came
957 goaway($return_path);
960 $json = array('success' => 1);
961 if (x($_REQUEST, 'jsreload') && strlen($_REQUEST['jsreload'])) {
962 $json['reload'] = $baseurl . '/' . $_REQUEST['jsreload'];
965 logger('post_json: ' . print_r($json,true), LOGGER_DEBUG);
967 echo json_encode($json);
973 function item_content(App $a) {
975 if (!local_user() && !remote_user()) {
979 require_once 'include/security.php';
982 if (($a->argc == 3) && ($a->argv[1] === 'drop') && intval($a->argv[2])) {
983 $o = drop_item($a->argv[2], !is_ajax());
985 // ajax return: [<item id>, 0 (no perm) | <owner id>]
986 echo json_encode(array(intval($a->argv[2]), intval($o)));
994 * This function removes the tag $tag from the text $body and replaces it with
995 * the appropiate link.
997 * @param App $a Application instance @TODO is unused in this function's scope (excluding included files)
998 * @param unknown_type $body the text to replace the tag in
999 * @param string $inform a comma-seperated string containing everybody to inform
1000 * @param string $str_tags string to add the tag to
1001 * @param integer $profile_uid
1002 * @param string $tag the tag to replace
1003 * @param string $network The network of the post
1005 * @return boolean true if replaced, false if not replaced
1007 function handle_tag(App $a, &$body, &$inform, &$str_tags, $profile_uid, $tag, $network = "")
1013 //is it a person tag?
1014 if ((strpos($tag, '@') === 0) || (strpos($tag, '!') === 0)) {
1015 $tag_type = substr($tag, 0, 1);
1016 //is it already replaced?
1017 if (strpos($tag, '[url=')) {
1018 //append tag to str_tags
1019 if (!stristr($str_tags, $tag)) {
1020 if (strlen($str_tags)) {
1026 // Checking for the alias that is used for OStatus
1027 $pattern = "/[@!]\[url\=(.*?)\](.*?)\[\/url\]/ism";
1028 if (preg_match($pattern, $tag, $matches)) {
1030 $r = q("SELECT `alias`, `name` FROM `contact` WHERE `nurl` = '%s' AND `alias` != '' AND `uid` = 0",
1031 normalise_link($matches[1]));
1032 if (!DBM::is_result($r)) {
1033 $r = q("SELECT `alias`, `name` FROM `gcontact` WHERE `nurl` = '%s' AND `alias` != ''",
1034 normalise_link($matches[1]));
1036 if (DBM::is_result($r)) {
1039 $data = Probe::uri($matches[1]);
1042 if ($data["alias"] != "") {
1043 $newtag = '@[url=' . $data["alias"] . ']' . $data["name"] . '[/url]';
1044 if (!stristr($str_tags, $newtag)) {
1045 if (strlen($str_tags)) {
1048 $str_tags .= $newtag;
1056 //get the person's name
1057 $name = substr($tag, 1);
1059 // Sometimes the tag detection doesn't seem to work right
1060 // This is some workaround
1061 $nameparts = explode(" ", $name);
1062 $name = $nameparts[0];
1064 // Try to detect the contact in various ways
1065 if ((strpos($name, '@')) || (strpos($name, 'http://'))) {
1066 // Is it in format @user@domain.tld or @http://domain.tld/...?
1068 // First check the contact table for the address
1069 $r = q("SELECT `id`, `url`, `nick`, `name`, `alias`, `network`, `notify`, `forum`, `prv` FROM `contact`
1070 WHERE `addr` = '%s' AND `uid` = %d AND
1071 (`network` != '%s' OR (`notify` != '' AND `alias` != ''))
1074 intval($profile_uid),
1075 dbesc(NETWORK_OSTATUS)
1078 // Then check in the contact table for the url
1079 if (!DBM::is_result($r)) {
1080 $r = q("SELECT `id`, `url`, `nick`, `name`, `alias`, `network`, `notify`, `forum`, `prv` FROM `contact`
1081 WHERE `nurl` = '%s' AND `uid` = %d AND
1082 (`network` != '%s' OR (`notify` != '' AND `alias` != ''))
1084 dbesc(normalise_link($name)),
1085 intval($profile_uid),
1086 dbesc(NETWORK_OSTATUS)
1090 // Then check in the global contacts for the address
1091 if (!DBM::is_result($r)) {
1092 $r = q("SELECT `url`, `nick`, `name`, `alias`, `network`, `notify` FROM `gcontact`
1093 WHERE `addr` = '%s' AND (`network` != '%s' OR (`notify` != '' AND `alias` != ''))
1096 dbesc(NETWORK_OSTATUS)
1100 // Then check in the global contacts for the url
1101 if (!DBM::is_result($r)) {
1102 $r = q("SELECT `url`, `nick`, `name`, `alias`, `network`, `notify` FROM `gcontact`
1103 WHERE `nurl` = '%s' AND (`network` != '%s' OR (`notify` != '' AND `alias` != ''))
1105 dbesc(normalise_link($name)),
1106 dbesc(NETWORK_OSTATUS)
1110 if (!DBM::is_result($r)) {
1111 $probed = Probe::uri($name);
1112 if ($result['network'] != NETWORK_PHANTOM) {
1113 GContact::update($probed);
1114 $r = q("SELECT `url`, `name`, `nick`, `network`, `alias`, `notify` FROM `gcontact` WHERE `nurl` = '%s' LIMIT 1",
1115 dbesc(normalise_link($probed["url"])));
1120 if (strrpos($name, '+')) {
1121 // Is it in format @nick+number?
1122 $tagcid = intval(substr($name, strrpos($name, '+') + 1));
1124 $r = q("SELECT `id`, `url`, `nick`, `name`, `alias`, `network` FROM `contact` WHERE `id` = %d AND `uid` = %d LIMIT 1",
1126 intval($profile_uid)
1130 // select someone by attag or nick and the name passed in the current network
1131 if (!DBM::is_result($r) && ($network != ""))
1132 $r = q("SELECT `id`, `url`, `nick`, `name`, `alias`, `network` FROM `contact` WHERE `attag` = '%s' OR `nick` = '%s' AND `network` = '%s' AND `uid` = %d ORDER BY `attag` DESC LIMIT 1",
1136 intval($profile_uid)
1139 //select someone from this user's contacts by name in the current network
1140 if (!DBM::is_result($r) && ($network != "")) {
1141 $r = q("SELECT `id`, `url`, `nick`, `name`, `alias`, `network` FROM `contact` WHERE `name` = '%s' AND `network` = '%s' AND `uid` = %d LIMIT 1",
1144 intval($profile_uid)
1148 // select someone by attag or nick and the name passed in
1149 if (!DBM::is_result($r)) {
1150 $r = q("SELECT `id`, `url`, `nick`, `name`, `alias`, `network` FROM `contact` WHERE `attag` = '%s' OR `nick` = '%s' AND `uid` = %d ORDER BY `attag` DESC LIMIT 1",
1153 intval($profile_uid)
1157 // select someone from this user's contacts by name
1158 if (!DBM::is_result($r)) {
1159 $r = q("SELECT `id`, `url`, `nick`, `name`, `alias`, `network` FROM `contact` WHERE `name` = '%s' AND `uid` = %d LIMIT 1",
1161 intval($profile_uid)
1166 if (DBM::is_result($r)) {
1167 if (strlen($inform) && (isset($r[0]["notify"]) || isset($r[0]["id"]))) {
1171 if (isset($r[0]["id"])) {
1172 $inform .= 'cid:' . $r[0]["id"];
1173 } elseif (isset($r[0]["notify"])) {
1174 $inform .= $r[0]["notify"];
1177 $profile = $r[0]["url"];
1178 $alias = $r[0]["alias"];
1179 $newname = $r[0]["nick"];
1180 if (($newname == "") || (($r[0]["network"] != NETWORK_OSTATUS) && ($r[0]["network"] != NETWORK_TWITTER)
1181 && ($r[0]["network"] != NETWORK_STATUSNET) && ($r[0]["network"] != NETWORK_APPNET))) {
1182 $newname = $r[0]["name"];
1186 //if there is an url for this persons profile
1187 if (isset($profile) && ($newname != "")) {
1189 // create profile link
1190 $profile = str_replace(',', '%2c', $profile);
1191 $newtag = $tag_type.'[url=' . $profile . ']' . $newname . '[/url]';
1192 $body = str_replace($tag_type . $name, $newtag, $body);
1193 // append tag to str_tags
1194 if (!stristr($str_tags, $newtag)) {
1195 if (strlen($str_tags)) {
1198 $str_tags .= $newtag;
1202 * Status.Net seems to require the numeric ID URL in a mention if the person isn't
1203 * subscribed to you. But the nickname URL is OK if they are. Grrr. We'll tag both.
1205 if (strlen($alias)) {
1206 $newtag = '@[url=' . $alias . ']' . $newname . '[/url]';
1207 if (!stristr($str_tags, $newtag)) {
1208 if (strlen($str_tags)) {
1211 $str_tags .= $newtag;
1217 return array('replaced' => $replaced, 'contact' => $r[0]);