4 * This is the POST destination for most all locally posted
5 * text stuff. This function handles status, wall-to-wall status,
6 * local comments, and remote coments that are posted on this site
7 * (as opposed to being delivered in a feed).
8 * Also processed here are posts and comments coming through the
9 * statusnet/twitter API.
11 * All of these become an "item" which is our basic unit of
14 * Posts that originate externally or do not fall into the above
15 * posting categories go through item_store() instead of this function.
19 use Friendica\Core\System;
20 use Friendica\Core\Worker;
22 require_once 'include/crypto.php';
23 require_once 'include/enotify.php';
24 require_once 'include/email.php';
25 require_once 'include/tags.php';
26 require_once 'include/files.php';
27 require_once 'include/threads.php';
28 require_once 'include/text.php';
29 require_once 'include/items.php';
30 require_once 'include/probe.php';
31 require_once 'include/diaspora.php';
32 require_once 'include/Contact.php';
34 function item_post(App $a) {
36 if ((! local_user()) && (! remote_user()) && (! x($_REQUEST, 'commenter'))) {
40 require_once 'include/security.php';
44 if (x($_REQUEST, 'dropitems')) {
45 $arr_drop = explode(',', $_REQUEST['dropitems']);
46 drop_items($arr_drop);
47 $json = array('success' => 1);
48 echo json_encode($json);
52 call_hooks('post_local_start', $_REQUEST);
53 // logger('postinput ' . file_get_contents('php://input'));
54 logger('postvars ' . print_r($_REQUEST,true), LOGGER_DATA);
56 $api_source = ((x($_REQUEST, 'api_source') && $_REQUEST['api_source']) ? true : false);
58 $message_id = ((x($_REQUEST, 'message_id') && $api_source) ? strip_tags($_REQUEST['message_id']) : '');
60 $return_path = ((x($_REQUEST, 'return')) ? $_REQUEST['return'] : '');
61 $preview = ((x($_REQUEST, 'preview')) ? intval($_REQUEST['preview']) : 0);
64 * Check for doubly-submitted posts, and reject duplicates
65 * Note that we have to ignore previews, otherwise nothing will post
66 * after it's been previewed
68 if (!$preview && x($_REQUEST, 'post_id_random')) {
69 if (x($_SESSION, 'post-random') && $_SESSION['post-random'] == $_REQUEST['post_id_random']) {
70 logger("item post: duplicate post", LOGGER_DEBUG);
71 item_post_return(System::baseUrl(), $api_source, $return_path);
73 $_SESSION['post-random'] = $_REQUEST['post_id_random'];
77 // Is this a reply to something?
78 $parent = ((x($_REQUEST, 'parent')) ? intval($_REQUEST['parent']) : 0);
79 $parent_uri = ((x($_REQUEST, 'parent_uri')) ? trim($_REQUEST['parent_uri']) : '');
82 $parent_contact = null;
88 if ($parent || $parent_uri) {
90 $objecttype = ACTIVITY_OBJ_COMMENT;
92 if (! x($_REQUEST, 'type')) {
93 $_REQUEST['type'] = 'net-comment';
97 $r = q("SELECT * FROM `item` WHERE `id` = %d LIMIT 1",
100 } elseif ($parent_uri && local_user()) {
101 // This is coming from an API source, and we are logged in
102 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
108 // if this isn't the real parent of the conversation, find it
109 if (dbm::is_result($r)) {
110 $parid = $r[0]['parent'];
111 $parent_uri = $r[0]['uri'];
112 if ($r[0]['id'] != $r[0]['parent']) {
113 $r = q("SELECT * FROM `item` WHERE `id` = `parent` AND `parent` = %d LIMIT 1",
119 if (! dbm::is_result($r)) {
120 notice( t('Unable to locate original post.') . EOL);
121 if (x($_REQUEST, 'return')) {
122 goaway($return_path);
126 $parent_item = $r[0];
127 $parent = $r[0]['id'];
129 // multi-level threading - preserve the info but re-parent to our single level threading
130 //if(($parid) && ($parid != $parent))
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 = get_contact_details_by_url($thrparent[0]["author-link"]);
148 if (!isset($parent_contact["nick"])) {
149 $probed_contact = probe_url($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);
207 * Now check that it is a page_type of PAGE_BLOG, and that valid personal details
208 * have been provided, and run any anti-spam plugins
210 if ((! can_write_wall($a, $profile_uid)) && (! $allow_moderated)) {
211 notice(t('Permission denied.') . EOL) ;
212 if (x($_REQUEST, 'return')) {
213 goaway($return_path);
219 // is this an edited post?
224 $i = q("SELECT * FROM `item` WHERE `uid` = %d AND `id` = %d LIMIT 1",
225 intval($profile_uid),
228 if (! dbm::is_result($i)) {
236 $r = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
239 if (dbm::is_result($r)) {
244 $str_group_allow = $orig_post['allow_gid'];
245 $str_contact_allow = $orig_post['allow_cid'];
246 $str_group_deny = $orig_post['deny_gid'];
247 $str_contact_deny = $orig_post['deny_cid'];
248 $location = $orig_post['location'];
249 $coord = $orig_post['coord'];
250 $verb = $orig_post['verb'];
251 $objecttype = $orig_post['object-type'];
252 $emailcc = $orig_post['emailcc'];
253 $app = $orig_post['app'];
254 $categories = $orig_post['file'];
255 $title = notags(trim($_REQUEST['title']));
256 $body = escape_tags(trim($_REQUEST['body']));
257 $private = $orig_post['private'];
258 $pubmail_enable = $orig_post['pubmail'];
259 $network = $orig_post['network'];
260 $guid = $orig_post['guid'];
261 $extid = $orig_post['extid'];
266 * if coming from the API and no privacy settings are set,
267 * use the user default permissions - as they won't have
268 * been supplied via a form.
270 /// @TODO use x($_REQUEST, 'foo') here
272 && (! array_key_exists('contact_allow', $_REQUEST))
273 && (! array_key_exists('group_allow', $_REQUEST))
274 && (! array_key_exists('contact_deny', $_REQUEST))
275 && (! array_key_exists('group_deny', $_REQUEST))) {
276 $str_group_allow = $user['allow_gid'];
277 $str_contact_allow = $user['allow_cid'];
278 $str_group_deny = $user['deny_gid'];
279 $str_contact_deny = $user['deny_cid'];
282 // use the posted permissions
284 $str_group_allow = perms2str($_REQUEST['group_allow']);
285 $str_contact_allow = perms2str($_REQUEST['contact_allow']);
286 $str_group_deny = perms2str($_REQUEST['group_deny']);
287 $str_contact_deny = perms2str($_REQUEST['contact_deny']);
290 $title = notags(trim($_REQUEST['title']));
291 $location = notags(trim($_REQUEST['location']));
292 $coord = notags(trim($_REQUEST['coord']));
293 $verb = notags(trim($_REQUEST['verb']));
294 $emailcc = notags(trim($_REQUEST['emailcc']));
295 $body = escape_tags(trim($_REQUEST['body']));
296 $network = notags(trim($_REQUEST['network']));
297 $guid = get_guid(32);
299 item_add_language_opt($_REQUEST);
300 $postopts = $_REQUEST['postopts'] ? $_REQUEST['postopts'] : "";
302 $private = ((strlen($str_group_allow) || strlen($str_contact_allow) || strlen($str_group_deny) || strlen($str_contact_deny)) ? 1 : 0);
304 if ($user['hidewall']) {
308 // If this is a comment, set the permissions from the parent.
312 // for non native networks use the network of the original post as network of the item
313 if (($parent_item['network'] != NETWORK_DIASPORA)
314 && ($parent_item['network'] != NETWORK_OSTATUS)
315 && ($network == "")) {
316 $network = $parent_item['network'];
319 $str_contact_allow = $parent_item['allow_cid'];
320 $str_group_allow = $parent_item['allow_gid'];
321 $str_contact_deny = $parent_item['deny_cid'];
322 $str_group_deny = $parent_item['deny_gid'];
323 $private = $parent_item['private'];
326 $pubmail_enable = ((x($_REQUEST, 'pubmail_enable') && intval($_REQUEST['pubmail_enable']) && (! $private)) ? 1 : 0);
328 // if using the API, we won't see pubmail_enable - figure out if it should be set
330 if ($api_source && $profile_uid && $profile_uid == local_user() && (! $private)) {
331 $mail_disabled = ((function_exists('imap_open') && (! get_config('system', 'imap_disabled'))) ? 0 : 1);
332 if (! $mail_disabled) {
333 /// @TODO Check if only pubmail is loaded, * loads all columns
334 $r = q("SELECT * FROM `mailacct` WHERE `uid` = %d AND `server` != '' LIMIT 1",
337 if (dbm::is_result($r) && intval($r[0]['pubmail'])) {
338 $pubmail_enabled = true;
343 if (! strlen($body)) {
347 info(t('Empty post discarded.') . EOL );
348 if (x($_REQUEST, 'return')) {
349 goaway($return_path);
355 if (strlen($categories)) {
356 // get the "fileas" tags for this post
357 $filedas = file_tag_file_to_list($categories, 'file');
359 // save old and new categories, so we can determine what needs to be deleted from pconfig
360 $categories_old = $categories;
361 $categories = file_tag_list_to_file(trim($_REQUEST['category']), 'category');
362 $categories_new = $categories;
363 if (strlen($filedas)) {
364 // append the fileas stuff to the new categories list
365 $categories .= file_tag_list_to_file($filedas, 'file');
368 // get contact info for poster
374 if ((local_user()) && (local_user() == $profile_uid)) {
376 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `self` = 1 LIMIT 1",
377 intval($_SESSION['uid']));
378 } elseif(remote_user()) {
379 if (x($_SESSION, 'remote') && is_array($_SESSION['remote'])) {
380 foreach ($_SESSION['remote'] as $v) {
381 if ($v['uid'] == $profile_uid) {
382 $contact_id = $v['cid'];
388 $r = q("SELECT * FROM `contact` WHERE `id` = %d LIMIT 1",
394 if (dbm::is_result($r)) {
396 $contact_id = $author['id'];
399 // get contact info for owner
401 if ($profile_uid == local_user()) {
402 $contact_record = $author;
404 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `self` = 1 LIMIT 1",
407 if (dbm::is_result($r)) {
408 $contact_record = $r[0];
412 $post_type = notags(trim($_REQUEST['type']));
414 if ($post_type === 'net-comment' && $parent_item !== null) {
415 if ($parent_item['wall'] == 1) {
416 $post_type = 'wall-comment';
418 $post_type = 'remote-comment';
423 * When a photo was uploaded into the message using the (profile wall) ajax
424 * uploader, The permissions are initially set to disallow anybody but the
425 * owner from seeing it. This is because the permissions may not yet have been
426 * set for the post. If it's private, the photo permissions should be set
427 * appropriately. But we didn't know the final permissions on the post until
428 * now. So now we'll look for links of uploaded messages that are in the
429 * post and set them to the same permissions as the post itself.
434 if ((! $preview) && preg_match_all("/\[img([\=0-9x]*?)\](.*?)\[\/img\]/",$body,$match)) {
436 if (count($images)) {
438 $objecttype = ACTIVITY_OBJ_IMAGE;
440 foreach ($images as $image) {
441 if (! stristr($image,System::baseUrl() . '/photo/')) {
444 $image_uri = substr($image,strrpos($image,'/') + 1);
445 $image_uri = substr($image_uri,0, strpos($image_uri,'-'));
446 if (! strlen($image_uri)) {
449 $srch = '<' . intval($contact_id) . '>';
451 $r = q("SELECT `id` FROM `photo` WHERE `allow_cid` = '%s' AND `allow_gid` = '' AND `deny_cid` = '' AND `deny_gid` = ''
452 AND `resource-id` = '%s' AND `uid` = %d LIMIT 1",
458 if (! dbm::is_result($r)) {
462 $r = q("UPDATE `photo` SET `allow_cid` = '%s', `allow_gid` = '%s', `deny_cid` = '%s', `deny_gid` = '%s'
463 WHERE `resource-id` = '%s' AND `uid` = %d AND `album` = '%s' ",
464 dbesc($str_contact_allow),
465 dbesc($str_group_allow),
466 dbesc($str_contact_deny),
467 dbesc($str_group_deny),
469 intval($profile_uid),
470 dbesc( t('Wall Photos'))
478 * Next link in any attachment references we find in the post.
482 if ((! $preview) && preg_match_all("/\[attachment\](.*?)\[\/attachment\]/", $body, $match)) {
483 $attaches = $match[1];
484 if (count($attaches)) {
485 foreach ($attaches as $attach) {
486 $r = q("SELECT * FROM `attach` WHERE `uid` = %d AND `id` = %d LIMIT 1",
487 intval($profile_uid),
490 if (dbm::is_result($r)) {
491 $r = q("UPDATE `attach` SET `allow_cid` = '%s', `allow_gid` = '%s', `deny_cid` = '%s', `deny_gid` = '%s'
492 WHERE `uid` = %d AND `id` = %d",
493 dbesc($str_contact_allow),
494 dbesc($str_group_allow),
495 dbesc($str_contact_deny),
496 dbesc($str_group_deny),
497 intval($profile_uid),
505 // embedded bookmark or attachment in post? set bookmark flag
508 $data = get_attachment_data($body);
509 if (preg_match_all("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/ism", $body, $match, PREG_SET_ORDER) || isset($data["type"])) {
510 $objecttype = ACTIVITY_OBJ_BOOKMARK;
514 $body = bb_translate_video($body);
517 // Fold multi-line [code] sequences
518 $body = preg_replace('/\[\/code\]\s*\[code\]/ism', "\n", $body);
520 $body = scale_external_images($body, false);
522 // Setting the object type if not defined before
524 $objecttype = ACTIVITY_OBJ_NOTE; // Default value
525 require_once 'include/plaintext.php';
526 $objectdata = get_attached_data($body);
528 if ($post["type"] == "link") {
529 $objecttype = ACTIVITY_OBJ_BOOKMARK;
530 } elseif ($post["type"] == "video") {
531 $objecttype = ACTIVITY_OBJ_VIDEO;
532 } elseif ($post["type"] == "photo") {
533 $objecttype = ACTIVITY_OBJ_IMAGE;
538 // Look for any tags and linkify them
542 $tags = get_tags($body);
545 * add a statusnet style reply tag if the original post was from there
546 * and we are replying, and there isn't one already
548 if ($parent && ($parent_contact['network'] == NETWORK_OSTATUS)) {
549 $contact = '@[url=' . $parent_contact['url'] . ']' . $parent_contact['nick'] . '[/url]';
551 if (!in_array($contact, $tags)) {
552 $body = $contact . ' ' . $body;
556 $toplevel_contact = "";
557 $toplevel_parent = q("SELECT `contact`.* FROM `contact`
558 INNER JOIN `item` ON `item`.`contact-id` = `contact`.`id` AND `contact`.`url` = `item`.`author-link`
559 WHERE `item`.`id` = `item`.`parent` AND `item`.`parent` = %d", intval($parent));
560 if (dbm::is_result($toplevel_parent)) {
561 if (!empty($toplevel_parent[0]['addr'])) {
562 $toplevel_contact = '@' . $toplevel_parent[0]['addr'];
564 $toplevel_contact = '@' . $toplevel_parent[0]['nick'] . '+' . $toplevel_parent[0]['id'];
567 $toplevel_parent = q("SELECT `author-link`, `author-name` FROM `item` WHERE `id` = `parent` AND `parent` = %d", intval($parent));
568 $toplevel_contact = '@[url=' . $toplevel_parent[0]['author-link'] . ']' . $toplevel_parent[0]['author-name'] . '[/url]';
571 if (!in_array($toplevel_contact, $tags)) {
572 $tags[] = $toplevel_contact;
578 $private_forum = false;
579 $only_to_forum = false;
580 $forum_contact = array();
583 foreach ($tags as $tag) {
585 $tag_type = substr($tag, 0, 1);
587 if ($tag_type == '#') {
592 * If we already tagged 'Robert Johnson', don't try and tag 'Robert'.
593 * Robert Johnson should be first in the $tags array
595 $fullnametagged = false;
596 /// @TODO $tagged is initialized above if() block and is not filled, maybe old-lost code?
597 foreach ($tagged as $nextTag) {
598 if (stristr($nextTag, $tag . ' ')) {
599 $fullnametagged = true;
603 if ($fullnametagged) {
607 $success = handle_tag($a, $body, $inform, $str_tags, (local_user()) ? local_user() : $profile_uid , $tag, $network);
608 if ($success['replaced']) {
611 // When the forum is private or the forum is addressed with a "!" make the post private
612 if (is_array($success['contact']) && ($success['contact']['prv'] || ($tag_type == '!'))) {
613 $private_forum = $success['contact']['prv'];
614 $only_to_forum = ($tag_type == '!');
615 $private_id = $success['contact']['id'];
616 $forum_contact = $success['contact'];
617 } elseif (is_array($success['contact']) && $success['contact']['forum'] &&
618 ($str_contact_allow == '<' . $success['contact']['id'] . '>')) {
619 $private_forum = false;
620 $only_to_forum = true;
621 $private_id = $success['contact']['id'];
622 $forum_contact = $success['contact'];
627 if (!$parent && count($forum_contact) && ($private_forum || $only_to_forum)) {
628 // we tagged a forum in a top level post. Now we change the post
629 $private = $private_forum;
631 $str_group_allow = '';
632 $str_contact_deny = '';
633 $str_group_deny = '';
634 if ($private_forum) {
635 $str_contact_allow = '<' . $private_id . '>';
637 $str_contact_allow = '';
639 $contact_id = $private_id;
640 $contact_record = $forum_contact;
641 $_REQUEST['origin'] = false;
647 if (preg_match_all('/(\[attachment\]([0-9]+)\[\/attachment\])/',$body,$match)) {
648 foreach ($match[2] as $mtch) {
649 $r = q("SELECT `id`,`filename`,`filesize`,`filetype` FROM `attach` WHERE `uid` = %d AND `id` = %d LIMIT 1",
650 intval($profile_uid),
653 if (dbm::is_result($r)) {
654 if (strlen($attachments)) {
657 $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]';
659 $body = str_replace($match[1],'',$body);
665 if (($post_type === 'wall' || $post_type === 'wall-comment') && !count($forum_contact)) {
669 if (! strlen($verb)) {
670 $verb = ACTIVITY_POST ;
673 if ($network == "") {
674 $network = NETWORK_DFRN;
677 $gravity = (($parent) ? 6 : 0 );
679 // even if the post arrived via API we are considering that it
680 // originated on this site by default for determining relayability.
682 $origin = ((x($_REQUEST, 'origin')) ? intval($_REQUEST['origin']) : 1);
684 $notify_type = (($parent) ? 'comment-new' : 'wall-new' );
686 $uri = (($message_id) ? $message_id : item_new_uri($a->get_hostname(),$profile_uid, $guid));
688 // Fallback so that we alway have a thr-parent
694 $datarray['uid'] = $profile_uid;
695 $datarray['type'] = $post_type;
696 $datarray['wall'] = $wall;
697 $datarray['gravity'] = $gravity;
698 $datarray['network'] = $network;
699 $datarray['contact-id'] = $contact_id;
700 $datarray['owner-name'] = $contact_record['name'];
701 $datarray['owner-link'] = $contact_record['url'];
702 $datarray['owner-avatar'] = $contact_record['thumb'];
703 $datarray['owner-id'] = get_contact($datarray['owner-link'], 0);
704 $datarray['author-name'] = $author['name'];
705 $datarray['author-link'] = $author['url'];
706 $datarray['author-avatar'] = $author['thumb'];
707 $datarray['author-id'] = get_contact($datarray['author-link'], 0);
708 $datarray['created'] = datetime_convert();
709 $datarray['edited'] = datetime_convert();
710 $datarray['commented'] = datetime_convert();
711 $datarray['received'] = datetime_convert();
712 $datarray['changed'] = datetime_convert();
713 $datarray['extid'] = $extid;
714 $datarray['guid'] = $guid;
715 $datarray['uri'] = $uri;
716 $datarray['title'] = $title;
717 $datarray['body'] = $body;
718 $datarray['app'] = $app;
719 $datarray['location'] = $location;
720 $datarray['coord'] = $coord;
721 $datarray['tag'] = $str_tags;
722 $datarray['file'] = $categories;
723 $datarray['inform'] = $inform;
724 $datarray['verb'] = $verb;
725 $datarray['object-type'] = $objecttype;
726 $datarray['allow_cid'] = $str_contact_allow;
727 $datarray['allow_gid'] = $str_group_allow;
728 $datarray['deny_cid'] = $str_contact_deny;
729 $datarray['deny_gid'] = $str_group_deny;
730 $datarray['private'] = $private;
731 $datarray['pubmail'] = $pubmail_enable;
732 $datarray['attach'] = $attachments;
733 $datarray['bookmark'] = intval($bookmark);
734 $datarray['thr-parent'] = $thr_parent;
735 $datarray['postopts'] = $postopts;
736 $datarray['origin'] = $origin;
737 $datarray['moderated'] = $allow_moderated;
738 $datarray['gcontact-id'] = get_gcontact_id(array("url" => $datarray['author-link'], "network" => $datarray['network'],
739 "photo" => $datarray['author-avatar'], "name" => $datarray['author-name']));
740 $datarray['object'] = $object;
743 * These fields are for the convenience of plugins...
744 * 'self' if true indicates the owner is posting on their own wall
745 * If parent is 0 it is a top-level post.
747 $datarray['parent'] = $parent;
748 $datarray['self'] = $self;
749 // $datarray['prvnets'] = $user['prvnets'];
751 // This triggers posts via API and the mirror functions
752 $datarray['api_source'] = $api_source;
754 $datarray['parent-uri'] = ($parent == 0) ? $uri : $parent_item['uri'];
755 $datarray['plink'] = System::baseUrl() . '/display/' . urlencode($datarray['guid']);
756 $datarray['last-child'] = 1;
757 $datarray['visible'] = 1;
759 $datarray['protocol'] = PROTOCOL_DFRN;
761 $r = dba::fetch_first("SELECT `conversation-uri`, `conversation-href` FROM `conversation` WHERE `item-uri` = ?", $datarray['parent-uri']);
762 if (dbm::is_result($r)) {
763 if ($r['conversation-uri'] != '') {
764 $datarray['conversation-uri'] = $r['conversation-uri'];
766 if ($r['conversation-href'] != '') {
767 $datarray['conversation-href'] = $r['conversation-href'];
772 $datarray['edit'] = true;
775 // Search for hashtags
776 item_body_set_hashtags($datarray);
778 // preview mode - prepare the body for display and send it via json
780 require_once 'include/conversation.php';
781 // We set the datarray ID to -1 because in preview mode the dataray
782 // doesn't have an ID.
783 $datarray["id"] = -1;
784 $o = conversation($a,array(array_merge($contact_record,$datarray)),'search', false, true);
785 logger('preview: ' . $o);
786 echo json_encode(array('preview' => $o));
790 call_hooks('post_local',$datarray);
792 if (x($datarray, 'cancel')) {
793 logger('mod_item: post cancelled by plugin.');
795 goaway($return_path);
798 $json = array('cancel' => 1);
799 if (x($_REQUEST, 'jsreload') && strlen($_REQUEST['jsreload'])) {
800 $json['reload'] = System::baseUrl() . '/' . $_REQUEST['jsreload'];
803 echo json_encode($json);
807 // Fill the cache field
808 put_item_in_cache($datarray);
810 $datarray = store_conversation($datarray);
813 $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `tag` = '%s', `attach` = '%s', `file` = '%s', `rendered-html` = '%s', `rendered-hash` = '%s', `edited` = '%s', `changed` = '%s' WHERE `id` = %d AND `uid` = %d",
814 dbesc($datarray['title']),
815 dbesc($datarray['body']),
816 dbesc($datarray['tag']),
817 dbesc($datarray['attach']),
818 dbesc($datarray['file']),
819 dbesc($datarray['rendered-html']),
820 dbesc($datarray['rendered-hash']),
821 dbesc(datetime_convert()),
822 dbesc(datetime_convert()),
827 create_tags_from_item($post_id);
828 create_files_from_item($post_id);
829 update_thread($post_id);
831 // update filetags in pconfig
832 file_tag_update_pconfig($uid,$categories_old,$categories_new,'category');
834 Worker::add(PRIORITY_HIGH, "notifier", 'edit_post', $post_id);
835 if ((x($_REQUEST, 'return')) && strlen($return_path)) {
836 logger('return: ' . $return_path);
837 goaway($return_path);
846 $r = q("INSERT INTO `item` (`guid`, `extid`, `uid`,`type`,`wall`,`gravity`, `network`, `contact-id`,
847 `owner-name`,`owner-link`,`owner-avatar`, `owner-id`,
848 `author-name`, `author-link`, `author-avatar`, `author-id`,
849 `created`, `edited`, `commented`, `received`, `changed`,
850 `uri`, `thr-parent`, `title`, `body`, `app`, `location`, `coord`,
851 `tag`, `inform`, `verb`, `object-type`, `postopts`,
852 `allow_cid`, `allow_gid`, `deny_cid`, `deny_gid`, `private`,
853 `pubmail`, `attach`, `bookmark`,`origin`, `moderated`, `file`,
854 `rendered-html`, `rendered-hash`, `gcontact-id`, `object`,
855 `parent`, `parent-uri`, `plink`, `last-child`, `visible`)
856 VALUES('%s', '%s', %d, '%s', %d, %d, '%s', %d,
857 '%s', '%s', '%s', %d,
858 '%s', '%s', '%s', %d,
859 '%s', '%s', '%s', '%s', '%s',
860 '%s', '%s', '%s', '%s', '%s', '%s', '%s',
861 '%s', '%s', '%s', '%s', '%s',
862 '%s', '%s', '%s', '%s', %d,
863 %d, '%s', %d, %d, %d, '%s',
864 '%s', '%s', %d, '%s',
865 %d, '%s', '%s', %d, %d)",
866 dbesc($datarray['guid']),
867 dbesc($datarray['extid']),
868 intval($datarray['uid']),
869 dbesc($datarray['type']),
870 intval($datarray['wall']),
871 intval($datarray['gravity']),
872 dbesc($datarray['network']),
873 intval($datarray['contact-id']),
874 dbesc($datarray['owner-name']),
875 dbesc($datarray['owner-link']),
876 dbesc($datarray['owner-avatar']),
877 intval($datarray['owner-id']),
878 dbesc($datarray['author-name']),
879 dbesc($datarray['author-link']),
880 dbesc($datarray['author-avatar']),
881 intval($datarray['author-id']),
882 dbesc($datarray['created']),
883 dbesc($datarray['edited']),
884 dbesc($datarray['commented']),
885 dbesc($datarray['received']),
886 dbesc($datarray['changed']),
887 dbesc($datarray['uri']),
888 dbesc($datarray['thr-parent']),
889 dbesc($datarray['title']),
890 dbesc($datarray['body']),
891 dbesc($datarray['app']),
892 dbesc($datarray['location']),
893 dbesc($datarray['coord']),
894 dbesc($datarray['tag']),
895 dbesc($datarray['inform']),
896 dbesc($datarray['verb']),
897 dbesc($datarray['object-type']),
898 dbesc($datarray['postopts']),
899 dbesc($datarray['allow_cid']),
900 dbesc($datarray['allow_gid']),
901 dbesc($datarray['deny_cid']),
902 dbesc($datarray['deny_gid']),
903 intval($datarray['private']),
904 intval($datarray['pubmail']),
905 dbesc($datarray['attach']),
906 intval($datarray['bookmark']),
907 intval($datarray['origin']),
908 intval($datarray['moderated']),
909 dbesc($datarray['file']),
910 dbesc($datarray['rendered-html']),
911 dbesc($datarray['rendered-hash']),
912 intval($datarray['gcontact-id']),
913 dbesc($datarray['object']),
914 intval($datarray['parent']),
915 dbesc($datarray['parent-uri']),
916 dbesc($datarray['plink']),
917 intval($datarray['last-child']),
918 intval($datarray['visible'])
921 if (dbm::is_result($r)) {
922 $post_id = dba::lastInsertId();
924 logger('mod_item: unable to create post.');
930 logger('mod_item: unable to retrieve post that was just stored.');
931 notice(t('System error. Post not saved.') . EOL);
932 goaway($return_path);
936 logger('mod_item: saved item ' . $post_id);
938 $datarray["id"] = $post_id;
940 item_set_last_item($datarray);
942 // update filetags in pconfig
943 file_tag_update_pconfig($uid,$categories_old,$categories_new,'category');
947 // This item is the last leaf and gets the comment box, clear any ancestors
948 $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent` = %d AND `last-child` AND `id` != %d",
949 dbesc(datetime_convert()),
954 // update the commented timestamp on the parent
955 q("UPDATE `item` SET `visible` = 1, `commented` = '%s', `changed` = '%s' WHERE `id` = %d",
956 dbesc(datetime_convert()),
957 dbesc(datetime_convert()),
961 if ($contact_record != $author) {
963 'type' => NOTIFY_COMMENT,
964 'notify_flags' => $user['notify-flags'],
965 'language' => $user['language'],
966 'to_name' => $user['username'],
967 'to_email' => $user['email'],
968 'uid' => $user['uid'],
970 'link' => System::baseUrl().'/display/'.urlencode($datarray['guid']),
971 'source_name' => $datarray['author-name'],
972 'source_link' => $datarray['author-link'],
973 'source_photo' => $datarray['author-avatar'],
974 'verb' => ACTIVITY_POST,
977 'parent_uri' => $parent_item['uri']
983 // Store the comment signature information in case we need to relay to Diaspora
984 Diaspora::store_comment_signature($datarray, $author, ($self ? $user['prvkey'] : false), $post_id);
989 $r = q("UPDATE `item` SET `parent` = %d WHERE `id` = %d",
993 if (($contact_record != $author) && !count($forum_contact)) {
995 'type' => NOTIFY_WALL,
996 'notify_flags' => $user['notify-flags'],
997 'language' => $user['language'],
998 'to_name' => $user['username'],
999 'to_email' => $user['email'],
1000 'uid' => $user['uid'],
1001 'item' => $datarray,
1002 'link' => System::baseUrl().'/display/'.urlencode($datarray['guid']),
1003 'source_name' => $datarray['author-name'],
1004 'source_link' => $datarray['author-link'],
1005 'source_photo' => $datarray['author-avatar'],
1006 'verb' => ACTIVITY_POST,
1012 call_hooks('post_local_end', $datarray);
1014 if (strlen($emailcc) && $profile_uid == local_user()) {
1015 $erecips = explode(',', $emailcc);
1016 if (count($erecips)) {
1017 foreach ($erecips as $recip) {
1018 $addr = trim($recip);
1019 if (! strlen($addr)) {
1022 $disclaimer = '<hr />' . sprintf( t('This message was sent to you by %s, a member of the Friendica social network.'), $a->user['username'])
1024 $disclaimer .= sprintf( t('You may visit them online at %s'), System::baseUrl() . '/profile/' . $a->user['nickname']) . EOL;
1025 $disclaimer .= t('Please contact the sender by replying to this post if you do not wish to receive these messages.') . EOL;
1026 if (!$datarray['title']=='') {
1027 $subject = email_header_encode($datarray['title'], 'UTF-8');
1029 $subject = email_header_encode('[Friendica]' . ' ' . sprintf( t('%s posted an update.'), $a->user['username']), 'UTF-8');
1031 $link = '<a href="' . System::baseUrl() . '/profile/' . $a->user['nickname'] . '"><img src="' . $author['thumb'] . '" alt="' . $a->user['username'] . '" /></a><br /><br />';
1032 $html = prepare_body($datarray);
1033 $message = '<html><body>' . $link . $html . $disclaimer . '</body></html>';
1034 include_once 'include/html2plain.php';
1036 'fromName' => $a->user['username'],
1037 'fromEmail' => $a->user['email'],
1039 'replyTo' => $a->user['email'],
1040 'messageSubject' => $subject,
1041 'htmlVersion' => $message,
1042 'textVersion' => html2plain($html.$disclaimer),
1044 Emailer::send($params);
1049 if ($post_id == $parent) {
1050 add_thread($post_id);
1052 update_thread($parent, true);
1057 create_tags_from_item($post_id);
1058 create_files_from_item($post_id);
1060 // Insert an item entry for UID=0 for global entries.
1061 // We now do it in the background to save some time.
1062 // This is important in interactive environments like the frontend or the API.
1063 // We don't fork a new process since this is done anyway with the following command
1064 Worker::add(array('priority' => PRIORITY_HIGH, 'dont_fork' => true), "create_shadowentry", $post_id);
1066 // Call the background process that is delivering the item to the receivers
1067 Worker::add(PRIORITY_HIGH, "notifier", $notify_type, $post_id);
1069 logger('post_complete');
1071 item_post_return(System::baseUrl(), $api_source, $return_path);
1075 function item_post_return($baseurl, $api_source, $return_path) {
1076 // figure out how to return, depending on from whence we came
1083 goaway($return_path);
1086 $json = array('success' => 1);
1087 if (x($_REQUEST, 'jsreload') && strlen($_REQUEST['jsreload'])) {
1088 $json['reload'] = $baseurl . '/' . $_REQUEST['jsreload'];
1091 logger('post_json: ' . print_r($json,true), LOGGER_DEBUG);
1093 echo json_encode($json);
1099 function item_content(App $a) {
1101 if ((! local_user()) && (! remote_user())) {
1105 require_once 'include/security.php';
1108 if (($a->argc == 3) && ($a->argv[1] === 'drop') && intval($a->argv[2])) {
1109 $o = drop_item($a->argv[2], !is_ajax());
1111 // ajax return: [<item id>, 0 (no perm) | <owner id>]
1112 echo json_encode(array(intval($a->argv[2]), intval($o)));
1120 * This function removes the tag $tag from the text $body and replaces it with
1121 * the appropiate link.
1123 * @param App $a Application instance @TODO is unused in this function's scope (excluding included files)
1124 * @param unknown_type $body the text to replace the tag in
1125 * @param string $inform a comma-seperated string containing everybody to inform
1126 * @param string $str_tags string to add the tag to
1127 * @param integer $profile_uid
1128 * @param string $tag the tag to replace
1129 * @param string $network The network of the post
1131 * @return boolean true if replaced, false if not replaced
1133 function handle_tag(App $a, &$body, &$inform, &$str_tags, $profile_uid, $tag, $network = "") {
1134 require_once 'include/socgraph.php';
1140 //is it a person tag?
1141 if ((strpos($tag, '@') === 0) || (strpos($tag, '!') === 0)) {
1142 $tag_type = substr($tag, 0, 1);
1143 //is it already replaced?
1144 if (strpos($tag, '[url=')) {
1145 //append tag to str_tags
1146 if (!stristr($str_tags, $tag)) {
1147 if (strlen($str_tags)) {
1153 // Checking for the alias that is used for OStatus
1154 $pattern = "/[@!]\[url\=(.*?)\](.*?)\[\/url\]/ism";
1155 if (preg_match($pattern, $tag, $matches)) {
1157 $r = q("SELECT `alias`, `name` FROM `contact` WHERE `nurl` = '%s' AND `alias` != '' AND `uid` = 0",
1158 normalise_link($matches[1]));
1159 if (!dbm::is_result($r)) {
1160 $r = q("SELECT `alias`, `name` FROM `gcontact` WHERE `nurl` = '%s' AND `alias` != ''",
1161 normalise_link($matches[1]));
1163 if (dbm::is_result($r)) {
1166 $data = probe_url($matches[1]);
1169 if ($data["alias"] != "") {
1170 $newtag = '@[url=' . $data["alias"] . ']' . $data["name"] . '[/url]';
1171 if (!stristr($str_tags, $newtag)) {
1172 if (strlen($str_tags)) {
1175 $str_tags .= $newtag;
1183 //get the person's name
1184 $name = substr($tag, 1);
1186 // Sometimes the tag detection doesn't seem to work right
1187 // This is some workaround
1188 $nameparts = explode(" ", $name);
1189 $name = $nameparts[0];
1191 // Try to detect the contact in various ways
1192 if ((strpos($name, '@')) || (strpos($name, 'http://'))) {
1193 // Is it in format @user@domain.tld or @http://domain.tld/...?
1195 // First check the contact table for the address
1196 $r = q("SELECT `id`, `url`, `nick`, `name`, `alias`, `network`, `notify`, `forum`, `prv` FROM `contact`
1197 WHERE `addr` = '%s' AND `uid` = %d AND
1198 (`network` != '%s' OR (`notify` != '' AND `alias` != ''))
1201 intval($profile_uid),
1202 dbesc(NETWORK_OSTATUS)
1205 // Then check in the contact table for the url
1206 if (!dbm::is_result($r)) {
1207 $r = q("SELECT `id`, `url`, `nick`, `name`, `alias`, `network`, `notify`, `forum`, `prv` FROM `contact`
1208 WHERE `nurl` = '%s' AND `uid` = %d AND
1209 (`network` != '%s' OR (`notify` != '' AND `alias` != ''))
1211 dbesc(normalise_link($name)),
1212 intval($profile_uid),
1213 dbesc(NETWORK_OSTATUS)
1217 // Then check in the global contacts for the address
1218 if (!dbm::is_result($r)) {
1219 $r = q("SELECT `url`, `nick`, `name`, `alias`, `network`, `notify` FROM `gcontact`
1220 WHERE `addr` = '%s' AND (`network` != '%s' OR (`notify` != '' AND `alias` != ''))
1223 dbesc(NETWORK_OSTATUS)
1227 // Then check in the global contacts for the url
1228 if (!dbm::is_result($r)) {
1229 $r = q("SELECT `url`, `nick`, `name`, `alias`, `network`, `notify` FROM `gcontact`
1230 WHERE `nurl` = '%s' AND (`network` != '%s' OR (`notify` != '' AND `alias` != ''))
1232 dbesc(normalise_link($name)),
1233 dbesc(NETWORK_OSTATUS)
1237 if (!dbm::is_result($r)) {
1238 $probed = probe_url($name);
1239 if ($result['network'] != NETWORK_PHANTOM) {
1240 update_gcontact($probed);
1241 $r = q("SELECT `url`, `name`, `nick`, `network`, `alias`, `notify` FROM `gcontact` WHERE `nurl` = '%s' LIMIT 1",
1242 dbesc(normalise_link($probed["url"])));
1247 if (strrpos($name, '+')) {
1248 // Is it in format @nick+number?
1249 $tagcid = intval(substr($name, strrpos($name, '+') + 1));
1251 $r = q("SELECT `id`, `url`, `nick`, `name`, `alias`, `network` FROM `contact` WHERE `id` = %d AND `uid` = %d LIMIT 1",
1253 intval($profile_uid)
1257 // select someone by attag or nick and the name passed in the current network
1258 if(!dbm::is_result($r) && ($network != ""))
1259 $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",
1263 intval($profile_uid)
1266 //select someone from this user's contacts by name in the current network
1267 if (!dbm::is_result($r) && ($network != "")) {
1268 $r = q("SELECT `id`, `url`, `nick`, `name`, `alias`, `network` FROM `contact` WHERE `name` = '%s' AND `network` = '%s' AND `uid` = %d LIMIT 1",
1271 intval($profile_uid)
1275 // select someone by attag or nick and the name passed in
1276 if(!dbm::is_result($r)) {
1277 $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",
1280 intval($profile_uid)
1284 // select someone from this user's contacts by name
1285 if(!dbm::is_result($r)) {
1286 $r = q("SELECT `id`, `url`, `nick`, `name`, `alias`, `network` FROM `contact` WHERE `name` = '%s' AND `uid` = %d LIMIT 1",
1288 intval($profile_uid)
1293 if (dbm::is_result($r)) {
1294 if (strlen($inform) && (isset($r[0]["notify"]) || isset($r[0]["id"]))) {
1298 if (isset($r[0]["id"])) {
1299 $inform .= 'cid:' . $r[0]["id"];
1300 } elseif (isset($r[0]["notify"])) {
1301 $inform .= $r[0]["notify"];
1304 $profile = $r[0]["url"];
1305 $alias = $r[0]["alias"];
1306 $newname = $r[0]["nick"];
1307 if (($newname == "") || (($r[0]["network"] != NETWORK_OSTATUS) && ($r[0]["network"] != NETWORK_TWITTER)
1308 && ($r[0]["network"] != NETWORK_STATUSNET) && ($r[0]["network"] != NETWORK_APPNET))) {
1309 $newname = $r[0]["name"];
1313 //if there is an url for this persons profile
1314 if (isset($profile) && ($newname != "")) {
1316 // create profile link
1317 $profile = str_replace(',', '%2c', $profile);
1318 $newtag = $tag_type.'[url=' . $profile . ']' . $newname . '[/url]';
1319 $body = str_replace($tag_type . $name, $newtag, $body);
1320 // append tag to str_tags
1321 if (! stristr($str_tags, $newtag)) {
1322 if (strlen($str_tags)) {
1325 $str_tags .= $newtag;
1329 * Status.Net seems to require the numeric ID URL in a mention if the person isn't
1330 * subscribed to you. But the nickname URL is OK if they are. Grrr. We'll tag both.
1332 if (strlen($alias)) {
1333 $newtag = '@[url=' . $alias . ']' . $newname . '[/url]';
1334 if (! stristr($str_tags, $newtag)) {
1335 if (strlen($str_tags)) {
1338 $str_tags .= $newtag;
1344 return array('replaced' => $replaced, 'contact' => $r[0]);